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