xref: /linux/drivers/vhost/vdpa.c (revision f16d85cd3de9d0c761b74155b4cbe2f20d3dcf80)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2018-2020 Intel Corporation.
4  * Copyright (C) 2020 Red Hat, Inc.
5  *
6  * Author: Tiwei Bie <tiwei.bie@intel.com>
7  *         Jason Wang <jasowang@redhat.com>
8  *
9  * Thanks Michael S. Tsirkin for the valuable comments and
10  * suggestions.  And thanks to Cunming Liang and Zhihong Wang for all
11  * their supports.
12  */
13 
14 #include <linux/kernel.h>
15 #include <linux/module.h>
16 #include <linux/cdev.h>
17 #include <linux/device.h>
18 #include <linux/mm.h>
19 #include <linux/slab.h>
20 #include <linux/iommu.h>
21 #include <linux/uuid.h>
22 #include <linux/vdpa.h>
23 #include <linux/nospec.h>
24 #include <linux/vhost.h>
25 
26 #include "vhost.h"
27 
28 enum {
29 	VHOST_VDPA_BACKEND_FEATURES =
30 	(1ULL << VHOST_BACKEND_F_IOTLB_MSG_V2) |
31 	(1ULL << VHOST_BACKEND_F_IOTLB_BATCH) |
32 	(1ULL << VHOST_BACKEND_F_IOTLB_ASID),
33 };
34 
35 #define VHOST_VDPA_DEV_MAX (1U << MINORBITS)
36 
37 static int max_iotlb_entries = 2048;
38 module_param(max_iotlb_entries, int, 0444);
39 MODULE_PARM_DESC(max_iotlb_entries,
40 		 "Maximum number of iotlb entries. (default: 2048)");
41 
42 #define VHOST_VDPA_IOTLB_BUCKETS 16
43 
44 struct vhost_vdpa_as {
45 	struct hlist_node hash_link;
46 	struct vhost_iotlb iotlb;
47 	u32 id;
48 };
49 
50 struct vhost_vdpa {
51 	struct vhost_dev vdev;
52 	struct iommu_domain *domain;
53 	struct vhost_virtqueue *vqs;
54 	struct completion completion;
55 	struct vdpa_device *vdpa;
56 	struct hlist_head as[VHOST_VDPA_IOTLB_BUCKETS];
57 	struct device dev;
58 	struct cdev cdev;
59 	atomic_t opened;
60 	u32 nvqs;
61 	u16 vq_num_max;
62 	int virtio_id;
63 	int minor;
64 	struct eventfd_ctx *config_ctx;
65 	/* Serialises vhost_vdpa_config_cb() against config_ctx being replaced. */
66 	spinlock_t config_lock;
67 	int in_batch;
68 	struct vdpa_iova_range range;
69 	u32 batch_asid;
70 	bool suspended;
71 };
72 
73 static DEFINE_IDA(vhost_vdpa_ida);
74 
75 static dev_t vhost_vdpa_major;
76 
77 static void vhost_vdpa_iotlb_unmap(struct vhost_vdpa *v,
78 				   struct vhost_iotlb *iotlb, u64 start,
79 				   u64 last, u32 asid);
80 
81 static inline u32 iotlb_to_asid(struct vhost_iotlb *iotlb)
82 {
83 	struct vhost_vdpa_as *as = container_of(iotlb, struct
84 						vhost_vdpa_as, iotlb);
85 	return as->id;
86 }
87 
88 static struct vhost_vdpa_as *asid_to_as(struct vhost_vdpa *v, u32 asid)
89 {
90 	struct hlist_head *head = &v->as[asid % VHOST_VDPA_IOTLB_BUCKETS];
91 	struct vhost_vdpa_as *as;
92 
93 	hlist_for_each_entry(as, head, hash_link)
94 		if (as->id == asid)
95 			return as;
96 
97 	return NULL;
98 }
99 
100 static struct vhost_iotlb *asid_to_iotlb(struct vhost_vdpa *v, u32 asid)
101 {
102 	struct vhost_vdpa_as *as = asid_to_as(v, asid);
103 
104 	if (!as)
105 		return NULL;
106 
107 	return &as->iotlb;
108 }
109 
110 static struct vhost_vdpa_as *vhost_vdpa_alloc_as(struct vhost_vdpa *v, u32 asid)
111 {
112 	struct hlist_head *head = &v->as[asid % VHOST_VDPA_IOTLB_BUCKETS];
113 	struct vhost_vdpa_as *as;
114 
115 	if (asid_to_as(v, asid))
116 		return NULL;
117 
118 	if (asid >= v->vdpa->nas)
119 		return NULL;
120 	if (max_iotlb_entries <= 0)
121 		return NULL;
122 
123 	as = kmalloc_obj(*as);
124 	if (!as)
125 		return NULL;
126 
127 	vhost_iotlb_init(&as->iotlb, max_iotlb_entries, 0);
128 	as->id = asid;
129 	hlist_add_head(&as->hash_link, head);
130 
131 	return as;
132 }
133 
134 static struct vhost_vdpa_as *vhost_vdpa_find_alloc_as(struct vhost_vdpa *v,
135 						      u32 asid)
136 {
137 	struct vhost_vdpa_as *as = asid_to_as(v, asid);
138 
139 	if (as)
140 		return as;
141 
142 	return vhost_vdpa_alloc_as(v, asid);
143 }
144 
145 static void vhost_vdpa_reset_map(struct vhost_vdpa *v, u32 asid)
146 {
147 	struct vdpa_device *vdpa = v->vdpa;
148 	const struct vdpa_config_ops *ops = vdpa->config;
149 
150 	if (ops->reset_map)
151 		ops->reset_map(vdpa, asid);
152 }
153 
154 static int vhost_vdpa_remove_as(struct vhost_vdpa *v, u32 asid)
155 {
156 	struct vhost_vdpa_as *as = asid_to_as(v, asid);
157 
158 	if (!as)
159 		return -EINVAL;
160 
161 	hlist_del(&as->hash_link);
162 	vhost_vdpa_iotlb_unmap(v, &as->iotlb, 0ULL, 0ULL - 1, asid);
163 	/*
164 	 * Devices with vendor specific IOMMU may need to restore
165 	 * iotlb to the initial or default state, which cannot be
166 	 * cleaned up in the all range unmap call above. Give them
167 	 * a chance to clean up or reset the map to the desired
168 	 * state.
169 	 */
170 	vhost_vdpa_reset_map(v, asid);
171 	kfree(as);
172 
173 	return 0;
174 }
175 
176 static void handle_vq_kick(struct vhost_work *work)
177 {
178 	struct vhost_virtqueue *vq = container_of(work, struct vhost_virtqueue,
179 						  poll.work);
180 	struct vhost_vdpa *v = container_of(vq->dev, struct vhost_vdpa, vdev);
181 	const struct vdpa_config_ops *ops = v->vdpa->config;
182 
183 	ops->kick_vq(v->vdpa, vq - v->vqs);
184 }
185 
186 static irqreturn_t vhost_vdpa_virtqueue_cb(void *private)
187 {
188 	struct vhost_virtqueue *vq = private;
189 	struct eventfd_ctx *call_ctx = vq->call_ctx.ctx;
190 
191 	if (call_ctx)
192 		eventfd_signal(call_ctx);
193 
194 	return IRQ_HANDLED;
195 }
196 
197 static irqreturn_t vhost_vdpa_config_cb(void *private)
198 {
199 	struct vhost_vdpa *v = private;
200 	unsigned long flags;
201 
202 	spin_lock_irqsave(&v->config_lock, flags);
203 	if (v->config_ctx)
204 		eventfd_signal(v->config_ctx);
205 	spin_unlock_irqrestore(&v->config_lock, flags);
206 
207 	return IRQ_HANDLED;
208 }
209 
210 static void vhost_vdpa_setup_vq_irq(struct vhost_vdpa *v, u16 qid)
211 {
212 	struct vhost_virtqueue *vq = &v->vqs[qid];
213 	const struct vdpa_config_ops *ops = v->vdpa->config;
214 	struct vdpa_device *vdpa = v->vdpa;
215 	int ret, irq;
216 
217 	if (!ops->get_vq_irq)
218 		return;
219 
220 	irq = ops->get_vq_irq(vdpa, qid);
221 	if (irq < 0)
222 		return;
223 
224 	if (!vq->call_ctx.ctx)
225 		return;
226 
227 	ret = irq_bypass_register_producer(&vq->call_ctx.producer,
228 					   vq->call_ctx.ctx, irq);
229 	if (unlikely(ret))
230 		dev_info(&v->dev, "vq %u, irq bypass producer (eventfd %p) registration fails, ret =  %d\n",
231 			 qid, vq->call_ctx.ctx, ret);
232 }
233 
234 static void vhost_vdpa_unsetup_vq_irq(struct vhost_vdpa *v, u16 qid)
235 {
236 	struct vhost_virtqueue *vq = &v->vqs[qid];
237 
238 	irq_bypass_unregister_producer(&vq->call_ctx.producer);
239 }
240 
241 static int _compat_vdpa_reset(struct vhost_vdpa *v)
242 {
243 	struct vdpa_device *vdpa = v->vdpa;
244 	const struct vdpa_config_ops *ops = vdpa->config;
245 	u32 flags = 0;
246 	int ret;
247 
248 	v->suspended = false;
249 
250 	if (v->vdev.vqs) {
251 		flags |= !vhost_backend_has_feature(v->vdev.vqs[0],
252 						    VHOST_BACKEND_F_IOTLB_PERSIST) ?
253 			 VDPA_RESET_F_CLEAN_MAP : 0;
254 	}
255 
256 	v->vq_num_max = 0;
257 	ret = vdpa_reset(vdpa, flags);
258 	if (!ret) {
259 		/* Some backends derive the max from mutable queue state. */
260 		v->vq_num_max = ops->get_vq_num_max(vdpa);
261 	}
262 
263 	return ret;
264 }
265 
266 static int vhost_vdpa_reset(struct vhost_vdpa *v)
267 {
268 	v->in_batch = 0;
269 	return _compat_vdpa_reset(v);
270 }
271 
272 static long vhost_vdpa_bind_mm(struct vhost_vdpa *v)
273 {
274 	struct vdpa_device *vdpa = v->vdpa;
275 	const struct vdpa_config_ops *ops = vdpa->config;
276 
277 	if (!vdpa->use_va || !ops->bind_mm)
278 		return 0;
279 
280 	return ops->bind_mm(vdpa, v->vdev.mm);
281 }
282 
283 static void vhost_vdpa_unbind_mm(struct vhost_vdpa *v)
284 {
285 	struct vdpa_device *vdpa = v->vdpa;
286 	const struct vdpa_config_ops *ops = vdpa->config;
287 
288 	if (!vdpa->use_va || !ops->unbind_mm)
289 		return;
290 
291 	ops->unbind_mm(vdpa);
292 }
293 
294 static long vhost_vdpa_get_device_id(struct vhost_vdpa *v, u8 __user *argp)
295 {
296 	struct vdpa_device *vdpa = v->vdpa;
297 	const struct vdpa_config_ops *ops = vdpa->config;
298 	u32 device_id;
299 
300 	device_id = ops->get_device_id(vdpa);
301 
302 	if (copy_to_user(argp, &device_id, sizeof(device_id)))
303 		return -EFAULT;
304 
305 	return 0;
306 }
307 
308 static long vhost_vdpa_get_status(struct vhost_vdpa *v, u8 __user *statusp)
309 {
310 	struct vdpa_device *vdpa = v->vdpa;
311 	const struct vdpa_config_ops *ops = vdpa->config;
312 	u8 status;
313 
314 	status = ops->get_status(vdpa);
315 
316 	if (copy_to_user(statusp, &status, sizeof(status)))
317 		return -EFAULT;
318 
319 	return 0;
320 }
321 
322 static long vhost_vdpa_set_status(struct vhost_vdpa *v, u8 __user *statusp)
323 {
324 	struct vdpa_device *vdpa = v->vdpa;
325 	const struct vdpa_config_ops *ops = vdpa->config;
326 	u8 status, status_old;
327 	u32 nvqs = v->nvqs;
328 	int ret;
329 	u16 i;
330 
331 	if (copy_from_user(&status, statusp, sizeof(status)))
332 		return -EFAULT;
333 
334 	status_old = ops->get_status(vdpa);
335 
336 	/*
337 	 * Userspace shouldn't remove status bits unless reset the
338 	 * status to 0.
339 	 */
340 	if (status != 0 && (status_old & ~status) != 0)
341 		return -EINVAL;
342 
343 	if ((status_old & VIRTIO_CONFIG_S_DRIVER_OK) && !(status & VIRTIO_CONFIG_S_DRIVER_OK))
344 		for (i = 0; i < nvqs; i++)
345 			vhost_vdpa_unsetup_vq_irq(v, i);
346 
347 	if (status == 0) {
348 		ret = _compat_vdpa_reset(v);
349 		if (ret)
350 			return ret;
351 	} else
352 		vdpa_set_status(vdpa, status);
353 
354 	if ((status & VIRTIO_CONFIG_S_DRIVER_OK) && !(status_old & VIRTIO_CONFIG_S_DRIVER_OK))
355 		for (i = 0; i < nvqs; i++)
356 			vhost_vdpa_setup_vq_irq(v, i);
357 
358 	return 0;
359 }
360 
361 static int vhost_vdpa_config_validate(struct vhost_vdpa *v,
362 				      struct vhost_vdpa_config *c)
363 {
364 	struct vdpa_device *vdpa = v->vdpa;
365 	size_t size = vdpa->config->get_config_size(vdpa);
366 
367 	if (c->len == 0 || c->off > size)
368 		return -EINVAL;
369 
370 	if (c->len > size - c->off)
371 		return -E2BIG;
372 
373 	return 0;
374 }
375 
376 static long vhost_vdpa_get_config(struct vhost_vdpa *v,
377 				  struct vhost_vdpa_config __user *c)
378 {
379 	struct vdpa_device *vdpa = v->vdpa;
380 	struct vhost_vdpa_config config;
381 	unsigned long size = offsetof(struct vhost_vdpa_config, buf);
382 	u8 *buf;
383 
384 	if (copy_from_user(&config, c, size))
385 		return -EFAULT;
386 	if (vhost_vdpa_config_validate(v, &config))
387 		return -EINVAL;
388 	buf = kvzalloc(config.len, GFP_KERNEL);
389 	if (!buf)
390 		return -ENOMEM;
391 
392 	vdpa_get_config(vdpa, config.off, buf, config.len);
393 
394 	if (copy_to_user(c->buf, buf, config.len)) {
395 		kvfree(buf);
396 		return -EFAULT;
397 	}
398 
399 	kvfree(buf);
400 	return 0;
401 }
402 
403 static long vhost_vdpa_set_config(struct vhost_vdpa *v,
404 				  struct vhost_vdpa_config __user *c)
405 {
406 	struct vdpa_device *vdpa = v->vdpa;
407 	struct vhost_vdpa_config config;
408 	unsigned long size = offsetof(struct vhost_vdpa_config, buf);
409 	u8 *buf;
410 
411 	if (copy_from_user(&config, c, size))
412 		return -EFAULT;
413 	if (vhost_vdpa_config_validate(v, &config))
414 		return -EINVAL;
415 
416 	buf = vmemdup_user(c->buf, config.len);
417 	if (IS_ERR(buf))
418 		return PTR_ERR(buf);
419 
420 	vdpa_set_config(vdpa, config.off, buf, config.len);
421 
422 	kvfree(buf);
423 	return 0;
424 }
425 
426 static bool vhost_vdpa_can_suspend(const struct vhost_vdpa *v)
427 {
428 	struct vdpa_device *vdpa = v->vdpa;
429 	const struct vdpa_config_ops *ops = vdpa->config;
430 
431 	return ops->suspend;
432 }
433 
434 static bool vhost_vdpa_can_resume(const struct vhost_vdpa *v)
435 {
436 	struct vdpa_device *vdpa = v->vdpa;
437 	const struct vdpa_config_ops *ops = vdpa->config;
438 
439 	return ops->resume;
440 }
441 
442 static bool vhost_vdpa_has_desc_group(const struct vhost_vdpa *v)
443 {
444 	struct vdpa_device *vdpa = v->vdpa;
445 	const struct vdpa_config_ops *ops = vdpa->config;
446 
447 	return ops->get_vq_desc_group;
448 }
449 
450 static long vhost_vdpa_get_features(struct vhost_vdpa *v, u64 __user *featurep)
451 {
452 	struct vdpa_device *vdpa = v->vdpa;
453 	const struct vdpa_config_ops *ops = vdpa->config;
454 	u64 features;
455 
456 	features = ops->get_device_features(vdpa);
457 
458 	if (copy_to_user(featurep, &features, sizeof(features)))
459 		return -EFAULT;
460 
461 	return 0;
462 }
463 
464 static u64 vhost_vdpa_get_backend_features(const struct vhost_vdpa *v)
465 {
466 	struct vdpa_device *vdpa = v->vdpa;
467 	const struct vdpa_config_ops *ops = vdpa->config;
468 
469 	if (!ops->get_backend_features)
470 		return 0;
471 	else
472 		return ops->get_backend_features(vdpa);
473 }
474 
475 static bool vhost_vdpa_has_persistent_map(const struct vhost_vdpa *v)
476 {
477 	struct vdpa_device *vdpa = v->vdpa;
478 	const struct vdpa_config_ops *ops = vdpa->config;
479 
480 	return (!ops->set_map && !ops->dma_map) || ops->reset_map ||
481 	       vhost_vdpa_get_backend_features(v) & BIT_ULL(VHOST_BACKEND_F_IOTLB_PERSIST);
482 }
483 
484 static long vhost_vdpa_set_features(struct vhost_vdpa *v, u64 __user *featurep)
485 {
486 	struct vdpa_device *vdpa = v->vdpa;
487 	const struct vdpa_config_ops *ops = vdpa->config;
488 	struct vhost_dev *d = &v->vdev;
489 	u64 actual_features;
490 	u64 features;
491 	int i;
492 
493 	/*
494 	 * It's not allowed to change the features after they have
495 	 * been negotiated.
496 	 */
497 	if (ops->get_status(vdpa) & VIRTIO_CONFIG_S_FEATURES_OK)
498 		return -EBUSY;
499 
500 	if (copy_from_user(&features, featurep, sizeof(features)))
501 		return -EFAULT;
502 
503 	if (vdpa_set_features(vdpa, features))
504 		return -EINVAL;
505 
506 	/* let the vqs know what has been configured */
507 	actual_features = ops->get_driver_features(vdpa);
508 	for (i = 0; i < d->nvqs; ++i) {
509 		struct vhost_virtqueue *vq = d->vqs[i];
510 
511 		mutex_lock(&vq->mutex);
512 		vq->acked_features = actual_features;
513 		mutex_unlock(&vq->mutex);
514 	}
515 
516 	return 0;
517 }
518 
519 static long vhost_vdpa_get_vring_num(struct vhost_vdpa *v, u16 __user *argp)
520 {
521 	struct vdpa_device *vdpa = v->vdpa;
522 	const struct vdpa_config_ops *ops = vdpa->config;
523 	u16 num;
524 
525 	num = ops->get_vq_num_max(vdpa);
526 
527 	if (copy_to_user(argp, &num, sizeof(num)))
528 		return -EFAULT;
529 
530 	return 0;
531 }
532 
533 static void vhost_vdpa_config_put(struct vhost_vdpa *v)
534 {
535 	struct eventfd_ctx *ctx;
536 	unsigned long flags;
537 
538 	spin_lock_irqsave(&v->config_lock, flags);
539 	ctx = v->config_ctx;
540 	v->config_ctx = NULL;
541 	spin_unlock_irqrestore(&v->config_lock, flags);
542 
543 	if (ctx)
544 		eventfd_ctx_put(ctx);
545 }
546 
547 static long vhost_vdpa_set_config_call(struct vhost_vdpa *v, u32 __user *argp)
548 {
549 	struct vdpa_callback cb;
550 	unsigned long flags;
551 	int fd;
552 	struct eventfd_ctx *ctx;
553 
554 	cb.callback = vhost_vdpa_config_cb;
555 	cb.private = v;
556 	if (copy_from_user(&fd, argp, sizeof(fd)))
557 		return  -EFAULT;
558 
559 	ctx = fd == VHOST_FILE_UNBIND ? NULL : eventfd_ctx_fdget(fd);
560 	if (IS_ERR(ctx))
561 		return PTR_ERR(ctx);
562 
563 	spin_lock_irqsave(&v->config_lock, flags);
564 	swap(ctx, v->config_ctx);
565 	spin_unlock_irqrestore(&v->config_lock, flags);
566 
567 	/*
568 	 * The callback can no longer reach the old context, so this is the
569 	 * last reference to it.
570 	 */
571 	if (ctx)
572 		eventfd_ctx_put(ctx);
573 
574 	v->vdpa->config->set_config_cb(v->vdpa, &cb);
575 
576 	return 0;
577 }
578 
579 static long vhost_vdpa_get_iova_range(struct vhost_vdpa *v, u32 __user *argp)
580 {
581 	struct vhost_vdpa_iova_range range = {
582 		.first = v->range.first,
583 		.last = v->range.last,
584 	};
585 
586 	if (copy_to_user(argp, &range, sizeof(range)))
587 		return -EFAULT;
588 	return 0;
589 }
590 
591 static long vhost_vdpa_get_config_size(struct vhost_vdpa *v, u32 __user *argp)
592 {
593 	struct vdpa_device *vdpa = v->vdpa;
594 	const struct vdpa_config_ops *ops = vdpa->config;
595 	u32 size;
596 
597 	size = ops->get_config_size(vdpa);
598 
599 	if (copy_to_user(argp, &size, sizeof(size)))
600 		return -EFAULT;
601 
602 	return 0;
603 }
604 
605 static long vhost_vdpa_get_vqs_count(struct vhost_vdpa *v, u32 __user *argp)
606 {
607 	struct vdpa_device *vdpa = v->vdpa;
608 
609 	if (copy_to_user(argp, &vdpa->nvqs, sizeof(vdpa->nvqs)))
610 		return -EFAULT;
611 
612 	return 0;
613 }
614 
615 /* After a successful return of ioctl the device must not process more
616  * virtqueue descriptors. The device can answer to read or writes of config
617  * fields as if it were not suspended. In particular, writing to "queue_enable"
618  * with a value of 1 will not make the device start processing buffers.
619  */
620 static long vhost_vdpa_suspend(struct vhost_vdpa *v)
621 {
622 	struct vdpa_device *vdpa = v->vdpa;
623 	const struct vdpa_config_ops *ops = vdpa->config;
624 	int ret;
625 
626 	if (!(ops->get_status(vdpa) & VIRTIO_CONFIG_S_DRIVER_OK))
627 		return 0;
628 
629 	if (!ops->suspend)
630 		return -EOPNOTSUPP;
631 
632 	ret = ops->suspend(vdpa);
633 	if (!ret)
634 		v->suspended = true;
635 
636 	return ret;
637 }
638 
639 /* After a successful return of this ioctl the device resumes processing
640  * virtqueue descriptors. The device becomes fully operational the same way it
641  * was before it was suspended.
642  */
643 static long vhost_vdpa_resume(struct vhost_vdpa *v)
644 {
645 	struct vdpa_device *vdpa = v->vdpa;
646 	const struct vdpa_config_ops *ops = vdpa->config;
647 	int ret;
648 
649 	if (!(ops->get_status(vdpa) & VIRTIO_CONFIG_S_DRIVER_OK))
650 		return 0;
651 
652 	if (!ops->resume)
653 		return -EOPNOTSUPP;
654 
655 	ret = ops->resume(vdpa);
656 	if (!ret)
657 		v->suspended = false;
658 
659 	return ret;
660 }
661 
662 static long vhost_vdpa_vring_ioctl(struct vhost_vdpa *v, unsigned int cmd,
663 				   void __user *argp)
664 {
665 	struct vdpa_device *vdpa = v->vdpa;
666 	const struct vdpa_config_ops *ops = vdpa->config;
667 	struct vdpa_vq_state vq_state;
668 	struct vdpa_callback cb;
669 	struct vhost_virtqueue *vq;
670 	struct vhost_vring_state s;
671 	u32 idx;
672 	long r;
673 
674 	if (cmd == VHOST_SET_VRING_NUM) {
675 		if (copy_from_user(&s, argp, sizeof(s)))
676 			return -EFAULT;
677 		idx = s.index;
678 	} else {
679 		r = get_user(idx, (u32 __user *)argp);
680 		if (r < 0)
681 			return r;
682 	}
683 
684 	if (idx >= v->nvqs)
685 		return -ENOBUFS;
686 
687 	idx = array_index_nospec(idx, v->nvqs);
688 	vq = &v->vqs[idx];
689 
690 	switch (cmd) {
691 	case VHOST_SET_VRING_NUM:
692 		mutex_lock(&vq->mutex);
693 		if (vq->private_data) {
694 			r = -EBUSY;
695 		} else if (!s.num || s.num > 0xffff ||
696 			   s.num > v->vq_num_max ||
697 			   (s.num & (s.num - 1))) {
698 			r = -EINVAL;
699 		} else {
700 			vq->num = s.num;
701 			r = 0;
702 		}
703 		mutex_unlock(&vq->mutex);
704 		if (r)
705 			return r;
706 		ops->set_vq_num(vdpa, idx, s.num);
707 		return 0;
708 	case VHOST_VDPA_SET_VRING_ENABLE:
709 		if (copy_from_user(&s, argp, sizeof(s)))
710 			return -EFAULT;
711 		ops->set_vq_ready(vdpa, idx, s.num);
712 		return 0;
713 	case VHOST_VDPA_GET_VRING_GROUP:
714 		if (!ops->get_vq_group)
715 			return -EOPNOTSUPP;
716 		s.index = idx;
717 		s.num = ops->get_vq_group(vdpa, idx);
718 		if (s.num >= vdpa->ngroups)
719 			return -EIO;
720 		else if (copy_to_user(argp, &s, sizeof(s)))
721 			return -EFAULT;
722 		return 0;
723 	case VHOST_VDPA_GET_VRING_DESC_GROUP:
724 		if (!vhost_vdpa_has_desc_group(v))
725 			return -EOPNOTSUPP;
726 		s.index = idx;
727 		s.num = ops->get_vq_desc_group(vdpa, idx);
728 		if (s.num >= vdpa->ngroups)
729 			return -EIO;
730 		else if (copy_to_user(argp, &s, sizeof(s)))
731 			return -EFAULT;
732 		return 0;
733 	case VHOST_VDPA_SET_GROUP_ASID:
734 		if (copy_from_user(&s, argp, sizeof(s)))
735 			return -EFAULT;
736 		if (idx >= vdpa->ngroups || s.num >= vdpa->nas)
737 			return -EINVAL;
738 		if (ops->get_status(vdpa) & VIRTIO_CONFIG_S_DRIVER_OK)
739 			return -EBUSY;
740 		if (!ops->set_group_asid)
741 			return -EOPNOTSUPP;
742 		return ops->set_group_asid(vdpa, idx, s.num);
743 	case VHOST_VDPA_GET_VRING_SIZE:
744 		if (!ops->get_vq_size)
745 			return -EOPNOTSUPP;
746 		s.index = idx;
747 		s.num = ops->get_vq_size(vdpa, idx);
748 		if (copy_to_user(argp, &s, sizeof(s)))
749 			return -EFAULT;
750 		return 0;
751 	case VHOST_GET_VRING_BASE:
752 		r = ops->get_vq_state(v->vdpa, idx, &vq_state);
753 		if (r)
754 			return r;
755 
756 		if (vhost_has_feature(vq, VIRTIO_F_RING_PACKED)) {
757 			vq->last_avail_idx = vq_state.packed.last_avail_idx |
758 					     (vq_state.packed.last_avail_counter << 15);
759 			vq->last_used_idx = vq_state.packed.last_used_idx |
760 					    (vq_state.packed.last_used_counter << 15);
761 		} else {
762 			vq->last_avail_idx = vq_state.split.avail_index;
763 		}
764 		break;
765 	case VHOST_SET_VRING_CALL:
766 		if (vq->call_ctx.ctx) {
767 			if (ops->get_status(vdpa) &
768 			    VIRTIO_CONFIG_S_DRIVER_OK)
769 				vhost_vdpa_unsetup_vq_irq(v, idx);
770 			/*
771 			 * The parent caches call_ctx.ctx in cb.trigger without
772 			 * holding a reference, so it has to stop using it
773 			 * before vhost_vring_ioctl() drops the last one.
774 			 */
775 			cb.callback = NULL;
776 			cb.private = NULL;
777 			cb.trigger = NULL;
778 			ops->set_vq_cb(vdpa, idx, &cb);
779 
780 			/*
781 			 * A parent interrupt handler that loaded the callback
782 			 * before that store can still be running, so wait for
783 			 * it to finish with the context too.
784 			 */
785 			if (ops->get_vq_irq) {
786 				int irq = ops->get_vq_irq(vdpa, idx);
787 
788 				if (irq >= 0)
789 					synchronize_irq(irq);
790 			}
791 		}
792 		break;
793 	}
794 
795 	r = vhost_vring_ioctl(&v->vdev, cmd, argp);
796 	if (r) {
797 		/*
798 		 * A failure here means the swap never happened and the old
799 		 * context is still installed, so give the parent back the
800 		 * callback that was torn down above.
801 		 */
802 		if (cmd == VHOST_SET_VRING_CALL && vq->call_ctx.ctx) {
803 			cb.callback = vhost_vdpa_virtqueue_cb;
804 			cb.private = vq;
805 			cb.trigger = vq->call_ctx.ctx;
806 			ops->set_vq_cb(vdpa, idx, &cb);
807 		}
808 		return r;
809 	}
810 
811 	switch (cmd) {
812 	case VHOST_SET_VRING_ADDR:
813 		if ((ops->get_status(vdpa) & VIRTIO_CONFIG_S_DRIVER_OK) && !v->suspended)
814 			return -EINVAL;
815 
816 		if (ops->set_vq_address(vdpa, idx,
817 					(u64)(uintptr_t)vq->desc,
818 					(u64)(uintptr_t)vq->avail,
819 					(u64)(uintptr_t)vq->used))
820 			r = -EINVAL;
821 		break;
822 
823 	case VHOST_SET_VRING_BASE:
824 		if ((ops->get_status(vdpa) & VIRTIO_CONFIG_S_DRIVER_OK) && !v->suspended)
825 			return -EINVAL;
826 
827 		if (vhost_has_feature(vq, VIRTIO_F_RING_PACKED)) {
828 			vq_state.packed.last_avail_idx = vq->last_avail_idx & 0x7fff;
829 			vq_state.packed.last_avail_counter = !!(vq->last_avail_idx & 0x8000);
830 			vq_state.packed.last_used_idx = vq->last_used_idx & 0x7fff;
831 			vq_state.packed.last_used_counter = !!(vq->last_used_idx & 0x8000);
832 		} else {
833 			vq_state.split.avail_index = vq->last_avail_idx;
834 		}
835 		r = ops->set_vq_state(vdpa, idx, &vq_state);
836 		break;
837 
838 	case VHOST_SET_VRING_CALL:
839 		if (vq->call_ctx.ctx) {
840 			cb.callback = vhost_vdpa_virtqueue_cb;
841 			cb.private = vq;
842 			cb.trigger = vq->call_ctx.ctx;
843 			if (ops->get_status(vdpa) &
844 			    VIRTIO_CONFIG_S_DRIVER_OK)
845 				vhost_vdpa_setup_vq_irq(v, idx);
846 		} else {
847 			cb.callback = NULL;
848 			cb.private = NULL;
849 			cb.trigger = NULL;
850 		}
851 		ops->set_vq_cb(vdpa, idx, &cb);
852 		break;
853 
854 	}
855 
856 	return r;
857 }
858 
859 static long vhost_vdpa_unlocked_ioctl(struct file *filep,
860 				      unsigned int cmd, unsigned long arg)
861 {
862 	struct vhost_vdpa *v = filep->private_data;
863 	struct vhost_dev *d = &v->vdev;
864 	void __user *argp = (void __user *)arg;
865 	u64 __user *featurep = argp;
866 	u64 features;
867 	long r = 0;
868 
869 	if (cmd == VHOST_SET_BACKEND_FEATURES) {
870 		if (copy_from_user(&features, featurep, sizeof(features)))
871 			return -EFAULT;
872 		if (features & ~(VHOST_VDPA_BACKEND_FEATURES |
873 				 BIT_ULL(VHOST_BACKEND_F_DESC_ASID) |
874 				 BIT_ULL(VHOST_BACKEND_F_IOTLB_PERSIST) |
875 				 BIT_ULL(VHOST_BACKEND_F_SUSPEND) |
876 				 BIT_ULL(VHOST_BACKEND_F_RESUME) |
877 				 BIT_ULL(VHOST_BACKEND_F_ENABLE_AFTER_DRIVER_OK)))
878 			return -EOPNOTSUPP;
879 		if ((features & BIT_ULL(VHOST_BACKEND_F_SUSPEND)) &&
880 		     !vhost_vdpa_can_suspend(v))
881 			return -EOPNOTSUPP;
882 		if ((features & BIT_ULL(VHOST_BACKEND_F_RESUME)) &&
883 		     !vhost_vdpa_can_resume(v))
884 			return -EOPNOTSUPP;
885 		if ((features & BIT_ULL(VHOST_BACKEND_F_DESC_ASID)) &&
886 		    !(features & BIT_ULL(VHOST_BACKEND_F_IOTLB_ASID)))
887 			return -EINVAL;
888 		if ((features & BIT_ULL(VHOST_BACKEND_F_DESC_ASID)) &&
889 		     !vhost_vdpa_has_desc_group(v))
890 			return -EOPNOTSUPP;
891 		if ((features & BIT_ULL(VHOST_BACKEND_F_IOTLB_PERSIST)) &&
892 		     !vhost_vdpa_has_persistent_map(v))
893 			return -EOPNOTSUPP;
894 		vhost_set_backend_features(&v->vdev, features);
895 		return 0;
896 	}
897 
898 	mutex_lock(&d->mutex);
899 
900 	switch (cmd) {
901 	case VHOST_VDPA_GET_DEVICE_ID:
902 		r = vhost_vdpa_get_device_id(v, argp);
903 		break;
904 	case VHOST_VDPA_GET_STATUS:
905 		r = vhost_vdpa_get_status(v, argp);
906 		break;
907 	case VHOST_VDPA_SET_STATUS:
908 		r = vhost_vdpa_set_status(v, argp);
909 		break;
910 	case VHOST_VDPA_GET_CONFIG:
911 		r = vhost_vdpa_get_config(v, argp);
912 		break;
913 	case VHOST_VDPA_SET_CONFIG:
914 		r = vhost_vdpa_set_config(v, argp);
915 		break;
916 	case VHOST_GET_FEATURES:
917 		r = vhost_vdpa_get_features(v, argp);
918 		break;
919 	case VHOST_SET_FEATURES:
920 		r = vhost_vdpa_set_features(v, argp);
921 		break;
922 	case VHOST_VDPA_GET_VRING_NUM:
923 		r = vhost_vdpa_get_vring_num(v, argp);
924 		break;
925 	case VHOST_VDPA_GET_GROUP_NUM:
926 		if (copy_to_user(argp, &v->vdpa->ngroups,
927 				 sizeof(v->vdpa->ngroups)))
928 			r = -EFAULT;
929 		break;
930 	case VHOST_VDPA_GET_AS_NUM:
931 		if (copy_to_user(argp, &v->vdpa->nas, sizeof(v->vdpa->nas)))
932 			r = -EFAULT;
933 		break;
934 	case VHOST_SET_LOG_BASE:
935 	case VHOST_SET_LOG_FD:
936 		r = -ENOIOCTLCMD;
937 		break;
938 	case VHOST_VDPA_SET_CONFIG_CALL:
939 		r = vhost_vdpa_set_config_call(v, argp);
940 		break;
941 	case VHOST_GET_BACKEND_FEATURES:
942 		features = VHOST_VDPA_BACKEND_FEATURES;
943 		if (vhost_vdpa_can_suspend(v))
944 			features |= BIT_ULL(VHOST_BACKEND_F_SUSPEND);
945 		if (vhost_vdpa_can_resume(v))
946 			features |= BIT_ULL(VHOST_BACKEND_F_RESUME);
947 		if (vhost_vdpa_has_desc_group(v))
948 			features |= BIT_ULL(VHOST_BACKEND_F_DESC_ASID);
949 		if (vhost_vdpa_has_persistent_map(v))
950 			features |= BIT_ULL(VHOST_BACKEND_F_IOTLB_PERSIST);
951 		features |= vhost_vdpa_get_backend_features(v);
952 		if (copy_to_user(featurep, &features, sizeof(features)))
953 			r = -EFAULT;
954 		break;
955 	case VHOST_VDPA_GET_IOVA_RANGE:
956 		r = vhost_vdpa_get_iova_range(v, argp);
957 		break;
958 	case VHOST_VDPA_GET_CONFIG_SIZE:
959 		r = vhost_vdpa_get_config_size(v, argp);
960 		break;
961 	case VHOST_VDPA_GET_VQS_COUNT:
962 		r = vhost_vdpa_get_vqs_count(v, argp);
963 		break;
964 	case VHOST_VDPA_SUSPEND:
965 		r = vhost_vdpa_suspend(v);
966 		break;
967 	case VHOST_VDPA_RESUME:
968 		r = vhost_vdpa_resume(v);
969 		break;
970 	default:
971 		r = vhost_dev_ioctl(&v->vdev, cmd, argp);
972 		if (r == -ENOIOCTLCMD)
973 			r = vhost_vdpa_vring_ioctl(v, cmd, argp);
974 		break;
975 	}
976 
977 	if (r)
978 		goto out;
979 
980 	switch (cmd) {
981 	case VHOST_SET_OWNER:
982 		r = vhost_vdpa_bind_mm(v);
983 		if (r)
984 			vhost_dev_reset_owner(d, NULL, false);
985 		break;
986 	}
987 out:
988 	mutex_unlock(&d->mutex);
989 	return r;
990 }
991 static void vhost_vdpa_general_unmap(struct vhost_vdpa *v,
992 				     struct vhost_iotlb_map *map, u32 asid)
993 {
994 	struct vdpa_device *vdpa = v->vdpa;
995 	const struct vdpa_config_ops *ops = vdpa->config;
996 	if (ops->dma_map) {
997 		ops->dma_unmap(vdpa, asid, map->start, map->size);
998 	} else if (ops->set_map == NULL) {
999 		iommu_unmap(v->domain, map->start, map->size);
1000 	}
1001 }
1002 
1003 static void vhost_vdpa_pa_unmap(struct vhost_vdpa *v, struct vhost_iotlb *iotlb,
1004 				u64 start, u64 last, u32 asid)
1005 {
1006 	struct vhost_dev *dev = &v->vdev;
1007 	struct vhost_iotlb_map *map;
1008 
1009 	while ((map = vhost_iotlb_itree_first(iotlb, start, last)) != NULL) {
1010 		/* Stop device access before releasing the pinned pages. */
1011 		vhost_vdpa_general_unmap(v, map, asid);
1012 		unpin_user_page_range_dirty_lock(pfn_to_page(PFN_DOWN(map->addr)),
1013 						 PFN_DOWN(map->size),
1014 						 map->perm & VHOST_ACCESS_WO);
1015 		atomic64_sub(PFN_DOWN(map->size), &dev->mm->pinned_vm);
1016 		vhost_iotlb_map_free(iotlb, map);
1017 	}
1018 }
1019 
1020 static void vhost_vdpa_va_unmap(struct vhost_vdpa *v, struct vhost_iotlb *iotlb,
1021 				u64 start, u64 last, u32 asid)
1022 {
1023 	struct vhost_iotlb_map *map;
1024 	struct vdpa_map_file *map_file;
1025 
1026 	while ((map = vhost_iotlb_itree_first(iotlb, start, last)) != NULL) {
1027 		vhost_vdpa_general_unmap(v, map, asid);
1028 		map_file = (struct vdpa_map_file *)map->opaque;
1029 		fput(map_file->file);
1030 		kfree(map_file);
1031 		vhost_iotlb_map_free(iotlb, map);
1032 	}
1033 }
1034 
1035 static void vhost_vdpa_iotlb_unmap(struct vhost_vdpa *v,
1036 				   struct vhost_iotlb *iotlb, u64 start,
1037 				   u64 last, u32 asid)
1038 {
1039 	struct vdpa_device *vdpa = v->vdpa;
1040 
1041 	if (vdpa->use_va)
1042 		return vhost_vdpa_va_unmap(v, iotlb, start, last, asid);
1043 
1044 	return vhost_vdpa_pa_unmap(v, iotlb, start, last, asid);
1045 }
1046 
1047 static int perm_to_iommu_flags(u32 perm)
1048 {
1049 	int flags = 0;
1050 
1051 	switch (perm) {
1052 	case VHOST_ACCESS_WO:
1053 		flags |= IOMMU_WRITE;
1054 		break;
1055 	case VHOST_ACCESS_RO:
1056 		flags |= IOMMU_READ;
1057 		break;
1058 	case VHOST_ACCESS_RW:
1059 		flags |= (IOMMU_WRITE | IOMMU_READ);
1060 		break;
1061 	default:
1062 		WARN(1, "invalidate vhost IOTLB permission\n");
1063 		break;
1064 	}
1065 
1066 	return flags | IOMMU_CACHE;
1067 }
1068 
1069 static int vhost_vdpa_map(struct vhost_vdpa *v, struct vhost_iotlb *iotlb,
1070 			  u64 iova, u64 size, u64 pa, u32 perm, void *opaque)
1071 {
1072 	struct vhost_dev *dev = &v->vdev;
1073 	struct vdpa_device *vdpa = v->vdpa;
1074 	const struct vdpa_config_ops *ops = vdpa->config;
1075 	u32 asid = iotlb_to_asid(iotlb);
1076 	int r = 0;
1077 
1078 	r = vhost_iotlb_add_range_ctx(iotlb, iova, iova + size - 1,
1079 				      pa, perm, opaque);
1080 	if (r)
1081 		return r;
1082 
1083 	if (ops->dma_map) {
1084 		r = ops->dma_map(vdpa, asid, iova, size, pa, perm, opaque);
1085 	} else if (ops->set_map) {
1086 		if (!v->in_batch)
1087 			r = ops->set_map(vdpa, asid, iotlb);
1088 	} else {
1089 		r = iommu_map(v->domain, iova, pa, size,
1090 			      perm_to_iommu_flags(perm),
1091 			      GFP_KERNEL_ACCOUNT);
1092 	}
1093 	if (r) {
1094 		vhost_iotlb_del_range(iotlb, iova, iova + size - 1);
1095 		return r;
1096 	}
1097 
1098 	if (!vdpa->use_va)
1099 		atomic64_add(PFN_DOWN(size), &dev->mm->pinned_vm);
1100 
1101 	return 0;
1102 }
1103 
1104 static int vhost_vdpa_unmap(struct vhost_vdpa *v,
1105 			    struct vhost_iotlb *iotlb,
1106 			    u64 iova, u64 size)
1107 {
1108 	struct vdpa_device *vdpa = v->vdpa;
1109 	const struct vdpa_config_ops *ops = vdpa->config;
1110 	struct vhost_iotlb_map *map;
1111 	struct vhost_iotlb new_iotlb;
1112 	u32 asid = iotlb_to_asid(iotlb);
1113 	u64 last = iova + size - 1;
1114 	int ret;
1115 
1116 	if (ops->set_map && !ops->dma_map) {
1117 		vhost_iotlb_init(&new_iotlb, iotlb->limit, iotlb->flags);
1118 		list_for_each_entry(map, &iotlb->list, link) {
1119 			if (map->start <= last && map->last >= iova)
1120 				continue;
1121 			ret = vhost_iotlb_add_range_ctx(&new_iotlb, map->start,
1122 							map->last, map->addr,
1123 							map->perm, map->opaque);
1124 			if (ret)
1125 				goto reset;
1126 		}
1127 
1128 		ret = ops->set_map(vdpa, asid, &new_iotlb);
1129 reset:
1130 		vhost_iotlb_reset(&new_iotlb);
1131 		if (ret)
1132 			return ret;
1133 	}
1134 
1135 	vhost_vdpa_iotlb_unmap(v, iotlb, iova, last, asid);
1136 	return 0;
1137 }
1138 
1139 static int vhost_vdpa_va_map(struct vhost_vdpa *v,
1140 			     struct vhost_iotlb *iotlb,
1141 			     u64 iova, u64 size, u64 uaddr, u32 perm)
1142 {
1143 	struct vhost_dev *dev = &v->vdev;
1144 	u64 offset, map_size, map_iova = iova;
1145 	struct vdpa_map_file *map_file;
1146 	struct vm_area_struct *vma;
1147 	int ret = 0;
1148 
1149 	mmap_read_lock(dev->mm);
1150 
1151 	while (size) {
1152 		vma = find_vma(dev->mm, uaddr);
1153 		if (!vma) {
1154 			ret = -EINVAL;
1155 			break;
1156 		}
1157 		map_size = min(size, vma->vm_end - uaddr);
1158 		if (!(vma->vm_file && (vma->vm_flags & VM_SHARED) &&
1159 			!(vma->vm_flags & (VM_IO | VM_PFNMAP))))
1160 			goto next;
1161 
1162 		map_file = kzalloc_obj(*map_file);
1163 		if (!map_file) {
1164 			ret = -ENOMEM;
1165 			break;
1166 		}
1167 		offset = (vma->vm_pgoff << PAGE_SHIFT) + uaddr - vma->vm_start;
1168 		map_file->offset = offset;
1169 		map_file->file = get_file(vma->vm_file);
1170 		ret = vhost_vdpa_map(v, iotlb, map_iova, map_size, uaddr,
1171 				     perm, map_file);
1172 		if (ret) {
1173 			fput(map_file->file);
1174 			kfree(map_file);
1175 			break;
1176 		}
1177 next:
1178 		size -= map_size;
1179 		uaddr += map_size;
1180 		map_iova += map_size;
1181 	}
1182 	if (ret)
1183 		vhost_vdpa_unmap(v, iotlb, iova, map_iova - iova);
1184 
1185 	mmap_read_unlock(dev->mm);
1186 
1187 	return ret;
1188 }
1189 
1190 static int vhost_vdpa_pa_map(struct vhost_vdpa *v,
1191 			     struct vhost_iotlb *iotlb,
1192 			     u64 iova, u64 size, u64 uaddr, u32 perm)
1193 {
1194 	struct vhost_dev *dev = &v->vdev;
1195 	struct page **page_list;
1196 	unsigned long list_size = PAGE_SIZE / sizeof(struct page *);
1197 	unsigned int gup_flags = FOLL_LONGTERM;
1198 	unsigned long npages, cur_base, map_pfn, last_pfn = 0;
1199 	unsigned long lock_limit, sz2pin, i;
1200 	unsigned long page_offset;
1201 	u64 start = iova;
1202 	long pinned;
1203 	int ret = 0;
1204 
1205 	/* Limit the use of memory for bookkeeping */
1206 	page_list = (struct page **) __get_free_page(GFP_KERNEL);
1207 	if (!page_list)
1208 		return -ENOMEM;
1209 
1210 	if (perm & VHOST_ACCESS_WO)
1211 		gup_flags |= FOLL_WRITE;
1212 
1213 	page_offset = iova & ~PAGE_MASK;
1214 	if (size > ULONG_MAX - page_offset) {
1215 		ret = -EINVAL;
1216 		goto free;
1217 	}
1218 
1219 	npages = PFN_UP(size + page_offset);
1220 	if (!npages) {
1221 		ret = -EINVAL;
1222 		goto free;
1223 	}
1224 
1225 	mmap_read_lock(dev->mm);
1226 
1227 	lock_limit = PFN_DOWN(rlimit(RLIMIT_MEMLOCK));
1228 	if (npages + atomic64_read(&dev->mm->pinned_vm) > lock_limit) {
1229 		ret = -ENOMEM;
1230 		goto unlock;
1231 	}
1232 
1233 	cur_base = uaddr & PAGE_MASK;
1234 	iova &= PAGE_MASK;
1235 
1236 	while (npages) {
1237 		sz2pin = min_t(unsigned long, npages, list_size);
1238 		pinned = pin_user_pages(cur_base, sz2pin,
1239 					gup_flags, page_list);
1240 		if (sz2pin != pinned) {
1241 			if (pinned < 0) {
1242 				ret = pinned;
1243 			} else {
1244 				unpin_user_pages(page_list, pinned);
1245 				ret = -ENOMEM;
1246 			}
1247 			goto out;
1248 		}
1249 
1250 		if (!last_pfn)
1251 			map_pfn = page_to_pfn(page_list[0]);
1252 
1253 		for (i = 0; i < pinned; i++) {
1254 			unsigned long this_pfn = page_to_pfn(page_list[i]);
1255 			u64 csize;
1256 
1257 			if (last_pfn && (this_pfn != last_pfn + 1)) {
1258 				/* Pin a contiguous chunk of memory */
1259 				csize = PFN_PHYS(last_pfn - map_pfn + 1);
1260 				ret = vhost_vdpa_map(v, iotlb, iova, csize,
1261 						     PFN_PHYS(map_pfn),
1262 						     perm, NULL);
1263 				if (ret) {
1264 					/*
1265 					 * Unpin the pages that are left unmapped
1266 					 * from this point on in the current
1267 					 * page_list. The remaining outstanding
1268 					 * ones which may stride across several
1269 					 * chunks will be covered in the common
1270 					 * error path subsequently.
1271 					 */
1272 					unpin_user_pages(&page_list[i],
1273 							 pinned - i);
1274 					goto out;
1275 				}
1276 
1277 				map_pfn = this_pfn;
1278 				iova += csize;
1279 			}
1280 
1281 			last_pfn = this_pfn;
1282 		}
1283 
1284 		cur_base += PFN_PHYS(pinned);
1285 		npages -= pinned;
1286 	}
1287 
1288 	/* Pin the rest chunk */
1289 	ret = vhost_vdpa_map(v, iotlb, iova, PFN_PHYS(last_pfn - map_pfn + 1),
1290 			     PFN_PHYS(map_pfn), perm, NULL);
1291 out:
1292 	if (ret) {
1293 		if (last_pfn) {
1294 			/*
1295 			 * Unpin the outstanding pages which are yet to be
1296 			 * mapped but haven't due to vdpa_map() or
1297 			 * pin_user_pages() failure.
1298 			 *
1299 			 * Mapped pages are accounted in vdpa_map(), hence
1300 			 * the corresponding unpinning will be handled by
1301 			 * vdpa_unmap().
1302 			 */
1303 			unpin_user_page_range_dirty_lock(pfn_to_page(map_pfn),
1304 							 last_pfn - map_pfn + 1,
1305 							 false);
1306 		}
1307 		vhost_vdpa_unmap(v, iotlb, start, size);
1308 	}
1309 unlock:
1310 	mmap_read_unlock(dev->mm);
1311 free:
1312 	free_page((unsigned long)page_list);
1313 	return ret;
1314 
1315 }
1316 
1317 static int vhost_vdpa_process_iotlb_update(struct vhost_vdpa *v,
1318 					   struct vhost_iotlb *iotlb,
1319 					   struct vhost_iotlb_msg *msg)
1320 {
1321 	struct vdpa_device *vdpa = v->vdpa;
1322 
1323 	if (msg->iova < v->range.first || !msg->size ||
1324 	    msg->iova > U64_MAX - msg->size + 1 ||
1325 	    msg->iova + msg->size - 1 > v->range.last)
1326 		return -EINVAL;
1327 
1328 	if (vhost_iotlb_itree_first(iotlb, msg->iova,
1329 				    msg->iova + msg->size - 1))
1330 		return -EEXIST;
1331 
1332 	if (vdpa->use_va)
1333 		return vhost_vdpa_va_map(v, iotlb, msg->iova, msg->size,
1334 					 msg->uaddr, msg->perm);
1335 
1336 	return vhost_vdpa_pa_map(v, iotlb, msg->iova, msg->size, msg->uaddr,
1337 				 msg->perm);
1338 }
1339 
1340 static int vhost_vdpa_process_iotlb_msg(struct vhost_dev *dev, u32 asid,
1341 					struct vhost_iotlb_msg *msg)
1342 {
1343 	struct vhost_vdpa *v = container_of(dev, struct vhost_vdpa, vdev);
1344 	struct vdpa_device *vdpa = v->vdpa;
1345 	const struct vdpa_config_ops *ops = vdpa->config;
1346 	struct vhost_iotlb *iotlb = NULL;
1347 	struct vhost_vdpa_as *as = NULL;
1348 	int r = 0;
1349 
1350 	mutex_lock(&dev->mutex);
1351 
1352 	r = vhost_dev_check_owner(dev);
1353 	if (r)
1354 		goto unlock;
1355 
1356 	if (msg->type == VHOST_IOTLB_UPDATE ||
1357 	    msg->type == VHOST_IOTLB_BATCH_BEGIN) {
1358 		as = vhost_vdpa_find_alloc_as(v, asid);
1359 		if (!as) {
1360 			dev_err(&v->dev, "can't find and alloc asid %d\n",
1361 				asid);
1362 			r = -EINVAL;
1363 			goto unlock;
1364 		}
1365 		iotlb = &as->iotlb;
1366 	} else
1367 		iotlb = asid_to_iotlb(v, asid);
1368 
1369 	if ((v->in_batch && v->batch_asid != asid) || !iotlb) {
1370 		if (v->in_batch && v->batch_asid != asid) {
1371 			dev_info(&v->dev, "batch id %d asid %d\n",
1372 				 v->batch_asid, asid);
1373 		}
1374 		if (!iotlb)
1375 			dev_err(&v->dev, "no iotlb for asid %d\n", asid);
1376 		r = -EINVAL;
1377 		goto unlock;
1378 	}
1379 
1380 	switch (msg->type) {
1381 	case VHOST_IOTLB_UPDATE:
1382 		r = vhost_vdpa_process_iotlb_update(v, iotlb, msg);
1383 		break;
1384 	case VHOST_IOTLB_INVALIDATE:
1385 		if (!msg->size || msg->iova > U64_MAX - msg->size + 1) {
1386 			r = -EINVAL;
1387 			break;
1388 		}
1389 		r = vhost_vdpa_unmap(v, iotlb, msg->iova, msg->size);
1390 		break;
1391 	case VHOST_IOTLB_BATCH_BEGIN:
1392 		v->batch_asid = asid;
1393 		v->in_batch = true;
1394 		break;
1395 	case VHOST_IOTLB_BATCH_END:
1396 		if (v->in_batch && ops->set_map)
1397 			ops->set_map(vdpa, asid, iotlb);
1398 		v->in_batch = false;
1399 		break;
1400 	default:
1401 		r = -EINVAL;
1402 		break;
1403 	}
1404 unlock:
1405 	mutex_unlock(&dev->mutex);
1406 
1407 	return r;
1408 }
1409 
1410 static ssize_t vhost_vdpa_chr_write_iter(struct kiocb *iocb,
1411 					 struct iov_iter *from)
1412 {
1413 	struct file *file = iocb->ki_filp;
1414 	struct vhost_vdpa *v = file->private_data;
1415 	struct vhost_dev *dev = &v->vdev;
1416 
1417 	return vhost_chr_write_iter(dev, from);
1418 }
1419 
1420 static int vhost_vdpa_alloc_domain(struct vhost_vdpa *v)
1421 {
1422 	struct vdpa_device *vdpa = v->vdpa;
1423 	const struct vdpa_config_ops *ops = vdpa->config;
1424 	union virtio_map map = vdpa_get_map(vdpa);
1425 	struct device *dma_dev = map.dma_dev;
1426 	int ret;
1427 
1428 	/* Device want to do DMA by itself */
1429 	if (ops->set_map || ops->dma_map)
1430 		return 0;
1431 
1432 	if (!device_iommu_capable(dma_dev, IOMMU_CAP_CACHE_COHERENCY)) {
1433 		dev_warn_once(&v->dev,
1434 			      "Failed to allocate domain, device is not IOMMU cache coherent capable\n");
1435 		return -ENOTSUPP;
1436 	}
1437 
1438 	v->domain = iommu_paging_domain_alloc(dma_dev);
1439 	if (IS_ERR(v->domain)) {
1440 		ret = PTR_ERR(v->domain);
1441 		v->domain = NULL;
1442 		return ret;
1443 	}
1444 
1445 	ret = iommu_attach_device(v->domain, dma_dev);
1446 	if (ret)
1447 		goto err_attach;
1448 
1449 	return 0;
1450 
1451 err_attach:
1452 	iommu_domain_free(v->domain);
1453 	v->domain = NULL;
1454 	return ret;
1455 }
1456 
1457 static void vhost_vdpa_free_domain(struct vhost_vdpa *v)
1458 {
1459 	struct vdpa_device *vdpa = v->vdpa;
1460 	union virtio_map map = vdpa_get_map(vdpa);
1461 	struct device *dma_dev = map.dma_dev;
1462 
1463 	if (v->domain) {
1464 		iommu_detach_device(v->domain, dma_dev);
1465 		iommu_domain_free(v->domain);
1466 	}
1467 
1468 	v->domain = NULL;
1469 }
1470 
1471 static void vhost_vdpa_set_iova_range(struct vhost_vdpa *v)
1472 {
1473 	struct vdpa_iova_range *range = &v->range;
1474 	struct vdpa_device *vdpa = v->vdpa;
1475 	const struct vdpa_config_ops *ops = vdpa->config;
1476 
1477 	if (ops->get_iova_range) {
1478 		*range = ops->get_iova_range(vdpa);
1479 	} else if (v->domain && v->domain->geometry.force_aperture) {
1480 		range->first = v->domain->geometry.aperture_start;
1481 		range->last = v->domain->geometry.aperture_end;
1482 	} else {
1483 		range->first = 0;
1484 		range->last = ULLONG_MAX;
1485 	}
1486 }
1487 
1488 static void vhost_vdpa_cleanup(struct vhost_vdpa *v)
1489 {
1490 	struct vhost_vdpa_as *as;
1491 	u32 asid;
1492 
1493 	for (asid = 0; asid < v->vdpa->nas; asid++) {
1494 		as = asid_to_as(v, asid);
1495 		if (as)
1496 			vhost_vdpa_remove_as(v, asid);
1497 	}
1498 
1499 	vhost_vdpa_free_domain(v);
1500 	vhost_dev_cleanup(&v->vdev, false);
1501 	kfree(v->vdev.vqs);
1502 	v->vdev.vqs = NULL;
1503 }
1504 
1505 static int vhost_vdpa_open(struct inode *inode, struct file *filep)
1506 {
1507 	struct vhost_vdpa *v;
1508 	struct vhost_dev *dev;
1509 	struct vhost_virtqueue **vqs;
1510 	int r, opened;
1511 	u32 i, nvqs;
1512 
1513 	v = container_of(inode->i_cdev, struct vhost_vdpa, cdev);
1514 
1515 	opened = atomic_cmpxchg(&v->opened, 0, 1);
1516 	if (opened)
1517 		return -EBUSY;
1518 
1519 	nvqs = v->nvqs;
1520 	r = vhost_vdpa_reset(v);
1521 	if (r)
1522 		goto err;
1523 
1524 	vqs = kmalloc_objs(*vqs, nvqs);
1525 	if (!vqs) {
1526 		r = -ENOMEM;
1527 		goto err;
1528 	}
1529 
1530 	dev = &v->vdev;
1531 	for (i = 0; i < nvqs; i++) {
1532 		vqs[i] = &v->vqs[i];
1533 		vqs[i]->handle_kick = handle_vq_kick;
1534 		vqs[i]->call_ctx.ctx = NULL;
1535 	}
1536 	vhost_dev_init(dev, vqs, nvqs, 0, 0, 0, false,
1537 		       vhost_vdpa_process_iotlb_msg);
1538 
1539 	r = vhost_vdpa_alloc_domain(v);
1540 	if (r)
1541 		goto err_alloc_domain;
1542 
1543 	vhost_vdpa_set_iova_range(v);
1544 
1545 	filep->private_data = v;
1546 
1547 	return 0;
1548 
1549 err_alloc_domain:
1550 	vhost_vdpa_cleanup(v);
1551 err:
1552 	atomic_dec(&v->opened);
1553 	return r;
1554 }
1555 
1556 static void vhost_vdpa_clean_irq(struct vhost_vdpa *v)
1557 {
1558 	u32 i;
1559 
1560 	for (i = 0; i < v->nvqs; i++)
1561 		vhost_vdpa_unsetup_vq_irq(v, i);
1562 }
1563 
1564 static int vhost_vdpa_release(struct inode *inode, struct file *filep)
1565 {
1566 	struct vhost_vdpa *v = filep->private_data;
1567 	struct vhost_dev *d = &v->vdev;
1568 
1569 	mutex_lock(&d->mutex);
1570 	filep->private_data = NULL;
1571 	vhost_vdpa_clean_irq(v);
1572 	vhost_vdpa_reset(v);
1573 	vhost_dev_stop(&v->vdev);
1574 	vhost_vdpa_unbind_mm(v);
1575 	vhost_vdpa_config_put(v);
1576 	vhost_vdpa_cleanup(v);
1577 	mutex_unlock(&d->mutex);
1578 
1579 	atomic_dec(&v->opened);
1580 	complete(&v->completion);
1581 
1582 	return 0;
1583 }
1584 
1585 #ifdef CONFIG_MMU
1586 static int
1587 vhost_vdpa_get_vq_notification(struct vhost_vdpa *v, unsigned long index,
1588 			       struct vdpa_notification_area *notify)
1589 {
1590 	struct vdpa_device *vdpa = v->vdpa;
1591 	const struct vdpa_config_ops *ops = vdpa->config;
1592 
1593 	if (index > 65535 || index >= v->nvqs)
1594 		return -EINVAL;
1595 
1596 	index = array_index_nospec(index, v->nvqs);
1597 
1598 	*notify = ops->get_vq_notification(vdpa, index);
1599 
1600 	return 0;
1601 }
1602 
1603 static vm_fault_t vhost_vdpa_fault(struct vm_fault *vmf)
1604 {
1605 	struct vhost_vdpa *v = vmf->vma->vm_file->private_data;
1606 	struct vdpa_notification_area notify;
1607 	struct vm_area_struct *vma = vmf->vma;
1608 	unsigned long index = vma->vm_pgoff;
1609 
1610 	if (vhost_vdpa_get_vq_notification(v, index, &notify))
1611 		return VM_FAULT_SIGBUS;
1612 
1613 	return vmf_insert_pfn(vma, vmf->address & PAGE_MASK, PFN_DOWN(notify.addr));
1614 }
1615 
1616 static const struct vm_operations_struct vhost_vdpa_vm_ops = {
1617 	.fault = vhost_vdpa_fault,
1618 };
1619 
1620 static int vhost_vdpa_mmap(struct file *file, struct vm_area_struct *vma)
1621 {
1622 	struct vhost_vdpa *v = vma->vm_file->private_data;
1623 	struct vdpa_device *vdpa = v->vdpa;
1624 	const struct vdpa_config_ops *ops = vdpa->config;
1625 	struct vdpa_notification_area notify;
1626 	unsigned long index = vma->vm_pgoff;
1627 
1628 	if (vma->vm_end - vma->vm_start != PAGE_SIZE)
1629 		return -EINVAL;
1630 	if ((vma->vm_flags & VM_SHARED) == 0)
1631 		return -EINVAL;
1632 	if (vma->vm_flags & VM_READ)
1633 		return -EINVAL;
1634 	if (!ops->get_vq_notification)
1635 		return -ENOTSUPP;
1636 
1637 	/* To be safe and easily modelled by userspace, We only
1638 	 * support the doorbell which sits on the page boundary and
1639 	 * does not share the page with other registers.
1640 	 */
1641 	if (vhost_vdpa_get_vq_notification(v, index, &notify))
1642 		return -EINVAL;
1643 	if (notify.addr & (PAGE_SIZE - 1))
1644 		return -EINVAL;
1645 	if (vma->vm_end - vma->vm_start != notify.size)
1646 		return -ENOTSUPP;
1647 
1648 	vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
1649 	vm_flags_set(vma, VM_IO | VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP);
1650 	vma->vm_ops = &vhost_vdpa_vm_ops;
1651 	return 0;
1652 }
1653 #endif /* CONFIG_MMU */
1654 
1655 static const struct file_operations vhost_vdpa_fops = {
1656 	.owner		= THIS_MODULE,
1657 	.open		= vhost_vdpa_open,
1658 	.release	= vhost_vdpa_release,
1659 	.write_iter	= vhost_vdpa_chr_write_iter,
1660 	.unlocked_ioctl	= vhost_vdpa_unlocked_ioctl,
1661 #ifdef CONFIG_MMU
1662 	.mmap		= vhost_vdpa_mmap,
1663 #endif /* CONFIG_MMU */
1664 	.compat_ioctl	= compat_ptr_ioctl,
1665 };
1666 
1667 static void vhost_vdpa_release_dev(struct device *device)
1668 {
1669 	struct vhost_vdpa *v =
1670 	       container_of(device, struct vhost_vdpa, dev);
1671 
1672 	ida_free(&vhost_vdpa_ida, v->minor);
1673 	kfree(v->vqs);
1674 	kfree(v);
1675 }
1676 
1677 static int vhost_vdpa_probe(struct vdpa_device *vdpa)
1678 {
1679 	const struct vdpa_config_ops *ops = vdpa->config;
1680 	struct vhost_vdpa *v;
1681 	int minor;
1682 	int i, r;
1683 
1684 	/* We can't support platform IOMMU device with more than 1
1685 	 * group or as
1686 	 */
1687 	if (!ops->set_map && !ops->dma_map &&
1688 	    (vdpa->ngroups > 1 || vdpa->nas > 1))
1689 		return -EOPNOTSUPP;
1690 
1691 	v = kzalloc_obj(*v, GFP_KERNEL | __GFP_RETRY_MAYFAIL);
1692 	if (!v)
1693 		return -ENOMEM;
1694 
1695 	minor = ida_alloc_max(&vhost_vdpa_ida, VHOST_VDPA_DEV_MAX - 1,
1696 			      GFP_KERNEL);
1697 	if (minor < 0) {
1698 		kfree(v);
1699 		return minor;
1700 	}
1701 
1702 	atomic_set(&v->opened, 1);
1703 	spin_lock_init(&v->config_lock);
1704 	v->minor = minor;
1705 	v->vdpa = vdpa;
1706 	v->nvqs = vdpa->nvqs;
1707 	v->virtio_id = ops->get_device_id(vdpa);
1708 
1709 	device_initialize(&v->dev);
1710 	v->dev.release = vhost_vdpa_release_dev;
1711 	v->dev.parent = &vdpa->dev;
1712 	v->dev.devt = MKDEV(MAJOR(vhost_vdpa_major), minor);
1713 	v->vqs = kmalloc_objs(struct vhost_virtqueue, v->nvqs);
1714 	if (!v->vqs) {
1715 		r = -ENOMEM;
1716 		goto err;
1717 	}
1718 
1719 	r = dev_set_name(&v->dev, "vhost-vdpa-%u", minor);
1720 	if (r)
1721 		goto err;
1722 
1723 	cdev_init(&v->cdev, &vhost_vdpa_fops);
1724 	v->cdev.owner = THIS_MODULE;
1725 	init_completion(&v->completion);
1726 	for (i = 0; i < VHOST_VDPA_IOTLB_BUCKETS; i++)
1727 		INIT_HLIST_HEAD(&v->as[i]);
1728 
1729 	r = cdev_device_add(&v->cdev, &v->dev);
1730 	if (r)
1731 		goto err;
1732 
1733 	vdpa_set_drvdata(vdpa, v);
1734 
1735 	atomic_set_release(&v->opened, 0);
1736 
1737 	return 0;
1738 
1739 err:
1740 	put_device(&v->dev);
1741 	return r;
1742 }
1743 
1744 static void vhost_vdpa_remove(struct vdpa_device *vdpa)
1745 {
1746 	struct vhost_vdpa *v = vdpa_get_drvdata(vdpa);
1747 	int opened;
1748 
1749 	cdev_device_del(&v->cdev, &v->dev);
1750 
1751 	do {
1752 		opened = atomic_cmpxchg(&v->opened, 0, 1);
1753 		if (!opened)
1754 			break;
1755 		wait_for_completion(&v->completion);
1756 	} while (1);
1757 
1758 	put_device(&v->dev);
1759 }
1760 
1761 static struct vdpa_driver vhost_vdpa_driver = {
1762 	.driver = {
1763 		.name	= "vhost_vdpa",
1764 	},
1765 	.probe	= vhost_vdpa_probe,
1766 	.remove	= vhost_vdpa_remove,
1767 };
1768 
1769 static int __init vhost_vdpa_init(void)
1770 {
1771 	int r;
1772 
1773 	r = alloc_chrdev_region(&vhost_vdpa_major, 0, VHOST_VDPA_DEV_MAX,
1774 				"vhost-vdpa");
1775 	if (r)
1776 		goto err_alloc_chrdev;
1777 
1778 	r = vdpa_register_driver(&vhost_vdpa_driver);
1779 	if (r)
1780 		goto err_vdpa_register_driver;
1781 
1782 	return 0;
1783 
1784 err_vdpa_register_driver:
1785 	unregister_chrdev_region(vhost_vdpa_major, VHOST_VDPA_DEV_MAX);
1786 err_alloc_chrdev:
1787 	return r;
1788 }
1789 module_init(vhost_vdpa_init);
1790 
1791 static void __exit vhost_vdpa_exit(void)
1792 {
1793 	vdpa_unregister_driver(&vhost_vdpa_driver);
1794 	unregister_chrdev_region(vhost_vdpa_major, VHOST_VDPA_DEV_MAX);
1795 }
1796 module_exit(vhost_vdpa_exit);
1797 
1798 MODULE_VERSION("0.0.1");
1799 MODULE_LICENSE("GPL v2");
1800 MODULE_AUTHOR("Intel Corporation");
1801 MODULE_DESCRIPTION("vDPA-based vhost backend for virtio");
1802