OSDN Git Service

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