xref: /linux/drivers/iommu/intel/svm.c (revision 1bc191051dca28fa6d20fd1dc34a1903e7d4fb62)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright © 2015 Intel Corporation.
4  *
5  * Authors: David Woodhouse <dwmw2@infradead.org>
6  */
7 
8 #include <linux/intel-iommu.h>
9 #include <linux/mmu_notifier.h>
10 #include <linux/sched.h>
11 #include <linux/sched/mm.h>
12 #include <linux/slab.h>
13 #include <linux/intel-svm.h>
14 #include <linux/rculist.h>
15 #include <linux/pci.h>
16 #include <linux/pci-ats.h>
17 #include <linux/dmar.h>
18 #include <linux/interrupt.h>
19 #include <linux/mm_types.h>
20 #include <linux/xarray.h>
21 #include <linux/ioasid.h>
22 #include <asm/page.h>
23 #include <asm/fpu/api.h>
24 #include <trace/events/intel_iommu.h>
25 
26 #include "pasid.h"
27 #include "perf.h"
28 #include "../iommu-sva-lib.h"
29 
30 static irqreturn_t prq_event_thread(int irq, void *d);
31 static void intel_svm_drain_prq(struct device *dev, u32 pasid);
32 #define to_intel_svm_dev(handle) container_of(handle, struct intel_svm_dev, sva)
33 
34 static DEFINE_XARRAY_ALLOC(pasid_private_array);
35 static int pasid_private_add(ioasid_t pasid, void *priv)
36 {
37 	return xa_alloc(&pasid_private_array, &pasid, priv,
38 			XA_LIMIT(pasid, pasid), GFP_ATOMIC);
39 }
40 
41 static void pasid_private_remove(ioasid_t pasid)
42 {
43 	xa_erase(&pasid_private_array, pasid);
44 }
45 
46 static void *pasid_private_find(ioasid_t pasid)
47 {
48 	return xa_load(&pasid_private_array, pasid);
49 }
50 
51 static struct intel_svm_dev *
52 svm_lookup_device_by_sid(struct intel_svm *svm, u16 sid)
53 {
54 	struct intel_svm_dev *sdev = NULL, *t;
55 
56 	rcu_read_lock();
57 	list_for_each_entry_rcu(t, &svm->devs, list) {
58 		if (t->sid == sid) {
59 			sdev = t;
60 			break;
61 		}
62 	}
63 	rcu_read_unlock();
64 
65 	return sdev;
66 }
67 
68 static struct intel_svm_dev *
69 svm_lookup_device_by_dev(struct intel_svm *svm, struct device *dev)
70 {
71 	struct intel_svm_dev *sdev = NULL, *t;
72 
73 	rcu_read_lock();
74 	list_for_each_entry_rcu(t, &svm->devs, list) {
75 		if (t->dev == dev) {
76 			sdev = t;
77 			break;
78 		}
79 	}
80 	rcu_read_unlock();
81 
82 	return sdev;
83 }
84 
85 int intel_svm_enable_prq(struct intel_iommu *iommu)
86 {
87 	struct iopf_queue *iopfq;
88 	struct page *pages;
89 	int irq, ret;
90 
91 	pages = alloc_pages(GFP_KERNEL | __GFP_ZERO, PRQ_ORDER);
92 	if (!pages) {
93 		pr_warn("IOMMU: %s: Failed to allocate page request queue\n",
94 			iommu->name);
95 		return -ENOMEM;
96 	}
97 	iommu->prq = page_address(pages);
98 
99 	irq = dmar_alloc_hwirq(DMAR_UNITS_SUPPORTED + iommu->seq_id, iommu->node, iommu);
100 	if (irq <= 0) {
101 		pr_err("IOMMU: %s: Failed to create IRQ vector for page request queue\n",
102 		       iommu->name);
103 		ret = -EINVAL;
104 		goto free_prq;
105 	}
106 	iommu->pr_irq = irq;
107 
108 	snprintf(iommu->iopfq_name, sizeof(iommu->iopfq_name),
109 		 "dmar%d-iopfq", iommu->seq_id);
110 	iopfq = iopf_queue_alloc(iommu->iopfq_name);
111 	if (!iopfq) {
112 		pr_err("IOMMU: %s: Failed to allocate iopf queue\n", iommu->name);
113 		ret = -ENOMEM;
114 		goto free_hwirq;
115 	}
116 	iommu->iopf_queue = iopfq;
117 
118 	snprintf(iommu->prq_name, sizeof(iommu->prq_name), "dmar%d-prq", iommu->seq_id);
119 
120 	ret = request_threaded_irq(irq, NULL, prq_event_thread, IRQF_ONESHOT,
121 				   iommu->prq_name, iommu);
122 	if (ret) {
123 		pr_err("IOMMU: %s: Failed to request IRQ for page request queue\n",
124 		       iommu->name);
125 		goto free_iopfq;
126 	}
127 	dmar_writeq(iommu->reg + DMAR_PQH_REG, 0ULL);
128 	dmar_writeq(iommu->reg + DMAR_PQT_REG, 0ULL);
129 	dmar_writeq(iommu->reg + DMAR_PQA_REG, virt_to_phys(iommu->prq) | PRQ_ORDER);
130 
131 	init_completion(&iommu->prq_complete);
132 
133 	return 0;
134 
135 free_iopfq:
136 	iopf_queue_free(iommu->iopf_queue);
137 	iommu->iopf_queue = NULL;
138 free_hwirq:
139 	dmar_free_hwirq(irq);
140 	iommu->pr_irq = 0;
141 free_prq:
142 	free_pages((unsigned long)iommu->prq, PRQ_ORDER);
143 	iommu->prq = NULL;
144 
145 	return ret;
146 }
147 
148 int intel_svm_finish_prq(struct intel_iommu *iommu)
149 {
150 	dmar_writeq(iommu->reg + DMAR_PQH_REG, 0ULL);
151 	dmar_writeq(iommu->reg + DMAR_PQT_REG, 0ULL);
152 	dmar_writeq(iommu->reg + DMAR_PQA_REG, 0ULL);
153 
154 	if (iommu->pr_irq) {
155 		free_irq(iommu->pr_irq, iommu);
156 		dmar_free_hwirq(iommu->pr_irq);
157 		iommu->pr_irq = 0;
158 	}
159 
160 	if (iommu->iopf_queue) {
161 		iopf_queue_free(iommu->iopf_queue);
162 		iommu->iopf_queue = NULL;
163 	}
164 
165 	free_pages((unsigned long)iommu->prq, PRQ_ORDER);
166 	iommu->prq = NULL;
167 
168 	return 0;
169 }
170 
171 static inline bool intel_svm_capable(struct intel_iommu *iommu)
172 {
173 	return iommu->flags & VTD_FLAG_SVM_CAPABLE;
174 }
175 
176 void intel_svm_check(struct intel_iommu *iommu)
177 {
178 	if (!pasid_supported(iommu))
179 		return;
180 
181 	if (cpu_feature_enabled(X86_FEATURE_GBPAGES) &&
182 	    !cap_fl1gp_support(iommu->cap)) {
183 		pr_err("%s SVM disabled, incompatible 1GB page capability\n",
184 		       iommu->name);
185 		return;
186 	}
187 
188 	if (cpu_feature_enabled(X86_FEATURE_LA57) &&
189 	    !cap_5lp_support(iommu->cap)) {
190 		pr_err("%s SVM disabled, incompatible paging mode\n",
191 		       iommu->name);
192 		return;
193 	}
194 
195 	iommu->flags |= VTD_FLAG_SVM_CAPABLE;
196 }
197 
198 static void __flush_svm_range_dev(struct intel_svm *svm,
199 				  struct intel_svm_dev *sdev,
200 				  unsigned long address,
201 				  unsigned long pages, int ih)
202 {
203 	struct device_domain_info *info = get_domain_info(sdev->dev);
204 
205 	if (WARN_ON(!pages))
206 		return;
207 
208 	qi_flush_piotlb(sdev->iommu, sdev->did, svm->pasid, address, pages, ih);
209 	if (info->ats_enabled)
210 		qi_flush_dev_iotlb_pasid(sdev->iommu, sdev->sid, info->pfsid,
211 					 svm->pasid, sdev->qdep, address,
212 					 order_base_2(pages));
213 }
214 
215 static void intel_flush_svm_range_dev(struct intel_svm *svm,
216 				      struct intel_svm_dev *sdev,
217 				      unsigned long address,
218 				      unsigned long pages, int ih)
219 {
220 	unsigned long shift = ilog2(__roundup_pow_of_two(pages));
221 	unsigned long align = (1ULL << (VTD_PAGE_SHIFT + shift));
222 	unsigned long start = ALIGN_DOWN(address, align);
223 	unsigned long end = ALIGN(address + (pages << VTD_PAGE_SHIFT), align);
224 
225 	while (start < end) {
226 		__flush_svm_range_dev(svm, sdev, start, align >> VTD_PAGE_SHIFT, ih);
227 		start += align;
228 	}
229 }
230 
231 static void intel_flush_svm_range(struct intel_svm *svm, unsigned long address,
232 				unsigned long pages, int ih)
233 {
234 	struct intel_svm_dev *sdev;
235 
236 	rcu_read_lock();
237 	list_for_each_entry_rcu(sdev, &svm->devs, list)
238 		intel_flush_svm_range_dev(svm, sdev, address, pages, ih);
239 	rcu_read_unlock();
240 }
241 
242 /* Pages have been freed at this point */
243 static void intel_invalidate_range(struct mmu_notifier *mn,
244 				   struct mm_struct *mm,
245 				   unsigned long start, unsigned long end)
246 {
247 	struct intel_svm *svm = container_of(mn, struct intel_svm, notifier);
248 
249 	intel_flush_svm_range(svm, start,
250 			      (end - start + PAGE_SIZE - 1) >> VTD_PAGE_SHIFT, 0);
251 }
252 
253 static void intel_mm_release(struct mmu_notifier *mn, struct mm_struct *mm)
254 {
255 	struct intel_svm *svm = container_of(mn, struct intel_svm, notifier);
256 	struct intel_svm_dev *sdev;
257 
258 	/* This might end up being called from exit_mmap(), *before* the page
259 	 * tables are cleared. And __mmu_notifier_release() will delete us from
260 	 * the list of notifiers so that our invalidate_range() callback doesn't
261 	 * get called when the page tables are cleared. So we need to protect
262 	 * against hardware accessing those page tables.
263 	 *
264 	 * We do it by clearing the entry in the PASID table and then flushing
265 	 * the IOTLB and the PASID table caches. This might upset hardware;
266 	 * perhaps we'll want to point the PASID to a dummy PGD (like the zero
267 	 * page) so that we end up taking a fault that the hardware really
268 	 * *has* to handle gracefully without affecting other processes.
269 	 */
270 	rcu_read_lock();
271 	list_for_each_entry_rcu(sdev, &svm->devs, list)
272 		intel_pasid_tear_down_entry(sdev->iommu, sdev->dev,
273 					    svm->pasid, true);
274 	rcu_read_unlock();
275 
276 }
277 
278 static const struct mmu_notifier_ops intel_mmuops = {
279 	.release = intel_mm_release,
280 	.invalidate_range = intel_invalidate_range,
281 };
282 
283 static DEFINE_MUTEX(pasid_mutex);
284 
285 static int pasid_to_svm_sdev(struct device *dev, unsigned int pasid,
286 			     struct intel_svm **rsvm,
287 			     struct intel_svm_dev **rsdev)
288 {
289 	struct intel_svm_dev *sdev = NULL;
290 	struct intel_svm *svm;
291 
292 	/* The caller should hold the pasid_mutex lock */
293 	if (WARN_ON(!mutex_is_locked(&pasid_mutex)))
294 		return -EINVAL;
295 
296 	if (pasid == INVALID_IOASID || pasid >= PASID_MAX)
297 		return -EINVAL;
298 
299 	svm = pasid_private_find(pasid);
300 	if (IS_ERR(svm))
301 		return PTR_ERR(svm);
302 
303 	if (!svm)
304 		goto out;
305 
306 	/*
307 	 * If we found svm for the PASID, there must be at least one device
308 	 * bond.
309 	 */
310 	if (WARN_ON(list_empty(&svm->devs)))
311 		return -EINVAL;
312 	sdev = svm_lookup_device_by_dev(svm, dev);
313 
314 out:
315 	*rsvm = svm;
316 	*rsdev = sdev;
317 
318 	return 0;
319 }
320 
321 int intel_svm_bind_gpasid(struct iommu_domain *domain, struct device *dev,
322 			  struct iommu_gpasid_bind_data *data)
323 {
324 	struct intel_iommu *iommu = device_to_iommu(dev, NULL, NULL);
325 	struct intel_svm_dev *sdev = NULL;
326 	struct dmar_domain *dmar_domain;
327 	struct device_domain_info *info;
328 	struct intel_svm *svm = NULL;
329 	unsigned long iflags;
330 	int ret = 0;
331 
332 	if (WARN_ON(!iommu) || !data)
333 		return -EINVAL;
334 
335 	if (data->format != IOMMU_PASID_FORMAT_INTEL_VTD)
336 		return -EINVAL;
337 
338 	/* IOMMU core ensures argsz is more than the start of the union */
339 	if (data->argsz < offsetofend(struct iommu_gpasid_bind_data, vendor.vtd))
340 		return -EINVAL;
341 
342 	/* Make sure no undefined flags are used in vendor data */
343 	if (data->vendor.vtd.flags & ~(IOMMU_SVA_VTD_GPASID_LAST - 1))
344 		return -EINVAL;
345 
346 	if (!dev_is_pci(dev))
347 		return -ENOTSUPP;
348 
349 	/* VT-d supports devices with full 20 bit PASIDs only */
350 	if (pci_max_pasids(to_pci_dev(dev)) != PASID_MAX)
351 		return -EINVAL;
352 
353 	/*
354 	 * We only check host PASID range, we have no knowledge to check
355 	 * guest PASID range.
356 	 */
357 	if (data->hpasid <= 0 || data->hpasid >= PASID_MAX)
358 		return -EINVAL;
359 
360 	info = get_domain_info(dev);
361 	if (!info)
362 		return -EINVAL;
363 
364 	dmar_domain = to_dmar_domain(domain);
365 
366 	mutex_lock(&pasid_mutex);
367 	ret = pasid_to_svm_sdev(dev, data->hpasid, &svm, &sdev);
368 	if (ret)
369 		goto out;
370 
371 	if (sdev) {
372 		/*
373 		 * Do not allow multiple bindings of the same device-PASID since
374 		 * there is only one SL page tables per PASID. We may revisit
375 		 * once sharing PGD across domains are supported.
376 		 */
377 		dev_warn_ratelimited(dev, "Already bound with PASID %u\n",
378 				     svm->pasid);
379 		ret = -EBUSY;
380 		goto out;
381 	}
382 
383 	if (!svm) {
384 		/* We come here when PASID has never been bond to a device. */
385 		svm = kzalloc(sizeof(*svm), GFP_KERNEL);
386 		if (!svm) {
387 			ret = -ENOMEM;
388 			goto out;
389 		}
390 		/* REVISIT: upper layer/VFIO can track host process that bind
391 		 * the PASID. ioasid_set = mm might be sufficient for vfio to
392 		 * check pasid VMM ownership. We can drop the following line
393 		 * once VFIO and IOASID set check is in place.
394 		 */
395 		svm->mm = get_task_mm(current);
396 		svm->pasid = data->hpasid;
397 		if (data->flags & IOMMU_SVA_GPASID_VAL) {
398 			svm->gpasid = data->gpasid;
399 			svm->flags |= SVM_FLAG_GUEST_PASID;
400 		}
401 		pasid_private_add(data->hpasid, svm);
402 		INIT_LIST_HEAD_RCU(&svm->devs);
403 		mmput(svm->mm);
404 	}
405 	sdev = kzalloc(sizeof(*sdev), GFP_KERNEL);
406 	if (!sdev) {
407 		ret = -ENOMEM;
408 		goto out;
409 	}
410 	sdev->dev = dev;
411 	sdev->sid = PCI_DEVID(info->bus, info->devfn);
412 	sdev->iommu = iommu;
413 
414 	/* Only count users if device has aux domains */
415 	if (iommu_dev_feature_enabled(dev, IOMMU_DEV_FEAT_AUX))
416 		sdev->users = 1;
417 
418 	/* Set up device context entry for PASID if not enabled already */
419 	ret = intel_iommu_enable_pasid(iommu, sdev->dev);
420 	if (ret) {
421 		dev_err_ratelimited(dev, "Failed to enable PASID capability\n");
422 		kfree(sdev);
423 		goto out;
424 	}
425 
426 	/*
427 	 * PASID table is per device for better security. Therefore, for
428 	 * each bind of a new device even with an existing PASID, we need to
429 	 * call the nested mode setup function here.
430 	 */
431 	spin_lock_irqsave(&iommu->lock, iflags);
432 	ret = intel_pasid_setup_nested(iommu, dev,
433 				       (pgd_t *)(uintptr_t)data->gpgd,
434 				       data->hpasid, &data->vendor.vtd, dmar_domain,
435 				       data->addr_width);
436 	spin_unlock_irqrestore(&iommu->lock, iflags);
437 	if (ret) {
438 		dev_err_ratelimited(dev, "Failed to set up PASID %llu in nested mode, Err %d\n",
439 				    data->hpasid, ret);
440 		/*
441 		 * PASID entry should be in cleared state if nested mode
442 		 * set up failed. So we only need to clear IOASID tracking
443 		 * data such that free call will succeed.
444 		 */
445 		kfree(sdev);
446 		goto out;
447 	}
448 
449 	svm->flags |= SVM_FLAG_GUEST_MODE;
450 
451 	init_rcu_head(&sdev->rcu);
452 	list_add_rcu(&sdev->list, &svm->devs);
453  out:
454 	if (!IS_ERR_OR_NULL(svm) && list_empty(&svm->devs)) {
455 		pasid_private_remove(data->hpasid);
456 		kfree(svm);
457 	}
458 
459 	mutex_unlock(&pasid_mutex);
460 	return ret;
461 }
462 
463 int intel_svm_unbind_gpasid(struct device *dev, u32 pasid)
464 {
465 	struct intel_iommu *iommu = device_to_iommu(dev, NULL, NULL);
466 	struct intel_svm_dev *sdev;
467 	struct intel_svm *svm;
468 	int ret;
469 
470 	if (WARN_ON(!iommu))
471 		return -EINVAL;
472 
473 	mutex_lock(&pasid_mutex);
474 	ret = pasid_to_svm_sdev(dev, pasid, &svm, &sdev);
475 	if (ret)
476 		goto out;
477 
478 	if (sdev) {
479 		if (iommu_dev_feature_enabled(dev, IOMMU_DEV_FEAT_AUX))
480 			sdev->users--;
481 		if (!sdev->users) {
482 			list_del_rcu(&sdev->list);
483 			intel_pasid_tear_down_entry(iommu, dev,
484 						    svm->pasid, false);
485 			intel_svm_drain_prq(dev, svm->pasid);
486 			kfree_rcu(sdev, rcu);
487 
488 			if (list_empty(&svm->devs)) {
489 				/*
490 				 * We do not free the IOASID here in that
491 				 * IOMMU driver did not allocate it.
492 				 * Unlike native SVM, IOASID for guest use was
493 				 * allocated prior to the bind call.
494 				 * In any case, if the free call comes before
495 				 * the unbind, IOMMU driver will get notified
496 				 * and perform cleanup.
497 				 */
498 				pasid_private_remove(pasid);
499 				kfree(svm);
500 			}
501 		}
502 	}
503 out:
504 	mutex_unlock(&pasid_mutex);
505 	return ret;
506 }
507 
508 static int intel_svm_alloc_pasid(struct device *dev, struct mm_struct *mm,
509 				 unsigned int flags)
510 {
511 	ioasid_t max_pasid = dev_is_pci(dev) ?
512 			pci_max_pasids(to_pci_dev(dev)) : intel_pasid_max_id;
513 
514 	return iommu_sva_alloc_pasid(mm, PASID_MIN, max_pasid - 1);
515 }
516 
517 static struct iommu_sva *intel_svm_bind_mm(struct intel_iommu *iommu,
518 					   struct device *dev,
519 					   struct mm_struct *mm,
520 					   unsigned int flags)
521 {
522 	struct device_domain_info *info = get_domain_info(dev);
523 	unsigned long iflags, sflags;
524 	struct intel_svm_dev *sdev;
525 	struct intel_svm *svm;
526 	int ret = 0;
527 
528 	svm = pasid_private_find(mm->pasid);
529 	if (!svm) {
530 		svm = kzalloc(sizeof(*svm), GFP_KERNEL);
531 		if (!svm)
532 			return ERR_PTR(-ENOMEM);
533 
534 		svm->pasid = mm->pasid;
535 		svm->mm = mm;
536 		svm->flags = flags;
537 		INIT_LIST_HEAD_RCU(&svm->devs);
538 
539 		if (!(flags & SVM_FLAG_SUPERVISOR_MODE)) {
540 			svm->notifier.ops = &intel_mmuops;
541 			ret = mmu_notifier_register(&svm->notifier, mm);
542 			if (ret) {
543 				kfree(svm);
544 				return ERR_PTR(ret);
545 			}
546 		}
547 
548 		ret = pasid_private_add(svm->pasid, svm);
549 		if (ret) {
550 			if (svm->notifier.ops)
551 				mmu_notifier_unregister(&svm->notifier, mm);
552 			kfree(svm);
553 			return ERR_PTR(ret);
554 		}
555 	}
556 
557 	/* Find the matching device in svm list */
558 	sdev = svm_lookup_device_by_dev(svm, dev);
559 	if (sdev) {
560 		sdev->users++;
561 		goto success;
562 	}
563 
564 	sdev = kzalloc(sizeof(*sdev), GFP_KERNEL);
565 	if (!sdev) {
566 		ret = -ENOMEM;
567 		goto free_svm;
568 	}
569 
570 	sdev->dev = dev;
571 	sdev->iommu = iommu;
572 	sdev->did = FLPT_DEFAULT_DID;
573 	sdev->sid = PCI_DEVID(info->bus, info->devfn);
574 	sdev->users = 1;
575 	sdev->pasid = svm->pasid;
576 	sdev->sva.dev = dev;
577 	init_rcu_head(&sdev->rcu);
578 	if (info->ats_enabled) {
579 		sdev->dev_iotlb = 1;
580 		sdev->qdep = info->ats_qdep;
581 		if (sdev->qdep >= QI_DEV_EIOTLB_MAX_INVS)
582 			sdev->qdep = 0;
583 	}
584 
585 	/* Setup the pasid table: */
586 	sflags = (flags & SVM_FLAG_SUPERVISOR_MODE) ?
587 			PASID_FLAG_SUPERVISOR_MODE : 0;
588 	sflags |= cpu_feature_enabled(X86_FEATURE_LA57) ? PASID_FLAG_FL5LP : 0;
589 	spin_lock_irqsave(&iommu->lock, iflags);
590 	ret = intel_pasid_setup_first_level(iommu, dev, mm->pgd, mm->pasid,
591 					    FLPT_DEFAULT_DID, sflags);
592 	spin_unlock_irqrestore(&iommu->lock, iflags);
593 
594 	if (ret)
595 		goto free_sdev;
596 
597 	list_add_rcu(&sdev->list, &svm->devs);
598 success:
599 	return &sdev->sva;
600 
601 free_sdev:
602 	kfree(sdev);
603 free_svm:
604 	if (list_empty(&svm->devs)) {
605 		if (svm->notifier.ops)
606 			mmu_notifier_unregister(&svm->notifier, mm);
607 		pasid_private_remove(mm->pasid);
608 		kfree(svm);
609 	}
610 
611 	return ERR_PTR(ret);
612 }
613 
614 /* Caller must hold pasid_mutex */
615 static int intel_svm_unbind_mm(struct device *dev, u32 pasid)
616 {
617 	struct intel_svm_dev *sdev;
618 	struct intel_iommu *iommu;
619 	struct intel_svm *svm;
620 	struct mm_struct *mm;
621 	int ret = -EINVAL;
622 
623 	iommu = device_to_iommu(dev, NULL, NULL);
624 	if (!iommu)
625 		goto out;
626 
627 	ret = pasid_to_svm_sdev(dev, pasid, &svm, &sdev);
628 	if (ret)
629 		goto out;
630 	mm = svm->mm;
631 
632 	if (sdev) {
633 		sdev->users--;
634 		if (!sdev->users) {
635 			list_del_rcu(&sdev->list);
636 			/* Flush the PASID cache and IOTLB for this device.
637 			 * Note that we do depend on the hardware *not* using
638 			 * the PASID any more. Just as we depend on other
639 			 * devices never using PASIDs that they have no right
640 			 * to use. We have a *shared* PASID table, because it's
641 			 * large and has to be physically contiguous. So it's
642 			 * hard to be as defensive as we might like. */
643 			intel_pasid_tear_down_entry(iommu, dev,
644 						    svm->pasid, false);
645 			intel_svm_drain_prq(dev, svm->pasid);
646 			kfree_rcu(sdev, rcu);
647 
648 			if (list_empty(&svm->devs)) {
649 				if (svm->notifier.ops)
650 					mmu_notifier_unregister(&svm->notifier, mm);
651 				pasid_private_remove(svm->pasid);
652 				/* We mandate that no page faults may be outstanding
653 				 * for the PASID when intel_svm_unbind_mm() is called.
654 				 * If that is not obeyed, subtle errors will happen.
655 				 * Let's make them less subtle... */
656 				memset(svm, 0x6b, sizeof(*svm));
657 				kfree(svm);
658 			}
659 		}
660 	}
661 out:
662 	return ret;
663 }
664 
665 /* Page request queue descriptor */
666 struct page_req_dsc {
667 	union {
668 		struct {
669 			u64 type:8;
670 			u64 pasid_present:1;
671 			u64 priv_data_present:1;
672 			u64 rsvd:6;
673 			u64 rid:16;
674 			u64 pasid:20;
675 			u64 exe_req:1;
676 			u64 pm_req:1;
677 			u64 rsvd2:10;
678 		};
679 		u64 qw_0;
680 	};
681 	union {
682 		struct {
683 			u64 rd_req:1;
684 			u64 wr_req:1;
685 			u64 lpig:1;
686 			u64 prg_index:9;
687 			u64 addr:52;
688 		};
689 		u64 qw_1;
690 	};
691 	u64 priv_data[2];
692 };
693 
694 static bool is_canonical_address(u64 addr)
695 {
696 	int shift = 64 - (__VIRTUAL_MASK_SHIFT + 1);
697 	long saddr = (long) addr;
698 
699 	return (((saddr << shift) >> shift) == saddr);
700 }
701 
702 /**
703  * intel_svm_drain_prq - Drain page requests and responses for a pasid
704  * @dev: target device
705  * @pasid: pasid for draining
706  *
707  * Drain all pending page requests and responses related to @pasid in both
708  * software and hardware. This is supposed to be called after the device
709  * driver has stopped DMA, the pasid entry has been cleared, and both IOTLB
710  * and DevTLB have been invalidated.
711  *
712  * It waits until all pending page requests for @pasid in the page fault
713  * queue are completed by the prq handling thread. Then follow the steps
714  * described in VT-d spec CH7.10 to drain all page requests and page
715  * responses pending in the hardware.
716  */
717 static void intel_svm_drain_prq(struct device *dev, u32 pasid)
718 {
719 	struct device_domain_info *info;
720 	struct dmar_domain *domain;
721 	struct intel_iommu *iommu;
722 	struct qi_desc desc[3];
723 	struct pci_dev *pdev;
724 	int head, tail;
725 	u16 sid, did;
726 	int qdep;
727 
728 	info = get_domain_info(dev);
729 	if (WARN_ON(!info || !dev_is_pci(dev)))
730 		return;
731 
732 	if (!info->pri_enabled)
733 		return;
734 
735 	iommu = info->iommu;
736 	domain = info->domain;
737 	pdev = to_pci_dev(dev);
738 	sid = PCI_DEVID(info->bus, info->devfn);
739 	did = domain->iommu_did[iommu->seq_id];
740 	qdep = pci_ats_queue_depth(pdev);
741 
742 	/*
743 	 * Check and wait until all pending page requests in the queue are
744 	 * handled by the prq handling thread.
745 	 */
746 prq_retry:
747 	reinit_completion(&iommu->prq_complete);
748 	tail = dmar_readq(iommu->reg + DMAR_PQT_REG) & PRQ_RING_MASK;
749 	head = dmar_readq(iommu->reg + DMAR_PQH_REG) & PRQ_RING_MASK;
750 	while (head != tail) {
751 		struct page_req_dsc *req;
752 
753 		req = &iommu->prq[head / sizeof(*req)];
754 		if (!req->pasid_present || req->pasid != pasid) {
755 			head = (head + sizeof(*req)) & PRQ_RING_MASK;
756 			continue;
757 		}
758 
759 		wait_for_completion(&iommu->prq_complete);
760 		goto prq_retry;
761 	}
762 
763 	/*
764 	 * A work in IO page fault workqueue may try to lock pasid_mutex now.
765 	 * Holding pasid_mutex while waiting in iopf_queue_flush_dev() for
766 	 * all works in the workqueue to finish may cause deadlock.
767 	 *
768 	 * It's unnecessary to hold pasid_mutex in iopf_queue_flush_dev().
769 	 * Unlock it to allow the works to be handled while waiting for
770 	 * them to finish.
771 	 */
772 	lockdep_assert_held(&pasid_mutex);
773 	mutex_unlock(&pasid_mutex);
774 	iopf_queue_flush_dev(dev);
775 	mutex_lock(&pasid_mutex);
776 
777 	/*
778 	 * Perform steps described in VT-d spec CH7.10 to drain page
779 	 * requests and responses in hardware.
780 	 */
781 	memset(desc, 0, sizeof(desc));
782 	desc[0].qw0 = QI_IWD_STATUS_DATA(QI_DONE) |
783 			QI_IWD_FENCE |
784 			QI_IWD_TYPE;
785 	desc[1].qw0 = QI_EIOTLB_PASID(pasid) |
786 			QI_EIOTLB_DID(did) |
787 			QI_EIOTLB_GRAN(QI_GRAN_NONG_PASID) |
788 			QI_EIOTLB_TYPE;
789 	desc[2].qw0 = QI_DEV_EIOTLB_PASID(pasid) |
790 			QI_DEV_EIOTLB_SID(sid) |
791 			QI_DEV_EIOTLB_QDEP(qdep) |
792 			QI_DEIOTLB_TYPE |
793 			QI_DEV_IOTLB_PFSID(info->pfsid);
794 qi_retry:
795 	reinit_completion(&iommu->prq_complete);
796 	qi_submit_sync(iommu, desc, 3, QI_OPT_WAIT_DRAIN);
797 	if (readl(iommu->reg + DMAR_PRS_REG) & DMA_PRS_PRO) {
798 		wait_for_completion(&iommu->prq_complete);
799 		goto qi_retry;
800 	}
801 }
802 
803 static int prq_to_iommu_prot(struct page_req_dsc *req)
804 {
805 	int prot = 0;
806 
807 	if (req->rd_req)
808 		prot |= IOMMU_FAULT_PERM_READ;
809 	if (req->wr_req)
810 		prot |= IOMMU_FAULT_PERM_WRITE;
811 	if (req->exe_req)
812 		prot |= IOMMU_FAULT_PERM_EXEC;
813 	if (req->pm_req)
814 		prot |= IOMMU_FAULT_PERM_PRIV;
815 
816 	return prot;
817 }
818 
819 static int intel_svm_prq_report(struct intel_iommu *iommu, struct device *dev,
820 				struct page_req_dsc *desc)
821 {
822 	struct iommu_fault_event event;
823 
824 	if (!dev || !dev_is_pci(dev))
825 		return -ENODEV;
826 
827 	/* Fill in event data for device specific processing */
828 	memset(&event, 0, sizeof(struct iommu_fault_event));
829 	event.fault.type = IOMMU_FAULT_PAGE_REQ;
830 	event.fault.prm.addr = (u64)desc->addr << VTD_PAGE_SHIFT;
831 	event.fault.prm.pasid = desc->pasid;
832 	event.fault.prm.grpid = desc->prg_index;
833 	event.fault.prm.perm = prq_to_iommu_prot(desc);
834 
835 	if (desc->lpig)
836 		event.fault.prm.flags |= IOMMU_FAULT_PAGE_REQUEST_LAST_PAGE;
837 	if (desc->pasid_present) {
838 		event.fault.prm.flags |= IOMMU_FAULT_PAGE_REQUEST_PASID_VALID;
839 		event.fault.prm.flags |= IOMMU_FAULT_PAGE_RESPONSE_NEEDS_PASID;
840 	}
841 	if (desc->priv_data_present) {
842 		/*
843 		 * Set last page in group bit if private data is present,
844 		 * page response is required as it does for LPIG.
845 		 * iommu_report_device_fault() doesn't understand this vendor
846 		 * specific requirement thus we set last_page as a workaround.
847 		 */
848 		event.fault.prm.flags |= IOMMU_FAULT_PAGE_REQUEST_LAST_PAGE;
849 		event.fault.prm.flags |= IOMMU_FAULT_PAGE_REQUEST_PRIV_DATA;
850 		event.fault.prm.private_data[0] = desc->priv_data[0];
851 		event.fault.prm.private_data[1] = desc->priv_data[1];
852 	} else if (dmar_latency_enabled(iommu, DMAR_LATENCY_PRQ)) {
853 		/*
854 		 * If the private data fields are not used by hardware, use it
855 		 * to monitor the prq handle latency.
856 		 */
857 		event.fault.prm.private_data[0] = ktime_to_ns(ktime_get());
858 	}
859 
860 	return iommu_report_device_fault(dev, &event);
861 }
862 
863 static void handle_bad_prq_event(struct intel_iommu *iommu,
864 				 struct page_req_dsc *req, int result)
865 {
866 	struct qi_desc desc;
867 
868 	pr_err("%s: Invalid page request: %08llx %08llx\n",
869 	       iommu->name, ((unsigned long long *)req)[0],
870 	       ((unsigned long long *)req)[1]);
871 
872 	/*
873 	 * Per VT-d spec. v3.0 ch7.7, system software must
874 	 * respond with page group response if private data
875 	 * is present (PDP) or last page in group (LPIG) bit
876 	 * is set. This is an additional VT-d feature beyond
877 	 * PCI ATS spec.
878 	 */
879 	if (!req->lpig && !req->priv_data_present)
880 		return;
881 
882 	desc.qw0 = QI_PGRP_PASID(req->pasid) |
883 			QI_PGRP_DID(req->rid) |
884 			QI_PGRP_PASID_P(req->pasid_present) |
885 			QI_PGRP_PDP(req->priv_data_present) |
886 			QI_PGRP_RESP_CODE(result) |
887 			QI_PGRP_RESP_TYPE;
888 	desc.qw1 = QI_PGRP_IDX(req->prg_index) |
889 			QI_PGRP_LPIG(req->lpig);
890 
891 	if (req->priv_data_present) {
892 		desc.qw2 = req->priv_data[0];
893 		desc.qw3 = req->priv_data[1];
894 	} else {
895 		desc.qw2 = 0;
896 		desc.qw3 = 0;
897 	}
898 
899 	qi_submit_sync(iommu, &desc, 1, 0);
900 }
901 
902 static irqreturn_t prq_event_thread(int irq, void *d)
903 {
904 	struct intel_svm_dev *sdev = NULL;
905 	struct intel_iommu *iommu = d;
906 	struct intel_svm *svm = NULL;
907 	struct page_req_dsc *req;
908 	int head, tail, handled;
909 	u64 address;
910 
911 	/*
912 	 * Clear PPR bit before reading head/tail registers, to ensure that
913 	 * we get a new interrupt if needed.
914 	 */
915 	writel(DMA_PRS_PPR, iommu->reg + DMAR_PRS_REG);
916 
917 	tail = dmar_readq(iommu->reg + DMAR_PQT_REG) & PRQ_RING_MASK;
918 	head = dmar_readq(iommu->reg + DMAR_PQH_REG) & PRQ_RING_MASK;
919 	handled = (head != tail);
920 	while (head != tail) {
921 		req = &iommu->prq[head / sizeof(*req)];
922 		address = (u64)req->addr << VTD_PAGE_SHIFT;
923 
924 		if (unlikely(!req->pasid_present)) {
925 			pr_err("IOMMU: %s: Page request without PASID\n",
926 			       iommu->name);
927 bad_req:
928 			svm = NULL;
929 			sdev = NULL;
930 			handle_bad_prq_event(iommu, req, QI_RESP_INVALID);
931 			goto prq_advance;
932 		}
933 
934 		if (unlikely(!is_canonical_address(address))) {
935 			pr_err("IOMMU: %s: Address is not canonical\n",
936 			       iommu->name);
937 			goto bad_req;
938 		}
939 
940 		if (unlikely(req->pm_req && (req->rd_req | req->wr_req))) {
941 			pr_err("IOMMU: %s: Page request in Privilege Mode\n",
942 			       iommu->name);
943 			goto bad_req;
944 		}
945 
946 		if (unlikely(req->exe_req && req->rd_req)) {
947 			pr_err("IOMMU: %s: Execution request not supported\n",
948 			       iommu->name);
949 			goto bad_req;
950 		}
951 
952 		if (!svm || svm->pasid != req->pasid) {
953 			/*
954 			 * It can't go away, because the driver is not permitted
955 			 * to unbind the mm while any page faults are outstanding.
956 			 */
957 			svm = pasid_private_find(req->pasid);
958 			if (IS_ERR_OR_NULL(svm) || (svm->flags & SVM_FLAG_SUPERVISOR_MODE))
959 				goto bad_req;
960 		}
961 
962 		if (!sdev || sdev->sid != req->rid) {
963 			sdev = svm_lookup_device_by_sid(svm, req->rid);
964 			if (!sdev)
965 				goto bad_req;
966 		}
967 
968 		sdev->prq_seq_number++;
969 
970 		/*
971 		 * If prq is to be handled outside iommu driver via receiver of
972 		 * the fault notifiers, we skip the page response here.
973 		 */
974 		if (intel_svm_prq_report(iommu, sdev->dev, req))
975 			handle_bad_prq_event(iommu, req, QI_RESP_INVALID);
976 
977 		trace_prq_report(iommu, sdev->dev, req->qw_0, req->qw_1,
978 				 req->priv_data[0], req->priv_data[1],
979 				 sdev->prq_seq_number);
980 prq_advance:
981 		head = (head + sizeof(*req)) & PRQ_RING_MASK;
982 	}
983 
984 	dmar_writeq(iommu->reg + DMAR_PQH_REG, tail);
985 
986 	/*
987 	 * Clear the page request overflow bit and wake up all threads that
988 	 * are waiting for the completion of this handling.
989 	 */
990 	if (readl(iommu->reg + DMAR_PRS_REG) & DMA_PRS_PRO) {
991 		pr_info_ratelimited("IOMMU: %s: PRQ overflow detected\n",
992 				    iommu->name);
993 		head = dmar_readq(iommu->reg + DMAR_PQH_REG) & PRQ_RING_MASK;
994 		tail = dmar_readq(iommu->reg + DMAR_PQT_REG) & PRQ_RING_MASK;
995 		if (head == tail) {
996 			iopf_queue_discard_partial(iommu->iopf_queue);
997 			writel(DMA_PRS_PRO, iommu->reg + DMAR_PRS_REG);
998 			pr_info_ratelimited("IOMMU: %s: PRQ overflow cleared",
999 					    iommu->name);
1000 		}
1001 	}
1002 
1003 	if (!completion_done(&iommu->prq_complete))
1004 		complete(&iommu->prq_complete);
1005 
1006 	return IRQ_RETVAL(handled);
1007 }
1008 
1009 struct iommu_sva *intel_svm_bind(struct device *dev, struct mm_struct *mm, void *drvdata)
1010 {
1011 	struct intel_iommu *iommu = device_to_iommu(dev, NULL, NULL);
1012 	unsigned int flags = 0;
1013 	struct iommu_sva *sva;
1014 	int ret;
1015 
1016 	if (drvdata)
1017 		flags = *(unsigned int *)drvdata;
1018 
1019 	if (flags & SVM_FLAG_SUPERVISOR_MODE) {
1020 		if (!ecap_srs(iommu->ecap)) {
1021 			dev_err(dev, "%s: Supervisor PASID not supported\n",
1022 				iommu->name);
1023 			return ERR_PTR(-EOPNOTSUPP);
1024 		}
1025 
1026 		if (mm) {
1027 			dev_err(dev, "%s: Supervisor PASID with user provided mm\n",
1028 				iommu->name);
1029 			return ERR_PTR(-EINVAL);
1030 		}
1031 
1032 		mm = &init_mm;
1033 	}
1034 
1035 	mutex_lock(&pasid_mutex);
1036 	ret = intel_svm_alloc_pasid(dev, mm, flags);
1037 	if (ret) {
1038 		mutex_unlock(&pasid_mutex);
1039 		return ERR_PTR(ret);
1040 	}
1041 
1042 	sva = intel_svm_bind_mm(iommu, dev, mm, flags);
1043 	mutex_unlock(&pasid_mutex);
1044 
1045 	return sva;
1046 }
1047 
1048 void intel_svm_unbind(struct iommu_sva *sva)
1049 {
1050 	struct intel_svm_dev *sdev = to_intel_svm_dev(sva);
1051 
1052 	mutex_lock(&pasid_mutex);
1053 	intel_svm_unbind_mm(sdev->dev, sdev->pasid);
1054 	mutex_unlock(&pasid_mutex);
1055 }
1056 
1057 u32 intel_svm_get_pasid(struct iommu_sva *sva)
1058 {
1059 	struct intel_svm_dev *sdev;
1060 	u32 pasid;
1061 
1062 	mutex_lock(&pasid_mutex);
1063 	sdev = to_intel_svm_dev(sva);
1064 	pasid = sdev->pasid;
1065 	mutex_unlock(&pasid_mutex);
1066 
1067 	return pasid;
1068 }
1069 
1070 int intel_svm_page_response(struct device *dev,
1071 			    struct iommu_fault_event *evt,
1072 			    struct iommu_page_response *msg)
1073 {
1074 	struct iommu_fault_page_request *prm;
1075 	struct intel_svm_dev *sdev = NULL;
1076 	struct intel_svm *svm = NULL;
1077 	struct intel_iommu *iommu;
1078 	bool private_present;
1079 	bool pasid_present;
1080 	bool last_page;
1081 	u8 bus, devfn;
1082 	int ret = 0;
1083 	u16 sid;
1084 
1085 	if (!dev || !dev_is_pci(dev))
1086 		return -ENODEV;
1087 
1088 	iommu = device_to_iommu(dev, &bus, &devfn);
1089 	if (!iommu)
1090 		return -ENODEV;
1091 
1092 	if (!msg || !evt)
1093 		return -EINVAL;
1094 
1095 	mutex_lock(&pasid_mutex);
1096 
1097 	prm = &evt->fault.prm;
1098 	sid = PCI_DEVID(bus, devfn);
1099 	pasid_present = prm->flags & IOMMU_FAULT_PAGE_REQUEST_PASID_VALID;
1100 	private_present = prm->flags & IOMMU_FAULT_PAGE_REQUEST_PRIV_DATA;
1101 	last_page = prm->flags & IOMMU_FAULT_PAGE_REQUEST_LAST_PAGE;
1102 
1103 	if (!pasid_present) {
1104 		ret = -EINVAL;
1105 		goto out;
1106 	}
1107 
1108 	if (prm->pasid == 0 || prm->pasid >= PASID_MAX) {
1109 		ret = -EINVAL;
1110 		goto out;
1111 	}
1112 
1113 	ret = pasid_to_svm_sdev(dev, prm->pasid, &svm, &sdev);
1114 	if (ret || !sdev) {
1115 		ret = -ENODEV;
1116 		goto out;
1117 	}
1118 
1119 	/*
1120 	 * For responses from userspace, need to make sure that the
1121 	 * pasid has been bound to its mm.
1122 	 */
1123 	if (svm->flags & SVM_FLAG_GUEST_MODE) {
1124 		struct mm_struct *mm;
1125 
1126 		mm = get_task_mm(current);
1127 		if (!mm) {
1128 			ret = -EINVAL;
1129 			goto out;
1130 		}
1131 
1132 		if (mm != svm->mm) {
1133 			ret = -ENODEV;
1134 			mmput(mm);
1135 			goto out;
1136 		}
1137 
1138 		mmput(mm);
1139 	}
1140 
1141 	/*
1142 	 * Per VT-d spec. v3.0 ch7.7, system software must respond
1143 	 * with page group response if private data is present (PDP)
1144 	 * or last page in group (LPIG) bit is set. This is an
1145 	 * additional VT-d requirement beyond PCI ATS spec.
1146 	 */
1147 	if (last_page || private_present) {
1148 		struct qi_desc desc;
1149 
1150 		desc.qw0 = QI_PGRP_PASID(prm->pasid) | QI_PGRP_DID(sid) |
1151 				QI_PGRP_PASID_P(pasid_present) |
1152 				QI_PGRP_PDP(private_present) |
1153 				QI_PGRP_RESP_CODE(msg->code) |
1154 				QI_PGRP_RESP_TYPE;
1155 		desc.qw1 = QI_PGRP_IDX(prm->grpid) | QI_PGRP_LPIG(last_page);
1156 		desc.qw2 = 0;
1157 		desc.qw3 = 0;
1158 
1159 		if (private_present) {
1160 			desc.qw2 = prm->private_data[0];
1161 			desc.qw3 = prm->private_data[1];
1162 		} else if (prm->private_data[0]) {
1163 			dmar_latency_update(iommu, DMAR_LATENCY_PRQ,
1164 				ktime_to_ns(ktime_get()) - prm->private_data[0]);
1165 		}
1166 
1167 		qi_submit_sync(iommu, &desc, 1, 0);
1168 	}
1169 out:
1170 	mutex_unlock(&pasid_mutex);
1171 	return ret;
1172 }
1173