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