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