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