xref: /linux/drivers/iommu/amd/iommu.c (revision f16d85cd3de9d0c761b74155b4cbe2f20d3dcf80)
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/cleanup.h>
15 #include <linux/pci-ats.h>
16 #include <linux/bitmap.h>
17 #include <linux/slab.h>
18 #include <linux/string_choices.h>
19 #include <linux/debugfs.h>
20 #include <linux/scatterlist.h>
21 #include <linux/dma-map-ops.h>
22 #include <linux/dma-direct.h>
23 #include <linux/idr.h>
24 #include <linux/iommu-helper.h>
25 #include <linux/delay.h>
26 #include <linux/amd-iommu.h>
27 #include <linux/notifier.h>
28 #include <linux/export.h>
29 #include <linux/irq.h>
30 #include <linux/irqchip/irq-msi-lib.h>
31 #include <linux/msi.h>
32 #include <linux/irqdomain.h>
33 #include <linux/percpu.h>
34 #include <linux/cc_platform.h>
35 #include <asm/irq_remapping.h>
36 #include <asm/io_apic.h>
37 #include <asm/apic.h>
38 #include <asm/hw_irq.h>
39 #include <asm/proto.h>
40 #include <asm/iommu.h>
41 #include <asm/gart.h>
42 #include <asm/dma.h>
43 #include <uapi/linux/iommufd.h>
44 #include <linux/generic_pt/iommu.h>
45 
46 #include "amd_iommu.h"
47 #include "iommufd.h"
48 #include "../irq_remapping.h"
49 #include "../iommu-pages.h"
50 
51 #define CMD_SET_TYPE(cmd, t) ((cmd)->data[1] |= ((t) << 28))
52 
53 /* Reserved IOVA ranges */
54 #define HT_RANGE_START		(0xfd00000000ULL)
55 #define HT_RANGE_END		(0xffffffffffULL)
56 
57 LIST_HEAD(ioapic_map);
58 LIST_HEAD(hpet_map);
59 LIST_HEAD(acpihid_map);
60 
61 const struct iommu_ops amd_iommu_ops;
62 
63 int amd_iommu_max_glx_val = -1;
64 
65 /*
66  * AMD IOMMU allows up to 2^16 different protection domains. This is a bitmap
67  * to know which ones are already in use.
68  */
69 DEFINE_IDA(pdom_ids);
70 
71 static int amd_iommu_attach_device(struct iommu_domain *dom, struct device *dev,
72 				   struct iommu_domain *old);
73 
74 static void set_dte_entry(struct amd_iommu *iommu,
75 			  struct iommu_dev_data *dev_data,
76 			  phys_addr_t top_paddr, unsigned int top_level);
77 
78 static int device_flush_dte(struct iommu_dev_data *dev_data);
79 
80 static void amd_iommu_change_top(struct pt_iommu *iommu_table,
81 				 phys_addr_t top_paddr, unsigned int top_level);
82 
83 static void iommu_flush_dte_sync(struct amd_iommu *iommu, u16 devid);
84 
85 static struct iommu_dev_data *find_dev_data(struct amd_iommu *iommu, u16 devid);
86 static bool amd_iommu_enforce_cache_coherency(struct iommu_domain *domain);
87 static int amd_iommu_set_dirty_tracking(struct iommu_domain *domain,
88 					bool enable);
89 
90 static void clone_aliases(struct amd_iommu *iommu, struct device *dev);
91 
92 static int iommu_completion_wait(struct amd_iommu *iommu);
93 
94 static int __amd_iommu_complete_ppr(struct device *dev, u32 pasid,
95 				    int status, int tag, bool gn);
96 
97 /****************************************************************************
98  *
99  * Helper functions
100  *
101  ****************************************************************************/
102 
103 static __always_inline void amd_iommu_atomic128_set(__int128 *ptr, __int128 val)
104 {
105 	/*
106 	 * Note:
107 	 * We use arch_cmpxchg128_local() because:
108 	 * - Need cmpxchg16b instruction mainly for 128-bit store to DTE
109 	 *   (not necessary for cmpxchg since this function is already
110 	 *   protected by a spin_lock for this DTE).
111 	 * - Neither need LOCK_PREFIX nor try loop because of the spin_lock.
112 	 */
113 	arch_cmpxchg128_local(ptr, *ptr, val);
114 }
115 
116 static void write_dte_upper128(struct dev_table_entry *ptr, struct dev_table_entry *new)
117 {
118 	struct dev_table_entry old;
119 
120 	old.data128[1] = ptr->data128[1];
121 	/*
122 	 * Preserve DTE_DATA2_INTR_MASK. This needs to be
123 	 * done here since it requires to be inside
124 	 * spin_lock(&dev_data->dte_lock) context.
125 	 */
126 	new->data[2] &= ~DTE_DATA2_INTR_MASK;
127 	new->data[2] |= old.data[2] & DTE_DATA2_INTR_MASK;
128 
129 	amd_iommu_atomic128_set(&ptr->data128[1], new->data128[1]);
130 }
131 
132 static void write_dte_lower128(struct dev_table_entry *ptr, struct dev_table_entry *new)
133 {
134 	amd_iommu_atomic128_set(&ptr->data128[0], new->data128[0]);
135 }
136 
137 /*
138  * Note:
139  * IOMMU reads the entire Device Table entry in a single 256-bit transaction
140  * but the driver is programming DTE using 2 128-bit cmpxchg. So, the driver
141  * need to ensure the following:
142  *   - DTE[V|GV] bit is being written last when setting.
143  *   - DTE[V|GV] bit is being written first when clearing.
144  *
145  * This function is used only by code, which updates DMA translation part of the DTE.
146  * So, only consider control bits related to DMA when updating the entry.
147  */
148 static void update_dte256(struct amd_iommu *iommu, struct iommu_dev_data *dev_data,
149 			  struct dev_table_entry *new)
150 {
151 	unsigned long flags;
152 	struct dev_table_entry *dev_table = get_dev_table(iommu);
153 	struct dev_table_entry *ptr = &dev_table[dev_data->devid];
154 
155 	spin_lock_irqsave(&dev_data->dte_lock, flags);
156 
157 	if (!(ptr->data[0] & DTE_FLAG_V)) {
158 		/* Existing DTE is not valid. */
159 		write_dte_upper128(ptr, new);
160 		write_dte_lower128(ptr, new);
161 		iommu_flush_dte_sync(iommu, dev_data->devid);
162 	} else if (!(new->data[0] & DTE_FLAG_V)) {
163 		/* Existing DTE is valid. New DTE is not valid.  */
164 		write_dte_lower128(ptr, new);
165 		write_dte_upper128(ptr, new);
166 		iommu_flush_dte_sync(iommu, dev_data->devid);
167 	} else if (!FIELD_GET(DTE_FLAG_GV, ptr->data[0])) {
168 		/*
169 		 * Both DTEs are valid.
170 		 * Existing DTE has no guest page table.
171 		 */
172 		write_dte_upper128(ptr, new);
173 		write_dte_lower128(ptr, new);
174 		iommu_flush_dte_sync(iommu, dev_data->devid);
175 	} else if (!FIELD_GET(DTE_FLAG_GV, new->data[0])) {
176 		/*
177 		 * Both DTEs are valid.
178 		 * Existing DTE has guest page table,
179 		 * new DTE has no guest page table,
180 		 */
181 		write_dte_lower128(ptr, new);
182 		write_dte_upper128(ptr, new);
183 		iommu_flush_dte_sync(iommu, dev_data->devid);
184 	} else if (FIELD_GET(DTE_GPT_LEVEL_MASK, ptr->data[2]) !=
185 		   FIELD_GET(DTE_GPT_LEVEL_MASK, new->data[2])) {
186 		/*
187 		 * Both DTEs are valid and have guest page table,
188 		 * but have different number of levels. So, we need
189 		 * to upadte both upper and lower 128-bit value, which
190 		 * require disabling and flushing.
191 		 */
192 		struct dev_table_entry clear = {};
193 
194 		/* First disable DTE */
195 		write_dte_lower128(ptr, &clear);
196 		iommu_flush_dte_sync(iommu, dev_data->devid);
197 
198 		/* Then update DTE */
199 		write_dte_upper128(ptr, new);
200 		write_dte_lower128(ptr, new);
201 		iommu_flush_dte_sync(iommu, dev_data->devid);
202 	} else {
203 		/*
204 		 * Both DTEs are valid and have guest page table,
205 		 * and same number of levels. We just need to only
206 		 * update the lower 128-bit. So no need to disable DTE.
207 		 */
208 		write_dte_lower128(ptr, new);
209 	}
210 
211 	spin_unlock_irqrestore(&dev_data->dte_lock, flags);
212 }
213 
214 void amd_iommu_update_dte(struct amd_iommu *iommu,
215 			     struct iommu_dev_data *dev_data,
216 			     struct dev_table_entry *new)
217 {
218 	update_dte256(iommu, dev_data, new);
219 	clone_aliases(iommu, dev_data->dev);
220 	device_flush_dte(dev_data);
221 	iommu_completion_wait(iommu);
222 }
223 
224 static void get_dte256(struct amd_iommu *iommu, struct iommu_dev_data *dev_data,
225 		      struct dev_table_entry *dte)
226 {
227 	unsigned long flags;
228 	struct dev_table_entry *ptr;
229 	struct dev_table_entry *dev_table = get_dev_table(iommu);
230 
231 	ptr = &dev_table[dev_data->devid];
232 
233 	spin_lock_irqsave(&dev_data->dte_lock, flags);
234 	dte->data128[0] = ptr->data128[0];
235 	dte->data128[1] = ptr->data128[1];
236 	spin_unlock_irqrestore(&dev_data->dte_lock, flags);
237 }
238 
239 static inline bool pdom_is_v2_pgtbl_mode(struct protection_domain *pdom)
240 {
241 	return (pdom && (pdom->pd_mode == PD_MODE_V2));
242 }
243 
244 static inline bool pdom_is_in_pt_mode(struct protection_domain *pdom)
245 {
246 	return (pdom->domain.type == IOMMU_DOMAIN_IDENTITY);
247 }
248 
249 /*
250  * We cannot support PASID w/ existing v1 page table in the same domain
251  * since it will be nested. However, existing domain w/ v2 page table
252  * or passthrough mode can be used for PASID.
253  */
254 static inline bool pdom_is_sva_capable(struct protection_domain *pdom)
255 {
256 	return pdom_is_v2_pgtbl_mode(pdom) || pdom_is_in_pt_mode(pdom);
257 }
258 
259 static inline int get_acpihid_device_id(struct device *dev,
260 					struct acpihid_map_entry **entry)
261 {
262 	struct acpi_device *adev = ACPI_COMPANION(dev);
263 	struct acpihid_map_entry *p, *p1 = NULL;
264 	int hid_count = 0;
265 	bool fw_bug;
266 
267 	if (!adev)
268 		return -ENODEV;
269 
270 	list_for_each_entry(p, &acpihid_map, list) {
271 		if (acpi_dev_hid_uid_match(adev, p->hid,
272 					   p->uid[0] ? p->uid : NULL)) {
273 			p1 = p;
274 			fw_bug = false;
275 			hid_count = 1;
276 			break;
277 		}
278 
279 		/*
280 		 * Count HID matches w/o UID, raise FW_BUG but allow exactly one match
281 		 */
282 		if (acpi_dev_hid_match(adev, p->hid)) {
283 			p1 = p;
284 			hid_count++;
285 			fw_bug = true;
286 		}
287 	}
288 
289 	if (!p1)
290 		return -EINVAL;
291 	if (fw_bug)
292 		dev_err_once(dev, FW_BUG "No ACPI device matched UID, but %d device%s matched HID.\n",
293 			     hid_count, str_plural(hid_count));
294 	if (hid_count > 1)
295 		return -EINVAL;
296 	if (entry)
297 		*entry = p1;
298 
299 	return p1->devid;
300 }
301 
302 static inline int get_device_sbdf_id(struct device *dev)
303 {
304 	int sbdf;
305 
306 	if (dev_is_pci(dev))
307 		sbdf = get_pci_sbdf_id(to_pci_dev(dev));
308 	else
309 		sbdf = get_acpihid_device_id(dev, NULL);
310 
311 	return sbdf;
312 }
313 
314 struct dev_table_entry *get_dev_table(struct amd_iommu *iommu)
315 {
316 	struct dev_table_entry *dev_table;
317 	struct amd_iommu_pci_seg *pci_seg = iommu->pci_seg;
318 
319 	BUG_ON(pci_seg == NULL);
320 	dev_table = pci_seg->dev_table;
321 	BUG_ON(dev_table == NULL);
322 
323 	return dev_table;
324 }
325 
326 static inline u16 get_device_segment(struct device *dev)
327 {
328 	u16 seg;
329 
330 	if (dev_is_pci(dev)) {
331 		struct pci_dev *pdev = to_pci_dev(dev);
332 
333 		seg = pci_domain_nr(pdev->bus);
334 	} else {
335 		u32 devid = get_acpihid_device_id(dev, NULL);
336 
337 		seg = PCI_SBDF_TO_SEGID(devid);
338 	}
339 
340 	return seg;
341 }
342 
343 /* Writes the specific IOMMU for a device into the PCI segment rlookup table */
344 void amd_iommu_set_rlookup_table(struct amd_iommu *iommu, u16 devid)
345 {
346 	struct amd_iommu_pci_seg *pci_seg = iommu->pci_seg;
347 
348 	pci_seg->rlookup_table[devid] = iommu;
349 }
350 
351 static struct amd_iommu *__rlookup_amd_iommu(u16 seg, u16 devid)
352 {
353 	struct amd_iommu_pci_seg *pci_seg;
354 
355 	for_each_pci_segment(pci_seg) {
356 		if (pci_seg->id != seg)
357 			continue;
358 		/* IVRS may not describe every device on the bus */
359 		if (devid > pci_seg->last_bdf)
360 			return NULL;
361 		return pci_seg->rlookup_table[devid];
362 	}
363 	return NULL;
364 }
365 
366 static struct amd_iommu *rlookup_amd_iommu(struct device *dev)
367 {
368 	u16 seg = get_device_segment(dev);
369 	int devid = get_device_sbdf_id(dev);
370 
371 	if (devid < 0)
372 		return NULL;
373 	return __rlookup_amd_iommu(seg, PCI_SBDF_TO_DEVID(devid));
374 }
375 
376 static struct iommu_dev_data *alloc_dev_data(struct amd_iommu *iommu, u16 devid)
377 {
378 	struct iommu_dev_data *dev_data;
379 	struct amd_iommu_pci_seg *pci_seg = iommu->pci_seg;
380 
381 	dev_data = kzalloc_obj(*dev_data);
382 	if (!dev_data)
383 		return NULL;
384 
385 	mutex_init(&dev_data->mutex);
386 	spin_lock_init(&dev_data->dte_lock);
387 	dev_data->devid = devid;
388 	ratelimit_default_init(&dev_data->rs);
389 
390 	llist_add(&dev_data->dev_data_list, &pci_seg->dev_data_list);
391 	return dev_data;
392 }
393 
394 struct iommu_dev_data *search_dev_data(struct amd_iommu *iommu, u16 devid)
395 {
396 	struct iommu_dev_data *dev_data;
397 	struct llist_node *node;
398 	struct amd_iommu_pci_seg *pci_seg = iommu->pci_seg;
399 
400 	if (llist_empty(&pci_seg->dev_data_list))
401 		return NULL;
402 
403 	node = pci_seg->dev_data_list.first;
404 	llist_for_each_entry(dev_data, node, dev_data_list) {
405 		if (dev_data->devid == devid)
406 			return dev_data;
407 	}
408 
409 	return NULL;
410 }
411 
412 static int clone_alias(struct pci_dev *pdev_origin, u16 alias, void *data)
413 {
414 	struct dev_table_entry new;
415 	struct amd_iommu *iommu;
416 	struct iommu_dev_data *dev_data, *alias_data;
417 	struct pci_dev *pdev = data;
418 	u16 devid = pci_dev_id(pdev);
419 	int ret = 0;
420 
421 	if (devid == alias)
422 		return 0;
423 
424 	iommu = rlookup_amd_iommu(&pdev->dev);
425 	if (!iommu)
426 		return 0;
427 
428 	/* Copy the data from pdev */
429 	dev_data = dev_iommu_priv_get(&pdev->dev);
430 	if (!dev_data) {
431 		pr_err("%s : Failed to get dev_data for 0x%x\n", __func__, devid);
432 		ret = -EINVAL;
433 		goto out;
434 	}
435 	get_dte256(iommu, dev_data, &new);
436 
437 	/* Setup alias */
438 	alias_data = find_dev_data(iommu, alias);
439 	if (!alias_data) {
440 		pr_err("%s : Failed to get alias dev_data for 0x%x\n", __func__, alias);
441 		ret = -EINVAL;
442 		goto out;
443 	}
444 	update_dte256(iommu, alias_data, &new);
445 
446 	amd_iommu_set_rlookup_table(iommu, alias);
447 out:
448 	return ret;
449 }
450 
451 static void clone_aliases(struct amd_iommu *iommu, struct device *dev)
452 {
453 	struct pci_dev *pdev;
454 
455 	if (!dev_is_pci(dev))
456 		return;
457 	pdev = to_pci_dev(dev);
458 
459 	/*
460 	 * The IVRS alias stored in the alias table may not be
461 	 * part of the PCI DMA aliases if its bus differs
462 	 * from the original device.
463 	 */
464 	clone_alias(pdev, iommu->pci_seg->alias_table[pci_dev_id(pdev)], pdev);
465 
466 	pci_for_each_dma_alias(pdev, clone_alias, pdev);
467 }
468 
469 static void setup_aliases(struct amd_iommu *iommu, struct device *dev)
470 {
471 	struct pci_dev *pdev = to_pci_dev(dev);
472 	struct amd_iommu_pci_seg *pci_seg = iommu->pci_seg;
473 	u16 ivrs_alias;
474 
475 	/* For ACPI HID devices, there are no aliases */
476 	if (!dev_is_pci(dev))
477 		return;
478 
479 	/*
480 	 * Add the IVRS alias to the pci aliases if it is on the same
481 	 * bus. The IVRS table may know about a quirk that we don't.
482 	 */
483 	ivrs_alias = pci_seg->alias_table[pci_dev_id(pdev)];
484 	if (ivrs_alias != pci_dev_id(pdev) &&
485 	    PCI_BUS_NUM(ivrs_alias) == pdev->bus->number)
486 		pci_add_dma_alias(pdev, ivrs_alias & 0xff, 1);
487 
488 	clone_aliases(iommu, dev);
489 }
490 
491 /*
492  * We keep dev_data around for unplugged devices and reuse it when the
493  * device is re-plugged - not doing so would introduce a ton of races.
494  */
495 static struct iommu_dev_data *find_dev_data(struct amd_iommu *iommu, u16 devid)
496 {
497 	struct iommu_dev_data *dev_data;
498 
499 	dev_data = search_dev_data(iommu, devid);
500 
501 	if (dev_data == NULL) {
502 		dev_data = alloc_dev_data(iommu, devid);
503 		if (!dev_data)
504 			return NULL;
505 
506 		if (translation_pre_enabled(iommu))
507 			dev_data->defer_attach = true;
508 	}
509 
510 	return dev_data;
511 }
512 
513 /*
514 * Find or create an IOMMU group for an acpihid device.
515 */
516 static struct iommu_group *acpihid_device_group(struct device *dev)
517 {
518 	struct acpihid_map_entry *p, *entry = NULL;
519 	int devid;
520 
521 	devid = get_acpihid_device_id(dev, &entry);
522 	if (devid < 0)
523 		return ERR_PTR(devid);
524 
525 	list_for_each_entry(p, &acpihid_map, list) {
526 		if ((devid == p->devid) && p->group)
527 			entry->group = p->group;
528 	}
529 
530 	if (!entry->group)
531 		entry->group = generic_device_group(dev);
532 	else
533 		iommu_group_ref_get(entry->group);
534 
535 	return entry->group;
536 }
537 
538 static inline bool pdev_pasid_supported(struct iommu_dev_data *dev_data)
539 {
540 	return (dev_data->flags & AMD_IOMMU_DEVICE_FLAG_PASID_SUP);
541 }
542 
543 static u32 pdev_get_caps(struct pci_dev *pdev)
544 {
545 	int features;
546 	u32 flags = 0;
547 
548 	if (pci_ats_supported(pdev))
549 		flags |= AMD_IOMMU_DEVICE_FLAG_ATS_SUP;
550 
551 	if (pci_pri_supported(pdev))
552 		flags |= AMD_IOMMU_DEVICE_FLAG_PRI_SUP;
553 
554 	features = pci_pasid_features(pdev);
555 	if (features >= 0) {
556 		flags |= AMD_IOMMU_DEVICE_FLAG_PASID_SUP;
557 
558 		if (features & PCI_PASID_CAP_EXEC)
559 			flags |= AMD_IOMMU_DEVICE_FLAG_EXEC_SUP;
560 
561 		if (features & PCI_PASID_CAP_PRIV)
562 			flags |= AMD_IOMMU_DEVICE_FLAG_PRIV_SUP;
563 	}
564 
565 	return flags;
566 }
567 
568 static inline int pdev_enable_cap_ats(struct pci_dev *pdev)
569 {
570 	struct iommu_dev_data *dev_data = dev_iommu_priv_get(&pdev->dev);
571 	int ret = -EINVAL;
572 
573 	if (dev_data->ats_enabled)
574 		return 0;
575 
576 	if (amd_iommu_iotlb_sup &&
577 	    (dev_data->flags & AMD_IOMMU_DEVICE_FLAG_ATS_SUP)) {
578 		ret = pci_enable_ats(pdev, PAGE_SHIFT);
579 
580 		/*
581 		 * pci_enable_ats() should not fail here because earlier
582 		 * checks have already verified support & config.
583 		 */
584 		if (WARN_ON(ret))
585 			return ret;
586 
587 		dev_data->ats_enabled = 1;
588 		dev_data->ats_qdep    = pci_ats_queue_depth(pdev);
589 		ret = 0;
590 	}
591 
592 	return ret;
593 }
594 
595 static inline void pdev_disable_cap_ats(struct pci_dev *pdev)
596 {
597 	struct iommu_dev_data *dev_data = dev_iommu_priv_get(&pdev->dev);
598 
599 	if (dev_data->ats_enabled) {
600 		pci_disable_ats(pdev);
601 		dev_data->ats_enabled = 0;
602 	}
603 }
604 
605 static inline int pdev_enable_cap_pri(struct pci_dev *pdev)
606 {
607 	struct iommu_dev_data *dev_data = dev_iommu_priv_get(&pdev->dev);
608 	int ret = -EINVAL;
609 
610 	if (dev_data->pri_enabled)
611 		return 0;
612 
613 	if (!dev_data->ats_enabled)
614 		return 0;
615 
616 	if (dev_data->flags & AMD_IOMMU_DEVICE_FLAG_PRI_SUP) {
617 		/*
618 		 * First reset the PRI state of the device.
619 		 * FIXME: Hardcode number of outstanding requests for now
620 		 */
621 		if (!pci_reset_pri(pdev) && !pci_enable_pri(pdev, 32)) {
622 			dev_data->pri_enabled = 1;
623 			dev_data->pri_tlp     = pci_prg_resp_pasid_required(pdev);
624 
625 			ret = 0;
626 		}
627 	}
628 
629 	return ret;
630 }
631 
632 static inline void pdev_disable_cap_pri(struct pci_dev *pdev)
633 {
634 	struct iommu_dev_data *dev_data = dev_iommu_priv_get(&pdev->dev);
635 
636 	if (dev_data->pri_enabled) {
637 		pci_disable_pri(pdev);
638 		dev_data->pri_enabled = 0;
639 	}
640 }
641 
642 static inline int pdev_enable_cap_pasid(struct pci_dev *pdev)
643 {
644 	struct iommu_dev_data *dev_data = dev_iommu_priv_get(&pdev->dev);
645 	int ret = -EINVAL;
646 
647 	if (dev_data->pasid_enabled)
648 		return 0;
649 
650 	if (dev_data->flags & AMD_IOMMU_DEVICE_FLAG_PASID_SUP) {
651 		/* Only allow access to user-accessible pages */
652 		ret = pci_enable_pasid(pdev, 0);
653 		if (!ret)
654 			dev_data->pasid_enabled = 1;
655 	}
656 
657 	return ret;
658 }
659 
660 static inline void pdev_disable_cap_pasid(struct pci_dev *pdev)
661 {
662 	struct iommu_dev_data *dev_data = dev_iommu_priv_get(&pdev->dev);
663 
664 	if (dev_data->pasid_enabled) {
665 		pci_disable_pasid(pdev);
666 		dev_data->pasid_enabled = 0;
667 	}
668 }
669 
670 static void pdev_enable_caps(struct pci_dev *pdev)
671 {
672 	pdev_enable_cap_pasid(pdev);
673 	pdev_enable_cap_ats(pdev);
674 	pdev_enable_cap_pri(pdev);
675 }
676 
677 static void pdev_disable_caps(struct pci_dev *pdev)
678 {
679 	pdev_disable_cap_ats(pdev);
680 	pdev_disable_cap_pasid(pdev);
681 	pdev_disable_cap_pri(pdev);
682 }
683 
684 /*
685  * This function checks if the driver got a valid device from the caller to
686  * avoid dereferencing invalid pointers.
687  */
688 static bool lookup_device(struct device *dev,
689 				struct amd_iommu **iommu_out, u16 *devid_out)
690 {
691 	struct amd_iommu_pci_seg *pci_seg;
692 	struct amd_iommu *iommu;
693 	int devid, sbdf;
694 
695 	if (!dev)
696 		return false;
697 
698 	sbdf = get_device_sbdf_id(dev);
699 	if (sbdf < 0)
700 		return false;
701 	devid = PCI_SBDF_TO_DEVID(sbdf);
702 
703 	iommu = rlookup_amd_iommu(dev);
704 	if (!iommu || !iommu->iommu.ops)
705 		return false;
706 
707 	/* Out of our scope? */
708 	pci_seg = iommu->pci_seg;
709 	if (devid > pci_seg->last_bdf)
710 		return false;
711 
712 	*iommu_out = iommu;
713 	*devid_out = devid;
714 	return true;
715 }
716 
717 static struct iommu_dev_data *iommu_init_device(struct amd_iommu *iommu,
718 						struct device *dev, u16 devid)
719 {
720 	struct iommu_dev_data *dev_data;
721 
722 	dev_data = find_dev_data(iommu, devid);
723 	if (!dev_data)
724 		return ERR_PTR(-ENOMEM);
725 
726 	dev_data->dev = dev;
727 
728 	/*
729 	 * The dev_iommu_priv_set() needs to be called before setup_aliases.
730 	 * Otherwise, subsequent call to dev_iommu_priv_get() will fail.
731 	 */
732 	dev_iommu_priv_set(dev, dev_data);
733 	setup_aliases(iommu, dev);
734 
735 	/* Wait for DTE updates to go through */
736 	iommu_completion_wait(iommu);
737 
738 	return dev_data;
739 }
740 
741 
742 
743 /****************************************************************************
744  *
745  * Interrupt handling functions
746  *
747  ****************************************************************************/
748 
749 static void dump_dte_entry(struct amd_iommu *iommu, u16 devid)
750 {
751 	int i;
752 	struct dev_table_entry dte;
753 	struct iommu_dev_data *dev_data = find_dev_data(iommu, devid);
754 
755 	get_dte256(iommu, dev_data, &dte);
756 
757 	for (i = 0; i < 4; ++i)
758 		pr_err("DTE[%d]: %016llx\n", i, dte.data[i]);
759 }
760 
761 static void dump_command(unsigned long phys_addr)
762 {
763 	struct iommu_cmd *cmd = iommu_phys_to_virt(phys_addr);
764 	int i;
765 
766 	for (i = 0; i < 4; ++i)
767 		pr_err("CMD[%d]: %08x\n", i, cmd->data[i]);
768 }
769 
770 static void amd_iommu_report_rmp_hw_error(struct amd_iommu *iommu, volatile u32 *event)
771 {
772 	struct iommu_dev_data *dev_data = NULL;
773 	int devid, vmg_tag, flags;
774 	struct pci_dev *pdev;
775 	u64 spa;
776 
777 	devid   = (event[0] >> EVENT_DEVID_SHIFT) & EVENT_DEVID_MASK;
778 	vmg_tag = (event[1]) & 0xFFFF;
779 	flags   = (event[1] >> EVENT_FLAGS_SHIFT) & EVENT_FLAGS_MASK;
780 	spa     = ((u64)event[3] << 32) | (event[2] & 0xFFFFFFF8);
781 
782 	pdev = pci_get_domain_bus_and_slot(iommu->pci_seg->id, PCI_BUS_NUM(devid),
783 					   devid & 0xff);
784 	if (pdev)
785 		dev_data = dev_iommu_priv_get(&pdev->dev);
786 
787 	if (dev_data) {
788 		if (__ratelimit(&dev_data->rs)) {
789 			pci_err(pdev, "Event logged [RMP_HW_ERROR vmg_tag=0x%04x, spa=0x%llx, flags=0x%04x]\n",
790 				vmg_tag, spa, flags);
791 		}
792 	} else {
793 		pr_err_ratelimited("Event logged [RMP_HW_ERROR device=%04x:%02x:%02x.%x, vmg_tag=0x%04x, spa=0x%llx, flags=0x%04x]\n",
794 			iommu->pci_seg->id, PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
795 			vmg_tag, spa, flags);
796 	}
797 
798 	if (pdev)
799 		pci_dev_put(pdev);
800 }
801 
802 static void amd_iommu_report_rmp_fault(struct amd_iommu *iommu, volatile u32 *event)
803 {
804 	struct iommu_dev_data *dev_data = NULL;
805 	int devid, flags_rmp, vmg_tag, flags;
806 	struct pci_dev *pdev;
807 	u64 gpa;
808 
809 	devid     = (event[0] >> EVENT_DEVID_SHIFT) & EVENT_DEVID_MASK;
810 	flags_rmp = (event[0] >> EVENT_FLAGS_SHIFT) & 0xFF;
811 	vmg_tag   = (event[1]) & 0xFFFF;
812 	flags     = (event[1] >> EVENT_FLAGS_SHIFT) & EVENT_FLAGS_MASK;
813 	gpa       = ((u64)event[3] << 32) | event[2];
814 
815 	pdev = pci_get_domain_bus_and_slot(iommu->pci_seg->id, PCI_BUS_NUM(devid),
816 					   devid & 0xff);
817 	if (pdev)
818 		dev_data = dev_iommu_priv_get(&pdev->dev);
819 
820 	if (dev_data) {
821 		if (__ratelimit(&dev_data->rs)) {
822 			pci_err(pdev, "Event logged [RMP_PAGE_FAULT vmg_tag=0x%04x, gpa=0x%llx, flags_rmp=0x%04x, flags=0x%04x]\n",
823 				vmg_tag, gpa, flags_rmp, flags);
824 		}
825 	} else {
826 		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",
827 			iommu->pci_seg->id, PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
828 			vmg_tag, gpa, flags_rmp, flags);
829 	}
830 
831 	if (pdev)
832 		pci_dev_put(pdev);
833 }
834 
835 #define IS_IOMMU_MEM_TRANSACTION(flags)		\
836 	(((flags) & EVENT_FLAG_I) == 0)
837 
838 #define IS_WRITE_REQUEST(flags)			\
839 	((flags) & EVENT_FLAG_RW)
840 
841 static void amd_iommu_report_page_fault(struct amd_iommu *iommu,
842 					u16 devid, u16 domain_id,
843 					u64 address, int flags)
844 {
845 	struct iommu_dev_data *dev_data = NULL;
846 	struct pci_dev *pdev;
847 
848 	pdev = pci_get_domain_bus_and_slot(iommu->pci_seg->id, PCI_BUS_NUM(devid),
849 					   devid & 0xff);
850 	if (pdev)
851 		dev_data = dev_iommu_priv_get(&pdev->dev);
852 
853 	if (dev_data) {
854 		/*
855 		 * If this is a DMA fault (for which the I(nterrupt)
856 		 * bit will be unset), allow report_iommu_fault() to
857 		 * prevent logging it.
858 		 */
859 		if (IS_IOMMU_MEM_TRANSACTION(flags)) {
860 			/* Device not attached to domain properly */
861 			if (dev_data->domain == NULL) {
862 				pr_err_ratelimited("Event logged [Device not attached to domain properly]\n");
863 				pr_err_ratelimited("  device=%04x:%02x:%02x.%x domain=0x%04x\n",
864 						   iommu->pci_seg->id, PCI_BUS_NUM(devid), PCI_SLOT(devid),
865 						   PCI_FUNC(devid), domain_id);
866 				goto out;
867 			}
868 
869 			if (!report_iommu_fault(&dev_data->domain->domain,
870 						&pdev->dev, address,
871 						IS_WRITE_REQUEST(flags) ?
872 							IOMMU_FAULT_WRITE :
873 							IOMMU_FAULT_READ))
874 				goto out;
875 		}
876 
877 		if (__ratelimit(&dev_data->rs)) {
878 			pci_err(pdev, "Event logged [IO_PAGE_FAULT domain=0x%04x address=0x%llx flags=0x%04x]\n",
879 				domain_id, address, flags);
880 		}
881 	} else {
882 		pr_err_ratelimited("Event logged [IO_PAGE_FAULT device=%04x:%02x:%02x.%x domain=0x%04x address=0x%llx flags=0x%04x]\n",
883 			iommu->pci_seg->id, PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
884 			domain_id, address, flags);
885 	}
886 
887 out:
888 	if (pdev)
889 		pci_dev_put(pdev);
890 }
891 
892 static void amd_iommu_report_ppr_err(struct amd_iommu *iommu, volatile u32 *event,
893 				     u16 devid, u64 address, int flags)
894 {
895 	struct pci_dev *pdev;
896 	struct device *dev = iommu->iommu.dev;
897 	u32 pasid = PPR_PASID(*((u64 *)event));
898 	int tag = event[1] & 0x03FF;
899 	bool gn;
900 
901 	dev_err_ratelimited(dev, "Event logged [INVALID_PPR_REQUEST device=%04x:%02x:%02x.%x "
902 			    "pasid=0x%05x address=0x%llx flags=0x%04x tag=0x%03x]\n",
903 			    iommu->pci_seg->id, PCI_BUS_NUM(devid), PCI_SLOT(devid),
904 			    PCI_FUNC(devid), pasid, address, flags, tag);
905 
906 	/* Skip COMPLETE_PPR_REQUEST response if RX=1 */
907 	if (flags & EVENT_FLAG_PPR_RX)
908 		return;
909 
910 	pdev = pci_get_domain_bus_and_slot(iommu->pci_seg->id, PCI_BUS_NUM(devid),
911 					   devid & 0xff);
912 	if (!pdev)
913 		return;
914 
915 	if (!dev_iommu_priv_get(&pdev->dev)) {
916 		pci_dev_put(pdev);
917 		return;
918 	}
919 
920 	gn = (flags & EVENT_FLAG_PPR_GN);
921 
922 	__amd_iommu_complete_ppr(&pdev->dev, pasid, IOMMU_PAGE_RESP_FAILURE, tag, gn);
923 	pci_dev_put(pdev);
924 }
925 
926 static void iommu_print_event(struct amd_iommu *iommu, void *__evt)
927 {
928 	struct device *dev = iommu->iommu.dev;
929 	int type, devid, flags;
930 	volatile u32 *event = __evt;
931 	int count = 0;
932 	u64 address, ctrl;
933 	u32 pasid;
934 
935 retry:
936 	type    = (event[1] >> EVENT_TYPE_SHIFT)  & EVENT_TYPE_MASK;
937 	devid   = (event[0] >> EVENT_DEVID_SHIFT) & EVENT_DEVID_MASK;
938 	pasid   = (event[0] & EVENT_DOMID_MASK_HI) |
939 		  (event[1] & EVENT_DOMID_MASK_LO);
940 	flags   = (event[1] >> EVENT_FLAGS_SHIFT) & EVENT_FLAGS_MASK;
941 	address = (u64)(((u64)event[3]) << 32) | event[2];
942 	ctrl    = readq(iommu->mmio_base + MMIO_CONTROL_OFFSET);
943 
944 	if (type == 0) {
945 		/* Did we hit the erratum? */
946 		if (++count == LOOP_TIMEOUT) {
947 			pr_err("No event written to event log\n");
948 			return;
949 		}
950 		udelay(1);
951 		goto retry;
952 	}
953 
954 	if (type == EVENT_TYPE_IO_FAULT) {
955 		amd_iommu_report_page_fault(iommu, devid, pasid, address, flags);
956 		return;
957 	}
958 
959 	switch (type) {
960 	case EVENT_TYPE_ILL_DEV:
961 		dev_err(dev, "Event logged [ILLEGAL_DEV_TABLE_ENTRY device=%04x:%02x:%02x.%x pasid=0x%05x address=0x%llx flags=0x%04x]\n",
962 			iommu->pci_seg->id, PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
963 			pasid, address, flags);
964 		dev_err(dev, "Control Reg : 0x%llx\n", ctrl);
965 		dump_dte_entry(iommu, devid);
966 		break;
967 	case EVENT_TYPE_DEV_TAB_ERR:
968 		dev_err(dev, "Event logged [DEV_TAB_HARDWARE_ERROR device=%04x:%02x:%02x.%x "
969 			"address=0x%llx flags=0x%04x]\n",
970 			iommu->pci_seg->id, PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
971 			address, flags);
972 		break;
973 	case EVENT_TYPE_PAGE_TAB_ERR:
974 		dev_err(dev, "Event logged [PAGE_TAB_HARDWARE_ERROR device=%04x:%02x:%02x.%x pasid=0x%04x address=0x%llx flags=0x%04x]\n",
975 			iommu->pci_seg->id, PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
976 			pasid, address, flags);
977 		break;
978 	case EVENT_TYPE_ILL_CMD:
979 		dev_err(dev, "Event logged [ILLEGAL_COMMAND_ERROR address=0x%llx]\n", address);
980 		dump_command(address);
981 		break;
982 	case EVENT_TYPE_CMD_HARD_ERR:
983 		dev_err(dev, "Event logged [COMMAND_HARDWARE_ERROR address=0x%llx flags=0x%04x]\n",
984 			address, flags);
985 		break;
986 	case EVENT_TYPE_IOTLB_INV_TO:
987 		dev_err(dev, "Event logged [IOTLB_INV_TIMEOUT device=%04x:%02x:%02x.%x address=0x%llx]\n",
988 			iommu->pci_seg->id, PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
989 			address);
990 		break;
991 	case EVENT_TYPE_INV_DEV_REQ:
992 		dev_err(dev, "Event logged [INVALID_DEVICE_REQUEST device=%04x:%02x:%02x.%x pasid=0x%05x address=0x%llx flags=0x%04x]\n",
993 			iommu->pci_seg->id, PCI_BUS_NUM(devid), PCI_SLOT(devid), PCI_FUNC(devid),
994 			pasid, address, flags);
995 		break;
996 	case EVENT_TYPE_RMP_FAULT:
997 		amd_iommu_report_rmp_fault(iommu, event);
998 		break;
999 	case EVENT_TYPE_RMP_HW_ERR:
1000 		amd_iommu_report_rmp_hw_error(iommu, event);
1001 		break;
1002 	case EVENT_TYPE_INV_PPR_REQ:
1003 		amd_iommu_report_ppr_err(iommu, event, devid, address, flags);
1004 		break;
1005 	default:
1006 		dev_err(dev, "Event logged [UNKNOWN event[0]=0x%08x event[1]=0x%08x event[2]=0x%08x event[3]=0x%08x\n",
1007 			event[0], event[1], event[2], event[3]);
1008 	}
1009 
1010 	/*
1011 	 * To detect the hardware errata 732 we need to clear the
1012 	 * entry back to zero. This issue does not exist on SNP
1013 	 * enabled system. Also this buffer is not writeable on
1014 	 * SNP enabled system.
1015 	 */
1016 	if (!amd_iommu_snp_en)
1017 		memset(__evt, 0, 4 * sizeof(u32));
1018 }
1019 
1020 static void iommu_poll_events(struct amd_iommu *iommu)
1021 {
1022 	u32 head, tail;
1023 
1024 	head = readl(iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
1025 	tail = readl(iommu->mmio_base + MMIO_EVT_TAIL_OFFSET);
1026 
1027 	while (head != tail) {
1028 		iommu_print_event(iommu, iommu->evt_buf + head);
1029 
1030 		/* Update head pointer of hardware ring-buffer */
1031 		head = (head + EVTLOG_ENTRY_SIZE) % amd_iommu_evtlog_size;
1032 		writel(head, iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
1033 	}
1034 
1035 }
1036 
1037 #ifdef CONFIG_IRQ_REMAP
1038 static int (*iommu_ga_log_notifier)(u32);
1039 
1040 int amd_iommu_register_ga_log_notifier(int (*notifier)(u32))
1041 {
1042 	iommu_ga_log_notifier = notifier;
1043 
1044 	/*
1045 	 * Ensure all in-flight IRQ handlers run to completion before returning
1046 	 * to the caller, e.g. to ensure module code isn't unloaded while it's
1047 	 * being executed in the IRQ handler.
1048 	 */
1049 	if (!notifier)
1050 		synchronize_rcu();
1051 
1052 	return 0;
1053 }
1054 EXPORT_SYMBOL(amd_iommu_register_ga_log_notifier);
1055 
1056 static void iommu_poll_ga_log(struct amd_iommu *iommu)
1057 {
1058 	u32 head, tail;
1059 
1060 	head = readl(iommu->mmio_base + MMIO_GA_HEAD_OFFSET);
1061 	tail = readl(iommu->mmio_base + MMIO_GA_TAIL_OFFSET);
1062 
1063 	while (head != tail) {
1064 		volatile u64 *raw;
1065 		u64 log_entry;
1066 
1067 		raw = (u64 *)(iommu->ga_log + head);
1068 
1069 		/* Avoid memcpy function-call overhead */
1070 		log_entry = *raw;
1071 
1072 		/* Update head pointer of hardware ring-buffer */
1073 		head = (head + GA_ENTRY_SIZE) % GA_LOG_SIZE;
1074 		writel(head, iommu->mmio_base + MMIO_GA_HEAD_OFFSET);
1075 
1076 		/* Handle GA entry */
1077 		switch (GA_REQ_TYPE(log_entry)) {
1078 		case GA_GUEST_NR:
1079 			if (!iommu_ga_log_notifier)
1080 				break;
1081 
1082 			pr_debug("%s: devid=%#x, ga_tag=%#x\n",
1083 				 __func__, GA_DEVID(log_entry),
1084 				 GA_TAG(log_entry));
1085 
1086 			if (iommu_ga_log_notifier(GA_TAG(log_entry)) != 0)
1087 				pr_err("GA log notifier failed.\n");
1088 			break;
1089 		default:
1090 			break;
1091 		}
1092 	}
1093 }
1094 
1095 static void
1096 amd_iommu_set_pci_msi_domain(struct device *dev, struct amd_iommu *iommu)
1097 {
1098 	if (!irq_remapping_enabled || !dev_is_pci(dev) ||
1099 	    !pci_dev_has_default_msi_parent_domain(to_pci_dev(dev)))
1100 		return;
1101 
1102 	dev_set_msi_domain(dev, iommu->ir_domain);
1103 }
1104 
1105 #else /* CONFIG_IRQ_REMAP */
1106 static inline void
1107 amd_iommu_set_pci_msi_domain(struct device *dev, struct amd_iommu *iommu) { }
1108 #endif /* !CONFIG_IRQ_REMAP */
1109 
1110 static void amd_iommu_handle_irq(void *data, const char *evt_type,
1111 				 u32 int_mask, u32 overflow_mask,
1112 				 void (*int_handler)(struct amd_iommu *),
1113 				 void (*overflow_handler)(struct amd_iommu *))
1114 {
1115 	struct amd_iommu *iommu = (struct amd_iommu *) data;
1116 	u32 status = readl(iommu->mmio_base + MMIO_STATUS_OFFSET);
1117 	u32 mask = int_mask | overflow_mask;
1118 
1119 	while (status & mask) {
1120 		/* Enable interrupt sources again */
1121 		writel(mask, iommu->mmio_base + MMIO_STATUS_OFFSET);
1122 
1123 		if (int_handler) {
1124 			pr_devel("Processing IOMMU (ivhd%d) %s Log\n",
1125 				 iommu->index, evt_type);
1126 			int_handler(iommu);
1127 		}
1128 
1129 		if ((status & overflow_mask) && overflow_handler)
1130 			overflow_handler(iommu);
1131 
1132 		/*
1133 		 * Hardware bug: ERBT1312
1134 		 * When re-enabling interrupt (by writing 1
1135 		 * to clear the bit), the hardware might also try to set
1136 		 * the interrupt bit in the event status register.
1137 		 * In this scenario, the bit will be set, and disable
1138 		 * subsequent interrupts.
1139 		 *
1140 		 * Workaround: The IOMMU driver should read back the
1141 		 * status register and check if the interrupt bits are cleared.
1142 		 * If not, driver will need to go through the interrupt handler
1143 		 * again and re-clear the bits
1144 		 */
1145 		status = readl(iommu->mmio_base + MMIO_STATUS_OFFSET);
1146 	}
1147 }
1148 
1149 irqreturn_t amd_iommu_int_thread_evtlog(int irq, void *data)
1150 {
1151 	amd_iommu_handle_irq(data, "Evt", MMIO_STATUS_EVT_INT_MASK,
1152 			     MMIO_STATUS_EVT_OVERFLOW_MASK,
1153 			     iommu_poll_events, amd_iommu_restart_event_logging);
1154 
1155 	return IRQ_HANDLED;
1156 }
1157 
1158 irqreturn_t amd_iommu_int_thread_pprlog(int irq, void *data)
1159 {
1160 	amd_iommu_handle_irq(data, "PPR", MMIO_STATUS_PPR_INT_MASK,
1161 			     MMIO_STATUS_PPR_OVERFLOW_MASK,
1162 			     amd_iommu_poll_ppr_log, amd_iommu_restart_ppr_log);
1163 
1164 	return IRQ_HANDLED;
1165 }
1166 
1167 irqreturn_t amd_iommu_int_thread_galog(int irq, void *data)
1168 {
1169 #ifdef CONFIG_IRQ_REMAP
1170 	amd_iommu_handle_irq(data, "GA", MMIO_STATUS_GALOG_INT_MASK,
1171 			     MMIO_STATUS_GALOG_OVERFLOW_MASK,
1172 			     iommu_poll_ga_log, amd_iommu_restart_ga_log);
1173 #endif
1174 
1175 	return IRQ_HANDLED;
1176 }
1177 
1178 irqreturn_t amd_iommu_int_thread(int irq, void *data)
1179 {
1180 	amd_iommu_int_thread_evtlog(irq, data);
1181 	amd_iommu_int_thread_pprlog(irq, data);
1182 	amd_iommu_int_thread_galog(irq, data);
1183 
1184 	return IRQ_HANDLED;
1185 }
1186 
1187 /****************************************************************************
1188  *
1189  * IOMMU command queuing functions
1190  *
1191  ****************************************************************************/
1192 
1193 static void dump_command_buffer(struct amd_iommu *iommu)
1194 {
1195 	struct iommu_cmd *cmd;
1196 	u32 head, tail;
1197 	int i;
1198 
1199 	head = readl(iommu->mmio_base + MMIO_CMD_HEAD_OFFSET);
1200 	tail = readl(iommu->mmio_base + MMIO_CMD_TAIL_OFFSET);
1201 
1202 	pr_err("CMD Buffer head=%llu tail=%llu\n", MMIO_CMD_BUFFER_HEAD(head),
1203 	       MMIO_CMD_BUFFER_TAIL(tail));
1204 
1205 	for (i = 0; i < CMD_BUFFER_ENTRIES; i++) {
1206 		cmd = (struct iommu_cmd *)(iommu->cmd_buf + i * sizeof(*cmd));
1207 		pr_err("%3d: %08x %08x %08x %08x\n", i, cmd->data[0], cmd->data[1], cmd->data[2],
1208 		       cmd->data[3]);
1209 	}
1210 }
1211 
1212 static int wait_on_sem(struct amd_iommu *iommu, u64 data)
1213 {
1214 	int i = 0;
1215 
1216 	/*
1217 	 * cmd_sem holds a monotonically non-decreasing completion sequence
1218 	 * number.
1219 	 */
1220 	while ((__s64)(READ_ONCE(*iommu->cmd_sem) - data) < 0 &&
1221 	       i < LOOP_TIMEOUT) {
1222 		udelay(1);
1223 		i += 1;
1224 	}
1225 
1226 	if (i == LOOP_TIMEOUT) {
1227 
1228 		pr_alert("IOMMU %04x:%02x:%02x.%01x: Completion-Wait loop timed out\n",
1229 			 iommu->pci_seg->id, PCI_BUS_NUM(iommu->devid),
1230 			 PCI_SLOT(iommu->devid), PCI_FUNC(iommu->devid));
1231 
1232 		if (amd_iommu_dump)
1233 			DO_ONCE_LITE(dump_command_buffer, iommu);
1234 
1235 		return -EIO;
1236 	}
1237 
1238 	return 0;
1239 }
1240 
1241 static void copy_cmd_to_buffer(struct amd_iommu *iommu,
1242 			       struct iommu_cmd *cmd)
1243 {
1244 	u8 *target;
1245 	u32 tail;
1246 
1247 	/* Copy command to buffer */
1248 	tail = iommu->cmd_buf_tail;
1249 	target = iommu->cmd_buf + tail;
1250 	memcpy(target, cmd, sizeof(*cmd));
1251 
1252 	tail = (tail + sizeof(*cmd)) % CMD_BUFFER_SIZE;
1253 	iommu->cmd_buf_tail = tail;
1254 
1255 	/* Tell the IOMMU about it */
1256 	writel(tail, iommu->mmio_base + MMIO_CMD_TAIL_OFFSET);
1257 }
1258 
1259 static void build_completion_wait(struct iommu_cmd *cmd,
1260 				  struct amd_iommu *iommu,
1261 				  u64 data)
1262 {
1263 	u64 paddr = iommu->cmd_sem_paddr;
1264 
1265 	memset(cmd, 0, sizeof(*cmd));
1266 	cmd->data[0] = lower_32_bits(paddr) | CMD_COMPL_WAIT_STORE_MASK;
1267 	cmd->data[1] = upper_32_bits(paddr);
1268 	cmd->data[2] = lower_32_bits(data);
1269 	cmd->data[3] = upper_32_bits(data);
1270 	CMD_SET_TYPE(cmd, CMD_COMPL_WAIT);
1271 }
1272 
1273 static void build_inv_dte(struct iommu_cmd *cmd, u16 devid)
1274 {
1275 	memset(cmd, 0, sizeof(*cmd));
1276 	cmd->data[0] = devid;
1277 	CMD_SET_TYPE(cmd, CMD_INV_DEV_ENTRY);
1278 }
1279 
1280 /*
1281  * Builds an invalidation address which is suitable for one page or multiple
1282  * pages. Sets the size bit (S) as needed if more than one page is flushed.
1283  */
1284 static inline u64 build_inv_address(u64 address, u64 last)
1285 {
1286 	unsigned int sz_lg2;
1287 
1288 	address &= GENMASK_U64(63, 12);
1289 	sz_lg2 = fls64(address ^ last);
1290 	if (sz_lg2 <= 12)
1291 		return address;
1292 
1293 	/*
1294 	 * Encode sz_lg2 according to Table 14: Example Page Size Encodings
1295 	 *
1296 	 * See "Note *":
1297 	 *   Address bits 51:32 can be used to encode page sizes greater
1298 	 *   that 4 Gbytes.
1299 	 * Which we take to mean that the highest page size has bit
1300 	 *  [51]=0, [50:12]=1
1301 	 * and that coding happens when sz_lg2 is 52. Fall back to full
1302 	 * invalidation if the size is too big.
1303 	 *
1304 	 */
1305 	if (unlikely(sz_lg2 > 52))
1306 		return CMD_INV_IOMMU_ALL_PAGES_ADDRESS |
1307 		       CMD_INV_IOMMU_PAGES_SIZE_MASK;
1308 
1309 	/*
1310 	 * The sz_lg2 calculation with fls() ensures that:
1311 	 *   address & BIT(sz_lg2 - 1) == 0
1312 	 * Therefore only the 1's need to be added. 8KB requires no 1's
1313 	 */
1314 	if (sz_lg2 > 13)
1315 		address |= GENMASK_U64(sz_lg2 - 2, 12);
1316 	return address | CMD_INV_IOMMU_PAGES_SIZE_MASK;
1317 }
1318 
1319 static void build_inv_iommu_pages(struct iommu_cmd *cmd, u64 address,
1320 				  u64 last, u16 domid, ioasid_t pasid,
1321 				  u32 flags)
1322 {
1323 	u64 inv_address = build_inv_address(address, last);
1324 
1325 	memset(cmd, 0, sizeof(*cmd));
1326 
1327 	cmd->data[1] |= domid;
1328 	cmd->data[2]  = lower_32_bits(inv_address);
1329 	cmd->data[3]  = upper_32_bits(inv_address);
1330 	cmd->data[2] |= flags;
1331 	if (flags & CMD_INV_IOMMU_PAGES_GN_MASK)
1332 		cmd->data[0] |= pasid;
1333 	CMD_SET_TYPE(cmd, CMD_INV_IOMMU_PAGES);
1334 }
1335 
1336 static void build_inv_iotlb_pages(struct iommu_cmd *cmd, u16 devid, int qdep,
1337 				  u64 address, u64 last,
1338 				  ioasid_t pasid, bool gn)
1339 {
1340 	u64 inv_address = build_inv_address(address, last);
1341 
1342 	memset(cmd, 0, sizeof(*cmd));
1343 
1344 	cmd->data[0]  = devid;
1345 	cmd->data[0] |= (qdep & 0xff) << 24;
1346 	cmd->data[1]  = devid;
1347 	cmd->data[2]  = lower_32_bits(inv_address);
1348 	cmd->data[3]  = upper_32_bits(inv_address);
1349 	if (gn) {
1350 		cmd->data[0] |= ((pasid >> 8) & 0xff) << 16;
1351 		cmd->data[1] |= (pasid & 0xff) << 16;
1352 		cmd->data[2] |= CMD_INV_IOMMU_PAGES_GN_MASK;
1353 	}
1354 
1355 	CMD_SET_TYPE(cmd, CMD_INV_IOTLB_PAGES);
1356 }
1357 
1358 static void build_complete_ppr(struct iommu_cmd *cmd, u16 devid, u32 pasid,
1359 			       int status, int tag, bool gn)
1360 {
1361 	memset(cmd, 0, sizeof(*cmd));
1362 
1363 	cmd->data[0]  = devid;
1364 	if (gn) {
1365 		cmd->data[1]  = pasid;
1366 		cmd->data[2]  = CMD_INV_IOMMU_PAGES_GN_MASK;
1367 	}
1368 	cmd->data[3]  = tag & 0x1ff;
1369 	cmd->data[3] |= (status & PPR_STATUS_MASK) << PPR_STATUS_SHIFT;
1370 
1371 	CMD_SET_TYPE(cmd, CMD_COMPLETE_PPR);
1372 }
1373 
1374 static void build_inv_all(struct iommu_cmd *cmd)
1375 {
1376 	memset(cmd, 0, sizeof(*cmd));
1377 	CMD_SET_TYPE(cmd, CMD_INV_ALL);
1378 }
1379 
1380 static void build_inv_irt(struct iommu_cmd *cmd, u16 devid)
1381 {
1382 	memset(cmd, 0, sizeof(*cmd));
1383 	cmd->data[0] = devid;
1384 	CMD_SET_TYPE(cmd, CMD_INV_IRT);
1385 }
1386 
1387 /*
1388  * Writes the command to the IOMMUs command buffer and informs the
1389  * hardware about the new command.
1390  */
1391 static int __iommu_queue_command_sync(struct amd_iommu *iommu,
1392 				      struct iommu_cmd *cmd,
1393 				      bool sync)
1394 {
1395 	unsigned int count = 0;
1396 	u32 left, next_tail;
1397 
1398 	next_tail = (iommu->cmd_buf_tail + sizeof(*cmd)) % CMD_BUFFER_SIZE;
1399 again:
1400 	left      = (iommu->cmd_buf_head - next_tail) % CMD_BUFFER_SIZE;
1401 
1402 	if (left <= 0x20) {
1403 		/* Skip udelay() the first time around */
1404 		if (count++) {
1405 			if (count == LOOP_TIMEOUT) {
1406 				pr_err("Command buffer timeout\n");
1407 				return -EIO;
1408 			}
1409 
1410 			udelay(1);
1411 		}
1412 
1413 		/* Update head and recheck remaining space */
1414 		iommu->cmd_buf_head = readl(iommu->mmio_base +
1415 					    MMIO_CMD_HEAD_OFFSET);
1416 
1417 		goto again;
1418 	}
1419 
1420 	copy_cmd_to_buffer(iommu, cmd);
1421 
1422 	/* Do we need to make sure all commands are processed? */
1423 	iommu->need_sync = sync;
1424 
1425 	return 0;
1426 }
1427 
1428 static int iommu_queue_command_sync(struct amd_iommu *iommu,
1429 				    struct iommu_cmd *cmd,
1430 				    bool sync)
1431 {
1432 	unsigned long flags;
1433 	int ret;
1434 
1435 	raw_spin_lock_irqsave(&iommu->lock, flags);
1436 	ret = __iommu_queue_command_sync(iommu, cmd, sync);
1437 	raw_spin_unlock_irqrestore(&iommu->lock, flags);
1438 
1439 	return ret;
1440 }
1441 
1442 static int iommu_queue_command(struct amd_iommu *iommu, struct iommu_cmd *cmd)
1443 {
1444 	return iommu_queue_command_sync(iommu, cmd, true);
1445 }
1446 
1447 static u64 get_cmdsem_val(struct amd_iommu *iommu)
1448 {
1449 	lockdep_assert_held(&iommu->lock);
1450 	return ++iommu->cmd_sem_val;
1451 }
1452 
1453 /*
1454  * This function queues a completion wait command into the command
1455  * buffer of an IOMMU
1456  */
1457 static int iommu_completion_wait(struct amd_iommu *iommu)
1458 {
1459 	struct iommu_cmd cmd;
1460 	unsigned long flags;
1461 	int ret;
1462 	u64 data;
1463 
1464 	raw_spin_lock_irqsave(&iommu->lock, flags);
1465 
1466 	if (!iommu->need_sync) {
1467 		/*
1468 		 * No command has been queued since the last completion-wait.
1469 		 * A concurrent CPU may have already queued that CWAIT and
1470 		 * cleared need_sync; need_sync == false only means a covering
1471 		 * CWAIT is queued, not that all prior commands have completed.
1472 		 * Wait for the last allocated sequence number so that any
1473 		 * command queued before this call (possibly on another CPU)
1474 		 * is guaranteed to have completed before returning.
1475 		 */
1476 		data = iommu->cmd_sem_val;
1477 		raw_spin_unlock_irqrestore(&iommu->lock, flags);
1478 		return wait_on_sem(iommu, data);
1479 	}
1480 
1481 	data = get_cmdsem_val(iommu);
1482 	build_completion_wait(&cmd, iommu, data);
1483 
1484 	ret = __iommu_queue_command_sync(iommu, &cmd, false);
1485 	raw_spin_unlock_irqrestore(&iommu->lock, flags);
1486 
1487 	if (ret)
1488 		return ret;
1489 
1490 	return wait_on_sem(iommu, data);
1491 }
1492 
1493 static void domain_flush_complete(struct protection_domain *domain)
1494 {
1495 	struct pdom_iommu_info *pdom_iommu_info;
1496 	unsigned long i;
1497 
1498 	lockdep_assert_held(&domain->lock);
1499 
1500 	/*
1501 	 * Devices of this domain are behind this IOMMU
1502 	 * We need to wait for completion of all commands.
1503 	 */
1504 	 xa_for_each(&domain->iommu_array, i, pdom_iommu_info)
1505 		iommu_completion_wait(pdom_iommu_info->iommu);
1506 }
1507 
1508 static int iommu_flush_dte(struct amd_iommu *iommu, u16 devid)
1509 {
1510 	struct iommu_cmd cmd;
1511 
1512 	build_inv_dte(&cmd, devid);
1513 
1514 	return iommu_queue_command(iommu, &cmd);
1515 }
1516 
1517 static void iommu_flush_dte_sync(struct amd_iommu *iommu, u16 devid)
1518 {
1519 	int ret;
1520 
1521 	ret = iommu_flush_dte(iommu, devid);
1522 	if (!ret)
1523 		iommu_completion_wait(iommu);
1524 }
1525 
1526 static void amd_iommu_flush_dte_all(struct amd_iommu *iommu)
1527 {
1528 	u32 devid;
1529 	u16 last_bdf = iommu->pci_seg->last_bdf;
1530 
1531 	for (devid = 0; devid <= last_bdf; ++devid)
1532 		iommu_flush_dte(iommu, devid);
1533 
1534 	iommu_completion_wait(iommu);
1535 }
1536 
1537 /*
1538  * This function uses heavy locking and may disable irqs for some time. But
1539  * this is no issue because it is only called during resume.
1540  */
1541 static void amd_iommu_flush_tlb_all(struct amd_iommu *iommu)
1542 {
1543 	u32 dom_id;
1544 	u16 last_bdf = iommu->pci_seg->last_bdf;
1545 
1546 	for (dom_id = 0; dom_id <= last_bdf; ++dom_id) {
1547 		struct iommu_cmd cmd;
1548 		build_inv_iommu_pages(&cmd, 0, U64_MAX,
1549 				      dom_id, IOMMU_NO_PASID,
1550 				      CMD_INV_IOMMU_PAGES_PDE_MASK);
1551 		iommu_queue_command(iommu, &cmd);
1552 	}
1553 
1554 	iommu_completion_wait(iommu);
1555 }
1556 
1557 static void amd_iommu_flush_tlb_domid(struct amd_iommu *iommu, u32 dom_id)
1558 {
1559 	struct iommu_cmd cmd;
1560 
1561 	build_inv_iommu_pages(&cmd, 0, U64_MAX,
1562 			      dom_id, IOMMU_NO_PASID,
1563 			      CMD_INV_IOMMU_PAGES_PDE_MASK);
1564 	iommu_queue_command(iommu, &cmd);
1565 
1566 	iommu_completion_wait(iommu);
1567 }
1568 
1569 static int iommu_flush_pages_v1_hdom_ids(struct protection_domain *pdom,
1570 					 u64 address, u64 last, u32 flags)
1571 {
1572 	int ret = 0;
1573 	struct amd_iommu_viommu *aviommu;
1574 
1575 	list_for_each_entry(aviommu, &pdom->viommu_list, pdom_list) {
1576 		unsigned long i;
1577 		struct guest_domain_mapping_info *gdom_info;
1578 		struct amd_iommu *iommu = container_of(aviommu->core.iommu_dev,
1579 						       struct amd_iommu, iommu);
1580 
1581 		xa_lock(&aviommu->gdomid_array);
1582 		xa_for_each(&aviommu->gdomid_array, i, gdom_info) {
1583 			struct iommu_cmd cmd;
1584 
1585 			pr_debug("%s: iommu=%#x, hdom_id=%#x\n", __func__,
1586 				 iommu->devid, gdom_info->hdom_id);
1587 			build_inv_iommu_pages(&cmd, address, last, gdom_info->hdom_id,
1588 					      IOMMU_NO_PASID, flags);
1589 			ret |= iommu_queue_command(iommu, &cmd);
1590 		}
1591 		xa_unlock(&aviommu->gdomid_array);
1592 	}
1593 	return ret;
1594 }
1595 
1596 static void amd_iommu_flush_all(struct amd_iommu *iommu)
1597 {
1598 	struct iommu_cmd cmd;
1599 
1600 	build_inv_all(&cmd);
1601 
1602 	iommu_queue_command(iommu, &cmd);
1603 	iommu_completion_wait(iommu);
1604 }
1605 
1606 static void iommu_flush_irt(struct amd_iommu *iommu, u16 devid)
1607 {
1608 	struct iommu_cmd cmd;
1609 
1610 	build_inv_irt(&cmd, devid);
1611 
1612 	iommu_queue_command(iommu, &cmd);
1613 }
1614 
1615 static void amd_iommu_flush_irt_all(struct amd_iommu *iommu)
1616 {
1617 	u32 devid;
1618 	u16 last_bdf = iommu->pci_seg->last_bdf;
1619 
1620 	if (iommu->irtcachedis_enabled)
1621 		return;
1622 
1623 	for (devid = 0; devid <= last_bdf; devid++)
1624 		iommu_flush_irt(iommu, devid);
1625 
1626 	iommu_completion_wait(iommu);
1627 }
1628 
1629 void amd_iommu_flush_all_caches(struct amd_iommu *iommu)
1630 {
1631 	if (check_feature(FEATURE_IA)) {
1632 		amd_iommu_flush_all(iommu);
1633 	} else {
1634 		amd_iommu_flush_dte_all(iommu);
1635 		amd_iommu_flush_irt_all(iommu);
1636 		amd_iommu_flush_tlb_all(iommu);
1637 	}
1638 }
1639 
1640 /*
1641  * Command send function for flushing on-device TLB
1642  */
1643 static int device_flush_iotlb(struct iommu_dev_data *dev_data, u64 address,
1644 			      u64 last, ioasid_t pasid, bool gn)
1645 {
1646 	struct amd_iommu *iommu = get_amd_iommu_from_dev_data(dev_data);
1647 	struct iommu_cmd cmd;
1648 	int qdep = dev_data->ats_qdep;
1649 
1650 	build_inv_iotlb_pages(&cmd, dev_data->devid, qdep, address,
1651 			      last, pasid, gn);
1652 
1653 	return iommu_queue_command(iommu, &cmd);
1654 }
1655 
1656 static int device_flush_dte_alias(struct pci_dev *pdev, u16 alias, void *data)
1657 {
1658 	struct amd_iommu *iommu = data;
1659 
1660 	return iommu_flush_dte(iommu, alias);
1661 }
1662 
1663 /*
1664  * Command send function for invalidating a device table entry
1665  */
1666 static int device_flush_dte(struct iommu_dev_data *dev_data)
1667 {
1668 	struct amd_iommu *iommu = get_amd_iommu_from_dev_data(dev_data);
1669 	struct pci_dev *pdev = NULL;
1670 	struct amd_iommu_pci_seg *pci_seg;
1671 	u16 alias;
1672 	int ret;
1673 
1674 	if (dev_is_pci(dev_data->dev))
1675 		pdev = to_pci_dev(dev_data->dev);
1676 
1677 	if (pdev)
1678 		ret = pci_for_each_dma_alias(pdev,
1679 					     device_flush_dte_alias, iommu);
1680 	else
1681 		ret = iommu_flush_dte(iommu, dev_data->devid);
1682 	if (ret)
1683 		return ret;
1684 
1685 	pci_seg = iommu->pci_seg;
1686 	alias = pci_seg->alias_table[dev_data->devid];
1687 	if (alias != dev_data->devid) {
1688 		ret = iommu_flush_dte(iommu, alias);
1689 		if (ret)
1690 			return ret;
1691 	}
1692 
1693 	if (dev_data->ats_enabled) {
1694 		/* Invalidate the entire contents of an IOTLB */
1695 		ret = device_flush_iotlb(dev_data, 0, U64_MAX,
1696 					 IOMMU_NO_PASID, false);
1697 	}
1698 
1699 	return ret;
1700 }
1701 
1702 static int domain_flush_pages_v2(struct protection_domain *pdom,
1703 				 u64 address, u64 last, u32 flags)
1704 {
1705 	struct iommu_dev_data *dev_data;
1706 	struct iommu_cmd cmd;
1707 	int ret = 0;
1708 
1709 	lockdep_assert_held(&pdom->lock);
1710 	list_for_each_entry(dev_data, &pdom->dev_list, list) {
1711 		struct amd_iommu *iommu = get_amd_iommu_from_dev(dev_data->dev);
1712 		u16 domid = dev_data->gcr3_info.domid;
1713 
1714 		build_inv_iommu_pages(&cmd, address, last, domid,
1715 				      IOMMU_NO_PASID,
1716 				      flags | CMD_INV_IOMMU_PAGES_GN_MASK);
1717 
1718 		ret |= iommu_queue_command(iommu, &cmd);
1719 	}
1720 
1721 	return ret;
1722 }
1723 
1724 static int domain_flush_pages_v1(struct protection_domain *pdom,
1725 				 u64 address, u64 last, u32 flags)
1726 {
1727 	struct pdom_iommu_info *pdom_iommu_info;
1728 	struct iommu_cmd cmd;
1729 	int ret = 0;
1730 	unsigned long i;
1731 
1732 	lockdep_assert_held(&pdom->lock);
1733 
1734 	build_inv_iommu_pages(&cmd, address, last,
1735 			      pdom->id, IOMMU_NO_PASID, flags);
1736 
1737 	xa_for_each(&pdom->iommu_array, i, pdom_iommu_info) {
1738 		/*
1739 		 * Devices of this domain are behind this IOMMU
1740 		 * We need a TLB flush
1741 		 */
1742 		ret |= iommu_queue_command(pdom_iommu_info->iommu, &cmd);
1743 	}
1744 
1745 	/*
1746 	 * A domain w/ v1 table can be a nest parent, which can have
1747 	 * multiple nested domains. Each nested domain has 1:1 mapping
1748 	 * between gDomID and hDomID. Therefore, flush every hDomID
1749 	 * associated to this nest parent domain.
1750 	 *
1751 	 * See drivers/iommu/amd/nested.c: amd_iommu_alloc_domain_nested()
1752 	 */
1753 	if (!list_empty(&pdom->viommu_list))
1754 		ret |= iommu_flush_pages_v1_hdom_ids(pdom, address, last, flags);
1755 
1756 	return ret;
1757 }
1758 
1759 /*
1760  * TLB invalidation function which is called from the mapping functions.
1761  * It flushes range of PTEs of the domain.
1762  */
1763 static void __domain_flush_pages(struct protection_domain *domain,
1764 				 u64 address, u64 last, u32 flags)
1765 {
1766 	struct iommu_dev_data *dev_data;
1767 	int ret = 0;
1768 	ioasid_t pasid = IOMMU_NO_PASID;
1769 	bool gn = false;
1770 
1771 	lockdep_assert_held(&domain->lock);
1772 
1773 	if (pdom_is_v2_pgtbl_mode(domain)) {
1774 		gn = true;
1775 		ret = domain_flush_pages_v2(domain, address, last, flags);
1776 	} else {
1777 		ret = domain_flush_pages_v1(domain, address, last, flags);
1778 	}
1779 
1780 	list_for_each_entry(dev_data, &domain->dev_list, list) {
1781 
1782 		if (!dev_data->ats_enabled)
1783 			continue;
1784 
1785 		ret |= device_flush_iotlb(dev_data, address, last, pasid, gn);
1786 	}
1787 
1788 	WARN_ON(ret);
1789 }
1790 
1791 void amd_iommu_domain_flush_pages(struct protection_domain *domain,
1792 				  u64 address, u64 last, u32 flags)
1793 {
1794 	lockdep_assert_held(&domain->lock);
1795 
1796 	if (likely(!amd_iommu_np_cache) ||
1797 	    unlikely(address == 0 && last == U64_MAX)) {
1798 		__domain_flush_pages(domain, address, last, flags);
1799 
1800 		/* Wait until IOMMU TLB and all device IOTLB flushes are complete */
1801 		domain_flush_complete(domain);
1802 
1803 		return;
1804 	}
1805 
1806 	/*
1807 	 * When NpCache is on, we infer that we run in a VM and use a vIOMMU.
1808 	 * In such setups it is best to avoid flushes of ranges which are not
1809 	 * naturally aligned, since it would lead to flushes of unmodified
1810 	 * PTEs. Such flushes would require the hypervisor to do more work than
1811 	 * necessary. Therefore, perform repeated flushes of aligned ranges
1812 	 * until you cover the range. Each iteration flushes the smaller
1813 	 * between the natural alignment of the address that we flush and the
1814 	 * greatest naturally aligned region that fits in the range.
1815 	 */
1816 	while (address <= last) {
1817 		unsigned int sz_lg2 = ilog2(last - address + 1);
1818 		u64 flush_last;
1819 
1820 		if (likely(address))
1821 			sz_lg2 = min_t(unsigned int, sz_lg2, __ffs64(address));
1822 
1823 		flush_last = address + (1ULL << sz_lg2) - 1;
1824 		__domain_flush_pages(domain, address, flush_last, flags);
1825 		if (check_add_overflow(flush_last, 1, &address))
1826 			break;
1827 	}
1828 
1829 	/* Wait until IOMMU TLB and all device IOTLB flushes are complete */
1830 	domain_flush_complete(domain);
1831 }
1832 
1833 /* Flush the whole IO/TLB for a given protection domain - including PDE */
1834 static void amd_iommu_domain_flush_all(struct protection_domain *domain)
1835 {
1836 	amd_iommu_domain_flush_pages(domain, 0, U64_MAX,
1837 				     CMD_INV_IOMMU_PAGES_PDE_MASK);
1838 }
1839 
1840 void amd_iommu_dev_flush_pasid_pages(struct iommu_dev_data *dev_data,
1841 				     ioasid_t pasid, u64 address, u64 last)
1842 {
1843 	struct iommu_cmd cmd;
1844 	struct amd_iommu *iommu = get_amd_iommu_from_dev(dev_data->dev);
1845 
1846 	build_inv_iommu_pages(&cmd, address, last,
1847 			      dev_data->gcr3_info.domid, pasid,
1848 			      CMD_INV_IOMMU_PAGES_GN_MASK |
1849 			      CMD_INV_IOMMU_PAGES_PDE_MASK);
1850 	iommu_queue_command(iommu, &cmd);
1851 
1852 	if (dev_data->ats_enabled)
1853 		device_flush_iotlb(dev_data, address, last, pasid, true);
1854 
1855 	iommu_completion_wait(iommu);
1856 }
1857 
1858 static void dev_flush_pasid_all(struct iommu_dev_data *dev_data,
1859 				ioasid_t pasid)
1860 {
1861 	amd_iommu_dev_flush_pasid_pages(dev_data, pasid, 0, U64_MAX);
1862 }
1863 
1864 static int __amd_iommu_complete_ppr(struct device *dev, u32 pasid,
1865 				    int status, int tag, bool gn)
1866 {
1867 	struct iommu_dev_data *dev_data;
1868 	struct amd_iommu *iommu;
1869 	struct iommu_cmd cmd;
1870 
1871 	dev_data = dev_iommu_priv_get(dev);
1872 	iommu    = get_amd_iommu_from_dev(dev);
1873 
1874 	build_complete_ppr(&cmd, dev_data->devid, pasid, status, tag, gn);
1875 
1876 	return iommu_queue_command(iommu, &cmd);
1877 }
1878 
1879 int amd_iommu_complete_ppr(struct device *dev, u32 pasid, int status, int tag)
1880 {
1881 	struct iommu_dev_data *dev_data = dev_iommu_priv_get(dev);
1882 	bool gn;
1883 
1884 	gn = pdom_is_v2_pgtbl_mode(dev_data->domain);
1885 
1886 	return __amd_iommu_complete_ppr(dev, pasid, status, tag, gn);
1887 }
1888 
1889 /****************************************************************************
1890  *
1891  * The next functions belong to the domain allocation. A domain is
1892  * allocated for every IOMMU as the default domain. If device isolation
1893  * is enabled, every device get its own domain. The most important thing
1894  * about domains is the page table mapping the DMA address space they
1895  * contain.
1896  *
1897  ****************************************************************************/
1898 int amd_iommu_pdom_id_alloc(void)
1899 {
1900 	return ida_alloc_range(&pdom_ids, 1, MAX_DOMAIN_ID - 1, GFP_ATOMIC);
1901 }
1902 
1903 int amd_iommu_pdom_id_reserve(u16 id, gfp_t gfp)
1904 {
1905 	return ida_alloc_range(&pdom_ids, id, id, gfp);
1906 }
1907 
1908 void amd_iommu_pdom_id_free(int id)
1909 {
1910 	ida_free(&pdom_ids, id);
1911 }
1912 
1913 void amd_iommu_pdom_id_destroy(void)
1914 {
1915 	ida_destroy(&pdom_ids);
1916 }
1917 
1918 static void free_gcr3_tbl_level1(u64 *tbl)
1919 {
1920 	u64 *ptr;
1921 	int i;
1922 
1923 	for (i = 0; i < 512; ++i) {
1924 		if (!(tbl[i] & GCR3_VALID))
1925 			continue;
1926 
1927 		ptr = iommu_phys_to_virt(tbl[i] & PAGE_MASK);
1928 
1929 		iommu_free_pages(ptr);
1930 	}
1931 }
1932 
1933 static void free_gcr3_tbl_level2(u64 *tbl)
1934 {
1935 	u64 *ptr;
1936 	int i;
1937 
1938 	for (i = 0; i < 512; ++i) {
1939 		if (!(tbl[i] & GCR3_VALID))
1940 			continue;
1941 
1942 		ptr = iommu_phys_to_virt(tbl[i] & PAGE_MASK);
1943 
1944 		free_gcr3_tbl_level1(ptr);
1945 	}
1946 }
1947 
1948 static void free_gcr3_table(struct gcr3_tbl_info *gcr3_info)
1949 {
1950 	if (gcr3_info->glx == 2)
1951 		free_gcr3_tbl_level2(gcr3_info->gcr3_tbl);
1952 	else if (gcr3_info->glx == 1)
1953 		free_gcr3_tbl_level1(gcr3_info->gcr3_tbl);
1954 	else
1955 		WARN_ON_ONCE(gcr3_info->glx != 0);
1956 
1957 	gcr3_info->glx = 0;
1958 
1959 	/* Free per device domain ID */
1960 	amd_iommu_pdom_id_free(gcr3_info->domid);
1961 
1962 	iommu_free_pages(gcr3_info->gcr3_tbl);
1963 	gcr3_info->gcr3_tbl = NULL;
1964 }
1965 
1966 /*
1967  * Number of GCR3 table levels required. Level must be 4-Kbyte
1968  * page and can contain up to 512 entries.
1969  */
1970 static int get_gcr3_levels(int pasids)
1971 {
1972 	int levels;
1973 
1974 	if (pasids == -1)
1975 		return amd_iommu_max_glx_val;
1976 
1977 	levels = get_count_order(pasids);
1978 
1979 	return levels ? (DIV_ROUND_UP(levels, 9) - 1) : levels;
1980 }
1981 
1982 static int setup_gcr3_table(struct gcr3_tbl_info *gcr3_info,
1983 			    struct amd_iommu *iommu, int pasids)
1984 {
1985 	int levels = get_gcr3_levels(pasids);
1986 	int nid = iommu ? dev_to_node(&iommu->dev->dev) : NUMA_NO_NODE;
1987 	int domid;
1988 
1989 	if (levels > amd_iommu_max_glx_val)
1990 		return -EINVAL;
1991 
1992 	if (gcr3_info->gcr3_tbl)
1993 		return -EBUSY;
1994 
1995 	/* Allocate per device domain ID */
1996 	domid = amd_iommu_pdom_id_alloc();
1997 	if (domid <= 0)
1998 		return -ENOSPC;
1999 	gcr3_info->domid = domid;
2000 
2001 	gcr3_info->gcr3_tbl = iommu_alloc_pages_node_sz(nid, GFP_ATOMIC, SZ_4K);
2002 	if (gcr3_info->gcr3_tbl == NULL) {
2003 		amd_iommu_pdom_id_free(domid);
2004 		return -ENOMEM;
2005 	}
2006 
2007 	gcr3_info->glx = levels;
2008 
2009 	return 0;
2010 }
2011 
2012 static u64 *__get_gcr3_pte(struct gcr3_tbl_info *gcr3_info,
2013 			   ioasid_t pasid, bool alloc)
2014 {
2015 	int index;
2016 	u64 *pte;
2017 	u64 *root = gcr3_info->gcr3_tbl;
2018 	int level = gcr3_info->glx;
2019 
2020 	while (true) {
2021 
2022 		index = (pasid >> (9 * level)) & 0x1ff;
2023 		pte   = &root[index];
2024 
2025 		if (level == 0)
2026 			break;
2027 
2028 		if (!(*pte & GCR3_VALID)) {
2029 			if (!alloc)
2030 				return NULL;
2031 
2032 			root = (void *)get_zeroed_page(GFP_ATOMIC);
2033 			if (root == NULL)
2034 				return NULL;
2035 
2036 			*pte = iommu_virt_to_phys(root) | GCR3_VALID;
2037 		}
2038 
2039 		root = iommu_phys_to_virt(*pte & PAGE_MASK);
2040 
2041 		level -= 1;
2042 	}
2043 
2044 	return pte;
2045 }
2046 
2047 static int update_gcr3(struct iommu_dev_data *dev_data,
2048 		       ioasid_t pasid, unsigned long gcr3, bool set)
2049 {
2050 	struct gcr3_tbl_info *gcr3_info = &dev_data->gcr3_info;
2051 	u64 *pte;
2052 
2053 	pte = __get_gcr3_pte(gcr3_info, pasid, true);
2054 	if (pte == NULL)
2055 		return -ENOMEM;
2056 
2057 	if (set)
2058 		*pte = (gcr3 & PAGE_MASK) | GCR3_VALID;
2059 	else
2060 		*pte = 0;
2061 
2062 	dev_flush_pasid_all(dev_data, pasid);
2063 	return 0;
2064 }
2065 
2066 int amd_iommu_set_gcr3(struct iommu_dev_data *dev_data, ioasid_t pasid,
2067 		       unsigned long gcr3)
2068 {
2069 	struct gcr3_tbl_info *gcr3_info = &dev_data->gcr3_info;
2070 	int ret;
2071 
2072 	iommu_group_mutex_assert(dev_data->dev);
2073 
2074 	ret = update_gcr3(dev_data, pasid, gcr3, true);
2075 	if (ret)
2076 		return ret;
2077 
2078 	gcr3_info->pasid_cnt++;
2079 	return ret;
2080 }
2081 
2082 int amd_iommu_clear_gcr3(struct iommu_dev_data *dev_data, ioasid_t pasid)
2083 {
2084 	struct gcr3_tbl_info *gcr3_info = &dev_data->gcr3_info;
2085 	int ret;
2086 
2087 	iommu_group_mutex_assert(dev_data->dev);
2088 
2089 	ret = update_gcr3(dev_data, pasid, 0, false);
2090 	if (ret)
2091 		return ret;
2092 
2093 	gcr3_info->pasid_cnt--;
2094 	return ret;
2095 }
2096 
2097 /*
2098  * Note:
2099  * The old value for GCR3 table and GPT have been cleared from caller.
2100  */
2101 static void set_dte_gcr3_table(struct iommu_dev_data *dev_data,
2102 			       struct dev_table_entry *new)
2103 {
2104 	struct gcr3_tbl_info *gcr3_info = &dev_data->gcr3_info;
2105 	u64 gcr3 = iommu_virt_to_phys(gcr3_info->gcr3_tbl);
2106 
2107 	new->data[0] |= DTE_FLAG_TV |
2108 			(dev_data->ppr ? DTE_FLAG_PPR : 0) |
2109 			(pdom_is_v2_pgtbl_mode(dev_data->domain) ?  DTE_FLAG_GIOV : 0) |
2110 			DTE_FLAG_GV |
2111 			FIELD_PREP(DTE_GLX, gcr3_info->glx) |
2112 			FIELD_PREP(DTE_GCR3_14_12, gcr3 >> 12) |
2113 			DTE_FLAG_IR | DTE_FLAG_IW;
2114 
2115 	new->data[1] |= FIELD_PREP(DTE_DOMID_MASK, dev_data->gcr3_info.domid) |
2116 			FIELD_PREP(DTE_GCR3_30_15, gcr3 >> 15) |
2117 			(dev_data->ats_enabled ? DTE_FLAG_IOTLB : 0) |
2118 			FIELD_PREP(DTE_GCR3_51_31, gcr3 >> 31);
2119 
2120 	/* Guest page table can only support 4 and 5 levels  */
2121 	if (amd_iommu_gpt_level == PAGE_MODE_5_LEVEL)
2122 		new->data[2] |= FIELD_PREP(DTE_GPT_LEVEL_MASK, GUEST_PGTABLE_5_LEVEL);
2123 	else
2124 		new->data[2] |= FIELD_PREP(DTE_GPT_LEVEL_MASK, GUEST_PGTABLE_4_LEVEL);
2125 }
2126 
2127 void amd_iommu_set_dte_v1(struct iommu_dev_data *dev_data,
2128 			  struct protection_domain *domain, u16 domid,
2129 			  struct pt_iommu_amdv1_hw_info *pt_info,
2130 			  struct dev_table_entry *new)
2131 {
2132 	u64 host_pt_root = __sme_set(pt_info->host_pt_root);
2133 
2134 	/* Note Dirty tracking is used for v1 table only for now */
2135 	new->data[0] |= DTE_FLAG_TV |
2136 			FIELD_PREP(DTE_MODE_MASK, pt_info->mode) |
2137 			(domain->dirty_tracking ? DTE_FLAG_HAD : 0) |
2138 			FIELD_PREP(DTE_HOST_TRP, host_pt_root >> 12) |
2139 			DTE_FLAG_IR | DTE_FLAG_IW;
2140 
2141 	new->data[1] |= FIELD_PREP(DTE_DOMID_MASK, domid) |
2142 			(dev_data->ats_enabled ? DTE_FLAG_IOTLB : 0);
2143 }
2144 
2145 static void set_dte_v1(struct iommu_dev_data *dev_data,
2146 		       struct protection_domain *domain, u16 domid,
2147 		       phys_addr_t top_paddr, unsigned int top_level,
2148 		       struct dev_table_entry *new)
2149 {
2150 	struct pt_iommu_amdv1_hw_info pt_info;
2151 
2152 	/*
2153 	 * When updating the IO pagetable, the new top and level
2154 	 * are provided as parameters. For other operations i.e.
2155 	 * device attach, retrieve the current pagetable info
2156 	 * via the IOMMU PT API.
2157 	 */
2158 	if (top_paddr) {
2159 		pt_info.host_pt_root = top_paddr;
2160 		pt_info.mode = top_level + 1;
2161 	} else {
2162 		WARN_ON(top_paddr || top_level);
2163 		pt_iommu_amdv1_hw_info(&domain->amdv1, &pt_info);
2164 	}
2165 
2166 	amd_iommu_set_dte_v1(dev_data, domain, domid, &pt_info, new);
2167 }
2168 
2169 static void set_dte_passthrough(struct iommu_dev_data *dev_data,
2170 				struct protection_domain *domain,
2171 				struct dev_table_entry *new)
2172 {
2173 	new->data[0] |= DTE_FLAG_TV | DTE_FLAG_IR | DTE_FLAG_IW;
2174 
2175 	new->data[1] |= FIELD_PREP(DTE_DOMID_MASK, domain->id) |
2176 			(dev_data->ats_enabled ? DTE_FLAG_IOTLB : 0);
2177 
2178 }
2179 
2180 static void set_dte_entry(struct amd_iommu *iommu,
2181 			  struct iommu_dev_data *dev_data,
2182 			  phys_addr_t top_paddr, unsigned int top_level)
2183 {
2184 	u32 old_domid;
2185 	struct dev_table_entry new = {};
2186 	struct protection_domain *domain = dev_data->domain;
2187 	struct gcr3_tbl_info *gcr3_info = &dev_data->gcr3_info;
2188 	struct dev_table_entry *dte = &get_dev_table(iommu)[dev_data->devid];
2189 
2190 	amd_iommu_make_clear_dte(dev_data, &new);
2191 
2192 	old_domid = READ_ONCE(dte->data[1]) & DTE_DOMID_MASK;
2193 	if (gcr3_info->gcr3_tbl)
2194 		set_dte_gcr3_table(dev_data, &new);
2195 	else if (domain->domain.type == IOMMU_DOMAIN_IDENTITY)
2196 		set_dte_passthrough(dev_data, domain, &new);
2197 	else if ((domain->domain.type & __IOMMU_DOMAIN_PAGING) &&
2198 		 domain->pd_mode == PD_MODE_V1)
2199 		set_dte_v1(dev_data, domain, domain->id, top_paddr, top_level, &new);
2200 	else
2201 		WARN_ON(true);
2202 
2203 	amd_iommu_update_dte(iommu, dev_data, &new);
2204 
2205 	/*
2206 	 * A kdump kernel might be replacing a domain ID that was copied from
2207 	 * the previous kernel--if so, it needs to flush the translation cache
2208 	 * entries for the old domain ID that is being overwritten
2209 	 */
2210 	if (old_domid) {
2211 		amd_iommu_flush_tlb_domid(iommu, old_domid);
2212 	}
2213 }
2214 
2215 /*
2216  * Clear DMA-remap related flags to block all DMA (blockeded domain)
2217  */
2218 static void clear_dte_entry(struct amd_iommu *iommu, struct iommu_dev_data *dev_data)
2219 {
2220 	struct dev_table_entry new = {};
2221 
2222 	amd_iommu_make_clear_dte(dev_data, &new);
2223 	amd_iommu_update_dte(iommu, dev_data, &new);
2224 }
2225 
2226 /* Update and flush DTE for the given device */
2227 static void dev_update_dte(struct iommu_dev_data *dev_data, bool set)
2228 {
2229 	struct amd_iommu *iommu = get_amd_iommu_from_dev(dev_data->dev);
2230 
2231 	if (set)
2232 		set_dte_entry(iommu, dev_data, 0, 0);
2233 	else
2234 		clear_dte_entry(iommu, dev_data);
2235 }
2236 
2237 /*
2238  * If domain is SVA capable then initialize GCR3 table. Also if domain is
2239  * in v2 page table mode then update GCR3[0].
2240  */
2241 static int init_gcr3_table(struct iommu_dev_data *dev_data,
2242 			   struct protection_domain *pdom)
2243 {
2244 	struct amd_iommu *iommu = get_amd_iommu_from_dev_data(dev_data);
2245 	int max_pasids = dev_data->max_pasids;
2246 	struct pt_iommu_x86_64_hw_info pt_info;
2247 	int ret = 0;
2248 
2249 	 /*
2250 	  * If domain is in pt mode then setup GCR3 table only if device
2251 	  * is PASID capable
2252 	  */
2253 	if (pdom_is_in_pt_mode(pdom) && !pdev_pasid_supported(dev_data))
2254 		return ret;
2255 
2256 	/*
2257 	 * By default, setup GCR3 table to support MAX PASIDs
2258 	 * supported by the device/IOMMU.
2259 	 */
2260 	ret = setup_gcr3_table(&dev_data->gcr3_info, iommu,
2261 			       max_pasids > 0 ?  max_pasids : 1);
2262 	if (ret)
2263 		return ret;
2264 
2265 	/* Setup GCR3[0] only if domain is setup with v2 page table mode */
2266 	if (!pdom_is_v2_pgtbl_mode(pdom))
2267 		return ret;
2268 
2269 	pt_iommu_x86_64_hw_info(&pdom->amdv2, &pt_info);
2270 	ret = update_gcr3(dev_data, 0, __sme_set(pt_info.gcr3_pt), true);
2271 	if (ret)
2272 		free_gcr3_table(&dev_data->gcr3_info);
2273 
2274 	return ret;
2275 }
2276 
2277 static void destroy_gcr3_table(struct iommu_dev_data *dev_data,
2278 			       struct protection_domain *pdom)
2279 {
2280 	struct gcr3_tbl_info *gcr3_info = &dev_data->gcr3_info;
2281 
2282 	if (pdom_is_v2_pgtbl_mode(pdom))
2283 		update_gcr3(dev_data, 0, 0, false);
2284 
2285 	if (gcr3_info->gcr3_tbl == NULL)
2286 		return;
2287 
2288 	free_gcr3_table(gcr3_info);
2289 }
2290 
2291 static int pdom_attach_iommu(struct amd_iommu *iommu,
2292 			     struct protection_domain *pdom)
2293 {
2294 	struct pdom_iommu_info *pdom_iommu_info, *curr;
2295 	unsigned long flags;
2296 	int ret = 0;
2297 
2298 	spin_lock_irqsave(&pdom->lock, flags);
2299 
2300 	pdom_iommu_info = xa_load(&pdom->iommu_array, iommu->index);
2301 	if (pdom_iommu_info) {
2302 		pdom_iommu_info->refcnt++;
2303 		goto out_unlock;
2304 	}
2305 
2306 	pdom_iommu_info = kzalloc_obj(*pdom_iommu_info, GFP_ATOMIC);
2307 	if (!pdom_iommu_info) {
2308 		ret = -ENOMEM;
2309 		goto out_unlock;
2310 	}
2311 
2312 	pdom_iommu_info->iommu = iommu;
2313 	pdom_iommu_info->refcnt = 1;
2314 
2315 	curr = xa_cmpxchg(&pdom->iommu_array, iommu->index,
2316 			  NULL, pdom_iommu_info, GFP_ATOMIC);
2317 	if (curr) {
2318 		kfree(pdom_iommu_info);
2319 		ret = -ENOSPC;
2320 		goto out_unlock;
2321 	}
2322 
2323 out_unlock:
2324 	spin_unlock_irqrestore(&pdom->lock, flags);
2325 	return ret;
2326 }
2327 
2328 static void pdom_detach_iommu(struct amd_iommu *iommu,
2329 			      struct protection_domain *pdom)
2330 {
2331 	struct pdom_iommu_info *pdom_iommu_info;
2332 	unsigned long flags;
2333 
2334 	spin_lock_irqsave(&pdom->lock, flags);
2335 
2336 	pdom_iommu_info = xa_load(&pdom->iommu_array, iommu->index);
2337 	if (!pdom_iommu_info) {
2338 		spin_unlock_irqrestore(&pdom->lock, flags);
2339 		return;
2340 	}
2341 
2342 	pdom_iommu_info->refcnt--;
2343 	if (pdom_iommu_info->refcnt == 0) {
2344 		xa_erase(&pdom->iommu_array, iommu->index);
2345 		kfree(pdom_iommu_info);
2346 	}
2347 
2348 	spin_unlock_irqrestore(&pdom->lock, flags);
2349 }
2350 
2351 /*
2352  * If a device is not yet associated with a domain, this function makes the
2353  * device visible in the domain
2354  */
2355 static int attach_device(struct device *dev,
2356 			 struct protection_domain *domain)
2357 {
2358 	struct iommu_dev_data *dev_data = dev_iommu_priv_get(dev);
2359 	struct amd_iommu *iommu = get_amd_iommu_from_dev_data(dev_data);
2360 	struct pci_dev *pdev;
2361 	unsigned long flags;
2362 	int ret = 0;
2363 
2364 	mutex_lock(&dev_data->mutex);
2365 
2366 	if (dev_data->domain != NULL) {
2367 		ret = -EBUSY;
2368 		goto out;
2369 	}
2370 
2371 	/* Do reference counting */
2372 	ret = pdom_attach_iommu(iommu, domain);
2373 	if (ret)
2374 		goto out;
2375 
2376 	if (dev_data->perfopt && pdom_is_in_pt_mode(domain))
2377 		goto skip_caps;
2378 
2379 	/* Setup GCR3 table */
2380 	if (pdom_is_sva_capable(domain)) {
2381 		ret = init_gcr3_table(dev_data, domain);
2382 		if (ret) {
2383 			pdom_detach_iommu(iommu, domain);
2384 			goto out;
2385 		}
2386 	}
2387 
2388 	pdev = dev_is_pci(dev_data->dev) ? to_pci_dev(dev_data->dev) : NULL;
2389 	if (pdev && pdom_is_sva_capable(domain)) {
2390 		pdev_enable_caps(pdev);
2391 
2392 		/*
2393 		 * Device can continue to function even if IOPF
2394 		 * enablement failed. Hence in error path just
2395 		 * disable device PRI support.
2396 		 */
2397 		if (amd_iommu_iopf_add_device(iommu, dev_data))
2398 			pdev_disable_cap_pri(pdev);
2399 	} else if (pdev) {
2400 		pdev_enable_cap_ats(pdev);
2401 	}
2402 
2403 skip_caps:
2404 	/* Update data structures */
2405 	dev_data->domain = domain;
2406 	spin_lock_irqsave(&domain->lock, flags);
2407 	list_add(&dev_data->list, &domain->dev_list);
2408 	spin_unlock_irqrestore(&domain->lock, flags);
2409 
2410 	/* Update device table */
2411 	dev_update_dte(dev_data, true);
2412 
2413 out:
2414 	mutex_unlock(&dev_data->mutex);
2415 
2416 	return ret;
2417 }
2418 
2419 /*
2420  * Removes a device from a protection domain (with devtable_lock held)
2421  */
2422 static void detach_device(struct device *dev)
2423 {
2424 	struct iommu_dev_data *dev_data = dev_iommu_priv_get(dev);
2425 	struct amd_iommu *iommu = get_amd_iommu_from_dev_data(dev_data);
2426 	struct protection_domain *domain = dev_data->domain;
2427 	unsigned long flags;
2428 
2429 	mutex_lock(&dev_data->mutex);
2430 
2431 	/*
2432 	 * First check if the device is still attached. It might already
2433 	 * be detached from its domain because the generic
2434 	 * iommu_detach_group code detached it and we try again here in
2435 	 * our alias handling.
2436 	 */
2437 	if (WARN_ON(!dev_data->domain))
2438 		goto out;
2439 
2440 	/* Remove IOPF handler */
2441 	if (dev_data->ppr) {
2442 		iopf_queue_flush_dev(dev);
2443 		amd_iommu_iopf_remove_device(iommu, dev_data);
2444 	}
2445 
2446 	if (dev_is_pci(dev))
2447 		pdev_disable_caps(to_pci_dev(dev));
2448 
2449 	/* Clear DTE and flush the entry */
2450 	dev_update_dte(dev_data, false);
2451 
2452 	/* Flush IOTLB and wait for the flushes to finish */
2453 	spin_lock_irqsave(&domain->lock, flags);
2454 	amd_iommu_domain_flush_all(domain);
2455 	list_del(&dev_data->list);
2456 	spin_unlock_irqrestore(&domain->lock, flags);
2457 
2458 	/* Clear GCR3 table */
2459 	if (pdom_is_sva_capable(domain))
2460 		destroy_gcr3_table(dev_data, domain);
2461 
2462 	/* Update data structures */
2463 	dev_data->domain = NULL;
2464 
2465 	/* decrease reference counters - needs to happen after the flushes */
2466 	pdom_detach_iommu(iommu, domain);
2467 
2468 out:
2469 	mutex_unlock(&dev_data->mutex);
2470 }
2471 
2472 static int iommu_init_device_caps(struct iommu_dev_data *dev_data,
2473 				  struct device *dev,
2474 				  struct amd_iommu *iommu)
2475 {
2476 	int ret;
2477 
2478 	if (FEATURE_NUM_INT_REMAP_SUP_2K(amd_iommu_efr2))
2479 		dev_data->max_irqs = MAX_IRQS_PER_TABLE_2K;
2480 	else
2481 		dev_data->max_irqs = MAX_IRQS_PER_TABLE_512;
2482 
2483 	amd_iommu_set_pci_msi_domain(dev, iommu);
2484 
2485 	if (!dev_is_pci(dev))
2486 		return 0;
2487 
2488 	/*
2489 	 * By default we use passthrough mode for IOMMUv2 capable device.
2490 	 * But if amd_iommu=force_isolation is set (e.g. to debug DMA to
2491 	 * invalid address), we ignore the capability for the device so
2492 	 * it'll be forced to go into translation mode.
2493 	 */
2494 	if ((iommu_default_passthrough() || !amd_iommu_force_isolation) &&
2495 	    amd_iommu_gt_ppr_supported()) {
2496 		dev_data->flags = pdev_get_caps(to_pci_dev(dev));
2497 	}
2498 
2499 	/*
2500 	 * If IOMMU and device supports PASID then it will contain max
2501 	 * supported PASIDs, else it will be zero.
2502 	 */
2503 	if (amd_iommu_pasid_supported() &&
2504 	    pdev_pasid_supported(dev_data)) {
2505 		dev_data->max_pasids = min_t(u32, iommu->iommu.max_pasids,
2506 					     pci_max_pasids(to_pci_dev(dev)));
2507 	}
2508 
2509 	if (pci_ats_supported(to_pci_dev(dev))) {
2510 		ret = pci_prepare_ats(to_pci_dev(dev), PAGE_SHIFT);
2511 		if (ret)
2512 			return ret;
2513 	}
2514 
2515 	return 0;
2516 }
2517 
2518 static struct iommu_device *amd_iommu_probe_device(struct device *dev)
2519 {
2520 	struct iommu_device *iommu_dev;
2521 	struct amd_iommu *iommu;
2522 	struct iommu_dev_data *dev_data;
2523 	u16 devid;
2524 	int ret;
2525 
2526 	if (!lookup_device(dev, &iommu, &devid))
2527 		return ERR_PTR(-ENODEV);
2528 
2529 	if (dev_iommu_priv_get(dev))
2530 		return &iommu->iommu;
2531 
2532 	dev_data = iommu_init_device(iommu, dev, devid);
2533 	if (IS_ERR(dev_data)) {
2534 		dev_err(dev, "Failed to initialize - trying to proceed anyway\n");
2535 		return ERR_CAST(dev_data);
2536 	}
2537 
2538 	ret = iommu_init_device_caps(dev_data, dev, iommu);
2539 	if (ret)
2540 		return ERR_PTR(ret);
2541 
2542 	iommu_dev = &iommu->iommu;
2543 
2544 	/*
2545 	 * When DMA translation is unavailable return error so the iommu core
2546 	 * won't attempt domain attach for this device, while preserving its
2547 	 * rlookup entry for interrupt remapping.
2548 	 */
2549 	if (amd_iommu_pgtable == PD_MODE_NONE) {
2550 		pr_warn_once("%s: DMA translation not supported by iommu.\n",
2551 			     __func__);
2552 		return ERR_PTR(-ENODEV);
2553 	}
2554 
2555 	return iommu_dev;
2556 }
2557 
2558 static struct iommu_group *amd_iommu_device_group(struct device *dev)
2559 {
2560 	if (dev_is_pci(dev))
2561 		return pci_device_group(dev);
2562 
2563 	return acpihid_device_group(dev);
2564 }
2565 
2566 /*****************************************************************************
2567  *
2568  * The following functions belong to the exported interface of AMD IOMMU
2569  *
2570  * This interface allows access to lower level functions of the IOMMU
2571  * like protection domain handling and assignement of devices to domains
2572  * which is not possible with the dma_ops interface.
2573  *
2574  *****************************************************************************/
2575 
2576 static void protection_domain_init(struct protection_domain *domain)
2577 {
2578 	spin_lock_init(&domain->lock);
2579 	INIT_LIST_HEAD(&domain->dev_list);
2580 	INIT_LIST_HEAD(&domain->dev_data_list);
2581 	INIT_LIST_HEAD(&domain->viommu_list);
2582 	xa_init(&domain->iommu_array);
2583 }
2584 
2585 struct protection_domain *protection_domain_alloc(void)
2586 {
2587 	struct protection_domain *domain;
2588 	int domid;
2589 
2590 	domain = kzalloc_obj(*domain);
2591 	if (!domain)
2592 		return NULL;
2593 
2594 	domid = amd_iommu_pdom_id_alloc();
2595 	if (domid <= 0) {
2596 		kfree(domain);
2597 		return NULL;
2598 	}
2599 	domain->id = domid;
2600 
2601 	protection_domain_init(domain);
2602 
2603 	return domain;
2604 }
2605 
2606 static bool amd_iommu_hd_support(struct amd_iommu *iommu)
2607 {
2608 	if (amd_iommu_hatdis)
2609 		return false;
2610 
2611 	return iommu && (iommu->features & FEATURE_HDSUP);
2612 }
2613 
2614 static spinlock_t *amd_iommu_get_top_lock(struct pt_iommu *iommupt)
2615 {
2616 	struct protection_domain *pdom =
2617 		container_of(iommupt, struct protection_domain, iommu);
2618 
2619 	return &pdom->lock;
2620 }
2621 
2622 /*
2623  * Update all HW references to the domain with a new pgtable configuration.
2624  */
2625 static void amd_iommu_change_top(struct pt_iommu *iommu_table,
2626 				 phys_addr_t top_paddr, unsigned int top_level)
2627 {
2628 	struct protection_domain *pdom =
2629 		container_of(iommu_table, struct protection_domain, iommu);
2630 	struct iommu_dev_data *dev_data;
2631 
2632 	lockdep_assert_held(&pdom->lock);
2633 
2634 	/* Update the DTE for all devices attached to this domain */
2635 	list_for_each_entry(dev_data, &pdom->dev_list, list) {
2636 		struct amd_iommu *iommu = rlookup_amd_iommu(dev_data->dev);
2637 
2638 		/* Update the HW references with the new level and top ptr */
2639 		set_dte_entry(iommu, dev_data, top_paddr, top_level);
2640 		clone_aliases(iommu, dev_data->dev);
2641 	}
2642 
2643 	list_for_each_entry(dev_data, &pdom->dev_list, list)
2644 		device_flush_dte(dev_data);
2645 
2646 	domain_flush_complete(pdom);
2647 }
2648 
2649 /*
2650  * amd_iommu_iotlb_sync_map() is used to generate flushes for non-present to
2651  * present (ie mapping) operations. It is a NOP if the IOMMU doesn't have non
2652  * present caching (like hypervisor shadowing).
2653  */
2654 static int amd_iommu_iotlb_sync_map(struct iommu_domain *dom,
2655 				    unsigned long iova, size_t size)
2656 {
2657 	struct protection_domain *domain = to_pdomain(dom);
2658 	unsigned long flags;
2659 
2660 	if (likely(!amd_iommu_np_cache))
2661 		return 0;
2662 
2663 	spin_lock_irqsave(&domain->lock, flags);
2664 	amd_iommu_domain_flush_pages(domain, iova, iova + size - 1,
2665 				     CMD_INV_IOMMU_PAGES_PDE_MASK);
2666 	spin_unlock_irqrestore(&domain->lock, flags);
2667 	return 0;
2668 }
2669 
2670 static void amd_iommu_flush_iotlb_all(struct iommu_domain *domain)
2671 {
2672 	struct protection_domain *dom = to_pdomain(domain);
2673 	unsigned long flags;
2674 
2675 	spin_lock_irqsave(&dom->lock, flags);
2676 	amd_iommu_domain_flush_all(dom);
2677 	spin_unlock_irqrestore(&dom->lock, flags);
2678 }
2679 
2680 static void amd_iommu_iotlb_sync(struct iommu_domain *domain,
2681 				 struct iommu_iotlb_gather *gather)
2682 {
2683 	struct protection_domain *dom = to_pdomain(domain);
2684 	unsigned long flags;
2685 
2686 	spin_lock_irqsave(&dom->lock, flags);
2687 	amd_iommu_domain_flush_pages(dom, gather->start, gather->end,
2688 				     iommu_pages_list_empty(&gather->freelist) ?
2689 				     0 : CMD_INV_IOMMU_PAGES_PDE_MASK);
2690 	spin_unlock_irqrestore(&dom->lock, flags);
2691 	iommu_put_pages_list(&gather->freelist);
2692 }
2693 
2694 static const struct pt_iommu_driver_ops amd_hw_driver_ops_v1 = {
2695 	.get_top_lock = amd_iommu_get_top_lock,
2696 	.change_top = amd_iommu_change_top,
2697 };
2698 
2699 static const struct iommu_domain_ops amdv1_ops = {
2700 	IOMMU_PT_DOMAIN_OPS(amdv1),
2701 	.iotlb_sync_map = amd_iommu_iotlb_sync_map,
2702 	.flush_iotlb_all = amd_iommu_flush_iotlb_all,
2703 	.iotlb_sync = amd_iommu_iotlb_sync,
2704 	.attach_dev = amd_iommu_attach_device,
2705 	.free = amd_iommu_domain_free,
2706 	.enforce_cache_coherency = amd_iommu_enforce_cache_coherency,
2707 };
2708 
2709 static const struct iommu_dirty_ops amdv1_dirty_ops = {
2710 	IOMMU_PT_DIRTY_OPS(amdv1),
2711 	.set_dirty_tracking = amd_iommu_set_dirty_tracking,
2712 };
2713 
2714 static struct iommu_domain *amd_iommu_domain_alloc_paging_v1(struct device *dev,
2715 							     u32 flags)
2716 {
2717 	struct pt_iommu_amdv1_cfg cfg = {};
2718 	struct protection_domain *domain;
2719 	int ret;
2720 
2721 	if (amd_iommu_hatdis)
2722 		return ERR_PTR(-EOPNOTSUPP);
2723 
2724 	domain = protection_domain_alloc();
2725 	if (!domain)
2726 		return ERR_PTR(-ENOMEM);
2727 
2728 	domain->pd_mode = PD_MODE_V1;
2729 	domain->iommu.driver_ops = &amd_hw_driver_ops_v1;
2730 	domain->iommu.nid = dev_to_node(dev);
2731 	if (flags & IOMMU_HWPT_ALLOC_DIRTY_TRACKING)
2732 		domain->domain.dirty_ops = &amdv1_dirty_ops;
2733 
2734 	/*
2735 	 * Someday FORCE_COHERENCE should be set by
2736 	 * amd_iommu_enforce_cache_coherency() like VT-d does.
2737 	 */
2738 	cfg.common.features = BIT(PT_FEAT_DYNAMIC_TOP) |
2739 			      BIT(PT_FEAT_AMDV1_ENCRYPT_TABLES) |
2740 			      BIT(PT_FEAT_AMDV1_FORCE_COHERENCE);
2741 
2742 	/*
2743 	 * AMD's IOMMU can flush as many pages as necessary in a single flush.
2744 	 * Unless we run in a virtual machine, which can be inferred according
2745 	 * to whether "non-present cache" is on, it is probably best to prefer
2746 	 * (potentially) too extensive TLB flushing (i.e., more misses) over
2747 	 * multiple TLB flushes (i.e., more flushes). For virtual machines the
2748 	 * hypervisor needs to synchronize the host IOMMU PTEs with those of
2749 	 * the guest, and the trade-off is different: unnecessary TLB flushes
2750 	 * should be avoided.
2751 	 */
2752 	if (amd_iommu_np_cache)
2753 		cfg.common.features |= BIT(PT_FEAT_FLUSH_RANGE_NO_GAPS);
2754 	else
2755 		cfg.common.features |= BIT(PT_FEAT_FLUSH_RANGE);
2756 
2757 	cfg.common.hw_max_vasz_lg2 = amd_iommu_hpt_vasize;
2758 	cfg.common.hw_max_oasz_lg2 = 52;
2759 	cfg.starting_level = 2;
2760 	domain->domain.ops = &amdv1_ops;
2761 
2762 	ret = pt_iommu_amdv1_init(&domain->amdv1, &cfg, GFP_KERNEL);
2763 	if (ret) {
2764 		amd_iommu_domain_free(&domain->domain);
2765 		return ERR_PTR(ret);
2766 	}
2767 
2768 	/*
2769 	 * Narrow the supported page sizes to those selected by the kernel
2770 	 * command line.
2771 	 */
2772 	domain->domain.pgsize_bitmap &= amd_iommu_pgsize_bitmap;
2773 	return &domain->domain;
2774 }
2775 
2776 static const struct iommu_domain_ops amdv2_ops = {
2777 	IOMMU_PT_DOMAIN_OPS(x86_64),
2778 	.iotlb_sync_map = amd_iommu_iotlb_sync_map,
2779 	.flush_iotlb_all = amd_iommu_flush_iotlb_all,
2780 	.iotlb_sync = amd_iommu_iotlb_sync,
2781 	.attach_dev = amd_iommu_attach_device,
2782 	.free = amd_iommu_domain_free,
2783 	/*
2784 	 * Note the AMDv2 page table format does not support a Force Coherency
2785 	 * bit, so enforce_cache_coherency should not be set. However VFIO is
2786 	 * not prepared to handle a case where some domains will support
2787 	 * enforcement and others do not. VFIO and iommufd will have to be fixed
2788 	 * before it can fully use the V2 page table. See the comment in
2789 	 * iommufd_hwpt_paging_alloc(). For now leave things as they have
2790 	 * historically been and lie about enforce_cache_coherencey.
2791 	 */
2792 	.enforce_cache_coherency = amd_iommu_enforce_cache_coherency,
2793 };
2794 
2795 static struct iommu_domain *amd_iommu_domain_alloc_paging_v2(struct device *dev,
2796 							     u32 flags)
2797 {
2798 	struct pt_iommu_x86_64_cfg cfg = {};
2799 	struct protection_domain *domain;
2800 	int ret;
2801 
2802 	if (!amd_iommu_v2_pgtbl_supported())
2803 		return ERR_PTR(-EOPNOTSUPP);
2804 
2805 	domain = protection_domain_alloc();
2806 	if (!domain)
2807 		return ERR_PTR(-ENOMEM);
2808 
2809 	domain->pd_mode = PD_MODE_V2;
2810 	domain->iommu.nid = dev_to_node(dev);
2811 
2812 	cfg.common.features = BIT(PT_FEAT_X86_64_AMD_ENCRYPT_TABLES);
2813 	if (amd_iommu_np_cache)
2814 		cfg.common.features |= BIT(PT_FEAT_FLUSH_RANGE_NO_GAPS);
2815 	else
2816 		cfg.common.features |= BIT(PT_FEAT_FLUSH_RANGE);
2817 
2818 	/*
2819 	 * The v2 table behaves differently if it is attached to PASID 0 vs a
2820 	 * non-zero PASID. On PASID 0 it has no sign extension and the full
2821 	 * 57/48 bits decode the lower addresses. Otherwise it behaves like a
2822 	 * normal sign extended x86 page table. Since we want the domain to work
2823 	 * in both modes the top bit is removed and PT_FEAT_SIGN_EXTEND is not
2824 	 * set which creates a table that is compatible in both modes.
2825 	 */
2826 	if (amd_iommu_gpt_level == PAGE_MODE_5_LEVEL) {
2827 		cfg.common.hw_max_vasz_lg2 = 56;
2828 		cfg.top_level = 4;
2829 	} else {
2830 		cfg.common.hw_max_vasz_lg2 = 47;
2831 		cfg.top_level = 3;
2832 	}
2833 	cfg.common.hw_max_oasz_lg2 = 52;
2834 	domain->domain.ops = &amdv2_ops;
2835 
2836 	ret = pt_iommu_x86_64_init(&domain->amdv2, &cfg, GFP_KERNEL);
2837 	if (ret) {
2838 		amd_iommu_domain_free(&domain->domain);
2839 		return ERR_PTR(ret);
2840 	}
2841 	return &domain->domain;
2842 }
2843 
2844 static inline bool is_nest_parent_supported(u32 flags)
2845 {
2846 	/* Only allow nest parent when these features are supported */
2847 	return check_feature(FEATURE_GT) &&
2848 	       check_feature(FEATURE_GIOSUP) &&
2849 	       check_feature2(FEATURE_GCR3TRPMODE);
2850 }
2851 
2852 static struct iommu_domain *
2853 amd_iommu_domain_alloc_paging_flags(struct device *dev, u32 flags,
2854 				    const struct iommu_user_data *user_data)
2855 
2856 {
2857 	struct amd_iommu *iommu = get_amd_iommu_from_dev(dev);
2858 	const u32 supported_flags = IOMMU_HWPT_ALLOC_DIRTY_TRACKING |
2859 						IOMMU_HWPT_ALLOC_PASID |
2860 						IOMMU_HWPT_ALLOC_NEST_PARENT;
2861 
2862 	if ((flags & ~supported_flags) || user_data)
2863 		return ERR_PTR(-EOPNOTSUPP);
2864 
2865 	switch (flags & supported_flags) {
2866 	case IOMMU_HWPT_ALLOC_DIRTY_TRACKING:
2867 	case IOMMU_HWPT_ALLOC_NEST_PARENT:
2868 	case IOMMU_HWPT_ALLOC_DIRTY_TRACKING | IOMMU_HWPT_ALLOC_NEST_PARENT:
2869 		/*
2870 		 * Allocate domain with v1 page table for dirty tracking
2871 		 * and/or Nest parent.
2872 		 */
2873 		if ((flags & IOMMU_HWPT_ALLOC_DIRTY_TRACKING) &&
2874 		    !amd_iommu_hd_support(iommu))
2875 			break;
2876 
2877 		if ((flags & IOMMU_HWPT_ALLOC_NEST_PARENT) &&
2878 		    !is_nest_parent_supported(flags))
2879 			break;
2880 
2881 		return amd_iommu_domain_alloc_paging_v1(dev, flags);
2882 	case IOMMU_HWPT_ALLOC_PASID:
2883 		/* Allocate domain with v2 page table if IOMMU supports PASID. */
2884 		if (!amd_iommu_pasid_supported())
2885 			break;
2886 		return amd_iommu_domain_alloc_paging_v2(dev, flags);
2887 	case 0: {
2888 		struct iommu_domain *ret;
2889 
2890 		/* If nothing specific is required use the kernel commandline default */
2891 		if (amd_iommu_pgtable == PD_MODE_V1) {
2892 			ret = amd_iommu_domain_alloc_paging_v1(dev, flags);
2893 			if (ret != ERR_PTR(-EOPNOTSUPP))
2894 				return ret;
2895 			return amd_iommu_domain_alloc_paging_v2(dev, flags);
2896 		}
2897 		ret = amd_iommu_domain_alloc_paging_v2(dev, flags);
2898 		if (ret != ERR_PTR(-EOPNOTSUPP))
2899 			return ret;
2900 		return amd_iommu_domain_alloc_paging_v1(dev, flags);
2901 	}
2902 	default:
2903 		break;
2904 	}
2905 	return ERR_PTR(-EOPNOTSUPP);
2906 }
2907 
2908 void amd_iommu_domain_free(struct iommu_domain *dom)
2909 {
2910 	struct protection_domain *domain = to_pdomain(dom);
2911 
2912 	WARN_ON(!list_empty(&domain->dev_list));
2913 	pt_iommu_deinit(&domain->iommu);
2914 	amd_iommu_pdom_id_free(domain->id);
2915 	kfree(domain);
2916 }
2917 
2918 /* Each IOMMU has at most one PerfOpt-eligible GPU. */
2919 static int set_device_perfopt(struct iommu_dev_data *dev_data, bool enable)
2920 {
2921 	struct amd_iommu *iommu = get_amd_iommu_from_dev_data(dev_data);
2922 
2923 	if (!dev_data->perfopt)
2924 		return 0;
2925 
2926 	guard(raw_spinlock_irqsave)(&iommu->lock);
2927 	if (iommu->perfopt_enabled == enable)
2928 		return 0;
2929 
2930 	return amd_iommu_perfopt_set(iommu, enable);
2931 }
2932 
2933 static int blocked_domain_attach_device(struct iommu_domain *domain,
2934 					struct device *dev,
2935 					struct iommu_domain *old)
2936 {
2937 	struct iommu_dev_data *dev_data = dev_iommu_priv_get(dev);
2938 	int ret;
2939 
2940 	/* Clearing the DTE cannot block DMA while PerfOpt bypasses it. */
2941 	ret = set_device_perfopt(dev_data, false);
2942 	if (ret)
2943 		return ret;
2944 
2945 	if (dev_data->domain)
2946 		detach_device(dev);
2947 
2948 	/* Clear DTE and flush the entry */
2949 	mutex_lock(&dev_data->mutex);
2950 	dev_update_dte(dev_data, false);
2951 	mutex_unlock(&dev_data->mutex);
2952 
2953 	return 0;
2954 }
2955 
2956 static int blocked_domain_set_dev_pasid(struct iommu_domain *domain,
2957 					struct device *dev, ioasid_t pasid,
2958 					struct iommu_domain *old)
2959 {
2960 	amd_iommu_remove_dev_pasid(dev, pasid, old);
2961 	return 0;
2962 }
2963 
2964 static struct iommu_domain blocked_domain = {
2965 	.type = IOMMU_DOMAIN_BLOCKED,
2966 	.ops = &(const struct iommu_domain_ops) {
2967 		.attach_dev     = blocked_domain_attach_device,
2968 		.set_dev_pasid  = blocked_domain_set_dev_pasid,
2969 	}
2970 };
2971 
2972 static struct protection_domain identity_domain;
2973 
2974 static int amd_iommu_identity_attach(struct iommu_domain *dom, struct device *dev,
2975 				     struct iommu_domain *old)
2976 {
2977 	struct iommu_dev_data *dev_data = dev_iommu_priv_get(dev);
2978 	int ret;
2979 
2980 	/*
2981 	 * Don't allow attaching a device to the identity domain if SNP is
2982 	 * enabled and SNP Mode0 support is not present.
2983 	 */
2984 	if (amd_iommu_snp_en && !amd_iommu_snp_mode0_sup)
2985 		return -EINVAL;
2986 
2987 	ret = amd_iommu_attach_device(dom, dev, old);
2988 	if (ret)
2989 		return ret;
2990 
2991 	/* PerfOpt is optional; the identity attachment is already complete. */
2992 	set_device_perfopt(dev_data, true);
2993 	return 0;
2994 }
2995 
2996 static const struct iommu_domain_ops identity_domain_ops = {
2997 	.attach_dev = amd_iommu_identity_attach,
2998 };
2999 
3000 void amd_iommu_init_identity_domain(void)
3001 {
3002 	struct iommu_domain *domain = &identity_domain.domain;
3003 
3004 	domain->type = IOMMU_DOMAIN_IDENTITY;
3005 	domain->ops = &identity_domain_ops;
3006 	domain->owner = &amd_iommu_ops;
3007 
3008 	identity_domain.id = amd_iommu_pdom_id_alloc();
3009 
3010 	protection_domain_init(&identity_domain);
3011 }
3012 
3013 static int amd_iommu_attach_device(struct iommu_domain *dom, struct device *dev,
3014 				   struct iommu_domain *old)
3015 {
3016 	struct iommu_dev_data *dev_data = dev_iommu_priv_get(dev);
3017 	struct protection_domain *domain = to_pdomain(dom);
3018 	struct amd_iommu *iommu = get_amd_iommu_from_dev(dev);
3019 	int ret;
3020 
3021 	/*
3022 	 * Skip attach device to domain if new domain is same as
3023 	 * devices current domain
3024 	 */
3025 	if (dev_data->domain == domain)
3026 		return 0;
3027 
3028 	dev_data->defer_attach = false;
3029 
3030 	/*
3031 	 * Restrict to devices with compatible IOMMU hardware support
3032 	 * when enforcement of dirty tracking is enabled.
3033 	 */
3034 	if (dom->dirty_ops && !amd_iommu_hd_support(iommu))
3035 		return -EINVAL;
3036 
3037 	if (!pdom_is_in_pt_mode(domain)) {
3038 		ret = set_device_perfopt(dev_data, false);
3039 		if (ret)
3040 			return ret;
3041 	}
3042 
3043 	if (dev_data->domain)
3044 		detach_device(dev);
3045 
3046 	ret = attach_device(dev, domain);
3047 
3048 #ifdef CONFIG_IRQ_REMAP
3049 	if (AMD_IOMMU_GUEST_IR_VAPIC(amd_iommu_guest_ir)) {
3050 		if (dom->type == IOMMU_DOMAIN_UNMANAGED)
3051 			dev_data->use_vapic = 1;
3052 		else
3053 			dev_data->use_vapic = 0;
3054 	}
3055 #endif
3056 
3057 	return ret;
3058 }
3059 
3060 static bool amd_iommu_capable(struct device *dev, enum iommu_cap cap)
3061 {
3062 	switch (cap) {
3063 	case IOMMU_CAP_CACHE_COHERENCY:
3064 		return true;
3065 	case IOMMU_CAP_NOEXEC:
3066 		return false;
3067 	case IOMMU_CAP_PRE_BOOT_PROTECTION:
3068 		return amdr_ivrs_remap_support;
3069 	case IOMMU_CAP_ENFORCE_CACHE_COHERENCY:
3070 		return true;
3071 	case IOMMU_CAP_DIRTY_TRACKING: {
3072 		struct amd_iommu *iommu = get_amd_iommu_from_dev(dev);
3073 
3074 		return amd_iommu_hd_support(iommu);
3075 	}
3076 	case IOMMU_CAP_PCI_ATS_SUPPORTED: {
3077 		struct iommu_dev_data *dev_data = dev_iommu_priv_get(dev);
3078 
3079 		return amd_iommu_iotlb_sup &&
3080 			 (dev_data->flags & AMD_IOMMU_DEVICE_FLAG_ATS_SUP);
3081 	}
3082 	default:
3083 		break;
3084 	}
3085 
3086 	return false;
3087 }
3088 
3089 static int amd_iommu_set_dirty_tracking(struct iommu_domain *domain,
3090 					bool enable)
3091 {
3092 	struct protection_domain *pdomain = to_pdomain(domain);
3093 	struct dev_table_entry *dte;
3094 	struct iommu_dev_data *dev_data;
3095 	bool domain_flush = false;
3096 	struct amd_iommu *iommu;
3097 	unsigned long flags;
3098 	u64 new;
3099 
3100 	spin_lock_irqsave(&pdomain->lock, flags);
3101 	if (!(pdomain->dirty_tracking ^ enable)) {
3102 		spin_unlock_irqrestore(&pdomain->lock, flags);
3103 		return 0;
3104 	}
3105 
3106 	list_for_each_entry(dev_data, &pdomain->dev_list, list) {
3107 		spin_lock(&dev_data->dte_lock);
3108 		iommu = get_amd_iommu_from_dev_data(dev_data);
3109 		dte = &get_dev_table(iommu)[dev_data->devid];
3110 		new = dte->data[0];
3111 		new = (enable ? new | DTE_FLAG_HAD : new & ~DTE_FLAG_HAD);
3112 		dte->data[0] = new;
3113 		spin_unlock(&dev_data->dte_lock);
3114 
3115 		/* Flush device DTE */
3116 		device_flush_dte(dev_data);
3117 		domain_flush = true;
3118 	}
3119 
3120 	/* Flush IOTLB to mark IOPTE dirty on the next translation(s) */
3121 	if (domain_flush)
3122 		amd_iommu_domain_flush_all(pdomain);
3123 
3124 	pdomain->dirty_tracking = enable;
3125 	spin_unlock_irqrestore(&pdomain->lock, flags);
3126 
3127 	return 0;
3128 }
3129 
3130 static void amd_iommu_get_resv_regions(struct device *dev,
3131 				       struct list_head *head)
3132 {
3133 	struct iommu_resv_region *region;
3134 	struct unity_map_entry *entry;
3135 	struct amd_iommu *iommu;
3136 	struct amd_iommu_pci_seg *pci_seg;
3137 	int devid, sbdf;
3138 
3139 	sbdf = get_device_sbdf_id(dev);
3140 	if (sbdf < 0)
3141 		return;
3142 
3143 	devid = PCI_SBDF_TO_DEVID(sbdf);
3144 	iommu = get_amd_iommu_from_dev(dev);
3145 	pci_seg = iommu->pci_seg;
3146 
3147 	list_for_each_entry(entry, &pci_seg->unity_map, list) {
3148 		int type, prot = 0;
3149 		size_t length;
3150 
3151 		if (devid < entry->devid_start || devid > entry->devid_end)
3152 			continue;
3153 
3154 		type   = IOMMU_RESV_DIRECT;
3155 		length = entry->address_end - entry->address_start;
3156 		if (entry->prot & IOMMU_PROT_IR)
3157 			prot |= IOMMU_READ;
3158 		if (entry->prot & IOMMU_PROT_IW)
3159 			prot |= IOMMU_WRITE;
3160 
3161 		region = iommu_alloc_resv_region(entry->address_start,
3162 						 length, prot, type,
3163 						 GFP_KERNEL);
3164 		if (!region) {
3165 			dev_err(dev, "Out of memory allocating dm-regions\n");
3166 			return;
3167 		}
3168 		list_add_tail(&region->list, head);
3169 	}
3170 
3171 	if (iommu_add_resv_x86_msi_region(head))
3172 		return;
3173 
3174 	if (amd_iommu_ht_range_ignore())
3175 		return;
3176 
3177 	region = iommu_alloc_resv_region(HT_RANGE_START,
3178 					 HT_RANGE_END - HT_RANGE_START + 1,
3179 					 0, IOMMU_RESV_RESERVED, GFP_KERNEL);
3180 	if (!region)
3181 		return;
3182 	list_add_tail(&region->list, head);
3183 }
3184 
3185 static bool amd_iommu_is_attach_deferred(struct device *dev)
3186 {
3187 	struct iommu_dev_data *dev_data = dev_iommu_priv_get(dev);
3188 
3189 	return dev_data->defer_attach;
3190 }
3191 
3192 static bool quirks_force_identity_mapping(struct pci_dev *pdev)
3193 {
3194 	struct pci_dev *bridge;
3195 	int class = pdev->class >> 8;
3196 
3197 	/* AMD GPU vendor ID */
3198 	if (pdev->vendor != PCI_VENDOR_ID_ATI)
3199 		return false;
3200 
3201 	/* GPU class */
3202 	if (class != PCI_CLASS_DISPLAY_VGA &&
3203 	    class != PCI_CLASS_DISPLAY_OTHER)
3204 		return false;
3205 
3206 	bridge = pci_upstream_bridge(pdev);
3207 	if (bridge && bridge->vendor == PCI_VENDOR_ID_ATI)
3208 		return false;
3209 
3210 	/* It is the GPU in an APU, force identity domain */
3211 	return true;
3212 }
3213 
3214 static int amd_iommu_def_domain_type(struct device *dev)
3215 {
3216 	struct iommu_dev_data *dev_data;
3217 
3218 	dev_data = dev_iommu_priv_get(dev);
3219 	if (!dev_data)
3220 		return 0;
3221 
3222 	if (!dev_is_pci(dev))
3223 		return 0;
3224 
3225 	/* Always use DMA domain for untrusted device */
3226 	if (to_pci_dev(dev)->untrusted)
3227 		return IOMMU_DOMAIN_DMA;
3228 
3229 	/* Apply device specific quirks */
3230 	if (quirks_force_identity_mapping(to_pci_dev(dev))) {
3231 		/*
3232 		 * When memory encryption is active, some of these devices
3233 		 * don't have the encryption bit in their DMA-mask and
3234 		 * require remapping.
3235 		 */
3236 		if (cc_platform_has(CC_ATTR_MEM_ENCRYPT))
3237 			return 0;
3238 
3239 		dev_data->perfopt = get_amd_iommu_from_dev_data(dev_data)->features &
3240 				    FEATURE_PERF_OPT;
3241 
3242 		return IOMMU_DOMAIN_IDENTITY;
3243 	}
3244 
3245 	return 0;
3246 }
3247 
3248 static bool amd_iommu_enforce_cache_coherency(struct iommu_domain *domain)
3249 {
3250 	/* IOMMU_PTE_FC is always set */
3251 	return true;
3252 }
3253 
3254 const struct iommu_ops amd_iommu_ops = {
3255 	.capable = amd_iommu_capable,
3256 	.hw_info = amd_iommufd_hw_info,
3257 	.blocked_domain = &blocked_domain,
3258 	.release_domain = &blocked_domain,
3259 	.identity_domain = &identity_domain.domain,
3260 	.domain_alloc_paging_flags = amd_iommu_domain_alloc_paging_flags,
3261 	.domain_alloc_sva = amd_iommu_domain_alloc_sva,
3262 	.probe_device = amd_iommu_probe_device,
3263 	.device_group = amd_iommu_device_group,
3264 	.get_resv_regions = amd_iommu_get_resv_regions,
3265 	.is_attach_deferred = amd_iommu_is_attach_deferred,
3266 	.def_domain_type = amd_iommu_def_domain_type,
3267 	.page_response = amd_iommu_page_response,
3268 	.get_viommu_size = amd_iommufd_get_viommu_size,
3269 	.viommu_init = amd_iommufd_viommu_init,
3270 };
3271 
3272 #ifdef CONFIG_IRQ_REMAP
3273 
3274 /*****************************************************************************
3275  *
3276  * Interrupt Remapping Implementation
3277  *
3278  *****************************************************************************/
3279 
3280 static struct irq_chip amd_ir_chip;
3281 static DEFINE_SPINLOCK(iommu_table_lock);
3282 
3283 static int iommu_flush_dev_irt(struct pci_dev *unused, u16 devid, void *data)
3284 {
3285 	int ret;
3286 	struct iommu_cmd cmd;
3287 	struct amd_iommu *iommu = data;
3288 
3289 	build_inv_irt(&cmd, devid);
3290 	ret = __iommu_queue_command_sync(iommu, &cmd, true);
3291 	return ret;
3292 }
3293 
3294 static void iommu_flush_irt_and_complete(struct amd_iommu *iommu, u16 devid)
3295 {
3296 	int ret;
3297 	u64 data;
3298 	unsigned long flags;
3299 	struct iommu_cmd cmd;
3300 	struct pci_dev *pdev = NULL;
3301 	struct iommu_dev_data *dev_data = search_dev_data(iommu, devid);
3302 
3303 	if (iommu->irtcachedis_enabled)
3304 		return;
3305 
3306 	if (dev_data && dev_data->dev && dev_is_pci(dev_data->dev))
3307 		pdev = to_pci_dev(dev_data->dev);
3308 
3309 	raw_spin_lock_irqsave(&iommu->lock, flags);
3310 	data = get_cmdsem_val(iommu);
3311 	build_completion_wait(&cmd, iommu, data);
3312 
3313 	if (pdev)
3314 		ret = pci_for_each_dma_alias(pdev, iommu_flush_dev_irt, iommu);
3315 	else
3316 		ret = iommu_flush_dev_irt(NULL, devid, iommu);
3317 	if (ret)
3318 		goto out_err;
3319 
3320 	ret = __iommu_queue_command_sync(iommu, &cmd, false);
3321 	if (ret)
3322 		goto out_err;
3323 	raw_spin_unlock_irqrestore(&iommu->lock, flags);
3324 
3325 	wait_on_sem(iommu, data);
3326 	return;
3327 
3328 out_err:
3329 	raw_spin_unlock_irqrestore(&iommu->lock, flags);
3330 }
3331 
3332 static inline u8 iommu_get_int_tablen(struct iommu_dev_data *dev_data)
3333 {
3334 	if (dev_data && dev_data->max_irqs == MAX_IRQS_PER_TABLE_2K)
3335 		return DTE_INTTABLEN_2K;
3336 	return DTE_INTTABLEN_512;
3337 }
3338 
3339 static void set_dte_irq_entry(struct amd_iommu *iommu, u16 devid,
3340 			      struct irq_remap_table *table)
3341 {
3342 	u64 new;
3343 	struct dev_table_entry *dte = &get_dev_table(iommu)[devid];
3344 	struct iommu_dev_data *dev_data = search_dev_data(iommu, devid);
3345 
3346 	if (dev_data)
3347 		spin_lock(&dev_data->dte_lock);
3348 
3349 	new = READ_ONCE(dte->data[2]);
3350 	new &= ~DTE_IRQ_PHYS_ADDR_MASK;
3351 	new |= iommu_virt_to_phys(table->table);
3352 	new |= DTE_IRQ_REMAP_INTCTL;
3353 	new |= iommu_get_int_tablen(dev_data);
3354 	new |= DTE_IRQ_REMAP_ENABLE;
3355 	WRITE_ONCE(dte->data[2], new);
3356 
3357 	if (dev_data)
3358 		spin_unlock(&dev_data->dte_lock);
3359 }
3360 
3361 static struct irq_remap_table *get_irq_table(struct amd_iommu *iommu, u16 devid)
3362 {
3363 	struct irq_remap_table *table;
3364 	struct amd_iommu_pci_seg *pci_seg = iommu->pci_seg;
3365 
3366 	if (WARN_ONCE(!pci_seg->rlookup_table[devid],
3367 		      "%s: no iommu for devid %x:%x\n",
3368 		      __func__, pci_seg->id, devid))
3369 		return NULL;
3370 
3371 	table = pci_seg->irq_lookup_table[devid];
3372 	if (WARN_ONCE(!table, "%s: no table for devid %x:%x\n",
3373 		      __func__, pci_seg->id, devid))
3374 		return NULL;
3375 
3376 	return table;
3377 }
3378 
3379 static struct irq_remap_table *__alloc_irq_table(int nid, size_t size)
3380 {
3381 	struct irq_remap_table *table;
3382 
3383 	table = kzalloc_obj(*table);
3384 	if (!table)
3385 		return NULL;
3386 
3387 	table->table = iommu_alloc_pages_node_sz(
3388 		nid, GFP_KERNEL, max(DTE_INTTAB_ALIGNMENT, size));
3389 	if (!table->table) {
3390 		kfree(table);
3391 		return NULL;
3392 	}
3393 	raw_spin_lock_init(&table->lock);
3394 
3395 	return table;
3396 }
3397 
3398 static void set_remap_table_entry(struct amd_iommu *iommu, u16 devid,
3399 				  struct irq_remap_table *table)
3400 {
3401 	struct amd_iommu_pci_seg *pci_seg = iommu->pci_seg;
3402 
3403 	pci_seg->irq_lookup_table[devid] = table;
3404 	set_dte_irq_entry(iommu, devid, table);
3405 	iommu_flush_dte(iommu, devid);
3406 }
3407 
3408 static int set_remap_table_entry_alias(struct pci_dev *pdev, u16 alias,
3409 				       void *data)
3410 {
3411 	struct irq_remap_table *table = data;
3412 	struct amd_iommu_pci_seg *pci_seg;
3413 	struct amd_iommu *iommu = rlookup_amd_iommu(&pdev->dev);
3414 
3415 	if (!iommu)
3416 		return -EINVAL;
3417 
3418 	pci_seg = iommu->pci_seg;
3419 	pci_seg->irq_lookup_table[alias] = table;
3420 	set_dte_irq_entry(iommu, alias, table);
3421 	iommu_flush_dte(pci_seg->rlookup_table[alias], alias);
3422 
3423 	return 0;
3424 }
3425 
3426 static inline size_t get_irq_table_size(unsigned int max_irqs)
3427 {
3428 	if (!AMD_IOMMU_GUEST_IR_GA(amd_iommu_guest_ir))
3429 		return max_irqs * sizeof(u32);
3430 
3431 	return max_irqs * (sizeof(u64) * 2);
3432 }
3433 
3434 static struct irq_remap_table *alloc_irq_table(struct amd_iommu *iommu,
3435 					       u16 devid, struct pci_dev *pdev,
3436 					       unsigned int max_irqs)
3437 {
3438 	struct irq_remap_table *table = NULL;
3439 	struct irq_remap_table *new_table = NULL;
3440 	struct amd_iommu_pci_seg *pci_seg;
3441 	unsigned long flags;
3442 	int nid = iommu->dev ? dev_to_node(&iommu->dev->dev) : NUMA_NO_NODE;
3443 	u16 alias;
3444 
3445 	spin_lock_irqsave(&iommu_table_lock, flags);
3446 
3447 	pci_seg = iommu->pci_seg;
3448 	table = pci_seg->irq_lookup_table[devid];
3449 	if (table)
3450 		goto out_unlock;
3451 
3452 	alias = pci_seg->alias_table[devid];
3453 	table = pci_seg->irq_lookup_table[alias];
3454 	if (table) {
3455 		set_remap_table_entry(iommu, devid, table);
3456 		goto out_wait;
3457 	}
3458 	spin_unlock_irqrestore(&iommu_table_lock, flags);
3459 
3460 	/* Nothing there yet, allocate new irq remapping table */
3461 	new_table = __alloc_irq_table(nid, get_irq_table_size(max_irqs));
3462 	if (!new_table)
3463 		return NULL;
3464 
3465 	spin_lock_irqsave(&iommu_table_lock, flags);
3466 
3467 	table = pci_seg->irq_lookup_table[devid];
3468 	if (table)
3469 		goto out_unlock;
3470 
3471 	table = pci_seg->irq_lookup_table[alias];
3472 	if (table) {
3473 		set_remap_table_entry(iommu, devid, table);
3474 		goto out_wait;
3475 	}
3476 
3477 	table = new_table;
3478 	new_table = NULL;
3479 
3480 	if (pdev)
3481 		pci_for_each_dma_alias(pdev, set_remap_table_entry_alias,
3482 				       table);
3483 	else
3484 		set_remap_table_entry(iommu, devid, table);
3485 
3486 	if (devid != alias)
3487 		set_remap_table_entry(iommu, alias, table);
3488 
3489 out_wait:
3490 	iommu_completion_wait(iommu);
3491 
3492 out_unlock:
3493 	spin_unlock_irqrestore(&iommu_table_lock, flags);
3494 
3495 	if (new_table) {
3496 		iommu_free_pages(new_table->table);
3497 		kfree(new_table);
3498 	}
3499 	return table;
3500 }
3501 
3502 static int alloc_irq_index(struct amd_iommu *iommu, u16 devid, int count,
3503 			   bool align, struct pci_dev *pdev,
3504 			   unsigned long max_irqs)
3505 {
3506 	struct irq_remap_table *table;
3507 	int index, c, alignment = 1;
3508 	unsigned long flags;
3509 
3510 	table = alloc_irq_table(iommu, devid, pdev, max_irqs);
3511 	if (!table)
3512 		return -ENODEV;
3513 
3514 	if (align)
3515 		alignment = roundup_pow_of_two(count);
3516 
3517 	raw_spin_lock_irqsave(&table->lock, flags);
3518 
3519 	/* Scan table for free entries */
3520 	for (index = ALIGN(table->min_index, alignment), c = 0;
3521 	     index < max_irqs;) {
3522 		if (!iommu->irte_ops->is_allocated(table, index)) {
3523 			c += 1;
3524 		} else {
3525 			c     = 0;
3526 			index = ALIGN(index + 1, alignment);
3527 			continue;
3528 		}
3529 
3530 		if (c == count)	{
3531 			for (; c != 0; --c)
3532 				iommu->irte_ops->set_allocated(table, index - c + 1);
3533 
3534 			index -= count - 1;
3535 			goto out;
3536 		}
3537 
3538 		index++;
3539 	}
3540 
3541 	index = -ENOSPC;
3542 
3543 out:
3544 	raw_spin_unlock_irqrestore(&table->lock, flags);
3545 
3546 	return index;
3547 }
3548 
3549 static int __modify_irte_ga(struct amd_iommu *iommu, u16 devid, int index,
3550 			    struct irte_ga *irte)
3551 {
3552 	struct irq_remap_table *table;
3553 	struct irte_ga *entry;
3554 	unsigned long flags;
3555 	u128 old;
3556 
3557 	table = get_irq_table(iommu, devid);
3558 	if (!table)
3559 		return -ENOMEM;
3560 
3561 	raw_spin_lock_irqsave(&table->lock, flags);
3562 
3563 	entry = (struct irte_ga *)table->table;
3564 	entry = &entry[index];
3565 
3566 	/*
3567 	 * We use cmpxchg16 to atomically update the 128-bit IRTE,
3568 	 * and it cannot be updated by the hardware or other processors
3569 	 * behind us, so the return value of cmpxchg16 should be the
3570 	 * same as the old value.
3571 	 */
3572 	old = entry->irte;
3573 	WARN_ON(!try_cmpxchg128(&entry->irte, &old, irte->irte));
3574 
3575 	raw_spin_unlock_irqrestore(&table->lock, flags);
3576 
3577 	return 0;
3578 }
3579 
3580 static int modify_irte_ga(struct amd_iommu *iommu, u16 devid, int index,
3581 			  struct irte_ga *irte)
3582 {
3583 	int ret;
3584 
3585 	ret = __modify_irte_ga(iommu, devid, index, irte);
3586 	if (ret)
3587 		return ret;
3588 
3589 	iommu_flush_irt_and_complete(iommu, devid);
3590 
3591 	return 0;
3592 }
3593 
3594 static int modify_irte(struct amd_iommu *iommu,
3595 		       u16 devid, int index, union irte *irte)
3596 {
3597 	struct irq_remap_table *table;
3598 	unsigned long flags;
3599 
3600 	table = get_irq_table(iommu, devid);
3601 	if (!table)
3602 		return -ENOMEM;
3603 
3604 	raw_spin_lock_irqsave(&table->lock, flags);
3605 	table->table[index] = irte->val;
3606 	raw_spin_unlock_irqrestore(&table->lock, flags);
3607 
3608 	iommu_flush_irt_and_complete(iommu, devid);
3609 
3610 	return 0;
3611 }
3612 
3613 static void free_irte(struct amd_iommu *iommu, u16 devid, int index)
3614 {
3615 	struct irq_remap_table *table;
3616 	unsigned long flags;
3617 
3618 	table = get_irq_table(iommu, devid);
3619 	if (!table)
3620 		return;
3621 
3622 	raw_spin_lock_irqsave(&table->lock, flags);
3623 	iommu->irte_ops->clear_allocated(table, index);
3624 	raw_spin_unlock_irqrestore(&table->lock, flags);
3625 
3626 	iommu_flush_irt_and_complete(iommu, devid);
3627 }
3628 
3629 static void irte_prepare(void *entry,
3630 			 u32 delivery_mode, bool dest_mode,
3631 			 u8 vector, u32 dest_apicid, int devid)
3632 {
3633 	union irte *irte = (union irte *) entry;
3634 
3635 	irte->val                = 0;
3636 	irte->fields.vector      = vector;
3637 	irte->fields.int_type    = delivery_mode;
3638 	irte->fields.destination = dest_apicid;
3639 	irte->fields.dm          = dest_mode;
3640 	irte->fields.valid       = 1;
3641 }
3642 
3643 static void irte_ga_prepare(void *entry,
3644 			    u32 delivery_mode, bool dest_mode,
3645 			    u8 vector, u32 dest_apicid, int devid)
3646 {
3647 	struct irte_ga *irte = (struct irte_ga *) entry;
3648 
3649 	irte->lo.val                      = 0;
3650 	irte->hi.val                      = 0;
3651 	irte->lo.fields_remap.int_type    = delivery_mode;
3652 	irte->lo.fields_remap.dm          = dest_mode;
3653 	irte->hi.fields.vector            = vector;
3654 	irte->lo.fields_remap.destination = APICID_TO_IRTE_DEST_LO(dest_apicid);
3655 	irte->hi.fields.destination       = APICID_TO_IRTE_DEST_HI(dest_apicid);
3656 	irte->lo.fields_remap.valid       = 1;
3657 }
3658 
3659 static void irte_activate(struct amd_iommu *iommu, void *entry, u16 devid, u16 index)
3660 {
3661 	union irte *irte = (union irte *) entry;
3662 
3663 	irte->fields.valid = 1;
3664 	modify_irte(iommu, devid, index, irte);
3665 }
3666 
3667 static void irte_ga_activate(struct amd_iommu *iommu, void *entry, u16 devid, u16 index)
3668 {
3669 	struct irte_ga *irte = (struct irte_ga *) entry;
3670 
3671 	irte->lo.fields_remap.valid = 1;
3672 	modify_irte_ga(iommu, devid, index, irte);
3673 }
3674 
3675 static void irte_deactivate(struct amd_iommu *iommu, void *entry, u16 devid, u16 index)
3676 {
3677 	union irte *irte = (union irte *) entry;
3678 
3679 	irte->fields.valid = 0;
3680 	modify_irte(iommu, devid, index, irte);
3681 }
3682 
3683 static void irte_ga_deactivate(struct amd_iommu *iommu, void *entry, u16 devid, u16 index)
3684 {
3685 	struct irte_ga *irte = (struct irte_ga *) entry;
3686 
3687 	irte->lo.fields_remap.valid = 0;
3688 	modify_irte_ga(iommu, devid, index, irte);
3689 }
3690 
3691 static void irte_set_affinity(struct amd_iommu *iommu, void *entry, u16 devid, u16 index,
3692 			      u8 vector, u32 dest_apicid)
3693 {
3694 	union irte *irte = (union irte *) entry;
3695 
3696 	irte->fields.vector = vector;
3697 	irte->fields.destination = dest_apicid;
3698 	modify_irte(iommu, devid, index, irte);
3699 }
3700 
3701 static void irte_ga_set_affinity(struct amd_iommu *iommu, void *entry, u16 devid, u16 index,
3702 				 u8 vector, u32 dest_apicid)
3703 {
3704 	struct irte_ga *irte = (struct irte_ga *) entry;
3705 
3706 	if (!irte->lo.fields_remap.guest_mode) {
3707 		irte->hi.fields.vector = vector;
3708 		irte->lo.fields_remap.destination =
3709 					APICID_TO_IRTE_DEST_LO(dest_apicid);
3710 		irte->hi.fields.destination =
3711 					APICID_TO_IRTE_DEST_HI(dest_apicid);
3712 		modify_irte_ga(iommu, devid, index, irte);
3713 	}
3714 }
3715 
3716 #define IRTE_ALLOCATED (~1U)
3717 static void irte_set_allocated(struct irq_remap_table *table, int index)
3718 {
3719 	table->table[index] = IRTE_ALLOCATED;
3720 }
3721 
3722 static void irte_ga_set_allocated(struct irq_remap_table *table, int index)
3723 {
3724 	struct irte_ga *ptr = (struct irte_ga *)table->table;
3725 	struct irte_ga *irte = &ptr[index];
3726 
3727 	memset(&irte->lo.val, 0, sizeof(u64));
3728 	memset(&irte->hi.val, 0, sizeof(u64));
3729 	irte->hi.fields.vector = 0xff;
3730 }
3731 
3732 static bool irte_is_allocated(struct irq_remap_table *table, int index)
3733 {
3734 	union irte *ptr = (union irte *)table->table;
3735 	union irte *irte = &ptr[index];
3736 
3737 	return irte->val != 0;
3738 }
3739 
3740 static bool irte_ga_is_allocated(struct irq_remap_table *table, int index)
3741 {
3742 	struct irte_ga *ptr = (struct irte_ga *)table->table;
3743 	struct irte_ga *irte = &ptr[index];
3744 
3745 	return irte->hi.fields.vector != 0;
3746 }
3747 
3748 static void irte_clear_allocated(struct irq_remap_table *table, int index)
3749 {
3750 	table->table[index] = 0;
3751 }
3752 
3753 static void irte_ga_clear_allocated(struct irq_remap_table *table, int index)
3754 {
3755 	struct irte_ga *ptr = (struct irte_ga *)table->table;
3756 	struct irte_ga *irte = &ptr[index];
3757 
3758 	memset(&irte->lo.val, 0, sizeof(u64));
3759 	memset(&irte->hi.val, 0, sizeof(u64));
3760 }
3761 
3762 static int get_devid(struct irq_alloc_info *info)
3763 {
3764 	switch (info->type) {
3765 	case X86_IRQ_ALLOC_TYPE_IOAPIC:
3766 		return get_ioapic_devid(info->devid);
3767 	case X86_IRQ_ALLOC_TYPE_HPET:
3768 		return get_hpet_devid(info->devid);
3769 	case X86_IRQ_ALLOC_TYPE_PCI_MSI:
3770 	case X86_IRQ_ALLOC_TYPE_PCI_MSIX:
3771 		return get_device_sbdf_id(msi_desc_to_dev(info->desc));
3772 	default:
3773 		WARN_ON_ONCE(1);
3774 		return -1;
3775 	}
3776 }
3777 
3778 struct irq_remap_ops amd_iommu_irq_ops = {
3779 	.prepare		= amd_iommu_prepare,
3780 	.enable			= amd_iommu_enable,
3781 	.disable		= amd_iommu_disable,
3782 	.reenable		= amd_iommu_reenable,
3783 	.enable_faulting	= amd_iommu_enable_faulting,
3784 };
3785 
3786 static void fill_msi_msg(struct msi_msg *msg, u32 index)
3787 {
3788 	msg->data = index;
3789 	msg->address_lo = 0;
3790 	msg->arch_addr_lo.base_address = X86_MSI_BASE_ADDRESS_LOW;
3791 	/*
3792 	 * The struct msi_msg.dest_mode_logical is used to set the DM bit
3793 	 * in MSI Message Address Register. For device w/ 2K int-remap support,
3794 	 * this bit must be set to 1 regardless of the actual destination
3795 	 * mode, which is signified by the IRTE[DM].
3796 	 */
3797 	if (FEATURE_NUM_INT_REMAP_SUP_2K(amd_iommu_efr2))
3798 		msg->arch_addr_lo.dest_mode_logical = true;
3799 	msg->address_hi = X86_MSI_BASE_ADDRESS_HIGH;
3800 }
3801 
3802 static void irq_remapping_prepare_irte(struct amd_ir_data *data,
3803 				       struct irq_cfg *irq_cfg,
3804 				       struct irq_alloc_info *info,
3805 				       int devid, int index, int sub_handle)
3806 {
3807 	struct irq_2_irte *irte_info = &data->irq_2_irte;
3808 	struct amd_iommu *iommu = data->iommu;
3809 
3810 	if (!iommu)
3811 		return;
3812 
3813 	data->irq_2_irte.devid = devid;
3814 	data->irq_2_irte.index = index + sub_handle;
3815 	iommu->irte_ops->prepare(data->entry, APIC_DELIVERY_MODE_FIXED,
3816 				 apic->dest_mode_logical, irq_cfg->vector,
3817 				 irq_cfg->dest_apicid, devid);
3818 
3819 	switch (info->type) {
3820 	case X86_IRQ_ALLOC_TYPE_IOAPIC:
3821 	case X86_IRQ_ALLOC_TYPE_HPET:
3822 	case X86_IRQ_ALLOC_TYPE_PCI_MSI:
3823 	case X86_IRQ_ALLOC_TYPE_PCI_MSIX:
3824 		fill_msi_msg(&data->msi_entry, irte_info->index);
3825 		break;
3826 
3827 	default:
3828 		BUG_ON(1);
3829 		break;
3830 	}
3831 }
3832 
3833 struct amd_irte_ops irte_32_ops = {
3834 	.prepare = irte_prepare,
3835 	.activate = irte_activate,
3836 	.deactivate = irte_deactivate,
3837 	.set_affinity = irte_set_affinity,
3838 	.set_allocated = irte_set_allocated,
3839 	.is_allocated = irte_is_allocated,
3840 	.clear_allocated = irte_clear_allocated,
3841 };
3842 
3843 struct amd_irte_ops irte_128_ops = {
3844 	.prepare = irte_ga_prepare,
3845 	.activate = irte_ga_activate,
3846 	.deactivate = irte_ga_deactivate,
3847 	.set_affinity = irte_ga_set_affinity,
3848 	.set_allocated = irte_ga_set_allocated,
3849 	.is_allocated = irte_ga_is_allocated,
3850 	.clear_allocated = irte_ga_clear_allocated,
3851 };
3852 
3853 static int irq_remapping_alloc(struct irq_domain *domain, unsigned int virq,
3854 			       unsigned int nr_irqs, void *arg)
3855 {
3856 	struct irq_alloc_info *info = arg;
3857 	struct irq_data *irq_data;
3858 	struct amd_ir_data *data = NULL;
3859 	struct amd_iommu *iommu;
3860 	struct irq_cfg *cfg;
3861 	struct iommu_dev_data *dev_data;
3862 	unsigned long max_irqs;
3863 	int i, ret, devid, seg, sbdf;
3864 	int index;
3865 
3866 	if (!info)
3867 		return -EINVAL;
3868 	if (nr_irqs > 1 && info->type != X86_IRQ_ALLOC_TYPE_PCI_MSI)
3869 		return -EINVAL;
3870 
3871 	sbdf = get_devid(info);
3872 	if (sbdf < 0)
3873 		return -EINVAL;
3874 
3875 	seg = PCI_SBDF_TO_SEGID(sbdf);
3876 	devid = PCI_SBDF_TO_DEVID(sbdf);
3877 	iommu = __rlookup_amd_iommu(seg, devid);
3878 	if (!iommu)
3879 		return -EINVAL;
3880 
3881 	dev_data = search_dev_data(iommu, devid);
3882 	max_irqs = dev_data ? dev_data->max_irqs : MAX_IRQS_PER_TABLE_512;
3883 
3884 	ret = irq_domain_alloc_irqs_parent(domain, virq, nr_irqs, arg);
3885 	if (ret < 0)
3886 		return ret;
3887 
3888 	if (info->type == X86_IRQ_ALLOC_TYPE_IOAPIC) {
3889 		struct irq_remap_table *table;
3890 
3891 		table = alloc_irq_table(iommu, devid, NULL, max_irqs);
3892 		if (table) {
3893 			if (!table->min_index) {
3894 				/*
3895 				 * Keep the first 32 indexes free for IOAPIC
3896 				 * interrupts.
3897 				 */
3898 				table->min_index = 32;
3899 				for (i = 0; i < 32; ++i)
3900 					iommu->irte_ops->set_allocated(table, i);
3901 			}
3902 			WARN_ON(table->min_index != 32);
3903 			index = info->ioapic.pin;
3904 		} else {
3905 			index = -ENOMEM;
3906 		}
3907 	} else if (info->type == X86_IRQ_ALLOC_TYPE_PCI_MSI ||
3908 		   info->type == X86_IRQ_ALLOC_TYPE_PCI_MSIX) {
3909 		bool align = (info->type == X86_IRQ_ALLOC_TYPE_PCI_MSI);
3910 
3911 		index = alloc_irq_index(iommu, devid, nr_irqs, align,
3912 					msi_desc_to_pci_dev(info->desc),
3913 					max_irqs);
3914 	} else {
3915 		index = alloc_irq_index(iommu, devid, nr_irqs, false, NULL,
3916 					max_irqs);
3917 	}
3918 
3919 	if (index < 0) {
3920 		pr_warn("Failed to allocate IRTE\n");
3921 		ret = index;
3922 		goto out_free_parent;
3923 	}
3924 
3925 	for (i = 0; i < nr_irqs; i++) {
3926 		irq_data = irq_domain_get_irq_data(domain, virq + i);
3927 		cfg = irq_data ? irqd_cfg(irq_data) : NULL;
3928 		if (!cfg) {
3929 			ret = -EINVAL;
3930 			goto out_free_data;
3931 		}
3932 
3933 		ret = -ENOMEM;
3934 		data = kzalloc_obj(*data);
3935 		if (!data)
3936 			goto out_free_data;
3937 
3938 		if (!AMD_IOMMU_GUEST_IR_GA(amd_iommu_guest_ir))
3939 			data->entry = kzalloc_obj(union irte);
3940 		else
3941 			data->entry = kzalloc_obj(struct irte_ga);
3942 		if (!data->entry) {
3943 			kfree(data);
3944 			goto out_free_data;
3945 		}
3946 
3947 		data->iommu = iommu;
3948 		irq_data->hwirq = (devid << 16) + i;
3949 		irq_data->chip_data = data;
3950 		irq_data->chip = &amd_ir_chip;
3951 		irq_remapping_prepare_irte(data, cfg, info, devid, index, i);
3952 	}
3953 
3954 	return 0;
3955 
3956 out_free_data:
3957 	for (i--; i >= 0; i--) {
3958 		irq_data = irq_domain_get_irq_data(domain, virq + i);
3959 		if (irq_data && irq_data->chip_data) {
3960 			data = irq_data->chip_data;
3961 			kfree(data->entry);
3962 			kfree(data);
3963 		}
3964 	}
3965 	for (i = 0; i < nr_irqs; i++)
3966 		free_irte(iommu, devid, index + i);
3967 out_free_parent:
3968 	irq_domain_free_irqs_common(domain, virq, nr_irqs);
3969 	return ret;
3970 }
3971 
3972 static void irq_remapping_free(struct irq_domain *domain, unsigned int virq,
3973 			       unsigned int nr_irqs)
3974 {
3975 	struct irq_2_irte *irte_info;
3976 	struct irq_data *irq_data;
3977 	struct amd_ir_data *data;
3978 	int i;
3979 
3980 	for (i = 0; i < nr_irqs; i++) {
3981 		irq_data = irq_domain_get_irq_data(domain, virq  + i);
3982 		if (irq_data && irq_data->chip_data) {
3983 			data = irq_data->chip_data;
3984 			irte_info = &data->irq_2_irte;
3985 			free_irte(data->iommu, irte_info->devid, irte_info->index);
3986 			kfree(data->entry);
3987 			kfree(data);
3988 		}
3989 	}
3990 	irq_domain_free_irqs_common(domain, virq, nr_irqs);
3991 }
3992 
3993 static void amd_ir_update_irte(struct irq_data *irqd, struct amd_iommu *iommu,
3994 			       struct amd_ir_data *ir_data,
3995 			       struct irq_2_irte *irte_info,
3996 			       struct irq_cfg *cfg);
3997 
3998 static int irq_remapping_activate(struct irq_domain *domain,
3999 				  struct irq_data *irq_data, bool reserve)
4000 {
4001 	struct amd_ir_data *data = irq_data->chip_data;
4002 	struct irq_2_irte *irte_info = &data->irq_2_irte;
4003 	struct amd_iommu *iommu = data->iommu;
4004 	struct irq_cfg *cfg = irqd_cfg(irq_data);
4005 
4006 	if (!iommu)
4007 		return 0;
4008 
4009 	iommu->irte_ops->activate(iommu, data->entry, irte_info->devid,
4010 				  irte_info->index);
4011 	amd_ir_update_irte(irq_data, iommu, data, irte_info, cfg);
4012 	return 0;
4013 }
4014 
4015 static void irq_remapping_deactivate(struct irq_domain *domain,
4016 				     struct irq_data *irq_data)
4017 {
4018 	struct amd_ir_data *data = irq_data->chip_data;
4019 	struct irq_2_irte *irte_info = &data->irq_2_irte;
4020 	struct amd_iommu *iommu = data->iommu;
4021 
4022 	if (iommu)
4023 		iommu->irte_ops->deactivate(iommu, data->entry, irte_info->devid,
4024 					    irte_info->index);
4025 }
4026 
4027 static int irq_remapping_select(struct irq_domain *d, struct irq_fwspec *fwspec,
4028 				enum irq_domain_bus_token bus_token)
4029 {
4030 	struct amd_iommu *iommu;
4031 	int devid = -1;
4032 
4033 	if (!amd_iommu_irq_remap)
4034 		return 0;
4035 
4036 	if (x86_fwspec_is_ioapic(fwspec))
4037 		devid = get_ioapic_devid(fwspec->param[0]);
4038 	else if (x86_fwspec_is_hpet(fwspec))
4039 		devid = get_hpet_devid(fwspec->param[0]);
4040 
4041 	if (devid < 0)
4042 		return 0;
4043 	iommu = __rlookup_amd_iommu((devid >> 16), (devid & 0xffff));
4044 
4045 	return iommu && iommu->ir_domain == d;
4046 }
4047 
4048 static const struct irq_domain_ops amd_ir_domain_ops = {
4049 	.select = irq_remapping_select,
4050 	.alloc = irq_remapping_alloc,
4051 	.free = irq_remapping_free,
4052 	.activate = irq_remapping_activate,
4053 	.deactivate = irq_remapping_deactivate,
4054 };
4055 
4056 static void __amd_iommu_update_ga(struct irte_ga *entry, int cpu,
4057 				  bool ga_log_intr)
4058 {
4059 	if (cpu >= 0) {
4060 		entry->lo.fields_vapic.destination =
4061 					APICID_TO_IRTE_DEST_LO(cpu);
4062 		entry->hi.fields.destination =
4063 					APICID_TO_IRTE_DEST_HI(cpu);
4064 		entry->lo.fields_vapic.is_run = true;
4065 		entry->lo.fields_vapic.ga_log_intr = false;
4066 	} else {
4067 		entry->lo.fields_vapic.is_run = false;
4068 		entry->lo.fields_vapic.ga_log_intr = ga_log_intr;
4069 	}
4070 }
4071 
4072 /*
4073  * Update the pCPU information for an IRTE that is configured to post IRQs to
4074  * a vCPU, without issuing an IOMMU invalidation for the IRTE.
4075  *
4076  * If the vCPU is associated with a pCPU (@cpu >= 0), configure the Destination
4077  * with the pCPU's APIC ID, set IsRun, and clear GALogIntr.  If the vCPU isn't
4078  * associated with a pCPU (@cpu < 0), clear IsRun and set/clear GALogIntr based
4079  * on input from the caller (e.g. KVM only requests GALogIntr when the vCPU is
4080  * blocking and requires a notification wake event).  I.e. treat vCPUs that are
4081  * associated with a pCPU as running.  This API is intended to be used when a
4082  * vCPU is scheduled in/out (or stops running for any reason), to do a fast
4083  * update of IsRun, GALogIntr, and (conditionally) Destination.
4084  *
4085  * Per the IOMMU spec, the Destination, IsRun, and GATag fields are not cached
4086  * and thus don't require an invalidation to ensure the IOMMU consumes fresh
4087  * information.
4088  */
4089 int amd_iommu_update_ga(void *data, int cpu, bool ga_log_intr)
4090 {
4091 	struct amd_ir_data *ir_data = (struct amd_ir_data *)data;
4092 	struct irte_ga *entry = (struct irte_ga *) ir_data->entry;
4093 
4094 	if (WARN_ON_ONCE(!AMD_IOMMU_GUEST_IR_VAPIC(amd_iommu_guest_ir)))
4095 		return -EINVAL;
4096 
4097 	if (!entry || !entry->lo.fields_vapic.guest_mode)
4098 		return 0;
4099 
4100 	if (!ir_data->iommu)
4101 		return -ENODEV;
4102 
4103 	__amd_iommu_update_ga(entry, cpu, ga_log_intr);
4104 
4105 	return __modify_irte_ga(ir_data->iommu, ir_data->irq_2_irte.devid,
4106 				ir_data->irq_2_irte.index, entry);
4107 }
4108 EXPORT_SYMBOL(amd_iommu_update_ga);
4109 
4110 int amd_iommu_activate_guest_mode(void *data, int cpu, bool ga_log_intr)
4111 {
4112 	struct amd_ir_data *ir_data = (struct amd_ir_data *)data;
4113 	struct irte_ga *entry = (struct irte_ga *) ir_data->entry;
4114 	u64 valid;
4115 
4116 	if (WARN_ON_ONCE(!AMD_IOMMU_GUEST_IR_VAPIC(amd_iommu_guest_ir)))
4117 		return -EINVAL;
4118 
4119 	if (!entry)
4120 		return 0;
4121 
4122 	valid = entry->lo.fields_vapic.valid;
4123 
4124 	entry->lo.val = 0;
4125 	entry->hi.val = 0;
4126 
4127 	entry->lo.fields_vapic.valid       = valid;
4128 	entry->lo.fields_vapic.guest_mode  = 1;
4129 	entry->hi.fields.ga_root_ptr       = ir_data->ga_root_ptr;
4130 	entry->hi.fields.vector            = ir_data->ga_vector;
4131 	entry->lo.fields_vapic.ga_tag      = ir_data->ga_tag;
4132 
4133 	__amd_iommu_update_ga(entry, cpu, ga_log_intr);
4134 
4135 	return modify_irte_ga(ir_data->iommu, ir_data->irq_2_irte.devid,
4136 			      ir_data->irq_2_irte.index, entry);
4137 }
4138 EXPORT_SYMBOL(amd_iommu_activate_guest_mode);
4139 
4140 int amd_iommu_deactivate_guest_mode(void *data)
4141 {
4142 	struct amd_ir_data *ir_data = (struct amd_ir_data *)data;
4143 	struct irte_ga *entry = (struct irte_ga *) ir_data->entry;
4144 	struct irq_cfg *cfg = ir_data->cfg;
4145 	u64 valid;
4146 
4147 	if (WARN_ON_ONCE(!AMD_IOMMU_GUEST_IR_VAPIC(amd_iommu_guest_ir)))
4148 		return -EINVAL;
4149 
4150 	if (!entry || !entry->lo.fields_vapic.guest_mode)
4151 		return 0;
4152 
4153 	valid = entry->lo.fields_remap.valid;
4154 
4155 	entry->lo.val = 0;
4156 	entry->hi.val = 0;
4157 
4158 	entry->lo.fields_remap.valid       = valid;
4159 	entry->lo.fields_remap.dm          = apic->dest_mode_logical;
4160 	entry->lo.fields_remap.int_type    = APIC_DELIVERY_MODE_FIXED;
4161 	entry->hi.fields.vector            = cfg->vector;
4162 	entry->lo.fields_remap.destination =
4163 				APICID_TO_IRTE_DEST_LO(cfg->dest_apicid);
4164 	entry->hi.fields.destination =
4165 				APICID_TO_IRTE_DEST_HI(cfg->dest_apicid);
4166 
4167 	return modify_irte_ga(ir_data->iommu, ir_data->irq_2_irte.devid,
4168 			      ir_data->irq_2_irte.index, entry);
4169 }
4170 EXPORT_SYMBOL(amd_iommu_deactivate_guest_mode);
4171 
4172 static int amd_ir_set_vcpu_affinity(struct irq_data *data, void *info)
4173 {
4174 	int ret;
4175 	struct amd_iommu_pi_data *pi_data = info;
4176 	struct amd_ir_data *ir_data = data->chip_data;
4177 	struct irq_2_irte *irte_info = &ir_data->irq_2_irte;
4178 	struct iommu_dev_data *dev_data;
4179 
4180 	if (WARN_ON_ONCE(!AMD_IOMMU_GUEST_IR_VAPIC(amd_iommu_guest_ir)))
4181 		return -EINVAL;
4182 
4183 	if (ir_data->iommu == NULL)
4184 		return -EINVAL;
4185 
4186 	dev_data = search_dev_data(ir_data->iommu, irte_info->devid);
4187 
4188 	/* Note:
4189 	 * This device has never been set up for guest mode.
4190 	 * we should not modify the IRTE
4191 	 */
4192 	if (!dev_data || !dev_data->use_vapic)
4193 		return -EINVAL;
4194 
4195 	ir_data->cfg = irqd_cfg(data);
4196 
4197 	if (pi_data) {
4198 		pi_data->ir_data = ir_data;
4199 
4200 		ir_data->ga_root_ptr = (pi_data->vapic_addr >> 12);
4201 		ir_data->ga_vector = pi_data->vector;
4202 		ir_data->ga_tag = pi_data->ga_tag;
4203 		if (pi_data->is_guest_mode)
4204 			ret = amd_iommu_activate_guest_mode(ir_data, pi_data->cpu,
4205 							    pi_data->ga_log_intr);
4206 		else
4207 			ret = amd_iommu_deactivate_guest_mode(ir_data);
4208 	} else {
4209 		ret = amd_iommu_deactivate_guest_mode(ir_data);
4210 	}
4211 
4212 	return ret;
4213 }
4214 
4215 
4216 static void amd_ir_update_irte(struct irq_data *irqd, struct amd_iommu *iommu,
4217 			       struct amd_ir_data *ir_data,
4218 			       struct irq_2_irte *irte_info,
4219 			       struct irq_cfg *cfg)
4220 {
4221 
4222 	/*
4223 	 * Atomically updates the IRTE with the new destination, vector
4224 	 * and flushes the interrupt entry cache.
4225 	 */
4226 	iommu->irte_ops->set_affinity(iommu, ir_data->entry, irte_info->devid,
4227 				      irte_info->index, cfg->vector,
4228 				      cfg->dest_apicid);
4229 }
4230 
4231 static int amd_ir_set_affinity(struct irq_data *data,
4232 			       const struct cpumask *mask, bool force)
4233 {
4234 	struct amd_ir_data *ir_data = data->chip_data;
4235 	struct irq_2_irte *irte_info = &ir_data->irq_2_irte;
4236 	struct irq_cfg *cfg = irqd_cfg(data);
4237 	struct irq_data *parent = data->parent_data;
4238 	struct amd_iommu *iommu = ir_data->iommu;
4239 	int ret;
4240 
4241 	if (!iommu)
4242 		return -ENODEV;
4243 
4244 	ret = parent->chip->irq_set_affinity(parent, mask, force);
4245 	if (ret < 0 || ret == IRQ_SET_MASK_OK_DONE)
4246 		return ret;
4247 
4248 	amd_ir_update_irte(data, iommu, ir_data, irte_info, cfg);
4249 	/*
4250 	 * After this point, all the interrupts will start arriving
4251 	 * at the new destination. So, time to cleanup the previous
4252 	 * vector allocation.
4253 	 */
4254 	vector_schedule_cleanup(cfg);
4255 
4256 	return IRQ_SET_MASK_OK_DONE;
4257 }
4258 
4259 static void ir_compose_msi_msg(struct irq_data *irq_data, struct msi_msg *msg)
4260 {
4261 	struct amd_ir_data *ir_data = irq_data->chip_data;
4262 
4263 	*msg = ir_data->msi_entry;
4264 }
4265 
4266 static struct irq_chip amd_ir_chip = {
4267 	.name			= "AMD-IR",
4268 	.irq_ack		= apic_ack_irq,
4269 	.irq_set_affinity	= amd_ir_set_affinity,
4270 	.irq_set_vcpu_affinity	= amd_ir_set_vcpu_affinity,
4271 	.irq_compose_msi_msg	= ir_compose_msi_msg,
4272 };
4273 
4274 static const struct msi_parent_ops amdvi_msi_parent_ops = {
4275 	.supported_flags	= X86_VECTOR_MSI_FLAGS_SUPPORTED | MSI_FLAG_MULTI_PCI_MSI,
4276 	.bus_select_token	= DOMAIN_BUS_AMDVI,
4277 	.bus_select_mask	= MATCH_PCI_MSI,
4278 	.prefix			= "IR-",
4279 	.init_dev_msi_info	= msi_parent_init_dev_msi_info,
4280 };
4281 
4282 int amd_iommu_create_irq_domain(struct amd_iommu *iommu)
4283 {
4284 	struct irq_domain_info info = {
4285 		.fwnode		= irq_domain_alloc_named_id_fwnode("AMD-IR", iommu->index),
4286 		.ops		= &amd_ir_domain_ops,
4287 		.domain_flags	= IRQ_DOMAIN_FLAG_ISOLATED_MSI,
4288 		.host_data	= iommu,
4289 		.parent		= arch_get_ir_parent_domain(),
4290 	};
4291 
4292 	if (!info.fwnode)
4293 		return -ENOMEM;
4294 
4295 	iommu->ir_domain = msi_create_parent_irq_domain(&info, &amdvi_msi_parent_ops);
4296 	if (!iommu->ir_domain) {
4297 		irq_domain_free_fwnode(info.fwnode);
4298 		return -ENOMEM;
4299 	}
4300 	return 0;
4301 }
4302 #endif
4303 
4304 MODULE_IMPORT_NS("GENERIC_PT_IOMMU");
4305