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