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