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