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