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