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