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