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