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