]> git.karo-electronics.de Git - karo-tx-linux.git/blob - drivers/iommu/amd_iommu.c
iommu/amd: Properly account for virtual aliases in IOMMU groups
[karo-tx-linux.git] / drivers / iommu / amd_iommu.c
1 /*
2  * Copyright (C) 2007-2010 Advanced Micro Devices, Inc.
3  * Author: Joerg Roedel <joerg.roedel@amd.com>
4  *         Leo Duran <leo.duran@amd.com>
5  *
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.
9  *
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.
14  *
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
18  */
19
20 #include <linux/ratelimit.h>
21 #include <linux/pci.h>
22 #include <linux/pci-ats.h>
23 #include <linux/bitmap.h>
24 #include <linux/slab.h>
25 #include <linux/debugfs.h>
26 #include <linux/scatterlist.h>
27 #include <linux/dma-mapping.h>
28 #include <linux/iommu-helper.h>
29 #include <linux/iommu.h>
30 #include <linux/delay.h>
31 #include <linux/amd-iommu.h>
32 #include <linux/notifier.h>
33 #include <linux/export.h>
34 #include <linux/irq.h>
35 #include <linux/msi.h>
36 #include <asm/irq_remapping.h>
37 #include <asm/io_apic.h>
38 #include <asm/apic.h>
39 #include <asm/hw_irq.h>
40 #include <asm/msidef.h>
41 #include <asm/proto.h>
42 #include <asm/iommu.h>
43 #include <asm/gart.h>
44 #include <asm/dma.h>
45
46 #include "amd_iommu_proto.h"
47 #include "amd_iommu_types.h"
48 #include "irq_remapping.h"
49
50 #define CMD_SET_TYPE(cmd, t) ((cmd)->data[1] |= ((t) << 28))
51
52 #define LOOP_TIMEOUT    100000
53
54 /*
55  * This bitmap is used to advertise the page sizes our hardware support
56  * to the IOMMU core, which will then use this information to split
57  * physically contiguous memory regions it is mapping into page sizes
58  * that we support.
59  *
60  * Traditionally the IOMMU core just handed us the mappings directly,
61  * after making sure the size is an order of a 4KiB page and that the
62  * mapping has natural alignment.
63  *
64  * To retain this behavior, we currently advertise that we support
65  * all page sizes that are an order of 4KiB.
66  *
67  * If at some point we'd like to utilize the IOMMU core's new behavior,
68  * we could change this to advertise the real page sizes we support.
69  */
70 #define AMD_IOMMU_PGSIZES       (~0xFFFUL)
71
72 static DEFINE_RWLOCK(amd_iommu_devtable_lock);
73
74 /* A list of preallocated protection domains */
75 static LIST_HEAD(iommu_pd_list);
76 static DEFINE_SPINLOCK(iommu_pd_list_lock);
77
78 /* List of all available dev_data structures */
79 static LIST_HEAD(dev_data_list);
80 static DEFINE_SPINLOCK(dev_data_list_lock);
81
82 LIST_HEAD(ioapic_map);
83 LIST_HEAD(hpet_map);
84
85 /*
86  * Domain for untranslated devices - only allocated
87  * if iommu=pt passed on kernel cmd line.
88  */
89 static struct protection_domain *pt_domain;
90
91 static struct iommu_ops amd_iommu_ops;
92
93 static ATOMIC_NOTIFIER_HEAD(ppr_notifier);
94 int amd_iommu_max_glx_val = -1;
95
96 static struct dma_map_ops amd_iommu_dma_ops;
97
98 /*
99  * general struct to manage commands send to an IOMMU
100  */
101 struct iommu_cmd {
102         u32 data[4];
103 };
104
105 struct kmem_cache *amd_iommu_irq_cache;
106
107 static void update_domain(struct protection_domain *domain);
108 static int __init alloc_passthrough_domain(void);
109
110 /****************************************************************************
111  *
112  * Helper functions
113  *
114  ****************************************************************************/
115
116 static struct iommu_dev_data *alloc_dev_data(u16 devid)
117 {
118         struct iommu_dev_data *dev_data;
119         unsigned long flags;
120
121         dev_data = kzalloc(sizeof(*dev_data), GFP_KERNEL);
122         if (!dev_data)
123                 return NULL;
124
125         dev_data->devid = devid;
126         atomic_set(&dev_data->bind, 0);
127
128         spin_lock_irqsave(&dev_data_list_lock, flags);
129         list_add_tail(&dev_data->dev_data_list, &dev_data_list);
130         spin_unlock_irqrestore(&dev_data_list_lock, flags);
131
132         return dev_data;
133 }
134
135 static void free_dev_data(struct iommu_dev_data *dev_data)
136 {
137         unsigned long flags;
138
139         spin_lock_irqsave(&dev_data_list_lock, flags);
140         list_del(&dev_data->dev_data_list);
141         spin_unlock_irqrestore(&dev_data_list_lock, flags);
142
143         if (dev_data->group)
144                 iommu_group_put(dev_data->group);
145
146         kfree(dev_data);
147 }
148
149 static struct iommu_dev_data *search_dev_data(u16 devid)
150 {
151         struct iommu_dev_data *dev_data;
152         unsigned long flags;
153
154         spin_lock_irqsave(&dev_data_list_lock, flags);
155         list_for_each_entry(dev_data, &dev_data_list, dev_data_list) {
156                 if (dev_data->devid == devid)
157                         goto out_unlock;
158         }
159
160         dev_data = NULL;
161
162 out_unlock:
163         spin_unlock_irqrestore(&dev_data_list_lock, flags);
164
165         return dev_data;
166 }
167
168 static struct iommu_dev_data *find_dev_data(u16 devid)
169 {
170         struct iommu_dev_data *dev_data;
171
172         dev_data = search_dev_data(devid);
173
174         if (dev_data == NULL)
175                 dev_data = alloc_dev_data(devid);
176
177         return dev_data;
178 }
179
180 static inline u16 get_device_id(struct device *dev)
181 {
182         struct pci_dev *pdev = to_pci_dev(dev);
183
184         return calc_devid(pdev->bus->number, pdev->devfn);
185 }
186
187 static struct iommu_dev_data *get_dev_data(struct device *dev)
188 {
189         return dev->archdata.iommu;
190 }
191
192 static bool pci_iommuv2_capable(struct pci_dev *pdev)
193 {
194         static const int caps[] = {
195                 PCI_EXT_CAP_ID_ATS,
196                 PCI_EXT_CAP_ID_PRI,
197                 PCI_EXT_CAP_ID_PASID,
198         };
199         int i, pos;
200
201         for (i = 0; i < 3; ++i) {
202                 pos = pci_find_ext_capability(pdev, caps[i]);
203                 if (pos == 0)
204                         return false;
205         }
206
207         return true;
208 }
209
210 static bool pdev_pri_erratum(struct pci_dev *pdev, u32 erratum)
211 {
212         struct iommu_dev_data *dev_data;
213
214         dev_data = get_dev_data(&pdev->dev);
215
216         return dev_data->errata & (1 << erratum) ? true : false;
217 }
218
219 /*
220  * In this function the list of preallocated protection domains is traversed to
221  * find the domain for a specific device
222  */
223 static struct dma_ops_domain *find_protection_domain(u16 devid)
224 {
225         struct dma_ops_domain *entry, *ret = NULL;
226         unsigned long flags;
227         u16 alias = amd_iommu_alias_table[devid];
228
229         if (list_empty(&iommu_pd_list))
230                 return NULL;
231
232         spin_lock_irqsave(&iommu_pd_list_lock, flags);
233
234         list_for_each_entry(entry, &iommu_pd_list, list) {
235                 if (entry->target_dev == devid ||
236                     entry->target_dev == alias) {
237                         ret = entry;
238                         break;
239                 }
240         }
241
242         spin_unlock_irqrestore(&iommu_pd_list_lock, flags);
243
244         return ret;
245 }
246
247 /*
248  * This function checks if the driver got a valid device from the caller to
249  * avoid dereferencing invalid pointers.
250  */
251 static bool check_device(struct device *dev)
252 {
253         u16 devid;
254
255         if (!dev || !dev->dma_mask)
256                 return false;
257
258         /* No device or no PCI device */
259         if (dev->bus != &pci_bus_type)
260                 return false;
261
262         devid = get_device_id(dev);
263
264         /* Out of our scope? */
265         if (devid > amd_iommu_last_bdf)
266                 return false;
267
268         if (amd_iommu_rlookup_table[devid] == NULL)
269                 return false;
270
271         return true;
272 }
273
274 static void swap_pci_ref(struct pci_dev **from, struct pci_dev *to)
275 {
276         pci_dev_put(*from);
277         *from = to;
278 }
279
280 static struct pci_bus *find_hosted_bus(struct pci_bus *bus)
281 {
282         while (!bus->self) {
283                 if (!pci_is_root_bus(bus))
284                         bus = bus->parent;
285                 else
286                         return ERR_PTR(-ENODEV);
287         }
288
289         return bus;
290 }
291
292 #define REQ_ACS_FLAGS   (PCI_ACS_SV | PCI_ACS_RR | PCI_ACS_CR | PCI_ACS_UF)
293
294 static struct pci_dev *get_isolation_root(struct pci_dev *pdev)
295 {
296         struct pci_dev *dma_pdev = pdev;
297
298         /* Account for quirked devices */
299         swap_pci_ref(&dma_pdev, pci_get_dma_source(dma_pdev));
300
301         /*
302          * If it's a multifunction device that does not support our
303          * required ACS flags, add to the same group as function 0.
304          */
305         if (dma_pdev->multifunction &&
306             !pci_acs_enabled(dma_pdev, REQ_ACS_FLAGS))
307                 swap_pci_ref(&dma_pdev,
308                              pci_get_slot(dma_pdev->bus,
309                                           PCI_DEVFN(PCI_SLOT(dma_pdev->devfn),
310                                           0)));
311
312         /*
313          * Devices on the root bus go through the iommu.  If that's not us,
314          * find the next upstream device and test ACS up to the root bus.
315          * Finding the next device may require skipping virtual buses.
316          */
317         while (!pci_is_root_bus(dma_pdev->bus)) {
318                 struct pci_bus *bus = find_hosted_bus(dma_pdev->bus);
319                 if (IS_ERR(bus))
320                         break;
321
322                 if (pci_acs_path_enabled(bus->self, NULL, REQ_ACS_FLAGS))
323                         break;
324
325                 swap_pci_ref(&dma_pdev, pci_dev_get(bus->self));
326         }
327
328         return dma_pdev;
329 }
330
331 static int use_pdev_iommu_group(struct pci_dev *pdev, struct device *dev)
332 {
333         struct iommu_group *group = iommu_group_get(&pdev->dev);
334         int ret;
335
336         if (!group) {
337                 group = iommu_group_alloc();
338                 if (IS_ERR(group))
339                         return PTR_ERR(group);
340
341                 WARN_ON(&pdev->dev != dev);
342         }
343
344         ret = iommu_group_add_device(group, dev);
345         iommu_group_put(group);
346         return ret;
347 }
348
349 static int use_dev_data_iommu_group(struct iommu_dev_data *dev_data,
350                                     struct device *dev)
351 {
352         if (!dev_data->group) {
353                 struct iommu_group *group = iommu_group_alloc();
354                 if (IS_ERR(group))
355                         return PTR_ERR(group);
356
357                 dev_data->group = group;
358         }
359
360         return iommu_group_add_device(dev_data->group, dev);
361 }
362
363 static int init_iommu_group(struct device *dev)
364 {
365         struct iommu_dev_data *dev_data;
366         struct iommu_group *group;
367         struct pci_dev *dma_pdev;
368         int ret;
369
370         group = iommu_group_get(dev);
371         if (group) {
372                 iommu_group_put(group);
373                 return 0;
374         }
375
376         dev_data = find_dev_data(get_device_id(dev));
377         if (!dev_data)
378                 return -ENOMEM;
379
380         if (dev_data->alias_data) {
381                 u16 alias;
382                 struct pci_bus *bus;
383
384                 if (dev_data->alias_data->group)
385                         goto use_group;
386
387                 /*
388                  * If the alias device exists, it's effectively just a first
389                  * level quirk for finding the DMA source.
390                  */
391                 alias = amd_iommu_alias_table[dev_data->devid];
392                 dma_pdev = pci_get_bus_and_slot(alias >> 8, alias & 0xff);
393                 if (dma_pdev) {
394                         dma_pdev = get_isolation_root(dma_pdev);
395                         goto use_pdev;
396                 }
397
398                 /*
399                  * If the alias is virtual, try to find a parent device
400                  * and test whether the IOMMU group is actualy rooted above
401                  * the alias.  Be careful to also test the parent device if
402                  * we think the alias is the root of the group.
403                  */
404                 bus = pci_find_bus(0, alias >> 8);
405                 if (!bus)
406                         goto use_group;
407
408                 bus = find_hosted_bus(bus);
409                 if (IS_ERR(bus) || !bus->self)
410                         goto use_group;
411
412                 dma_pdev = get_isolation_root(pci_dev_get(bus->self));
413                 if (dma_pdev != bus->self || (dma_pdev->multifunction &&
414                     !pci_acs_enabled(dma_pdev, REQ_ACS_FLAGS)))
415                         goto use_pdev;
416
417                 pci_dev_put(dma_pdev);
418                 goto use_group;
419         }
420
421         dma_pdev = get_isolation_root(pci_dev_get(to_pci_dev(dev)));
422 use_pdev:
423         ret = use_pdev_iommu_group(dma_pdev, dev);
424         pci_dev_put(dma_pdev);
425         return ret;
426 use_group:
427         return use_dev_data_iommu_group(dev_data->alias_data, dev);
428 }
429
430 static int iommu_init_device(struct device *dev)
431 {
432         struct pci_dev *pdev = to_pci_dev(dev);
433         struct iommu_dev_data *dev_data;
434         u16 alias;
435         int ret;
436
437         if (dev->archdata.iommu)
438                 return 0;
439
440         dev_data = find_dev_data(get_device_id(dev));
441         if (!dev_data)
442                 return -ENOMEM;
443
444         alias = amd_iommu_alias_table[dev_data->devid];
445         if (alias != dev_data->devid) {
446                 struct iommu_dev_data *alias_data;
447
448                 alias_data = find_dev_data(alias);
449                 if (alias_data == NULL) {
450                         pr_err("AMD-Vi: Warning: Unhandled device %s\n",
451                                         dev_name(dev));
452                         free_dev_data(dev_data);
453                         return -ENOTSUPP;
454                 }
455                 dev_data->alias_data = alias_data;
456         }
457
458         ret = init_iommu_group(dev);
459         if (ret)
460                 return ret;
461
462         if (pci_iommuv2_capable(pdev)) {
463                 struct amd_iommu *iommu;
464
465                 iommu              = amd_iommu_rlookup_table[dev_data->devid];
466                 dev_data->iommu_v2 = iommu->is_iommu_v2;
467         }
468
469         dev->archdata.iommu = dev_data;
470
471         return 0;
472 }
473
474 static void iommu_ignore_device(struct device *dev)
475 {
476         u16 devid, alias;
477
478         devid = get_device_id(dev);
479         alias = amd_iommu_alias_table[devid];
480
481         memset(&amd_iommu_dev_table[devid], 0, sizeof(struct dev_table_entry));
482         memset(&amd_iommu_dev_table[alias], 0, sizeof(struct dev_table_entry));
483
484         amd_iommu_rlookup_table[devid] = NULL;
485         amd_iommu_rlookup_table[alias] = NULL;
486 }
487
488 static void iommu_uninit_device(struct device *dev)
489 {
490         iommu_group_remove_device(dev);
491
492         /*
493          * Nothing to do here - we keep dev_data around for unplugged devices
494          * and reuse it when the device is re-plugged - not doing so would
495          * introduce a ton of races.
496          */
497 }
498
499 void __init amd_iommu_uninit_devices(void)
500 {
501         struct iommu_dev_data *dev_data, *n;
502         struct pci_dev *pdev = NULL;
503
504         for_each_pci_dev(pdev) {
505
506                 if (!check_device(&pdev->dev))
507                         continue;
508
509                 iommu_uninit_device(&pdev->dev);
510         }
511
512         /* Free all of our dev_data structures */
513         list_for_each_entry_safe(dev_data, n, &dev_data_list, dev_data_list)
514                 free_dev_data(dev_data);
515 }
516
517 int __init amd_iommu_init_devices(void)
518 {
519         struct pci_dev *pdev = NULL;
520         int ret = 0;
521
522         for_each_pci_dev(pdev) {
523
524                 if (!check_device(&pdev->dev))
525                         continue;
526
527                 ret = iommu_init_device(&pdev->dev);
528                 if (ret == -ENOTSUPP)
529                         iommu_ignore_device(&pdev->dev);
530                 else if (ret)
531                         goto out_free;
532         }
533
534         return 0;
535
536 out_free:
537
538         amd_iommu_uninit_devices();
539
540         return ret;
541 }
542 #ifdef CONFIG_AMD_IOMMU_STATS
543
544 /*
545  * Initialization code for statistics collection
546  */
547
548 DECLARE_STATS_COUNTER(compl_wait);
549 DECLARE_STATS_COUNTER(cnt_map_single);
550 DECLARE_STATS_COUNTER(cnt_unmap_single);
551 DECLARE_STATS_COUNTER(cnt_map_sg);
552 DECLARE_STATS_COUNTER(cnt_unmap_sg);
553 DECLARE_STATS_COUNTER(cnt_alloc_coherent);
554 DECLARE_STATS_COUNTER(cnt_free_coherent);
555 DECLARE_STATS_COUNTER(cross_page);
556 DECLARE_STATS_COUNTER(domain_flush_single);
557 DECLARE_STATS_COUNTER(domain_flush_all);
558 DECLARE_STATS_COUNTER(alloced_io_mem);
559 DECLARE_STATS_COUNTER(total_map_requests);
560 DECLARE_STATS_COUNTER(complete_ppr);
561 DECLARE_STATS_COUNTER(invalidate_iotlb);
562 DECLARE_STATS_COUNTER(invalidate_iotlb_all);
563 DECLARE_STATS_COUNTER(pri_requests);
564
565 static struct dentry *stats_dir;
566 static struct dentry *de_fflush;
567
568 static void amd_iommu_stats_add(struct __iommu_counter *cnt)
569 {
570         if (stats_dir == NULL)
571                 return;
572
573         cnt->dent = debugfs_create_u64(cnt->name, 0444, stats_dir,
574                                        &cnt->value);
575 }
576
577 static void amd_iommu_stats_init(void)
578 {
579         stats_dir = debugfs_create_dir("amd-iommu", NULL);
580         if (stats_dir == NULL)
581                 return;
582
583         de_fflush  = debugfs_create_bool("fullflush", 0444, stats_dir,
584                                          &amd_iommu_unmap_flush);
585
586         amd_iommu_stats_add(&compl_wait);
587         amd_iommu_stats_add(&cnt_map_single);
588         amd_iommu_stats_add(&cnt_unmap_single);
589         amd_iommu_stats_add(&cnt_map_sg);
590         amd_iommu_stats_add(&cnt_unmap_sg);
591         amd_iommu_stats_add(&cnt_alloc_coherent);
592         amd_iommu_stats_add(&cnt_free_coherent);
593         amd_iommu_stats_add(&cross_page);
594         amd_iommu_stats_add(&domain_flush_single);
595         amd_iommu_stats_add(&domain_flush_all);
596         amd_iommu_stats_add(&alloced_io_mem);
597         amd_iommu_stats_add(&total_map_requests);
598         amd_iommu_stats_add(&complete_ppr);
599         amd_iommu_stats_add(&invalidate_iotlb);
600         amd_iommu_stats_add(&invalidate_iotlb_all);
601         amd_iommu_stats_add(&pri_requests);
602 }
603
604 #endif
605
606 /****************************************************************************
607  *
608  * Interrupt handling functions
609  *
610  ****************************************************************************/
611
612 static void dump_dte_entry(u16 devid)
613 {
614         int i;
615
616         for (i = 0; i < 4; ++i)
617                 pr_err("AMD-Vi: DTE[%d]: %016llx\n", i,
618                         amd_iommu_dev_table[devid].data[i]);
619 }
620
621 static void dump_command(unsigned long phys_addr)
622 {
623         struct iommu_cmd *cmd = phys_to_virt(phys_addr);
624         int i;
625
626         for (i = 0; i < 4; ++i)
627                 pr_err("AMD-Vi: CMD[%d]: %08x\n", i, cmd->data[i]);
628 }
629
630 static void iommu_print_event(struct amd_iommu *iommu, void *__evt)
631 {
632         int type, devid, domid, flags;
633         volatile u32 *event = __evt;
634         int count = 0;
635         u64 address;
636
637 retry:
638         type    = (event[1] >> EVENT_TYPE_SHIFT)  & EVENT_TYPE_MASK;
639         devid   = (event[0] >> EVENT_DEVID_SHIFT) & EVENT_DEVID_MASK;
640         domid   = (event[1] >> EVENT_DOMID_SHIFT) & EVENT_DOMID_MASK;
641         flags   = (event[1] >> EVENT_FLAGS_SHIFT) & EVENT_FLAGS_MASK;
642         address = (u64)(((u64)event[3]) << 32) | event[2];
643
644         if (type == 0) {
645                 /* Did we hit the erratum? */
646                 if (++count == LOOP_TIMEOUT) {
647                         pr_err("AMD-Vi: No event written to event log\n");
648                         return;
649                 }
650                 udelay(1);
651                 goto retry;
652         }
653
654         printk(KERN_ERR "AMD-Vi: Event logged [");
655
656         switch (type) {
657         case EVENT_TYPE_ILL_DEV:
658                 printk("ILLEGAL_DEV_TABLE_ENTRY device=%02x:%02x.%x "
659                        "address=0x%016llx flags=0x%04x]\n",
660                        PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
661                        address, flags);
662                 dump_dte_entry(devid);
663                 break;
664         case EVENT_TYPE_IO_FAULT:
665                 printk("IO_PAGE_FAULT device=%02x:%02x.%x "
666                        "domain=0x%04x address=0x%016llx flags=0x%04x]\n",
667                        PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
668                        domid, address, flags);
669                 break;
670         case EVENT_TYPE_DEV_TAB_ERR:
671                 printk("DEV_TAB_HARDWARE_ERROR device=%02x:%02x.%x "
672                        "address=0x%016llx flags=0x%04x]\n",
673                        PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
674                        address, flags);
675                 break;
676         case EVENT_TYPE_PAGE_TAB_ERR:
677                 printk("PAGE_TAB_HARDWARE_ERROR device=%02x:%02x.%x "
678                        "domain=0x%04x address=0x%016llx flags=0x%04x]\n",
679                        PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
680                        domid, address, flags);
681                 break;
682         case EVENT_TYPE_ILL_CMD:
683                 printk("ILLEGAL_COMMAND_ERROR address=0x%016llx]\n", address);
684                 dump_command(address);
685                 break;
686         case EVENT_TYPE_CMD_HARD_ERR:
687                 printk("COMMAND_HARDWARE_ERROR address=0x%016llx "
688                        "flags=0x%04x]\n", address, flags);
689                 break;
690         case EVENT_TYPE_IOTLB_INV_TO:
691                 printk("IOTLB_INV_TIMEOUT device=%02x:%02x.%x "
692                        "address=0x%016llx]\n",
693                        PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
694                        address);
695                 break;
696         case EVENT_TYPE_INV_DEV_REQ:
697                 printk("INVALID_DEVICE_REQUEST device=%02x:%02x.%x "
698                        "address=0x%016llx flags=0x%04x]\n",
699                        PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
700                        address, flags);
701                 break;
702         default:
703                 printk(KERN_ERR "UNKNOWN type=0x%02x]\n", type);
704         }
705
706         memset(__evt, 0, 4 * sizeof(u32));
707 }
708
709 static void iommu_poll_events(struct amd_iommu *iommu)
710 {
711         u32 head, tail;
712         unsigned long flags;
713
714         spin_lock_irqsave(&iommu->lock, flags);
715
716         head = readl(iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
717         tail = readl(iommu->mmio_base + MMIO_EVT_TAIL_OFFSET);
718
719         while (head != tail) {
720                 iommu_print_event(iommu, iommu->evt_buf + head);
721                 head = (head + EVENT_ENTRY_SIZE) % iommu->evt_buf_size;
722         }
723
724         writel(head, iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
725
726         spin_unlock_irqrestore(&iommu->lock, flags);
727 }
728
729 static void iommu_handle_ppr_entry(struct amd_iommu *iommu, u64 *raw)
730 {
731         struct amd_iommu_fault fault;
732
733         INC_STATS_COUNTER(pri_requests);
734
735         if (PPR_REQ_TYPE(raw[0]) != PPR_REQ_FAULT) {
736                 pr_err_ratelimited("AMD-Vi: Unknown PPR request received\n");
737                 return;
738         }
739
740         fault.address   = raw[1];
741         fault.pasid     = PPR_PASID(raw[0]);
742         fault.device_id = PPR_DEVID(raw[0]);
743         fault.tag       = PPR_TAG(raw[0]);
744         fault.flags     = PPR_FLAGS(raw[0]);
745
746         atomic_notifier_call_chain(&ppr_notifier, 0, &fault);
747 }
748
749 static void iommu_poll_ppr_log(struct amd_iommu *iommu)
750 {
751         unsigned long flags;
752         u32 head, tail;
753
754         if (iommu->ppr_log == NULL)
755                 return;
756
757         /* enable ppr interrupts again */
758         writel(MMIO_STATUS_PPR_INT_MASK, iommu->mmio_base + MMIO_STATUS_OFFSET);
759
760         spin_lock_irqsave(&iommu->lock, flags);
761
762         head = readl(iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
763         tail = readl(iommu->mmio_base + MMIO_PPR_TAIL_OFFSET);
764
765         while (head != tail) {
766                 volatile u64 *raw;
767                 u64 entry[2];
768                 int i;
769
770                 raw = (u64 *)(iommu->ppr_log + head);
771
772                 /*
773                  * Hardware bug: Interrupt may arrive before the entry is
774                  * written to memory. If this happens we need to wait for the
775                  * entry to arrive.
776                  */
777                 for (i = 0; i < LOOP_TIMEOUT; ++i) {
778                         if (PPR_REQ_TYPE(raw[0]) != 0)
779                                 break;
780                         udelay(1);
781                 }
782
783                 /* Avoid memcpy function-call overhead */
784                 entry[0] = raw[0];
785                 entry[1] = raw[1];
786
787                 /*
788                  * To detect the hardware bug we need to clear the entry
789                  * back to zero.
790                  */
791                 raw[0] = raw[1] = 0UL;
792
793                 /* Update head pointer of hardware ring-buffer */
794                 head = (head + PPR_ENTRY_SIZE) % PPR_LOG_SIZE;
795                 writel(head, iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
796
797                 /*
798                  * Release iommu->lock because ppr-handling might need to
799                  * re-acquire it
800                  */
801                 spin_unlock_irqrestore(&iommu->lock, flags);
802
803                 /* Handle PPR entry */
804                 iommu_handle_ppr_entry(iommu, entry);
805
806                 spin_lock_irqsave(&iommu->lock, flags);
807
808                 /* Refresh ring-buffer information */
809                 head = readl(iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
810                 tail = readl(iommu->mmio_base + MMIO_PPR_TAIL_OFFSET);
811         }
812
813         spin_unlock_irqrestore(&iommu->lock, flags);
814 }
815
816 irqreturn_t amd_iommu_int_thread(int irq, void *data)
817 {
818         struct amd_iommu *iommu;
819
820         for_each_iommu(iommu) {
821                 iommu_poll_events(iommu);
822                 iommu_poll_ppr_log(iommu);
823         }
824
825         return IRQ_HANDLED;
826 }
827
828 irqreturn_t amd_iommu_int_handler(int irq, void *data)
829 {
830         return IRQ_WAKE_THREAD;
831 }
832
833 /****************************************************************************
834  *
835  * IOMMU command queuing functions
836  *
837  ****************************************************************************/
838
839 static int wait_on_sem(volatile u64 *sem)
840 {
841         int i = 0;
842
843         while (*sem == 0 && i < LOOP_TIMEOUT) {
844                 udelay(1);
845                 i += 1;
846         }
847
848         if (i == LOOP_TIMEOUT) {
849                 pr_alert("AMD-Vi: Completion-Wait loop timed out\n");
850                 return -EIO;
851         }
852
853         return 0;
854 }
855
856 static void copy_cmd_to_buffer(struct amd_iommu *iommu,
857                                struct iommu_cmd *cmd,
858                                u32 tail)
859 {
860         u8 *target;
861
862         target = iommu->cmd_buf + tail;
863         tail   = (tail + sizeof(*cmd)) % iommu->cmd_buf_size;
864
865         /* Copy command to buffer */
866         memcpy(target, cmd, sizeof(*cmd));
867
868         /* Tell the IOMMU about it */
869         writel(tail, iommu->mmio_base + MMIO_CMD_TAIL_OFFSET);
870 }
871
872 static void build_completion_wait(struct iommu_cmd *cmd, u64 address)
873 {
874         WARN_ON(address & 0x7ULL);
875
876         memset(cmd, 0, sizeof(*cmd));
877         cmd->data[0] = lower_32_bits(__pa(address)) | CMD_COMPL_WAIT_STORE_MASK;
878         cmd->data[1] = upper_32_bits(__pa(address));
879         cmd->data[2] = 1;
880         CMD_SET_TYPE(cmd, CMD_COMPL_WAIT);
881 }
882
883 static void build_inv_dte(struct iommu_cmd *cmd, u16 devid)
884 {
885         memset(cmd, 0, sizeof(*cmd));
886         cmd->data[0] = devid;
887         CMD_SET_TYPE(cmd, CMD_INV_DEV_ENTRY);
888 }
889
890 static void build_inv_iommu_pages(struct iommu_cmd *cmd, u64 address,
891                                   size_t size, u16 domid, int pde)
892 {
893         u64 pages;
894         int s;
895
896         pages = iommu_num_pages(address, size, PAGE_SIZE);
897         s     = 0;
898
899         if (pages > 1) {
900                 /*
901                  * If we have to flush more than one page, flush all
902                  * TLB entries for this domain
903                  */
904                 address = CMD_INV_IOMMU_ALL_PAGES_ADDRESS;
905                 s = 1;
906         }
907
908         address &= PAGE_MASK;
909
910         memset(cmd, 0, sizeof(*cmd));
911         cmd->data[1] |= domid;
912         cmd->data[2]  = lower_32_bits(address);
913         cmd->data[3]  = upper_32_bits(address);
914         CMD_SET_TYPE(cmd, CMD_INV_IOMMU_PAGES);
915         if (s) /* size bit - we flush more than one 4kb page */
916                 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
917         if (pde) /* PDE bit - we want to flush everything, not only the PTEs */
918                 cmd->data[2] |= CMD_INV_IOMMU_PAGES_PDE_MASK;
919 }
920
921 static void build_inv_iotlb_pages(struct iommu_cmd *cmd, u16 devid, int qdep,
922                                   u64 address, size_t size)
923 {
924         u64 pages;
925         int s;
926
927         pages = iommu_num_pages(address, size, PAGE_SIZE);
928         s     = 0;
929
930         if (pages > 1) {
931                 /*
932                  * If we have to flush more than one page, flush all
933                  * TLB entries for this domain
934                  */
935                 address = CMD_INV_IOMMU_ALL_PAGES_ADDRESS;
936                 s = 1;
937         }
938
939         address &= PAGE_MASK;
940
941         memset(cmd, 0, sizeof(*cmd));
942         cmd->data[0]  = devid;
943         cmd->data[0] |= (qdep & 0xff) << 24;
944         cmd->data[1]  = devid;
945         cmd->data[2]  = lower_32_bits(address);
946         cmd->data[3]  = upper_32_bits(address);
947         CMD_SET_TYPE(cmd, CMD_INV_IOTLB_PAGES);
948         if (s)
949                 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
950 }
951
952 static void build_inv_iommu_pasid(struct iommu_cmd *cmd, u16 domid, int pasid,
953                                   u64 address, bool size)
954 {
955         memset(cmd, 0, sizeof(*cmd));
956
957         address &= ~(0xfffULL);
958
959         cmd->data[0]  = pasid & PASID_MASK;
960         cmd->data[1]  = domid;
961         cmd->data[2]  = lower_32_bits(address);
962         cmd->data[3]  = upper_32_bits(address);
963         cmd->data[2] |= CMD_INV_IOMMU_PAGES_PDE_MASK;
964         cmd->data[2] |= CMD_INV_IOMMU_PAGES_GN_MASK;
965         if (size)
966                 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
967         CMD_SET_TYPE(cmd, CMD_INV_IOMMU_PAGES);
968 }
969
970 static void build_inv_iotlb_pasid(struct iommu_cmd *cmd, u16 devid, int pasid,
971                                   int qdep, u64 address, bool size)
972 {
973         memset(cmd, 0, sizeof(*cmd));
974
975         address &= ~(0xfffULL);
976
977         cmd->data[0]  = devid;
978         cmd->data[0] |= (pasid & 0xff) << 16;
979         cmd->data[0] |= (qdep  & 0xff) << 24;
980         cmd->data[1]  = devid;
981         cmd->data[1] |= ((pasid >> 8) & 0xfff) << 16;
982         cmd->data[2]  = lower_32_bits(address);
983         cmd->data[2] |= CMD_INV_IOMMU_PAGES_GN_MASK;
984         cmd->data[3]  = upper_32_bits(address);
985         if (size)
986                 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
987         CMD_SET_TYPE(cmd, CMD_INV_IOTLB_PAGES);
988 }
989
990 static void build_complete_ppr(struct iommu_cmd *cmd, u16 devid, int pasid,
991                                int status, int tag, bool gn)
992 {
993         memset(cmd, 0, sizeof(*cmd));
994
995         cmd->data[0]  = devid;
996         if (gn) {
997                 cmd->data[1]  = pasid & PASID_MASK;
998                 cmd->data[2]  = CMD_INV_IOMMU_PAGES_GN_MASK;
999         }
1000         cmd->data[3]  = tag & 0x1ff;
1001         cmd->data[3] |= (status & PPR_STATUS_MASK) << PPR_STATUS_SHIFT;
1002
1003         CMD_SET_TYPE(cmd, CMD_COMPLETE_PPR);
1004 }
1005
1006 static void build_inv_all(struct iommu_cmd *cmd)
1007 {
1008         memset(cmd, 0, sizeof(*cmd));
1009         CMD_SET_TYPE(cmd, CMD_INV_ALL);
1010 }
1011
1012 static void build_inv_irt(struct iommu_cmd *cmd, u16 devid)
1013 {
1014         memset(cmd, 0, sizeof(*cmd));
1015         cmd->data[0] = devid;
1016         CMD_SET_TYPE(cmd, CMD_INV_IRT);
1017 }
1018
1019 /*
1020  * Writes the command to the IOMMUs command buffer and informs the
1021  * hardware about the new command.
1022  */
1023 static int iommu_queue_command_sync(struct amd_iommu *iommu,
1024                                     struct iommu_cmd *cmd,
1025                                     bool sync)
1026 {
1027         u32 left, tail, head, next_tail;
1028         unsigned long flags;
1029
1030         WARN_ON(iommu->cmd_buf_size & CMD_BUFFER_UNINITIALIZED);
1031
1032 again:
1033         spin_lock_irqsave(&iommu->lock, flags);
1034
1035         head      = readl(iommu->mmio_base + MMIO_CMD_HEAD_OFFSET);
1036         tail      = readl(iommu->mmio_base + MMIO_CMD_TAIL_OFFSET);
1037         next_tail = (tail + sizeof(*cmd)) % iommu->cmd_buf_size;
1038         left      = (head - next_tail) % iommu->cmd_buf_size;
1039
1040         if (left <= 2) {
1041                 struct iommu_cmd sync_cmd;
1042                 volatile u64 sem = 0;
1043                 int ret;
1044
1045                 build_completion_wait(&sync_cmd, (u64)&sem);
1046                 copy_cmd_to_buffer(iommu, &sync_cmd, tail);
1047
1048                 spin_unlock_irqrestore(&iommu->lock, flags);
1049
1050                 if ((ret = wait_on_sem(&sem)) != 0)
1051                         return ret;
1052
1053                 goto again;
1054         }
1055
1056         copy_cmd_to_buffer(iommu, cmd, tail);
1057
1058         /* We need to sync now to make sure all commands are processed */
1059         iommu->need_sync = sync;
1060
1061         spin_unlock_irqrestore(&iommu->lock, flags);
1062
1063         return 0;
1064 }
1065
1066 static int iommu_queue_command(struct amd_iommu *iommu, struct iommu_cmd *cmd)
1067 {
1068         return iommu_queue_command_sync(iommu, cmd, true);
1069 }
1070
1071 /*
1072  * This function queues a completion wait command into the command
1073  * buffer of an IOMMU
1074  */
1075 static int iommu_completion_wait(struct amd_iommu *iommu)
1076 {
1077         struct iommu_cmd cmd;
1078         volatile u64 sem = 0;
1079         int ret;
1080
1081         if (!iommu->need_sync)
1082                 return 0;
1083
1084         build_completion_wait(&cmd, (u64)&sem);
1085
1086         ret = iommu_queue_command_sync(iommu, &cmd, false);
1087         if (ret)
1088                 return ret;
1089
1090         return wait_on_sem(&sem);
1091 }
1092
1093 static int iommu_flush_dte(struct amd_iommu *iommu, u16 devid)
1094 {
1095         struct iommu_cmd cmd;
1096
1097         build_inv_dte(&cmd, devid);
1098
1099         return iommu_queue_command(iommu, &cmd);
1100 }
1101
1102 static void iommu_flush_dte_all(struct amd_iommu *iommu)
1103 {
1104         u32 devid;
1105
1106         for (devid = 0; devid <= 0xffff; ++devid)
1107                 iommu_flush_dte(iommu, devid);
1108
1109         iommu_completion_wait(iommu);
1110 }
1111
1112 /*
1113  * This function uses heavy locking and may disable irqs for some time. But
1114  * this is no issue because it is only called during resume.
1115  */
1116 static void iommu_flush_tlb_all(struct amd_iommu *iommu)
1117 {
1118         u32 dom_id;
1119
1120         for (dom_id = 0; dom_id <= 0xffff; ++dom_id) {
1121                 struct iommu_cmd cmd;
1122                 build_inv_iommu_pages(&cmd, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS,
1123                                       dom_id, 1);
1124                 iommu_queue_command(iommu, &cmd);
1125         }
1126
1127         iommu_completion_wait(iommu);
1128 }
1129
1130 static void iommu_flush_all(struct amd_iommu *iommu)
1131 {
1132         struct iommu_cmd cmd;
1133
1134         build_inv_all(&cmd);
1135
1136         iommu_queue_command(iommu, &cmd);
1137         iommu_completion_wait(iommu);
1138 }
1139
1140 static void iommu_flush_irt(struct amd_iommu *iommu, u16 devid)
1141 {
1142         struct iommu_cmd cmd;
1143
1144         build_inv_irt(&cmd, devid);
1145
1146         iommu_queue_command(iommu, &cmd);
1147 }
1148
1149 static void iommu_flush_irt_all(struct amd_iommu *iommu)
1150 {
1151         u32 devid;
1152
1153         for (devid = 0; devid <= MAX_DEV_TABLE_ENTRIES; devid++)
1154                 iommu_flush_irt(iommu, devid);
1155
1156         iommu_completion_wait(iommu);
1157 }
1158
1159 void iommu_flush_all_caches(struct amd_iommu *iommu)
1160 {
1161         if (iommu_feature(iommu, FEATURE_IA)) {
1162                 iommu_flush_all(iommu);
1163         } else {
1164                 iommu_flush_dte_all(iommu);
1165                 iommu_flush_irt_all(iommu);
1166                 iommu_flush_tlb_all(iommu);
1167         }
1168 }
1169
1170 /*
1171  * Command send function for flushing on-device TLB
1172  */
1173 static int device_flush_iotlb(struct iommu_dev_data *dev_data,
1174                               u64 address, size_t size)
1175 {
1176         struct amd_iommu *iommu;
1177         struct iommu_cmd cmd;
1178         int qdep;
1179
1180         qdep     = dev_data->ats.qdep;
1181         iommu    = amd_iommu_rlookup_table[dev_data->devid];
1182
1183         build_inv_iotlb_pages(&cmd, dev_data->devid, qdep, address, size);
1184
1185         return iommu_queue_command(iommu, &cmd);
1186 }
1187
1188 /*
1189  * Command send function for invalidating a device table entry
1190  */
1191 static int device_flush_dte(struct iommu_dev_data *dev_data)
1192 {
1193         struct amd_iommu *iommu;
1194         int ret;
1195
1196         iommu = amd_iommu_rlookup_table[dev_data->devid];
1197
1198         ret = iommu_flush_dte(iommu, dev_data->devid);
1199         if (ret)
1200                 return ret;
1201
1202         if (dev_data->ats.enabled)
1203                 ret = device_flush_iotlb(dev_data, 0, ~0UL);
1204
1205         return ret;
1206 }
1207
1208 /*
1209  * TLB invalidation function which is called from the mapping functions.
1210  * It invalidates a single PTE if the range to flush is within a single
1211  * page. Otherwise it flushes the whole TLB of the IOMMU.
1212  */
1213 static void __domain_flush_pages(struct protection_domain *domain,
1214                                  u64 address, size_t size, int pde)
1215 {
1216         struct iommu_dev_data *dev_data;
1217         struct iommu_cmd cmd;
1218         int ret = 0, i;
1219
1220         build_inv_iommu_pages(&cmd, address, size, domain->id, pde);
1221
1222         for (i = 0; i < amd_iommus_present; ++i) {
1223                 if (!domain->dev_iommu[i])
1224                         continue;
1225
1226                 /*
1227                  * Devices of this domain are behind this IOMMU
1228                  * We need a TLB flush
1229                  */
1230                 ret |= iommu_queue_command(amd_iommus[i], &cmd);
1231         }
1232
1233         list_for_each_entry(dev_data, &domain->dev_list, list) {
1234
1235                 if (!dev_data->ats.enabled)
1236                         continue;
1237
1238                 ret |= device_flush_iotlb(dev_data, address, size);
1239         }
1240
1241         WARN_ON(ret);
1242 }
1243
1244 static void domain_flush_pages(struct protection_domain *domain,
1245                                u64 address, size_t size)
1246 {
1247         __domain_flush_pages(domain, address, size, 0);
1248 }
1249
1250 /* Flush the whole IO/TLB for a given protection domain */
1251 static void domain_flush_tlb(struct protection_domain *domain)
1252 {
1253         __domain_flush_pages(domain, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS, 0);
1254 }
1255
1256 /* Flush the whole IO/TLB for a given protection domain - including PDE */
1257 static void domain_flush_tlb_pde(struct protection_domain *domain)
1258 {
1259         __domain_flush_pages(domain, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS, 1);
1260 }
1261
1262 static void domain_flush_complete(struct protection_domain *domain)
1263 {
1264         int i;
1265
1266         for (i = 0; i < amd_iommus_present; ++i) {
1267                 if (!domain->dev_iommu[i])
1268                         continue;
1269
1270                 /*
1271                  * Devices of this domain are behind this IOMMU
1272                  * We need to wait for completion of all commands.
1273                  */
1274                 iommu_completion_wait(amd_iommus[i]);
1275         }
1276 }
1277
1278
1279 /*
1280  * This function flushes the DTEs for all devices in domain
1281  */
1282 static void domain_flush_devices(struct protection_domain *domain)
1283 {
1284         struct iommu_dev_data *dev_data;
1285
1286         list_for_each_entry(dev_data, &domain->dev_list, list)
1287                 device_flush_dte(dev_data);
1288 }
1289
1290 /****************************************************************************
1291  *
1292  * The functions below are used the create the page table mappings for
1293  * unity mapped regions.
1294  *
1295  ****************************************************************************/
1296
1297 /*
1298  * This function is used to add another level to an IO page table. Adding
1299  * another level increases the size of the address space by 9 bits to a size up
1300  * to 64 bits.
1301  */
1302 static bool increase_address_space(struct protection_domain *domain,
1303                                    gfp_t gfp)
1304 {
1305         u64 *pte;
1306
1307         if (domain->mode == PAGE_MODE_6_LEVEL)
1308                 /* address space already 64 bit large */
1309                 return false;
1310
1311         pte = (void *)get_zeroed_page(gfp);
1312         if (!pte)
1313                 return false;
1314
1315         *pte             = PM_LEVEL_PDE(domain->mode,
1316                                         virt_to_phys(domain->pt_root));
1317         domain->pt_root  = pte;
1318         domain->mode    += 1;
1319         domain->updated  = true;
1320
1321         return true;
1322 }
1323
1324 static u64 *alloc_pte(struct protection_domain *domain,
1325                       unsigned long address,
1326                       unsigned long page_size,
1327                       u64 **pte_page,
1328                       gfp_t gfp)
1329 {
1330         int level, end_lvl;
1331         u64 *pte, *page;
1332
1333         BUG_ON(!is_power_of_2(page_size));
1334
1335         while (address > PM_LEVEL_SIZE(domain->mode))
1336                 increase_address_space(domain, gfp);
1337
1338         level   = domain->mode - 1;
1339         pte     = &domain->pt_root[PM_LEVEL_INDEX(level, address)];
1340         address = PAGE_SIZE_ALIGN(address, page_size);
1341         end_lvl = PAGE_SIZE_LEVEL(page_size);
1342
1343         while (level > end_lvl) {
1344                 if (!IOMMU_PTE_PRESENT(*pte)) {
1345                         page = (u64 *)get_zeroed_page(gfp);
1346                         if (!page)
1347                                 return NULL;
1348                         *pte = PM_LEVEL_PDE(level, virt_to_phys(page));
1349                 }
1350
1351                 /* No level skipping support yet */
1352                 if (PM_PTE_LEVEL(*pte) != level)
1353                         return NULL;
1354
1355                 level -= 1;
1356
1357                 pte = IOMMU_PTE_PAGE(*pte);
1358
1359                 if (pte_page && level == end_lvl)
1360                         *pte_page = pte;
1361
1362                 pte = &pte[PM_LEVEL_INDEX(level, address)];
1363         }
1364
1365         return pte;
1366 }
1367
1368 /*
1369  * This function checks if there is a PTE for a given dma address. If
1370  * there is one, it returns the pointer to it.
1371  */
1372 static u64 *fetch_pte(struct protection_domain *domain, unsigned long address)
1373 {
1374         int level;
1375         u64 *pte;
1376
1377         if (address > PM_LEVEL_SIZE(domain->mode))
1378                 return NULL;
1379
1380         level   =  domain->mode - 1;
1381         pte     = &domain->pt_root[PM_LEVEL_INDEX(level, address)];
1382
1383         while (level > 0) {
1384
1385                 /* Not Present */
1386                 if (!IOMMU_PTE_PRESENT(*pte))
1387                         return NULL;
1388
1389                 /* Large PTE */
1390                 if (PM_PTE_LEVEL(*pte) == 0x07) {
1391                         unsigned long pte_mask, __pte;
1392
1393                         /*
1394                          * If we have a series of large PTEs, make
1395                          * sure to return a pointer to the first one.
1396                          */
1397                         pte_mask = PTE_PAGE_SIZE(*pte);
1398                         pte_mask = ~((PAGE_SIZE_PTE_COUNT(pte_mask) << 3) - 1);
1399                         __pte    = ((unsigned long)pte) & pte_mask;
1400
1401                         return (u64 *)__pte;
1402                 }
1403
1404                 /* No level skipping support yet */
1405                 if (PM_PTE_LEVEL(*pte) != level)
1406                         return NULL;
1407
1408                 level -= 1;
1409
1410                 /* Walk to the next level */
1411                 pte = IOMMU_PTE_PAGE(*pte);
1412                 pte = &pte[PM_LEVEL_INDEX(level, address)];
1413         }
1414
1415         return pte;
1416 }
1417
1418 /*
1419  * Generic mapping functions. It maps a physical address into a DMA
1420  * address space. It allocates the page table pages if necessary.
1421  * In the future it can be extended to a generic mapping function
1422  * supporting all features of AMD IOMMU page tables like level skipping
1423  * and full 64 bit address spaces.
1424  */
1425 static int iommu_map_page(struct protection_domain *dom,
1426                           unsigned long bus_addr,
1427                           unsigned long phys_addr,
1428                           int prot,
1429                           unsigned long page_size)
1430 {
1431         u64 __pte, *pte;
1432         int i, count;
1433
1434         if (!(prot & IOMMU_PROT_MASK))
1435                 return -EINVAL;
1436
1437         bus_addr  = PAGE_ALIGN(bus_addr);
1438         phys_addr = PAGE_ALIGN(phys_addr);
1439         count     = PAGE_SIZE_PTE_COUNT(page_size);
1440         pte       = alloc_pte(dom, bus_addr, page_size, NULL, GFP_KERNEL);
1441
1442         for (i = 0; i < count; ++i)
1443                 if (IOMMU_PTE_PRESENT(pte[i]))
1444                         return -EBUSY;
1445
1446         if (page_size > PAGE_SIZE) {
1447                 __pte = PAGE_SIZE_PTE(phys_addr, page_size);
1448                 __pte |= PM_LEVEL_ENC(7) | IOMMU_PTE_P | IOMMU_PTE_FC;
1449         } else
1450                 __pte = phys_addr | IOMMU_PTE_P | IOMMU_PTE_FC;
1451
1452         if (prot & IOMMU_PROT_IR)
1453                 __pte |= IOMMU_PTE_IR;
1454         if (prot & IOMMU_PROT_IW)
1455                 __pte |= IOMMU_PTE_IW;
1456
1457         for (i = 0; i < count; ++i)
1458                 pte[i] = __pte;
1459
1460         update_domain(dom);
1461
1462         return 0;
1463 }
1464
1465 static unsigned long iommu_unmap_page(struct protection_domain *dom,
1466                                       unsigned long bus_addr,
1467                                       unsigned long page_size)
1468 {
1469         unsigned long long unmap_size, unmapped;
1470         u64 *pte;
1471
1472         BUG_ON(!is_power_of_2(page_size));
1473
1474         unmapped = 0;
1475
1476         while (unmapped < page_size) {
1477
1478                 pte = fetch_pte(dom, bus_addr);
1479
1480                 if (!pte) {
1481                         /*
1482                          * No PTE for this address
1483                          * move forward in 4kb steps
1484                          */
1485                         unmap_size = PAGE_SIZE;
1486                 } else if (PM_PTE_LEVEL(*pte) == 0) {
1487                         /* 4kb PTE found for this address */
1488                         unmap_size = PAGE_SIZE;
1489                         *pte       = 0ULL;
1490                 } else {
1491                         int count, i;
1492
1493                         /* Large PTE found which maps this address */
1494                         unmap_size = PTE_PAGE_SIZE(*pte);
1495                         count      = PAGE_SIZE_PTE_COUNT(unmap_size);
1496                         for (i = 0; i < count; i++)
1497                                 pte[i] = 0ULL;
1498                 }
1499
1500                 bus_addr  = (bus_addr & ~(unmap_size - 1)) + unmap_size;
1501                 unmapped += unmap_size;
1502         }
1503
1504         BUG_ON(!is_power_of_2(unmapped));
1505
1506         return unmapped;
1507 }
1508
1509 /*
1510  * This function checks if a specific unity mapping entry is needed for
1511  * this specific IOMMU.
1512  */
1513 static int iommu_for_unity_map(struct amd_iommu *iommu,
1514                                struct unity_map_entry *entry)
1515 {
1516         u16 bdf, i;
1517
1518         for (i = entry->devid_start; i <= entry->devid_end; ++i) {
1519                 bdf = amd_iommu_alias_table[i];
1520                 if (amd_iommu_rlookup_table[bdf] == iommu)
1521                         return 1;
1522         }
1523
1524         return 0;
1525 }
1526
1527 /*
1528  * This function actually applies the mapping to the page table of the
1529  * dma_ops domain.
1530  */
1531 static int dma_ops_unity_map(struct dma_ops_domain *dma_dom,
1532                              struct unity_map_entry *e)
1533 {
1534         u64 addr;
1535         int ret;
1536
1537         for (addr = e->address_start; addr < e->address_end;
1538              addr += PAGE_SIZE) {
1539                 ret = iommu_map_page(&dma_dom->domain, addr, addr, e->prot,
1540                                      PAGE_SIZE);
1541                 if (ret)
1542                         return ret;
1543                 /*
1544                  * if unity mapping is in aperture range mark the page
1545                  * as allocated in the aperture
1546                  */
1547                 if (addr < dma_dom->aperture_size)
1548                         __set_bit(addr >> PAGE_SHIFT,
1549                                   dma_dom->aperture[0]->bitmap);
1550         }
1551
1552         return 0;
1553 }
1554
1555 /*
1556  * Init the unity mappings for a specific IOMMU in the system
1557  *
1558  * Basically iterates over all unity mapping entries and applies them to
1559  * the default domain DMA of that IOMMU if necessary.
1560  */
1561 static int iommu_init_unity_mappings(struct amd_iommu *iommu)
1562 {
1563         struct unity_map_entry *entry;
1564         int ret;
1565
1566         list_for_each_entry(entry, &amd_iommu_unity_map, list) {
1567                 if (!iommu_for_unity_map(iommu, entry))
1568                         continue;
1569                 ret = dma_ops_unity_map(iommu->default_dom, entry);
1570                 if (ret)
1571                         return ret;
1572         }
1573
1574         return 0;
1575 }
1576
1577 /*
1578  * Inits the unity mappings required for a specific device
1579  */
1580 static int init_unity_mappings_for_device(struct dma_ops_domain *dma_dom,
1581                                           u16 devid)
1582 {
1583         struct unity_map_entry *e;
1584         int ret;
1585
1586         list_for_each_entry(e, &amd_iommu_unity_map, list) {
1587                 if (!(devid >= e->devid_start && devid <= e->devid_end))
1588                         continue;
1589                 ret = dma_ops_unity_map(dma_dom, e);
1590                 if (ret)
1591                         return ret;
1592         }
1593
1594         return 0;
1595 }
1596
1597 /****************************************************************************
1598  *
1599  * The next functions belong to the address allocator for the dma_ops
1600  * interface functions. They work like the allocators in the other IOMMU
1601  * drivers. Its basically a bitmap which marks the allocated pages in
1602  * the aperture. Maybe it could be enhanced in the future to a more
1603  * efficient allocator.
1604  *
1605  ****************************************************************************/
1606
1607 /*
1608  * The address allocator core functions.
1609  *
1610  * called with domain->lock held
1611  */
1612
1613 /*
1614  * Used to reserve address ranges in the aperture (e.g. for exclusion
1615  * ranges.
1616  */
1617 static void dma_ops_reserve_addresses(struct dma_ops_domain *dom,
1618                                       unsigned long start_page,
1619                                       unsigned int pages)
1620 {
1621         unsigned int i, last_page = dom->aperture_size >> PAGE_SHIFT;
1622
1623         if (start_page + pages > last_page)
1624                 pages = last_page - start_page;
1625
1626         for (i = start_page; i < start_page + pages; ++i) {
1627                 int index = i / APERTURE_RANGE_PAGES;
1628                 int page  = i % APERTURE_RANGE_PAGES;
1629                 __set_bit(page, dom->aperture[index]->bitmap);
1630         }
1631 }
1632
1633 /*
1634  * This function is used to add a new aperture range to an existing
1635  * aperture in case of dma_ops domain allocation or address allocation
1636  * failure.
1637  */
1638 static int alloc_new_range(struct dma_ops_domain *dma_dom,
1639                            bool populate, gfp_t gfp)
1640 {
1641         int index = dma_dom->aperture_size >> APERTURE_RANGE_SHIFT;
1642         struct amd_iommu *iommu;
1643         unsigned long i, old_size;
1644
1645 #ifdef CONFIG_IOMMU_STRESS
1646         populate = false;
1647 #endif
1648
1649         if (index >= APERTURE_MAX_RANGES)
1650                 return -ENOMEM;
1651
1652         dma_dom->aperture[index] = kzalloc(sizeof(struct aperture_range), gfp);
1653         if (!dma_dom->aperture[index])
1654                 return -ENOMEM;
1655
1656         dma_dom->aperture[index]->bitmap = (void *)get_zeroed_page(gfp);
1657         if (!dma_dom->aperture[index]->bitmap)
1658                 goto out_free;
1659
1660         dma_dom->aperture[index]->offset = dma_dom->aperture_size;
1661
1662         if (populate) {
1663                 unsigned long address = dma_dom->aperture_size;
1664                 int i, num_ptes = APERTURE_RANGE_PAGES / 512;
1665                 u64 *pte, *pte_page;
1666
1667                 for (i = 0; i < num_ptes; ++i) {
1668                         pte = alloc_pte(&dma_dom->domain, address, PAGE_SIZE,
1669                                         &pte_page, gfp);
1670                         if (!pte)
1671                                 goto out_free;
1672
1673                         dma_dom->aperture[index]->pte_pages[i] = pte_page;
1674
1675                         address += APERTURE_RANGE_SIZE / 64;
1676                 }
1677         }
1678
1679         old_size                = dma_dom->aperture_size;
1680         dma_dom->aperture_size += APERTURE_RANGE_SIZE;
1681
1682         /* Reserve address range used for MSI messages */
1683         if (old_size < MSI_ADDR_BASE_LO &&
1684             dma_dom->aperture_size > MSI_ADDR_BASE_LO) {
1685                 unsigned long spage;
1686                 int pages;
1687
1688                 pages = iommu_num_pages(MSI_ADDR_BASE_LO, 0x10000, PAGE_SIZE);
1689                 spage = MSI_ADDR_BASE_LO >> PAGE_SHIFT;
1690
1691                 dma_ops_reserve_addresses(dma_dom, spage, pages);
1692         }
1693
1694         /* Initialize the exclusion range if necessary */
1695         for_each_iommu(iommu) {
1696                 if (iommu->exclusion_start &&
1697                     iommu->exclusion_start >= dma_dom->aperture[index]->offset
1698                     && iommu->exclusion_start < dma_dom->aperture_size) {
1699                         unsigned long startpage;
1700                         int pages = iommu_num_pages(iommu->exclusion_start,
1701                                                     iommu->exclusion_length,
1702                                                     PAGE_SIZE);
1703                         startpage = iommu->exclusion_start >> PAGE_SHIFT;
1704                         dma_ops_reserve_addresses(dma_dom, startpage, pages);
1705                 }
1706         }
1707
1708         /*
1709          * Check for areas already mapped as present in the new aperture
1710          * range and mark those pages as reserved in the allocator. Such
1711          * mappings may already exist as a result of requested unity
1712          * mappings for devices.
1713          */
1714         for (i = dma_dom->aperture[index]->offset;
1715              i < dma_dom->aperture_size;
1716              i += PAGE_SIZE) {
1717                 u64 *pte = fetch_pte(&dma_dom->domain, i);
1718                 if (!pte || !IOMMU_PTE_PRESENT(*pte))
1719                         continue;
1720
1721                 dma_ops_reserve_addresses(dma_dom, i >> PAGE_SHIFT, 1);
1722         }
1723
1724         update_domain(&dma_dom->domain);
1725
1726         return 0;
1727
1728 out_free:
1729         update_domain(&dma_dom->domain);
1730
1731         free_page((unsigned long)dma_dom->aperture[index]->bitmap);
1732
1733         kfree(dma_dom->aperture[index]);
1734         dma_dom->aperture[index] = NULL;
1735
1736         return -ENOMEM;
1737 }
1738
1739 static unsigned long dma_ops_area_alloc(struct device *dev,
1740                                         struct dma_ops_domain *dom,
1741                                         unsigned int pages,
1742                                         unsigned long align_mask,
1743                                         u64 dma_mask,
1744                                         unsigned long start)
1745 {
1746         unsigned long next_bit = dom->next_address % APERTURE_RANGE_SIZE;
1747         int max_index = dom->aperture_size >> APERTURE_RANGE_SHIFT;
1748         int i = start >> APERTURE_RANGE_SHIFT;
1749         unsigned long boundary_size;
1750         unsigned long address = -1;
1751         unsigned long limit;
1752
1753         next_bit >>= PAGE_SHIFT;
1754
1755         boundary_size = ALIGN(dma_get_seg_boundary(dev) + 1,
1756                         PAGE_SIZE) >> PAGE_SHIFT;
1757
1758         for (;i < max_index; ++i) {
1759                 unsigned long offset = dom->aperture[i]->offset >> PAGE_SHIFT;
1760
1761                 if (dom->aperture[i]->offset >= dma_mask)
1762                         break;
1763
1764                 limit = iommu_device_max_index(APERTURE_RANGE_PAGES, offset,
1765                                                dma_mask >> PAGE_SHIFT);
1766
1767                 address = iommu_area_alloc(dom->aperture[i]->bitmap,
1768                                            limit, next_bit, pages, 0,
1769                                             boundary_size, align_mask);
1770                 if (address != -1) {
1771                         address = dom->aperture[i]->offset +
1772                                   (address << PAGE_SHIFT);
1773                         dom->next_address = address + (pages << PAGE_SHIFT);
1774                         break;
1775                 }
1776
1777                 next_bit = 0;
1778         }
1779
1780         return address;
1781 }
1782
1783 static unsigned long dma_ops_alloc_addresses(struct device *dev,
1784                                              struct dma_ops_domain *dom,
1785                                              unsigned int pages,
1786                                              unsigned long align_mask,
1787                                              u64 dma_mask)
1788 {
1789         unsigned long address;
1790
1791 #ifdef CONFIG_IOMMU_STRESS
1792         dom->next_address = 0;
1793         dom->need_flush = true;
1794 #endif
1795
1796         address = dma_ops_area_alloc(dev, dom, pages, align_mask,
1797                                      dma_mask, dom->next_address);
1798
1799         if (address == -1) {
1800                 dom->next_address = 0;
1801                 address = dma_ops_area_alloc(dev, dom, pages, align_mask,
1802                                              dma_mask, 0);
1803                 dom->need_flush = true;
1804         }
1805
1806         if (unlikely(address == -1))
1807                 address = DMA_ERROR_CODE;
1808
1809         WARN_ON((address + (PAGE_SIZE*pages)) > dom->aperture_size);
1810
1811         return address;
1812 }
1813
1814 /*
1815  * The address free function.
1816  *
1817  * called with domain->lock held
1818  */
1819 static void dma_ops_free_addresses(struct dma_ops_domain *dom,
1820                                    unsigned long address,
1821                                    unsigned int pages)
1822 {
1823         unsigned i = address >> APERTURE_RANGE_SHIFT;
1824         struct aperture_range *range = dom->aperture[i];
1825
1826         BUG_ON(i >= APERTURE_MAX_RANGES || range == NULL);
1827
1828 #ifdef CONFIG_IOMMU_STRESS
1829         if (i < 4)
1830                 return;
1831 #endif
1832
1833         if (address >= dom->next_address)
1834                 dom->need_flush = true;
1835
1836         address = (address % APERTURE_RANGE_SIZE) >> PAGE_SHIFT;
1837
1838         bitmap_clear(range->bitmap, address, pages);
1839
1840 }
1841
1842 /****************************************************************************
1843  *
1844  * The next functions belong to the domain allocation. A domain is
1845  * allocated for every IOMMU as the default domain. If device isolation
1846  * is enabled, every device get its own domain. The most important thing
1847  * about domains is the page table mapping the DMA address space they
1848  * contain.
1849  *
1850  ****************************************************************************/
1851
1852 /*
1853  * This function adds a protection domain to the global protection domain list
1854  */
1855 static void add_domain_to_list(struct protection_domain *domain)
1856 {
1857         unsigned long flags;
1858
1859         spin_lock_irqsave(&amd_iommu_pd_lock, flags);
1860         list_add(&domain->list, &amd_iommu_pd_list);
1861         spin_unlock_irqrestore(&amd_iommu_pd_lock, flags);
1862 }
1863
1864 /*
1865  * This function removes a protection domain to the global
1866  * protection domain list
1867  */
1868 static void del_domain_from_list(struct protection_domain *domain)
1869 {
1870         unsigned long flags;
1871
1872         spin_lock_irqsave(&amd_iommu_pd_lock, flags);
1873         list_del(&domain->list);
1874         spin_unlock_irqrestore(&amd_iommu_pd_lock, flags);
1875 }
1876
1877 static u16 domain_id_alloc(void)
1878 {
1879         unsigned long flags;
1880         int id;
1881
1882         write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1883         id = find_first_zero_bit(amd_iommu_pd_alloc_bitmap, MAX_DOMAIN_ID);
1884         BUG_ON(id == 0);
1885         if (id > 0 && id < MAX_DOMAIN_ID)
1886                 __set_bit(id, amd_iommu_pd_alloc_bitmap);
1887         else
1888                 id = 0;
1889         write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1890
1891         return id;
1892 }
1893
1894 static void domain_id_free(int id)
1895 {
1896         unsigned long flags;
1897
1898         write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1899         if (id > 0 && id < MAX_DOMAIN_ID)
1900                 __clear_bit(id, amd_iommu_pd_alloc_bitmap);
1901         write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1902 }
1903
1904 static void free_pagetable(struct protection_domain *domain)
1905 {
1906         int i, j;
1907         u64 *p1, *p2, *p3;
1908
1909         p1 = domain->pt_root;
1910
1911         if (!p1)
1912                 return;
1913
1914         for (i = 0; i < 512; ++i) {
1915                 if (!IOMMU_PTE_PRESENT(p1[i]))
1916                         continue;
1917
1918                 p2 = IOMMU_PTE_PAGE(p1[i]);
1919                 for (j = 0; j < 512; ++j) {
1920                         if (!IOMMU_PTE_PRESENT(p2[j]))
1921                                 continue;
1922                         p3 = IOMMU_PTE_PAGE(p2[j]);
1923                         free_page((unsigned long)p3);
1924                 }
1925
1926                 free_page((unsigned long)p2);
1927         }
1928
1929         free_page((unsigned long)p1);
1930
1931         domain->pt_root = NULL;
1932 }
1933
1934 static void free_gcr3_tbl_level1(u64 *tbl)
1935 {
1936         u64 *ptr;
1937         int i;
1938
1939         for (i = 0; i < 512; ++i) {
1940                 if (!(tbl[i] & GCR3_VALID))
1941                         continue;
1942
1943                 ptr = __va(tbl[i] & PAGE_MASK);
1944
1945                 free_page((unsigned long)ptr);
1946         }
1947 }
1948
1949 static void free_gcr3_tbl_level2(u64 *tbl)
1950 {
1951         u64 *ptr;
1952         int i;
1953
1954         for (i = 0; i < 512; ++i) {
1955                 if (!(tbl[i] & GCR3_VALID))
1956                         continue;
1957
1958                 ptr = __va(tbl[i] & PAGE_MASK);
1959
1960                 free_gcr3_tbl_level1(ptr);
1961         }
1962 }
1963
1964 static void free_gcr3_table(struct protection_domain *domain)
1965 {
1966         if (domain->glx == 2)
1967                 free_gcr3_tbl_level2(domain->gcr3_tbl);
1968         else if (domain->glx == 1)
1969                 free_gcr3_tbl_level1(domain->gcr3_tbl);
1970         else if (domain->glx != 0)
1971                 BUG();
1972
1973         free_page((unsigned long)domain->gcr3_tbl);
1974 }
1975
1976 /*
1977  * Free a domain, only used if something went wrong in the
1978  * allocation path and we need to free an already allocated page table
1979  */
1980 static void dma_ops_domain_free(struct dma_ops_domain *dom)
1981 {
1982         int i;
1983
1984         if (!dom)
1985                 return;
1986
1987         del_domain_from_list(&dom->domain);
1988
1989         free_pagetable(&dom->domain);
1990
1991         for (i = 0; i < APERTURE_MAX_RANGES; ++i) {
1992                 if (!dom->aperture[i])
1993                         continue;
1994                 free_page((unsigned long)dom->aperture[i]->bitmap);
1995                 kfree(dom->aperture[i]);
1996         }
1997
1998         kfree(dom);
1999 }
2000
2001 /*
2002  * Allocates a new protection domain usable for the dma_ops functions.
2003  * It also initializes the page table and the address allocator data
2004  * structures required for the dma_ops interface
2005  */
2006 static struct dma_ops_domain *dma_ops_domain_alloc(void)
2007 {
2008         struct dma_ops_domain *dma_dom;
2009
2010         dma_dom = kzalloc(sizeof(struct dma_ops_domain), GFP_KERNEL);
2011         if (!dma_dom)
2012                 return NULL;
2013
2014         spin_lock_init(&dma_dom->domain.lock);
2015
2016         dma_dom->domain.id = domain_id_alloc();
2017         if (dma_dom->domain.id == 0)
2018                 goto free_dma_dom;
2019         INIT_LIST_HEAD(&dma_dom->domain.dev_list);
2020         dma_dom->domain.mode = PAGE_MODE_2_LEVEL;
2021         dma_dom->domain.pt_root = (void *)get_zeroed_page(GFP_KERNEL);
2022         dma_dom->domain.flags = PD_DMA_OPS_MASK;
2023         dma_dom->domain.priv = dma_dom;
2024         if (!dma_dom->domain.pt_root)
2025                 goto free_dma_dom;
2026
2027         dma_dom->need_flush = false;
2028         dma_dom->target_dev = 0xffff;
2029
2030         add_domain_to_list(&dma_dom->domain);
2031
2032         if (alloc_new_range(dma_dom, true, GFP_KERNEL))
2033                 goto free_dma_dom;
2034
2035         /*
2036          * mark the first page as allocated so we never return 0 as
2037          * a valid dma-address. So we can use 0 as error value
2038          */
2039         dma_dom->aperture[0]->bitmap[0] = 1;
2040         dma_dom->next_address = 0;
2041
2042
2043         return dma_dom;
2044
2045 free_dma_dom:
2046         dma_ops_domain_free(dma_dom);
2047
2048         return NULL;
2049 }
2050
2051 /*
2052  * little helper function to check whether a given protection domain is a
2053  * dma_ops domain
2054  */
2055 static bool dma_ops_domain(struct protection_domain *domain)
2056 {
2057         return domain->flags & PD_DMA_OPS_MASK;
2058 }
2059
2060 static void set_dte_entry(u16 devid, struct protection_domain *domain, bool ats)
2061 {
2062         u64 pte_root = 0;
2063         u64 flags = 0;
2064
2065         if (domain->mode != PAGE_MODE_NONE)
2066                 pte_root = virt_to_phys(domain->pt_root);
2067
2068         pte_root |= (domain->mode & DEV_ENTRY_MODE_MASK)
2069                     << DEV_ENTRY_MODE_SHIFT;
2070         pte_root |= IOMMU_PTE_IR | IOMMU_PTE_IW | IOMMU_PTE_P | IOMMU_PTE_TV;
2071
2072         flags = amd_iommu_dev_table[devid].data[1];
2073
2074         if (ats)
2075                 flags |= DTE_FLAG_IOTLB;
2076
2077         if (domain->flags & PD_IOMMUV2_MASK) {
2078                 u64 gcr3 = __pa(domain->gcr3_tbl);
2079                 u64 glx  = domain->glx;
2080                 u64 tmp;
2081
2082                 pte_root |= DTE_FLAG_GV;
2083                 pte_root |= (glx & DTE_GLX_MASK) << DTE_GLX_SHIFT;
2084
2085                 /* First mask out possible old values for GCR3 table */
2086                 tmp = DTE_GCR3_VAL_B(~0ULL) << DTE_GCR3_SHIFT_B;
2087                 flags    &= ~tmp;
2088
2089                 tmp = DTE_GCR3_VAL_C(~0ULL) << DTE_GCR3_SHIFT_C;
2090                 flags    &= ~tmp;
2091
2092                 /* Encode GCR3 table into DTE */
2093                 tmp = DTE_GCR3_VAL_A(gcr3) << DTE_GCR3_SHIFT_A;
2094                 pte_root |= tmp;
2095
2096                 tmp = DTE_GCR3_VAL_B(gcr3) << DTE_GCR3_SHIFT_B;
2097                 flags    |= tmp;
2098
2099                 tmp = DTE_GCR3_VAL_C(gcr3) << DTE_GCR3_SHIFT_C;
2100                 flags    |= tmp;
2101         }
2102
2103         flags &= ~(0xffffUL);
2104         flags |= domain->id;
2105
2106         amd_iommu_dev_table[devid].data[1]  = flags;
2107         amd_iommu_dev_table[devid].data[0]  = pte_root;
2108 }
2109
2110 static void clear_dte_entry(u16 devid)
2111 {
2112         /* remove entry from the device table seen by the hardware */
2113         amd_iommu_dev_table[devid].data[0] = IOMMU_PTE_P | IOMMU_PTE_TV;
2114         amd_iommu_dev_table[devid].data[1] = 0;
2115
2116         amd_iommu_apply_erratum_63(devid);
2117 }
2118
2119 static void do_attach(struct iommu_dev_data *dev_data,
2120                       struct protection_domain *domain)
2121 {
2122         struct amd_iommu *iommu;
2123         bool ats;
2124
2125         iommu = amd_iommu_rlookup_table[dev_data->devid];
2126         ats   = dev_data->ats.enabled;
2127
2128         /* Update data structures */
2129         dev_data->domain = domain;
2130         list_add(&dev_data->list, &domain->dev_list);
2131         set_dte_entry(dev_data->devid, domain, ats);
2132
2133         /* Do reference counting */
2134         domain->dev_iommu[iommu->index] += 1;
2135         domain->dev_cnt                 += 1;
2136
2137         /* Flush the DTE entry */
2138         device_flush_dte(dev_data);
2139 }
2140
2141 static void do_detach(struct iommu_dev_data *dev_data)
2142 {
2143         struct amd_iommu *iommu;
2144
2145         iommu = amd_iommu_rlookup_table[dev_data->devid];
2146
2147         /* decrease reference counters */
2148         dev_data->domain->dev_iommu[iommu->index] -= 1;
2149         dev_data->domain->dev_cnt                 -= 1;
2150
2151         /* Update data structures */
2152         dev_data->domain = NULL;
2153         list_del(&dev_data->list);
2154         clear_dte_entry(dev_data->devid);
2155
2156         /* Flush the DTE entry */
2157         device_flush_dte(dev_data);
2158 }
2159
2160 /*
2161  * If a device is not yet associated with a domain, this function does
2162  * assigns it visible for the hardware
2163  */
2164 static int __attach_device(struct iommu_dev_data *dev_data,
2165                            struct protection_domain *domain)
2166 {
2167         int ret;
2168
2169         /* lock domain */
2170         spin_lock(&domain->lock);
2171
2172         if (dev_data->alias_data != NULL) {
2173                 struct iommu_dev_data *alias_data = dev_data->alias_data;
2174
2175                 /* Some sanity checks */
2176                 ret = -EBUSY;
2177                 if (alias_data->domain != NULL &&
2178                                 alias_data->domain != domain)
2179                         goto out_unlock;
2180
2181                 if (dev_data->domain != NULL &&
2182                                 dev_data->domain != domain)
2183                         goto out_unlock;
2184
2185                 /* Do real assignment */
2186                 if (alias_data->domain == NULL)
2187                         do_attach(alias_data, domain);
2188
2189                 atomic_inc(&alias_data->bind);
2190         }
2191
2192         if (dev_data->domain == NULL)
2193                 do_attach(dev_data, domain);
2194
2195         atomic_inc(&dev_data->bind);
2196
2197         ret = 0;
2198
2199 out_unlock:
2200
2201         /* ready */
2202         spin_unlock(&domain->lock);
2203
2204         return ret;
2205 }
2206
2207
2208 static void pdev_iommuv2_disable(struct pci_dev *pdev)
2209 {
2210         pci_disable_ats(pdev);
2211         pci_disable_pri(pdev);
2212         pci_disable_pasid(pdev);
2213 }
2214
2215 /* FIXME: Change generic reset-function to do the same */
2216 static int pri_reset_while_enabled(struct pci_dev *pdev)
2217 {
2218         u16 control;
2219         int pos;
2220
2221         pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PRI);
2222         if (!pos)
2223                 return -EINVAL;
2224
2225         pci_read_config_word(pdev, pos + PCI_PRI_CTRL, &control);
2226         control |= PCI_PRI_CTRL_RESET;
2227         pci_write_config_word(pdev, pos + PCI_PRI_CTRL, control);
2228
2229         return 0;
2230 }
2231
2232 static int pdev_iommuv2_enable(struct pci_dev *pdev)
2233 {
2234         bool reset_enable;
2235         int reqs, ret;
2236
2237         /* FIXME: Hardcode number of outstanding requests for now */
2238         reqs = 32;
2239         if (pdev_pri_erratum(pdev, AMD_PRI_DEV_ERRATUM_LIMIT_REQ_ONE))
2240                 reqs = 1;
2241         reset_enable = pdev_pri_erratum(pdev, AMD_PRI_DEV_ERRATUM_ENABLE_RESET);
2242
2243         /* Only allow access to user-accessible pages */
2244         ret = pci_enable_pasid(pdev, 0);
2245         if (ret)
2246                 goto out_err;
2247
2248         /* First reset the PRI state of the device */
2249         ret = pci_reset_pri(pdev);
2250         if (ret)
2251                 goto out_err;
2252
2253         /* Enable PRI */
2254         ret = pci_enable_pri(pdev, reqs);
2255         if (ret)
2256                 goto out_err;
2257
2258         if (reset_enable) {
2259                 ret = pri_reset_while_enabled(pdev);
2260                 if (ret)
2261                         goto out_err;
2262         }
2263
2264         ret = pci_enable_ats(pdev, PAGE_SHIFT);
2265         if (ret)
2266                 goto out_err;
2267
2268         return 0;
2269
2270 out_err:
2271         pci_disable_pri(pdev);
2272         pci_disable_pasid(pdev);
2273
2274         return ret;
2275 }
2276
2277 /* FIXME: Move this to PCI code */
2278 #define PCI_PRI_TLP_OFF         (1 << 15)
2279
2280 static bool pci_pri_tlp_required(struct pci_dev *pdev)
2281 {
2282         u16 status;
2283         int pos;
2284
2285         pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PRI);
2286         if (!pos)
2287                 return false;
2288
2289         pci_read_config_word(pdev, pos + PCI_PRI_STATUS, &status);
2290
2291         return (status & PCI_PRI_TLP_OFF) ? true : false;
2292 }
2293
2294 /*
2295  * If a device is not yet associated with a domain, this function
2296  * assigns it visible for the hardware
2297  */
2298 static int attach_device(struct device *dev,
2299                          struct protection_domain *domain)
2300 {
2301         struct pci_dev *pdev = to_pci_dev(dev);
2302         struct iommu_dev_data *dev_data;
2303         unsigned long flags;
2304         int ret;
2305
2306         dev_data = get_dev_data(dev);
2307
2308         if (domain->flags & PD_IOMMUV2_MASK) {
2309                 if (!dev_data->iommu_v2 || !dev_data->passthrough)
2310                         return -EINVAL;
2311
2312                 if (pdev_iommuv2_enable(pdev) != 0)
2313                         return -EINVAL;
2314
2315                 dev_data->ats.enabled = true;
2316                 dev_data->ats.qdep    = pci_ats_queue_depth(pdev);
2317                 dev_data->pri_tlp     = pci_pri_tlp_required(pdev);
2318         } else if (amd_iommu_iotlb_sup &&
2319                    pci_enable_ats(pdev, PAGE_SHIFT) == 0) {
2320                 dev_data->ats.enabled = true;
2321                 dev_data->ats.qdep    = pci_ats_queue_depth(pdev);
2322         }
2323
2324         write_lock_irqsave(&amd_iommu_devtable_lock, flags);
2325         ret = __attach_device(dev_data, domain);
2326         write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2327
2328         /*
2329          * We might boot into a crash-kernel here. The crashed kernel
2330          * left the caches in the IOMMU dirty. So we have to flush
2331          * here to evict all dirty stuff.
2332          */
2333         domain_flush_tlb_pde(domain);
2334
2335         return ret;
2336 }
2337
2338 /*
2339  * Removes a device from a protection domain (unlocked)
2340  */
2341 static void __detach_device(struct iommu_dev_data *dev_data)
2342 {
2343         struct protection_domain *domain;
2344         unsigned long flags;
2345
2346         BUG_ON(!dev_data->domain);
2347
2348         domain = dev_data->domain;
2349
2350         spin_lock_irqsave(&domain->lock, flags);
2351
2352         if (dev_data->alias_data != NULL) {
2353                 struct iommu_dev_data *alias_data = dev_data->alias_data;
2354
2355                 if (atomic_dec_and_test(&alias_data->bind))
2356                         do_detach(alias_data);
2357         }
2358
2359         if (atomic_dec_and_test(&dev_data->bind))
2360                 do_detach(dev_data);
2361
2362         spin_unlock_irqrestore(&domain->lock, flags);
2363
2364         /*
2365          * If we run in passthrough mode the device must be assigned to the
2366          * passthrough domain if it is detached from any other domain.
2367          * Make sure we can deassign from the pt_domain itself.
2368          */
2369         if (dev_data->passthrough &&
2370             (dev_data->domain == NULL && domain != pt_domain))
2371                 __attach_device(dev_data, pt_domain);
2372 }
2373
2374 /*
2375  * Removes a device from a protection domain (with devtable_lock held)
2376  */
2377 static void detach_device(struct device *dev)
2378 {
2379         struct protection_domain *domain;
2380         struct iommu_dev_data *dev_data;
2381         unsigned long flags;
2382
2383         dev_data = get_dev_data(dev);
2384         domain   = dev_data->domain;
2385
2386         /* lock device table */
2387         write_lock_irqsave(&amd_iommu_devtable_lock, flags);
2388         __detach_device(dev_data);
2389         write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2390
2391         if (domain->flags & PD_IOMMUV2_MASK)
2392                 pdev_iommuv2_disable(to_pci_dev(dev));
2393         else if (dev_data->ats.enabled)
2394                 pci_disable_ats(to_pci_dev(dev));
2395
2396         dev_data->ats.enabled = false;
2397 }
2398
2399 /*
2400  * Find out the protection domain structure for a given PCI device. This
2401  * will give us the pointer to the page table root for example.
2402  */
2403 static struct protection_domain *domain_for_device(struct device *dev)
2404 {
2405         struct iommu_dev_data *dev_data;
2406         struct protection_domain *dom = NULL;
2407         unsigned long flags;
2408
2409         dev_data   = get_dev_data(dev);
2410
2411         if (dev_data->domain)
2412                 return dev_data->domain;
2413
2414         if (dev_data->alias_data != NULL) {
2415                 struct iommu_dev_data *alias_data = dev_data->alias_data;
2416
2417                 read_lock_irqsave(&amd_iommu_devtable_lock, flags);
2418                 if (alias_data->domain != NULL) {
2419                         __attach_device(dev_data, alias_data->domain);
2420                         dom = alias_data->domain;
2421                 }
2422                 read_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2423         }
2424
2425         return dom;
2426 }
2427
2428 static int device_change_notifier(struct notifier_block *nb,
2429                                   unsigned long action, void *data)
2430 {
2431         struct dma_ops_domain *dma_domain;
2432         struct protection_domain *domain;
2433         struct iommu_dev_data *dev_data;
2434         struct device *dev = data;
2435         struct amd_iommu *iommu;
2436         unsigned long flags;
2437         u16 devid;
2438
2439         if (!check_device(dev))
2440                 return 0;
2441
2442         devid    = get_device_id(dev);
2443         iommu    = amd_iommu_rlookup_table[devid];
2444         dev_data = get_dev_data(dev);
2445
2446         switch (action) {
2447         case BUS_NOTIFY_UNBOUND_DRIVER:
2448
2449                 domain = domain_for_device(dev);
2450
2451                 if (!domain)
2452                         goto out;
2453                 if (dev_data->passthrough)
2454                         break;
2455                 detach_device(dev);
2456                 break;
2457         case BUS_NOTIFY_ADD_DEVICE:
2458
2459                 iommu_init_device(dev);
2460
2461                 /*
2462                  * dev_data is still NULL and
2463                  * got initialized in iommu_init_device
2464                  */
2465                 dev_data = get_dev_data(dev);
2466
2467                 if (iommu_pass_through || dev_data->iommu_v2) {
2468                         dev_data->passthrough = true;
2469                         attach_device(dev, pt_domain);
2470                         break;
2471                 }
2472
2473                 domain = domain_for_device(dev);
2474
2475                 /* allocate a protection domain if a device is added */
2476                 dma_domain = find_protection_domain(devid);
2477                 if (dma_domain)
2478                         goto out;
2479                 dma_domain = dma_ops_domain_alloc();
2480                 if (!dma_domain)
2481                         goto out;
2482                 dma_domain->target_dev = devid;
2483
2484                 spin_lock_irqsave(&iommu_pd_list_lock, flags);
2485                 list_add_tail(&dma_domain->list, &iommu_pd_list);
2486                 spin_unlock_irqrestore(&iommu_pd_list_lock, flags);
2487
2488                 dev_data = get_dev_data(dev);
2489
2490                 dev->archdata.dma_ops = &amd_iommu_dma_ops;
2491
2492                 break;
2493         case BUS_NOTIFY_DEL_DEVICE:
2494
2495                 iommu_uninit_device(dev);
2496
2497         default:
2498                 goto out;
2499         }
2500
2501         iommu_completion_wait(iommu);
2502
2503 out:
2504         return 0;
2505 }
2506
2507 static struct notifier_block device_nb = {
2508         .notifier_call = device_change_notifier,
2509 };
2510
2511 void amd_iommu_init_notifier(void)
2512 {
2513         bus_register_notifier(&pci_bus_type, &device_nb);
2514 }
2515
2516 /*****************************************************************************
2517  *
2518  * The next functions belong to the dma_ops mapping/unmapping code.
2519  *
2520  *****************************************************************************/
2521
2522 /*
2523  * In the dma_ops path we only have the struct device. This function
2524  * finds the corresponding IOMMU, the protection domain and the
2525  * requestor id for a given device.
2526  * If the device is not yet associated with a domain this is also done
2527  * in this function.
2528  */
2529 static struct protection_domain *get_domain(struct device *dev)
2530 {
2531         struct protection_domain *domain;
2532         struct dma_ops_domain *dma_dom;
2533         u16 devid = get_device_id(dev);
2534
2535         if (!check_device(dev))
2536                 return ERR_PTR(-EINVAL);
2537
2538         domain = domain_for_device(dev);
2539         if (domain != NULL && !dma_ops_domain(domain))
2540                 return ERR_PTR(-EBUSY);
2541
2542         if (domain != NULL)
2543                 return domain;
2544
2545         /* Device not bound yet - bind it */
2546         dma_dom = find_protection_domain(devid);
2547         if (!dma_dom)
2548                 dma_dom = amd_iommu_rlookup_table[devid]->default_dom;
2549         attach_device(dev, &dma_dom->domain);
2550         DUMP_printk("Using protection domain %d for device %s\n",
2551                     dma_dom->domain.id, dev_name(dev));
2552
2553         return &dma_dom->domain;
2554 }
2555
2556 static void update_device_table(struct protection_domain *domain)
2557 {
2558         struct iommu_dev_data *dev_data;
2559
2560         list_for_each_entry(dev_data, &domain->dev_list, list)
2561                 set_dte_entry(dev_data->devid, domain, dev_data->ats.enabled);
2562 }
2563
2564 static void update_domain(struct protection_domain *domain)
2565 {
2566         if (!domain->updated)
2567                 return;
2568
2569         update_device_table(domain);
2570
2571         domain_flush_devices(domain);
2572         domain_flush_tlb_pde(domain);
2573
2574         domain->updated = false;
2575 }
2576
2577 /*
2578  * This function fetches the PTE for a given address in the aperture
2579  */
2580 static u64* dma_ops_get_pte(struct dma_ops_domain *dom,
2581                             unsigned long address)
2582 {
2583         struct aperture_range *aperture;
2584         u64 *pte, *pte_page;
2585
2586         aperture = dom->aperture[APERTURE_RANGE_INDEX(address)];
2587         if (!aperture)
2588                 return NULL;
2589
2590         pte = aperture->pte_pages[APERTURE_PAGE_INDEX(address)];
2591         if (!pte) {
2592                 pte = alloc_pte(&dom->domain, address, PAGE_SIZE, &pte_page,
2593                                 GFP_ATOMIC);
2594                 aperture->pte_pages[APERTURE_PAGE_INDEX(address)] = pte_page;
2595         } else
2596                 pte += PM_LEVEL_INDEX(0, address);
2597
2598         update_domain(&dom->domain);
2599
2600         return pte;
2601 }
2602
2603 /*
2604  * This is the generic map function. It maps one 4kb page at paddr to
2605  * the given address in the DMA address space for the domain.
2606  */
2607 static dma_addr_t dma_ops_domain_map(struct dma_ops_domain *dom,
2608                                      unsigned long address,
2609                                      phys_addr_t paddr,
2610                                      int direction)
2611 {
2612         u64 *pte, __pte;
2613
2614         WARN_ON(address > dom->aperture_size);
2615
2616         paddr &= PAGE_MASK;
2617
2618         pte  = dma_ops_get_pte(dom, address);
2619         if (!pte)
2620                 return DMA_ERROR_CODE;
2621
2622         __pte = paddr | IOMMU_PTE_P | IOMMU_PTE_FC;
2623
2624         if (direction == DMA_TO_DEVICE)
2625                 __pte |= IOMMU_PTE_IR;
2626         else if (direction == DMA_FROM_DEVICE)
2627                 __pte |= IOMMU_PTE_IW;
2628         else if (direction == DMA_BIDIRECTIONAL)
2629                 __pte |= IOMMU_PTE_IR | IOMMU_PTE_IW;
2630
2631         WARN_ON(*pte);
2632
2633         *pte = __pte;
2634
2635         return (dma_addr_t)address;
2636 }
2637
2638 /*
2639  * The generic unmapping function for on page in the DMA address space.
2640  */
2641 static void dma_ops_domain_unmap(struct dma_ops_domain *dom,
2642                                  unsigned long address)
2643 {
2644         struct aperture_range *aperture;
2645         u64 *pte;
2646
2647         if (address >= dom->aperture_size)
2648                 return;
2649
2650         aperture = dom->aperture[APERTURE_RANGE_INDEX(address)];
2651         if (!aperture)
2652                 return;
2653
2654         pte  = aperture->pte_pages[APERTURE_PAGE_INDEX(address)];
2655         if (!pte)
2656                 return;
2657
2658         pte += PM_LEVEL_INDEX(0, address);
2659
2660         WARN_ON(!*pte);
2661
2662         *pte = 0ULL;
2663 }
2664
2665 /*
2666  * This function contains common code for mapping of a physically
2667  * contiguous memory region into DMA address space. It is used by all
2668  * mapping functions provided with this IOMMU driver.
2669  * Must be called with the domain lock held.
2670  */
2671 static dma_addr_t __map_single(struct device *dev,
2672                                struct dma_ops_domain *dma_dom,
2673                                phys_addr_t paddr,
2674                                size_t size,
2675                                int dir,
2676                                bool align,
2677                                u64 dma_mask)
2678 {
2679         dma_addr_t offset = paddr & ~PAGE_MASK;
2680         dma_addr_t address, start, ret;
2681         unsigned int pages;
2682         unsigned long align_mask = 0;
2683         int i;
2684
2685         pages = iommu_num_pages(paddr, size, PAGE_SIZE);
2686         paddr &= PAGE_MASK;
2687
2688         INC_STATS_COUNTER(total_map_requests);
2689
2690         if (pages > 1)
2691                 INC_STATS_COUNTER(cross_page);
2692
2693         if (align)
2694                 align_mask = (1UL << get_order(size)) - 1;
2695
2696 retry:
2697         address = dma_ops_alloc_addresses(dev, dma_dom, pages, align_mask,
2698                                           dma_mask);
2699         if (unlikely(address == DMA_ERROR_CODE)) {
2700                 /*
2701                  * setting next_address here will let the address
2702                  * allocator only scan the new allocated range in the
2703                  * first run. This is a small optimization.
2704                  */
2705                 dma_dom->next_address = dma_dom->aperture_size;
2706
2707                 if (alloc_new_range(dma_dom, false, GFP_ATOMIC))
2708                         goto out;
2709
2710                 /*
2711                  * aperture was successfully enlarged by 128 MB, try
2712                  * allocation again
2713                  */
2714                 goto retry;
2715         }
2716
2717         start = address;
2718         for (i = 0; i < pages; ++i) {
2719                 ret = dma_ops_domain_map(dma_dom, start, paddr, dir);
2720                 if (ret == DMA_ERROR_CODE)
2721                         goto out_unmap;
2722
2723                 paddr += PAGE_SIZE;
2724                 start += PAGE_SIZE;
2725         }
2726         address += offset;
2727
2728         ADD_STATS_COUNTER(alloced_io_mem, size);
2729
2730         if (unlikely(dma_dom->need_flush && !amd_iommu_unmap_flush)) {
2731                 domain_flush_tlb(&dma_dom->domain);
2732                 dma_dom->need_flush = false;
2733         } else if (unlikely(amd_iommu_np_cache))
2734                 domain_flush_pages(&dma_dom->domain, address, size);
2735
2736 out:
2737         return address;
2738
2739 out_unmap:
2740
2741         for (--i; i >= 0; --i) {
2742                 start -= PAGE_SIZE;
2743                 dma_ops_domain_unmap(dma_dom, start);
2744         }
2745
2746         dma_ops_free_addresses(dma_dom, address, pages);
2747
2748         return DMA_ERROR_CODE;
2749 }
2750
2751 /*
2752  * Does the reverse of the __map_single function. Must be called with
2753  * the domain lock held too
2754  */
2755 static void __unmap_single(struct dma_ops_domain *dma_dom,
2756                            dma_addr_t dma_addr,
2757                            size_t size,
2758                            int dir)
2759 {
2760         dma_addr_t flush_addr;
2761         dma_addr_t i, start;
2762         unsigned int pages;
2763
2764         if ((dma_addr == DMA_ERROR_CODE) ||
2765             (dma_addr + size > dma_dom->aperture_size))
2766                 return;
2767
2768         flush_addr = dma_addr;
2769         pages = iommu_num_pages(dma_addr, size, PAGE_SIZE);
2770         dma_addr &= PAGE_MASK;
2771         start = dma_addr;
2772
2773         for (i = 0; i < pages; ++i) {
2774                 dma_ops_domain_unmap(dma_dom, start);
2775                 start += PAGE_SIZE;
2776         }
2777
2778         SUB_STATS_COUNTER(alloced_io_mem, size);
2779
2780         dma_ops_free_addresses(dma_dom, dma_addr, pages);
2781
2782         if (amd_iommu_unmap_flush || dma_dom->need_flush) {
2783                 domain_flush_pages(&dma_dom->domain, flush_addr, size);
2784                 dma_dom->need_flush = false;
2785         }
2786 }
2787
2788 /*
2789  * The exported map_single function for dma_ops.
2790  */
2791 static dma_addr_t map_page(struct device *dev, struct page *page,
2792                            unsigned long offset, size_t size,
2793                            enum dma_data_direction dir,
2794                            struct dma_attrs *attrs)
2795 {
2796         unsigned long flags;
2797         struct protection_domain *domain;
2798         dma_addr_t addr;
2799         u64 dma_mask;
2800         phys_addr_t paddr = page_to_phys(page) + offset;
2801
2802         INC_STATS_COUNTER(cnt_map_single);
2803
2804         domain = get_domain(dev);
2805         if (PTR_ERR(domain) == -EINVAL)
2806                 return (dma_addr_t)paddr;
2807         else if (IS_ERR(domain))
2808                 return DMA_ERROR_CODE;
2809
2810         dma_mask = *dev->dma_mask;
2811
2812         spin_lock_irqsave(&domain->lock, flags);
2813
2814         addr = __map_single(dev, domain->priv, paddr, size, dir, false,
2815                             dma_mask);
2816         if (addr == DMA_ERROR_CODE)
2817                 goto out;
2818
2819         domain_flush_complete(domain);
2820
2821 out:
2822         spin_unlock_irqrestore(&domain->lock, flags);
2823
2824         return addr;
2825 }
2826
2827 /*
2828  * The exported unmap_single function for dma_ops.
2829  */
2830 static void unmap_page(struct device *dev, dma_addr_t dma_addr, size_t size,
2831                        enum dma_data_direction dir, struct dma_attrs *attrs)
2832 {
2833         unsigned long flags;
2834         struct protection_domain *domain;
2835
2836         INC_STATS_COUNTER(cnt_unmap_single);
2837
2838         domain = get_domain(dev);
2839         if (IS_ERR(domain))
2840                 return;
2841
2842         spin_lock_irqsave(&domain->lock, flags);
2843
2844         __unmap_single(domain->priv, dma_addr, size, dir);
2845
2846         domain_flush_complete(domain);
2847
2848         spin_unlock_irqrestore(&domain->lock, flags);
2849 }
2850
2851 /*
2852  * This is a special map_sg function which is used if we should map a
2853  * device which is not handled by an AMD IOMMU in the system.
2854  */
2855 static int map_sg_no_iommu(struct device *dev, struct scatterlist *sglist,
2856                            int nelems, int dir)
2857 {
2858         struct scatterlist *s;
2859         int i;
2860
2861         for_each_sg(sglist, s, nelems, i) {
2862                 s->dma_address = (dma_addr_t)sg_phys(s);
2863                 s->dma_length  = s->length;
2864         }
2865
2866         return nelems;
2867 }
2868
2869 /*
2870  * The exported map_sg function for dma_ops (handles scatter-gather
2871  * lists).
2872  */
2873 static int map_sg(struct device *dev, struct scatterlist *sglist,
2874                   int nelems, enum dma_data_direction dir,
2875                   struct dma_attrs *attrs)
2876 {
2877         unsigned long flags;
2878         struct protection_domain *domain;
2879         int i;
2880         struct scatterlist *s;
2881         phys_addr_t paddr;
2882         int mapped_elems = 0;
2883         u64 dma_mask;
2884
2885         INC_STATS_COUNTER(cnt_map_sg);
2886
2887         domain = get_domain(dev);
2888         if (PTR_ERR(domain) == -EINVAL)
2889                 return map_sg_no_iommu(dev, sglist, nelems, dir);
2890         else if (IS_ERR(domain))
2891                 return 0;
2892
2893         dma_mask = *dev->dma_mask;
2894
2895         spin_lock_irqsave(&domain->lock, flags);
2896
2897         for_each_sg(sglist, s, nelems, i) {
2898                 paddr = sg_phys(s);
2899
2900                 s->dma_address = __map_single(dev, domain->priv,
2901                                               paddr, s->length, dir, false,
2902                                               dma_mask);
2903
2904                 if (s->dma_address) {
2905                         s->dma_length = s->length;
2906                         mapped_elems++;
2907                 } else
2908                         goto unmap;
2909         }
2910
2911         domain_flush_complete(domain);
2912
2913 out:
2914         spin_unlock_irqrestore(&domain->lock, flags);
2915
2916         return mapped_elems;
2917 unmap:
2918         for_each_sg(sglist, s, mapped_elems, i) {
2919                 if (s->dma_address)
2920                         __unmap_single(domain->priv, s->dma_address,
2921                                        s->dma_length, dir);
2922                 s->dma_address = s->dma_length = 0;
2923         }
2924
2925         mapped_elems = 0;
2926
2927         goto out;
2928 }
2929
2930 /*
2931  * The exported map_sg function for dma_ops (handles scatter-gather
2932  * lists).
2933  */
2934 static void unmap_sg(struct device *dev, struct scatterlist *sglist,
2935                      int nelems, enum dma_data_direction dir,
2936                      struct dma_attrs *attrs)
2937 {
2938         unsigned long flags;
2939         struct protection_domain *domain;
2940         struct scatterlist *s;
2941         int i;
2942
2943         INC_STATS_COUNTER(cnt_unmap_sg);
2944
2945         domain = get_domain(dev);
2946         if (IS_ERR(domain))
2947                 return;
2948
2949         spin_lock_irqsave(&domain->lock, flags);
2950
2951         for_each_sg(sglist, s, nelems, i) {
2952                 __unmap_single(domain->priv, s->dma_address,
2953                                s->dma_length, dir);
2954                 s->dma_address = s->dma_length = 0;
2955         }
2956
2957         domain_flush_complete(domain);
2958
2959         spin_unlock_irqrestore(&domain->lock, flags);
2960 }
2961
2962 /*
2963  * The exported alloc_coherent function for dma_ops.
2964  */
2965 static void *alloc_coherent(struct device *dev, size_t size,
2966                             dma_addr_t *dma_addr, gfp_t flag,
2967                             struct dma_attrs *attrs)
2968 {
2969         unsigned long flags;
2970         void *virt_addr;
2971         struct protection_domain *domain;
2972         phys_addr_t paddr;
2973         u64 dma_mask = dev->coherent_dma_mask;
2974
2975         INC_STATS_COUNTER(cnt_alloc_coherent);
2976
2977         domain = get_domain(dev);
2978         if (PTR_ERR(domain) == -EINVAL) {
2979                 virt_addr = (void *)__get_free_pages(flag, get_order(size));
2980                 *dma_addr = __pa(virt_addr);
2981                 return virt_addr;
2982         } else if (IS_ERR(domain))
2983                 return NULL;
2984
2985         dma_mask  = dev->coherent_dma_mask;
2986         flag     &= ~(__GFP_DMA | __GFP_HIGHMEM | __GFP_DMA32);
2987         flag     |= __GFP_ZERO;
2988
2989         virt_addr = (void *)__get_free_pages(flag, get_order(size));
2990         if (!virt_addr)
2991                 return NULL;
2992
2993         paddr = virt_to_phys(virt_addr);
2994
2995         if (!dma_mask)
2996                 dma_mask = *dev->dma_mask;
2997
2998         spin_lock_irqsave(&domain->lock, flags);
2999
3000         *dma_addr = __map_single(dev, domain->priv, paddr,
3001                                  size, DMA_BIDIRECTIONAL, true, dma_mask);
3002
3003         if (*dma_addr == DMA_ERROR_CODE) {
3004                 spin_unlock_irqrestore(&domain->lock, flags);
3005                 goto out_free;
3006         }
3007
3008         domain_flush_complete(domain);
3009
3010         spin_unlock_irqrestore(&domain->lock, flags);
3011
3012         return virt_addr;
3013
3014 out_free:
3015
3016         free_pages((unsigned long)virt_addr, get_order(size));
3017
3018         return NULL;
3019 }
3020
3021 /*
3022  * The exported free_coherent function for dma_ops.
3023  */
3024 static void free_coherent(struct device *dev, size_t size,
3025                           void *virt_addr, dma_addr_t dma_addr,
3026                           struct dma_attrs *attrs)
3027 {
3028         unsigned long flags;
3029         struct protection_domain *domain;
3030
3031         INC_STATS_COUNTER(cnt_free_coherent);
3032
3033         domain = get_domain(dev);
3034         if (IS_ERR(domain))
3035                 goto free_mem;
3036
3037         spin_lock_irqsave(&domain->lock, flags);
3038
3039         __unmap_single(domain->priv, dma_addr, size, DMA_BIDIRECTIONAL);
3040
3041         domain_flush_complete(domain);
3042
3043         spin_unlock_irqrestore(&domain->lock, flags);
3044
3045 free_mem:
3046         free_pages((unsigned long)virt_addr, get_order(size));
3047 }
3048
3049 /*
3050  * This function is called by the DMA layer to find out if we can handle a
3051  * particular device. It is part of the dma_ops.
3052  */
3053 static int amd_iommu_dma_supported(struct device *dev, u64 mask)
3054 {
3055         return check_device(dev);
3056 }
3057
3058 /*
3059  * The function for pre-allocating protection domains.
3060  *
3061  * If the driver core informs the DMA layer if a driver grabs a device
3062  * we don't need to preallocate the protection domains anymore.
3063  * For now we have to.
3064  */
3065 static void __init prealloc_protection_domains(void)
3066 {
3067         struct iommu_dev_data *dev_data;
3068         struct dma_ops_domain *dma_dom;
3069         struct pci_dev *dev = NULL;
3070         u16 devid;
3071
3072         for_each_pci_dev(dev) {
3073
3074                 /* Do we handle this device? */
3075                 if (!check_device(&dev->dev))
3076                         continue;
3077
3078                 dev_data = get_dev_data(&dev->dev);
3079                 if (!amd_iommu_force_isolation && dev_data->iommu_v2) {
3080                         /* Make sure passthrough domain is allocated */
3081                         alloc_passthrough_domain();
3082                         dev_data->passthrough = true;
3083                         attach_device(&dev->dev, pt_domain);
3084                         pr_info("AMD-Vi: Using passthrough domain for device %s\n",
3085                                 dev_name(&dev->dev));
3086                 }
3087
3088                 /* Is there already any domain for it? */
3089                 if (domain_for_device(&dev->dev))
3090                         continue;
3091
3092                 devid = get_device_id(&dev->dev);
3093
3094                 dma_dom = dma_ops_domain_alloc();
3095                 if (!dma_dom)
3096                         continue;
3097                 init_unity_mappings_for_device(dma_dom, devid);
3098                 dma_dom->target_dev = devid;
3099
3100                 attach_device(&dev->dev, &dma_dom->domain);
3101
3102                 list_add_tail(&dma_dom->list, &iommu_pd_list);
3103         }
3104 }
3105
3106 static struct dma_map_ops amd_iommu_dma_ops = {
3107         .alloc = alloc_coherent,
3108         .free = free_coherent,
3109         .map_page = map_page,
3110         .unmap_page = unmap_page,
3111         .map_sg = map_sg,
3112         .unmap_sg = unmap_sg,
3113         .dma_supported = amd_iommu_dma_supported,
3114 };
3115
3116 static unsigned device_dma_ops_init(void)
3117 {
3118         struct iommu_dev_data *dev_data;
3119         struct pci_dev *pdev = NULL;
3120         unsigned unhandled = 0;
3121
3122         for_each_pci_dev(pdev) {
3123                 if (!check_device(&pdev->dev)) {
3124
3125                         iommu_ignore_device(&pdev->dev);
3126
3127                         unhandled += 1;
3128                         continue;
3129                 }
3130
3131                 dev_data = get_dev_data(&pdev->dev);
3132
3133                 if (!dev_data->passthrough)
3134                         pdev->dev.archdata.dma_ops = &amd_iommu_dma_ops;
3135                 else
3136                         pdev->dev.archdata.dma_ops = &nommu_dma_ops;
3137         }
3138
3139         return unhandled;
3140 }
3141
3142 /*
3143  * The function which clues the AMD IOMMU driver into dma_ops.
3144  */
3145
3146 void __init amd_iommu_init_api(void)
3147 {
3148         bus_set_iommu(&pci_bus_type, &amd_iommu_ops);
3149 }
3150
3151 int __init amd_iommu_init_dma_ops(void)
3152 {
3153         struct amd_iommu *iommu;
3154         int ret, unhandled;
3155
3156         /*
3157          * first allocate a default protection domain for every IOMMU we
3158          * found in the system. Devices not assigned to any other
3159          * protection domain will be assigned to the default one.
3160          */
3161         for_each_iommu(iommu) {
3162                 iommu->default_dom = dma_ops_domain_alloc();
3163                 if (iommu->default_dom == NULL)
3164                         return -ENOMEM;
3165                 iommu->default_dom->domain.flags |= PD_DEFAULT_MASK;
3166                 ret = iommu_init_unity_mappings(iommu);
3167                 if (ret)
3168                         goto free_domains;
3169         }
3170
3171         /*
3172          * Pre-allocate the protection domains for each device.
3173          */
3174         prealloc_protection_domains();
3175
3176         iommu_detected = 1;
3177         swiotlb = 0;
3178
3179         /* Make the driver finally visible to the drivers */
3180         unhandled = device_dma_ops_init();
3181         if (unhandled && max_pfn > MAX_DMA32_PFN) {
3182                 /* There are unhandled devices - initialize swiotlb for them */
3183                 swiotlb = 1;
3184         }
3185
3186         amd_iommu_stats_init();
3187
3188         if (amd_iommu_unmap_flush)
3189                 pr_info("AMD-Vi: IO/TLB flush on unmap enabled\n");
3190         else
3191                 pr_info("AMD-Vi: Lazy IO/TLB flushing enabled\n");
3192
3193         return 0;
3194
3195 free_domains:
3196
3197         for_each_iommu(iommu) {
3198                 if (iommu->default_dom)
3199                         dma_ops_domain_free(iommu->default_dom);
3200         }
3201
3202         return ret;
3203 }
3204
3205 /*****************************************************************************
3206  *
3207  * The following functions belong to the exported interface of AMD IOMMU
3208  *
3209  * This interface allows access to lower level functions of the IOMMU
3210  * like protection domain handling and assignement of devices to domains
3211  * which is not possible with the dma_ops interface.
3212  *
3213  *****************************************************************************/
3214
3215 static void cleanup_domain(struct protection_domain *domain)
3216 {
3217         struct iommu_dev_data *dev_data, *next;
3218         unsigned long flags;
3219
3220         write_lock_irqsave(&amd_iommu_devtable_lock, flags);
3221
3222         list_for_each_entry_safe(dev_data, next, &domain->dev_list, list) {
3223                 __detach_device(dev_data);
3224                 atomic_set(&dev_data->bind, 0);
3225         }
3226
3227         write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
3228 }
3229
3230 static void protection_domain_free(struct protection_domain *domain)
3231 {
3232         if (!domain)
3233                 return;
3234
3235         del_domain_from_list(domain);
3236
3237         if (domain->id)
3238                 domain_id_free(domain->id);
3239
3240         kfree(domain);
3241 }
3242
3243 static struct protection_domain *protection_domain_alloc(void)
3244 {
3245         struct protection_domain *domain;
3246
3247         domain = kzalloc(sizeof(*domain), GFP_KERNEL);
3248         if (!domain)
3249                 return NULL;
3250
3251         spin_lock_init(&domain->lock);
3252         mutex_init(&domain->api_lock);
3253         domain->id = domain_id_alloc();
3254         if (!domain->id)
3255                 goto out_err;
3256         INIT_LIST_HEAD(&domain->dev_list);
3257
3258         add_domain_to_list(domain);
3259
3260         return domain;
3261
3262 out_err:
3263         kfree(domain);
3264
3265         return NULL;
3266 }
3267
3268 static int __init alloc_passthrough_domain(void)
3269 {
3270         if (pt_domain != NULL)
3271                 return 0;
3272
3273         /* allocate passthrough domain */
3274         pt_domain = protection_domain_alloc();
3275         if (!pt_domain)
3276                 return -ENOMEM;
3277
3278         pt_domain->mode = PAGE_MODE_NONE;
3279
3280         return 0;
3281 }
3282 static int amd_iommu_domain_init(struct iommu_domain *dom)
3283 {
3284         struct protection_domain *domain;
3285
3286         domain = protection_domain_alloc();
3287         if (!domain)
3288                 goto out_free;
3289
3290         domain->mode    = PAGE_MODE_3_LEVEL;
3291         domain->pt_root = (void *)get_zeroed_page(GFP_KERNEL);
3292         if (!domain->pt_root)
3293                 goto out_free;
3294
3295         domain->iommu_domain = dom;
3296
3297         dom->priv = domain;
3298
3299         dom->geometry.aperture_start = 0;
3300         dom->geometry.aperture_end   = ~0ULL;
3301         dom->geometry.force_aperture = true;
3302
3303         return 0;
3304
3305 out_free:
3306         protection_domain_free(domain);
3307
3308         return -ENOMEM;
3309 }
3310
3311 static void amd_iommu_domain_destroy(struct iommu_domain *dom)
3312 {
3313         struct protection_domain *domain = dom->priv;
3314
3315         if (!domain)
3316                 return;
3317
3318         if (domain->dev_cnt > 0)
3319                 cleanup_domain(domain);
3320
3321         BUG_ON(domain->dev_cnt != 0);
3322
3323         if (domain->mode != PAGE_MODE_NONE)
3324                 free_pagetable(domain);
3325
3326         if (domain->flags & PD_IOMMUV2_MASK)
3327                 free_gcr3_table(domain);
3328
3329         protection_domain_free(domain);
3330
3331         dom->priv = NULL;
3332 }
3333
3334 static void amd_iommu_detach_device(struct iommu_domain *dom,
3335                                     struct device *dev)
3336 {
3337         struct iommu_dev_data *dev_data = dev->archdata.iommu;
3338         struct amd_iommu *iommu;
3339         u16 devid;
3340
3341         if (!check_device(dev))
3342                 return;
3343
3344         devid = get_device_id(dev);
3345
3346         if (dev_data->domain != NULL)
3347                 detach_device(dev);
3348
3349         iommu = amd_iommu_rlookup_table[devid];
3350         if (!iommu)
3351                 return;
3352
3353         iommu_completion_wait(iommu);
3354 }
3355
3356 static int amd_iommu_attach_device(struct iommu_domain *dom,
3357                                    struct device *dev)
3358 {
3359         struct protection_domain *domain = dom->priv;
3360         struct iommu_dev_data *dev_data;
3361         struct amd_iommu *iommu;
3362         int ret;
3363
3364         if (!check_device(dev))
3365                 return -EINVAL;
3366
3367         dev_data = dev->archdata.iommu;
3368
3369         iommu = amd_iommu_rlookup_table[dev_data->devid];
3370         if (!iommu)
3371                 return -EINVAL;
3372
3373         if (dev_data->domain)
3374                 detach_device(dev);
3375
3376         ret = attach_device(dev, domain);
3377
3378         iommu_completion_wait(iommu);
3379
3380         return ret;
3381 }
3382
3383 static int amd_iommu_map(struct iommu_domain *dom, unsigned long iova,
3384                          phys_addr_t paddr, size_t page_size, int iommu_prot)
3385 {
3386         struct protection_domain *domain = dom->priv;
3387         int prot = 0;
3388         int ret;
3389
3390         if (domain->mode == PAGE_MODE_NONE)
3391                 return -EINVAL;
3392
3393         if (iommu_prot & IOMMU_READ)
3394                 prot |= IOMMU_PROT_IR;
3395         if (iommu_prot & IOMMU_WRITE)
3396                 prot |= IOMMU_PROT_IW;
3397
3398         mutex_lock(&domain->api_lock);
3399         ret = iommu_map_page(domain, iova, paddr, prot, page_size);
3400         mutex_unlock(&domain->api_lock);
3401
3402         return ret;
3403 }
3404
3405 static size_t amd_iommu_unmap(struct iommu_domain *dom, unsigned long iova,
3406                            size_t page_size)
3407 {
3408         struct protection_domain *domain = dom->priv;
3409         size_t unmap_size;
3410
3411         if (domain->mode == PAGE_MODE_NONE)
3412                 return -EINVAL;
3413
3414         mutex_lock(&domain->api_lock);
3415         unmap_size = iommu_unmap_page(domain, iova, page_size);
3416         mutex_unlock(&domain->api_lock);
3417
3418         domain_flush_tlb_pde(domain);
3419
3420         return unmap_size;
3421 }
3422
3423 static phys_addr_t amd_iommu_iova_to_phys(struct iommu_domain *dom,
3424                                           unsigned long iova)
3425 {
3426         struct protection_domain *domain = dom->priv;
3427         unsigned long offset_mask;
3428         phys_addr_t paddr;
3429         u64 *pte, __pte;
3430
3431         if (domain->mode == PAGE_MODE_NONE)
3432                 return iova;
3433
3434         pte = fetch_pte(domain, iova);
3435
3436         if (!pte || !IOMMU_PTE_PRESENT(*pte))
3437                 return 0;
3438
3439         if (PM_PTE_LEVEL(*pte) == 0)
3440                 offset_mask = PAGE_SIZE - 1;
3441         else
3442                 offset_mask = PTE_PAGE_SIZE(*pte) - 1;
3443
3444         __pte = *pte & PM_ADDR_MASK;
3445         paddr = (__pte & ~offset_mask) | (iova & offset_mask);
3446
3447         return paddr;
3448 }
3449
3450 static int amd_iommu_domain_has_cap(struct iommu_domain *domain,
3451                                     unsigned long cap)
3452 {
3453         switch (cap) {
3454         case IOMMU_CAP_CACHE_COHERENCY:
3455                 return 1;
3456         case IOMMU_CAP_INTR_REMAP:
3457                 return irq_remapping_enabled;
3458         }
3459
3460         return 0;
3461 }
3462
3463 static struct iommu_ops amd_iommu_ops = {
3464         .domain_init = amd_iommu_domain_init,
3465         .domain_destroy = amd_iommu_domain_destroy,
3466         .attach_dev = amd_iommu_attach_device,
3467         .detach_dev = amd_iommu_detach_device,
3468         .map = amd_iommu_map,
3469         .unmap = amd_iommu_unmap,
3470         .iova_to_phys = amd_iommu_iova_to_phys,
3471         .domain_has_cap = amd_iommu_domain_has_cap,
3472         .pgsize_bitmap  = AMD_IOMMU_PGSIZES,
3473 };
3474
3475 /*****************************************************************************
3476  *
3477  * The next functions do a basic initialization of IOMMU for pass through
3478  * mode
3479  *
3480  * In passthrough mode the IOMMU is initialized and enabled but not used for
3481  * DMA-API translation.
3482  *
3483  *****************************************************************************/
3484
3485 int __init amd_iommu_init_passthrough(void)
3486 {
3487         struct iommu_dev_data *dev_data;
3488         struct pci_dev *dev = NULL;
3489         struct amd_iommu *iommu;
3490         u16 devid;
3491         int ret;
3492
3493         ret = alloc_passthrough_domain();
3494         if (ret)
3495                 return ret;
3496
3497         for_each_pci_dev(dev) {
3498                 if (!check_device(&dev->dev))
3499                         continue;
3500
3501                 dev_data = get_dev_data(&dev->dev);
3502                 dev_data->passthrough = true;
3503
3504                 devid = get_device_id(&dev->dev);
3505
3506                 iommu = amd_iommu_rlookup_table[devid];
3507                 if (!iommu)
3508                         continue;
3509
3510                 attach_device(&dev->dev, pt_domain);
3511         }
3512
3513         amd_iommu_stats_init();
3514
3515         pr_info("AMD-Vi: Initialized for Passthrough Mode\n");
3516
3517         return 0;
3518 }
3519
3520 /* IOMMUv2 specific functions */
3521 int amd_iommu_register_ppr_notifier(struct notifier_block *nb)
3522 {
3523         return atomic_notifier_chain_register(&ppr_notifier, nb);
3524 }
3525 EXPORT_SYMBOL(amd_iommu_register_ppr_notifier);
3526
3527 int amd_iommu_unregister_ppr_notifier(struct notifier_block *nb)
3528 {
3529         return atomic_notifier_chain_unregister(&ppr_notifier, nb);
3530 }
3531 EXPORT_SYMBOL(amd_iommu_unregister_ppr_notifier);
3532
3533 void amd_iommu_domain_direct_map(struct iommu_domain *dom)
3534 {
3535         struct protection_domain *domain = dom->priv;
3536         unsigned long flags;
3537
3538         spin_lock_irqsave(&domain->lock, flags);
3539
3540         /* Update data structure */
3541         domain->mode    = PAGE_MODE_NONE;
3542         domain->updated = true;
3543
3544         /* Make changes visible to IOMMUs */
3545         update_domain(domain);
3546
3547         /* Page-table is not visible to IOMMU anymore, so free it */
3548         free_pagetable(domain);
3549
3550         spin_unlock_irqrestore(&domain->lock, flags);
3551 }
3552 EXPORT_SYMBOL(amd_iommu_domain_direct_map);
3553
3554 int amd_iommu_domain_enable_v2(struct iommu_domain *dom, int pasids)
3555 {
3556         struct protection_domain *domain = dom->priv;
3557         unsigned long flags;
3558         int levels, ret;
3559
3560         if (pasids <= 0 || pasids > (PASID_MASK + 1))
3561                 return -EINVAL;
3562
3563         /* Number of GCR3 table levels required */
3564         for (levels = 0; (pasids - 1) & ~0x1ff; pasids >>= 9)
3565                 levels += 1;
3566
3567         if (levels > amd_iommu_max_glx_val)
3568                 return -EINVAL;
3569
3570         spin_lock_irqsave(&domain->lock, flags);
3571
3572         /*
3573          * Save us all sanity checks whether devices already in the
3574          * domain support IOMMUv2. Just force that the domain has no
3575          * devices attached when it is switched into IOMMUv2 mode.
3576          */
3577         ret = -EBUSY;
3578         if (domain->dev_cnt > 0 || domain->flags & PD_IOMMUV2_MASK)
3579                 goto out;
3580
3581         ret = -ENOMEM;
3582         domain->gcr3_tbl = (void *)get_zeroed_page(GFP_ATOMIC);
3583         if (domain->gcr3_tbl == NULL)
3584                 goto out;
3585
3586         domain->glx      = levels;
3587         domain->flags   |= PD_IOMMUV2_MASK;
3588         domain->updated  = true;
3589
3590         update_domain(domain);
3591
3592         ret = 0;
3593
3594 out:
3595         spin_unlock_irqrestore(&domain->lock, flags);
3596
3597         return ret;
3598 }
3599 EXPORT_SYMBOL(amd_iommu_domain_enable_v2);
3600
3601 static int __flush_pasid(struct protection_domain *domain, int pasid,
3602                          u64 address, bool size)
3603 {
3604         struct iommu_dev_data *dev_data;
3605         struct iommu_cmd cmd;
3606         int i, ret;
3607
3608         if (!(domain->flags & PD_IOMMUV2_MASK))
3609                 return -EINVAL;
3610
3611         build_inv_iommu_pasid(&cmd, domain->id, pasid, address, size);
3612
3613         /*
3614          * IOMMU TLB needs to be flushed before Device TLB to
3615          * prevent device TLB refill from IOMMU TLB
3616          */
3617         for (i = 0; i < amd_iommus_present; ++i) {
3618                 if (domain->dev_iommu[i] == 0)
3619                         continue;
3620
3621                 ret = iommu_queue_command(amd_iommus[i], &cmd);
3622                 if (ret != 0)
3623                         goto out;
3624         }
3625
3626         /* Wait until IOMMU TLB flushes are complete */
3627         domain_flush_complete(domain);
3628
3629         /* Now flush device TLBs */
3630         list_for_each_entry(dev_data, &domain->dev_list, list) {
3631                 struct amd_iommu *iommu;
3632                 int qdep;
3633
3634                 BUG_ON(!dev_data->ats.enabled);
3635
3636                 qdep  = dev_data->ats.qdep;
3637                 iommu = amd_iommu_rlookup_table[dev_data->devid];
3638
3639                 build_inv_iotlb_pasid(&cmd, dev_data->devid, pasid,
3640                                       qdep, address, size);
3641
3642                 ret = iommu_queue_command(iommu, &cmd);
3643                 if (ret != 0)
3644                         goto out;
3645         }
3646
3647         /* Wait until all device TLBs are flushed */
3648         domain_flush_complete(domain);
3649
3650         ret = 0;
3651
3652 out:
3653
3654         return ret;
3655 }
3656
3657 static int __amd_iommu_flush_page(struct protection_domain *domain, int pasid,
3658                                   u64 address)
3659 {
3660         INC_STATS_COUNTER(invalidate_iotlb);
3661
3662         return __flush_pasid(domain, pasid, address, false);
3663 }
3664
3665 int amd_iommu_flush_page(struct iommu_domain *dom, int pasid,
3666                          u64 address)
3667 {
3668         struct protection_domain *domain = dom->priv;
3669         unsigned long flags;
3670         int ret;
3671
3672         spin_lock_irqsave(&domain->lock, flags);
3673         ret = __amd_iommu_flush_page(domain, pasid, address);
3674         spin_unlock_irqrestore(&domain->lock, flags);
3675
3676         return ret;
3677 }
3678 EXPORT_SYMBOL(amd_iommu_flush_page);
3679
3680 static int __amd_iommu_flush_tlb(struct protection_domain *domain, int pasid)
3681 {
3682         INC_STATS_COUNTER(invalidate_iotlb_all);
3683
3684         return __flush_pasid(domain, pasid, CMD_INV_IOMMU_ALL_PAGES_ADDRESS,
3685                              true);
3686 }
3687
3688 int amd_iommu_flush_tlb(struct iommu_domain *dom, int pasid)
3689 {
3690         struct protection_domain *domain = dom->priv;
3691         unsigned long flags;
3692         int ret;
3693
3694         spin_lock_irqsave(&domain->lock, flags);
3695         ret = __amd_iommu_flush_tlb(domain, pasid);
3696         spin_unlock_irqrestore(&domain->lock, flags);
3697
3698         return ret;
3699 }
3700 EXPORT_SYMBOL(amd_iommu_flush_tlb);
3701
3702 static u64 *__get_gcr3_pte(u64 *root, int level, int pasid, bool alloc)
3703 {
3704         int index;
3705         u64 *pte;
3706
3707         while (true) {
3708
3709                 index = (pasid >> (9 * level)) & 0x1ff;
3710                 pte   = &root[index];
3711
3712                 if (level == 0)
3713                         break;
3714
3715                 if (!(*pte & GCR3_VALID)) {
3716                         if (!alloc)
3717                                 return NULL;
3718
3719                         root = (void *)get_zeroed_page(GFP_ATOMIC);
3720                         if (root == NULL)
3721                                 return NULL;
3722
3723                         *pte = __pa(root) | GCR3_VALID;
3724                 }
3725
3726                 root = __va(*pte & PAGE_MASK);
3727
3728                 level -= 1;
3729         }
3730
3731         return pte;
3732 }
3733
3734 static int __set_gcr3(struct protection_domain *domain, int pasid,
3735                       unsigned long cr3)
3736 {
3737         u64 *pte;
3738
3739         if (domain->mode != PAGE_MODE_NONE)
3740                 return -EINVAL;
3741
3742         pte = __get_gcr3_pte(domain->gcr3_tbl, domain->glx, pasid, true);
3743         if (pte == NULL)
3744                 return -ENOMEM;
3745
3746         *pte = (cr3 & PAGE_MASK) | GCR3_VALID;
3747
3748         return __amd_iommu_flush_tlb(domain, pasid);
3749 }
3750
3751 static int __clear_gcr3(struct protection_domain *domain, int pasid)
3752 {
3753         u64 *pte;
3754
3755         if (domain->mode != PAGE_MODE_NONE)
3756                 return -EINVAL;
3757
3758         pte = __get_gcr3_pte(domain->gcr3_tbl, domain->glx, pasid, false);
3759         if (pte == NULL)
3760                 return 0;
3761
3762         *pte = 0;
3763
3764         return __amd_iommu_flush_tlb(domain, pasid);
3765 }
3766
3767 int amd_iommu_domain_set_gcr3(struct iommu_domain *dom, int pasid,
3768                               unsigned long cr3)
3769 {
3770         struct protection_domain *domain = dom->priv;
3771         unsigned long flags;
3772         int ret;
3773
3774         spin_lock_irqsave(&domain->lock, flags);
3775         ret = __set_gcr3(domain, pasid, cr3);
3776         spin_unlock_irqrestore(&domain->lock, flags);
3777
3778         return ret;
3779 }
3780 EXPORT_SYMBOL(amd_iommu_domain_set_gcr3);
3781
3782 int amd_iommu_domain_clear_gcr3(struct iommu_domain *dom, int pasid)
3783 {
3784         struct protection_domain *domain = dom->priv;
3785         unsigned long flags;
3786         int ret;
3787
3788         spin_lock_irqsave(&domain->lock, flags);
3789         ret = __clear_gcr3(domain, pasid);
3790         spin_unlock_irqrestore(&domain->lock, flags);
3791
3792         return ret;
3793 }
3794 EXPORT_SYMBOL(amd_iommu_domain_clear_gcr3);
3795
3796 int amd_iommu_complete_ppr(struct pci_dev *pdev, int pasid,
3797                            int status, int tag)
3798 {
3799         struct iommu_dev_data *dev_data;
3800         struct amd_iommu *iommu;
3801         struct iommu_cmd cmd;
3802
3803         INC_STATS_COUNTER(complete_ppr);
3804
3805         dev_data = get_dev_data(&pdev->dev);
3806         iommu    = amd_iommu_rlookup_table[dev_data->devid];
3807
3808         build_complete_ppr(&cmd, dev_data->devid, pasid, status,
3809                            tag, dev_data->pri_tlp);
3810
3811         return iommu_queue_command(iommu, &cmd);
3812 }
3813 EXPORT_SYMBOL(amd_iommu_complete_ppr);
3814
3815 struct iommu_domain *amd_iommu_get_v2_domain(struct pci_dev *pdev)
3816 {
3817         struct protection_domain *domain;
3818
3819         domain = get_domain(&pdev->dev);
3820         if (IS_ERR(domain))
3821                 return NULL;
3822
3823         /* Only return IOMMUv2 domains */
3824         if (!(domain->flags & PD_IOMMUV2_MASK))
3825                 return NULL;
3826
3827         return domain->iommu_domain;
3828 }
3829 EXPORT_SYMBOL(amd_iommu_get_v2_domain);
3830
3831 void amd_iommu_enable_device_erratum(struct pci_dev *pdev, u32 erratum)
3832 {
3833         struct iommu_dev_data *dev_data;
3834
3835         if (!amd_iommu_v2_supported())
3836                 return;
3837
3838         dev_data = get_dev_data(&pdev->dev);
3839         dev_data->errata |= (1 << erratum);
3840 }
3841 EXPORT_SYMBOL(amd_iommu_enable_device_erratum);
3842
3843 int amd_iommu_device_info(struct pci_dev *pdev,
3844                           struct amd_iommu_device_info *info)
3845 {
3846         int max_pasids;
3847         int pos;
3848
3849         if (pdev == NULL || info == NULL)
3850                 return -EINVAL;
3851
3852         if (!amd_iommu_v2_supported())
3853                 return -EINVAL;
3854
3855         memset(info, 0, sizeof(*info));
3856
3857         pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_ATS);
3858         if (pos)
3859                 info->flags |= AMD_IOMMU_DEVICE_FLAG_ATS_SUP;
3860
3861         pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PRI);
3862         if (pos)
3863                 info->flags |= AMD_IOMMU_DEVICE_FLAG_PRI_SUP;
3864
3865         pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PASID);
3866         if (pos) {
3867                 int features;
3868
3869                 max_pasids = 1 << (9 * (amd_iommu_max_glx_val + 1));
3870                 max_pasids = min(max_pasids, (1 << 20));
3871
3872                 info->flags |= AMD_IOMMU_DEVICE_FLAG_PASID_SUP;
3873                 info->max_pasids = min(pci_max_pasids(pdev), max_pasids);
3874
3875                 features = pci_pasid_features(pdev);
3876                 if (features & PCI_PASID_CAP_EXEC)
3877                         info->flags |= AMD_IOMMU_DEVICE_FLAG_EXEC_SUP;
3878                 if (features & PCI_PASID_CAP_PRIV)
3879                         info->flags |= AMD_IOMMU_DEVICE_FLAG_PRIV_SUP;
3880         }
3881
3882         return 0;
3883 }
3884 EXPORT_SYMBOL(amd_iommu_device_info);
3885
3886 #ifdef CONFIG_IRQ_REMAP
3887
3888 /*****************************************************************************
3889  *
3890  * Interrupt Remapping Implementation
3891  *
3892  *****************************************************************************/
3893
3894 union irte {
3895         u32 val;
3896         struct {
3897                 u32 valid       : 1,
3898                     no_fault    : 1,
3899                     int_type    : 3,
3900                     rq_eoi      : 1,
3901                     dm          : 1,
3902                     rsvd_1      : 1,
3903                     destination : 8,
3904                     vector      : 8,
3905                     rsvd_2      : 8;
3906         } fields;
3907 };
3908
3909 #define DTE_IRQ_PHYS_ADDR_MASK  (((1ULL << 45)-1) << 6)
3910 #define DTE_IRQ_REMAP_INTCTL    (2ULL << 60)
3911 #define DTE_IRQ_TABLE_LEN       (8ULL << 1)
3912 #define DTE_IRQ_REMAP_ENABLE    1ULL
3913
3914 static void set_dte_irq_entry(u16 devid, struct irq_remap_table *table)
3915 {
3916         u64 dte;
3917
3918         dte     = amd_iommu_dev_table[devid].data[2];
3919         dte     &= ~DTE_IRQ_PHYS_ADDR_MASK;
3920         dte     |= virt_to_phys(table->table);
3921         dte     |= DTE_IRQ_REMAP_INTCTL;
3922         dte     |= DTE_IRQ_TABLE_LEN;
3923         dte     |= DTE_IRQ_REMAP_ENABLE;
3924
3925         amd_iommu_dev_table[devid].data[2] = dte;
3926 }
3927
3928 #define IRTE_ALLOCATED (~1U)
3929
3930 static struct irq_remap_table *get_irq_table(u16 devid, bool ioapic)
3931 {
3932         struct irq_remap_table *table = NULL;
3933         struct amd_iommu *iommu;
3934         unsigned long flags;
3935         u16 alias;
3936
3937         write_lock_irqsave(&amd_iommu_devtable_lock, flags);
3938
3939         iommu = amd_iommu_rlookup_table[devid];
3940         if (!iommu)
3941                 goto out_unlock;
3942
3943         table = irq_lookup_table[devid];
3944         if (table)
3945                 goto out;
3946
3947         alias = amd_iommu_alias_table[devid];
3948         table = irq_lookup_table[alias];
3949         if (table) {
3950                 irq_lookup_table[devid] = table;
3951                 set_dte_irq_entry(devid, table);
3952                 iommu_flush_dte(iommu, devid);
3953                 goto out;
3954         }
3955
3956         /* Nothing there yet, allocate new irq remapping table */
3957         table = kzalloc(sizeof(*table), GFP_ATOMIC);
3958         if (!table)
3959                 goto out;
3960
3961         if (ioapic)
3962                 /* Keep the first 32 indexes free for IOAPIC interrupts */
3963                 table->min_index = 32;
3964
3965         table->table = kmem_cache_alloc(amd_iommu_irq_cache, GFP_ATOMIC);
3966         if (!table->table) {
3967                 kfree(table);
3968                 table = NULL;
3969                 goto out;
3970         }
3971
3972         memset(table->table, 0, MAX_IRQS_PER_TABLE * sizeof(u32));
3973
3974         if (ioapic) {
3975                 int i;
3976
3977                 for (i = 0; i < 32; ++i)
3978                         table->table[i] = IRTE_ALLOCATED;
3979         }
3980
3981         irq_lookup_table[devid] = table;
3982         set_dte_irq_entry(devid, table);
3983         iommu_flush_dte(iommu, devid);
3984         if (devid != alias) {
3985                 irq_lookup_table[alias] = table;
3986                 set_dte_irq_entry(devid, table);
3987                 iommu_flush_dte(iommu, alias);
3988         }
3989
3990 out:
3991         iommu_completion_wait(iommu);
3992
3993 out_unlock:
3994         write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
3995
3996         return table;
3997 }
3998
3999 static int alloc_irq_index(struct irq_cfg *cfg, u16 devid, int count)
4000 {
4001         struct irq_remap_table *table;
4002         unsigned long flags;
4003         int index, c;
4004
4005         table = get_irq_table(devid, false);
4006         if (!table)
4007                 return -ENODEV;
4008
4009         spin_lock_irqsave(&table->lock, flags);
4010
4011         /* Scan table for free entries */
4012         for (c = 0, index = table->min_index;
4013              index < MAX_IRQS_PER_TABLE;
4014              ++index) {
4015                 if (table->table[index] == 0)
4016                         c += 1;
4017                 else
4018                         c = 0;
4019
4020                 if (c == count) {
4021                         struct irq_2_iommu *irte_info;
4022
4023                         for (; c != 0; --c)
4024                                 table->table[index - c + 1] = IRTE_ALLOCATED;
4025
4026                         index -= count - 1;
4027
4028                         irte_info             = &cfg->irq_2_iommu;
4029                         irte_info->sub_handle = devid;
4030                         irte_info->irte_index = index;
4031                         irte_info->iommu      = (void *)cfg;
4032
4033                         goto out;
4034                 }
4035         }
4036
4037         index = -ENOSPC;
4038
4039 out:
4040         spin_unlock_irqrestore(&table->lock, flags);
4041
4042         return index;
4043 }
4044
4045 static int get_irte(u16 devid, int index, union irte *irte)
4046 {
4047         struct irq_remap_table *table;
4048         unsigned long flags;
4049
4050         table = get_irq_table(devid, false);
4051         if (!table)
4052                 return -ENOMEM;
4053
4054         spin_lock_irqsave(&table->lock, flags);
4055         irte->val = table->table[index];
4056         spin_unlock_irqrestore(&table->lock, flags);
4057
4058         return 0;
4059 }
4060
4061 static int modify_irte(u16 devid, int index, union irte irte)
4062 {
4063         struct irq_remap_table *table;
4064         struct amd_iommu *iommu;
4065         unsigned long flags;
4066
4067         iommu = amd_iommu_rlookup_table[devid];
4068         if (iommu == NULL)
4069                 return -EINVAL;
4070
4071         table = get_irq_table(devid, false);
4072         if (!table)
4073                 return -ENOMEM;
4074
4075         spin_lock_irqsave(&table->lock, flags);
4076         table->table[index] = irte.val;
4077         spin_unlock_irqrestore(&table->lock, flags);
4078
4079         iommu_flush_irt(iommu, devid);
4080         iommu_completion_wait(iommu);
4081
4082         return 0;
4083 }
4084
4085 static void free_irte(u16 devid, int index)
4086 {
4087         struct irq_remap_table *table;
4088         struct amd_iommu *iommu;
4089         unsigned long flags;
4090
4091         iommu = amd_iommu_rlookup_table[devid];
4092         if (iommu == NULL)
4093                 return;
4094
4095         table = get_irq_table(devid, false);
4096         if (!table)
4097                 return;
4098
4099         spin_lock_irqsave(&table->lock, flags);
4100         table->table[index] = 0;
4101         spin_unlock_irqrestore(&table->lock, flags);
4102
4103         iommu_flush_irt(iommu, devid);
4104         iommu_completion_wait(iommu);
4105 }
4106
4107 static int setup_ioapic_entry(int irq, struct IO_APIC_route_entry *entry,
4108                               unsigned int destination, int vector,
4109                               struct io_apic_irq_attr *attr)
4110 {
4111         struct irq_remap_table *table;
4112         struct irq_2_iommu *irte_info;
4113         struct irq_cfg *cfg;
4114         union irte irte;
4115         int ioapic_id;
4116         int index;
4117         int devid;
4118         int ret;
4119
4120         cfg = irq_get_chip_data(irq);
4121         if (!cfg)
4122                 return -EINVAL;
4123
4124         irte_info = &cfg->irq_2_iommu;
4125         ioapic_id = mpc_ioapic_id(attr->ioapic);
4126         devid     = get_ioapic_devid(ioapic_id);
4127
4128         if (devid < 0)
4129                 return devid;
4130
4131         table = get_irq_table(devid, true);
4132         if (table == NULL)
4133                 return -ENOMEM;
4134
4135         index = attr->ioapic_pin;
4136
4137         /* Setup IRQ remapping info */
4138         irte_info->sub_handle = devid;
4139         irte_info->irte_index = index;
4140         irte_info->iommu      = (void *)cfg;
4141
4142         /* Setup IRTE for IOMMU */
4143         irte.val                = 0;
4144         irte.fields.vector      = vector;
4145         irte.fields.int_type    = apic->irq_delivery_mode;
4146         irte.fields.destination = destination;
4147         irte.fields.dm          = apic->irq_dest_mode;
4148         irte.fields.valid       = 1;
4149
4150         ret = modify_irte(devid, index, irte);
4151         if (ret)
4152                 return ret;
4153
4154         /* Setup IOAPIC entry */
4155         memset(entry, 0, sizeof(*entry));
4156
4157         entry->vector        = index;
4158         entry->mask          = 0;
4159         entry->trigger       = attr->trigger;
4160         entry->polarity      = attr->polarity;
4161
4162         /*
4163          * Mask level triggered irqs.
4164          */
4165         if (attr->trigger)
4166                 entry->mask = 1;
4167
4168         return 0;
4169 }
4170
4171 static int set_affinity(struct irq_data *data, const struct cpumask *mask,
4172                         bool force)
4173 {
4174         struct irq_2_iommu *irte_info;
4175         unsigned int dest, irq;
4176         struct irq_cfg *cfg;
4177         union irte irte;
4178         int err;
4179
4180         if (!config_enabled(CONFIG_SMP))
4181                 return -1;
4182
4183         cfg       = data->chip_data;
4184         irq       = data->irq;
4185         irte_info = &cfg->irq_2_iommu;
4186
4187         if (!cpumask_intersects(mask, cpu_online_mask))
4188                 return -EINVAL;
4189
4190         if (get_irte(irte_info->sub_handle, irte_info->irte_index, &irte))
4191                 return -EBUSY;
4192
4193         if (assign_irq_vector(irq, cfg, mask))
4194                 return -EBUSY;
4195
4196         err = apic->cpu_mask_to_apicid_and(cfg->domain, mask, &dest);
4197         if (err) {
4198                 if (assign_irq_vector(irq, cfg, data->affinity))
4199                         pr_err("AMD-Vi: Failed to recover vector for irq %d\n", irq);
4200                 return err;
4201         }
4202
4203         irte.fields.vector      = cfg->vector;
4204         irte.fields.destination = dest;
4205
4206         modify_irte(irte_info->sub_handle, irte_info->irte_index, irte);
4207
4208         if (cfg->move_in_progress)
4209                 send_cleanup_vector(cfg);
4210
4211         cpumask_copy(data->affinity, mask);
4212
4213         return 0;
4214 }
4215
4216 static int free_irq(int irq)
4217 {
4218         struct irq_2_iommu *irte_info;
4219         struct irq_cfg *cfg;
4220
4221         cfg = irq_get_chip_data(irq);
4222         if (!cfg)
4223                 return -EINVAL;
4224
4225         irte_info = &cfg->irq_2_iommu;
4226
4227         free_irte(irte_info->sub_handle, irte_info->irte_index);
4228
4229         return 0;
4230 }
4231
4232 static void compose_msi_msg(struct pci_dev *pdev,
4233                             unsigned int irq, unsigned int dest,
4234                             struct msi_msg *msg, u8 hpet_id)
4235 {
4236         struct irq_2_iommu *irte_info;
4237         struct irq_cfg *cfg;
4238         union irte irte;
4239
4240         cfg = irq_get_chip_data(irq);
4241         if (!cfg)
4242                 return;
4243
4244         irte_info = &cfg->irq_2_iommu;
4245
4246         irte.val                = 0;
4247         irte.fields.vector      = cfg->vector;
4248         irte.fields.int_type    = apic->irq_delivery_mode;
4249         irte.fields.destination = dest;
4250         irte.fields.dm          = apic->irq_dest_mode;
4251         irte.fields.valid       = 1;
4252
4253         modify_irte(irte_info->sub_handle, irte_info->irte_index, irte);
4254
4255         msg->address_hi = MSI_ADDR_BASE_HI;
4256         msg->address_lo = MSI_ADDR_BASE_LO;
4257         msg->data       = irte_info->irte_index;
4258 }
4259
4260 static int msi_alloc_irq(struct pci_dev *pdev, int irq, int nvec)
4261 {
4262         struct irq_cfg *cfg;
4263         int index;
4264         u16 devid;
4265
4266         if (!pdev)
4267                 return -EINVAL;
4268
4269         cfg = irq_get_chip_data(irq);
4270         if (!cfg)
4271                 return -EINVAL;
4272
4273         devid = get_device_id(&pdev->dev);
4274         index = alloc_irq_index(cfg, devid, nvec);
4275
4276         return index < 0 ? MAX_IRQS_PER_TABLE : index;
4277 }
4278
4279 static int msi_setup_irq(struct pci_dev *pdev, unsigned int irq,
4280                          int index, int offset)
4281 {
4282         struct irq_2_iommu *irte_info;
4283         struct irq_cfg *cfg;
4284         u16 devid;
4285
4286         if (!pdev)
4287                 return -EINVAL;
4288
4289         cfg = irq_get_chip_data(irq);
4290         if (!cfg)
4291                 return -EINVAL;
4292
4293         if (index >= MAX_IRQS_PER_TABLE)
4294                 return 0;
4295
4296         devid           = get_device_id(&pdev->dev);
4297         irte_info       = &cfg->irq_2_iommu;
4298
4299         irte_info->sub_handle = devid;
4300         irte_info->irte_index = index + offset;
4301         irte_info->iommu      = (void *)cfg;
4302
4303         return 0;
4304 }
4305
4306 static int setup_hpet_msi(unsigned int irq, unsigned int id)
4307 {
4308         struct irq_2_iommu *irte_info;
4309         struct irq_cfg *cfg;
4310         int index, devid;
4311
4312         cfg = irq_get_chip_data(irq);
4313         if (!cfg)
4314                 return -EINVAL;
4315
4316         irte_info = &cfg->irq_2_iommu;
4317         devid     = get_hpet_devid(id);
4318         if (devid < 0)
4319                 return devid;
4320
4321         index = alloc_irq_index(cfg, devid, 1);
4322         if (index < 0)
4323                 return index;
4324
4325         irte_info->sub_handle = devid;
4326         irte_info->irte_index = index;
4327         irte_info->iommu      = (void *)cfg;
4328
4329         return 0;
4330 }
4331
4332 struct irq_remap_ops amd_iommu_irq_ops = {
4333         .supported              = amd_iommu_supported,
4334         .prepare                = amd_iommu_prepare,
4335         .enable                 = amd_iommu_enable,
4336         .disable                = amd_iommu_disable,
4337         .reenable               = amd_iommu_reenable,
4338         .enable_faulting        = amd_iommu_enable_faulting,
4339         .setup_ioapic_entry     = setup_ioapic_entry,
4340         .set_affinity           = set_affinity,
4341         .free_irq               = free_irq,
4342         .compose_msi_msg        = compose_msi_msg,
4343         .msi_alloc_irq          = msi_alloc_irq,
4344         .msi_setup_irq          = msi_setup_irq,
4345         .setup_hpet_msi         = setup_hpet_msi,
4346 };
4347 #endif