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