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