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