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