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