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