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