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