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