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