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