Merge branch 'v4.4/topic/mm-kaslr-pax_usercopy' into linux-linaro-lsk-v4.4
[firefly-linux-kernel-4.4.55.git] / drivers / iommu / amd_iommu.c
1 /*
2  * Copyright (C) 2007-2010 Advanced Micro Devices, Inc.
3  * Author: Joerg Roedel <jroedel@suse.de>
4  *         Leo Duran <leo.duran@amd.com>
5  *
6  * This program is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License version 2 as published
8  * by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
18  */
19
20 #include <linux/ratelimit.h>
21 #include <linux/pci.h>
22 #include <linux/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 <= 2) {
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         kfree(dom);
1837 }
1838
1839 /*
1840  * Allocates a new protection domain usable for the dma_ops functions.
1841  * It also initializes the page table and the address allocator data
1842  * structures required for the dma_ops interface
1843  */
1844 static struct dma_ops_domain *dma_ops_domain_alloc(void)
1845 {
1846         struct dma_ops_domain *dma_dom;
1847
1848         dma_dom = kzalloc(sizeof(struct dma_ops_domain), GFP_KERNEL);
1849         if (!dma_dom)
1850                 return NULL;
1851
1852         if (protection_domain_init(&dma_dom->domain))
1853                 goto free_dma_dom;
1854
1855         dma_dom->domain.mode = PAGE_MODE_2_LEVEL;
1856         dma_dom->domain.pt_root = (void *)get_zeroed_page(GFP_KERNEL);
1857         dma_dom->domain.flags = PD_DMA_OPS_MASK;
1858         dma_dom->domain.priv = dma_dom;
1859         if (!dma_dom->domain.pt_root)
1860                 goto free_dma_dom;
1861
1862         dma_dom->need_flush = false;
1863
1864         add_domain_to_list(&dma_dom->domain);
1865
1866         if (alloc_new_range(dma_dom, true, GFP_KERNEL))
1867                 goto free_dma_dom;
1868
1869         /*
1870          * mark the first page as allocated so we never return 0 as
1871          * a valid dma-address. So we can use 0 as error value
1872          */
1873         dma_dom->aperture[0]->bitmap[0] = 1;
1874         dma_dom->next_address = 0;
1875
1876
1877         return dma_dom;
1878
1879 free_dma_dom:
1880         dma_ops_domain_free(dma_dom);
1881
1882         return NULL;
1883 }
1884
1885 /*
1886  * little helper function to check whether a given protection domain is a
1887  * dma_ops domain
1888  */
1889 static bool dma_ops_domain(struct protection_domain *domain)
1890 {
1891         return domain->flags & PD_DMA_OPS_MASK;
1892 }
1893
1894 static void set_dte_entry(u16 devid, struct protection_domain *domain, bool ats)
1895 {
1896         u64 pte_root = 0;
1897         u64 flags = 0;
1898
1899         if (domain->mode != PAGE_MODE_NONE)
1900                 pte_root = virt_to_phys(domain->pt_root);
1901
1902         pte_root |= (domain->mode & DEV_ENTRY_MODE_MASK)
1903                     << DEV_ENTRY_MODE_SHIFT;
1904         pte_root |= IOMMU_PTE_IR | IOMMU_PTE_IW | IOMMU_PTE_P | IOMMU_PTE_TV;
1905
1906         flags = amd_iommu_dev_table[devid].data[1];
1907
1908         if (ats)
1909                 flags |= DTE_FLAG_IOTLB;
1910
1911         if (domain->flags & PD_IOMMUV2_MASK) {
1912                 u64 gcr3 = __pa(domain->gcr3_tbl);
1913                 u64 glx  = domain->glx;
1914                 u64 tmp;
1915
1916                 pte_root |= DTE_FLAG_GV;
1917                 pte_root |= (glx & DTE_GLX_MASK) << DTE_GLX_SHIFT;
1918
1919                 /* First mask out possible old values for GCR3 table */
1920                 tmp = DTE_GCR3_VAL_B(~0ULL) << DTE_GCR3_SHIFT_B;
1921                 flags    &= ~tmp;
1922
1923                 tmp = DTE_GCR3_VAL_C(~0ULL) << DTE_GCR3_SHIFT_C;
1924                 flags    &= ~tmp;
1925
1926                 /* Encode GCR3 table into DTE */
1927                 tmp = DTE_GCR3_VAL_A(gcr3) << DTE_GCR3_SHIFT_A;
1928                 pte_root |= tmp;
1929
1930                 tmp = DTE_GCR3_VAL_B(gcr3) << DTE_GCR3_SHIFT_B;
1931                 flags    |= tmp;
1932
1933                 tmp = DTE_GCR3_VAL_C(gcr3) << DTE_GCR3_SHIFT_C;
1934                 flags    |= tmp;
1935         }
1936
1937         flags &= ~(0xffffUL);
1938         flags |= domain->id;
1939
1940         amd_iommu_dev_table[devid].data[1]  = flags;
1941         amd_iommu_dev_table[devid].data[0]  = pte_root;
1942 }
1943
1944 static void clear_dte_entry(u16 devid)
1945 {
1946         /* remove entry from the device table seen by the hardware */
1947         amd_iommu_dev_table[devid].data[0]  = IOMMU_PTE_P | IOMMU_PTE_TV;
1948         amd_iommu_dev_table[devid].data[1] &= DTE_FLAG_MASK;
1949
1950         amd_iommu_apply_erratum_63(devid);
1951 }
1952
1953 static void do_attach(struct iommu_dev_data *dev_data,
1954                       struct protection_domain *domain)
1955 {
1956         struct amd_iommu *iommu;
1957         u16 alias;
1958         bool ats;
1959
1960         iommu = amd_iommu_rlookup_table[dev_data->devid];
1961         alias = dev_data->alias;
1962         ats   = dev_data->ats.enabled;
1963
1964         /* Update data structures */
1965         dev_data->domain = domain;
1966         list_add(&dev_data->list, &domain->dev_list);
1967
1968         /* Do reference counting */
1969         domain->dev_iommu[iommu->index] += 1;
1970         domain->dev_cnt                 += 1;
1971
1972         /* Update device table */
1973         set_dte_entry(dev_data->devid, domain, ats);
1974         if (alias != dev_data->devid)
1975                 set_dte_entry(alias, domain, ats);
1976
1977         device_flush_dte(dev_data);
1978 }
1979
1980 static void do_detach(struct iommu_dev_data *dev_data)
1981 {
1982         struct amd_iommu *iommu;
1983         u16 alias;
1984
1985         /*
1986          * First check if the device is still attached. It might already
1987          * be detached from its domain because the generic
1988          * iommu_detach_group code detached it and we try again here in
1989          * our alias handling.
1990          */
1991         if (!dev_data->domain)
1992                 return;
1993
1994         iommu = amd_iommu_rlookup_table[dev_data->devid];
1995         alias = dev_data->alias;
1996
1997         /* decrease reference counters */
1998         dev_data->domain->dev_iommu[iommu->index] -= 1;
1999         dev_data->domain->dev_cnt                 -= 1;
2000
2001         /* Update data structures */
2002         dev_data->domain = NULL;
2003         list_del(&dev_data->list);
2004         clear_dte_entry(dev_data->devid);
2005         if (alias != dev_data->devid)
2006                 clear_dte_entry(alias);
2007
2008         /* Flush the DTE entry */
2009         device_flush_dte(dev_data);
2010 }
2011
2012 /*
2013  * If a device is not yet associated with a domain, this function does
2014  * assigns it visible for the hardware
2015  */
2016 static int __attach_device(struct iommu_dev_data *dev_data,
2017                            struct protection_domain *domain)
2018 {
2019         int ret;
2020
2021         /*
2022          * Must be called with IRQs disabled. Warn here to detect early
2023          * when its not.
2024          */
2025         WARN_ON(!irqs_disabled());
2026
2027         /* lock domain */
2028         spin_lock(&domain->lock);
2029
2030         ret = -EBUSY;
2031         if (dev_data->domain != NULL)
2032                 goto out_unlock;
2033
2034         /* Attach alias group root */
2035         do_attach(dev_data, domain);
2036
2037         ret = 0;
2038
2039 out_unlock:
2040
2041         /* ready */
2042         spin_unlock(&domain->lock);
2043
2044         return ret;
2045 }
2046
2047
2048 static void pdev_iommuv2_disable(struct pci_dev *pdev)
2049 {
2050         pci_disable_ats(pdev);
2051         pci_disable_pri(pdev);
2052         pci_disable_pasid(pdev);
2053 }
2054
2055 /* FIXME: Change generic reset-function to do the same */
2056 static int pri_reset_while_enabled(struct pci_dev *pdev)
2057 {
2058         u16 control;
2059         int pos;
2060
2061         pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PRI);
2062         if (!pos)
2063                 return -EINVAL;
2064
2065         pci_read_config_word(pdev, pos + PCI_PRI_CTRL, &control);
2066         control |= PCI_PRI_CTRL_RESET;
2067         pci_write_config_word(pdev, pos + PCI_PRI_CTRL, control);
2068
2069         return 0;
2070 }
2071
2072 static int pdev_iommuv2_enable(struct pci_dev *pdev)
2073 {
2074         bool reset_enable;
2075         int reqs, ret;
2076
2077         /* FIXME: Hardcode number of outstanding requests for now */
2078         reqs = 32;
2079         if (pdev_pri_erratum(pdev, AMD_PRI_DEV_ERRATUM_LIMIT_REQ_ONE))
2080                 reqs = 1;
2081         reset_enable = pdev_pri_erratum(pdev, AMD_PRI_DEV_ERRATUM_ENABLE_RESET);
2082
2083         /* Only allow access to user-accessible pages */
2084         ret = pci_enable_pasid(pdev, 0);
2085         if (ret)
2086                 goto out_err;
2087
2088         /* First reset the PRI state of the device */
2089         ret = pci_reset_pri(pdev);
2090         if (ret)
2091                 goto out_err;
2092
2093         /* Enable PRI */
2094         ret = pci_enable_pri(pdev, reqs);
2095         if (ret)
2096                 goto out_err;
2097
2098         if (reset_enable) {
2099                 ret = pri_reset_while_enabled(pdev);
2100                 if (ret)
2101                         goto out_err;
2102         }
2103
2104         ret = pci_enable_ats(pdev, PAGE_SHIFT);
2105         if (ret)
2106                 goto out_err;
2107
2108         return 0;
2109
2110 out_err:
2111         pci_disable_pri(pdev);
2112         pci_disable_pasid(pdev);
2113
2114         return ret;
2115 }
2116
2117 /* FIXME: Move this to PCI code */
2118 #define PCI_PRI_TLP_OFF         (1 << 15)
2119
2120 static bool pci_pri_tlp_required(struct pci_dev *pdev)
2121 {
2122         u16 status;
2123         int pos;
2124
2125         pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PRI);
2126         if (!pos)
2127                 return false;
2128
2129         pci_read_config_word(pdev, pos + PCI_PRI_STATUS, &status);
2130
2131         return (status & PCI_PRI_TLP_OFF) ? true : false;
2132 }
2133
2134 /*
2135  * If a device is not yet associated with a domain, this function
2136  * assigns it visible for the hardware
2137  */
2138 static int attach_device(struct device *dev,
2139                          struct protection_domain *domain)
2140 {
2141         struct pci_dev *pdev = to_pci_dev(dev);
2142         struct iommu_dev_data *dev_data;
2143         unsigned long flags;
2144         int ret;
2145
2146         dev_data = get_dev_data(dev);
2147
2148         if (domain->flags & PD_IOMMUV2_MASK) {
2149                 if (!dev_data->passthrough)
2150                         return -EINVAL;
2151
2152                 if (dev_data->iommu_v2) {
2153                         if (pdev_iommuv2_enable(pdev) != 0)
2154                                 return -EINVAL;
2155
2156                         dev_data->ats.enabled = true;
2157                         dev_data->ats.qdep    = pci_ats_queue_depth(pdev);
2158                         dev_data->pri_tlp     = pci_pri_tlp_required(pdev);
2159                 }
2160         } else if (amd_iommu_iotlb_sup &&
2161                    pci_enable_ats(pdev, PAGE_SHIFT) == 0) {
2162                 dev_data->ats.enabled = true;
2163                 dev_data->ats.qdep    = pci_ats_queue_depth(pdev);
2164         }
2165
2166         write_lock_irqsave(&amd_iommu_devtable_lock, flags);
2167         ret = __attach_device(dev_data, domain);
2168         write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2169
2170         /*
2171          * We might boot into a crash-kernel here. The crashed kernel
2172          * left the caches in the IOMMU dirty. So we have to flush
2173          * here to evict all dirty stuff.
2174          */
2175         domain_flush_tlb_pde(domain);
2176
2177         return ret;
2178 }
2179
2180 /*
2181  * Removes a device from a protection domain (unlocked)
2182  */
2183 static void __detach_device(struct iommu_dev_data *dev_data)
2184 {
2185         struct protection_domain *domain;
2186
2187         /*
2188          * Must be called with IRQs disabled. Warn here to detect early
2189          * when its not.
2190          */
2191         WARN_ON(!irqs_disabled());
2192
2193         if (WARN_ON(!dev_data->domain))
2194                 return;
2195
2196         domain = dev_data->domain;
2197
2198         spin_lock(&domain->lock);
2199
2200         do_detach(dev_data);
2201
2202         spin_unlock(&domain->lock);
2203 }
2204
2205 /*
2206  * Removes a device from a protection domain (with devtable_lock held)
2207  */
2208 static void detach_device(struct device *dev)
2209 {
2210         struct protection_domain *domain;
2211         struct iommu_dev_data *dev_data;
2212         unsigned long flags;
2213
2214         dev_data = get_dev_data(dev);
2215         domain   = dev_data->domain;
2216
2217         /* lock device table */
2218         write_lock_irqsave(&amd_iommu_devtable_lock, flags);
2219         __detach_device(dev_data);
2220         write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2221
2222         if (domain->flags & PD_IOMMUV2_MASK && dev_data->iommu_v2)
2223                 pdev_iommuv2_disable(to_pci_dev(dev));
2224         else if (dev_data->ats.enabled)
2225                 pci_disable_ats(to_pci_dev(dev));
2226
2227         dev_data->ats.enabled = false;
2228 }
2229
2230 static int amd_iommu_add_device(struct device *dev)
2231 {
2232         struct iommu_dev_data *dev_data;
2233         struct iommu_domain *domain;
2234         struct amd_iommu *iommu;
2235         u16 devid;
2236         int ret;
2237
2238         if (!check_device(dev) || get_dev_data(dev))
2239                 return 0;
2240
2241         devid = get_device_id(dev);
2242         iommu = amd_iommu_rlookup_table[devid];
2243
2244         ret = iommu_init_device(dev);
2245         if (ret) {
2246                 if (ret != -ENOTSUPP)
2247                         pr_err("Failed to initialize device %s - trying to proceed anyway\n",
2248                                 dev_name(dev));
2249
2250                 iommu_ignore_device(dev);
2251                 dev->archdata.dma_ops = &nommu_dma_ops;
2252                 goto out;
2253         }
2254         init_iommu_group(dev);
2255
2256         dev_data = get_dev_data(dev);
2257
2258         BUG_ON(!dev_data);
2259
2260         if (iommu_pass_through || dev_data->iommu_v2)
2261                 iommu_request_dm_for_dev(dev);
2262
2263         /* Domains are initialized for this device - have a look what we ended up with */
2264         domain = iommu_get_domain_for_dev(dev);
2265         if (domain->type == IOMMU_DOMAIN_IDENTITY)
2266                 dev_data->passthrough = true;
2267         else
2268                 dev->archdata.dma_ops = &amd_iommu_dma_ops;
2269
2270 out:
2271         iommu_completion_wait(iommu);
2272
2273         return 0;
2274 }
2275
2276 static void amd_iommu_remove_device(struct device *dev)
2277 {
2278         struct amd_iommu *iommu;
2279         u16 devid;
2280
2281         if (!check_device(dev))
2282                 return;
2283
2284         devid = get_device_id(dev);
2285         iommu = amd_iommu_rlookup_table[devid];
2286
2287         iommu_uninit_device(dev);
2288         iommu_completion_wait(iommu);
2289 }
2290
2291 /*****************************************************************************
2292  *
2293  * The next functions belong to the dma_ops mapping/unmapping code.
2294  *
2295  *****************************************************************************/
2296
2297 /*
2298  * In the dma_ops path we only have the struct device. This function
2299  * finds the corresponding IOMMU, the protection domain and the
2300  * requestor id for a given device.
2301  * If the device is not yet associated with a domain this is also done
2302  * in this function.
2303  */
2304 static struct protection_domain *get_domain(struct device *dev)
2305 {
2306         struct protection_domain *domain;
2307         struct iommu_domain *io_domain;
2308
2309         if (!check_device(dev))
2310                 return ERR_PTR(-EINVAL);
2311
2312         io_domain = iommu_get_domain_for_dev(dev);
2313         if (!io_domain)
2314                 return NULL;
2315
2316         domain = to_pdomain(io_domain);
2317         if (!dma_ops_domain(domain))
2318                 return ERR_PTR(-EBUSY);
2319
2320         return domain;
2321 }
2322
2323 static void update_device_table(struct protection_domain *domain)
2324 {
2325         struct iommu_dev_data *dev_data;
2326
2327         list_for_each_entry(dev_data, &domain->dev_list, list) {
2328                 set_dte_entry(dev_data->devid, domain, dev_data->ats.enabled);
2329
2330                 if (dev_data->devid == dev_data->alias)
2331                         continue;
2332
2333                 /* There is an alias, update device table entry for it */
2334                 set_dte_entry(dev_data->alias, domain, dev_data->ats.enabled);
2335         }
2336 }
2337
2338 static void update_domain(struct protection_domain *domain)
2339 {
2340         if (!domain->updated)
2341                 return;
2342
2343         update_device_table(domain);
2344
2345         domain_flush_devices(domain);
2346         domain_flush_tlb_pde(domain);
2347
2348         domain->updated = false;
2349 }
2350
2351 /*
2352  * This function fetches the PTE for a given address in the aperture
2353  */
2354 static u64* dma_ops_get_pte(struct dma_ops_domain *dom,
2355                             unsigned long address)
2356 {
2357         struct aperture_range *aperture;
2358         u64 *pte, *pte_page;
2359
2360         aperture = dom->aperture[APERTURE_RANGE_INDEX(address)];
2361         if (!aperture)
2362                 return NULL;
2363
2364         pte = aperture->pte_pages[APERTURE_PAGE_INDEX(address)];
2365         if (!pte) {
2366                 pte = alloc_pte(&dom->domain, address, PAGE_SIZE, &pte_page,
2367                                 GFP_ATOMIC);
2368                 aperture->pte_pages[APERTURE_PAGE_INDEX(address)] = pte_page;
2369         } else
2370                 pte += PM_LEVEL_INDEX(0, address);
2371
2372         update_domain(&dom->domain);
2373
2374         return pte;
2375 }
2376
2377 /*
2378  * This is the generic map function. It maps one 4kb page at paddr to
2379  * the given address in the DMA address space for the domain.
2380  */
2381 static dma_addr_t dma_ops_domain_map(struct dma_ops_domain *dom,
2382                                      unsigned long address,
2383                                      phys_addr_t paddr,
2384                                      int direction)
2385 {
2386         u64 *pte, __pte;
2387
2388         WARN_ON(address > dom->aperture_size);
2389
2390         paddr &= PAGE_MASK;
2391
2392         pte  = dma_ops_get_pte(dom, address);
2393         if (!pte)
2394                 return DMA_ERROR_CODE;
2395
2396         __pte = paddr | IOMMU_PTE_P | IOMMU_PTE_FC;
2397
2398         if (direction == DMA_TO_DEVICE)
2399                 __pte |= IOMMU_PTE_IR;
2400         else if (direction == DMA_FROM_DEVICE)
2401                 __pte |= IOMMU_PTE_IW;
2402         else if (direction == DMA_BIDIRECTIONAL)
2403                 __pte |= IOMMU_PTE_IR | IOMMU_PTE_IW;
2404
2405         WARN_ON(*pte);
2406
2407         *pte = __pte;
2408
2409         return (dma_addr_t)address;
2410 }
2411
2412 /*
2413  * The generic unmapping function for on page in the DMA address space.
2414  */
2415 static void dma_ops_domain_unmap(struct dma_ops_domain *dom,
2416                                  unsigned long address)
2417 {
2418         struct aperture_range *aperture;
2419         u64 *pte;
2420
2421         if (address >= dom->aperture_size)
2422                 return;
2423
2424         aperture = dom->aperture[APERTURE_RANGE_INDEX(address)];
2425         if (!aperture)
2426                 return;
2427
2428         pte  = aperture->pte_pages[APERTURE_PAGE_INDEX(address)];
2429         if (!pte)
2430                 return;
2431
2432         pte += PM_LEVEL_INDEX(0, address);
2433
2434         WARN_ON(!*pte);
2435
2436         *pte = 0ULL;
2437 }
2438
2439 /*
2440  * This function contains common code for mapping of a physically
2441  * contiguous memory region into DMA address space. It is used by all
2442  * mapping functions provided with this IOMMU driver.
2443  * Must be called with the domain lock held.
2444  */
2445 static dma_addr_t __map_single(struct device *dev,
2446                                struct dma_ops_domain *dma_dom,
2447                                phys_addr_t paddr,
2448                                size_t size,
2449                                int dir,
2450                                bool align,
2451                                u64 dma_mask)
2452 {
2453         dma_addr_t offset = paddr & ~PAGE_MASK;
2454         dma_addr_t address, start, ret;
2455         unsigned int pages;
2456         unsigned long align_mask = 0;
2457         int i;
2458
2459         pages = iommu_num_pages(paddr, size, PAGE_SIZE);
2460         paddr &= PAGE_MASK;
2461
2462         INC_STATS_COUNTER(total_map_requests);
2463
2464         if (pages > 1)
2465                 INC_STATS_COUNTER(cross_page);
2466
2467         if (align)
2468                 align_mask = (1UL << get_order(size)) - 1;
2469
2470 retry:
2471         address = dma_ops_alloc_addresses(dev, dma_dom, pages, align_mask,
2472                                           dma_mask);
2473         if (unlikely(address == DMA_ERROR_CODE)) {
2474                 /*
2475                  * setting next_address here will let the address
2476                  * allocator only scan the new allocated range in the
2477                  * first run. This is a small optimization.
2478                  */
2479                 dma_dom->next_address = dma_dom->aperture_size;
2480
2481                 if (alloc_new_range(dma_dom, false, GFP_ATOMIC))
2482                         goto out;
2483
2484                 /*
2485                  * aperture was successfully enlarged by 128 MB, try
2486                  * allocation again
2487                  */
2488                 goto retry;
2489         }
2490
2491         start = address;
2492         for (i = 0; i < pages; ++i) {
2493                 ret = dma_ops_domain_map(dma_dom, start, paddr, dir);
2494                 if (ret == DMA_ERROR_CODE)
2495                         goto out_unmap;
2496
2497                 paddr += PAGE_SIZE;
2498                 start += PAGE_SIZE;
2499         }
2500         address += offset;
2501
2502         ADD_STATS_COUNTER(alloced_io_mem, size);
2503
2504         if (unlikely(dma_dom->need_flush && !amd_iommu_unmap_flush)) {
2505                 domain_flush_tlb(&dma_dom->domain);
2506                 dma_dom->need_flush = false;
2507         } else if (unlikely(amd_iommu_np_cache))
2508                 domain_flush_pages(&dma_dom->domain, address, size);
2509
2510 out:
2511         return address;
2512
2513 out_unmap:
2514
2515         for (--i; i >= 0; --i) {
2516                 start -= PAGE_SIZE;
2517                 dma_ops_domain_unmap(dma_dom, start);
2518         }
2519
2520         dma_ops_free_addresses(dma_dom, address, pages);
2521
2522         return DMA_ERROR_CODE;
2523 }
2524
2525 /*
2526  * Does the reverse of the __map_single function. Must be called with
2527  * the domain lock held too
2528  */
2529 static void __unmap_single(struct dma_ops_domain *dma_dom,
2530                            dma_addr_t dma_addr,
2531                            size_t size,
2532                            int dir)
2533 {
2534         dma_addr_t flush_addr;
2535         dma_addr_t i, start;
2536         unsigned int pages;
2537
2538         if ((dma_addr == DMA_ERROR_CODE) ||
2539             (dma_addr + size > dma_dom->aperture_size))
2540                 return;
2541
2542         flush_addr = dma_addr;
2543         pages = iommu_num_pages(dma_addr, size, PAGE_SIZE);
2544         dma_addr &= PAGE_MASK;
2545         start = dma_addr;
2546
2547         for (i = 0; i < pages; ++i) {
2548                 dma_ops_domain_unmap(dma_dom, start);
2549                 start += PAGE_SIZE;
2550         }
2551
2552         SUB_STATS_COUNTER(alloced_io_mem, size);
2553
2554         dma_ops_free_addresses(dma_dom, dma_addr, pages);
2555
2556         if (amd_iommu_unmap_flush || dma_dom->need_flush) {
2557                 domain_flush_pages(&dma_dom->domain, flush_addr, size);
2558                 dma_dom->need_flush = false;
2559         }
2560 }
2561
2562 /*
2563  * The exported map_single function for dma_ops.
2564  */
2565 static dma_addr_t map_page(struct device *dev, struct page *page,
2566                            unsigned long offset, size_t size,
2567                            enum dma_data_direction dir,
2568                            struct dma_attrs *attrs)
2569 {
2570         unsigned long flags;
2571         struct protection_domain *domain;
2572         dma_addr_t addr;
2573         u64 dma_mask;
2574         phys_addr_t paddr = page_to_phys(page) + offset;
2575
2576         INC_STATS_COUNTER(cnt_map_single);
2577
2578         domain = get_domain(dev);
2579         if (PTR_ERR(domain) == -EINVAL)
2580                 return (dma_addr_t)paddr;
2581         else if (IS_ERR(domain))
2582                 return DMA_ERROR_CODE;
2583
2584         dma_mask = *dev->dma_mask;
2585
2586         spin_lock_irqsave(&domain->lock, flags);
2587
2588         addr = __map_single(dev, domain->priv, paddr, size, dir, false,
2589                             dma_mask);
2590         if (addr == DMA_ERROR_CODE)
2591                 goto out;
2592
2593         domain_flush_complete(domain);
2594
2595 out:
2596         spin_unlock_irqrestore(&domain->lock, flags);
2597
2598         return addr;
2599 }
2600
2601 /*
2602  * The exported unmap_single function for dma_ops.
2603  */
2604 static void unmap_page(struct device *dev, dma_addr_t dma_addr, size_t size,
2605                        enum dma_data_direction dir, struct dma_attrs *attrs)
2606 {
2607         unsigned long flags;
2608         struct protection_domain *domain;
2609
2610         INC_STATS_COUNTER(cnt_unmap_single);
2611
2612         domain = get_domain(dev);
2613         if (IS_ERR(domain))
2614                 return;
2615
2616         spin_lock_irqsave(&domain->lock, flags);
2617
2618         __unmap_single(domain->priv, dma_addr, size, dir);
2619
2620         domain_flush_complete(domain);
2621
2622         spin_unlock_irqrestore(&domain->lock, flags);
2623 }
2624
2625 /*
2626  * The exported map_sg function for dma_ops (handles scatter-gather
2627  * lists).
2628  */
2629 static int map_sg(struct device *dev, struct scatterlist *sglist,
2630                   int nelems, enum dma_data_direction dir,
2631                   struct dma_attrs *attrs)
2632 {
2633         unsigned long flags;
2634         struct protection_domain *domain;
2635         int i;
2636         struct scatterlist *s;
2637         phys_addr_t paddr;
2638         int mapped_elems = 0;
2639         u64 dma_mask;
2640
2641         INC_STATS_COUNTER(cnt_map_sg);
2642
2643         domain = get_domain(dev);
2644         if (IS_ERR(domain))
2645                 return 0;
2646
2647         dma_mask = *dev->dma_mask;
2648
2649         spin_lock_irqsave(&domain->lock, flags);
2650
2651         for_each_sg(sglist, s, nelems, i) {
2652                 paddr = sg_phys(s);
2653
2654                 s->dma_address = __map_single(dev, domain->priv,
2655                                               paddr, s->length, dir, false,
2656                                               dma_mask);
2657
2658                 if (s->dma_address) {
2659                         s->dma_length = s->length;
2660                         mapped_elems++;
2661                 } else
2662                         goto unmap;
2663         }
2664
2665         domain_flush_complete(domain);
2666
2667 out:
2668         spin_unlock_irqrestore(&domain->lock, flags);
2669
2670         return mapped_elems;
2671 unmap:
2672         for_each_sg(sglist, s, mapped_elems, i) {
2673                 if (s->dma_address)
2674                         __unmap_single(domain->priv, s->dma_address,
2675                                        s->dma_length, dir);
2676                 s->dma_address = s->dma_length = 0;
2677         }
2678
2679         mapped_elems = 0;
2680
2681         goto out;
2682 }
2683
2684 /*
2685  * The exported map_sg function for dma_ops (handles scatter-gather
2686  * lists).
2687  */
2688 static void unmap_sg(struct device *dev, struct scatterlist *sglist,
2689                      int nelems, enum dma_data_direction dir,
2690                      struct dma_attrs *attrs)
2691 {
2692         unsigned long flags;
2693         struct protection_domain *domain;
2694         struct scatterlist *s;
2695         int i;
2696
2697         INC_STATS_COUNTER(cnt_unmap_sg);
2698
2699         domain = get_domain(dev);
2700         if (IS_ERR(domain))
2701                 return;
2702
2703         spin_lock_irqsave(&domain->lock, flags);
2704
2705         for_each_sg(sglist, s, nelems, i) {
2706                 __unmap_single(domain->priv, s->dma_address,
2707                                s->dma_length, dir);
2708                 s->dma_address = s->dma_length = 0;
2709         }
2710
2711         domain_flush_complete(domain);
2712
2713         spin_unlock_irqrestore(&domain->lock, flags);
2714 }
2715
2716 /*
2717  * The exported alloc_coherent function for dma_ops.
2718  */
2719 static void *alloc_coherent(struct device *dev, size_t size,
2720                             dma_addr_t *dma_addr, gfp_t flag,
2721                             struct dma_attrs *attrs)
2722 {
2723         u64 dma_mask = dev->coherent_dma_mask;
2724         struct protection_domain *domain;
2725         unsigned long flags;
2726         struct page *page;
2727
2728         INC_STATS_COUNTER(cnt_alloc_coherent);
2729
2730         domain = get_domain(dev);
2731         if (PTR_ERR(domain) == -EINVAL) {
2732                 page = alloc_pages(flag, get_order(size));
2733                 *dma_addr = page_to_phys(page);
2734                 return page_address(page);
2735         } else if (IS_ERR(domain))
2736                 return NULL;
2737
2738         size      = PAGE_ALIGN(size);
2739         dma_mask  = dev->coherent_dma_mask;
2740         flag     &= ~(__GFP_DMA | __GFP_HIGHMEM | __GFP_DMA32);
2741         flag     |= __GFP_ZERO;
2742
2743         page = alloc_pages(flag | __GFP_NOWARN,  get_order(size));
2744         if (!page) {
2745                 if (!gfpflags_allow_blocking(flag))
2746                         return NULL;
2747
2748                 page = dma_alloc_from_contiguous(dev, size >> PAGE_SHIFT,
2749                                                  get_order(size));
2750                 if (!page)
2751                         return NULL;
2752         }
2753
2754         if (!dma_mask)
2755                 dma_mask = *dev->dma_mask;
2756
2757         spin_lock_irqsave(&domain->lock, flags);
2758
2759         *dma_addr = __map_single(dev, domain->priv, page_to_phys(page),
2760                                  size, DMA_BIDIRECTIONAL, true, dma_mask);
2761
2762         if (*dma_addr == DMA_ERROR_CODE) {
2763                 spin_unlock_irqrestore(&domain->lock, flags);
2764                 goto out_free;
2765         }
2766
2767         domain_flush_complete(domain);
2768
2769         spin_unlock_irqrestore(&domain->lock, flags);
2770
2771         return page_address(page);
2772
2773 out_free:
2774
2775         if (!dma_release_from_contiguous(dev, page, size >> PAGE_SHIFT))
2776                 __free_pages(page, get_order(size));
2777
2778         return NULL;
2779 }
2780
2781 /*
2782  * The exported free_coherent function for dma_ops.
2783  */
2784 static void free_coherent(struct device *dev, size_t size,
2785                           void *virt_addr, dma_addr_t dma_addr,
2786                           struct dma_attrs *attrs)
2787 {
2788         struct protection_domain *domain;
2789         unsigned long flags;
2790         struct page *page;
2791
2792         INC_STATS_COUNTER(cnt_free_coherent);
2793
2794         page = virt_to_page(virt_addr);
2795         size = PAGE_ALIGN(size);
2796
2797         domain = get_domain(dev);
2798         if (IS_ERR(domain))
2799                 goto free_mem;
2800
2801         spin_lock_irqsave(&domain->lock, flags);
2802
2803         __unmap_single(domain->priv, dma_addr, size, DMA_BIDIRECTIONAL);
2804
2805         domain_flush_complete(domain);
2806
2807         spin_unlock_irqrestore(&domain->lock, flags);
2808
2809 free_mem:
2810         if (!dma_release_from_contiguous(dev, page, size >> PAGE_SHIFT))
2811                 __free_pages(page, get_order(size));
2812 }
2813
2814 /*
2815  * This function is called by the DMA layer to find out if we can handle a
2816  * particular device. It is part of the dma_ops.
2817  */
2818 static int amd_iommu_dma_supported(struct device *dev, u64 mask)
2819 {
2820         return check_device(dev);
2821 }
2822
2823 static struct dma_map_ops amd_iommu_dma_ops = {
2824         .alloc = alloc_coherent,
2825         .free = free_coherent,
2826         .map_page = map_page,
2827         .unmap_page = unmap_page,
2828         .map_sg = map_sg,
2829         .unmap_sg = unmap_sg,
2830         .dma_supported = amd_iommu_dma_supported,
2831 };
2832
2833 int __init amd_iommu_init_api(void)
2834 {
2835         return bus_set_iommu(&pci_bus_type, &amd_iommu_ops);
2836 }
2837
2838 int __init amd_iommu_init_dma_ops(void)
2839 {
2840         swiotlb        = iommu_pass_through ? 1 : 0;
2841         iommu_detected = 1;
2842
2843         /*
2844          * In case we don't initialize SWIOTLB (actually the common case
2845          * when AMD IOMMU is enabled), make sure there are global
2846          * dma_ops set as a fall-back for devices not handled by this
2847          * driver (for example non-PCI devices).
2848          */
2849         if (!swiotlb)
2850                 dma_ops = &nommu_dma_ops;
2851
2852         amd_iommu_stats_init();
2853
2854         if (amd_iommu_unmap_flush)
2855                 pr_info("AMD-Vi: IO/TLB flush on unmap enabled\n");
2856         else
2857                 pr_info("AMD-Vi: Lazy IO/TLB flushing enabled\n");
2858
2859         return 0;
2860 }
2861
2862 /*****************************************************************************
2863  *
2864  * The following functions belong to the exported interface of AMD IOMMU
2865  *
2866  * This interface allows access to lower level functions of the IOMMU
2867  * like protection domain handling and assignement of devices to domains
2868  * which is not possible with the dma_ops interface.
2869  *
2870  *****************************************************************************/
2871
2872 static void cleanup_domain(struct protection_domain *domain)
2873 {
2874         struct iommu_dev_data *entry;
2875         unsigned long flags;
2876
2877         write_lock_irqsave(&amd_iommu_devtable_lock, flags);
2878
2879         while (!list_empty(&domain->dev_list)) {
2880                 entry = list_first_entry(&domain->dev_list,
2881                                          struct iommu_dev_data, list);
2882                 __detach_device(entry);
2883         }
2884
2885         write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2886 }
2887
2888 static void protection_domain_free(struct protection_domain *domain)
2889 {
2890         if (!domain)
2891                 return;
2892
2893         del_domain_from_list(domain);
2894
2895         if (domain->id)
2896                 domain_id_free(domain->id);
2897
2898         kfree(domain);
2899 }
2900
2901 static int protection_domain_init(struct protection_domain *domain)
2902 {
2903         spin_lock_init(&domain->lock);
2904         mutex_init(&domain->api_lock);
2905         domain->id = domain_id_alloc();
2906         if (!domain->id)
2907                 return -ENOMEM;
2908         INIT_LIST_HEAD(&domain->dev_list);
2909
2910         return 0;
2911 }
2912
2913 static struct protection_domain *protection_domain_alloc(void)
2914 {
2915         struct protection_domain *domain;
2916
2917         domain = kzalloc(sizeof(*domain), GFP_KERNEL);
2918         if (!domain)
2919                 return NULL;
2920
2921         if (protection_domain_init(domain))
2922                 goto out_err;
2923
2924         add_domain_to_list(domain);
2925
2926         return domain;
2927
2928 out_err:
2929         kfree(domain);
2930
2931         return NULL;
2932 }
2933
2934 static struct iommu_domain *amd_iommu_domain_alloc(unsigned type)
2935 {
2936         struct protection_domain *pdomain;
2937         struct dma_ops_domain *dma_domain;
2938
2939         switch (type) {
2940         case IOMMU_DOMAIN_UNMANAGED:
2941                 pdomain = protection_domain_alloc();
2942                 if (!pdomain)
2943                         return NULL;
2944
2945                 pdomain->mode    = PAGE_MODE_3_LEVEL;
2946                 pdomain->pt_root = (void *)get_zeroed_page(GFP_KERNEL);
2947                 if (!pdomain->pt_root) {
2948                         protection_domain_free(pdomain);
2949                         return NULL;
2950                 }
2951
2952                 pdomain->domain.geometry.aperture_start = 0;
2953                 pdomain->domain.geometry.aperture_end   = ~0ULL;
2954                 pdomain->domain.geometry.force_aperture = true;
2955
2956                 break;
2957         case IOMMU_DOMAIN_DMA:
2958                 dma_domain = dma_ops_domain_alloc();
2959                 if (!dma_domain) {
2960                         pr_err("AMD-Vi: Failed to allocate\n");
2961                         return NULL;
2962                 }
2963                 pdomain = &dma_domain->domain;
2964                 break;
2965         case IOMMU_DOMAIN_IDENTITY:
2966                 pdomain = protection_domain_alloc();
2967                 if (!pdomain)
2968                         return NULL;
2969
2970                 pdomain->mode = PAGE_MODE_NONE;
2971                 break;
2972         default:
2973                 return NULL;
2974         }
2975
2976         return &pdomain->domain;
2977 }
2978
2979 static void amd_iommu_domain_free(struct iommu_domain *dom)
2980 {
2981         struct protection_domain *domain;
2982         struct dma_ops_domain *dma_dom;
2983
2984         domain = to_pdomain(dom);
2985
2986         if (domain->dev_cnt > 0)
2987                 cleanup_domain(domain);
2988
2989         BUG_ON(domain->dev_cnt != 0);
2990
2991         if (!dom)
2992                 return;
2993
2994         switch (dom->type) {
2995         case IOMMU_DOMAIN_DMA:
2996                 dma_dom = domain->priv;
2997                 dma_ops_domain_free(dma_dom);
2998                 break;
2999         default:
3000                 if (domain->mode != PAGE_MODE_NONE)
3001                         free_pagetable(domain);
3002
3003                 if (domain->flags & PD_IOMMUV2_MASK)
3004                         free_gcr3_table(domain);
3005
3006                 protection_domain_free(domain);
3007                 break;
3008         }
3009 }
3010
3011 static void amd_iommu_detach_device(struct iommu_domain *dom,
3012                                     struct device *dev)
3013 {
3014         struct iommu_dev_data *dev_data = dev->archdata.iommu;
3015         struct amd_iommu *iommu;
3016         u16 devid;
3017
3018         if (!check_device(dev))
3019                 return;
3020
3021         devid = get_device_id(dev);
3022
3023         if (dev_data->domain != NULL)
3024                 detach_device(dev);
3025
3026         iommu = amd_iommu_rlookup_table[devid];
3027         if (!iommu)
3028                 return;
3029
3030         iommu_completion_wait(iommu);
3031 }
3032
3033 static int amd_iommu_attach_device(struct iommu_domain *dom,
3034                                    struct device *dev)
3035 {
3036         struct protection_domain *domain = to_pdomain(dom);
3037         struct iommu_dev_data *dev_data;
3038         struct amd_iommu *iommu;
3039         int ret;
3040
3041         if (!check_device(dev))
3042                 return -EINVAL;
3043
3044         dev_data = dev->archdata.iommu;
3045
3046         iommu = amd_iommu_rlookup_table[dev_data->devid];
3047         if (!iommu)
3048                 return -EINVAL;
3049
3050         if (dev_data->domain)
3051                 detach_device(dev);
3052
3053         ret = attach_device(dev, domain);
3054
3055         iommu_completion_wait(iommu);
3056
3057         return ret;
3058 }
3059
3060 static int amd_iommu_map(struct iommu_domain *dom, unsigned long iova,
3061                          phys_addr_t paddr, size_t page_size, int iommu_prot)
3062 {
3063         struct protection_domain *domain = to_pdomain(dom);
3064         int prot = 0;
3065         int ret;
3066
3067         if (domain->mode == PAGE_MODE_NONE)
3068                 return -EINVAL;
3069
3070         if (iommu_prot & IOMMU_READ)
3071                 prot |= IOMMU_PROT_IR;
3072         if (iommu_prot & IOMMU_WRITE)
3073                 prot |= IOMMU_PROT_IW;
3074
3075         mutex_lock(&domain->api_lock);
3076         ret = iommu_map_page(domain, iova, paddr, prot, page_size);
3077         mutex_unlock(&domain->api_lock);
3078
3079         return ret;
3080 }
3081
3082 static size_t amd_iommu_unmap(struct iommu_domain *dom, unsigned long iova,
3083                            size_t page_size)
3084 {
3085         struct protection_domain *domain = to_pdomain(dom);
3086         size_t unmap_size;
3087
3088         if (domain->mode == PAGE_MODE_NONE)
3089                 return -EINVAL;
3090
3091         mutex_lock(&domain->api_lock);
3092         unmap_size = iommu_unmap_page(domain, iova, page_size);
3093         mutex_unlock(&domain->api_lock);
3094
3095         domain_flush_tlb_pde(domain);
3096
3097         return unmap_size;
3098 }
3099
3100 static phys_addr_t amd_iommu_iova_to_phys(struct iommu_domain *dom,
3101                                           dma_addr_t iova)
3102 {
3103         struct protection_domain *domain = to_pdomain(dom);
3104         unsigned long offset_mask, pte_pgsize;
3105         u64 *pte, __pte;
3106
3107         if (domain->mode == PAGE_MODE_NONE)
3108                 return iova;
3109
3110         pte = fetch_pte(domain, iova, &pte_pgsize);
3111
3112         if (!pte || !IOMMU_PTE_PRESENT(*pte))
3113                 return 0;
3114
3115         offset_mask = pte_pgsize - 1;
3116         __pte       = *pte & PM_ADDR_MASK;
3117
3118         return (__pte & ~offset_mask) | (iova & offset_mask);
3119 }
3120
3121 static bool amd_iommu_capable(enum iommu_cap cap)
3122 {
3123         switch (cap) {
3124         case IOMMU_CAP_CACHE_COHERENCY:
3125                 return true;
3126         case IOMMU_CAP_INTR_REMAP:
3127                 return (irq_remapping_enabled == 1);
3128         case IOMMU_CAP_NOEXEC:
3129                 return false;
3130         }
3131
3132         return false;
3133 }
3134
3135 static void amd_iommu_get_dm_regions(struct device *dev,
3136                                      struct list_head *head)
3137 {
3138         struct unity_map_entry *entry;
3139         u16 devid;
3140
3141         devid = get_device_id(dev);
3142
3143         list_for_each_entry(entry, &amd_iommu_unity_map, list) {
3144                 struct iommu_dm_region *region;
3145
3146                 if (devid < entry->devid_start || devid > entry->devid_end)
3147                         continue;
3148
3149                 region = kzalloc(sizeof(*region), GFP_KERNEL);
3150                 if (!region) {
3151                         pr_err("Out of memory allocating dm-regions for %s\n",
3152                                 dev_name(dev));
3153                         return;
3154                 }
3155
3156                 region->start = entry->address_start;
3157                 region->length = entry->address_end - entry->address_start;
3158                 if (entry->prot & IOMMU_PROT_IR)
3159                         region->prot |= IOMMU_READ;
3160                 if (entry->prot & IOMMU_PROT_IW)
3161                         region->prot |= IOMMU_WRITE;
3162
3163                 list_add_tail(&region->list, head);
3164         }
3165 }
3166
3167 static void amd_iommu_put_dm_regions(struct device *dev,
3168                                      struct list_head *head)
3169 {
3170         struct iommu_dm_region *entry, *next;
3171
3172         list_for_each_entry_safe(entry, next, head, list)
3173                 kfree(entry);
3174 }
3175
3176 static const struct iommu_ops amd_iommu_ops = {
3177         .capable = amd_iommu_capable,
3178         .domain_alloc = amd_iommu_domain_alloc,
3179         .domain_free  = amd_iommu_domain_free,
3180         .attach_dev = amd_iommu_attach_device,
3181         .detach_dev = amd_iommu_detach_device,
3182         .map = amd_iommu_map,
3183         .unmap = amd_iommu_unmap,
3184         .map_sg = default_iommu_map_sg,
3185         .iova_to_phys = amd_iommu_iova_to_phys,
3186         .add_device = amd_iommu_add_device,
3187         .remove_device = amd_iommu_remove_device,
3188         .device_group = pci_device_group,
3189         .get_dm_regions = amd_iommu_get_dm_regions,
3190         .put_dm_regions = amd_iommu_put_dm_regions,
3191         .pgsize_bitmap  = AMD_IOMMU_PGSIZES,
3192 };
3193
3194 /*****************************************************************************
3195  *
3196  * The next functions do a basic initialization of IOMMU for pass through
3197  * mode
3198  *
3199  * In passthrough mode the IOMMU is initialized and enabled but not used for
3200  * DMA-API translation.
3201  *
3202  *****************************************************************************/
3203
3204 /* IOMMUv2 specific functions */
3205 int amd_iommu_register_ppr_notifier(struct notifier_block *nb)
3206 {
3207         return atomic_notifier_chain_register(&ppr_notifier, nb);
3208 }
3209 EXPORT_SYMBOL(amd_iommu_register_ppr_notifier);
3210
3211 int amd_iommu_unregister_ppr_notifier(struct notifier_block *nb)
3212 {
3213         return atomic_notifier_chain_unregister(&ppr_notifier, nb);
3214 }
3215 EXPORT_SYMBOL(amd_iommu_unregister_ppr_notifier);
3216
3217 void amd_iommu_domain_direct_map(struct iommu_domain *dom)
3218 {
3219         struct protection_domain *domain = to_pdomain(dom);
3220         unsigned long flags;
3221
3222         spin_lock_irqsave(&domain->lock, flags);
3223
3224         /* Update data structure */
3225         domain->mode    = PAGE_MODE_NONE;
3226         domain->updated = true;
3227
3228         /* Make changes visible to IOMMUs */
3229         update_domain(domain);
3230
3231         /* Page-table is not visible to IOMMU anymore, so free it */
3232         free_pagetable(domain);
3233
3234         spin_unlock_irqrestore(&domain->lock, flags);
3235 }
3236 EXPORT_SYMBOL(amd_iommu_domain_direct_map);
3237
3238 int amd_iommu_domain_enable_v2(struct iommu_domain *dom, int pasids)
3239 {
3240         struct protection_domain *domain = to_pdomain(dom);
3241         unsigned long flags;
3242         int levels, ret;
3243
3244         if (pasids <= 0 || pasids > (PASID_MASK + 1))
3245                 return -EINVAL;
3246
3247         /* Number of GCR3 table levels required */
3248         for (levels = 0; (pasids - 1) & ~0x1ff; pasids >>= 9)
3249                 levels += 1;
3250
3251         if (levels > amd_iommu_max_glx_val)
3252                 return -EINVAL;
3253
3254         spin_lock_irqsave(&domain->lock, flags);
3255
3256         /*
3257          * Save us all sanity checks whether devices already in the
3258          * domain support IOMMUv2. Just force that the domain has no
3259          * devices attached when it is switched into IOMMUv2 mode.
3260          */
3261         ret = -EBUSY;
3262         if (domain->dev_cnt > 0 || domain->flags & PD_IOMMUV2_MASK)
3263                 goto out;
3264
3265         ret = -ENOMEM;
3266         domain->gcr3_tbl = (void *)get_zeroed_page(GFP_ATOMIC);
3267         if (domain->gcr3_tbl == NULL)
3268                 goto out;
3269
3270         domain->glx      = levels;
3271         domain->flags   |= PD_IOMMUV2_MASK;
3272         domain->updated  = true;
3273
3274         update_domain(domain);
3275
3276         ret = 0;
3277
3278 out:
3279         spin_unlock_irqrestore(&domain->lock, flags);
3280
3281         return ret;
3282 }
3283 EXPORT_SYMBOL(amd_iommu_domain_enable_v2);
3284
3285 static int __flush_pasid(struct protection_domain *domain, int pasid,
3286                          u64 address, bool size)
3287 {
3288         struct iommu_dev_data *dev_data;
3289         struct iommu_cmd cmd;
3290         int i, ret;
3291
3292         if (!(domain->flags & PD_IOMMUV2_MASK))
3293                 return -EINVAL;
3294
3295         build_inv_iommu_pasid(&cmd, domain->id, pasid, address, size);
3296
3297         /*
3298          * IOMMU TLB needs to be flushed before Device TLB to
3299          * prevent device TLB refill from IOMMU TLB
3300          */
3301         for (i = 0; i < amd_iommus_present; ++i) {
3302                 if (domain->dev_iommu[i] == 0)
3303                         continue;
3304
3305                 ret = iommu_queue_command(amd_iommus[i], &cmd);
3306                 if (ret != 0)
3307                         goto out;
3308         }
3309
3310         /* Wait until IOMMU TLB flushes are complete */
3311         domain_flush_complete(domain);
3312
3313         /* Now flush device TLBs */
3314         list_for_each_entry(dev_data, &domain->dev_list, list) {
3315                 struct amd_iommu *iommu;
3316                 int qdep;
3317
3318                 /*
3319                    There might be non-IOMMUv2 capable devices in an IOMMUv2
3320                  * domain.
3321                  */
3322                 if (!dev_data->ats.enabled)
3323                         continue;
3324
3325                 qdep  = dev_data->ats.qdep;
3326                 iommu = amd_iommu_rlookup_table[dev_data->devid];
3327
3328                 build_inv_iotlb_pasid(&cmd, dev_data->devid, pasid,
3329                                       qdep, address, size);
3330
3331                 ret = iommu_queue_command(iommu, &cmd);
3332                 if (ret != 0)
3333                         goto out;
3334         }
3335
3336         /* Wait until all device TLBs are flushed */
3337         domain_flush_complete(domain);
3338
3339         ret = 0;
3340
3341 out:
3342
3343         return ret;
3344 }
3345
3346 static int __amd_iommu_flush_page(struct protection_domain *domain, int pasid,
3347                                   u64 address)
3348 {
3349         INC_STATS_COUNTER(invalidate_iotlb);
3350
3351         return __flush_pasid(domain, pasid, address, false);
3352 }
3353
3354 int amd_iommu_flush_page(struct iommu_domain *dom, int pasid,
3355                          u64 address)
3356 {
3357         struct protection_domain *domain = to_pdomain(dom);
3358         unsigned long flags;
3359         int ret;
3360
3361         spin_lock_irqsave(&domain->lock, flags);
3362         ret = __amd_iommu_flush_page(domain, pasid, address);
3363         spin_unlock_irqrestore(&domain->lock, flags);
3364
3365         return ret;
3366 }
3367 EXPORT_SYMBOL(amd_iommu_flush_page);
3368
3369 static int __amd_iommu_flush_tlb(struct protection_domain *domain, int pasid)
3370 {
3371         INC_STATS_COUNTER(invalidate_iotlb_all);
3372
3373         return __flush_pasid(domain, pasid, CMD_INV_IOMMU_ALL_PAGES_ADDRESS,
3374                              true);
3375 }
3376
3377 int amd_iommu_flush_tlb(struct iommu_domain *dom, int pasid)
3378 {
3379         struct protection_domain *domain = to_pdomain(dom);
3380         unsigned long flags;
3381         int ret;
3382
3383         spin_lock_irqsave(&domain->lock, flags);
3384         ret = __amd_iommu_flush_tlb(domain, pasid);
3385         spin_unlock_irqrestore(&domain->lock, flags);
3386
3387         return ret;
3388 }
3389 EXPORT_SYMBOL(amd_iommu_flush_tlb);
3390
3391 static u64 *__get_gcr3_pte(u64 *root, int level, int pasid, bool alloc)
3392 {
3393         int index;
3394         u64 *pte;
3395
3396         while (true) {
3397
3398                 index = (pasid >> (9 * level)) & 0x1ff;
3399                 pte   = &root[index];
3400
3401                 if (level == 0)
3402                         break;
3403
3404                 if (!(*pte & GCR3_VALID)) {
3405                         if (!alloc)
3406                                 return NULL;
3407
3408                         root = (void *)get_zeroed_page(GFP_ATOMIC);
3409                         if (root == NULL)
3410                                 return NULL;
3411
3412                         *pte = __pa(root) | GCR3_VALID;
3413                 }
3414
3415                 root = __va(*pte & PAGE_MASK);
3416
3417                 level -= 1;
3418         }
3419
3420         return pte;
3421 }
3422
3423 static int __set_gcr3(struct protection_domain *domain, int pasid,
3424                       unsigned long cr3)
3425 {
3426         u64 *pte;
3427
3428         if (domain->mode != PAGE_MODE_NONE)
3429                 return -EINVAL;
3430
3431         pte = __get_gcr3_pte(domain->gcr3_tbl, domain->glx, pasid, true);
3432         if (pte == NULL)
3433                 return -ENOMEM;
3434
3435         *pte = (cr3 & PAGE_MASK) | GCR3_VALID;
3436
3437         return __amd_iommu_flush_tlb(domain, pasid);
3438 }
3439
3440 static int __clear_gcr3(struct protection_domain *domain, int pasid)
3441 {
3442         u64 *pte;
3443
3444         if (domain->mode != PAGE_MODE_NONE)
3445                 return -EINVAL;
3446
3447         pte = __get_gcr3_pte(domain->gcr3_tbl, domain->glx, pasid, false);
3448         if (pte == NULL)
3449                 return 0;
3450
3451         *pte = 0;
3452
3453         return __amd_iommu_flush_tlb(domain, pasid);
3454 }
3455
3456 int amd_iommu_domain_set_gcr3(struct iommu_domain *dom, int pasid,
3457                               unsigned long cr3)
3458 {
3459         struct protection_domain *domain = to_pdomain(dom);
3460         unsigned long flags;
3461         int ret;
3462
3463         spin_lock_irqsave(&domain->lock, flags);
3464         ret = __set_gcr3(domain, pasid, cr3);
3465         spin_unlock_irqrestore(&domain->lock, flags);
3466
3467         return ret;
3468 }
3469 EXPORT_SYMBOL(amd_iommu_domain_set_gcr3);
3470
3471 int amd_iommu_domain_clear_gcr3(struct iommu_domain *dom, int pasid)
3472 {
3473         struct protection_domain *domain = to_pdomain(dom);
3474         unsigned long flags;
3475         int ret;
3476
3477         spin_lock_irqsave(&domain->lock, flags);
3478         ret = __clear_gcr3(domain, pasid);
3479         spin_unlock_irqrestore(&domain->lock, flags);
3480
3481         return ret;
3482 }
3483 EXPORT_SYMBOL(amd_iommu_domain_clear_gcr3);
3484
3485 int amd_iommu_complete_ppr(struct pci_dev *pdev, int pasid,
3486                            int status, int tag)
3487 {
3488         struct iommu_dev_data *dev_data;
3489         struct amd_iommu *iommu;
3490         struct iommu_cmd cmd;
3491
3492         INC_STATS_COUNTER(complete_ppr);
3493
3494         dev_data = get_dev_data(&pdev->dev);
3495         iommu    = amd_iommu_rlookup_table[dev_data->devid];
3496
3497         build_complete_ppr(&cmd, dev_data->devid, pasid, status,
3498                            tag, dev_data->pri_tlp);
3499
3500         return iommu_queue_command(iommu, &cmd);
3501 }
3502 EXPORT_SYMBOL(amd_iommu_complete_ppr);
3503
3504 struct iommu_domain *amd_iommu_get_v2_domain(struct pci_dev *pdev)
3505 {
3506         struct protection_domain *pdomain;
3507
3508         pdomain = get_domain(&pdev->dev);
3509         if (IS_ERR(pdomain))
3510                 return NULL;
3511
3512         /* Only return IOMMUv2 domains */
3513         if (!(pdomain->flags & PD_IOMMUV2_MASK))
3514                 return NULL;
3515
3516         return &pdomain->domain;
3517 }
3518 EXPORT_SYMBOL(amd_iommu_get_v2_domain);
3519
3520 void amd_iommu_enable_device_erratum(struct pci_dev *pdev, u32 erratum)
3521 {
3522         struct iommu_dev_data *dev_data;
3523
3524         if (!amd_iommu_v2_supported())
3525                 return;
3526
3527         dev_data = get_dev_data(&pdev->dev);
3528         dev_data->errata |= (1 << erratum);
3529 }
3530 EXPORT_SYMBOL(amd_iommu_enable_device_erratum);
3531
3532 int amd_iommu_device_info(struct pci_dev *pdev,
3533                           struct amd_iommu_device_info *info)
3534 {
3535         int max_pasids;
3536         int pos;
3537
3538         if (pdev == NULL || info == NULL)
3539                 return -EINVAL;
3540
3541         if (!amd_iommu_v2_supported())
3542                 return -EINVAL;
3543
3544         memset(info, 0, sizeof(*info));
3545
3546         pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_ATS);
3547         if (pos)
3548                 info->flags |= AMD_IOMMU_DEVICE_FLAG_ATS_SUP;
3549
3550         pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PRI);
3551         if (pos)
3552                 info->flags |= AMD_IOMMU_DEVICE_FLAG_PRI_SUP;
3553
3554         pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_PASID);
3555         if (pos) {
3556                 int features;
3557
3558                 max_pasids = 1 << (9 * (amd_iommu_max_glx_val + 1));
3559                 max_pasids = min(max_pasids, (1 << 20));
3560
3561                 info->flags |= AMD_IOMMU_DEVICE_FLAG_PASID_SUP;
3562                 info->max_pasids = min(pci_max_pasids(pdev), max_pasids);
3563
3564                 features = pci_pasid_features(pdev);
3565                 if (features & PCI_PASID_CAP_EXEC)
3566                         info->flags |= AMD_IOMMU_DEVICE_FLAG_EXEC_SUP;
3567                 if (features & PCI_PASID_CAP_PRIV)
3568                         info->flags |= AMD_IOMMU_DEVICE_FLAG_PRIV_SUP;
3569         }
3570
3571         return 0;
3572 }
3573 EXPORT_SYMBOL(amd_iommu_device_info);
3574
3575 #ifdef CONFIG_IRQ_REMAP
3576
3577 /*****************************************************************************
3578  *
3579  * Interrupt Remapping Implementation
3580  *
3581  *****************************************************************************/
3582
3583 union irte {
3584         u32 val;
3585         struct {
3586                 u32 valid       : 1,
3587                     no_fault    : 1,
3588                     int_type    : 3,
3589                     rq_eoi      : 1,
3590                     dm          : 1,
3591                     rsvd_1      : 1,
3592                     destination : 8,
3593                     vector      : 8,
3594                     rsvd_2      : 8;
3595         } fields;
3596 };
3597
3598 struct irq_2_irte {
3599         u16 devid; /* Device ID for IRTE table */
3600         u16 index; /* Index into IRTE table*/
3601 };
3602
3603 struct amd_ir_data {
3604         struct irq_2_irte                       irq_2_irte;
3605         union irte                              irte_entry;
3606         union {
3607                 struct msi_msg                  msi_entry;
3608         };
3609 };
3610
3611 static struct irq_chip amd_ir_chip;
3612
3613 #define DTE_IRQ_PHYS_ADDR_MASK  (((1ULL << 45)-1) << 6)
3614 #define DTE_IRQ_REMAP_INTCTL    (2ULL << 60)
3615 #define DTE_IRQ_TABLE_LEN       (8ULL << 1)
3616 #define DTE_IRQ_REMAP_ENABLE    1ULL
3617
3618 static void set_dte_irq_entry(u16 devid, struct irq_remap_table *table)
3619 {
3620         u64 dte;
3621
3622         dte     = amd_iommu_dev_table[devid].data[2];
3623         dte     &= ~DTE_IRQ_PHYS_ADDR_MASK;
3624         dte     |= virt_to_phys(table->table);
3625         dte     |= DTE_IRQ_REMAP_INTCTL;
3626         dte     |= DTE_IRQ_TABLE_LEN;
3627         dte     |= DTE_IRQ_REMAP_ENABLE;
3628
3629         amd_iommu_dev_table[devid].data[2] = dte;
3630 }
3631
3632 #define IRTE_ALLOCATED (~1U)
3633
3634 static struct irq_remap_table *get_irq_table(u16 devid, bool ioapic)
3635 {
3636         struct irq_remap_table *table = NULL;
3637         struct amd_iommu *iommu;
3638         unsigned long flags;
3639         u16 alias;
3640
3641         write_lock_irqsave(&amd_iommu_devtable_lock, flags);
3642
3643         iommu = amd_iommu_rlookup_table[devid];
3644         if (!iommu)
3645                 goto out_unlock;
3646
3647         table = irq_lookup_table[devid];
3648         if (table)
3649                 goto out;
3650
3651         alias = amd_iommu_alias_table[devid];
3652         table = irq_lookup_table[alias];
3653         if (table) {
3654                 irq_lookup_table[devid] = table;
3655                 set_dte_irq_entry(devid, table);
3656                 iommu_flush_dte(iommu, devid);
3657                 goto out;
3658         }
3659
3660         /* Nothing there yet, allocate new irq remapping table */
3661         table = kzalloc(sizeof(*table), GFP_ATOMIC);
3662         if (!table)
3663                 goto out;
3664
3665         /* Initialize table spin-lock */
3666         spin_lock_init(&table->lock);
3667
3668         if (ioapic)
3669                 /* Keep the first 32 indexes free for IOAPIC interrupts */
3670                 table->min_index = 32;
3671
3672         table->table = kmem_cache_alloc(amd_iommu_irq_cache, GFP_ATOMIC);
3673         if (!table->table) {
3674                 kfree(table);
3675                 table = NULL;
3676                 goto out;
3677         }
3678
3679         memset(table->table, 0, MAX_IRQS_PER_TABLE * sizeof(u32));
3680
3681         if (ioapic) {
3682                 int i;
3683
3684                 for (i = 0; i < 32; ++i)
3685                         table->table[i] = IRTE_ALLOCATED;
3686         }
3687
3688         irq_lookup_table[devid] = table;
3689         set_dte_irq_entry(devid, table);
3690         iommu_flush_dte(iommu, devid);
3691         if (devid != alias) {
3692                 irq_lookup_table[alias] = table;
3693                 set_dte_irq_entry(alias, table);
3694                 iommu_flush_dte(iommu, alias);
3695         }
3696
3697 out:
3698         iommu_completion_wait(iommu);
3699
3700 out_unlock:
3701         write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
3702
3703         return table;
3704 }
3705
3706 static int alloc_irq_index(u16 devid, int count)
3707 {
3708         struct irq_remap_table *table;
3709         unsigned long flags;
3710         int index, c;
3711
3712         table = get_irq_table(devid, false);
3713         if (!table)
3714                 return -ENODEV;
3715
3716         spin_lock_irqsave(&table->lock, flags);
3717
3718         /* Scan table for free entries */
3719         for (c = 0, index = table->min_index;
3720              index < MAX_IRQS_PER_TABLE;
3721              ++index) {
3722                 if (table->table[index] == 0)
3723                         c += 1;
3724                 else
3725                         c = 0;
3726
3727                 if (c == count) {
3728                         for (; c != 0; --c)
3729                                 table->table[index - c + 1] = IRTE_ALLOCATED;
3730
3731                         index -= count - 1;
3732                         goto out;
3733                 }
3734         }
3735
3736         index = -ENOSPC;
3737
3738 out:
3739         spin_unlock_irqrestore(&table->lock, flags);
3740
3741         return index;
3742 }
3743
3744 static int modify_irte(u16 devid, int index, union irte irte)
3745 {
3746         struct irq_remap_table *table;
3747         struct amd_iommu *iommu;
3748         unsigned long flags;
3749
3750         iommu = amd_iommu_rlookup_table[devid];
3751         if (iommu == NULL)
3752                 return -EINVAL;
3753
3754         table = get_irq_table(devid, false);
3755         if (!table)
3756                 return -ENOMEM;
3757
3758         spin_lock_irqsave(&table->lock, flags);
3759         table->table[index] = irte.val;
3760         spin_unlock_irqrestore(&table->lock, flags);
3761
3762         iommu_flush_irt(iommu, devid);
3763         iommu_completion_wait(iommu);
3764
3765         return 0;
3766 }
3767
3768 static void free_irte(u16 devid, int index)
3769 {
3770         struct irq_remap_table *table;
3771         struct amd_iommu *iommu;
3772         unsigned long flags;
3773
3774         iommu = amd_iommu_rlookup_table[devid];
3775         if (iommu == NULL)
3776                 return;
3777
3778         table = get_irq_table(devid, false);
3779         if (!table)
3780                 return;
3781
3782         spin_lock_irqsave(&table->lock, flags);
3783         table->table[index] = 0;
3784         spin_unlock_irqrestore(&table->lock, flags);
3785
3786         iommu_flush_irt(iommu, devid);
3787         iommu_completion_wait(iommu);
3788 }
3789
3790 static int get_devid(struct irq_alloc_info *info)
3791 {
3792         int devid = -1;
3793
3794         switch (info->type) {
3795         case X86_IRQ_ALLOC_TYPE_IOAPIC:
3796                 devid     = get_ioapic_devid(info->ioapic_id);
3797                 break;
3798         case X86_IRQ_ALLOC_TYPE_HPET:
3799                 devid     = get_hpet_devid(info->hpet_id);
3800                 break;
3801         case X86_IRQ_ALLOC_TYPE_MSI:
3802         case X86_IRQ_ALLOC_TYPE_MSIX:
3803                 devid = get_device_id(&info->msi_dev->dev);
3804                 break;
3805         default:
3806                 BUG_ON(1);
3807                 break;
3808         }
3809
3810         return devid;
3811 }
3812
3813 static struct irq_domain *get_ir_irq_domain(struct irq_alloc_info *info)
3814 {
3815         struct amd_iommu *iommu;
3816         int devid;
3817
3818         if (!info)
3819                 return NULL;
3820
3821         devid = get_devid(info);
3822         if (devid >= 0) {
3823                 iommu = amd_iommu_rlookup_table[devid];
3824                 if (iommu)
3825                         return iommu->ir_domain;
3826         }
3827
3828         return NULL;
3829 }
3830
3831 static struct irq_domain *get_irq_domain(struct irq_alloc_info *info)
3832 {
3833         struct amd_iommu *iommu;
3834         int devid;
3835
3836         if (!info)
3837                 return NULL;
3838
3839         switch (info->type) {
3840         case X86_IRQ_ALLOC_TYPE_MSI:
3841         case X86_IRQ_ALLOC_TYPE_MSIX:
3842                 devid = get_device_id(&info->msi_dev->dev);
3843                 if (devid >= 0) {
3844                         iommu = amd_iommu_rlookup_table[devid];
3845                         if (iommu)
3846                                 return iommu->msi_domain;
3847                 }
3848                 break;
3849         default:
3850                 break;
3851         }
3852
3853         return NULL;
3854 }
3855
3856 struct irq_remap_ops amd_iommu_irq_ops = {
3857         .prepare                = amd_iommu_prepare,
3858         .enable                 = amd_iommu_enable,
3859         .disable                = amd_iommu_disable,
3860         .reenable               = amd_iommu_reenable,
3861         .enable_faulting        = amd_iommu_enable_faulting,
3862         .get_ir_irq_domain      = get_ir_irq_domain,
3863         .get_irq_domain         = get_irq_domain,
3864 };
3865
3866 static void irq_remapping_prepare_irte(struct amd_ir_data *data,
3867                                        struct irq_cfg *irq_cfg,
3868                                        struct irq_alloc_info *info,
3869                                        int devid, int index, int sub_handle)
3870 {
3871         struct irq_2_irte *irte_info = &data->irq_2_irte;
3872         struct msi_msg *msg = &data->msi_entry;
3873         union irte *irte = &data->irte_entry;
3874         struct IO_APIC_route_entry *entry;
3875
3876         data->irq_2_irte.devid = devid;
3877         data->irq_2_irte.index = index + sub_handle;
3878
3879         /* Setup IRTE for IOMMU */
3880         irte->val = 0;
3881         irte->fields.vector      = irq_cfg->vector;
3882         irte->fields.int_type    = apic->irq_delivery_mode;
3883         irte->fields.destination = irq_cfg->dest_apicid;
3884         irte->fields.dm          = apic->irq_dest_mode;
3885         irte->fields.valid       = 1;
3886
3887         switch (info->type) {
3888         case X86_IRQ_ALLOC_TYPE_IOAPIC:
3889                 /* Setup IOAPIC entry */
3890                 entry = info->ioapic_entry;
3891                 info->ioapic_entry = NULL;
3892                 memset(entry, 0, sizeof(*entry));
3893                 entry->vector        = index;
3894                 entry->mask          = 0;
3895                 entry->trigger       = info->ioapic_trigger;
3896                 entry->polarity      = info->ioapic_polarity;
3897                 /* Mask level triggered irqs. */
3898                 if (info->ioapic_trigger)
3899                         entry->mask = 1;
3900                 break;
3901
3902         case X86_IRQ_ALLOC_TYPE_HPET:
3903         case X86_IRQ_ALLOC_TYPE_MSI:
3904         case X86_IRQ_ALLOC_TYPE_MSIX:
3905                 msg->address_hi = MSI_ADDR_BASE_HI;
3906                 msg->address_lo = MSI_ADDR_BASE_LO;
3907                 msg->data = irte_info->index;
3908                 break;
3909
3910         default:
3911                 BUG_ON(1);
3912                 break;
3913         }
3914 }
3915
3916 static int irq_remapping_alloc(struct irq_domain *domain, unsigned int virq,
3917                                unsigned int nr_irqs, void *arg)
3918 {
3919         struct irq_alloc_info *info = arg;
3920         struct irq_data *irq_data;
3921         struct amd_ir_data *data;
3922         struct irq_cfg *cfg;
3923         int i, ret, devid;
3924         int index = -1;
3925
3926         if (!info)
3927                 return -EINVAL;
3928         if (nr_irqs > 1 && info->type != X86_IRQ_ALLOC_TYPE_MSI &&
3929             info->type != X86_IRQ_ALLOC_TYPE_MSIX)
3930                 return -EINVAL;
3931
3932         /*
3933          * With IRQ remapping enabled, don't need contiguous CPU vectors
3934          * to support multiple MSI interrupts.
3935          */
3936         if (info->type == X86_IRQ_ALLOC_TYPE_MSI)
3937                 info->flags &= ~X86_IRQ_ALLOC_CONTIGUOUS_VECTORS;
3938
3939         devid = get_devid(info);
3940         if (devid < 0)
3941                 return -EINVAL;
3942
3943         ret = irq_domain_alloc_irqs_parent(domain, virq, nr_irqs, arg);
3944         if (ret < 0)
3945                 return ret;
3946
3947         if (info->type == X86_IRQ_ALLOC_TYPE_IOAPIC) {
3948                 if (get_irq_table(devid, true))
3949                         index = info->ioapic_pin;
3950                 else
3951                         ret = -ENOMEM;
3952         } else {
3953                 index = alloc_irq_index(devid, nr_irqs);
3954         }
3955         if (index < 0) {
3956                 pr_warn("Failed to allocate IRTE\n");
3957                 goto out_free_parent;
3958         }
3959
3960         for (i = 0; i < nr_irqs; i++) {
3961                 irq_data = irq_domain_get_irq_data(domain, virq + i);
3962                 cfg = irqd_cfg(irq_data);
3963                 if (!irq_data || !cfg) {
3964                         ret = -EINVAL;
3965                         goto out_free_data;
3966                 }
3967
3968                 ret = -ENOMEM;
3969                 data = kzalloc(sizeof(*data), GFP_KERNEL);
3970                 if (!data)
3971                         goto out_free_data;
3972
3973                 irq_data->hwirq = (devid << 16) + i;
3974                 irq_data->chip_data = data;
3975                 irq_data->chip = &amd_ir_chip;
3976                 irq_remapping_prepare_irte(data, cfg, info, devid, index, i);
3977                 irq_set_status_flags(virq + i, IRQ_MOVE_PCNTXT);
3978         }
3979
3980         return 0;
3981
3982 out_free_data:
3983         for (i--; i >= 0; i--) {
3984                 irq_data = irq_domain_get_irq_data(domain, virq + i);
3985                 if (irq_data)
3986                         kfree(irq_data->chip_data);
3987         }
3988         for (i = 0; i < nr_irqs; i++)
3989                 free_irte(devid, index + i);
3990 out_free_parent:
3991         irq_domain_free_irqs_common(domain, virq, nr_irqs);
3992         return ret;
3993 }
3994
3995 static void irq_remapping_free(struct irq_domain *domain, unsigned int virq,
3996                                unsigned int nr_irqs)
3997 {
3998         struct irq_2_irte *irte_info;
3999         struct irq_data *irq_data;
4000         struct amd_ir_data *data;
4001         int i;
4002
4003         for (i = 0; i < nr_irqs; i++) {
4004                 irq_data = irq_domain_get_irq_data(domain, virq  + i);
4005                 if (irq_data && irq_data->chip_data) {
4006                         data = irq_data->chip_data;
4007                         irte_info = &data->irq_2_irte;
4008                         free_irte(irte_info->devid, irte_info->index);
4009                         kfree(data);
4010                 }
4011         }
4012         irq_domain_free_irqs_common(domain, virq, nr_irqs);
4013 }
4014
4015 static void irq_remapping_activate(struct irq_domain *domain,
4016                                    struct irq_data *irq_data)
4017 {
4018         struct amd_ir_data *data = irq_data->chip_data;
4019         struct irq_2_irte *irte_info = &data->irq_2_irte;
4020
4021         modify_irte(irte_info->devid, irte_info->index, data->irte_entry);
4022 }
4023
4024 static void irq_remapping_deactivate(struct irq_domain *domain,
4025                                      struct irq_data *irq_data)
4026 {
4027         struct amd_ir_data *data = irq_data->chip_data;
4028         struct irq_2_irte *irte_info = &data->irq_2_irte;
4029         union irte entry;
4030
4031         entry.val = 0;
4032         modify_irte(irte_info->devid, irte_info->index, data->irte_entry);
4033 }
4034
4035 static struct irq_domain_ops amd_ir_domain_ops = {
4036         .alloc = irq_remapping_alloc,
4037         .free = irq_remapping_free,
4038         .activate = irq_remapping_activate,
4039         .deactivate = irq_remapping_deactivate,
4040 };
4041
4042 static int amd_ir_set_affinity(struct irq_data *data,
4043                                const struct cpumask *mask, bool force)
4044 {
4045         struct amd_ir_data *ir_data = data->chip_data;
4046         struct irq_2_irte *irte_info = &ir_data->irq_2_irte;
4047         struct irq_cfg *cfg = irqd_cfg(data);
4048         struct irq_data *parent = data->parent_data;
4049         int ret;
4050
4051         ret = parent->chip->irq_set_affinity(parent, mask, force);
4052         if (ret < 0 || ret == IRQ_SET_MASK_OK_DONE)
4053                 return ret;
4054
4055         /*
4056          * Atomically updates the IRTE with the new destination, vector
4057          * and flushes the interrupt entry cache.
4058          */
4059         ir_data->irte_entry.fields.vector = cfg->vector;
4060         ir_data->irte_entry.fields.destination = cfg->dest_apicid;
4061         modify_irte(irte_info->devid, irte_info->index, ir_data->irte_entry);
4062
4063         /*
4064          * After this point, all the interrupts will start arriving
4065          * at the new destination. So, time to cleanup the previous
4066          * vector allocation.
4067          */
4068         send_cleanup_vector(cfg);
4069
4070         return IRQ_SET_MASK_OK_DONE;
4071 }
4072
4073 static void ir_compose_msi_msg(struct irq_data *irq_data, struct msi_msg *msg)
4074 {
4075         struct amd_ir_data *ir_data = irq_data->chip_data;
4076
4077         *msg = ir_data->msi_entry;
4078 }
4079
4080 static struct irq_chip amd_ir_chip = {
4081         .irq_ack = ir_ack_apic_edge,
4082         .irq_set_affinity = amd_ir_set_affinity,
4083         .irq_compose_msi_msg = ir_compose_msi_msg,
4084 };
4085
4086 int amd_iommu_create_irq_domain(struct amd_iommu *iommu)
4087 {
4088         iommu->ir_domain = irq_domain_add_tree(NULL, &amd_ir_domain_ops, iommu);
4089         if (!iommu->ir_domain)
4090                 return -ENOMEM;
4091
4092         iommu->ir_domain->parent = arch_get_ir_parent_domain();
4093         iommu->msi_domain = arch_create_msi_irq_domain(iommu->ir_domain);
4094
4095         return 0;
4096 }
4097 #endif