xref: /linux/drivers/iommu/amd/iommu.c (revision 10bcc637f7a657725dd8bbcc2b30d027acee6f2d)
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 /*
2796  * Force a clflush on Cezanne (family 19h, model 50h) when the v2
2797  * page-table is enabled.
2798  */
2799 static bool amd_iommu_force_incoherent(void)
2800 {
2801 	return boot_cpu_data.x86 == 0x19 && boot_cpu_data.x86_model == 0x50;
2802 }
2803 
2804 static struct iommu_domain *amd_iommu_domain_alloc_paging_v2(struct device *dev,
2805 							     u32 flags)
2806 {
2807 	struct pt_iommu_x86_64_cfg cfg = {};
2808 	struct protection_domain *domain;
2809 	int ret;
2810 
2811 	if (!amd_iommu_v2_pgtbl_supported())
2812 		return ERR_PTR(-EOPNOTSUPP);
2813 
2814 	domain = protection_domain_alloc();
2815 	if (!domain)
2816 		return ERR_PTR(-ENOMEM);
2817 
2818 	domain->pd_mode = PD_MODE_V2;
2819 	domain->iommu.nid = dev_to_node(dev);
2820 
2821 	cfg.common.features = BIT(PT_FEAT_X86_64_AMD_ENCRYPT_TABLES);
2822 
2823 	if (amd_iommu_force_incoherent()) {
2824 		cfg.common.features |= BIT(PT_FEAT_DMA_INCOHERENT);
2825 		/* pt_iommu_init() rejects DMA_INCOHERENT without a device */
2826 		domain->iommu.iommu_device = dev;
2827 	}
2828 
2829 	if (amd_iommu_np_cache)
2830 		cfg.common.features |= BIT(PT_FEAT_FLUSH_RANGE_NO_GAPS);
2831 	else
2832 		cfg.common.features |= BIT(PT_FEAT_FLUSH_RANGE);
2833 
2834 	/*
2835 	 * The v2 table behaves differently if it is attached to PASID 0 vs a
2836 	 * non-zero PASID. On PASID 0 it has no sign extension and the full
2837 	 * 57/48 bits decode the lower addresses. Otherwise it behaves like a
2838 	 * normal sign extended x86 page table. Since we want the domain to work
2839 	 * in both modes the top bit is removed and PT_FEAT_SIGN_EXTEND is not
2840 	 * set which creates a table that is compatible in both modes.
2841 	 */
2842 	if (amd_iommu_gpt_level == PAGE_MODE_5_LEVEL) {
2843 		cfg.common.hw_max_vasz_lg2 = 56;
2844 		cfg.top_level = 4;
2845 	} else {
2846 		cfg.common.hw_max_vasz_lg2 = 47;
2847 		cfg.top_level = 3;
2848 	}
2849 	cfg.common.hw_max_oasz_lg2 = 52;
2850 	domain->domain.ops = &amdv2_ops;
2851 
2852 	ret = pt_iommu_x86_64_init(&domain->amdv2, &cfg, GFP_KERNEL);
2853 	if (ret) {
2854 		amd_iommu_domain_free(&domain->domain);
2855 		return ERR_PTR(ret);
2856 	}
2857 	return &domain->domain;
2858 }
2859 
2860 static inline bool is_nest_parent_supported(u32 flags)
2861 {
2862 	/* Only allow nest parent when these features are supported */
2863 	return check_feature(FEATURE_GT) &&
2864 	       check_feature(FEATURE_GIOSUP) &&
2865 	       check_feature2(FEATURE_GCR3TRPMODE);
2866 }
2867 
2868 static struct iommu_domain *
2869 amd_iommu_domain_alloc_paging_flags(struct device *dev, u32 flags,
2870 				    const struct iommu_user_data *user_data)
2871 
2872 {
2873 	struct amd_iommu *iommu = get_amd_iommu_from_dev(dev);
2874 	const u32 supported_flags = IOMMU_HWPT_ALLOC_DIRTY_TRACKING |
2875 						IOMMU_HWPT_ALLOC_PASID |
2876 						IOMMU_HWPT_ALLOC_NEST_PARENT;
2877 
2878 	if ((flags & ~supported_flags) || user_data)
2879 		return ERR_PTR(-EOPNOTSUPP);
2880 
2881 	switch (flags & supported_flags) {
2882 	case IOMMU_HWPT_ALLOC_DIRTY_TRACKING:
2883 	case IOMMU_HWPT_ALLOC_NEST_PARENT:
2884 	case IOMMU_HWPT_ALLOC_DIRTY_TRACKING | IOMMU_HWPT_ALLOC_NEST_PARENT:
2885 		/*
2886 		 * Allocate domain with v1 page table for dirty tracking
2887 		 * and/or Nest parent.
2888 		 */
2889 		if ((flags & IOMMU_HWPT_ALLOC_DIRTY_TRACKING) &&
2890 		    !amd_iommu_hd_support(iommu))
2891 			break;
2892 
2893 		if ((flags & IOMMU_HWPT_ALLOC_NEST_PARENT) &&
2894 		    !is_nest_parent_supported(flags))
2895 			break;
2896 
2897 		return amd_iommu_domain_alloc_paging_v1(dev, flags);
2898 	case IOMMU_HWPT_ALLOC_PASID:
2899 		/* Allocate domain with v2 page table if IOMMU supports PASID. */
2900 		if (!amd_iommu_pasid_supported())
2901 			break;
2902 		return amd_iommu_domain_alloc_paging_v2(dev, flags);
2903 	case 0: {
2904 		struct iommu_domain *ret;
2905 
2906 		/* If nothing specific is required use the kernel commandline default */
2907 		if (amd_iommu_pgtable == PD_MODE_V1) {
2908 			ret = amd_iommu_domain_alloc_paging_v1(dev, flags);
2909 			if (ret != ERR_PTR(-EOPNOTSUPP))
2910 				return ret;
2911 			return amd_iommu_domain_alloc_paging_v2(dev, flags);
2912 		}
2913 		ret = amd_iommu_domain_alloc_paging_v2(dev, flags);
2914 		if (ret != ERR_PTR(-EOPNOTSUPP))
2915 			return ret;
2916 		return amd_iommu_domain_alloc_paging_v1(dev, flags);
2917 	}
2918 	default:
2919 		break;
2920 	}
2921 	return ERR_PTR(-EOPNOTSUPP);
2922 }
2923 
2924 void amd_iommu_domain_free(struct iommu_domain *dom)
2925 {
2926 	struct protection_domain *domain = to_pdomain(dom);
2927 
2928 	WARN_ON(!list_empty(&domain->dev_list));
2929 	pt_iommu_deinit(&domain->iommu);
2930 	amd_iommu_pdom_id_free(domain->id);
2931 	kfree(domain);
2932 }
2933 
2934 /* Each IOMMU has at most one PerfOpt-eligible GPU. */
2935 static int set_device_perfopt(struct iommu_dev_data *dev_data, bool enable)
2936 {
2937 	struct amd_iommu *iommu = get_amd_iommu_from_dev_data(dev_data);
2938 
2939 	if (!dev_data->perfopt)
2940 		return 0;
2941 
2942 	guard(raw_spinlock_irqsave)(&iommu->lock);
2943 	if (iommu->perfopt_enabled == enable)
2944 		return 0;
2945 
2946 	return amd_iommu_perfopt_set(iommu, enable);
2947 }
2948 
2949 static int blocked_domain_attach_device(struct iommu_domain *domain,
2950 					struct device *dev,
2951 					struct iommu_domain *old)
2952 {
2953 	struct iommu_dev_data *dev_data = dev_iommu_priv_get(dev);
2954 	int ret;
2955 
2956 	/* Clearing the DTE cannot block DMA while PerfOpt bypasses it. */
2957 	ret = set_device_perfopt(dev_data, false);
2958 	if (ret)
2959 		return ret;
2960 
2961 	if (dev_data->domain)
2962 		detach_device(dev);
2963 
2964 	/* Clear DTE and flush the entry */
2965 	mutex_lock(&dev_data->mutex);
2966 	dev_update_dte(dev_data, false);
2967 	mutex_unlock(&dev_data->mutex);
2968 
2969 	return 0;
2970 }
2971 
2972 static int blocked_domain_set_dev_pasid(struct iommu_domain *domain,
2973 					struct device *dev, ioasid_t pasid,
2974 					struct iommu_domain *old)
2975 {
2976 	amd_iommu_remove_dev_pasid(dev, pasid, old);
2977 	return 0;
2978 }
2979 
2980 static struct iommu_domain blocked_domain = {
2981 	.type = IOMMU_DOMAIN_BLOCKED,
2982 	.ops = &(const struct iommu_domain_ops) {
2983 		.attach_dev     = blocked_domain_attach_device,
2984 		.set_dev_pasid  = blocked_domain_set_dev_pasid,
2985 	}
2986 };
2987 
2988 static struct protection_domain identity_domain;
2989 
2990 static int amd_iommu_identity_attach(struct iommu_domain *dom, struct device *dev,
2991 				     struct iommu_domain *old)
2992 {
2993 	struct iommu_dev_data *dev_data = dev_iommu_priv_get(dev);
2994 	int ret;
2995 
2996 	/*
2997 	 * Don't allow attaching a device to the identity domain if SNP is
2998 	 * enabled and SNP Mode0 support is not present.
2999 	 */
3000 	if (amd_iommu_snp_en && !amd_iommu_snp_mode0_sup)
3001 		return -EINVAL;
3002 
3003 	ret = amd_iommu_attach_device(dom, dev, old);
3004 	if (ret)
3005 		return ret;
3006 
3007 	/* PerfOpt is optional; the identity attachment is already complete. */
3008 	set_device_perfopt(dev_data, true);
3009 	return 0;
3010 }
3011 
3012 static const struct iommu_domain_ops identity_domain_ops = {
3013 	.attach_dev = amd_iommu_identity_attach,
3014 };
3015 
3016 void amd_iommu_init_identity_domain(void)
3017 {
3018 	struct iommu_domain *domain = &identity_domain.domain;
3019 
3020 	domain->type = IOMMU_DOMAIN_IDENTITY;
3021 	domain->ops = &identity_domain_ops;
3022 	domain->owner = &amd_iommu_ops;
3023 
3024 	identity_domain.id = amd_iommu_pdom_id_alloc();
3025 
3026 	protection_domain_init(&identity_domain);
3027 }
3028 
3029 static int amd_iommu_attach_device(struct iommu_domain *dom, struct device *dev,
3030 				   struct iommu_domain *old)
3031 {
3032 	struct iommu_dev_data *dev_data = dev_iommu_priv_get(dev);
3033 	struct protection_domain *domain = to_pdomain(dom);
3034 	struct amd_iommu *iommu = get_amd_iommu_from_dev(dev);
3035 	int ret;
3036 
3037 	/*
3038 	 * Skip attach device to domain if new domain is same as
3039 	 * devices current domain
3040 	 */
3041 	if (dev_data->domain == domain)
3042 		return 0;
3043 
3044 	dev_data->defer_attach = false;
3045 
3046 	/*
3047 	 * Restrict to devices with compatible IOMMU hardware support
3048 	 * when enforcement of dirty tracking is enabled.
3049 	 */
3050 	if (dom->dirty_ops && !amd_iommu_hd_support(iommu))
3051 		return -EINVAL;
3052 
3053 	if (!pdom_is_in_pt_mode(domain)) {
3054 		ret = set_device_perfopt(dev_data, false);
3055 		if (ret)
3056 			return ret;
3057 	}
3058 
3059 	if (dev_data->domain)
3060 		detach_device(dev);
3061 
3062 	ret = attach_device(dev, domain);
3063 
3064 #ifdef CONFIG_IRQ_REMAP
3065 	if (AMD_IOMMU_GUEST_IR_VAPIC(amd_iommu_guest_ir)) {
3066 		if (dom->type == IOMMU_DOMAIN_UNMANAGED)
3067 			dev_data->use_vapic = 1;
3068 		else
3069 			dev_data->use_vapic = 0;
3070 	}
3071 #endif
3072 
3073 	return ret;
3074 }
3075 
3076 static bool amd_iommu_capable(struct device *dev, enum iommu_cap cap)
3077 {
3078 	switch (cap) {
3079 	case IOMMU_CAP_CACHE_COHERENCY:
3080 		return true;
3081 	case IOMMU_CAP_NOEXEC:
3082 		return false;
3083 	case IOMMU_CAP_PRE_BOOT_PROTECTION:
3084 		return amdr_ivrs_remap_support;
3085 	case IOMMU_CAP_ENFORCE_CACHE_COHERENCY:
3086 		return true;
3087 	case IOMMU_CAP_DIRTY_TRACKING: {
3088 		struct amd_iommu *iommu = get_amd_iommu_from_dev(dev);
3089 
3090 		return amd_iommu_hd_support(iommu);
3091 	}
3092 	case IOMMU_CAP_PCI_ATS_SUPPORTED: {
3093 		struct iommu_dev_data *dev_data = dev_iommu_priv_get(dev);
3094 
3095 		return amd_iommu_iotlb_sup &&
3096 			 (dev_data->flags & AMD_IOMMU_DEVICE_FLAG_ATS_SUP);
3097 	}
3098 	default:
3099 		break;
3100 	}
3101 
3102 	return false;
3103 }
3104 
3105 static int amd_iommu_set_dirty_tracking(struct iommu_domain *domain,
3106 					bool enable)
3107 {
3108 	struct protection_domain *pdomain = to_pdomain(domain);
3109 	struct dev_table_entry *dte;
3110 	struct iommu_dev_data *dev_data;
3111 	bool domain_flush = false;
3112 	struct amd_iommu *iommu;
3113 	unsigned long flags;
3114 	u64 new;
3115 
3116 	spin_lock_irqsave(&pdomain->lock, flags);
3117 	if (!(pdomain->dirty_tracking ^ enable)) {
3118 		spin_unlock_irqrestore(&pdomain->lock, flags);
3119 		return 0;
3120 	}
3121 
3122 	list_for_each_entry(dev_data, &pdomain->dev_list, list) {
3123 		spin_lock(&dev_data->dte_lock);
3124 		iommu = get_amd_iommu_from_dev_data(dev_data);
3125 		dte = &get_dev_table(iommu)[dev_data->devid];
3126 		new = dte->data[0];
3127 		new = (enable ? new | DTE_FLAG_HAD : new & ~DTE_FLAG_HAD);
3128 		dte->data[0] = new;
3129 		spin_unlock(&dev_data->dte_lock);
3130 
3131 		/* Flush device DTE */
3132 		device_flush_dte(dev_data);
3133 		domain_flush = true;
3134 	}
3135 
3136 	/* Flush IOTLB to mark IOPTE dirty on the next translation(s) */
3137 	if (domain_flush)
3138 		amd_iommu_domain_flush_all(pdomain);
3139 
3140 	pdomain->dirty_tracking = enable;
3141 	spin_unlock_irqrestore(&pdomain->lock, flags);
3142 
3143 	return 0;
3144 }
3145 
3146 static void amd_iommu_get_resv_regions(struct device *dev,
3147 				       struct list_head *head)
3148 {
3149 	struct iommu_resv_region *region;
3150 	struct unity_map_entry *entry;
3151 	struct amd_iommu *iommu;
3152 	struct amd_iommu_pci_seg *pci_seg;
3153 	int devid, sbdf;
3154 
3155 	sbdf = get_device_sbdf_id(dev);
3156 	if (sbdf < 0)
3157 		return;
3158 
3159 	devid = PCI_SBDF_TO_DEVID(sbdf);
3160 	iommu = get_amd_iommu_from_dev(dev);
3161 	pci_seg = iommu->pci_seg;
3162 
3163 	list_for_each_entry(entry, &pci_seg->unity_map, list) {
3164 		int type, prot = 0;
3165 		size_t length;
3166 
3167 		if (devid < entry->devid_start || devid > entry->devid_end)
3168 			continue;
3169 
3170 		type   = IOMMU_RESV_DIRECT;
3171 		length = entry->address_end - entry->address_start;
3172 		if (entry->prot & IOMMU_PROT_IR)
3173 			prot |= IOMMU_READ;
3174 		if (entry->prot & IOMMU_PROT_IW)
3175 			prot |= IOMMU_WRITE;
3176 
3177 		region = iommu_alloc_resv_region(entry->address_start,
3178 						 length, prot, type,
3179 						 GFP_KERNEL);
3180 		if (!region) {
3181 			dev_err(dev, "Out of memory allocating dm-regions\n");
3182 			return;
3183 		}
3184 		list_add_tail(&region->list, head);
3185 	}
3186 
3187 	if (iommu_add_resv_x86_msi_region(head))
3188 		return;
3189 
3190 	if (amd_iommu_ht_range_ignore())
3191 		return;
3192 
3193 	region = iommu_alloc_resv_region(HT_RANGE_START,
3194 					 HT_RANGE_END - HT_RANGE_START + 1,
3195 					 0, IOMMU_RESV_RESERVED, GFP_KERNEL);
3196 	if (!region)
3197 		return;
3198 	list_add_tail(&region->list, head);
3199 }
3200 
3201 static bool amd_iommu_is_attach_deferred(struct device *dev)
3202 {
3203 	struct iommu_dev_data *dev_data = dev_iommu_priv_get(dev);
3204 
3205 	return dev_data->defer_attach;
3206 }
3207 
3208 static bool quirks_force_identity_mapping(struct pci_dev *pdev)
3209 {
3210 	struct pci_dev *bridge;
3211 	int class = pdev->class >> 8;
3212 
3213 	/* AMD GPU vendor ID */
3214 	if (pdev->vendor != PCI_VENDOR_ID_ATI)
3215 		return false;
3216 
3217 	/* GPU class */
3218 	if (class != PCI_CLASS_DISPLAY_VGA &&
3219 	    class != PCI_CLASS_DISPLAY_OTHER)
3220 		return false;
3221 
3222 	bridge = pci_upstream_bridge(pdev);
3223 	if (bridge && bridge->vendor == PCI_VENDOR_ID_ATI)
3224 		return false;
3225 
3226 	/* It is the GPU in an APU, force identity domain */
3227 	return true;
3228 }
3229 
3230 static int amd_iommu_def_domain_type(struct device *dev)
3231 {
3232 	struct iommu_dev_data *dev_data;
3233 
3234 	dev_data = dev_iommu_priv_get(dev);
3235 	if (!dev_data)
3236 		return 0;
3237 
3238 	if (!dev_is_pci(dev))
3239 		return 0;
3240 
3241 	/* Always use DMA domain for untrusted device */
3242 	if (to_pci_dev(dev)->untrusted)
3243 		return IOMMU_DOMAIN_DMA;
3244 
3245 	/* Apply device specific quirks */
3246 	if (quirks_force_identity_mapping(to_pci_dev(dev))) {
3247 		/*
3248 		 * When memory encryption is active, some of these devices
3249 		 * don't have the encryption bit in their DMA-mask and
3250 		 * require remapping.
3251 		 */
3252 		if (cc_platform_has(CC_ATTR_MEM_ENCRYPT))
3253 			return 0;
3254 
3255 		dev_data->perfopt = get_amd_iommu_from_dev_data(dev_data)->features &
3256 				    FEATURE_PERF_OPT;
3257 
3258 		return IOMMU_DOMAIN_IDENTITY;
3259 	}
3260 
3261 	return 0;
3262 }
3263 
3264 static bool amd_iommu_enforce_cache_coherency(struct iommu_domain *domain)
3265 {
3266 	/* IOMMU_PTE_FC is always set */
3267 	return true;
3268 }
3269 
3270 const struct iommu_ops amd_iommu_ops = {
3271 	.capable = amd_iommu_capable,
3272 	.hw_info = amd_iommufd_hw_info,
3273 	.blocked_domain = &blocked_domain,
3274 	.release_domain = &blocked_domain,
3275 	.identity_domain = &identity_domain.domain,
3276 	.domain_alloc_paging_flags = amd_iommu_domain_alloc_paging_flags,
3277 	.domain_alloc_sva = amd_iommu_domain_alloc_sva,
3278 	.probe_device = amd_iommu_probe_device,
3279 	.device_group = amd_iommu_device_group,
3280 	.get_resv_regions = amd_iommu_get_resv_regions,
3281 	.is_attach_deferred = amd_iommu_is_attach_deferred,
3282 	.def_domain_type = amd_iommu_def_domain_type,
3283 	.page_response = amd_iommu_page_response,
3284 	.get_viommu_size = amd_iommufd_get_viommu_size,
3285 	.viommu_init = amd_iommufd_viommu_init,
3286 };
3287 
3288 #ifdef CONFIG_IRQ_REMAP
3289 
3290 /*****************************************************************************
3291  *
3292  * Interrupt Remapping Implementation
3293  *
3294  *****************************************************************************/
3295 
3296 static struct irq_chip amd_ir_chip;
3297 static DEFINE_SPINLOCK(iommu_table_lock);
3298 
3299 static int iommu_flush_dev_irt(struct pci_dev *unused, u16 devid, void *data)
3300 {
3301 	int ret;
3302 	struct iommu_cmd cmd;
3303 	struct amd_iommu *iommu = data;
3304 
3305 	build_inv_irt(&cmd, devid);
3306 	ret = __iommu_queue_command_sync(iommu, &cmd, true);
3307 	return ret;
3308 }
3309 
3310 static void iommu_flush_irt_and_complete(struct amd_iommu *iommu, u16 devid)
3311 {
3312 	int ret;
3313 	u64 data;
3314 	unsigned long flags;
3315 	struct iommu_cmd cmd;
3316 	struct pci_dev *pdev = NULL;
3317 	struct iommu_dev_data *dev_data = search_dev_data(iommu, devid);
3318 
3319 	if (iommu->irtcachedis_enabled)
3320 		return;
3321 
3322 	if (dev_data && dev_data->dev && dev_is_pci(dev_data->dev))
3323 		pdev = to_pci_dev(dev_data->dev);
3324 
3325 	raw_spin_lock_irqsave(&iommu->lock, flags);
3326 	data = get_cmdsem_val(iommu);
3327 	build_completion_wait(&cmd, iommu, data);
3328 
3329 	if (pdev)
3330 		ret = pci_for_each_dma_alias(pdev, iommu_flush_dev_irt, iommu);
3331 	else
3332 		ret = iommu_flush_dev_irt(NULL, devid, iommu);
3333 	if (ret)
3334 		goto out_err;
3335 
3336 	ret = __iommu_queue_command_sync(iommu, &cmd, false);
3337 	if (ret)
3338 		goto out_err;
3339 	raw_spin_unlock_irqrestore(&iommu->lock, flags);
3340 
3341 	wait_on_sem(iommu, data);
3342 	return;
3343 
3344 out_err:
3345 	raw_spin_unlock_irqrestore(&iommu->lock, flags);
3346 }
3347 
3348 static inline u8 iommu_get_int_tablen(struct iommu_dev_data *dev_data)
3349 {
3350 	if (dev_data && dev_data->max_irqs == MAX_IRQS_PER_TABLE_2K)
3351 		return DTE_INTTABLEN_2K;
3352 	return DTE_INTTABLEN_512;
3353 }
3354 
3355 static void set_dte_irq_entry(struct amd_iommu *iommu, u16 devid,
3356 			      struct irq_remap_table *table)
3357 {
3358 	u64 new;
3359 	struct dev_table_entry *dte = &get_dev_table(iommu)[devid];
3360 	struct iommu_dev_data *dev_data = search_dev_data(iommu, devid);
3361 
3362 	if (dev_data)
3363 		spin_lock(&dev_data->dte_lock);
3364 
3365 	new = READ_ONCE(dte->data[2]);
3366 	new &= ~DTE_IRQ_PHYS_ADDR_MASK;
3367 	new |= iommu_virt_to_phys(table->table);
3368 	new |= DTE_IRQ_REMAP_INTCTL;
3369 	new |= iommu_get_int_tablen(dev_data);
3370 	new |= DTE_IRQ_REMAP_ENABLE;
3371 	WRITE_ONCE(dte->data[2], new);
3372 
3373 	if (dev_data)
3374 		spin_unlock(&dev_data->dte_lock);
3375 }
3376 
3377 static struct irq_remap_table *get_irq_table(struct amd_iommu *iommu, u16 devid)
3378 {
3379 	struct irq_remap_table *table;
3380 	struct amd_iommu_pci_seg *pci_seg = iommu->pci_seg;
3381 
3382 	if (WARN_ONCE(!pci_seg->rlookup_table[devid],
3383 		      "%s: no iommu for devid %x:%x\n",
3384 		      __func__, pci_seg->id, devid))
3385 		return NULL;
3386 
3387 	table = pci_seg->irq_lookup_table[devid];
3388 	if (WARN_ONCE(!table, "%s: no table for devid %x:%x\n",
3389 		      __func__, pci_seg->id, devid))
3390 		return NULL;
3391 
3392 	return table;
3393 }
3394 
3395 static struct irq_remap_table *__alloc_irq_table(int nid, size_t size)
3396 {
3397 	struct irq_remap_table *table;
3398 
3399 	table = kzalloc_obj(*table);
3400 	if (!table)
3401 		return NULL;
3402 
3403 	table->table = iommu_alloc_pages_node_sz(
3404 		nid, GFP_KERNEL, max(DTE_INTTAB_ALIGNMENT, size));
3405 	if (!table->table) {
3406 		kfree(table);
3407 		return NULL;
3408 	}
3409 	raw_spin_lock_init(&table->lock);
3410 
3411 	return table;
3412 }
3413 
3414 static void set_remap_table_entry(struct amd_iommu *iommu, u16 devid,
3415 				  struct irq_remap_table *table)
3416 {
3417 	struct amd_iommu_pci_seg *pci_seg = iommu->pci_seg;
3418 
3419 	pci_seg->irq_lookup_table[devid] = table;
3420 	set_dte_irq_entry(iommu, devid, table);
3421 	iommu_flush_dte(iommu, devid);
3422 }
3423 
3424 static int set_remap_table_entry_alias(struct pci_dev *pdev, u16 alias,
3425 				       void *data)
3426 {
3427 	struct irq_remap_table *table = data;
3428 	struct amd_iommu_pci_seg *pci_seg;
3429 	struct amd_iommu *iommu = rlookup_amd_iommu(&pdev->dev);
3430 
3431 	if (!iommu)
3432 		return -EINVAL;
3433 
3434 	pci_seg = iommu->pci_seg;
3435 	pci_seg->irq_lookup_table[alias] = table;
3436 	set_dte_irq_entry(iommu, alias, table);
3437 	iommu_flush_dte(pci_seg->rlookup_table[alias], alias);
3438 
3439 	return 0;
3440 }
3441 
3442 static inline size_t get_irq_table_size(unsigned int max_irqs)
3443 {
3444 	if (!AMD_IOMMU_GUEST_IR_GA(amd_iommu_guest_ir))
3445 		return max_irqs * sizeof(u32);
3446 
3447 	return max_irqs * (sizeof(u64) * 2);
3448 }
3449 
3450 static struct irq_remap_table *alloc_irq_table(struct amd_iommu *iommu,
3451 					       u16 devid, struct pci_dev *pdev,
3452 					       unsigned int max_irqs)
3453 {
3454 	struct irq_remap_table *table = NULL;
3455 	struct irq_remap_table *new_table = NULL;
3456 	struct amd_iommu_pci_seg *pci_seg;
3457 	unsigned long flags;
3458 	int nid = iommu->dev ? dev_to_node(&iommu->dev->dev) : NUMA_NO_NODE;
3459 	u16 alias;
3460 
3461 	spin_lock_irqsave(&iommu_table_lock, flags);
3462 
3463 	pci_seg = iommu->pci_seg;
3464 	table = pci_seg->irq_lookup_table[devid];
3465 	if (table)
3466 		goto out_unlock;
3467 
3468 	alias = pci_seg->alias_table[devid];
3469 	table = pci_seg->irq_lookup_table[alias];
3470 	if (table) {
3471 		set_remap_table_entry(iommu, devid, table);
3472 		goto out_wait;
3473 	}
3474 	spin_unlock_irqrestore(&iommu_table_lock, flags);
3475 
3476 	/* Nothing there yet, allocate new irq remapping table */
3477 	new_table = __alloc_irq_table(nid, get_irq_table_size(max_irqs));
3478 	if (!new_table)
3479 		return NULL;
3480 
3481 	spin_lock_irqsave(&iommu_table_lock, flags);
3482 
3483 	table = pci_seg->irq_lookup_table[devid];
3484 	if (table)
3485 		goto out_unlock;
3486 
3487 	table = pci_seg->irq_lookup_table[alias];
3488 	if (table) {
3489 		set_remap_table_entry(iommu, devid, table);
3490 		goto out_wait;
3491 	}
3492 
3493 	table = new_table;
3494 	new_table = NULL;
3495 
3496 	if (pdev)
3497 		pci_for_each_dma_alias(pdev, set_remap_table_entry_alias,
3498 				       table);
3499 	else
3500 		set_remap_table_entry(iommu, devid, table);
3501 
3502 	if (devid != alias)
3503 		set_remap_table_entry(iommu, alias, table);
3504 
3505 out_wait:
3506 	iommu_completion_wait(iommu);
3507 
3508 out_unlock:
3509 	spin_unlock_irqrestore(&iommu_table_lock, flags);
3510 
3511 	if (new_table) {
3512 		iommu_free_pages(new_table->table);
3513 		kfree(new_table);
3514 	}
3515 	return table;
3516 }
3517 
3518 static int alloc_irq_index(struct amd_iommu *iommu, u16 devid, int count,
3519 			   bool align, struct pci_dev *pdev,
3520 			   unsigned long max_irqs)
3521 {
3522 	struct irq_remap_table *table;
3523 	int index, c, alignment = 1;
3524 	unsigned long flags;
3525 
3526 	table = alloc_irq_table(iommu, devid, pdev, max_irqs);
3527 	if (!table)
3528 		return -ENODEV;
3529 
3530 	if (align)
3531 		alignment = roundup_pow_of_two(count);
3532 
3533 	raw_spin_lock_irqsave(&table->lock, flags);
3534 
3535 	/* Scan table for free entries */
3536 	for (index = ALIGN(table->min_index, alignment), c = 0;
3537 	     index < max_irqs;) {
3538 		if (!iommu->irte_ops->is_allocated(table, index)) {
3539 			c += 1;
3540 		} else {
3541 			c     = 0;
3542 			index = ALIGN(index + 1, alignment);
3543 			continue;
3544 		}
3545 
3546 		if (c == count)	{
3547 			for (; c != 0; --c)
3548 				iommu->irte_ops->set_allocated(table, index - c + 1);
3549 
3550 			index -= count - 1;
3551 			goto out;
3552 		}
3553 
3554 		index++;
3555 	}
3556 
3557 	index = -ENOSPC;
3558 
3559 out:
3560 	raw_spin_unlock_irqrestore(&table->lock, flags);
3561 
3562 	return index;
3563 }
3564 
3565 static int __modify_irte_ga(struct amd_iommu *iommu, u16 devid, int index,
3566 			    struct irte_ga *irte)
3567 {
3568 	struct irq_remap_table *table;
3569 	struct irte_ga *entry;
3570 	unsigned long flags;
3571 	u128 old;
3572 
3573 	table = get_irq_table(iommu, devid);
3574 	if (!table)
3575 		return -ENOMEM;
3576 
3577 	raw_spin_lock_irqsave(&table->lock, flags);
3578 
3579 	entry = (struct irte_ga *)table->table;
3580 	entry = &entry[index];
3581 
3582 	/*
3583 	 * We use cmpxchg16 to atomically update the 128-bit IRTE,
3584 	 * and it cannot be updated by the hardware or other processors
3585 	 * behind us, so the return value of cmpxchg16 should be the
3586 	 * same as the old value.
3587 	 */
3588 	old = entry->irte;
3589 	WARN_ON(!try_cmpxchg128(&entry->irte, &old, irte->irte));
3590 
3591 	raw_spin_unlock_irqrestore(&table->lock, flags);
3592 
3593 	return 0;
3594 }
3595 
3596 static int modify_irte_ga(struct amd_iommu *iommu, u16 devid, int index,
3597 			  struct irte_ga *irte)
3598 {
3599 	int ret;
3600 
3601 	ret = __modify_irte_ga(iommu, devid, index, irte);
3602 	if (ret)
3603 		return ret;
3604 
3605 	iommu_flush_irt_and_complete(iommu, devid);
3606 
3607 	return 0;
3608 }
3609 
3610 static int modify_irte(struct amd_iommu *iommu,
3611 		       u16 devid, int index, union irte *irte)
3612 {
3613 	struct irq_remap_table *table;
3614 	unsigned long flags;
3615 
3616 	table = get_irq_table(iommu, devid);
3617 	if (!table)
3618 		return -ENOMEM;
3619 
3620 	raw_spin_lock_irqsave(&table->lock, flags);
3621 	table->table[index] = irte->val;
3622 	raw_spin_unlock_irqrestore(&table->lock, flags);
3623 
3624 	iommu_flush_irt_and_complete(iommu, devid);
3625 
3626 	return 0;
3627 }
3628 
3629 static void free_irte(struct amd_iommu *iommu, u16 devid, int index)
3630 {
3631 	struct irq_remap_table *table;
3632 	unsigned long flags;
3633 
3634 	table = get_irq_table(iommu, devid);
3635 	if (!table)
3636 		return;
3637 
3638 	raw_spin_lock_irqsave(&table->lock, flags);
3639 	iommu->irte_ops->clear_allocated(table, index);
3640 	raw_spin_unlock_irqrestore(&table->lock, flags);
3641 
3642 	iommu_flush_irt_and_complete(iommu, devid);
3643 }
3644 
3645 static void irte_prepare(void *entry,
3646 			 u32 delivery_mode, bool dest_mode,
3647 			 u8 vector, u32 dest_apicid, int devid)
3648 {
3649 	union irte *irte = (union irte *) entry;
3650 
3651 	irte->val                = 0;
3652 	irte->fields.vector      = vector;
3653 	irte->fields.int_type    = delivery_mode;
3654 	irte->fields.destination = dest_apicid;
3655 	irte->fields.dm          = dest_mode;
3656 	irte->fields.valid       = 1;
3657 }
3658 
3659 static void irte_ga_prepare(void *entry,
3660 			    u32 delivery_mode, bool dest_mode,
3661 			    u8 vector, u32 dest_apicid, int devid)
3662 {
3663 	struct irte_ga *irte = (struct irte_ga *) entry;
3664 
3665 	irte->lo.val                      = 0;
3666 	irte->hi.val                      = 0;
3667 	irte->lo.fields_remap.int_type    = delivery_mode;
3668 	irte->lo.fields_remap.dm          = dest_mode;
3669 	irte->hi.fields.vector            = vector;
3670 	irte->lo.fields_remap.destination = APICID_TO_IRTE_DEST_LO(dest_apicid);
3671 	irte->hi.fields.destination       = APICID_TO_IRTE_DEST_HI(dest_apicid);
3672 	irte->lo.fields_remap.valid       = 1;
3673 }
3674 
3675 static void irte_activate(struct amd_iommu *iommu, void *entry, u16 devid, u16 index)
3676 {
3677 	union irte *irte = (union irte *) entry;
3678 
3679 	irte->fields.valid = 1;
3680 	modify_irte(iommu, devid, index, irte);
3681 }
3682 
3683 static void irte_ga_activate(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 = 1;
3688 	modify_irte_ga(iommu, devid, index, irte);
3689 }
3690 
3691 static void irte_deactivate(struct amd_iommu *iommu, void *entry, u16 devid, u16 index)
3692 {
3693 	union irte *irte = (union irte *) entry;
3694 
3695 	irte->fields.valid = 0;
3696 	modify_irte(iommu, devid, index, irte);
3697 }
3698 
3699 static void irte_ga_deactivate(struct amd_iommu *iommu, void *entry, u16 devid, u16 index)
3700 {
3701 	struct irte_ga *irte = (struct irte_ga *) entry;
3702 
3703 	irte->lo.fields_remap.valid = 0;
3704 	modify_irte_ga(iommu, devid, index, irte);
3705 }
3706 
3707 static void irte_set_affinity(struct amd_iommu *iommu, void *entry, u16 devid, u16 index,
3708 			      u8 vector, u32 dest_apicid)
3709 {
3710 	union irte *irte = (union irte *) entry;
3711 
3712 	irte->fields.vector = vector;
3713 	irte->fields.destination = dest_apicid;
3714 	modify_irte(iommu, devid, index, irte);
3715 }
3716 
3717 static void irte_ga_set_affinity(struct amd_iommu *iommu, void *entry, u16 devid, u16 index,
3718 				 u8 vector, u32 dest_apicid)
3719 {
3720 	struct irte_ga *irte = (struct irte_ga *) entry;
3721 
3722 	if (!irte->lo.fields_remap.guest_mode) {
3723 		irte->hi.fields.vector = vector;
3724 		irte->lo.fields_remap.destination =
3725 					APICID_TO_IRTE_DEST_LO(dest_apicid);
3726 		irte->hi.fields.destination =
3727 					APICID_TO_IRTE_DEST_HI(dest_apicid);
3728 		modify_irte_ga(iommu, devid, index, irte);
3729 	}
3730 }
3731 
3732 #define IRTE_ALLOCATED (~1U)
3733 static void irte_set_allocated(struct irq_remap_table *table, int index)
3734 {
3735 	table->table[index] = IRTE_ALLOCATED;
3736 }
3737 
3738 static void irte_ga_set_allocated(struct irq_remap_table *table, int index)
3739 {
3740 	struct irte_ga *ptr = (struct irte_ga *)table->table;
3741 	struct irte_ga *irte = &ptr[index];
3742 
3743 	memset(&irte->lo.val, 0, sizeof(u64));
3744 	memset(&irte->hi.val, 0, sizeof(u64));
3745 	irte->hi.fields.vector = 0xff;
3746 }
3747 
3748 static bool irte_is_allocated(struct irq_remap_table *table, int index)
3749 {
3750 	union irte *ptr = (union irte *)table->table;
3751 	union irte *irte = &ptr[index];
3752 
3753 	return irte->val != 0;
3754 }
3755 
3756 static bool irte_ga_is_allocated(struct irq_remap_table *table, int index)
3757 {
3758 	struct irte_ga *ptr = (struct irte_ga *)table->table;
3759 	struct irte_ga *irte = &ptr[index];
3760 
3761 	return irte->hi.fields.vector != 0;
3762 }
3763 
3764 static void irte_clear_allocated(struct irq_remap_table *table, int index)
3765 {
3766 	table->table[index] = 0;
3767 }
3768 
3769 static void irte_ga_clear_allocated(struct irq_remap_table *table, int index)
3770 {
3771 	struct irte_ga *ptr = (struct irte_ga *)table->table;
3772 	struct irte_ga *irte = &ptr[index];
3773 
3774 	memset(&irte->lo.val, 0, sizeof(u64));
3775 	memset(&irte->hi.val, 0, sizeof(u64));
3776 }
3777 
3778 static int get_devid(struct irq_alloc_info *info)
3779 {
3780 	switch (info->type) {
3781 	case X86_IRQ_ALLOC_TYPE_IOAPIC:
3782 		return get_ioapic_devid(info->devid);
3783 	case X86_IRQ_ALLOC_TYPE_HPET:
3784 		return get_hpet_devid(info->devid);
3785 	case X86_IRQ_ALLOC_TYPE_PCI_MSI:
3786 	case X86_IRQ_ALLOC_TYPE_PCI_MSIX:
3787 		return get_device_sbdf_id(msi_desc_to_dev(info->desc));
3788 	default:
3789 		WARN_ON_ONCE(1);
3790 		return -1;
3791 	}
3792 }
3793 
3794 struct irq_remap_ops amd_iommu_irq_ops = {
3795 	.prepare		= amd_iommu_prepare,
3796 	.enable			= amd_iommu_enable,
3797 	.disable		= amd_iommu_disable,
3798 	.reenable		= amd_iommu_reenable,
3799 	.enable_faulting	= amd_iommu_enable_faulting,
3800 };
3801 
3802 static void fill_msi_msg(struct msi_msg *msg, u32 index)
3803 {
3804 	msg->data = index;
3805 	msg->address_lo = 0;
3806 	msg->arch_addr_lo.base_address = X86_MSI_BASE_ADDRESS_LOW;
3807 	/*
3808 	 * The struct msi_msg.dest_mode_logical is used to set the DM bit
3809 	 * in MSI Message Address Register. For device w/ 2K int-remap support,
3810 	 * this bit must be set to 1 regardless of the actual destination
3811 	 * mode, which is signified by the IRTE[DM].
3812 	 */
3813 	if (FEATURE_NUM_INT_REMAP_SUP_2K(amd_iommu_efr2))
3814 		msg->arch_addr_lo.dest_mode_logical = true;
3815 	msg->address_hi = X86_MSI_BASE_ADDRESS_HIGH;
3816 }
3817 
3818 static void irq_remapping_prepare_irte(struct amd_ir_data *data,
3819 				       struct irq_cfg *irq_cfg,
3820 				       struct irq_alloc_info *info,
3821 				       int devid, int index, int sub_handle)
3822 {
3823 	struct irq_2_irte *irte_info = &data->irq_2_irte;
3824 	struct amd_iommu *iommu = data->iommu;
3825 
3826 	if (!iommu)
3827 		return;
3828 
3829 	data->irq_2_irte.devid = devid;
3830 	data->irq_2_irte.index = index + sub_handle;
3831 	iommu->irte_ops->prepare(data->entry, APIC_DELIVERY_MODE_FIXED,
3832 				 apic->dest_mode_logical, irq_cfg->vector,
3833 				 irq_cfg->dest_apicid, devid);
3834 
3835 	switch (info->type) {
3836 	case X86_IRQ_ALLOC_TYPE_IOAPIC:
3837 	case X86_IRQ_ALLOC_TYPE_HPET:
3838 	case X86_IRQ_ALLOC_TYPE_PCI_MSI:
3839 	case X86_IRQ_ALLOC_TYPE_PCI_MSIX:
3840 		fill_msi_msg(&data->msi_entry, irte_info->index);
3841 		break;
3842 
3843 	default:
3844 		BUG_ON(1);
3845 		break;
3846 	}
3847 }
3848 
3849 struct amd_irte_ops irte_32_ops = {
3850 	.prepare = irte_prepare,
3851 	.activate = irte_activate,
3852 	.deactivate = irte_deactivate,
3853 	.set_affinity = irte_set_affinity,
3854 	.set_allocated = irte_set_allocated,
3855 	.is_allocated = irte_is_allocated,
3856 	.clear_allocated = irte_clear_allocated,
3857 };
3858 
3859 struct amd_irte_ops irte_128_ops = {
3860 	.prepare = irte_ga_prepare,
3861 	.activate = irte_ga_activate,
3862 	.deactivate = irte_ga_deactivate,
3863 	.set_affinity = irte_ga_set_affinity,
3864 	.set_allocated = irte_ga_set_allocated,
3865 	.is_allocated = irte_ga_is_allocated,
3866 	.clear_allocated = irte_ga_clear_allocated,
3867 };
3868 
3869 static int irq_remapping_alloc(struct irq_domain *domain, unsigned int virq,
3870 			       unsigned int nr_irqs, void *arg)
3871 {
3872 	struct irq_alloc_info *info = arg;
3873 	struct irq_data *irq_data;
3874 	struct amd_ir_data *data = NULL;
3875 	struct amd_iommu *iommu;
3876 	struct irq_cfg *cfg;
3877 	struct iommu_dev_data *dev_data;
3878 	unsigned long max_irqs;
3879 	int i, ret, devid, seg, sbdf;
3880 	int index;
3881 
3882 	if (!info)
3883 		return -EINVAL;
3884 	if (nr_irqs > 1 && info->type != X86_IRQ_ALLOC_TYPE_PCI_MSI)
3885 		return -EINVAL;
3886 
3887 	sbdf = get_devid(info);
3888 	if (sbdf < 0)
3889 		return -EINVAL;
3890 
3891 	seg = PCI_SBDF_TO_SEGID(sbdf);
3892 	devid = PCI_SBDF_TO_DEVID(sbdf);
3893 	iommu = __rlookup_amd_iommu(seg, devid);
3894 	if (!iommu)
3895 		return -EINVAL;
3896 
3897 	dev_data = search_dev_data(iommu, devid);
3898 	max_irqs = dev_data ? dev_data->max_irqs : MAX_IRQS_PER_TABLE_512;
3899 
3900 	ret = irq_domain_alloc_irqs_parent(domain, virq, nr_irqs, arg);
3901 	if (ret < 0)
3902 		return ret;
3903 
3904 	if (info->type == X86_IRQ_ALLOC_TYPE_IOAPIC) {
3905 		struct irq_remap_table *table;
3906 
3907 		table = alloc_irq_table(iommu, devid, NULL, max_irqs);
3908 		if (table) {
3909 			if (!table->min_index) {
3910 				/*
3911 				 * Keep the first 32 indexes free for IOAPIC
3912 				 * interrupts.
3913 				 */
3914 				table->min_index = 32;
3915 				for (i = 0; i < 32; ++i)
3916 					iommu->irte_ops->set_allocated(table, i);
3917 			}
3918 			WARN_ON(table->min_index != 32);
3919 			index = info->ioapic.pin;
3920 		} else {
3921 			index = -ENOMEM;
3922 		}
3923 	} else if (info->type == X86_IRQ_ALLOC_TYPE_PCI_MSI ||
3924 		   info->type == X86_IRQ_ALLOC_TYPE_PCI_MSIX) {
3925 		bool align = (info->type == X86_IRQ_ALLOC_TYPE_PCI_MSI);
3926 
3927 		index = alloc_irq_index(iommu, devid, nr_irqs, align,
3928 					msi_desc_to_pci_dev(info->desc),
3929 					max_irqs);
3930 	} else {
3931 		index = alloc_irq_index(iommu, devid, nr_irqs, false, NULL,
3932 					max_irqs);
3933 	}
3934 
3935 	if (index < 0) {
3936 		pr_warn("Failed to allocate IRTE\n");
3937 		ret = index;
3938 		goto out_free_parent;
3939 	}
3940 
3941 	for (i = 0; i < nr_irqs; i++) {
3942 		irq_data = irq_domain_get_irq_data(domain, virq + i);
3943 		cfg = irq_data ? irqd_cfg(irq_data) : NULL;
3944 		if (!cfg) {
3945 			ret = -EINVAL;
3946 			goto out_free_data;
3947 		}
3948 
3949 		ret = -ENOMEM;
3950 		data = kzalloc_obj(*data);
3951 		if (!data)
3952 			goto out_free_data;
3953 
3954 		if (!AMD_IOMMU_GUEST_IR_GA(amd_iommu_guest_ir))
3955 			data->entry = kzalloc_obj(union irte);
3956 		else
3957 			data->entry = kzalloc_obj(struct irte_ga);
3958 		if (!data->entry) {
3959 			kfree(data);
3960 			goto out_free_data;
3961 		}
3962 
3963 		data->iommu = iommu;
3964 		irq_data->hwirq = (devid << 16) + i;
3965 		irq_data->chip_data = data;
3966 		irq_data->chip = &amd_ir_chip;
3967 		irq_remapping_prepare_irte(data, cfg, info, devid, index, i);
3968 	}
3969 
3970 	return 0;
3971 
3972 out_free_data:
3973 	for (i--; i >= 0; i--) {
3974 		irq_data = irq_domain_get_irq_data(domain, virq + i);
3975 		if (irq_data && irq_data->chip_data) {
3976 			data = irq_data->chip_data;
3977 			kfree(data->entry);
3978 			kfree(data);
3979 		}
3980 	}
3981 	for (i = 0; i < nr_irqs; i++)
3982 		free_irte(iommu, devid, index + i);
3983 out_free_parent:
3984 	irq_domain_free_irqs_common(domain, virq, nr_irqs);
3985 	return ret;
3986 }
3987 
3988 static void irq_remapping_free(struct irq_domain *domain, unsigned int virq,
3989 			       unsigned int nr_irqs)
3990 {
3991 	struct irq_2_irte *irte_info;
3992 	struct irq_data *irq_data;
3993 	struct amd_ir_data *data;
3994 	int i;
3995 
3996 	for (i = 0; i < nr_irqs; i++) {
3997 		irq_data = irq_domain_get_irq_data(domain, virq  + i);
3998 		if (irq_data && irq_data->chip_data) {
3999 			data = irq_data->chip_data;
4000 			irte_info = &data->irq_2_irte;
4001 			free_irte(data->iommu, irte_info->devid, irte_info->index);
4002 			kfree(data->entry);
4003 			kfree(data);
4004 		}
4005 	}
4006 	irq_domain_free_irqs_common(domain, virq, nr_irqs);
4007 }
4008 
4009 static void amd_ir_update_irte(struct irq_data *irqd, struct amd_iommu *iommu,
4010 			       struct amd_ir_data *ir_data,
4011 			       struct irq_2_irte *irte_info,
4012 			       struct irq_cfg *cfg);
4013 
4014 static int irq_remapping_activate(struct irq_domain *domain,
4015 				  struct irq_data *irq_data, bool reserve)
4016 {
4017 	struct amd_ir_data *data = irq_data->chip_data;
4018 	struct irq_2_irte *irte_info = &data->irq_2_irte;
4019 	struct amd_iommu *iommu = data->iommu;
4020 	struct irq_cfg *cfg = irqd_cfg(irq_data);
4021 
4022 	if (!iommu)
4023 		return 0;
4024 
4025 	iommu->irte_ops->activate(iommu, data->entry, irte_info->devid,
4026 				  irte_info->index);
4027 	amd_ir_update_irte(irq_data, iommu, data, irte_info, cfg);
4028 	return 0;
4029 }
4030 
4031 static void irq_remapping_deactivate(struct irq_domain *domain,
4032 				     struct irq_data *irq_data)
4033 {
4034 	struct amd_ir_data *data = irq_data->chip_data;
4035 	struct irq_2_irte *irte_info = &data->irq_2_irte;
4036 	struct amd_iommu *iommu = data->iommu;
4037 
4038 	if (iommu)
4039 		iommu->irte_ops->deactivate(iommu, data->entry, irte_info->devid,
4040 					    irte_info->index);
4041 }
4042 
4043 static int irq_remapping_select(struct irq_domain *d, struct irq_fwspec *fwspec,
4044 				enum irq_domain_bus_token bus_token)
4045 {
4046 	struct amd_iommu *iommu;
4047 	int devid = -1;
4048 
4049 	if (!amd_iommu_irq_remap)
4050 		return 0;
4051 
4052 	if (x86_fwspec_is_ioapic(fwspec))
4053 		devid = get_ioapic_devid(fwspec->param[0]);
4054 	else if (x86_fwspec_is_hpet(fwspec))
4055 		devid = get_hpet_devid(fwspec->param[0]);
4056 
4057 	if (devid < 0)
4058 		return 0;
4059 	iommu = __rlookup_amd_iommu((devid >> 16), (devid & 0xffff));
4060 
4061 	return iommu && iommu->ir_domain == d;
4062 }
4063 
4064 static const struct irq_domain_ops amd_ir_domain_ops = {
4065 	.select = irq_remapping_select,
4066 	.alloc = irq_remapping_alloc,
4067 	.free = irq_remapping_free,
4068 	.activate = irq_remapping_activate,
4069 	.deactivate = irq_remapping_deactivate,
4070 };
4071 
4072 static void __amd_iommu_update_ga(struct irte_ga *entry, int cpu,
4073 				  bool ga_log_intr)
4074 {
4075 	if (cpu >= 0) {
4076 		entry->lo.fields_vapic.destination =
4077 					APICID_TO_IRTE_DEST_LO(cpu);
4078 		entry->hi.fields.destination =
4079 					APICID_TO_IRTE_DEST_HI(cpu);
4080 		entry->lo.fields_vapic.is_run = true;
4081 		entry->lo.fields_vapic.ga_log_intr = false;
4082 	} else {
4083 		entry->lo.fields_vapic.is_run = false;
4084 		entry->lo.fields_vapic.ga_log_intr = ga_log_intr;
4085 	}
4086 }
4087 
4088 /*
4089  * Update the pCPU information for an IRTE that is configured to post IRQs to
4090  * a vCPU, without issuing an IOMMU invalidation for the IRTE.
4091  *
4092  * If the vCPU is associated with a pCPU (@cpu >= 0), configure the Destination
4093  * with the pCPU's APIC ID, set IsRun, and clear GALogIntr.  If the vCPU isn't
4094  * associated with a pCPU (@cpu < 0), clear IsRun and set/clear GALogIntr based
4095  * on input from the caller (e.g. KVM only requests GALogIntr when the vCPU is
4096  * blocking and requires a notification wake event).  I.e. treat vCPUs that are
4097  * associated with a pCPU as running.  This API is intended to be used when a
4098  * vCPU is scheduled in/out (or stops running for any reason), to do a fast
4099  * update of IsRun, GALogIntr, and (conditionally) Destination.
4100  *
4101  * Per the IOMMU spec, the Destination, IsRun, and GATag fields are not cached
4102  * and thus don't require an invalidation to ensure the IOMMU consumes fresh
4103  * information.
4104  */
4105 int amd_iommu_update_ga(void *data, int cpu, bool ga_log_intr)
4106 {
4107 	struct amd_ir_data *ir_data = (struct amd_ir_data *)data;
4108 	struct irte_ga *entry = (struct irte_ga *) ir_data->entry;
4109 
4110 	if (WARN_ON_ONCE(!AMD_IOMMU_GUEST_IR_VAPIC(amd_iommu_guest_ir)))
4111 		return -EINVAL;
4112 
4113 	if (!entry || !entry->lo.fields_vapic.guest_mode)
4114 		return 0;
4115 
4116 	if (!ir_data->iommu)
4117 		return -ENODEV;
4118 
4119 	__amd_iommu_update_ga(entry, cpu, ga_log_intr);
4120 
4121 	return __modify_irte_ga(ir_data->iommu, ir_data->irq_2_irte.devid,
4122 				ir_data->irq_2_irte.index, entry);
4123 }
4124 EXPORT_SYMBOL(amd_iommu_update_ga);
4125 
4126 int amd_iommu_activate_guest_mode(void *data, int cpu, bool ga_log_intr)
4127 {
4128 	struct amd_ir_data *ir_data = (struct amd_ir_data *)data;
4129 	struct irte_ga *entry = (struct irte_ga *) ir_data->entry;
4130 	u64 valid;
4131 
4132 	if (WARN_ON_ONCE(!AMD_IOMMU_GUEST_IR_VAPIC(amd_iommu_guest_ir)))
4133 		return -EINVAL;
4134 
4135 	if (!entry)
4136 		return 0;
4137 
4138 	valid = entry->lo.fields_vapic.valid;
4139 
4140 	entry->lo.val = 0;
4141 	entry->hi.val = 0;
4142 
4143 	entry->lo.fields_vapic.valid       = valid;
4144 	entry->lo.fields_vapic.guest_mode  = 1;
4145 	entry->hi.fields.ga_root_ptr       = ir_data->ga_root_ptr;
4146 	entry->hi.fields.vector            = ir_data->ga_vector;
4147 	entry->lo.fields_vapic.ga_tag      = ir_data->ga_tag;
4148 
4149 	__amd_iommu_update_ga(entry, cpu, ga_log_intr);
4150 
4151 	return modify_irte_ga(ir_data->iommu, ir_data->irq_2_irte.devid,
4152 			      ir_data->irq_2_irte.index, entry);
4153 }
4154 EXPORT_SYMBOL(amd_iommu_activate_guest_mode);
4155 
4156 int amd_iommu_deactivate_guest_mode(void *data)
4157 {
4158 	struct amd_ir_data *ir_data = (struct amd_ir_data *)data;
4159 	struct irte_ga *entry = (struct irte_ga *) ir_data->entry;
4160 	struct irq_cfg *cfg = ir_data->cfg;
4161 	u64 valid;
4162 
4163 	if (WARN_ON_ONCE(!AMD_IOMMU_GUEST_IR_VAPIC(amd_iommu_guest_ir)))
4164 		return -EINVAL;
4165 
4166 	if (!entry || !entry->lo.fields_vapic.guest_mode)
4167 		return 0;
4168 
4169 	valid = entry->lo.fields_remap.valid;
4170 
4171 	entry->lo.val = 0;
4172 	entry->hi.val = 0;
4173 
4174 	entry->lo.fields_remap.valid       = valid;
4175 	entry->lo.fields_remap.dm          = apic->dest_mode_logical;
4176 	entry->lo.fields_remap.int_type    = APIC_DELIVERY_MODE_FIXED;
4177 	entry->hi.fields.vector            = cfg->vector;
4178 	entry->lo.fields_remap.destination =
4179 				APICID_TO_IRTE_DEST_LO(cfg->dest_apicid);
4180 	entry->hi.fields.destination =
4181 				APICID_TO_IRTE_DEST_HI(cfg->dest_apicid);
4182 
4183 	return modify_irte_ga(ir_data->iommu, ir_data->irq_2_irte.devid,
4184 			      ir_data->irq_2_irte.index, entry);
4185 }
4186 EXPORT_SYMBOL(amd_iommu_deactivate_guest_mode);
4187 
4188 static int amd_ir_set_vcpu_affinity(struct irq_data *data, void *info)
4189 {
4190 	int ret;
4191 	struct amd_iommu_pi_data *pi_data = info;
4192 	struct amd_ir_data *ir_data = data->chip_data;
4193 	struct irq_2_irte *irte_info = &ir_data->irq_2_irte;
4194 	struct iommu_dev_data *dev_data;
4195 
4196 	if (WARN_ON_ONCE(!AMD_IOMMU_GUEST_IR_VAPIC(amd_iommu_guest_ir)))
4197 		return -EINVAL;
4198 
4199 	if (ir_data->iommu == NULL)
4200 		return -EINVAL;
4201 
4202 	dev_data = search_dev_data(ir_data->iommu, irte_info->devid);
4203 
4204 	/* Note:
4205 	 * This device has never been set up for guest mode.
4206 	 * we should not modify the IRTE
4207 	 */
4208 	if (!dev_data || !dev_data->use_vapic)
4209 		return -EINVAL;
4210 
4211 	ir_data->cfg = irqd_cfg(data);
4212 
4213 	if (pi_data) {
4214 		pi_data->ir_data = ir_data;
4215 
4216 		ir_data->ga_root_ptr = (pi_data->vapic_addr >> 12);
4217 		ir_data->ga_vector = pi_data->vector;
4218 		ir_data->ga_tag = pi_data->ga_tag;
4219 		if (pi_data->is_guest_mode)
4220 			ret = amd_iommu_activate_guest_mode(ir_data, pi_data->cpu,
4221 							    pi_data->ga_log_intr);
4222 		else
4223 			ret = amd_iommu_deactivate_guest_mode(ir_data);
4224 	} else {
4225 		ret = amd_iommu_deactivate_guest_mode(ir_data);
4226 	}
4227 
4228 	return ret;
4229 }
4230 
4231 
4232 static void amd_ir_update_irte(struct irq_data *irqd, struct amd_iommu *iommu,
4233 			       struct amd_ir_data *ir_data,
4234 			       struct irq_2_irte *irte_info,
4235 			       struct irq_cfg *cfg)
4236 {
4237 
4238 	/*
4239 	 * Atomically updates the IRTE with the new destination, vector
4240 	 * and flushes the interrupt entry cache.
4241 	 */
4242 	iommu->irte_ops->set_affinity(iommu, ir_data->entry, irte_info->devid,
4243 				      irte_info->index, cfg->vector,
4244 				      cfg->dest_apicid);
4245 }
4246 
4247 static int amd_ir_set_affinity(struct irq_data *data,
4248 			       const struct cpumask *mask, bool force)
4249 {
4250 	struct amd_ir_data *ir_data = data->chip_data;
4251 	struct irq_2_irte *irte_info = &ir_data->irq_2_irte;
4252 	struct irq_cfg *cfg = irqd_cfg(data);
4253 	struct irq_data *parent = data->parent_data;
4254 	struct amd_iommu *iommu = ir_data->iommu;
4255 	int ret;
4256 
4257 	if (!iommu)
4258 		return -ENODEV;
4259 
4260 	ret = parent->chip->irq_set_affinity(parent, mask, force);
4261 	if (ret < 0 || ret == IRQ_SET_MASK_OK_DONE)
4262 		return ret;
4263 
4264 	amd_ir_update_irte(data, iommu, ir_data, irte_info, cfg);
4265 	/*
4266 	 * After this point, all the interrupts will start arriving
4267 	 * at the new destination. So, time to cleanup the previous
4268 	 * vector allocation.
4269 	 */
4270 	vector_schedule_cleanup(cfg);
4271 
4272 	return IRQ_SET_MASK_OK_DONE;
4273 }
4274 
4275 static void ir_compose_msi_msg(struct irq_data *irq_data, struct msi_msg *msg)
4276 {
4277 	struct amd_ir_data *ir_data = irq_data->chip_data;
4278 
4279 	*msg = ir_data->msi_entry;
4280 }
4281 
4282 static struct irq_chip amd_ir_chip = {
4283 	.name			= "AMD-IR",
4284 	.irq_ack		= apic_ack_irq,
4285 	.irq_set_affinity	= amd_ir_set_affinity,
4286 	.irq_set_vcpu_affinity	= amd_ir_set_vcpu_affinity,
4287 	.irq_compose_msi_msg	= ir_compose_msi_msg,
4288 };
4289 
4290 static const struct msi_parent_ops amdvi_msi_parent_ops = {
4291 	.supported_flags	= X86_VECTOR_MSI_FLAGS_SUPPORTED | MSI_FLAG_MULTI_PCI_MSI,
4292 	.bus_select_token	= DOMAIN_BUS_AMDVI,
4293 	.bus_select_mask	= MATCH_PCI_MSI,
4294 	.prefix			= "IR-",
4295 	.init_dev_msi_info	= msi_parent_init_dev_msi_info,
4296 };
4297 
4298 int amd_iommu_create_irq_domain(struct amd_iommu *iommu)
4299 {
4300 	struct irq_domain_info info = {
4301 		.fwnode		= irq_domain_alloc_named_id_fwnode("AMD-IR", iommu->index),
4302 		.ops		= &amd_ir_domain_ops,
4303 		.domain_flags	= IRQ_DOMAIN_FLAG_ISOLATED_MSI,
4304 		.host_data	= iommu,
4305 		.parent		= arch_get_ir_parent_domain(),
4306 	};
4307 
4308 	if (!info.fwnode)
4309 		return -ENOMEM;
4310 
4311 	iommu->ir_domain = msi_create_parent_irq_domain(&info, &amdvi_msi_parent_ops);
4312 	if (!iommu->ir_domain) {
4313 		irq_domain_free_fwnode(info.fwnode);
4314 		return -ENOMEM;
4315 	}
4316 	return 0;
4317 }
4318 #endif
4319 
4320 MODULE_IMPORT_NS("GENERIC_PT_IOMMU");
4321