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