xref: /linux/fs/fuse/virtio_fs.c (revision 5ea5880764cbb164afb17a62e76ca75dc371409d)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * virtio-fs: Virtio Filesystem
4  * Copyright (C) 2018 Red Hat, Inc.
5  */
6 
7 #include <linux/fs.h>
8 #include <linux/dax.h>
9 #include <linux/pci.h>
10 #include <linux/interrupt.h>
11 #include <linux/group_cpus.h>
12 #include <linux/memremap.h>
13 #include <linux/module.h>
14 #include <linux/virtio.h>
15 #include <linux/virtio_fs.h>
16 #include <linux/delay.h>
17 #include <linux/fs_context.h>
18 #include <linux/fs_parser.h>
19 #include <linux/highmem.h>
20 #include <linux/cleanup.h>
21 #include <linux/uio.h>
22 #include "fuse_i.h"
23 #include "fuse_dev_i.h"
24 
25 /* Used to help calculate the FUSE connection's max_pages limit for a request's
26  * size. Parts of the struct fuse_req are sliced into scattergather lists in
27  * addition to the pages used, so this can help account for that overhead.
28  */
29 #define FUSE_HEADER_OVERHEAD    4
30 
31 /* List of virtio-fs device instances and a lock for the list. Also provides
32  * mutual exclusion in device removal and mounting path
33  */
34 static DEFINE_MUTEX(virtio_fs_mutex);
35 static LIST_HEAD(virtio_fs_instances);
36 
37 /* The /sys/fs/virtio_fs/ kset */
38 static struct kset *virtio_fs_kset;
39 
40 enum {
41 	VQ_HIPRIO,
42 	VQ_REQUEST
43 };
44 
45 #define VQ_NAME_LEN	24
46 
47 /* Per-virtqueue state */
48 struct virtio_fs_vq {
49 	spinlock_t lock;
50 	struct virtqueue *vq;     /* protected by ->lock */
51 	struct work_struct done_work;
52 	struct list_head queued_reqs;
53 	struct list_head end_reqs;	/* End these requests */
54 	struct work_struct dispatch_work;
55 	struct fuse_dev *fud;
56 	bool connected;
57 	long in_flight;
58 	struct completion in_flight_zero; /* No inflight requests */
59 	struct kobject *kobj;
60 	char name[VQ_NAME_LEN];
61 } ____cacheline_aligned_in_smp;
62 
63 /* A virtio-fs device instance */
64 struct virtio_fs {
65 	struct kobject kobj;
66 	struct kobject *mqs_kobj;
67 	struct list_head list;    /* on virtio_fs_instances */
68 	char *tag;
69 	struct virtio_fs_vq *vqs;
70 	unsigned int nvqs;               /* number of virtqueues */
71 	unsigned int num_request_queues; /* number of request queues */
72 	struct dax_device *dax_dev;
73 
74 	unsigned int *mq_map; /* index = cpu id, value = request vq id */
75 
76 	/* DAX memory window where file contents are mapped */
77 	void *window_kaddr;
78 	phys_addr_t window_phys_addr;
79 	size_t window_len;
80 };
81 
82 struct virtio_fs_forget_req {
83 	struct fuse_in_header ih;
84 	struct fuse_forget_in arg;
85 };
86 
87 struct virtio_fs_forget {
88 	/* This request can be temporarily queued on virt queue */
89 	struct list_head list;
90 	struct virtio_fs_forget_req req;
91 };
92 
93 struct virtio_fs_req_work {
94 	struct fuse_req *req;
95 	struct virtio_fs_vq *fsvq;
96 	struct work_struct done_work;
97 };
98 
99 static int virtio_fs_enqueue_req(struct virtio_fs_vq *fsvq,
100 				 struct fuse_req *req, bool in_flight,
101 				 gfp_t gfp);
102 
103 static const struct constant_table dax_param_enums[] = {
104 	{"always",	FUSE_DAX_ALWAYS },
105 	{"never",	FUSE_DAX_NEVER },
106 	{"inode",	FUSE_DAX_INODE_USER },
107 	{}
108 };
109 
110 enum {
111 	OPT_DAX,
112 	OPT_DAX_ENUM,
113 };
114 
115 static const struct fs_parameter_spec virtio_fs_parameters[] = {
116 	fsparam_flag("dax", OPT_DAX),
117 	fsparam_enum("dax", OPT_DAX_ENUM, dax_param_enums),
118 	{}
119 };
120 
121 static int virtio_fs_parse_param(struct fs_context *fsc,
122 				 struct fs_parameter *param)
123 {
124 	struct fs_parse_result result;
125 	struct fuse_fs_context *ctx = fsc->fs_private;
126 	int opt;
127 
128 	opt = fs_parse(fsc, virtio_fs_parameters, param, &result);
129 	if (opt < 0)
130 		return opt;
131 
132 	switch (opt) {
133 	case OPT_DAX:
134 		ctx->dax_mode = FUSE_DAX_ALWAYS;
135 		break;
136 	case OPT_DAX_ENUM:
137 		ctx->dax_mode = result.uint_32;
138 		break;
139 	default:
140 		return -EINVAL;
141 	}
142 
143 	return 0;
144 }
145 
146 static void virtio_fs_free_fsc(struct fs_context *fsc)
147 {
148 	struct fuse_fs_context *ctx = fsc->fs_private;
149 
150 	kfree(ctx);
151 }
152 
153 static inline struct virtio_fs_vq *vq_to_fsvq(struct virtqueue *vq)
154 {
155 	struct virtio_fs *fs = vq->vdev->priv;
156 
157 	return &fs->vqs[vq->index];
158 }
159 
160 /* Should be called with fsvq->lock held. */
161 static inline void inc_in_flight_req(struct virtio_fs_vq *fsvq)
162 {
163 	fsvq->in_flight++;
164 }
165 
166 /* Should be called with fsvq->lock held. */
167 static inline void dec_in_flight_req(struct virtio_fs_vq *fsvq)
168 {
169 	WARN_ON(fsvq->in_flight <= 0);
170 	fsvq->in_flight--;
171 	if (!fsvq->in_flight)
172 		complete(&fsvq->in_flight_zero);
173 }
174 
175 static ssize_t tag_show(struct kobject *kobj,
176 		struct kobj_attribute *attr, char *buf)
177 {
178 	struct virtio_fs *fs = container_of(kobj, struct virtio_fs, kobj);
179 
180 	return sysfs_emit(buf, "%s\n", fs->tag);
181 }
182 
183 static struct kobj_attribute virtio_fs_tag_attr = __ATTR_RO(tag);
184 
185 static struct attribute *virtio_fs_attrs[] = {
186 	&virtio_fs_tag_attr.attr,
187 	NULL
188 };
189 ATTRIBUTE_GROUPS(virtio_fs);
190 
191 static void virtio_fs_ktype_release(struct kobject *kobj)
192 {
193 	struct virtio_fs *vfs = container_of(kobj, struct virtio_fs, kobj);
194 
195 	kfree(vfs->mq_map);
196 	kfree(vfs->vqs);
197 	kfree(vfs);
198 }
199 
200 static const struct kobj_type virtio_fs_ktype = {
201 	.release = virtio_fs_ktype_release,
202 	.sysfs_ops = &kobj_sysfs_ops,
203 	.default_groups = virtio_fs_groups,
204 };
205 
206 static struct virtio_fs_vq *virtio_fs_kobj_to_vq(struct virtio_fs *fs,
207 		struct kobject *kobj)
208 {
209 	int i;
210 
211 	for (i = 0; i < fs->nvqs; i++) {
212 		if (kobj == fs->vqs[i].kobj)
213 			return &fs->vqs[i];
214 	}
215 	return NULL;
216 }
217 
218 static ssize_t name_show(struct kobject *kobj,
219 		struct kobj_attribute *attr, char *buf)
220 {
221 	struct virtio_fs *fs = container_of(kobj->parent->parent, struct virtio_fs, kobj);
222 	struct virtio_fs_vq *fsvq = virtio_fs_kobj_to_vq(fs, kobj);
223 
224 	if (!fsvq)
225 		return -EINVAL;
226 	return sysfs_emit(buf, "%s\n", fsvq->name);
227 }
228 
229 static struct kobj_attribute virtio_fs_vq_name_attr = __ATTR_RO(name);
230 
231 static ssize_t cpu_list_show(struct kobject *kobj,
232 		struct kobj_attribute *attr, char *buf)
233 {
234 	struct virtio_fs *fs = container_of(kobj->parent->parent, struct virtio_fs, kobj);
235 	struct virtio_fs_vq *fsvq = virtio_fs_kobj_to_vq(fs, kobj);
236 	unsigned int cpu, qid;
237 	const size_t size = PAGE_SIZE - 1;
238 	bool first = true;
239 	int ret = 0, pos = 0;
240 
241 	if (!fsvq)
242 		return -EINVAL;
243 
244 	qid = fsvq->vq->index;
245 	for (cpu = 0; cpu < nr_cpu_ids; cpu++) {
246 		if (qid < VQ_REQUEST || (fs->mq_map[cpu] == qid)) {
247 			if (first)
248 				ret = snprintf(buf + pos, size - pos, "%u", cpu);
249 			else
250 				ret = snprintf(buf + pos, size - pos, ", %u", cpu);
251 
252 			if (ret >= size - pos)
253 				break;
254 			first = false;
255 			pos += ret;
256 		}
257 	}
258 	ret = snprintf(buf + pos, size + 1 - pos, "\n");
259 	return pos + ret;
260 }
261 
262 static struct kobj_attribute virtio_fs_vq_cpu_list_attr = __ATTR_RO(cpu_list);
263 
264 static struct attribute *virtio_fs_vq_attrs[] = {
265 	&virtio_fs_vq_name_attr.attr,
266 	&virtio_fs_vq_cpu_list_attr.attr,
267 	NULL
268 };
269 
270 static struct attribute_group virtio_fs_vq_attr_group = {
271 	.attrs = virtio_fs_vq_attrs,
272 };
273 
274 /* Make sure virtiofs_mutex is held */
275 static void virtio_fs_put_locked(struct virtio_fs *fs)
276 {
277 	lockdep_assert_held(&virtio_fs_mutex);
278 
279 	kobject_put(&fs->kobj);
280 }
281 
282 static void virtio_fs_put(struct virtio_fs *fs)
283 {
284 	mutex_lock(&virtio_fs_mutex);
285 	virtio_fs_put_locked(fs);
286 	mutex_unlock(&virtio_fs_mutex);
287 }
288 
289 static void virtio_fs_fiq_release(struct fuse_iqueue *fiq)
290 {
291 	struct virtio_fs *vfs = fiq->priv;
292 
293 	virtio_fs_put(vfs);
294 }
295 
296 static void virtio_fs_drain_queue(struct virtio_fs_vq *fsvq)
297 {
298 	WARN_ON(fsvq->in_flight < 0);
299 
300 	/* Wait for in flight requests to finish.*/
301 	spin_lock(&fsvq->lock);
302 	if (fsvq->in_flight) {
303 		/* We are holding virtio_fs_mutex. There should not be any
304 		 * waiters waiting for completion.
305 		 */
306 		reinit_completion(&fsvq->in_flight_zero);
307 		spin_unlock(&fsvq->lock);
308 		wait_for_completion(&fsvq->in_flight_zero);
309 	} else {
310 		spin_unlock(&fsvq->lock);
311 	}
312 
313 	flush_work(&fsvq->done_work);
314 	flush_work(&fsvq->dispatch_work);
315 }
316 
317 static void virtio_fs_drain_all_queues_locked(struct virtio_fs *fs)
318 {
319 	struct virtio_fs_vq *fsvq;
320 	int i;
321 
322 	for (i = 0; i < fs->nvqs; i++) {
323 		fsvq = &fs->vqs[i];
324 		virtio_fs_drain_queue(fsvq);
325 	}
326 }
327 
328 static void virtio_fs_drain_all_queues(struct virtio_fs *fs)
329 {
330 	/* Provides mutual exclusion between ->remove and ->kill_sb
331 	 * paths. We don't want both of these draining queue at the
332 	 * same time. Current completion logic reinits completion
333 	 * and that means there should not be any other thread
334 	 * doing reinit or waiting for completion already.
335 	 */
336 	mutex_lock(&virtio_fs_mutex);
337 	virtio_fs_drain_all_queues_locked(fs);
338 	mutex_unlock(&virtio_fs_mutex);
339 }
340 
341 static void virtio_fs_start_all_queues(struct virtio_fs *fs)
342 {
343 	struct virtio_fs_vq *fsvq;
344 	int i;
345 
346 	for (i = 0; i < fs->nvqs; i++) {
347 		fsvq = &fs->vqs[i];
348 		spin_lock(&fsvq->lock);
349 		fsvq->connected = true;
350 		spin_unlock(&fsvq->lock);
351 	}
352 }
353 
354 static void virtio_fs_delete_queues_sysfs(struct virtio_fs *fs)
355 {
356 	struct virtio_fs_vq *fsvq;
357 	int i;
358 
359 	for (i = 0; i < fs->nvqs; i++) {
360 		fsvq = &fs->vqs[i];
361 		kobject_put(fsvq->kobj);
362 	}
363 }
364 
365 static int virtio_fs_add_queues_sysfs(struct virtio_fs *fs)
366 {
367 	struct virtio_fs_vq *fsvq;
368 	char buff[12];
369 	int i, j, ret;
370 
371 	for (i = 0; i < fs->nvqs; i++) {
372 		fsvq = &fs->vqs[i];
373 
374 		sprintf(buff, "%d", i);
375 		fsvq->kobj = kobject_create_and_add(buff, fs->mqs_kobj);
376 		if (!fsvq->kobj) {
377 			ret = -ENOMEM;
378 			goto out_del;
379 		}
380 
381 		ret = sysfs_create_group(fsvq->kobj, &virtio_fs_vq_attr_group);
382 		if (ret) {
383 			kobject_put(fsvq->kobj);
384 			goto out_del;
385 		}
386 	}
387 
388 	return 0;
389 
390 out_del:
391 	for (j = 0; j < i; j++) {
392 		fsvq = &fs->vqs[j];
393 		kobject_put(fsvq->kobj);
394 	}
395 	return ret;
396 }
397 
398 /* Add a new instance to the list or return -EEXIST if tag name exists*/
399 static int virtio_fs_add_instance(struct virtio_device *vdev,
400 				  struct virtio_fs *fs)
401 {
402 	struct virtio_fs *fs2;
403 	int ret;
404 
405 	mutex_lock(&virtio_fs_mutex);
406 
407 	list_for_each_entry(fs2, &virtio_fs_instances, list) {
408 		if (strcmp(fs->tag, fs2->tag) == 0) {
409 			mutex_unlock(&virtio_fs_mutex);
410 			return -EEXIST;
411 		}
412 	}
413 
414 	/* Use the virtio_device's index as a unique identifier, there is no
415 	 * need to allocate our own identifiers because the virtio_fs instance
416 	 * is only visible to userspace as long as the underlying virtio_device
417 	 * exists.
418 	 */
419 	fs->kobj.kset = virtio_fs_kset;
420 	ret = kobject_add(&fs->kobj, NULL, "%d", vdev->index);
421 	if (ret < 0)
422 		goto out_unlock;
423 
424 	fs->mqs_kobj = kobject_create_and_add("mqs", &fs->kobj);
425 	if (!fs->mqs_kobj) {
426 		ret = -ENOMEM;
427 		goto out_del;
428 	}
429 
430 	ret = sysfs_create_link(&fs->kobj, &vdev->dev.kobj, "device");
431 	if (ret < 0)
432 		goto out_put;
433 
434 	ret = virtio_fs_add_queues_sysfs(fs);
435 	if (ret)
436 		goto out_remove;
437 
438 	list_add_tail(&fs->list, &virtio_fs_instances);
439 
440 	mutex_unlock(&virtio_fs_mutex);
441 
442 	kobject_uevent(&fs->kobj, KOBJ_ADD);
443 
444 	return 0;
445 
446 out_remove:
447 	sysfs_remove_link(&fs->kobj, "device");
448 out_put:
449 	kobject_put(fs->mqs_kobj);
450 out_del:
451 	kobject_del(&fs->kobj);
452 out_unlock:
453 	mutex_unlock(&virtio_fs_mutex);
454 	return ret;
455 }
456 
457 /* Return the virtio_fs with a given tag, or NULL */
458 static struct virtio_fs *virtio_fs_find_instance(const char *tag)
459 {
460 	struct virtio_fs *fs;
461 
462 	mutex_lock(&virtio_fs_mutex);
463 
464 	list_for_each_entry(fs, &virtio_fs_instances, list) {
465 		if (strcmp(fs->tag, tag) == 0) {
466 			kobject_get(&fs->kobj);
467 			goto found;
468 		}
469 	}
470 
471 	fs = NULL; /* not found */
472 
473 found:
474 	mutex_unlock(&virtio_fs_mutex);
475 
476 	return fs;
477 }
478 
479 static void virtio_fs_free_devs(struct virtio_fs *fs)
480 {
481 	unsigned int i;
482 
483 	for (i = 0; i < fs->nvqs; i++) {
484 		struct virtio_fs_vq *fsvq = &fs->vqs[i];
485 
486 		if (!fsvq->fud)
487 			continue;
488 
489 		fuse_dev_put(fsvq->fud);
490 		fsvq->fud = NULL;
491 	}
492 }
493 
494 /* Read filesystem name from virtio config into fs->tag (must kfree()). */
495 static int virtio_fs_read_tag(struct virtio_device *vdev, struct virtio_fs *fs)
496 {
497 	char tag_buf[sizeof_field(struct virtio_fs_config, tag)];
498 	char *end;
499 	size_t len;
500 
501 	virtio_cread_bytes(vdev, offsetof(struct virtio_fs_config, tag),
502 			   &tag_buf, sizeof(tag_buf));
503 	end = memchr(tag_buf, '\0', sizeof(tag_buf));
504 	if (end == tag_buf)
505 		return -EINVAL; /* empty tag */
506 	if (!end)
507 		end = &tag_buf[sizeof(tag_buf)];
508 
509 	len = end - tag_buf;
510 	fs->tag = devm_kmalloc(&vdev->dev, len + 1, GFP_KERNEL);
511 	if (!fs->tag)
512 		return -ENOMEM;
513 	memcpy(fs->tag, tag_buf, len);
514 	fs->tag[len] = '\0';
515 
516 	/* While the VIRTIO specification allows any character, newlines are
517 	 * awkward on mount(8) command-lines and cause problems in the sysfs
518 	 * "tag" attr and uevent TAG= properties. Forbid them.
519 	 */
520 	if (strchr(fs->tag, '\n')) {
521 		dev_dbg(&vdev->dev, "refusing virtiofs tag with newline character\n");
522 		return -EINVAL;
523 	}
524 
525 	dev_info(&vdev->dev, "discovered new tag: %s\n", fs->tag);
526 	return 0;
527 }
528 
529 /* Work function for hiprio completion */
530 static void virtio_fs_hiprio_done_work(struct work_struct *work)
531 {
532 	struct virtio_fs_vq *fsvq = container_of(work, struct virtio_fs_vq,
533 						 done_work);
534 	struct virtqueue *vq = fsvq->vq;
535 
536 	/* Free completed FUSE_FORGET requests */
537 	spin_lock(&fsvq->lock);
538 	do {
539 		unsigned int len;
540 		void *req;
541 
542 		virtqueue_disable_cb(vq);
543 
544 		while ((req = virtqueue_get_buf(vq, &len)) != NULL) {
545 			kfree(req);
546 			dec_in_flight_req(fsvq);
547 		}
548 	} while (!virtqueue_enable_cb(vq));
549 
550 	if (!list_empty(&fsvq->queued_reqs))
551 		schedule_work(&fsvq->dispatch_work);
552 
553 	spin_unlock(&fsvq->lock);
554 }
555 
556 static void virtio_fs_request_dispatch_work(struct work_struct *work)
557 {
558 	struct fuse_req *req;
559 	struct virtio_fs_vq *fsvq = container_of(work, struct virtio_fs_vq,
560 						 dispatch_work);
561 	int ret;
562 
563 	pr_debug("virtio-fs: worker %s called.\n", __func__);
564 	while (1) {
565 		spin_lock(&fsvq->lock);
566 		req = list_first_entry_or_null(&fsvq->end_reqs, struct fuse_req,
567 					       list);
568 		if (!req) {
569 			spin_unlock(&fsvq->lock);
570 			break;
571 		}
572 
573 		list_del_init(&req->list);
574 		spin_unlock(&fsvq->lock);
575 		fuse_request_end(req);
576 	}
577 
578 	/* Dispatch pending requests */
579 	while (1) {
580 		unsigned int flags;
581 
582 		spin_lock(&fsvq->lock);
583 		req = list_first_entry_or_null(&fsvq->queued_reqs,
584 					       struct fuse_req, list);
585 		if (!req) {
586 			spin_unlock(&fsvq->lock);
587 			return;
588 		}
589 		list_del_init(&req->list);
590 		spin_unlock(&fsvq->lock);
591 
592 		flags = memalloc_nofs_save();
593 		ret = virtio_fs_enqueue_req(fsvq, req, true, GFP_KERNEL);
594 		memalloc_nofs_restore(flags);
595 		if (ret < 0) {
596 			if (ret == -ENOSPC) {
597 				spin_lock(&fsvq->lock);
598 				list_add_tail(&req->list, &fsvq->queued_reqs);
599 				spin_unlock(&fsvq->lock);
600 				return;
601 			}
602 			req->out.h.error = ret;
603 			spin_lock(&fsvq->lock);
604 			dec_in_flight_req(fsvq);
605 			spin_unlock(&fsvq->lock);
606 			pr_err("virtio-fs: virtio_fs_enqueue_req() failed %d\n",
607 			       ret);
608 			fuse_request_end(req);
609 		}
610 	}
611 }
612 
613 /*
614  * Returns 1 if queue is full and sender should wait a bit before sending
615  * next request, 0 otherwise.
616  */
617 static int send_forget_request(struct virtio_fs_vq *fsvq,
618 			       struct virtio_fs_forget *forget,
619 			       bool in_flight)
620 {
621 	struct scatterlist sg;
622 	struct virtqueue *vq;
623 	int ret = 0;
624 	bool notify;
625 	struct virtio_fs_forget_req *req = &forget->req;
626 
627 	spin_lock(&fsvq->lock);
628 	if (!fsvq->connected) {
629 		if (in_flight)
630 			dec_in_flight_req(fsvq);
631 		kfree(forget);
632 		goto out;
633 	}
634 
635 	sg_init_one(&sg, req, sizeof(*req));
636 	vq = fsvq->vq;
637 	dev_dbg(&vq->vdev->dev, "%s\n", __func__);
638 
639 	ret = virtqueue_add_outbuf(vq, &sg, 1, forget, GFP_ATOMIC);
640 	if (ret < 0) {
641 		if (ret == -ENOSPC) {
642 			pr_debug("virtio-fs: Could not queue FORGET: err=%d. Will try later\n",
643 				 ret);
644 			list_add_tail(&forget->list, &fsvq->queued_reqs);
645 			if (!in_flight)
646 				inc_in_flight_req(fsvq);
647 			/* Queue is full */
648 			ret = 1;
649 		} else {
650 			pr_debug("virtio-fs: Could not queue FORGET: err=%d. Dropping it.\n",
651 				 ret);
652 			kfree(forget);
653 			if (in_flight)
654 				dec_in_flight_req(fsvq);
655 		}
656 		goto out;
657 	}
658 
659 	if (!in_flight)
660 		inc_in_flight_req(fsvq);
661 	notify = virtqueue_kick_prepare(vq);
662 	spin_unlock(&fsvq->lock);
663 
664 	if (notify)
665 		virtqueue_notify(vq);
666 	return ret;
667 out:
668 	spin_unlock(&fsvq->lock);
669 	return ret;
670 }
671 
672 static void virtio_fs_hiprio_dispatch_work(struct work_struct *work)
673 {
674 	struct virtio_fs_forget *forget;
675 	struct virtio_fs_vq *fsvq = container_of(work, struct virtio_fs_vq,
676 						 dispatch_work);
677 	pr_debug("virtio-fs: worker %s called.\n", __func__);
678 	while (1) {
679 		spin_lock(&fsvq->lock);
680 		forget = list_first_entry_or_null(&fsvq->queued_reqs,
681 					struct virtio_fs_forget, list);
682 		if (!forget) {
683 			spin_unlock(&fsvq->lock);
684 			return;
685 		}
686 
687 		list_del(&forget->list);
688 		spin_unlock(&fsvq->lock);
689 		if (send_forget_request(fsvq, forget, true))
690 			return;
691 	}
692 }
693 
694 /* Allocate and copy args into req->argbuf */
695 static int copy_args_to_argbuf(struct fuse_req *req, gfp_t gfp)
696 {
697 	struct fuse_args *args = req->args;
698 	unsigned int offset = 0;
699 	unsigned int num_in;
700 	unsigned int num_out;
701 	unsigned int len;
702 	unsigned int i;
703 
704 	num_in = args->in_numargs - args->in_pages;
705 	num_out = args->out_numargs - args->out_pages;
706 	len = fuse_len_args(num_in, (struct fuse_arg *) args->in_args) +
707 	      fuse_len_args(num_out, args->out_args);
708 
709 	req->argbuf = kmalloc(len, gfp);
710 	if (!req->argbuf)
711 		return -ENOMEM;
712 
713 	for (i = 0; i < num_in; i++) {
714 		memcpy(req->argbuf + offset,
715 		       args->in_args[i].value,
716 		       args->in_args[i].size);
717 		offset += args->in_args[i].size;
718 	}
719 
720 	return 0;
721 }
722 
723 /* Copy args out of and free req->argbuf */
724 static void copy_args_from_argbuf(struct fuse_args *args, struct fuse_req *req)
725 {
726 	unsigned int remaining;
727 	unsigned int offset;
728 	unsigned int num_in;
729 	unsigned int num_out;
730 	unsigned int i;
731 
732 	remaining = req->out.h.len - sizeof(req->out.h);
733 	num_in = args->in_numargs - args->in_pages;
734 	num_out = args->out_numargs - args->out_pages;
735 	offset = fuse_len_args(num_in, (struct fuse_arg *)args->in_args);
736 
737 	for (i = 0; i < num_out; i++) {
738 		unsigned int argsize = args->out_args[i].size;
739 
740 		if (args->out_argvar &&
741 		    i == args->out_numargs - 1 &&
742 		    argsize > remaining) {
743 			argsize = remaining;
744 		}
745 
746 		memcpy(args->out_args[i].value, req->argbuf + offset, argsize);
747 		offset += argsize;
748 
749 		if (i != args->out_numargs - 1)
750 			remaining -= argsize;
751 	}
752 
753 	/* Store the actual size of the variable-length arg */
754 	if (args->out_argvar)
755 		args->out_args[args->out_numargs - 1].size = remaining;
756 
757 	kfree(req->argbuf);
758 	req->argbuf = NULL;
759 }
760 
761 /* Verify that the server properly follows the FUSE protocol */
762 static bool virtio_fs_verify_response(struct fuse_req *req, unsigned int len)
763 {
764 	struct fuse_out_header *oh = &req->out.h;
765 
766 	if (len < sizeof(*oh)) {
767 		pr_warn("virtio-fs: response too short (%u)\n", len);
768 		return false;
769 	}
770 	if (oh->len != len) {
771 		pr_warn("virtio-fs: oh.len mismatch (%u != %u)\n", oh->len, len);
772 		return false;
773 	}
774 	if (oh->unique != req->in.h.unique) {
775 		pr_warn("virtio-fs: oh.unique mismatch (%llu != %llu)\n",
776 			oh->unique, req->in.h.unique);
777 		return false;
778 	}
779 	return true;
780 }
781 
782 /* Work function for request completion */
783 static void virtio_fs_request_complete(struct fuse_req *req,
784 				       struct virtio_fs_vq *fsvq)
785 {
786 	struct fuse_args *args;
787 	struct fuse_args_pages *ap;
788 	unsigned int len, i, thislen;
789 	struct folio *folio;
790 
791 	args = req->args;
792 	copy_args_from_argbuf(args, req);
793 
794 	if (args->out_pages && args->page_zeroing) {
795 		len = args->out_args[args->out_numargs - 1].size;
796 		ap = container_of(args, typeof(*ap), args);
797 		for (i = 0; i < ap->num_folios; i++) {
798 			thislen = ap->descs[i].length;
799 			if (len < thislen) {
800 				WARN_ON(ap->descs[i].offset);
801 				folio = ap->folios[i];
802 				folio_zero_segment(folio, len, thislen);
803 				len = 0;
804 			} else {
805 				len -= thislen;
806 			}
807 		}
808 	}
809 
810 	clear_bit(FR_SENT, &req->flags);
811 
812 	fuse_request_end(req);
813 	spin_lock(&fsvq->lock);
814 	dec_in_flight_req(fsvq);
815 	spin_unlock(&fsvq->lock);
816 }
817 
818 static void virtio_fs_complete_req_work(struct work_struct *work)
819 {
820 	struct virtio_fs_req_work *w =
821 		container_of(work, typeof(*w), done_work);
822 
823 	virtio_fs_request_complete(w->req, w->fsvq);
824 	kfree(w);
825 }
826 
827 static void virtio_fs_requests_done_work(struct work_struct *work)
828 {
829 	struct virtio_fs_vq *fsvq = container_of(work, struct virtio_fs_vq,
830 						 done_work);
831 	struct fuse_pqueue *fpq = &fsvq->fud->pq;
832 	struct virtqueue *vq = fsvq->vq;
833 	struct fuse_req *req;
834 	struct fuse_req *next;
835 	unsigned int len;
836 	LIST_HEAD(reqs);
837 
838 	/* Collect completed requests off the virtqueue */
839 	spin_lock(&fsvq->lock);
840 	do {
841 		virtqueue_disable_cb(vq);
842 
843 		while ((req = virtqueue_get_buf(vq, &len)) != NULL) {
844 			if (!virtio_fs_verify_response(req, len)) {
845 				req->out.h.error = -EIO;
846 				req->out.h.len = sizeof(struct fuse_out_header);
847 			}
848 			spin_lock(&fpq->lock);
849 			list_move_tail(&req->list, &reqs);
850 			spin_unlock(&fpq->lock);
851 		}
852 	} while (!virtqueue_enable_cb(vq));
853 	spin_unlock(&fsvq->lock);
854 
855 	/* End requests */
856 	list_for_each_entry_safe(req, next, &reqs, list) {
857 		list_del_init(&req->list);
858 
859 		/* blocking async request completes in a worker context */
860 		if (req->args->may_block) {
861 			struct virtio_fs_req_work *w;
862 
863 			w = kzalloc_obj(*w, GFP_NOFS | __GFP_NOFAIL);
864 			INIT_WORK(&w->done_work, virtio_fs_complete_req_work);
865 			w->fsvq = fsvq;
866 			w->req = req;
867 			schedule_work(&w->done_work);
868 		} else {
869 			virtio_fs_request_complete(req, fsvq);
870 		}
871 	}
872 
873 	/* Try to push previously queued requests, as the queue might no longer be full */
874 	spin_lock(&fsvq->lock);
875 	if (!list_empty(&fsvq->queued_reqs))
876 		schedule_work(&fsvq->dispatch_work);
877 	spin_unlock(&fsvq->lock);
878 }
879 
880 static void virtio_fs_map_queues(struct virtio_device *vdev, struct virtio_fs *fs)
881 {
882 	const struct cpumask *mask, *masks;
883 	unsigned int q, cpu, nr_masks;
884 
885 	/* First attempt to map using existing transport layer affinities
886 	 * e.g. PCIe MSI-X
887 	 */
888 	if (!vdev->config->get_vq_affinity)
889 		goto fallback;
890 
891 	for (q = 0; q < fs->num_request_queues; q++) {
892 		mask = vdev->config->get_vq_affinity(vdev, VQ_REQUEST + q);
893 		if (!mask)
894 			goto fallback;
895 
896 		for_each_cpu(cpu, mask)
897 			fs->mq_map[cpu] = q + VQ_REQUEST;
898 	}
899 
900 	return;
901 fallback:
902 	/* Attempt to map evenly in groups over the CPUs */
903 	masks = group_cpus_evenly(fs->num_request_queues, &nr_masks);
904 	/* If even this fails we default to all CPUs use first request queue */
905 	if (!masks) {
906 		for_each_possible_cpu(cpu)
907 			fs->mq_map[cpu] = VQ_REQUEST;
908 		return;
909 	}
910 
911 	for (q = 0; q < fs->num_request_queues; q++) {
912 		for_each_cpu(cpu, &masks[q % nr_masks])
913 			fs->mq_map[cpu] = q + VQ_REQUEST;
914 	}
915 	kfree(masks);
916 }
917 
918 /* Virtqueue interrupt handler */
919 static void virtio_fs_vq_done(struct virtqueue *vq)
920 {
921 	struct virtio_fs_vq *fsvq = vq_to_fsvq(vq);
922 
923 	dev_dbg(&vq->vdev->dev, "%s %s\n", __func__, fsvq->name);
924 
925 	schedule_work(&fsvq->done_work);
926 }
927 
928 static void virtio_fs_init_vq(struct virtio_fs_vq *fsvq, char *name,
929 			      int vq_type)
930 {
931 	strscpy(fsvq->name, name, VQ_NAME_LEN);
932 	spin_lock_init(&fsvq->lock);
933 	INIT_LIST_HEAD(&fsvq->queued_reqs);
934 	INIT_LIST_HEAD(&fsvq->end_reqs);
935 	init_completion(&fsvq->in_flight_zero);
936 
937 	if (vq_type == VQ_REQUEST) {
938 		INIT_WORK(&fsvq->done_work, virtio_fs_requests_done_work);
939 		INIT_WORK(&fsvq->dispatch_work,
940 				virtio_fs_request_dispatch_work);
941 	} else {
942 		INIT_WORK(&fsvq->done_work, virtio_fs_hiprio_done_work);
943 		INIT_WORK(&fsvq->dispatch_work,
944 				virtio_fs_hiprio_dispatch_work);
945 	}
946 }
947 
948 /* Initialize virtqueues */
949 static int virtio_fs_setup_vqs(struct virtio_device *vdev,
950 			       struct virtio_fs *fs)
951 {
952 	struct virtqueue_info *vqs_info;
953 	struct virtqueue **vqs;
954 	/* Specify pre_vectors to ensure that the queues before the
955 	 * request queues (e.g. hiprio) don't claim any of the CPUs in
956 	 * the multi-queue mapping and interrupt affinities
957 	 */
958 	struct irq_affinity desc = { .pre_vectors = VQ_REQUEST };
959 	unsigned int i;
960 	int ret = 0;
961 
962 	virtio_cread_le(vdev, struct virtio_fs_config, num_request_queues,
963 			&fs->num_request_queues);
964 	if (fs->num_request_queues == 0)
965 		return -EINVAL;
966 
967 	/* Truncate nr of request queues to nr_cpu_id */
968 	fs->num_request_queues = min_t(unsigned int, fs->num_request_queues,
969 					nr_cpu_ids);
970 	fs->nvqs = VQ_REQUEST + fs->num_request_queues;
971 	fs->vqs = kzalloc_objs(fs->vqs[VQ_HIPRIO], fs->nvqs);
972 	if (!fs->vqs)
973 		return -ENOMEM;
974 
975 	vqs = kmalloc_objs(vqs[VQ_HIPRIO], fs->nvqs);
976 	fs->mq_map = kcalloc_node(nr_cpu_ids, sizeof(*fs->mq_map), GFP_KERNEL,
977 					dev_to_node(&vdev->dev));
978 	vqs_info = kzalloc_objs(*vqs_info, fs->nvqs);
979 	if (!vqs || !vqs_info || !fs->mq_map) {
980 		ret = -ENOMEM;
981 		goto out;
982 	}
983 
984 	/* Initialize the hiprio/forget request virtqueue */
985 	vqs_info[VQ_HIPRIO].callback = virtio_fs_vq_done;
986 	virtio_fs_init_vq(&fs->vqs[VQ_HIPRIO], "hiprio", VQ_HIPRIO);
987 	vqs_info[VQ_HIPRIO].name = fs->vqs[VQ_HIPRIO].name;
988 
989 	/* Initialize the requests virtqueues */
990 	for (i = VQ_REQUEST; i < fs->nvqs; i++) {
991 		char vq_name[VQ_NAME_LEN];
992 
993 		snprintf(vq_name, VQ_NAME_LEN, "requests.%u", i - VQ_REQUEST);
994 		virtio_fs_init_vq(&fs->vqs[i], vq_name, VQ_REQUEST);
995 		vqs_info[i].callback = virtio_fs_vq_done;
996 		vqs_info[i].name = fs->vqs[i].name;
997 	}
998 
999 	ret = virtio_find_vqs(vdev, fs->nvqs, vqs, vqs_info, &desc);
1000 	if (ret < 0)
1001 		goto out;
1002 
1003 	for (i = 0; i < fs->nvqs; i++)
1004 		fs->vqs[i].vq = vqs[i];
1005 
1006 	virtio_fs_start_all_queues(fs);
1007 out:
1008 	kfree(vqs_info);
1009 	kfree(vqs);
1010 	if (ret) {
1011 		kfree(fs->vqs);
1012 		kfree(fs->mq_map);
1013 	}
1014 	return ret;
1015 }
1016 
1017 /* Free virtqueues (device must already be reset) */
1018 static void virtio_fs_cleanup_vqs(struct virtio_device *vdev)
1019 {
1020 	vdev->config->del_vqs(vdev);
1021 }
1022 
1023 /* Map a window offset to a page frame number.  The window offset will have
1024  * been produced by .iomap_begin(), which maps a file offset to a window
1025  * offset.
1026  */
1027 static long virtio_fs_direct_access(struct dax_device *dax_dev, pgoff_t pgoff,
1028 				    long nr_pages, enum dax_access_mode mode,
1029 				    void **kaddr, unsigned long *pfn)
1030 {
1031 	struct virtio_fs *fs = dax_get_private(dax_dev);
1032 	phys_addr_t offset = PFN_PHYS(pgoff);
1033 	size_t max_nr_pages = fs->window_len / PAGE_SIZE - pgoff;
1034 
1035 	if (kaddr)
1036 		*kaddr = fs->window_kaddr + offset;
1037 	if (pfn)
1038 		*pfn = PHYS_PFN(fs->window_phys_addr + offset);
1039 	return nr_pages > max_nr_pages ? max_nr_pages : nr_pages;
1040 }
1041 
1042 static int virtio_fs_zero_page_range(struct dax_device *dax_dev,
1043 				     pgoff_t pgoff, size_t nr_pages)
1044 {
1045 	long rc;
1046 	void *kaddr;
1047 
1048 	rc = dax_direct_access(dax_dev, pgoff, nr_pages, DAX_ACCESS, &kaddr,
1049 			       NULL);
1050 	if (rc < 0)
1051 		return dax_mem2blk_err(rc);
1052 
1053 	memset(kaddr, 0, nr_pages << PAGE_SHIFT);
1054 	dax_flush(dax_dev, kaddr, nr_pages << PAGE_SHIFT);
1055 	return 0;
1056 }
1057 
1058 static const struct dax_operations virtio_fs_dax_ops = {
1059 	.direct_access = virtio_fs_direct_access,
1060 	.zero_page_range = virtio_fs_zero_page_range,
1061 };
1062 
1063 static void virtio_fs_cleanup_dax(void *data)
1064 {
1065 	struct dax_device *dax_dev = data;
1066 
1067 	kill_dax(dax_dev);
1068 	put_dax(dax_dev);
1069 }
1070 
1071 DEFINE_FREE(cleanup_dax, struct dax_dev *, if (!IS_ERR_OR_NULL(_T)) virtio_fs_cleanup_dax(_T))
1072 
1073 static int virtio_fs_setup_dax(struct virtio_device *vdev, struct virtio_fs *fs)
1074 {
1075 	struct dax_device *dax_dev __free(cleanup_dax) = NULL;
1076 	struct virtio_shm_region cache_reg;
1077 	struct dev_pagemap *pgmap;
1078 	bool have_cache;
1079 
1080 	if (!IS_ENABLED(CONFIG_FUSE_DAX))
1081 		return 0;
1082 
1083 	dax_dev = alloc_dax(fs, &virtio_fs_dax_ops);
1084 	if (IS_ERR(dax_dev)) {
1085 		int rc = PTR_ERR(dax_dev);
1086 		return rc == -EOPNOTSUPP ? 0 : rc;
1087 	}
1088 
1089 	/* Get cache region */
1090 	have_cache = virtio_get_shm_region(vdev, &cache_reg,
1091 					   (u8)VIRTIO_FS_SHMCAP_ID_CACHE);
1092 	if (!have_cache) {
1093 		dev_notice(&vdev->dev, "%s: No cache capability\n", __func__);
1094 		return 0;
1095 	}
1096 
1097 	if (!devm_request_mem_region(&vdev->dev, cache_reg.addr, cache_reg.len,
1098 				     dev_name(&vdev->dev))) {
1099 		dev_warn(&vdev->dev, "could not reserve region addr=0x%llx len=0x%llx\n",
1100 			 cache_reg.addr, cache_reg.len);
1101 		return -EBUSY;
1102 	}
1103 
1104 	dev_notice(&vdev->dev, "Cache len: 0x%llx @ 0x%llx\n", cache_reg.len,
1105 		   cache_reg.addr);
1106 
1107 	pgmap = devm_kzalloc(&vdev->dev, sizeof(*pgmap), GFP_KERNEL);
1108 	if (!pgmap)
1109 		return -ENOMEM;
1110 
1111 	pgmap->type = MEMORY_DEVICE_FS_DAX;
1112 
1113 	/* Ideally we would directly use the PCI BAR resource but
1114 	 * devm_memremap_pages() wants its own copy in pgmap.  So
1115 	 * initialize a struct resource from scratch (only the start
1116 	 * and end fields will be used).
1117 	 */
1118 	pgmap->range = (struct range) {
1119 		.start = (phys_addr_t) cache_reg.addr,
1120 		.end = (phys_addr_t) cache_reg.addr + cache_reg.len - 1,
1121 	};
1122 	pgmap->nr_range = 1;
1123 
1124 	fs->window_kaddr = devm_memremap_pages(&vdev->dev, pgmap);
1125 	if (IS_ERR(fs->window_kaddr))
1126 		return PTR_ERR(fs->window_kaddr);
1127 
1128 	fs->window_phys_addr = (phys_addr_t) cache_reg.addr;
1129 	fs->window_len = (phys_addr_t) cache_reg.len;
1130 
1131 	dev_dbg(&vdev->dev, "%s: window kaddr 0x%px phys_addr 0x%llx len 0x%llx\n",
1132 		__func__, fs->window_kaddr, cache_reg.addr, cache_reg.len);
1133 
1134 	fs->dax_dev = no_free_ptr(dax_dev);
1135 	return devm_add_action_or_reset(&vdev->dev, virtio_fs_cleanup_dax,
1136 					fs->dax_dev);
1137 }
1138 
1139 static int virtio_fs_probe(struct virtio_device *vdev)
1140 {
1141 	struct virtio_fs *fs;
1142 	int ret;
1143 
1144 	fs = kzalloc_obj(*fs);
1145 	if (!fs)
1146 		return -ENOMEM;
1147 	kobject_init(&fs->kobj, &virtio_fs_ktype);
1148 	vdev->priv = fs;
1149 
1150 	ret = virtio_fs_read_tag(vdev, fs);
1151 	if (ret < 0)
1152 		goto out;
1153 
1154 	ret = virtio_fs_setup_vqs(vdev, fs);
1155 	if (ret < 0)
1156 		goto out;
1157 
1158 	virtio_fs_map_queues(vdev, fs);
1159 
1160 	ret = virtio_fs_setup_dax(vdev, fs);
1161 	if (ret < 0)
1162 		goto out_vqs;
1163 
1164 	/* Bring the device online in case the filesystem is mounted and
1165 	 * requests need to be sent before we return.
1166 	 */
1167 	virtio_device_ready(vdev);
1168 
1169 	ret = virtio_fs_add_instance(vdev, fs);
1170 	if (ret < 0)
1171 		goto out_vqs;
1172 
1173 	return 0;
1174 
1175 out_vqs:
1176 	virtio_reset_device(vdev);
1177 	virtio_fs_cleanup_vqs(vdev);
1178 
1179 out:
1180 	vdev->priv = NULL;
1181 	kobject_put(&fs->kobj);
1182 	return ret;
1183 }
1184 
1185 static void virtio_fs_stop_all_queues(struct virtio_fs *fs)
1186 {
1187 	struct virtio_fs_vq *fsvq;
1188 	int i;
1189 
1190 	for (i = 0; i < fs->nvqs; i++) {
1191 		fsvq = &fs->vqs[i];
1192 		spin_lock(&fsvq->lock);
1193 		fsvq->connected = false;
1194 		spin_unlock(&fsvq->lock);
1195 	}
1196 }
1197 
1198 static void virtio_fs_remove(struct virtio_device *vdev)
1199 {
1200 	struct virtio_fs *fs = vdev->priv;
1201 
1202 	mutex_lock(&virtio_fs_mutex);
1203 	/* This device is going away. No one should get new reference */
1204 	list_del_init(&fs->list);
1205 	virtio_fs_delete_queues_sysfs(fs);
1206 	sysfs_remove_link(&fs->kobj, "device");
1207 	kobject_put(fs->mqs_kobj);
1208 	kobject_del(&fs->kobj);
1209 	virtio_fs_stop_all_queues(fs);
1210 	virtio_fs_drain_all_queues_locked(fs);
1211 	virtio_reset_device(vdev);
1212 	virtio_fs_cleanup_vqs(vdev);
1213 
1214 	vdev->priv = NULL;
1215 	/* Put device reference on virtio_fs object */
1216 	virtio_fs_put_locked(fs);
1217 	mutex_unlock(&virtio_fs_mutex);
1218 }
1219 
1220 #ifdef CONFIG_PM_SLEEP
1221 static int virtio_fs_freeze(struct virtio_device *vdev)
1222 {
1223 	/* TODO need to save state here */
1224 	pr_warn("virtio-fs: suspend/resume not yet supported\n");
1225 	return -EOPNOTSUPP;
1226 }
1227 
1228 static int virtio_fs_restore(struct virtio_device *vdev)
1229 {
1230 	 /* TODO need to restore state here */
1231 	return 0;
1232 }
1233 #endif /* CONFIG_PM_SLEEP */
1234 
1235 static const struct virtio_device_id id_table[] = {
1236 	{ VIRTIO_ID_FS, VIRTIO_DEV_ANY_ID },
1237 	{},
1238 };
1239 
1240 static const unsigned int feature_table[] = {};
1241 
1242 static struct virtio_driver virtio_fs_driver = {
1243 	.driver.name		= KBUILD_MODNAME,
1244 	.id_table		= id_table,
1245 	.feature_table		= feature_table,
1246 	.feature_table_size	= ARRAY_SIZE(feature_table),
1247 	.probe			= virtio_fs_probe,
1248 	.remove			= virtio_fs_remove,
1249 #ifdef CONFIG_PM_SLEEP
1250 	.freeze			= virtio_fs_freeze,
1251 	.restore		= virtio_fs_restore,
1252 #endif
1253 };
1254 
1255 static void virtio_fs_send_forget(struct fuse_iqueue *fiq, struct fuse_forget_link *link)
1256 {
1257 	struct virtio_fs_forget *forget;
1258 	struct virtio_fs_forget_req *req;
1259 	struct virtio_fs *fs = fiq->priv;
1260 	struct virtio_fs_vq *fsvq = &fs->vqs[VQ_HIPRIO];
1261 	u64 unique = fuse_get_unique(fiq);
1262 
1263 	/* Allocate a buffer for the request */
1264 	forget = kmalloc_obj(*forget, GFP_NOFS | __GFP_NOFAIL);
1265 	req = &forget->req;
1266 
1267 	req->ih = (struct fuse_in_header){
1268 		.opcode = FUSE_FORGET,
1269 		.nodeid = link->forget_one.nodeid,
1270 		.unique = unique,
1271 		.len = sizeof(*req),
1272 	};
1273 	req->arg = (struct fuse_forget_in){
1274 		.nlookup = link->forget_one.nlookup,
1275 	};
1276 
1277 	send_forget_request(fsvq, forget, false);
1278 	kfree(link);
1279 }
1280 
1281 static void virtio_fs_send_interrupt(struct fuse_iqueue *fiq, struct fuse_req *req)
1282 {
1283 	/*
1284 	 * TODO interrupts.
1285 	 *
1286 	 * Normal fs operations on a local filesystems aren't interruptible.
1287 	 * Exceptions are blocking lock operations; for example fcntl(F_SETLKW)
1288 	 * with shared lock between host and guest.
1289 	 */
1290 }
1291 
1292 /* Count number of scatter-gather elements required */
1293 static unsigned int sg_count_fuse_folios(struct fuse_folio_desc *folio_descs,
1294 					 unsigned int num_folios,
1295 					 unsigned int total_len)
1296 {
1297 	unsigned int i;
1298 	unsigned int this_len;
1299 
1300 	for (i = 0; i < num_folios && total_len; i++) {
1301 		this_len =  min(folio_descs[i].length, total_len);
1302 		total_len -= this_len;
1303 	}
1304 
1305 	return i;
1306 }
1307 
1308 /* Return the number of scatter-gather list elements required */
1309 static unsigned int sg_count_fuse_req(struct fuse_req *req)
1310 {
1311 	struct fuse_args *args = req->args;
1312 	struct fuse_args_pages *ap = container_of(args, typeof(*ap), args);
1313 	unsigned int size, total_sgs = 1 /* fuse_in_header */;
1314 
1315 	if (args->in_numargs - args->in_pages)
1316 		total_sgs += 1;
1317 
1318 	if (args->in_pages) {
1319 		size = args->in_args[args->in_numargs - 1].size;
1320 		total_sgs += sg_count_fuse_folios(ap->descs, ap->num_folios,
1321 						  size);
1322 	}
1323 
1324 	if (!test_bit(FR_ISREPLY, &req->flags))
1325 		return total_sgs;
1326 
1327 	total_sgs += 1 /* fuse_out_header */;
1328 
1329 	if (args->out_numargs - args->out_pages)
1330 		total_sgs += 1;
1331 
1332 	if (args->out_pages) {
1333 		size = args->out_args[args->out_numargs - 1].size;
1334 		total_sgs += sg_count_fuse_folios(ap->descs, ap->num_folios,
1335 						  size);
1336 	}
1337 
1338 	return total_sgs;
1339 }
1340 
1341 /* Add folios to scatter-gather list and return number of elements used */
1342 static unsigned int sg_init_fuse_folios(struct scatterlist *sg,
1343 					struct folio **folios,
1344 					struct fuse_folio_desc *folio_descs,
1345 					unsigned int num_folios,
1346 				        unsigned int total_len)
1347 {
1348 	unsigned int i;
1349 	unsigned int this_len;
1350 
1351 	for (i = 0; i < num_folios && total_len; i++) {
1352 		sg_init_table(&sg[i], 1);
1353 		this_len =  min(folio_descs[i].length, total_len);
1354 		sg_set_folio(&sg[i], folios[i], this_len, folio_descs[i].offset);
1355 		total_len -= this_len;
1356 	}
1357 
1358 	return i;
1359 }
1360 
1361 /* Add args to scatter-gather list and return number of elements used */
1362 static unsigned int sg_init_fuse_args(struct scatterlist *sg,
1363 				      struct fuse_req *req,
1364 				      struct fuse_arg *args,
1365 				      unsigned int numargs,
1366 				      bool argpages,
1367 				      void *argbuf,
1368 				      unsigned int *len_used)
1369 {
1370 	struct fuse_args_pages *ap = container_of(req->args, typeof(*ap), args);
1371 	unsigned int total_sgs = 0;
1372 	unsigned int len;
1373 
1374 	len = fuse_len_args(numargs - argpages, args);
1375 	if (len)
1376 		sg_init_one(&sg[total_sgs++], argbuf, len);
1377 
1378 	if (argpages)
1379 		total_sgs += sg_init_fuse_folios(&sg[total_sgs],
1380 						 ap->folios, ap->descs,
1381 						 ap->num_folios,
1382 						 args[numargs - 1].size);
1383 
1384 	if (len_used)
1385 		*len_used = len;
1386 
1387 	return total_sgs;
1388 }
1389 
1390 /* Add a request to a virtqueue and kick the device */
1391 static int virtio_fs_enqueue_req(struct virtio_fs_vq *fsvq,
1392 				 struct fuse_req *req, bool in_flight,
1393 				 gfp_t gfp)
1394 {
1395 	/* requests need at least 4 elements */
1396 	struct scatterlist *stack_sgs[6];
1397 	struct scatterlist stack_sg[ARRAY_SIZE(stack_sgs)];
1398 	struct scatterlist **sgs = stack_sgs;
1399 	struct scatterlist *sg = stack_sg;
1400 	struct virtqueue *vq;
1401 	struct fuse_args *args = req->args;
1402 	unsigned int argbuf_used = 0;
1403 	unsigned int out_sgs = 0;
1404 	unsigned int in_sgs = 0;
1405 	unsigned int total_sgs;
1406 	unsigned int i, hash;
1407 	int ret;
1408 	bool notify;
1409 	struct fuse_pqueue *fpq;
1410 
1411 	/* Does the sglist fit on the stack? */
1412 	total_sgs = sg_count_fuse_req(req);
1413 	if (total_sgs > ARRAY_SIZE(stack_sgs)) {
1414 		sgs = kmalloc_objs(sgs[0], total_sgs, gfp);
1415 		sg = kmalloc_objs(sg[0], total_sgs, gfp);
1416 		if (!sgs || !sg) {
1417 			ret = -ENOMEM;
1418 			goto out;
1419 		}
1420 	}
1421 
1422 	/* Use a bounce buffer since stack args cannot be mapped */
1423 	ret = copy_args_to_argbuf(req, gfp);
1424 	if (ret < 0)
1425 		goto out;
1426 
1427 	/* Request elements */
1428 	sg_init_one(&sg[out_sgs++], &req->in.h, sizeof(req->in.h));
1429 	out_sgs += sg_init_fuse_args(&sg[out_sgs], req,
1430 				     (struct fuse_arg *)args->in_args,
1431 				     args->in_numargs, args->in_pages,
1432 				     req->argbuf, &argbuf_used);
1433 
1434 	/* Reply elements */
1435 	if (test_bit(FR_ISREPLY, &req->flags)) {
1436 		sg_init_one(&sg[out_sgs + in_sgs++],
1437 			    &req->out.h, sizeof(req->out.h));
1438 		in_sgs += sg_init_fuse_args(&sg[out_sgs + in_sgs], req,
1439 					    args->out_args, args->out_numargs,
1440 					    args->out_pages,
1441 					    req->argbuf + argbuf_used, NULL);
1442 	}
1443 
1444 	WARN_ON(out_sgs + in_sgs != total_sgs);
1445 
1446 	for (i = 0; i < total_sgs; i++)
1447 		sgs[i] = &sg[i];
1448 
1449 	spin_lock(&fsvq->lock);
1450 
1451 	if (!fsvq->connected) {
1452 		spin_unlock(&fsvq->lock);
1453 		ret = -ENOTCONN;
1454 		goto out;
1455 	}
1456 
1457 	vq = fsvq->vq;
1458 	ret = virtqueue_add_sgs(vq, sgs, out_sgs, in_sgs, req, GFP_ATOMIC);
1459 	if (ret < 0) {
1460 		spin_unlock(&fsvq->lock);
1461 		goto out;
1462 	}
1463 
1464 	/* Request successfully sent. */
1465 	fpq = &fsvq->fud->pq;
1466 	hash = fuse_req_hash(req->in.h.unique);
1467 	spin_lock(&fpq->lock);
1468 	list_add_tail(&req->list, &fpq->processing[hash]);
1469 	spin_unlock(&fpq->lock);
1470 	set_bit(FR_SENT, &req->flags);
1471 	/* matches barrier in request_wait_answer() */
1472 	smp_mb__after_atomic();
1473 
1474 	if (!in_flight)
1475 		inc_in_flight_req(fsvq);
1476 	notify = virtqueue_kick_prepare(vq);
1477 
1478 	spin_unlock(&fsvq->lock);
1479 
1480 	if (notify)
1481 		virtqueue_notify(vq);
1482 
1483 out:
1484 	if (ret < 0 && req->argbuf) {
1485 		kfree(req->argbuf);
1486 		req->argbuf = NULL;
1487 	}
1488 	if (sgs != stack_sgs) {
1489 		kfree(sgs);
1490 		kfree(sg);
1491 	}
1492 
1493 	return ret;
1494 }
1495 
1496 static void virtio_fs_send_req(struct fuse_iqueue *fiq, struct fuse_req *req)
1497 {
1498 	unsigned int queue_id;
1499 	struct virtio_fs *fs;
1500 	struct virtio_fs_vq *fsvq;
1501 	int ret;
1502 
1503 	fuse_request_assign_unique(fiq, req);
1504 
1505 	clear_bit(FR_PENDING, &req->flags);
1506 
1507 	fs = fiq->priv;
1508 	queue_id = fs->mq_map[raw_smp_processor_id()];
1509 
1510 	pr_debug("%s: opcode %u unique %#llx nodeid %#llx in.len %u out.len %u queue_id %u\n",
1511 		 __func__, req->in.h.opcode, req->in.h.unique,
1512 		 req->in.h.nodeid, req->in.h.len,
1513 		 fuse_len_args(req->args->out_numargs, req->args->out_args),
1514 		 queue_id);
1515 
1516 	fsvq = &fs->vqs[queue_id];
1517 	ret = virtio_fs_enqueue_req(fsvq, req, false, GFP_ATOMIC);
1518 	if (ret < 0) {
1519 		if (ret == -ENOSPC) {
1520 			/*
1521 			 * Virtqueue full. Retry submission from worker
1522 			 * context as we might be holding fc->bg_lock.
1523 			 */
1524 			spin_lock(&fsvq->lock);
1525 			list_add_tail(&req->list, &fsvq->queued_reqs);
1526 			inc_in_flight_req(fsvq);
1527 			spin_unlock(&fsvq->lock);
1528 			return;
1529 		}
1530 		req->out.h.error = ret;
1531 		pr_err("virtio-fs: virtio_fs_enqueue_req() failed %d\n", ret);
1532 
1533 		/* Can't end request in submission context. Use a worker */
1534 		spin_lock(&fsvq->lock);
1535 		list_add_tail(&req->list, &fsvq->end_reqs);
1536 		schedule_work(&fsvq->dispatch_work);
1537 		spin_unlock(&fsvq->lock);
1538 		return;
1539 	}
1540 }
1541 
1542 static const struct fuse_iqueue_ops virtio_fs_fiq_ops = {
1543 	.send_forget	= virtio_fs_send_forget,
1544 	.send_interrupt	= virtio_fs_send_interrupt,
1545 	.send_req	= virtio_fs_send_req,
1546 	.release	= virtio_fs_fiq_release,
1547 };
1548 
1549 static inline void virtio_fs_ctx_set_defaults(struct fuse_fs_context *ctx)
1550 {
1551 	ctx->rootmode = S_IFDIR;
1552 	ctx->default_permissions = 1;
1553 	ctx->allow_other = 1;
1554 	ctx->max_read = UINT_MAX;
1555 	ctx->blksize = 512;
1556 	ctx->destroy = true;
1557 	ctx->no_control = true;
1558 	ctx->no_force_umount = true;
1559 }
1560 
1561 static int virtio_fs_fill_super(struct super_block *sb, struct fs_context *fsc)
1562 {
1563 	struct fuse_mount *fm = get_fuse_mount_super(sb);
1564 	struct fuse_conn *fc = fm->fc;
1565 	struct virtio_fs *fs = fc->iq.priv;
1566 	struct fuse_fs_context *ctx = fsc->fs_private;
1567 	unsigned int i;
1568 	int err;
1569 
1570 	virtio_fs_ctx_set_defaults(ctx);
1571 	mutex_lock(&virtio_fs_mutex);
1572 
1573 	/* After holding mutex, make sure virtiofs device is still there.
1574 	 * Though we are holding a reference to it, drive ->remove might
1575 	 * still have cleaned up virtual queues. In that case bail out.
1576 	 */
1577 	err = -EINVAL;
1578 	if (list_empty(&fs->list)) {
1579 		pr_info("virtio-fs: tag <%s> not found\n", fs->tag);
1580 		goto err;
1581 	}
1582 
1583 	err = -ENOMEM;
1584 	/* Allocate fuse_dev for hiprio and notification queues */
1585 	for (i = 0; i < fs->nvqs; i++) {
1586 		struct virtio_fs_vq *fsvq = &fs->vqs[i];
1587 
1588 		fsvq->fud = fuse_dev_alloc();
1589 		if (!fsvq->fud)
1590 			goto err_free_fuse_devs;
1591 	}
1592 
1593 	if (ctx->dax_mode != FUSE_DAX_NEVER) {
1594 		if (ctx->dax_mode == FUSE_DAX_ALWAYS && !fs->dax_dev) {
1595 			err = -EINVAL;
1596 			pr_err("virtio-fs: dax can't be enabled as filesystem"
1597 			       " device does not support it.\n");
1598 			goto err_free_fuse_devs;
1599 		}
1600 		ctx->dax_dev = fs->dax_dev;
1601 	}
1602 	err = fuse_fill_super_common(sb, ctx);
1603 	if (err < 0)
1604 		goto err_free_fuse_devs;
1605 
1606 	for (i = 0; i < fs->nvqs; i++) {
1607 		struct virtio_fs_vq *fsvq = &fs->vqs[i];
1608 
1609 		fuse_dev_install(fsvq->fud, fc);
1610 	}
1611 
1612 	/* Previous unmount will stop all queues. Start these again */
1613 	virtio_fs_start_all_queues(fs);
1614 	fuse_send_init(fm);
1615 	mutex_unlock(&virtio_fs_mutex);
1616 	return 0;
1617 
1618 err_free_fuse_devs:
1619 	virtio_fs_free_devs(fs);
1620 err:
1621 	mutex_unlock(&virtio_fs_mutex);
1622 	return err;
1623 }
1624 
1625 static void virtio_fs_conn_destroy(struct fuse_mount *fm)
1626 {
1627 	struct fuse_conn *fc = fm->fc;
1628 	struct virtio_fs *vfs = fc->iq.priv;
1629 	struct virtio_fs_vq *fsvq = &vfs->vqs[VQ_HIPRIO];
1630 
1631 	/* Stop dax worker. Soon evict_inodes() will be called which
1632 	 * will free all memory ranges belonging to all inodes.
1633 	 */
1634 	if (IS_ENABLED(CONFIG_FUSE_DAX))
1635 		fuse_dax_cancel_work(fc);
1636 
1637 	/* Stop forget queue. Soon destroy will be sent */
1638 	spin_lock(&fsvq->lock);
1639 	fsvq->connected = false;
1640 	spin_unlock(&fsvq->lock);
1641 	virtio_fs_drain_all_queues(vfs);
1642 
1643 	fuse_conn_destroy(fm);
1644 
1645 	/* fuse_conn_destroy() must have sent destroy. Stop all queues
1646 	 * and drain one more time and free fuse devices. Freeing fuse
1647 	 * devices will drop their reference on fuse_conn and that in
1648 	 * turn will drop its reference on virtio_fs object.
1649 	 */
1650 	virtio_fs_stop_all_queues(vfs);
1651 	virtio_fs_drain_all_queues(vfs);
1652 	virtio_fs_free_devs(vfs);
1653 }
1654 
1655 static void virtio_kill_sb(struct super_block *sb)
1656 {
1657 	struct fuse_mount *fm = get_fuse_mount_super(sb);
1658 	bool last;
1659 
1660 	/* If mount failed, we can still be called without any fc */
1661 	if (sb->s_root) {
1662 		last = fuse_mount_remove(fm);
1663 		if (last)
1664 			virtio_fs_conn_destroy(fm);
1665 	}
1666 	kill_anon_super(sb);
1667 	fuse_mount_destroy(fm);
1668 }
1669 
1670 static int virtio_fs_test_super(struct super_block *sb,
1671 				struct fs_context *fsc)
1672 {
1673 	struct fuse_mount *fsc_fm = fsc->s_fs_info;
1674 	struct fuse_mount *sb_fm = get_fuse_mount_super(sb);
1675 
1676 	return fsc_fm->fc->iq.priv == sb_fm->fc->iq.priv;
1677 }
1678 
1679 static int virtio_fs_get_tree(struct fs_context *fsc)
1680 {
1681 	struct virtio_fs *fs;
1682 	struct super_block *sb;
1683 	struct fuse_conn *fc = NULL;
1684 	struct fuse_mount *fm;
1685 	unsigned int virtqueue_size;
1686 	int err = -EIO;
1687 
1688 	if (!fsc->source)
1689 		return invalf(fsc, "No source specified");
1690 
1691 	/* This gets a reference on virtio_fs object. This ptr gets installed
1692 	 * in fc->iq->priv. Once fuse_conn is going away, it calls ->put()
1693 	 * to drop the reference to this object.
1694 	 */
1695 	fs = virtio_fs_find_instance(fsc->source);
1696 	if (!fs) {
1697 		pr_info("virtio-fs: tag <%s> not found\n", fsc->source);
1698 		return -EINVAL;
1699 	}
1700 
1701 	virtqueue_size = virtqueue_get_vring_size(fs->vqs[VQ_REQUEST].vq);
1702 	if (WARN_ON(virtqueue_size <= FUSE_HEADER_OVERHEAD))
1703 		goto out_err;
1704 
1705 	err = -ENOMEM;
1706 	fc = kzalloc_obj(struct fuse_conn);
1707 	if (!fc)
1708 		goto out_err;
1709 
1710 	fm = kzalloc_obj(struct fuse_mount);
1711 	if (!fm)
1712 		goto out_err;
1713 
1714 	fuse_conn_init(fc, fm, fsc->user_ns, &virtio_fs_fiq_ops, fs);
1715 	fc->release = fuse_free_conn;
1716 	fc->delete_stale = true;
1717 	fc->auto_submounts = true;
1718 	fc->sync_fs = true;
1719 	fc->use_pages_for_kvec_io = true;
1720 
1721 	/* Tell FUSE to split requests that exceed the virtqueue's size */
1722 	fc->max_pages_limit = min_t(unsigned int, fc->max_pages_limit,
1723 				    virtqueue_size - FUSE_HEADER_OVERHEAD);
1724 
1725 	fsc->s_fs_info = fm;
1726 	sb = sget_fc(fsc, virtio_fs_test_super, set_anon_super_fc);
1727 	if (fsc->s_fs_info)
1728 		fuse_mount_destroy(fm);
1729 	if (IS_ERR(sb))
1730 		return PTR_ERR(sb);
1731 
1732 	if (!sb->s_root) {
1733 		err = virtio_fs_fill_super(sb, fsc);
1734 		if (err) {
1735 			deactivate_locked_super(sb);
1736 			return err;
1737 		}
1738 
1739 		sb->s_flags |= SB_ACTIVE;
1740 	}
1741 
1742 	WARN_ON(fsc->root);
1743 	fsc->root = dget(sb->s_root);
1744 	return 0;
1745 
1746 out_err:
1747 	kfree(fc);
1748 	virtio_fs_put(fs);
1749 	return err;
1750 }
1751 
1752 static const struct fs_context_operations virtio_fs_context_ops = {
1753 	.free		= virtio_fs_free_fsc,
1754 	.parse_param	= virtio_fs_parse_param,
1755 	.get_tree	= virtio_fs_get_tree,
1756 };
1757 
1758 static int virtio_fs_init_fs_context(struct fs_context *fsc)
1759 {
1760 	struct fuse_fs_context *ctx;
1761 
1762 	if (fsc->purpose == FS_CONTEXT_FOR_SUBMOUNT)
1763 		return fuse_init_fs_context_submount(fsc);
1764 
1765 	ctx = kzalloc_obj(struct fuse_fs_context);
1766 	if (!ctx)
1767 		return -ENOMEM;
1768 	fsc->fs_private = ctx;
1769 	fsc->ops = &virtio_fs_context_ops;
1770 	return 0;
1771 }
1772 
1773 static struct file_system_type virtio_fs_type = {
1774 	.owner		= THIS_MODULE,
1775 	.name		= "virtiofs",
1776 	.init_fs_context = virtio_fs_init_fs_context,
1777 	.kill_sb	= virtio_kill_sb,
1778 	.fs_flags	= FS_ALLOW_IDMAP,
1779 };
1780 
1781 static int virtio_fs_uevent(const struct kobject *kobj, struct kobj_uevent_env *env)
1782 {
1783 	const struct virtio_fs *fs = container_of(kobj, struct virtio_fs, kobj);
1784 
1785 	add_uevent_var(env, "TAG=%s", fs->tag);
1786 	return 0;
1787 }
1788 
1789 static const struct kset_uevent_ops virtio_fs_uevent_ops = {
1790 	.uevent = virtio_fs_uevent,
1791 };
1792 
1793 static int __init virtio_fs_sysfs_init(void)
1794 {
1795 	virtio_fs_kset = kset_create_and_add("virtiofs", &virtio_fs_uevent_ops,
1796 					     fs_kobj);
1797 	if (!virtio_fs_kset)
1798 		return -ENOMEM;
1799 	return 0;
1800 }
1801 
1802 static void virtio_fs_sysfs_exit(void)
1803 {
1804 	kset_unregister(virtio_fs_kset);
1805 	virtio_fs_kset = NULL;
1806 }
1807 
1808 static int __init virtio_fs_init(void)
1809 {
1810 	int ret;
1811 
1812 	ret = virtio_fs_sysfs_init();
1813 	if (ret < 0)
1814 		return ret;
1815 
1816 	ret = register_virtio_driver(&virtio_fs_driver);
1817 	if (ret < 0)
1818 		goto sysfs_exit;
1819 
1820 	ret = register_filesystem(&virtio_fs_type);
1821 	if (ret < 0)
1822 		goto unregister_virtio_driver;
1823 
1824 	return 0;
1825 
1826 unregister_virtio_driver:
1827 	unregister_virtio_driver(&virtio_fs_driver);
1828 sysfs_exit:
1829 	virtio_fs_sysfs_exit();
1830 	return ret;
1831 }
1832 module_init(virtio_fs_init);
1833 
1834 static void __exit virtio_fs_exit(void)
1835 {
1836 	unregister_filesystem(&virtio_fs_type);
1837 	unregister_virtio_driver(&virtio_fs_driver);
1838 	virtio_fs_sysfs_exit();
1839 }
1840 module_exit(virtio_fs_exit);
1841 
1842 MODULE_AUTHOR("Stefan Hajnoczi <stefanha@redhat.com>");
1843 MODULE_DESCRIPTION("Virtio Filesystem");
1844 MODULE_LICENSE("GPL");
1845 MODULE_ALIAS_FS(KBUILD_MODNAME);
1846 MODULE_DEVICE_TABLE(virtio, id_table);
1847