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