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