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