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