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