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