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);
1080 /* Only unmap from the first pte in the page */
1081 if ((unmap_size - 1) & bus_addr)
1083 count = PAGE_SIZE_PTE_COUNT(unmap_size);
1084 for (i = 0; i < count; i++)
1088 bus_addr = (bus_addr & ~(unmap_size - 1)) + unmap_size;
1089 unmapped += unmap_size;
1092 BUG_ON(unmapped && !is_power_of_2(unmapped));
1098 * This function checks if a specific unity mapping entry is needed for
1099 * this specific IOMMU.
1101 static int iommu_for_unity_map(struct amd_iommu *iommu,
1102 struct unity_map_entry *entry)
1106 for (i = entry->devid_start; i <= entry->devid_end; ++i) {
1107 bdf = amd_iommu_alias_table[i];
1108 if (amd_iommu_rlookup_table[bdf] == iommu)
1116 * This function actually applies the mapping to the page table of the
1119 static int dma_ops_unity_map(struct dma_ops_domain *dma_dom,
1120 struct unity_map_entry *e)
1125 for (addr = e->address_start; addr < e->address_end;
1126 addr += PAGE_SIZE) {
1127 ret = iommu_map_page(&dma_dom->domain, addr, addr, e->prot,
1132 * if unity mapping is in aperture range mark the page
1133 * as allocated in the aperture
1135 if (addr < dma_dom->aperture_size)
1136 __set_bit(addr >> PAGE_SHIFT,
1137 dma_dom->aperture[0]->bitmap);
1144 * Init the unity mappings for a specific IOMMU in the system
1146 * Basically iterates over all unity mapping entries and applies them to
1147 * the default domain DMA of that IOMMU if necessary.
1149 static int iommu_init_unity_mappings(struct amd_iommu *iommu)
1151 struct unity_map_entry *entry;
1154 list_for_each_entry(entry, &amd_iommu_unity_map, list) {
1155 if (!iommu_for_unity_map(iommu, entry))
1157 ret = dma_ops_unity_map(iommu->default_dom, entry);
1166 * Inits the unity mappings required for a specific device
1168 static int init_unity_mappings_for_device(struct dma_ops_domain *dma_dom,
1171 struct unity_map_entry *e;
1174 list_for_each_entry(e, &amd_iommu_unity_map, list) {
1175 if (!(devid >= e->devid_start && devid <= e->devid_end))
1177 ret = dma_ops_unity_map(dma_dom, e);
1185 /****************************************************************************
1187 * The next functions belong to the address allocator for the dma_ops
1188 * interface functions. They work like the allocators in the other IOMMU
1189 * drivers. Its basically a bitmap which marks the allocated pages in
1190 * the aperture. Maybe it could be enhanced in the future to a more
1191 * efficient allocator.
1193 ****************************************************************************/
1196 * The address allocator core functions.
1198 * called with domain->lock held
1202 * Used to reserve address ranges in the aperture (e.g. for exclusion
1205 static void dma_ops_reserve_addresses(struct dma_ops_domain *dom,
1206 unsigned long start_page,
1209 unsigned int i, last_page = dom->aperture_size >> PAGE_SHIFT;
1211 if (start_page + pages > last_page)
1212 pages = last_page - start_page;
1214 for (i = start_page; i < start_page + pages; ++i) {
1215 int index = i / APERTURE_RANGE_PAGES;
1216 int page = i % APERTURE_RANGE_PAGES;
1217 __set_bit(page, dom->aperture[index]->bitmap);
1222 * This function is used to add a new aperture range to an existing
1223 * aperture in case of dma_ops domain allocation or address allocation
1226 static int alloc_new_range(struct dma_ops_domain *dma_dom,
1227 bool populate, gfp_t gfp)
1229 int index = dma_dom->aperture_size >> APERTURE_RANGE_SHIFT;
1230 struct amd_iommu *iommu;
1231 unsigned long i, old_size;
1233 #ifdef CONFIG_IOMMU_STRESS
1237 if (index >= APERTURE_MAX_RANGES)
1240 dma_dom->aperture[index] = kzalloc(sizeof(struct aperture_range), gfp);
1241 if (!dma_dom->aperture[index])
1244 dma_dom->aperture[index]->bitmap = (void *)get_zeroed_page(gfp);
1245 if (!dma_dom->aperture[index]->bitmap)
1248 dma_dom->aperture[index]->offset = dma_dom->aperture_size;
1251 unsigned long address = dma_dom->aperture_size;
1252 int i, num_ptes = APERTURE_RANGE_PAGES / 512;
1253 u64 *pte, *pte_page;
1255 for (i = 0; i < num_ptes; ++i) {
1256 pte = alloc_pte(&dma_dom->domain, address, PAGE_SIZE,
1261 dma_dom->aperture[index]->pte_pages[i] = pte_page;
1263 address += APERTURE_RANGE_SIZE / 64;
1267 old_size = dma_dom->aperture_size;
1268 dma_dom->aperture_size += APERTURE_RANGE_SIZE;
1270 /* Reserve address range used for MSI messages */
1271 if (old_size < MSI_ADDR_BASE_LO &&
1272 dma_dom->aperture_size > MSI_ADDR_BASE_LO) {
1273 unsigned long spage;
1276 pages = iommu_num_pages(MSI_ADDR_BASE_LO, 0x10000, PAGE_SIZE);
1277 spage = MSI_ADDR_BASE_LO >> PAGE_SHIFT;
1279 dma_ops_reserve_addresses(dma_dom, spage, pages);
1282 /* Initialize the exclusion range if necessary */
1283 for_each_iommu(iommu) {
1284 if (iommu->exclusion_start &&
1285 iommu->exclusion_start >= dma_dom->aperture[index]->offset
1286 && iommu->exclusion_start < dma_dom->aperture_size) {
1287 unsigned long startpage;
1288 int pages = iommu_num_pages(iommu->exclusion_start,
1289 iommu->exclusion_length,
1291 startpage = iommu->exclusion_start >> PAGE_SHIFT;
1292 dma_ops_reserve_addresses(dma_dom, startpage, pages);
1297 * Check for areas already mapped as present in the new aperture
1298 * range and mark those pages as reserved in the allocator. Such
1299 * mappings may already exist as a result of requested unity
1300 * mappings for devices.
1302 for (i = dma_dom->aperture[index]->offset;
1303 i < dma_dom->aperture_size;
1305 u64 *pte = fetch_pte(&dma_dom->domain, i);
1306 if (!pte || !IOMMU_PTE_PRESENT(*pte))
1309 dma_ops_reserve_addresses(dma_dom, i >> PAGE_SHIFT, 1);
1312 update_domain(&dma_dom->domain);
1317 update_domain(&dma_dom->domain);
1319 free_page((unsigned long)dma_dom->aperture[index]->bitmap);
1321 kfree(dma_dom->aperture[index]);
1322 dma_dom->aperture[index] = NULL;
1327 static unsigned long dma_ops_area_alloc(struct device *dev,
1328 struct dma_ops_domain *dom,
1330 unsigned long align_mask,
1332 unsigned long start)
1334 unsigned long next_bit = dom->next_address % APERTURE_RANGE_SIZE;
1335 int max_index = dom->aperture_size >> APERTURE_RANGE_SHIFT;
1336 int i = start >> APERTURE_RANGE_SHIFT;
1337 unsigned long boundary_size;
1338 unsigned long address = -1;
1339 unsigned long limit;
1341 next_bit >>= PAGE_SHIFT;
1343 boundary_size = ALIGN(dma_get_seg_boundary(dev) + 1,
1344 PAGE_SIZE) >> PAGE_SHIFT;
1346 for (;i < max_index; ++i) {
1347 unsigned long offset = dom->aperture[i]->offset >> PAGE_SHIFT;
1349 if (dom->aperture[i]->offset >= dma_mask)
1352 limit = iommu_device_max_index(APERTURE_RANGE_PAGES, offset,
1353 dma_mask >> PAGE_SHIFT);
1355 address = iommu_area_alloc(dom->aperture[i]->bitmap,
1356 limit, next_bit, pages, 0,
1357 boundary_size, align_mask);
1358 if (address != -1) {
1359 address = dom->aperture[i]->offset +
1360 (address << PAGE_SHIFT);
1361 dom->next_address = address + (pages << PAGE_SHIFT);
1371 static unsigned long dma_ops_alloc_addresses(struct device *dev,
1372 struct dma_ops_domain *dom,
1374 unsigned long align_mask,
1377 unsigned long address;
1379 #ifdef CONFIG_IOMMU_STRESS
1380 dom->next_address = 0;
1381 dom->need_flush = true;
1384 address = dma_ops_area_alloc(dev, dom, pages, align_mask,
1385 dma_mask, dom->next_address);
1387 if (address == -1) {
1388 dom->next_address = 0;
1389 address = dma_ops_area_alloc(dev, dom, pages, align_mask,
1391 dom->need_flush = true;
1394 if (unlikely(address == -1))
1395 address = DMA_ERROR_CODE;
1397 WARN_ON((address + (PAGE_SIZE*pages)) > dom->aperture_size);
1403 * The address free function.
1405 * called with domain->lock held
1407 static void dma_ops_free_addresses(struct dma_ops_domain *dom,
1408 unsigned long address,
1411 unsigned i = address >> APERTURE_RANGE_SHIFT;
1412 struct aperture_range *range = dom->aperture[i];
1414 BUG_ON(i >= APERTURE_MAX_RANGES || range == NULL);
1416 #ifdef CONFIG_IOMMU_STRESS
1421 if (address >= dom->next_address)
1422 dom->need_flush = true;
1424 address = (address % APERTURE_RANGE_SIZE) >> PAGE_SHIFT;
1426 bitmap_clear(range->bitmap, address, pages);
1430 /****************************************************************************
1432 * The next functions belong to the domain allocation. A domain is
1433 * allocated for every IOMMU as the default domain. If device isolation
1434 * is enabled, every device get its own domain. The most important thing
1435 * about domains is the page table mapping the DMA address space they
1438 ****************************************************************************/
1441 * This function adds a protection domain to the global protection domain list
1443 static void add_domain_to_list(struct protection_domain *domain)
1445 unsigned long flags;
1447 spin_lock_irqsave(&amd_iommu_pd_lock, flags);
1448 list_add(&domain->list, &amd_iommu_pd_list);
1449 spin_unlock_irqrestore(&amd_iommu_pd_lock, flags);
1453 * This function removes a protection domain to the global
1454 * protection domain list
1456 static void del_domain_from_list(struct protection_domain *domain)
1458 unsigned long flags;
1460 spin_lock_irqsave(&amd_iommu_pd_lock, flags);
1461 list_del(&domain->list);
1462 spin_unlock_irqrestore(&amd_iommu_pd_lock, flags);
1465 static u16 domain_id_alloc(void)
1467 unsigned long flags;
1470 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1471 id = find_first_zero_bit(amd_iommu_pd_alloc_bitmap, MAX_DOMAIN_ID);
1473 if (id > 0 && id < MAX_DOMAIN_ID)
1474 __set_bit(id, amd_iommu_pd_alloc_bitmap);
1477 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1482 static void domain_id_free(int id)
1484 unsigned long flags;
1486 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1487 if (id > 0 && id < MAX_DOMAIN_ID)
1488 __clear_bit(id, amd_iommu_pd_alloc_bitmap);
1489 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1492 static void free_pagetable(struct protection_domain *domain)
1497 p1 = domain->pt_root;
1502 for (i = 0; i < 512; ++i) {
1503 if (!IOMMU_PTE_PRESENT(p1[i]))
1506 p2 = IOMMU_PTE_PAGE(p1[i]);
1507 for (j = 0; j < 512; ++j) {
1508 if (!IOMMU_PTE_PRESENT(p2[j]))
1510 p3 = IOMMU_PTE_PAGE(p2[j]);
1511 free_page((unsigned long)p3);
1514 free_page((unsigned long)p2);
1517 free_page((unsigned long)p1);
1519 domain->pt_root = NULL;
1523 * Free a domain, only used if something went wrong in the
1524 * allocation path and we need to free an already allocated page table
1526 static void dma_ops_domain_free(struct dma_ops_domain *dom)
1533 del_domain_from_list(&dom->domain);
1535 free_pagetable(&dom->domain);
1537 for (i = 0; i < APERTURE_MAX_RANGES; ++i) {
1538 if (!dom->aperture[i])
1540 free_page((unsigned long)dom->aperture[i]->bitmap);
1541 kfree(dom->aperture[i]);
1545 domain_id_free(dom->domain.id);
1551 * Allocates a new protection domain usable for the dma_ops functions.
1552 * It also initializes the page table and the address allocator data
1553 * structures required for the dma_ops interface
1555 static struct dma_ops_domain *dma_ops_domain_alloc(void)
1557 struct dma_ops_domain *dma_dom;
1559 dma_dom = kzalloc(sizeof(struct dma_ops_domain), GFP_KERNEL);
1563 spin_lock_init(&dma_dom->domain.lock);
1565 dma_dom->domain.id = domain_id_alloc();
1566 if (dma_dom->domain.id == 0)
1568 INIT_LIST_HEAD(&dma_dom->domain.dev_list);
1569 dma_dom->domain.mode = PAGE_MODE_2_LEVEL;
1570 dma_dom->domain.pt_root = (void *)get_zeroed_page(GFP_KERNEL);
1571 dma_dom->domain.flags = PD_DMA_OPS_MASK;
1572 dma_dom->domain.priv = dma_dom;
1573 if (!dma_dom->domain.pt_root)
1576 dma_dom->need_flush = false;
1577 dma_dom->target_dev = 0xffff;
1579 add_domain_to_list(&dma_dom->domain);
1581 if (alloc_new_range(dma_dom, true, GFP_KERNEL))
1585 * mark the first page as allocated so we never return 0 as
1586 * a valid dma-address. So we can use 0 as error value
1588 dma_dom->aperture[0]->bitmap[0] = 1;
1589 dma_dom->next_address = 0;
1595 dma_ops_domain_free(dma_dom);
1601 * little helper function to check whether a given protection domain is a
1604 static bool dma_ops_domain(struct protection_domain *domain)
1606 return domain->flags & PD_DMA_OPS_MASK;
1609 static void set_dte_entry(u16 devid, struct protection_domain *domain, bool ats)
1611 u64 pte_root = virt_to_phys(domain->pt_root);
1614 pte_root |= (domain->mode & DEV_ENTRY_MODE_MASK)
1615 << DEV_ENTRY_MODE_SHIFT;
1616 pte_root |= IOMMU_PTE_IR | IOMMU_PTE_IW | IOMMU_PTE_P | IOMMU_PTE_TV;
1619 flags |= DTE_FLAG_IOTLB;
1621 amd_iommu_dev_table[devid].data[3] |= flags;
1622 amd_iommu_dev_table[devid].data[2] = domain->id;
1623 amd_iommu_dev_table[devid].data[1] = upper_32_bits(pte_root);
1624 amd_iommu_dev_table[devid].data[0] = lower_32_bits(pte_root);
1627 static void clear_dte_entry(u16 devid)
1629 /* remove entry from the device table seen by the hardware */
1630 amd_iommu_dev_table[devid].data[0] = IOMMU_PTE_P | IOMMU_PTE_TV;
1631 amd_iommu_dev_table[devid].data[1] = 0;
1632 amd_iommu_dev_table[devid].data[2] = 0;
1634 amd_iommu_apply_erratum_63(devid);
1637 static void do_attach(struct iommu_dev_data *dev_data,
1638 struct protection_domain *domain)
1640 struct amd_iommu *iommu;
1643 iommu = amd_iommu_rlookup_table[dev_data->devid];
1644 ats = dev_data->ats.enabled;
1646 /* Update data structures */
1647 dev_data->domain = domain;
1648 list_add(&dev_data->list, &domain->dev_list);
1649 set_dte_entry(dev_data->devid, domain, ats);
1651 /* Do reference counting */
1652 domain->dev_iommu[iommu->index] += 1;
1653 domain->dev_cnt += 1;
1655 /* Flush the DTE entry */
1656 device_flush_dte(dev_data);
1659 static void do_detach(struct iommu_dev_data *dev_data)
1661 struct amd_iommu *iommu;
1663 iommu = amd_iommu_rlookup_table[dev_data->devid];
1665 /* decrease reference counters */
1666 dev_data->domain->dev_iommu[iommu->index] -= 1;
1667 dev_data->domain->dev_cnt -= 1;
1669 /* Update data structures */
1670 dev_data->domain = NULL;
1671 list_del(&dev_data->list);
1672 clear_dte_entry(dev_data->devid);
1674 /* Flush the DTE entry */
1675 device_flush_dte(dev_data);
1679 * If a device is not yet associated with a domain, this function does
1680 * assigns it visible for the hardware
1682 static int __attach_device(struct iommu_dev_data *dev_data,
1683 struct protection_domain *domain)
1688 spin_lock(&domain->lock);
1690 if (dev_data->alias_data != NULL) {
1691 struct iommu_dev_data *alias_data = dev_data->alias_data;
1693 /* Some sanity checks */
1695 if (alias_data->domain != NULL &&
1696 alias_data->domain != domain)
1699 if (dev_data->domain != NULL &&
1700 dev_data->domain != domain)
1703 /* Do real assignment */
1704 if (alias_data->domain == NULL)
1705 do_attach(alias_data, domain);
1707 atomic_inc(&alias_data->bind);
1710 if (dev_data->domain == NULL)
1711 do_attach(dev_data, domain);
1713 atomic_inc(&dev_data->bind);
1720 spin_unlock(&domain->lock);
1726 * If a device is not yet associated with a domain, this function does
1727 * assigns it visible for the hardware
1729 static int attach_device(struct device *dev,
1730 struct protection_domain *domain)
1732 struct pci_dev *pdev = to_pci_dev(dev);
1733 struct iommu_dev_data *dev_data;
1734 unsigned long flags;
1737 dev_data = get_dev_data(dev);
1739 if (amd_iommu_iotlb_sup && pci_enable_ats(pdev, PAGE_SHIFT) == 0) {
1740 dev_data->ats.enabled = true;
1741 dev_data->ats.qdep = pci_ats_queue_depth(pdev);
1744 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1745 ret = __attach_device(dev_data, domain);
1746 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1749 * We might boot into a crash-kernel here. The crashed kernel
1750 * left the caches in the IOMMU dirty. So we have to flush
1751 * here to evict all dirty stuff.
1753 domain_flush_tlb_pde(domain);
1759 * Removes a device from a protection domain (unlocked)
1761 static void __detach_device(struct iommu_dev_data *dev_data)
1763 struct protection_domain *domain;
1764 unsigned long flags;
1766 BUG_ON(!dev_data->domain);
1768 domain = dev_data->domain;
1770 spin_lock_irqsave(&domain->lock, flags);
1772 if (dev_data->alias_data != NULL) {
1773 struct iommu_dev_data *alias_data = dev_data->alias_data;
1775 if (atomic_dec_and_test(&alias_data->bind))
1776 do_detach(alias_data);
1779 if (atomic_dec_and_test(&dev_data->bind))
1780 do_detach(dev_data);
1782 spin_unlock_irqrestore(&domain->lock, flags);
1785 * If we run in passthrough mode the device must be assigned to the
1786 * passthrough domain if it is detached from any other domain.
1787 * Make sure we can deassign from the pt_domain itself.
1789 if (iommu_pass_through &&
1790 (dev_data->domain == NULL && domain != pt_domain))
1791 __attach_device(dev_data, pt_domain);
1795 * Removes a device from a protection domain (with devtable_lock held)
1797 static void detach_device(struct device *dev)
1799 struct iommu_dev_data *dev_data;
1800 unsigned long flags;
1802 dev_data = get_dev_data(dev);
1804 /* lock device table */
1805 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1806 __detach_device(dev_data);
1807 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1809 if (dev_data->ats.enabled) {
1810 pci_disable_ats(to_pci_dev(dev));
1811 dev_data->ats.enabled = false;
1816 * Find out the protection domain structure for a given PCI device. This
1817 * will give us the pointer to the page table root for example.
1819 static struct protection_domain *domain_for_device(struct device *dev)
1821 struct iommu_dev_data *dev_data;
1822 struct protection_domain *dom = NULL;
1823 unsigned long flags;
1825 dev_data = get_dev_data(dev);
1827 if (dev_data->domain)
1828 return dev_data->domain;
1830 if (dev_data->alias_data != NULL) {
1831 struct iommu_dev_data *alias_data = dev_data->alias_data;
1833 read_lock_irqsave(&amd_iommu_devtable_lock, flags);
1834 if (alias_data->domain != NULL) {
1835 __attach_device(dev_data, alias_data->domain);
1836 dom = alias_data->domain;
1838 read_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1844 static int device_change_notifier(struct notifier_block *nb,
1845 unsigned long action, void *data)
1847 struct device *dev = data;
1849 struct protection_domain *domain;
1850 struct dma_ops_domain *dma_domain;
1851 struct amd_iommu *iommu;
1852 unsigned long flags;
1854 if (!check_device(dev))
1857 devid = get_device_id(dev);
1858 iommu = amd_iommu_rlookup_table[devid];
1861 case BUS_NOTIFY_UNBOUND_DRIVER:
1863 domain = domain_for_device(dev);
1867 if (iommu_pass_through)
1871 case BUS_NOTIFY_ADD_DEVICE:
1873 iommu_init_device(dev);
1875 if (iommu_pass_through) {
1876 attach_device(dev, pt_domain);
1880 domain = domain_for_device(dev);
1882 /* allocate a protection domain if a device is added */
1883 dma_domain = find_protection_domain(devid);
1885 dma_domain = dma_ops_domain_alloc();
1888 dma_domain->target_dev = devid;
1890 spin_lock_irqsave(&iommu_pd_list_lock, flags);
1891 list_add_tail(&dma_domain->list, &iommu_pd_list);
1892 spin_unlock_irqrestore(&iommu_pd_list_lock, flags);
1895 dev->archdata.dma_ops = &amd_iommu_dma_ops;
1898 case BUS_NOTIFY_DEL_DEVICE:
1900 iommu_uninit_device(dev);
1906 iommu_completion_wait(iommu);
1912 static struct notifier_block device_nb = {
1913 .notifier_call = device_change_notifier,
1916 void amd_iommu_init_notifier(void)
1918 bus_register_notifier(&pci_bus_type, &device_nb);
1921 /*****************************************************************************
1923 * The next functions belong to the dma_ops mapping/unmapping code.
1925 *****************************************************************************/
1928 * In the dma_ops path we only have the struct device. This function
1929 * finds the corresponding IOMMU, the protection domain and the
1930 * requestor id for a given device.
1931 * If the device is not yet associated with a domain this is also done
1934 static struct protection_domain *get_domain(struct device *dev)
1936 struct protection_domain *domain;
1937 struct dma_ops_domain *dma_dom;
1938 u16 devid = get_device_id(dev);
1940 if (!check_device(dev))
1941 return ERR_PTR(-EINVAL);
1943 domain = domain_for_device(dev);
1944 if (domain != NULL && !dma_ops_domain(domain))
1945 return ERR_PTR(-EBUSY);
1950 /* Device not bount yet - bind it */
1951 dma_dom = find_protection_domain(devid);
1953 dma_dom = amd_iommu_rlookup_table[devid]->default_dom;
1954 attach_device(dev, &dma_dom->domain);
1955 DUMP_printk("Using protection domain %d for device %s\n",
1956 dma_dom->domain.id, dev_name(dev));
1958 return &dma_dom->domain;
1961 static void update_device_table(struct protection_domain *domain)
1963 struct iommu_dev_data *dev_data;
1965 list_for_each_entry(dev_data, &domain->dev_list, list)
1966 set_dte_entry(dev_data->devid, domain, dev_data->ats.enabled);
1969 static void update_domain(struct protection_domain *domain)
1971 if (!domain->updated)
1974 update_device_table(domain);
1976 domain_flush_devices(domain);
1977 domain_flush_tlb_pde(domain);
1979 domain->updated = false;
1983 * This function fetches the PTE for a given address in the aperture
1985 static u64* dma_ops_get_pte(struct dma_ops_domain *dom,
1986 unsigned long address)
1988 struct aperture_range *aperture;
1989 u64 *pte, *pte_page;
1991 aperture = dom->aperture[APERTURE_RANGE_INDEX(address)];
1995 pte = aperture->pte_pages[APERTURE_PAGE_INDEX(address)];
1997 pte = alloc_pte(&dom->domain, address, PAGE_SIZE, &pte_page,
1999 aperture->pte_pages[APERTURE_PAGE_INDEX(address)] = pte_page;
2001 pte += PM_LEVEL_INDEX(0, address);
2003 update_domain(&dom->domain);
2009 * This is the generic map function. It maps one 4kb page at paddr to
2010 * the given address in the DMA address space for the domain.
2012 static dma_addr_t dma_ops_domain_map(struct dma_ops_domain *dom,
2013 unsigned long address,
2019 WARN_ON(address > dom->aperture_size);
2023 pte = dma_ops_get_pte(dom, address);
2025 return DMA_ERROR_CODE;
2027 __pte = paddr | IOMMU_PTE_P | IOMMU_PTE_FC;
2029 if (direction == DMA_TO_DEVICE)
2030 __pte |= IOMMU_PTE_IR;
2031 else if (direction == DMA_FROM_DEVICE)
2032 __pte |= IOMMU_PTE_IW;
2033 else if (direction == DMA_BIDIRECTIONAL)
2034 __pte |= IOMMU_PTE_IR | IOMMU_PTE_IW;
2040 return (dma_addr_t)address;
2044 * The generic unmapping function for on page in the DMA address space.
2046 static void dma_ops_domain_unmap(struct dma_ops_domain *dom,
2047 unsigned long address)
2049 struct aperture_range *aperture;
2052 if (address >= dom->aperture_size)
2055 aperture = dom->aperture[APERTURE_RANGE_INDEX(address)];
2059 pte = aperture->pte_pages[APERTURE_PAGE_INDEX(address)];
2063 pte += PM_LEVEL_INDEX(0, address);
2071 * This function contains common code for mapping of a physically
2072 * contiguous memory region into DMA address space. It is used by all
2073 * mapping functions provided with this IOMMU driver.
2074 * Must be called with the domain lock held.
2076 static dma_addr_t __map_single(struct device *dev,
2077 struct dma_ops_domain *dma_dom,
2084 dma_addr_t offset = paddr & ~PAGE_MASK;
2085 dma_addr_t address, start, ret;
2087 unsigned long align_mask = 0;
2090 pages = iommu_num_pages(paddr, size, PAGE_SIZE);
2093 INC_STATS_COUNTER(total_map_requests);
2096 INC_STATS_COUNTER(cross_page);
2099 align_mask = (1UL << get_order(size)) - 1;
2102 address = dma_ops_alloc_addresses(dev, dma_dom, pages, align_mask,
2104 if (unlikely(address == DMA_ERROR_CODE)) {
2106 * setting next_address here will let the address
2107 * allocator only scan the new allocated range in the
2108 * first run. This is a small optimization.
2110 dma_dom->next_address = dma_dom->aperture_size;
2112 if (alloc_new_range(dma_dom, false, GFP_ATOMIC))
2116 * aperture was successfully enlarged by 128 MB, try
2123 for (i = 0; i < pages; ++i) {
2124 ret = dma_ops_domain_map(dma_dom, start, paddr, dir);
2125 if (ret == DMA_ERROR_CODE)
2133 ADD_STATS_COUNTER(alloced_io_mem, size);
2135 if (unlikely(dma_dom->need_flush && !amd_iommu_unmap_flush)) {
2136 domain_flush_tlb(&dma_dom->domain);
2137 dma_dom->need_flush = false;
2138 } else if (unlikely(amd_iommu_np_cache))
2139 domain_flush_pages(&dma_dom->domain, address, size);
2146 for (--i; i >= 0; --i) {
2148 dma_ops_domain_unmap(dma_dom, start);
2151 dma_ops_free_addresses(dma_dom, address, pages);
2153 return DMA_ERROR_CODE;
2157 * Does the reverse of the __map_single function. Must be called with
2158 * the domain lock held too
2160 static void __unmap_single(struct dma_ops_domain *dma_dom,
2161 dma_addr_t dma_addr,
2165 dma_addr_t flush_addr;
2166 dma_addr_t i, start;
2169 if ((dma_addr == DMA_ERROR_CODE) ||
2170 (dma_addr + size > dma_dom->aperture_size))
2173 flush_addr = dma_addr;
2174 pages = iommu_num_pages(dma_addr, size, PAGE_SIZE);
2175 dma_addr &= PAGE_MASK;
2178 for (i = 0; i < pages; ++i) {
2179 dma_ops_domain_unmap(dma_dom, start);
2183 SUB_STATS_COUNTER(alloced_io_mem, size);
2185 dma_ops_free_addresses(dma_dom, dma_addr, pages);
2187 if (amd_iommu_unmap_flush || dma_dom->need_flush) {
2188 domain_flush_pages(&dma_dom->domain, flush_addr, size);
2189 dma_dom->need_flush = false;
2194 * The exported map_single function for dma_ops.
2196 static dma_addr_t map_page(struct device *dev, struct page *page,
2197 unsigned long offset, size_t size,
2198 enum dma_data_direction dir,
2199 struct dma_attrs *attrs)
2201 unsigned long flags;
2202 struct protection_domain *domain;
2205 phys_addr_t paddr = page_to_phys(page) + offset;
2207 INC_STATS_COUNTER(cnt_map_single);
2209 domain = get_domain(dev);
2210 if (PTR_ERR(domain) == -EINVAL)
2211 return (dma_addr_t)paddr;
2212 else if (IS_ERR(domain))
2213 return DMA_ERROR_CODE;
2215 dma_mask = *dev->dma_mask;
2217 spin_lock_irqsave(&domain->lock, flags);
2219 addr = __map_single(dev, domain->priv, paddr, size, dir, false,
2221 if (addr == DMA_ERROR_CODE)
2224 domain_flush_complete(domain);
2227 spin_unlock_irqrestore(&domain->lock, flags);
2233 * The exported unmap_single function for dma_ops.
2235 static void unmap_page(struct device *dev, dma_addr_t dma_addr, size_t size,
2236 enum dma_data_direction dir, struct dma_attrs *attrs)
2238 unsigned long flags;
2239 struct protection_domain *domain;
2241 INC_STATS_COUNTER(cnt_unmap_single);
2243 domain = get_domain(dev);
2247 spin_lock_irqsave(&domain->lock, flags);
2249 __unmap_single(domain->priv, dma_addr, size, dir);
2251 domain_flush_complete(domain);
2253 spin_unlock_irqrestore(&domain->lock, flags);
2257 * This is a special map_sg function which is used if we should map a
2258 * device which is not handled by an AMD IOMMU in the system.
2260 static int map_sg_no_iommu(struct device *dev, struct scatterlist *sglist,
2261 int nelems, int dir)
2263 struct scatterlist *s;
2266 for_each_sg(sglist, s, nelems, i) {
2267 s->dma_address = (dma_addr_t)sg_phys(s);
2268 s->dma_length = s->length;
2275 * The exported map_sg function for dma_ops (handles scatter-gather
2278 static int map_sg(struct device *dev, struct scatterlist *sglist,
2279 int nelems, enum dma_data_direction dir,
2280 struct dma_attrs *attrs)
2282 unsigned long flags;
2283 struct protection_domain *domain;
2285 struct scatterlist *s;
2287 int mapped_elems = 0;
2290 INC_STATS_COUNTER(cnt_map_sg);
2292 domain = get_domain(dev);
2293 if (PTR_ERR(domain) == -EINVAL)
2294 return map_sg_no_iommu(dev, sglist, nelems, dir);
2295 else if (IS_ERR(domain))
2298 dma_mask = *dev->dma_mask;
2300 spin_lock_irqsave(&domain->lock, flags);
2302 for_each_sg(sglist, s, nelems, i) {
2305 s->dma_address = __map_single(dev, domain->priv,
2306 paddr, s->length, dir, false,
2309 if (s->dma_address) {
2310 s->dma_length = s->length;
2316 domain_flush_complete(domain);
2319 spin_unlock_irqrestore(&domain->lock, flags);
2321 return mapped_elems;
2323 for_each_sg(sglist, s, mapped_elems, i) {
2325 __unmap_single(domain->priv, s->dma_address,
2326 s->dma_length, dir);
2327 s->dma_address = s->dma_length = 0;
2336 * The exported map_sg function for dma_ops (handles scatter-gather
2339 static void unmap_sg(struct device *dev, struct scatterlist *sglist,
2340 int nelems, enum dma_data_direction dir,
2341 struct dma_attrs *attrs)
2343 unsigned long flags;
2344 struct protection_domain *domain;
2345 struct scatterlist *s;
2348 INC_STATS_COUNTER(cnt_unmap_sg);
2350 domain = get_domain(dev);
2354 spin_lock_irqsave(&domain->lock, flags);
2356 for_each_sg(sglist, s, nelems, i) {
2357 __unmap_single(domain->priv, s->dma_address,
2358 s->dma_length, dir);
2359 s->dma_address = s->dma_length = 0;
2362 domain_flush_complete(domain);
2364 spin_unlock_irqrestore(&domain->lock, flags);
2368 * The exported alloc_coherent function for dma_ops.
2370 static void *alloc_coherent(struct device *dev, size_t size,
2371 dma_addr_t *dma_addr, gfp_t flag)
2373 unsigned long flags;
2375 struct protection_domain *domain;
2377 u64 dma_mask = dev->coherent_dma_mask;
2379 INC_STATS_COUNTER(cnt_alloc_coherent);
2381 domain = get_domain(dev);
2382 if (PTR_ERR(domain) == -EINVAL) {
2383 virt_addr = (void *)__get_free_pages(flag, get_order(size));
2384 *dma_addr = __pa(virt_addr);
2386 } else if (IS_ERR(domain))
2389 dma_mask = dev->coherent_dma_mask;
2390 flag &= ~(__GFP_DMA | __GFP_HIGHMEM | __GFP_DMA32);
2393 virt_addr = (void *)__get_free_pages(flag, get_order(size));
2397 paddr = virt_to_phys(virt_addr);
2400 dma_mask = *dev->dma_mask;
2402 spin_lock_irqsave(&domain->lock, flags);
2404 *dma_addr = __map_single(dev, domain->priv, paddr,
2405 size, DMA_BIDIRECTIONAL, true, dma_mask);
2407 if (*dma_addr == DMA_ERROR_CODE) {
2408 spin_unlock_irqrestore(&domain->lock, flags);
2412 domain_flush_complete(domain);
2414 spin_unlock_irqrestore(&domain->lock, flags);
2420 free_pages((unsigned long)virt_addr, get_order(size));
2426 * The exported free_coherent function for dma_ops.
2428 static void free_coherent(struct device *dev, size_t size,
2429 void *virt_addr, dma_addr_t dma_addr)
2431 unsigned long flags;
2432 struct protection_domain *domain;
2434 INC_STATS_COUNTER(cnt_free_coherent);
2436 domain = get_domain(dev);
2440 spin_lock_irqsave(&domain->lock, flags);
2442 __unmap_single(domain->priv, dma_addr, size, DMA_BIDIRECTIONAL);
2444 domain_flush_complete(domain);
2446 spin_unlock_irqrestore(&domain->lock, flags);
2449 free_pages((unsigned long)virt_addr, get_order(size));
2453 * This function is called by the DMA layer to find out if we can handle a
2454 * particular device. It is part of the dma_ops.
2456 static int amd_iommu_dma_supported(struct device *dev, u64 mask)
2458 return check_device(dev);
2462 * The function for pre-allocating protection domains.
2464 * If the driver core informs the DMA layer if a driver grabs a device
2465 * we don't need to preallocate the protection domains anymore.
2466 * For now we have to.
2468 static void __init prealloc_protection_domains(void)
2470 struct pci_dev *dev = NULL;
2471 struct dma_ops_domain *dma_dom;
2474 for_each_pci_dev(dev) {
2476 /* Do we handle this device? */
2477 if (!check_device(&dev->dev))
2480 /* Is there already any domain for it? */
2481 if (domain_for_device(&dev->dev))
2484 devid = get_device_id(&dev->dev);
2486 dma_dom = dma_ops_domain_alloc();
2489 init_unity_mappings_for_device(dma_dom, devid);
2490 dma_dom->target_dev = devid;
2492 attach_device(&dev->dev, &dma_dom->domain);
2494 list_add_tail(&dma_dom->list, &iommu_pd_list);
2498 static struct dma_map_ops amd_iommu_dma_ops = {
2499 .alloc_coherent = alloc_coherent,
2500 .free_coherent = free_coherent,
2501 .map_page = map_page,
2502 .unmap_page = unmap_page,
2504 .unmap_sg = unmap_sg,
2505 .dma_supported = amd_iommu_dma_supported,
2508 static unsigned device_dma_ops_init(void)
2510 struct pci_dev *pdev = NULL;
2511 unsigned unhandled = 0;
2513 for_each_pci_dev(pdev) {
2514 if (!check_device(&pdev->dev)) {
2516 iommu_ignore_device(&pdev->dev);
2522 pdev->dev.archdata.dma_ops = &amd_iommu_dma_ops;
2529 * The function which clues the AMD IOMMU driver into dma_ops.
2532 void __init amd_iommu_init_api(void)
2534 bus_set_iommu(&pci_bus_type, &amd_iommu_ops);
2537 int __init amd_iommu_init_dma_ops(void)
2539 struct amd_iommu *iommu;
2543 * first allocate a default protection domain for every IOMMU we
2544 * found in the system. Devices not assigned to any other
2545 * protection domain will be assigned to the default one.
2547 for_each_iommu(iommu) {
2548 iommu->default_dom = dma_ops_domain_alloc();
2549 if (iommu->default_dom == NULL)
2551 iommu->default_dom->domain.flags |= PD_DEFAULT_MASK;
2552 ret = iommu_init_unity_mappings(iommu);
2558 * Pre-allocate the protection domains for each device.
2560 prealloc_protection_domains();
2565 /* Make the driver finally visible to the drivers */
2566 unhandled = device_dma_ops_init();
2567 if (unhandled && max_pfn > MAX_DMA32_PFN) {
2568 /* There are unhandled devices - initialize swiotlb for them */
2572 amd_iommu_stats_init();
2578 for_each_iommu(iommu) {
2579 if (iommu->default_dom)
2580 dma_ops_domain_free(iommu->default_dom);
2586 /*****************************************************************************
2588 * The following functions belong to the exported interface of AMD IOMMU
2590 * This interface allows access to lower level functions of the IOMMU
2591 * like protection domain handling and assignement of devices to domains
2592 * which is not possible with the dma_ops interface.
2594 *****************************************************************************/
2596 static void cleanup_domain(struct protection_domain *domain)
2598 struct iommu_dev_data *entry;
2599 unsigned long flags;
2601 write_lock_irqsave(&amd_iommu_devtable_lock, flags);
2603 while (!list_empty(&domain->dev_list)) {
2604 entry = list_first_entry(&domain->dev_list,
2605 struct iommu_dev_data, list);
2606 __detach_device(entry);
2607 atomic_set(&entry->bind, 0);
2610 write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2613 static void protection_domain_free(struct protection_domain *domain)
2618 del_domain_from_list(domain);
2621 domain_id_free(domain->id);
2626 static struct protection_domain *protection_domain_alloc(void)
2628 struct protection_domain *domain;
2630 domain = kzalloc(sizeof(*domain), GFP_KERNEL);
2634 spin_lock_init(&domain->lock);
2635 mutex_init(&domain->api_lock);
2636 domain->id = domain_id_alloc();
2639 INIT_LIST_HEAD(&domain->dev_list);
2641 add_domain_to_list(domain);
2651 static int amd_iommu_domain_init(struct iommu_domain *dom)
2653 struct protection_domain *domain;
2655 domain = protection_domain_alloc();
2659 domain->mode = PAGE_MODE_3_LEVEL;
2660 domain->pt_root = (void *)get_zeroed_page(GFP_KERNEL);
2661 if (!domain->pt_root)
2669 protection_domain_free(domain);
2674 static void amd_iommu_domain_destroy(struct iommu_domain *dom)
2676 struct protection_domain *domain = dom->priv;
2681 if (domain->dev_cnt > 0)
2682 cleanup_domain(domain);
2684 BUG_ON(domain->dev_cnt != 0);
2686 free_pagetable(domain);
2688 protection_domain_free(domain);
2693 static void amd_iommu_detach_device(struct iommu_domain *dom,
2696 struct iommu_dev_data *dev_data = dev->archdata.iommu;
2697 struct amd_iommu *iommu;
2700 if (!check_device(dev))
2703 devid = get_device_id(dev);
2705 if (dev_data->domain != NULL)
2708 iommu = amd_iommu_rlookup_table[devid];
2712 iommu_completion_wait(iommu);
2715 static int amd_iommu_attach_device(struct iommu_domain *dom,
2718 struct protection_domain *domain = dom->priv;
2719 struct iommu_dev_data *dev_data;
2720 struct amd_iommu *iommu;
2723 if (!check_device(dev))
2726 dev_data = dev->archdata.iommu;
2728 iommu = amd_iommu_rlookup_table[dev_data->devid];
2732 if (dev_data->domain)
2735 ret = attach_device(dev, domain);
2737 iommu_completion_wait(iommu);
2742 static int amd_iommu_map(struct iommu_domain *dom, unsigned long iova,
2743 phys_addr_t paddr, int gfp_order, int iommu_prot)
2745 unsigned long page_size = 0x1000UL << gfp_order;
2746 struct protection_domain *domain = dom->priv;
2750 if (iommu_prot & IOMMU_READ)
2751 prot |= IOMMU_PROT_IR;
2752 if (iommu_prot & IOMMU_WRITE)
2753 prot |= IOMMU_PROT_IW;
2755 mutex_lock(&domain->api_lock);
2756 ret = iommu_map_page(domain, iova, paddr, prot, page_size);
2757 mutex_unlock(&domain->api_lock);
2762 static int amd_iommu_unmap(struct iommu_domain *dom, unsigned long iova,
2765 struct protection_domain *domain = dom->priv;
2766 unsigned long page_size, unmap_size;
2768 page_size = 0x1000UL << gfp_order;
2770 mutex_lock(&domain->api_lock);
2771 unmap_size = iommu_unmap_page(domain, iova, page_size);
2772 mutex_unlock(&domain->api_lock);
2774 domain_flush_tlb_pde(domain);
2776 return get_order(unmap_size);
2779 static phys_addr_t amd_iommu_iova_to_phys(struct iommu_domain *dom,
2782 struct protection_domain *domain = dom->priv;
2783 unsigned long offset_mask;
2787 pte = fetch_pte(domain, iova);
2789 if (!pte || !IOMMU_PTE_PRESENT(*pte))
2792 if (PM_PTE_LEVEL(*pte) == 0)
2793 offset_mask = PAGE_SIZE - 1;
2795 offset_mask = PTE_PAGE_SIZE(*pte) - 1;
2797 __pte = *pte & PM_ADDR_MASK;
2798 paddr = (__pte & ~offset_mask) | (iova & offset_mask);
2803 static int amd_iommu_domain_has_cap(struct iommu_domain *domain,
2807 case IOMMU_CAP_CACHE_COHERENCY:
2814 static struct iommu_ops amd_iommu_ops = {
2815 .domain_init = amd_iommu_domain_init,
2816 .domain_destroy = amd_iommu_domain_destroy,
2817 .attach_dev = amd_iommu_attach_device,
2818 .detach_dev = amd_iommu_detach_device,
2819 .map = amd_iommu_map,
2820 .unmap = amd_iommu_unmap,
2821 .iova_to_phys = amd_iommu_iova_to_phys,
2822 .domain_has_cap = amd_iommu_domain_has_cap,
2825 /*****************************************************************************
2827 * The next functions do a basic initialization of IOMMU for pass through
2830 * In passthrough mode the IOMMU is initialized and enabled but not used for
2831 * DMA-API translation.
2833 *****************************************************************************/
2835 int __init amd_iommu_init_passthrough(void)
2837 struct amd_iommu *iommu;
2838 struct pci_dev *dev = NULL;
2841 /* allocate passthrough domain */
2842 pt_domain = protection_domain_alloc();
2846 pt_domain->mode |= PAGE_MODE_NONE;
2848 for_each_pci_dev(dev) {
2849 if (!check_device(&dev->dev))
2852 devid = get_device_id(&dev->dev);
2854 iommu = amd_iommu_rlookup_table[devid];
2858 attach_device(&dev->dev, pt_domain);
2861 pr_info("AMD-Vi: Initialized for Passthrough Mode\n");