xref: /linux/fs/fuse/dev.c (revision df2e3152f1cb798ed8ffa7e488c50261e6dc50e3)
1 /*
2   FUSE: Filesystem in Userspace
3   Copyright (C) 2001-2008  Miklos Szeredi <miklos@szeredi.hu>
4 
5   This program can be distributed under the terms of the GNU GPL.
6   See the file COPYING.
7 */
8 
9 #include "dev_uring_i.h"
10 #include "fuse_i.h"
11 #include "fuse_dev_i.h"
12 
13 #include <linux/init.h>
14 #include <linux/module.h>
15 #include <linux/poll.h>
16 #include <linux/sched/signal.h>
17 #include <linux/uio.h>
18 #include <linux/miscdevice.h>
19 #include <linux/pagemap.h>
20 #include <linux/file.h>
21 #include <linux/slab.h>
22 #include <linux/pipe_fs_i.h>
23 #include <linux/swap.h>
24 #include <linux/splice.h>
25 #include <linux/sched.h>
26 
27 #define CREATE_TRACE_POINTS
28 #include "fuse_trace.h"
29 
30 MODULE_ALIAS_MISCDEV(FUSE_MINOR);
31 MODULE_ALIAS("devname:fuse");
32 
33 static struct kmem_cache *fuse_req_cachep;
34 
35 static void fuse_request_init(struct fuse_mount *fm, struct fuse_req *req)
36 {
37 	INIT_LIST_HEAD(&req->list);
38 	INIT_LIST_HEAD(&req->intr_entry);
39 	init_waitqueue_head(&req->waitq);
40 	refcount_set(&req->count, 1);
41 	__set_bit(FR_PENDING, &req->flags);
42 	req->fm = fm;
43 }
44 
45 static struct fuse_req *fuse_request_alloc(struct fuse_mount *fm, gfp_t flags)
46 {
47 	struct fuse_req *req = kmem_cache_zalloc(fuse_req_cachep, flags);
48 	if (req)
49 		fuse_request_init(fm, req);
50 
51 	return req;
52 }
53 
54 static void fuse_request_free(struct fuse_req *req)
55 {
56 	kmem_cache_free(fuse_req_cachep, req);
57 }
58 
59 static void __fuse_get_request(struct fuse_req *req)
60 {
61 	refcount_inc(&req->count);
62 }
63 
64 /* Must be called with > 1 refcount */
65 static void __fuse_put_request(struct fuse_req *req)
66 {
67 	refcount_dec(&req->count);
68 }
69 
70 void fuse_set_initialized(struct fuse_conn *fc)
71 {
72 	/* Make sure stores before this are seen on another CPU */
73 	smp_wmb();
74 	fc->initialized = 1;
75 }
76 
77 static bool fuse_block_alloc(struct fuse_conn *fc, bool for_background)
78 {
79 	return !fc->initialized || (for_background && fc->blocked) ||
80 	       (fc->io_uring && !fuse_uring_ready(fc));
81 }
82 
83 static void fuse_drop_waiting(struct fuse_conn *fc)
84 {
85 	/*
86 	 * lockess check of fc->connected is okay, because atomic_dec_and_test()
87 	 * provides a memory barrier matched with the one in fuse_wait_aborted()
88 	 * to ensure no wake-up is missed.
89 	 */
90 	if (atomic_dec_and_test(&fc->num_waiting) &&
91 	    !READ_ONCE(fc->connected)) {
92 		/* wake up aborters */
93 		wake_up_all(&fc->blocked_waitq);
94 	}
95 }
96 
97 static void fuse_put_request(struct fuse_req *req);
98 
99 static struct fuse_req *fuse_get_req(struct mnt_idmap *idmap,
100 				     struct fuse_mount *fm,
101 				     bool for_background)
102 {
103 	struct fuse_conn *fc = fm->fc;
104 	struct fuse_req *req;
105 	bool no_idmap = !fm->sb || (fm->sb->s_iflags & SB_I_NOIDMAP);
106 	kuid_t fsuid;
107 	kgid_t fsgid;
108 	int err;
109 
110 	atomic_inc(&fc->num_waiting);
111 
112 	if (fuse_block_alloc(fc, for_background)) {
113 		err = -EINTR;
114 		if (wait_event_killable_exclusive(fc->blocked_waitq,
115 				!fuse_block_alloc(fc, for_background)))
116 			goto out;
117 	}
118 	/* Matches smp_wmb() in fuse_set_initialized() */
119 	smp_rmb();
120 
121 	err = -ENOTCONN;
122 	if (!fc->connected)
123 		goto out;
124 
125 	err = -ECONNREFUSED;
126 	if (fc->conn_error)
127 		goto out;
128 
129 	req = fuse_request_alloc(fm, GFP_KERNEL);
130 	err = -ENOMEM;
131 	if (!req) {
132 		if (for_background)
133 			wake_up(&fc->blocked_waitq);
134 		goto out;
135 	}
136 
137 	req->in.h.pid = pid_nr_ns(task_pid(current), fc->pid_ns);
138 
139 	__set_bit(FR_WAITING, &req->flags);
140 	if (for_background)
141 		__set_bit(FR_BACKGROUND, &req->flags);
142 
143 	/*
144 	 * Keep the old behavior when idmappings support was not
145 	 * declared by a FUSE server.
146 	 *
147 	 * For those FUSE servers who support idmapped mounts,
148 	 * we send UID/GID only along with "inode creation"
149 	 * fuse requests, otherwise idmap == &invalid_mnt_idmap and
150 	 * req->in.h.{u,g}id will be equal to FUSE_INVALID_UIDGID.
151 	 */
152 	fsuid = no_idmap ? current_fsuid() : mapped_fsuid(idmap, fc->user_ns);
153 	fsgid = no_idmap ? current_fsgid() : mapped_fsgid(idmap, fc->user_ns);
154 	req->in.h.uid = from_kuid(fc->user_ns, fsuid);
155 	req->in.h.gid = from_kgid(fc->user_ns, fsgid);
156 
157 	if (no_idmap && unlikely(req->in.h.uid == ((uid_t)-1) ||
158 				 req->in.h.gid == ((gid_t)-1))) {
159 		fuse_put_request(req);
160 		return ERR_PTR(-EOVERFLOW);
161 	}
162 
163 	return req;
164 
165  out:
166 	fuse_drop_waiting(fc);
167 	return ERR_PTR(err);
168 }
169 
170 static void fuse_put_request(struct fuse_req *req)
171 {
172 	struct fuse_conn *fc = req->fm->fc;
173 
174 	if (refcount_dec_and_test(&req->count)) {
175 		if (test_bit(FR_BACKGROUND, &req->flags)) {
176 			/*
177 			 * We get here in the unlikely case that a background
178 			 * request was allocated but not sent
179 			 */
180 			spin_lock(&fc->bg_lock);
181 			if (!fc->blocked)
182 				wake_up(&fc->blocked_waitq);
183 			spin_unlock(&fc->bg_lock);
184 		}
185 
186 		if (test_bit(FR_WAITING, &req->flags)) {
187 			__clear_bit(FR_WAITING, &req->flags);
188 			fuse_drop_waiting(fc);
189 		}
190 
191 		fuse_request_free(req);
192 	}
193 }
194 
195 unsigned int fuse_len_args(unsigned int numargs, struct fuse_arg *args)
196 {
197 	unsigned nbytes = 0;
198 	unsigned i;
199 
200 	for (i = 0; i < numargs; i++)
201 		nbytes += args[i].size;
202 
203 	return nbytes;
204 }
205 EXPORT_SYMBOL_GPL(fuse_len_args);
206 
207 static u64 fuse_get_unique_locked(struct fuse_iqueue *fiq)
208 {
209 	fiq->reqctr += FUSE_REQ_ID_STEP;
210 	return fiq->reqctr;
211 }
212 
213 u64 fuse_get_unique(struct fuse_iqueue *fiq)
214 {
215 	u64 ret;
216 
217 	spin_lock(&fiq->lock);
218 	ret = fuse_get_unique_locked(fiq);
219 	spin_unlock(&fiq->lock);
220 
221 	return ret;
222 }
223 EXPORT_SYMBOL_GPL(fuse_get_unique);
224 
225 unsigned int fuse_req_hash(u64 unique)
226 {
227 	return hash_long(unique & ~FUSE_INT_REQ_BIT, FUSE_PQ_HASH_BITS);
228 }
229 
230 /*
231  * A new request is available, wake fiq->waitq
232  */
233 static void fuse_dev_wake_and_unlock(struct fuse_iqueue *fiq)
234 __releases(fiq->lock)
235 {
236 	wake_up(&fiq->waitq);
237 	kill_fasync(&fiq->fasync, SIGIO, POLL_IN);
238 	spin_unlock(&fiq->lock);
239 }
240 
241 void fuse_dev_queue_forget(struct fuse_iqueue *fiq,
242 			   struct fuse_forget_link *forget)
243 {
244 	spin_lock(&fiq->lock);
245 	if (fiq->connected) {
246 		fiq->forget_list_tail->next = forget;
247 		fiq->forget_list_tail = forget;
248 		fuse_dev_wake_and_unlock(fiq);
249 	} else {
250 		kfree(forget);
251 		spin_unlock(&fiq->lock);
252 	}
253 }
254 
255 void fuse_dev_queue_interrupt(struct fuse_iqueue *fiq, struct fuse_req *req)
256 {
257 	spin_lock(&fiq->lock);
258 	if (list_empty(&req->intr_entry)) {
259 		list_add_tail(&req->intr_entry, &fiq->interrupts);
260 		/*
261 		 * Pairs with smp_mb() implied by test_and_set_bit()
262 		 * from fuse_request_end().
263 		 */
264 		smp_mb();
265 		if (test_bit(FR_FINISHED, &req->flags)) {
266 			list_del_init(&req->intr_entry);
267 			spin_unlock(&fiq->lock);
268 		} else  {
269 			fuse_dev_wake_and_unlock(fiq);
270 		}
271 	} else {
272 		spin_unlock(&fiq->lock);
273 	}
274 }
275 
276 static void fuse_dev_queue_req(struct fuse_iqueue *fiq, struct fuse_req *req)
277 {
278 	spin_lock(&fiq->lock);
279 	if (fiq->connected) {
280 		if (req->in.h.opcode != FUSE_NOTIFY_REPLY)
281 			req->in.h.unique = fuse_get_unique_locked(fiq);
282 		list_add_tail(&req->list, &fiq->pending);
283 		fuse_dev_wake_and_unlock(fiq);
284 	} else {
285 		spin_unlock(&fiq->lock);
286 		req->out.h.error = -ENOTCONN;
287 		clear_bit(FR_PENDING, &req->flags);
288 		fuse_request_end(req);
289 	}
290 }
291 
292 const struct fuse_iqueue_ops fuse_dev_fiq_ops = {
293 	.send_forget	= fuse_dev_queue_forget,
294 	.send_interrupt	= fuse_dev_queue_interrupt,
295 	.send_req	= fuse_dev_queue_req,
296 };
297 EXPORT_SYMBOL_GPL(fuse_dev_fiq_ops);
298 
299 static void fuse_send_one(struct fuse_iqueue *fiq, struct fuse_req *req)
300 {
301 	req->in.h.len = sizeof(struct fuse_in_header) +
302 		fuse_len_args(req->args->in_numargs,
303 			      (struct fuse_arg *) req->args->in_args);
304 	trace_fuse_request_send(req);
305 	fiq->ops->send_req(fiq, req);
306 }
307 
308 void fuse_queue_forget(struct fuse_conn *fc, struct fuse_forget_link *forget,
309 		       u64 nodeid, u64 nlookup)
310 {
311 	struct fuse_iqueue *fiq = &fc->iq;
312 
313 	forget->forget_one.nodeid = nodeid;
314 	forget->forget_one.nlookup = nlookup;
315 
316 	fiq->ops->send_forget(fiq, forget);
317 }
318 
319 static void flush_bg_queue(struct fuse_conn *fc)
320 {
321 	struct fuse_iqueue *fiq = &fc->iq;
322 
323 	while (fc->active_background < fc->max_background &&
324 	       !list_empty(&fc->bg_queue)) {
325 		struct fuse_req *req;
326 
327 		req = list_first_entry(&fc->bg_queue, struct fuse_req, list);
328 		list_del(&req->list);
329 		fc->active_background++;
330 		fuse_send_one(fiq, req);
331 	}
332 }
333 
334 /*
335  * This function is called when a request is finished.  Either a reply
336  * has arrived or it was aborted (and not yet sent) or some error
337  * occurred during communication with userspace, or the device file
338  * was closed.  The requester thread is woken up (if still waiting),
339  * the 'end' callback is called if given, else the reference to the
340  * request is released
341  */
342 void fuse_request_end(struct fuse_req *req)
343 {
344 	struct fuse_mount *fm = req->fm;
345 	struct fuse_conn *fc = fm->fc;
346 	struct fuse_iqueue *fiq = &fc->iq;
347 
348 	if (test_and_set_bit(FR_FINISHED, &req->flags))
349 		goto put_request;
350 
351 	trace_fuse_request_end(req);
352 	/*
353 	 * test_and_set_bit() implies smp_mb() between bit
354 	 * changing and below FR_INTERRUPTED check. Pairs with
355 	 * smp_mb() from queue_interrupt().
356 	 */
357 	if (test_bit(FR_INTERRUPTED, &req->flags)) {
358 		spin_lock(&fiq->lock);
359 		list_del_init(&req->intr_entry);
360 		spin_unlock(&fiq->lock);
361 	}
362 	WARN_ON(test_bit(FR_PENDING, &req->flags));
363 	WARN_ON(test_bit(FR_SENT, &req->flags));
364 	if (test_bit(FR_BACKGROUND, &req->flags)) {
365 		spin_lock(&fc->bg_lock);
366 		clear_bit(FR_BACKGROUND, &req->flags);
367 		if (fc->num_background == fc->max_background) {
368 			fc->blocked = 0;
369 			wake_up(&fc->blocked_waitq);
370 		} else if (!fc->blocked) {
371 			/*
372 			 * Wake up next waiter, if any.  It's okay to use
373 			 * waitqueue_active(), as we've already synced up
374 			 * fc->blocked with waiters with the wake_up() call
375 			 * above.
376 			 */
377 			if (waitqueue_active(&fc->blocked_waitq))
378 				wake_up(&fc->blocked_waitq);
379 		}
380 
381 		fc->num_background--;
382 		fc->active_background--;
383 		flush_bg_queue(fc);
384 		spin_unlock(&fc->bg_lock);
385 	} else {
386 		/* Wake up waiter sleeping in request_wait_answer() */
387 		wake_up(&req->waitq);
388 	}
389 
390 	if (test_bit(FR_ASYNC, &req->flags))
391 		req->args->end(fm, req->args, req->out.h.error);
392 put_request:
393 	fuse_put_request(req);
394 }
395 EXPORT_SYMBOL_GPL(fuse_request_end);
396 
397 static int queue_interrupt(struct fuse_req *req)
398 {
399 	struct fuse_iqueue *fiq = &req->fm->fc->iq;
400 
401 	/* Check for we've sent request to interrupt this req */
402 	if (unlikely(!test_bit(FR_INTERRUPTED, &req->flags)))
403 		return -EINVAL;
404 
405 	fiq->ops->send_interrupt(fiq, req);
406 
407 	return 0;
408 }
409 
410 static void request_wait_answer(struct fuse_req *req)
411 {
412 	struct fuse_conn *fc = req->fm->fc;
413 	struct fuse_iqueue *fiq = &fc->iq;
414 	int err;
415 
416 	if (!fc->no_interrupt) {
417 		/* Any signal may interrupt this */
418 		err = wait_event_interruptible(req->waitq,
419 					test_bit(FR_FINISHED, &req->flags));
420 		if (!err)
421 			return;
422 
423 		set_bit(FR_INTERRUPTED, &req->flags);
424 		/* matches barrier in fuse_dev_do_read() */
425 		smp_mb__after_atomic();
426 		if (test_bit(FR_SENT, &req->flags))
427 			queue_interrupt(req);
428 	}
429 
430 	if (!test_bit(FR_FORCE, &req->flags)) {
431 		/* Only fatal signals may interrupt this */
432 		err = wait_event_killable(req->waitq,
433 					test_bit(FR_FINISHED, &req->flags));
434 		if (!err)
435 			return;
436 
437 		spin_lock(&fiq->lock);
438 		/* Request is not yet in userspace, bail out */
439 		if (test_bit(FR_PENDING, &req->flags)) {
440 			list_del(&req->list);
441 			spin_unlock(&fiq->lock);
442 			__fuse_put_request(req);
443 			req->out.h.error = -EINTR;
444 			return;
445 		}
446 		spin_unlock(&fiq->lock);
447 	}
448 
449 	/*
450 	 * Either request is already in userspace, or it was forced.
451 	 * Wait it out.
452 	 */
453 	wait_event(req->waitq, test_bit(FR_FINISHED, &req->flags));
454 }
455 
456 static void __fuse_request_send(struct fuse_req *req)
457 {
458 	struct fuse_iqueue *fiq = &req->fm->fc->iq;
459 
460 	BUG_ON(test_bit(FR_BACKGROUND, &req->flags));
461 
462 	/* acquire extra reference, since request is still needed after
463 	   fuse_request_end() */
464 	__fuse_get_request(req);
465 	fuse_send_one(fiq, req);
466 
467 	request_wait_answer(req);
468 	/* Pairs with smp_wmb() in fuse_request_end() */
469 	smp_rmb();
470 }
471 
472 static void fuse_adjust_compat(struct fuse_conn *fc, struct fuse_args *args)
473 {
474 	if (fc->minor < 4 && args->opcode == FUSE_STATFS)
475 		args->out_args[0].size = FUSE_COMPAT_STATFS_SIZE;
476 
477 	if (fc->minor < 9) {
478 		switch (args->opcode) {
479 		case FUSE_LOOKUP:
480 		case FUSE_CREATE:
481 		case FUSE_MKNOD:
482 		case FUSE_MKDIR:
483 		case FUSE_SYMLINK:
484 		case FUSE_LINK:
485 			args->out_args[0].size = FUSE_COMPAT_ENTRY_OUT_SIZE;
486 			break;
487 		case FUSE_GETATTR:
488 		case FUSE_SETATTR:
489 			args->out_args[0].size = FUSE_COMPAT_ATTR_OUT_SIZE;
490 			break;
491 		}
492 	}
493 	if (fc->minor < 12) {
494 		switch (args->opcode) {
495 		case FUSE_CREATE:
496 			args->in_args[0].size = sizeof(struct fuse_open_in);
497 			break;
498 		case FUSE_MKNOD:
499 			args->in_args[0].size = FUSE_COMPAT_MKNOD_IN_SIZE;
500 			break;
501 		}
502 	}
503 }
504 
505 static void fuse_force_creds(struct fuse_req *req)
506 {
507 	struct fuse_conn *fc = req->fm->fc;
508 
509 	if (!req->fm->sb || req->fm->sb->s_iflags & SB_I_NOIDMAP) {
510 		req->in.h.uid = from_kuid_munged(fc->user_ns, current_fsuid());
511 		req->in.h.gid = from_kgid_munged(fc->user_ns, current_fsgid());
512 	} else {
513 		req->in.h.uid = FUSE_INVALID_UIDGID;
514 		req->in.h.gid = FUSE_INVALID_UIDGID;
515 	}
516 
517 	req->in.h.pid = pid_nr_ns(task_pid(current), fc->pid_ns);
518 }
519 
520 static void fuse_args_to_req(struct fuse_req *req, struct fuse_args *args)
521 {
522 	req->in.h.opcode = args->opcode;
523 	req->in.h.nodeid = args->nodeid;
524 	req->args = args;
525 	if (args->is_ext)
526 		req->in.h.total_extlen = args->in_args[args->ext_idx].size / 8;
527 	if (args->end)
528 		__set_bit(FR_ASYNC, &req->flags);
529 }
530 
531 ssize_t __fuse_simple_request(struct mnt_idmap *idmap,
532 			      struct fuse_mount *fm,
533 			      struct fuse_args *args)
534 {
535 	struct fuse_conn *fc = fm->fc;
536 	struct fuse_req *req;
537 	ssize_t ret;
538 
539 	if (args->force) {
540 		atomic_inc(&fc->num_waiting);
541 		req = fuse_request_alloc(fm, GFP_KERNEL | __GFP_NOFAIL);
542 
543 		if (!args->nocreds)
544 			fuse_force_creds(req);
545 
546 		__set_bit(FR_WAITING, &req->flags);
547 		__set_bit(FR_FORCE, &req->flags);
548 	} else {
549 		WARN_ON(args->nocreds);
550 		req = fuse_get_req(idmap, fm, false);
551 		if (IS_ERR(req))
552 			return PTR_ERR(req);
553 	}
554 
555 	/* Needs to be done after fuse_get_req() so that fc->minor is valid */
556 	fuse_adjust_compat(fc, args);
557 	fuse_args_to_req(req, args);
558 
559 	if (!args->noreply)
560 		__set_bit(FR_ISREPLY, &req->flags);
561 	__fuse_request_send(req);
562 	ret = req->out.h.error;
563 	if (!ret && args->out_argvar) {
564 		BUG_ON(args->out_numargs == 0);
565 		ret = args->out_args[args->out_numargs - 1].size;
566 	}
567 	fuse_put_request(req);
568 
569 	return ret;
570 }
571 
572 #ifdef CONFIG_FUSE_IO_URING
573 static bool fuse_request_queue_background_uring(struct fuse_conn *fc,
574 					       struct fuse_req *req)
575 {
576 	struct fuse_iqueue *fiq = &fc->iq;
577 
578 	req->in.h.unique = fuse_get_unique(fiq);
579 	req->in.h.len = sizeof(struct fuse_in_header) +
580 		fuse_len_args(req->args->in_numargs,
581 			      (struct fuse_arg *) req->args->in_args);
582 
583 	return fuse_uring_queue_bq_req(req);
584 }
585 #endif
586 
587 /*
588  * @return true if queued
589  */
590 static int fuse_request_queue_background(struct fuse_req *req)
591 {
592 	struct fuse_mount *fm = req->fm;
593 	struct fuse_conn *fc = fm->fc;
594 	bool queued = false;
595 
596 	WARN_ON(!test_bit(FR_BACKGROUND, &req->flags));
597 	if (!test_bit(FR_WAITING, &req->flags)) {
598 		__set_bit(FR_WAITING, &req->flags);
599 		atomic_inc(&fc->num_waiting);
600 	}
601 	__set_bit(FR_ISREPLY, &req->flags);
602 
603 #ifdef CONFIG_FUSE_IO_URING
604 	if (fuse_uring_ready(fc))
605 		return fuse_request_queue_background_uring(fc, req);
606 #endif
607 
608 	spin_lock(&fc->bg_lock);
609 	if (likely(fc->connected)) {
610 		fc->num_background++;
611 		if (fc->num_background == fc->max_background)
612 			fc->blocked = 1;
613 		list_add_tail(&req->list, &fc->bg_queue);
614 		flush_bg_queue(fc);
615 		queued = true;
616 	}
617 	spin_unlock(&fc->bg_lock);
618 
619 	return queued;
620 }
621 
622 int fuse_simple_background(struct fuse_mount *fm, struct fuse_args *args,
623 			    gfp_t gfp_flags)
624 {
625 	struct fuse_req *req;
626 
627 	if (args->force) {
628 		WARN_ON(!args->nocreds);
629 		req = fuse_request_alloc(fm, gfp_flags);
630 		if (!req)
631 			return -ENOMEM;
632 		__set_bit(FR_BACKGROUND, &req->flags);
633 	} else {
634 		WARN_ON(args->nocreds);
635 		req = fuse_get_req(&invalid_mnt_idmap, fm, true);
636 		if (IS_ERR(req))
637 			return PTR_ERR(req);
638 	}
639 
640 	fuse_args_to_req(req, args);
641 
642 	if (!fuse_request_queue_background(req)) {
643 		fuse_put_request(req);
644 		return -ENOTCONN;
645 	}
646 
647 	return 0;
648 }
649 EXPORT_SYMBOL_GPL(fuse_simple_background);
650 
651 static int fuse_simple_notify_reply(struct fuse_mount *fm,
652 				    struct fuse_args *args, u64 unique)
653 {
654 	struct fuse_req *req;
655 	struct fuse_iqueue *fiq = &fm->fc->iq;
656 
657 	req = fuse_get_req(&invalid_mnt_idmap, fm, false);
658 	if (IS_ERR(req))
659 		return PTR_ERR(req);
660 
661 	__clear_bit(FR_ISREPLY, &req->flags);
662 	req->in.h.unique = unique;
663 
664 	fuse_args_to_req(req, args);
665 
666 	fuse_send_one(fiq, req);
667 
668 	return 0;
669 }
670 
671 /*
672  * Lock the request.  Up to the next unlock_request() there mustn't be
673  * anything that could cause a page-fault.  If the request was already
674  * aborted bail out.
675  */
676 static int lock_request(struct fuse_req *req)
677 {
678 	int err = 0;
679 	if (req) {
680 		spin_lock(&req->waitq.lock);
681 		if (test_bit(FR_ABORTED, &req->flags))
682 			err = -ENOENT;
683 		else
684 			set_bit(FR_LOCKED, &req->flags);
685 		spin_unlock(&req->waitq.lock);
686 	}
687 	return err;
688 }
689 
690 /*
691  * Unlock request.  If it was aborted while locked, caller is responsible
692  * for unlocking and ending the request.
693  */
694 static int unlock_request(struct fuse_req *req)
695 {
696 	int err = 0;
697 	if (req) {
698 		spin_lock(&req->waitq.lock);
699 		if (test_bit(FR_ABORTED, &req->flags))
700 			err = -ENOENT;
701 		else
702 			clear_bit(FR_LOCKED, &req->flags);
703 		spin_unlock(&req->waitq.lock);
704 	}
705 	return err;
706 }
707 
708 void fuse_copy_init(struct fuse_copy_state *cs, int write,
709 		    struct iov_iter *iter)
710 {
711 	memset(cs, 0, sizeof(*cs));
712 	cs->write = write;
713 	cs->iter = iter;
714 }
715 
716 /* Unmap and put previous page of userspace buffer */
717 static void fuse_copy_finish(struct fuse_copy_state *cs)
718 {
719 	if (cs->currbuf) {
720 		struct pipe_buffer *buf = cs->currbuf;
721 
722 		if (cs->write)
723 			buf->len = PAGE_SIZE - cs->len;
724 		cs->currbuf = NULL;
725 	} else if (cs->pg) {
726 		if (cs->write) {
727 			flush_dcache_page(cs->pg);
728 			set_page_dirty_lock(cs->pg);
729 		}
730 		put_page(cs->pg);
731 	}
732 	cs->pg = NULL;
733 }
734 
735 /*
736  * Get another pagefull of userspace buffer, and map it to kernel
737  * address space, and lock request
738  */
739 static int fuse_copy_fill(struct fuse_copy_state *cs)
740 {
741 	struct page *page;
742 	int err;
743 
744 	err = unlock_request(cs->req);
745 	if (err)
746 		return err;
747 
748 	fuse_copy_finish(cs);
749 	if (cs->pipebufs) {
750 		struct pipe_buffer *buf = cs->pipebufs;
751 
752 		if (!cs->write) {
753 			err = pipe_buf_confirm(cs->pipe, buf);
754 			if (err)
755 				return err;
756 
757 			BUG_ON(!cs->nr_segs);
758 			cs->currbuf = buf;
759 			cs->pg = buf->page;
760 			cs->offset = buf->offset;
761 			cs->len = buf->len;
762 			cs->pipebufs++;
763 			cs->nr_segs--;
764 		} else {
765 			if (cs->nr_segs >= cs->pipe->max_usage)
766 				return -EIO;
767 
768 			page = alloc_page(GFP_HIGHUSER);
769 			if (!page)
770 				return -ENOMEM;
771 
772 			buf->page = page;
773 			buf->offset = 0;
774 			buf->len = 0;
775 
776 			cs->currbuf = buf;
777 			cs->pg = page;
778 			cs->offset = 0;
779 			cs->len = PAGE_SIZE;
780 			cs->pipebufs++;
781 			cs->nr_segs++;
782 		}
783 	} else {
784 		size_t off;
785 		err = iov_iter_get_pages2(cs->iter, &page, PAGE_SIZE, 1, &off);
786 		if (err < 0)
787 			return err;
788 		BUG_ON(!err);
789 		cs->len = err;
790 		cs->offset = off;
791 		cs->pg = page;
792 	}
793 
794 	return lock_request(cs->req);
795 }
796 
797 /* Do as much copy to/from userspace buffer as we can */
798 static int fuse_copy_do(struct fuse_copy_state *cs, void **val, unsigned *size)
799 {
800 	unsigned ncpy = min(*size, cs->len);
801 	if (val) {
802 		void *pgaddr = kmap_local_page(cs->pg);
803 		void *buf = pgaddr + cs->offset;
804 
805 		if (cs->write)
806 			memcpy(buf, *val, ncpy);
807 		else
808 			memcpy(*val, buf, ncpy);
809 
810 		kunmap_local(pgaddr);
811 		*val += ncpy;
812 	}
813 	*size -= ncpy;
814 	cs->len -= ncpy;
815 	cs->offset += ncpy;
816 	if (cs->is_uring)
817 		cs->ring.copied_sz += ncpy;
818 
819 	return ncpy;
820 }
821 
822 static int fuse_check_folio(struct folio *folio)
823 {
824 	if (folio_mapped(folio) ||
825 	    folio->mapping != NULL ||
826 	    (folio->flags & PAGE_FLAGS_CHECK_AT_PREP &
827 	     ~(1 << PG_locked |
828 	       1 << PG_referenced |
829 	       1 << PG_lru |
830 	       1 << PG_active |
831 	       1 << PG_workingset |
832 	       1 << PG_reclaim |
833 	       1 << PG_waiters |
834 	       LRU_GEN_MASK | LRU_REFS_MASK))) {
835 		dump_page(&folio->page, "fuse: trying to steal weird page");
836 		return 1;
837 	}
838 	return 0;
839 }
840 
841 static int fuse_try_move_page(struct fuse_copy_state *cs, struct page **pagep)
842 {
843 	int err;
844 	struct folio *oldfolio = page_folio(*pagep);
845 	struct folio *newfolio;
846 	struct pipe_buffer *buf = cs->pipebufs;
847 
848 	folio_get(oldfolio);
849 	err = unlock_request(cs->req);
850 	if (err)
851 		goto out_put_old;
852 
853 	fuse_copy_finish(cs);
854 
855 	err = pipe_buf_confirm(cs->pipe, buf);
856 	if (err)
857 		goto out_put_old;
858 
859 	BUG_ON(!cs->nr_segs);
860 	cs->currbuf = buf;
861 	cs->len = buf->len;
862 	cs->pipebufs++;
863 	cs->nr_segs--;
864 
865 	if (cs->len != PAGE_SIZE)
866 		goto out_fallback;
867 
868 	if (!pipe_buf_try_steal(cs->pipe, buf))
869 		goto out_fallback;
870 
871 	newfolio = page_folio(buf->page);
872 
873 	folio_clear_uptodate(newfolio);
874 	folio_clear_mappedtodisk(newfolio);
875 
876 	if (fuse_check_folio(newfolio) != 0)
877 		goto out_fallback_unlock;
878 
879 	/*
880 	 * This is a new and locked page, it shouldn't be mapped or
881 	 * have any special flags on it
882 	 */
883 	if (WARN_ON(folio_mapped(oldfolio)))
884 		goto out_fallback_unlock;
885 	if (WARN_ON(folio_has_private(oldfolio)))
886 		goto out_fallback_unlock;
887 	if (WARN_ON(folio_test_dirty(oldfolio) ||
888 				folio_test_writeback(oldfolio)))
889 		goto out_fallback_unlock;
890 	if (WARN_ON(folio_test_mlocked(oldfolio)))
891 		goto out_fallback_unlock;
892 
893 	replace_page_cache_folio(oldfolio, newfolio);
894 
895 	folio_get(newfolio);
896 
897 	if (!(buf->flags & PIPE_BUF_FLAG_LRU))
898 		folio_add_lru(newfolio);
899 
900 	/*
901 	 * Release while we have extra ref on stolen page.  Otherwise
902 	 * anon_pipe_buf_release() might think the page can be reused.
903 	 */
904 	pipe_buf_release(cs->pipe, buf);
905 
906 	err = 0;
907 	spin_lock(&cs->req->waitq.lock);
908 	if (test_bit(FR_ABORTED, &cs->req->flags))
909 		err = -ENOENT;
910 	else
911 		*pagep = &newfolio->page;
912 	spin_unlock(&cs->req->waitq.lock);
913 
914 	if (err) {
915 		folio_unlock(newfolio);
916 		folio_put(newfolio);
917 		goto out_put_old;
918 	}
919 
920 	folio_unlock(oldfolio);
921 	/* Drop ref for ap->pages[] array */
922 	folio_put(oldfolio);
923 	cs->len = 0;
924 
925 	err = 0;
926 out_put_old:
927 	/* Drop ref obtained in this function */
928 	folio_put(oldfolio);
929 	return err;
930 
931 out_fallback_unlock:
932 	folio_unlock(newfolio);
933 out_fallback:
934 	cs->pg = buf->page;
935 	cs->offset = buf->offset;
936 
937 	err = lock_request(cs->req);
938 	if (!err)
939 		err = 1;
940 
941 	goto out_put_old;
942 }
943 
944 static int fuse_ref_page(struct fuse_copy_state *cs, struct page *page,
945 			 unsigned offset, unsigned count)
946 {
947 	struct pipe_buffer *buf;
948 	int err;
949 
950 	if (cs->nr_segs >= cs->pipe->max_usage)
951 		return -EIO;
952 
953 	get_page(page);
954 	err = unlock_request(cs->req);
955 	if (err) {
956 		put_page(page);
957 		return err;
958 	}
959 
960 	fuse_copy_finish(cs);
961 
962 	buf = cs->pipebufs;
963 	buf->page = page;
964 	buf->offset = offset;
965 	buf->len = count;
966 
967 	cs->pipebufs++;
968 	cs->nr_segs++;
969 	cs->len = 0;
970 
971 	return 0;
972 }
973 
974 /*
975  * Copy a page in the request to/from the userspace buffer.  Must be
976  * done atomically
977  */
978 static int fuse_copy_page(struct fuse_copy_state *cs, struct page **pagep,
979 			  unsigned offset, unsigned count, int zeroing)
980 {
981 	int err;
982 	struct page *page = *pagep;
983 
984 	if (page && zeroing && count < PAGE_SIZE)
985 		clear_highpage(page);
986 
987 	while (count) {
988 		if (cs->write && cs->pipebufs && page) {
989 			/*
990 			 * Can't control lifetime of pipe buffers, so always
991 			 * copy user pages.
992 			 */
993 			if (cs->req->args->user_pages) {
994 				err = fuse_copy_fill(cs);
995 				if (err)
996 					return err;
997 			} else {
998 				return fuse_ref_page(cs, page, offset, count);
999 			}
1000 		} else if (!cs->len) {
1001 			if (cs->move_pages && page &&
1002 			    offset == 0 && count == PAGE_SIZE) {
1003 				err = fuse_try_move_page(cs, pagep);
1004 				if (err <= 0)
1005 					return err;
1006 			} else {
1007 				err = fuse_copy_fill(cs);
1008 				if (err)
1009 					return err;
1010 			}
1011 		}
1012 		if (page) {
1013 			void *mapaddr = kmap_local_page(page);
1014 			void *buf = mapaddr + offset;
1015 			offset += fuse_copy_do(cs, &buf, &count);
1016 			kunmap_local(mapaddr);
1017 		} else
1018 			offset += fuse_copy_do(cs, NULL, &count);
1019 	}
1020 	if (page && !cs->write)
1021 		flush_dcache_page(page);
1022 	return 0;
1023 }
1024 
1025 /* Copy pages in the request to/from userspace buffer */
1026 static int fuse_copy_pages(struct fuse_copy_state *cs, unsigned nbytes,
1027 			   int zeroing)
1028 {
1029 	unsigned i;
1030 	struct fuse_req *req = cs->req;
1031 	struct fuse_args_pages *ap = container_of(req->args, typeof(*ap), args);
1032 
1033 	for (i = 0; i < ap->num_folios && (nbytes || zeroing); i++) {
1034 		int err;
1035 		unsigned int offset = ap->descs[i].offset;
1036 		unsigned int count = min(nbytes, ap->descs[i].length);
1037 		struct page *orig, *pagep;
1038 
1039 		orig = pagep = &ap->folios[i]->page;
1040 
1041 		err = fuse_copy_page(cs, &pagep, offset, count, zeroing);
1042 		if (err)
1043 			return err;
1044 
1045 		nbytes -= count;
1046 
1047 		/*
1048 		 *  fuse_copy_page may have moved a page from a pipe instead of
1049 		 *  copying into our given page, so update the folios if it was
1050 		 *  replaced.
1051 		 */
1052 		if (pagep != orig)
1053 			ap->folios[i] = page_folio(pagep);
1054 	}
1055 	return 0;
1056 }
1057 
1058 /* Copy a single argument in the request to/from userspace buffer */
1059 static int fuse_copy_one(struct fuse_copy_state *cs, void *val, unsigned size)
1060 {
1061 	while (size) {
1062 		if (!cs->len) {
1063 			int err = fuse_copy_fill(cs);
1064 			if (err)
1065 				return err;
1066 		}
1067 		fuse_copy_do(cs, &val, &size);
1068 	}
1069 	return 0;
1070 }
1071 
1072 /* Copy request arguments to/from userspace buffer */
1073 int fuse_copy_args(struct fuse_copy_state *cs, unsigned numargs,
1074 		   unsigned argpages, struct fuse_arg *args,
1075 		   int zeroing)
1076 {
1077 	int err = 0;
1078 	unsigned i;
1079 
1080 	for (i = 0; !err && i < numargs; i++)  {
1081 		struct fuse_arg *arg = &args[i];
1082 		if (i == numargs - 1 && argpages)
1083 			err = fuse_copy_pages(cs, arg->size, zeroing);
1084 		else
1085 			err = fuse_copy_one(cs, arg->value, arg->size);
1086 	}
1087 	return err;
1088 }
1089 
1090 static int forget_pending(struct fuse_iqueue *fiq)
1091 {
1092 	return fiq->forget_list_head.next != NULL;
1093 }
1094 
1095 static int request_pending(struct fuse_iqueue *fiq)
1096 {
1097 	return !list_empty(&fiq->pending) || !list_empty(&fiq->interrupts) ||
1098 		forget_pending(fiq);
1099 }
1100 
1101 /*
1102  * Transfer an interrupt request to userspace
1103  *
1104  * Unlike other requests this is assembled on demand, without a need
1105  * to allocate a separate fuse_req structure.
1106  *
1107  * Called with fiq->lock held, releases it
1108  */
1109 static int fuse_read_interrupt(struct fuse_iqueue *fiq,
1110 			       struct fuse_copy_state *cs,
1111 			       size_t nbytes, struct fuse_req *req)
1112 __releases(fiq->lock)
1113 {
1114 	struct fuse_in_header ih;
1115 	struct fuse_interrupt_in arg;
1116 	unsigned reqsize = sizeof(ih) + sizeof(arg);
1117 	int err;
1118 
1119 	list_del_init(&req->intr_entry);
1120 	memset(&ih, 0, sizeof(ih));
1121 	memset(&arg, 0, sizeof(arg));
1122 	ih.len = reqsize;
1123 	ih.opcode = FUSE_INTERRUPT;
1124 	ih.unique = (req->in.h.unique | FUSE_INT_REQ_BIT);
1125 	arg.unique = req->in.h.unique;
1126 
1127 	spin_unlock(&fiq->lock);
1128 	if (nbytes < reqsize)
1129 		return -EINVAL;
1130 
1131 	err = fuse_copy_one(cs, &ih, sizeof(ih));
1132 	if (!err)
1133 		err = fuse_copy_one(cs, &arg, sizeof(arg));
1134 	fuse_copy_finish(cs);
1135 
1136 	return err ? err : reqsize;
1137 }
1138 
1139 static struct fuse_forget_link *fuse_dequeue_forget(struct fuse_iqueue *fiq,
1140 						    unsigned int max,
1141 						    unsigned int *countp)
1142 {
1143 	struct fuse_forget_link *head = fiq->forget_list_head.next;
1144 	struct fuse_forget_link **newhead = &head;
1145 	unsigned count;
1146 
1147 	for (count = 0; *newhead != NULL && count < max; count++)
1148 		newhead = &(*newhead)->next;
1149 
1150 	fiq->forget_list_head.next = *newhead;
1151 	*newhead = NULL;
1152 	if (fiq->forget_list_head.next == NULL)
1153 		fiq->forget_list_tail = &fiq->forget_list_head;
1154 
1155 	if (countp != NULL)
1156 		*countp = count;
1157 
1158 	return head;
1159 }
1160 
1161 static int fuse_read_single_forget(struct fuse_iqueue *fiq,
1162 				   struct fuse_copy_state *cs,
1163 				   size_t nbytes)
1164 __releases(fiq->lock)
1165 {
1166 	int err;
1167 	struct fuse_forget_link *forget = fuse_dequeue_forget(fiq, 1, NULL);
1168 	struct fuse_forget_in arg = {
1169 		.nlookup = forget->forget_one.nlookup,
1170 	};
1171 	struct fuse_in_header ih = {
1172 		.opcode = FUSE_FORGET,
1173 		.nodeid = forget->forget_one.nodeid,
1174 		.unique = fuse_get_unique_locked(fiq),
1175 		.len = sizeof(ih) + sizeof(arg),
1176 	};
1177 
1178 	spin_unlock(&fiq->lock);
1179 	kfree(forget);
1180 	if (nbytes < ih.len)
1181 		return -EINVAL;
1182 
1183 	err = fuse_copy_one(cs, &ih, sizeof(ih));
1184 	if (!err)
1185 		err = fuse_copy_one(cs, &arg, sizeof(arg));
1186 	fuse_copy_finish(cs);
1187 
1188 	if (err)
1189 		return err;
1190 
1191 	return ih.len;
1192 }
1193 
1194 static int fuse_read_batch_forget(struct fuse_iqueue *fiq,
1195 				   struct fuse_copy_state *cs, size_t nbytes)
1196 __releases(fiq->lock)
1197 {
1198 	int err;
1199 	unsigned max_forgets;
1200 	unsigned count;
1201 	struct fuse_forget_link *head;
1202 	struct fuse_batch_forget_in arg = { .count = 0 };
1203 	struct fuse_in_header ih = {
1204 		.opcode = FUSE_BATCH_FORGET,
1205 		.unique = fuse_get_unique_locked(fiq),
1206 		.len = sizeof(ih) + sizeof(arg),
1207 	};
1208 
1209 	if (nbytes < ih.len) {
1210 		spin_unlock(&fiq->lock);
1211 		return -EINVAL;
1212 	}
1213 
1214 	max_forgets = (nbytes - ih.len) / sizeof(struct fuse_forget_one);
1215 	head = fuse_dequeue_forget(fiq, max_forgets, &count);
1216 	spin_unlock(&fiq->lock);
1217 
1218 	arg.count = count;
1219 	ih.len += count * sizeof(struct fuse_forget_one);
1220 	err = fuse_copy_one(cs, &ih, sizeof(ih));
1221 	if (!err)
1222 		err = fuse_copy_one(cs, &arg, sizeof(arg));
1223 
1224 	while (head) {
1225 		struct fuse_forget_link *forget = head;
1226 
1227 		if (!err) {
1228 			err = fuse_copy_one(cs, &forget->forget_one,
1229 					    sizeof(forget->forget_one));
1230 		}
1231 		head = forget->next;
1232 		kfree(forget);
1233 	}
1234 
1235 	fuse_copy_finish(cs);
1236 
1237 	if (err)
1238 		return err;
1239 
1240 	return ih.len;
1241 }
1242 
1243 static int fuse_read_forget(struct fuse_conn *fc, struct fuse_iqueue *fiq,
1244 			    struct fuse_copy_state *cs,
1245 			    size_t nbytes)
1246 __releases(fiq->lock)
1247 {
1248 	if (fc->minor < 16 || fiq->forget_list_head.next->next == NULL)
1249 		return fuse_read_single_forget(fiq, cs, nbytes);
1250 	else
1251 		return fuse_read_batch_forget(fiq, cs, nbytes);
1252 }
1253 
1254 /*
1255  * Read a single request into the userspace filesystem's buffer.  This
1256  * function waits until a request is available, then removes it from
1257  * the pending list and copies request data to userspace buffer.  If
1258  * no reply is needed (FORGET) or request has been aborted or there
1259  * was an error during the copying then it's finished by calling
1260  * fuse_request_end().  Otherwise add it to the processing list, and set
1261  * the 'sent' flag.
1262  */
1263 static ssize_t fuse_dev_do_read(struct fuse_dev *fud, struct file *file,
1264 				struct fuse_copy_state *cs, size_t nbytes)
1265 {
1266 	ssize_t err;
1267 	struct fuse_conn *fc = fud->fc;
1268 	struct fuse_iqueue *fiq = &fc->iq;
1269 	struct fuse_pqueue *fpq = &fud->pq;
1270 	struct fuse_req *req;
1271 	struct fuse_args *args;
1272 	unsigned reqsize;
1273 	unsigned int hash;
1274 
1275 	/*
1276 	 * Require sane minimum read buffer - that has capacity for fixed part
1277 	 * of any request header + negotiated max_write room for data.
1278 	 *
1279 	 * Historically libfuse reserves 4K for fixed header room, but e.g.
1280 	 * GlusterFS reserves only 80 bytes
1281 	 *
1282 	 *	= `sizeof(fuse_in_header) + sizeof(fuse_write_in)`
1283 	 *
1284 	 * which is the absolute minimum any sane filesystem should be using
1285 	 * for header room.
1286 	 */
1287 	if (nbytes < max_t(size_t, FUSE_MIN_READ_BUFFER,
1288 			   sizeof(struct fuse_in_header) +
1289 			   sizeof(struct fuse_write_in) +
1290 			   fc->max_write))
1291 		return -EINVAL;
1292 
1293  restart:
1294 	for (;;) {
1295 		spin_lock(&fiq->lock);
1296 		if (!fiq->connected || request_pending(fiq))
1297 			break;
1298 		spin_unlock(&fiq->lock);
1299 
1300 		if (file->f_flags & O_NONBLOCK)
1301 			return -EAGAIN;
1302 		err = wait_event_interruptible_exclusive(fiq->waitq,
1303 				!fiq->connected || request_pending(fiq));
1304 		if (err)
1305 			return err;
1306 	}
1307 
1308 	if (!fiq->connected) {
1309 		err = fc->aborted ? -ECONNABORTED : -ENODEV;
1310 		goto err_unlock;
1311 	}
1312 
1313 	if (!list_empty(&fiq->interrupts)) {
1314 		req = list_entry(fiq->interrupts.next, struct fuse_req,
1315 				 intr_entry);
1316 		return fuse_read_interrupt(fiq, cs, nbytes, req);
1317 	}
1318 
1319 	if (forget_pending(fiq)) {
1320 		if (list_empty(&fiq->pending) || fiq->forget_batch-- > 0)
1321 			return fuse_read_forget(fc, fiq, cs, nbytes);
1322 
1323 		if (fiq->forget_batch <= -8)
1324 			fiq->forget_batch = 16;
1325 	}
1326 
1327 	req = list_entry(fiq->pending.next, struct fuse_req, list);
1328 	clear_bit(FR_PENDING, &req->flags);
1329 	list_del_init(&req->list);
1330 	spin_unlock(&fiq->lock);
1331 
1332 	args = req->args;
1333 	reqsize = req->in.h.len;
1334 
1335 	/* If request is too large, reply with an error and restart the read */
1336 	if (nbytes < reqsize) {
1337 		req->out.h.error = -EIO;
1338 		/* SETXATTR is special, since it may contain too large data */
1339 		if (args->opcode == FUSE_SETXATTR)
1340 			req->out.h.error = -E2BIG;
1341 		fuse_request_end(req);
1342 		goto restart;
1343 	}
1344 	spin_lock(&fpq->lock);
1345 	/*
1346 	 *  Must not put request on fpq->io queue after having been shut down by
1347 	 *  fuse_abort_conn()
1348 	 */
1349 	if (!fpq->connected) {
1350 		req->out.h.error = err = -ECONNABORTED;
1351 		goto out_end;
1352 
1353 	}
1354 	list_add(&req->list, &fpq->io);
1355 	spin_unlock(&fpq->lock);
1356 	cs->req = req;
1357 	err = fuse_copy_one(cs, &req->in.h, sizeof(req->in.h));
1358 	if (!err)
1359 		err = fuse_copy_args(cs, args->in_numargs, args->in_pages,
1360 				     (struct fuse_arg *) args->in_args, 0);
1361 	fuse_copy_finish(cs);
1362 	spin_lock(&fpq->lock);
1363 	clear_bit(FR_LOCKED, &req->flags);
1364 	if (!fpq->connected) {
1365 		err = fc->aborted ? -ECONNABORTED : -ENODEV;
1366 		goto out_end;
1367 	}
1368 	if (err) {
1369 		req->out.h.error = -EIO;
1370 		goto out_end;
1371 	}
1372 	if (!test_bit(FR_ISREPLY, &req->flags)) {
1373 		err = reqsize;
1374 		goto out_end;
1375 	}
1376 	hash = fuse_req_hash(req->in.h.unique);
1377 	list_move_tail(&req->list, &fpq->processing[hash]);
1378 	__fuse_get_request(req);
1379 	set_bit(FR_SENT, &req->flags);
1380 	spin_unlock(&fpq->lock);
1381 	/* matches barrier in request_wait_answer() */
1382 	smp_mb__after_atomic();
1383 	if (test_bit(FR_INTERRUPTED, &req->flags))
1384 		queue_interrupt(req);
1385 	fuse_put_request(req);
1386 
1387 	return reqsize;
1388 
1389 out_end:
1390 	if (!test_bit(FR_PRIVATE, &req->flags))
1391 		list_del_init(&req->list);
1392 	spin_unlock(&fpq->lock);
1393 	fuse_request_end(req);
1394 	return err;
1395 
1396  err_unlock:
1397 	spin_unlock(&fiq->lock);
1398 	return err;
1399 }
1400 
1401 static int fuse_dev_open(struct inode *inode, struct file *file)
1402 {
1403 	/*
1404 	 * The fuse device's file's private_data is used to hold
1405 	 * the fuse_conn(ection) when it is mounted, and is used to
1406 	 * keep track of whether the file has been mounted already.
1407 	 */
1408 	file->private_data = NULL;
1409 	return 0;
1410 }
1411 
1412 static ssize_t fuse_dev_read(struct kiocb *iocb, struct iov_iter *to)
1413 {
1414 	struct fuse_copy_state cs;
1415 	struct file *file = iocb->ki_filp;
1416 	struct fuse_dev *fud = fuse_get_dev(file);
1417 
1418 	if (!fud)
1419 		return -EPERM;
1420 
1421 	if (!user_backed_iter(to))
1422 		return -EINVAL;
1423 
1424 	fuse_copy_init(&cs, 1, to);
1425 
1426 	return fuse_dev_do_read(fud, file, &cs, iov_iter_count(to));
1427 }
1428 
1429 static ssize_t fuse_dev_splice_read(struct file *in, loff_t *ppos,
1430 				    struct pipe_inode_info *pipe,
1431 				    size_t len, unsigned int flags)
1432 {
1433 	int total, ret;
1434 	int page_nr = 0;
1435 	struct pipe_buffer *bufs;
1436 	struct fuse_copy_state cs;
1437 	struct fuse_dev *fud = fuse_get_dev(in);
1438 
1439 	if (!fud)
1440 		return -EPERM;
1441 
1442 	bufs = kvmalloc_array(pipe->max_usage, sizeof(struct pipe_buffer),
1443 			      GFP_KERNEL);
1444 	if (!bufs)
1445 		return -ENOMEM;
1446 
1447 	fuse_copy_init(&cs, 1, NULL);
1448 	cs.pipebufs = bufs;
1449 	cs.pipe = pipe;
1450 	ret = fuse_dev_do_read(fud, in, &cs, len);
1451 	if (ret < 0)
1452 		goto out;
1453 
1454 	if (pipe_occupancy(pipe->head, pipe->tail) + cs.nr_segs > pipe->max_usage) {
1455 		ret = -EIO;
1456 		goto out;
1457 	}
1458 
1459 	for (ret = total = 0; page_nr < cs.nr_segs; total += ret) {
1460 		/*
1461 		 * Need to be careful about this.  Having buf->ops in module
1462 		 * code can Oops if the buffer persists after module unload.
1463 		 */
1464 		bufs[page_nr].ops = &nosteal_pipe_buf_ops;
1465 		bufs[page_nr].flags = 0;
1466 		ret = add_to_pipe(pipe, &bufs[page_nr++]);
1467 		if (unlikely(ret < 0))
1468 			break;
1469 	}
1470 	if (total)
1471 		ret = total;
1472 out:
1473 	for (; page_nr < cs.nr_segs; page_nr++)
1474 		put_page(bufs[page_nr].page);
1475 
1476 	kvfree(bufs);
1477 	return ret;
1478 }
1479 
1480 static int fuse_notify_poll(struct fuse_conn *fc, unsigned int size,
1481 			    struct fuse_copy_state *cs)
1482 {
1483 	struct fuse_notify_poll_wakeup_out outarg;
1484 	int err = -EINVAL;
1485 
1486 	if (size != sizeof(outarg))
1487 		goto err;
1488 
1489 	err = fuse_copy_one(cs, &outarg, sizeof(outarg));
1490 	if (err)
1491 		goto err;
1492 
1493 	fuse_copy_finish(cs);
1494 	return fuse_notify_poll_wakeup(fc, &outarg);
1495 
1496 err:
1497 	fuse_copy_finish(cs);
1498 	return err;
1499 }
1500 
1501 static int fuse_notify_inval_inode(struct fuse_conn *fc, unsigned int size,
1502 				   struct fuse_copy_state *cs)
1503 {
1504 	struct fuse_notify_inval_inode_out outarg;
1505 	int err = -EINVAL;
1506 
1507 	if (size != sizeof(outarg))
1508 		goto err;
1509 
1510 	err = fuse_copy_one(cs, &outarg, sizeof(outarg));
1511 	if (err)
1512 		goto err;
1513 	fuse_copy_finish(cs);
1514 
1515 	down_read(&fc->killsb);
1516 	err = fuse_reverse_inval_inode(fc, outarg.ino,
1517 				       outarg.off, outarg.len);
1518 	up_read(&fc->killsb);
1519 	return err;
1520 
1521 err:
1522 	fuse_copy_finish(cs);
1523 	return err;
1524 }
1525 
1526 static int fuse_notify_inval_entry(struct fuse_conn *fc, unsigned int size,
1527 				   struct fuse_copy_state *cs)
1528 {
1529 	struct fuse_notify_inval_entry_out outarg;
1530 	int err = -ENOMEM;
1531 	char *buf;
1532 	struct qstr name;
1533 
1534 	buf = kzalloc(FUSE_NAME_MAX + 1, GFP_KERNEL);
1535 	if (!buf)
1536 		goto err;
1537 
1538 	err = -EINVAL;
1539 	if (size < sizeof(outarg))
1540 		goto err;
1541 
1542 	err = fuse_copy_one(cs, &outarg, sizeof(outarg));
1543 	if (err)
1544 		goto err;
1545 
1546 	err = -ENAMETOOLONG;
1547 	if (outarg.namelen > FUSE_NAME_MAX)
1548 		goto err;
1549 
1550 	err = -EINVAL;
1551 	if (size != sizeof(outarg) + outarg.namelen + 1)
1552 		goto err;
1553 
1554 	name.name = buf;
1555 	name.len = outarg.namelen;
1556 	err = fuse_copy_one(cs, buf, outarg.namelen + 1);
1557 	if (err)
1558 		goto err;
1559 	fuse_copy_finish(cs);
1560 	buf[outarg.namelen] = 0;
1561 
1562 	down_read(&fc->killsb);
1563 	err = fuse_reverse_inval_entry(fc, outarg.parent, 0, &name, outarg.flags);
1564 	up_read(&fc->killsb);
1565 	kfree(buf);
1566 	return err;
1567 
1568 err:
1569 	kfree(buf);
1570 	fuse_copy_finish(cs);
1571 	return err;
1572 }
1573 
1574 static int fuse_notify_delete(struct fuse_conn *fc, unsigned int size,
1575 			      struct fuse_copy_state *cs)
1576 {
1577 	struct fuse_notify_delete_out outarg;
1578 	int err = -ENOMEM;
1579 	char *buf;
1580 	struct qstr name;
1581 
1582 	buf = kzalloc(FUSE_NAME_MAX + 1, GFP_KERNEL);
1583 	if (!buf)
1584 		goto err;
1585 
1586 	err = -EINVAL;
1587 	if (size < sizeof(outarg))
1588 		goto err;
1589 
1590 	err = fuse_copy_one(cs, &outarg, sizeof(outarg));
1591 	if (err)
1592 		goto err;
1593 
1594 	err = -ENAMETOOLONG;
1595 	if (outarg.namelen > FUSE_NAME_MAX)
1596 		goto err;
1597 
1598 	err = -EINVAL;
1599 	if (size != sizeof(outarg) + outarg.namelen + 1)
1600 		goto err;
1601 
1602 	name.name = buf;
1603 	name.len = outarg.namelen;
1604 	err = fuse_copy_one(cs, buf, outarg.namelen + 1);
1605 	if (err)
1606 		goto err;
1607 	fuse_copy_finish(cs);
1608 	buf[outarg.namelen] = 0;
1609 
1610 	down_read(&fc->killsb);
1611 	err = fuse_reverse_inval_entry(fc, outarg.parent, outarg.child, &name, 0);
1612 	up_read(&fc->killsb);
1613 	kfree(buf);
1614 	return err;
1615 
1616 err:
1617 	kfree(buf);
1618 	fuse_copy_finish(cs);
1619 	return err;
1620 }
1621 
1622 static int fuse_notify_store(struct fuse_conn *fc, unsigned int size,
1623 			     struct fuse_copy_state *cs)
1624 {
1625 	struct fuse_notify_store_out outarg;
1626 	struct inode *inode;
1627 	struct address_space *mapping;
1628 	u64 nodeid;
1629 	int err;
1630 	pgoff_t index;
1631 	unsigned int offset;
1632 	unsigned int num;
1633 	loff_t file_size;
1634 	loff_t end;
1635 
1636 	err = -EINVAL;
1637 	if (size < sizeof(outarg))
1638 		goto out_finish;
1639 
1640 	err = fuse_copy_one(cs, &outarg, sizeof(outarg));
1641 	if (err)
1642 		goto out_finish;
1643 
1644 	err = -EINVAL;
1645 	if (size - sizeof(outarg) != outarg.size)
1646 		goto out_finish;
1647 
1648 	nodeid = outarg.nodeid;
1649 
1650 	down_read(&fc->killsb);
1651 
1652 	err = -ENOENT;
1653 	inode = fuse_ilookup(fc, nodeid,  NULL);
1654 	if (!inode)
1655 		goto out_up_killsb;
1656 
1657 	mapping = inode->i_mapping;
1658 	index = outarg.offset >> PAGE_SHIFT;
1659 	offset = outarg.offset & ~PAGE_MASK;
1660 	file_size = i_size_read(inode);
1661 	end = outarg.offset + outarg.size;
1662 	if (end > file_size) {
1663 		file_size = end;
1664 		fuse_write_update_attr(inode, file_size, outarg.size);
1665 	}
1666 
1667 	num = outarg.size;
1668 	while (num) {
1669 		struct folio *folio;
1670 		struct page *page;
1671 		unsigned int this_num;
1672 
1673 		folio = filemap_grab_folio(mapping, index);
1674 		err = PTR_ERR(folio);
1675 		if (IS_ERR(folio))
1676 			goto out_iput;
1677 
1678 		page = &folio->page;
1679 		this_num = min_t(unsigned, num, folio_size(folio) - offset);
1680 		err = fuse_copy_page(cs, &page, offset, this_num, 0);
1681 		if (!folio_test_uptodate(folio) && !err && offset == 0 &&
1682 		    (this_num == folio_size(folio) || file_size == end)) {
1683 			folio_zero_segment(folio, this_num, folio_size(folio));
1684 			folio_mark_uptodate(folio);
1685 		}
1686 		folio_unlock(folio);
1687 		folio_put(folio);
1688 
1689 		if (err)
1690 			goto out_iput;
1691 
1692 		num -= this_num;
1693 		offset = 0;
1694 		index++;
1695 	}
1696 
1697 	err = 0;
1698 
1699 out_iput:
1700 	iput(inode);
1701 out_up_killsb:
1702 	up_read(&fc->killsb);
1703 out_finish:
1704 	fuse_copy_finish(cs);
1705 	return err;
1706 }
1707 
1708 struct fuse_retrieve_args {
1709 	struct fuse_args_pages ap;
1710 	struct fuse_notify_retrieve_in inarg;
1711 };
1712 
1713 static void fuse_retrieve_end(struct fuse_mount *fm, struct fuse_args *args,
1714 			      int error)
1715 {
1716 	struct fuse_retrieve_args *ra =
1717 		container_of(args, typeof(*ra), ap.args);
1718 
1719 	release_pages(ra->ap.folios, ra->ap.num_folios);
1720 	kfree(ra);
1721 }
1722 
1723 static int fuse_retrieve(struct fuse_mount *fm, struct inode *inode,
1724 			 struct fuse_notify_retrieve_out *outarg)
1725 {
1726 	int err;
1727 	struct address_space *mapping = inode->i_mapping;
1728 	pgoff_t index;
1729 	loff_t file_size;
1730 	unsigned int num;
1731 	unsigned int offset;
1732 	size_t total_len = 0;
1733 	unsigned int num_pages, cur_pages = 0;
1734 	struct fuse_conn *fc = fm->fc;
1735 	struct fuse_retrieve_args *ra;
1736 	size_t args_size = sizeof(*ra);
1737 	struct fuse_args_pages *ap;
1738 	struct fuse_args *args;
1739 
1740 	offset = outarg->offset & ~PAGE_MASK;
1741 	file_size = i_size_read(inode);
1742 
1743 	num = min(outarg->size, fc->max_write);
1744 	if (outarg->offset > file_size)
1745 		num = 0;
1746 	else if (outarg->offset + num > file_size)
1747 		num = file_size - outarg->offset;
1748 
1749 	num_pages = (num + offset + PAGE_SIZE - 1) >> PAGE_SHIFT;
1750 	num_pages = min(num_pages, fc->max_pages);
1751 
1752 	args_size += num_pages * (sizeof(ap->folios[0]) + sizeof(ap->descs[0]));
1753 
1754 	ra = kzalloc(args_size, GFP_KERNEL);
1755 	if (!ra)
1756 		return -ENOMEM;
1757 
1758 	ap = &ra->ap;
1759 	ap->folios = (void *) (ra + 1);
1760 	ap->descs = (void *) (ap->folios + num_pages);
1761 
1762 	args = &ap->args;
1763 	args->nodeid = outarg->nodeid;
1764 	args->opcode = FUSE_NOTIFY_REPLY;
1765 	args->in_numargs = 3;
1766 	args->in_pages = true;
1767 	args->end = fuse_retrieve_end;
1768 
1769 	index = outarg->offset >> PAGE_SHIFT;
1770 
1771 	while (num && cur_pages < num_pages) {
1772 		struct folio *folio;
1773 		unsigned int this_num;
1774 
1775 		folio = filemap_get_folio(mapping, index);
1776 		if (IS_ERR(folio))
1777 			break;
1778 
1779 		this_num = min_t(unsigned, num, PAGE_SIZE - offset);
1780 		ap->folios[ap->num_folios] = folio;
1781 		ap->descs[ap->num_folios].offset = offset;
1782 		ap->descs[ap->num_folios].length = this_num;
1783 		ap->num_folios++;
1784 		cur_pages++;
1785 
1786 		offset = 0;
1787 		num -= this_num;
1788 		total_len += this_num;
1789 		index++;
1790 	}
1791 	ra->inarg.offset = outarg->offset;
1792 	ra->inarg.size = total_len;
1793 	fuse_set_zero_arg0(args);
1794 	args->in_args[1].size = sizeof(ra->inarg);
1795 	args->in_args[1].value = &ra->inarg;
1796 	args->in_args[2].size = total_len;
1797 
1798 	err = fuse_simple_notify_reply(fm, args, outarg->notify_unique);
1799 	if (err)
1800 		fuse_retrieve_end(fm, args, err);
1801 
1802 	return err;
1803 }
1804 
1805 static int fuse_notify_retrieve(struct fuse_conn *fc, unsigned int size,
1806 				struct fuse_copy_state *cs)
1807 {
1808 	struct fuse_notify_retrieve_out outarg;
1809 	struct fuse_mount *fm;
1810 	struct inode *inode;
1811 	u64 nodeid;
1812 	int err;
1813 
1814 	err = -EINVAL;
1815 	if (size != sizeof(outarg))
1816 		goto copy_finish;
1817 
1818 	err = fuse_copy_one(cs, &outarg, sizeof(outarg));
1819 	if (err)
1820 		goto copy_finish;
1821 
1822 	fuse_copy_finish(cs);
1823 
1824 	down_read(&fc->killsb);
1825 	err = -ENOENT;
1826 	nodeid = outarg.nodeid;
1827 
1828 	inode = fuse_ilookup(fc, nodeid, &fm);
1829 	if (inode) {
1830 		err = fuse_retrieve(fm, inode, &outarg);
1831 		iput(inode);
1832 	}
1833 	up_read(&fc->killsb);
1834 
1835 	return err;
1836 
1837 copy_finish:
1838 	fuse_copy_finish(cs);
1839 	return err;
1840 }
1841 
1842 /*
1843  * Resending all processing queue requests.
1844  *
1845  * During a FUSE daemon panics and failover, it is possible for some inflight
1846  * requests to be lost and never returned. As a result, applications awaiting
1847  * replies would become stuck forever. To address this, we can use notification
1848  * to trigger resending of these pending requests to the FUSE daemon, ensuring
1849  * they are properly processed again.
1850  *
1851  * Please note that this strategy is applicable only to idempotent requests or
1852  * if the FUSE daemon takes careful measures to avoid processing duplicated
1853  * non-idempotent requests.
1854  */
1855 static void fuse_resend(struct fuse_conn *fc)
1856 {
1857 	struct fuse_dev *fud;
1858 	struct fuse_req *req, *next;
1859 	struct fuse_iqueue *fiq = &fc->iq;
1860 	LIST_HEAD(to_queue);
1861 	unsigned int i;
1862 
1863 	spin_lock(&fc->lock);
1864 	if (!fc->connected) {
1865 		spin_unlock(&fc->lock);
1866 		return;
1867 	}
1868 
1869 	list_for_each_entry(fud, &fc->devices, entry) {
1870 		struct fuse_pqueue *fpq = &fud->pq;
1871 
1872 		spin_lock(&fpq->lock);
1873 		for (i = 0; i < FUSE_PQ_HASH_SIZE; i++)
1874 			list_splice_tail_init(&fpq->processing[i], &to_queue);
1875 		spin_unlock(&fpq->lock);
1876 	}
1877 	spin_unlock(&fc->lock);
1878 
1879 	list_for_each_entry_safe(req, next, &to_queue, list) {
1880 		set_bit(FR_PENDING, &req->flags);
1881 		clear_bit(FR_SENT, &req->flags);
1882 		/* mark the request as resend request */
1883 		req->in.h.unique |= FUSE_UNIQUE_RESEND;
1884 	}
1885 
1886 	spin_lock(&fiq->lock);
1887 	if (!fiq->connected) {
1888 		spin_unlock(&fiq->lock);
1889 		list_for_each_entry(req, &to_queue, list)
1890 			clear_bit(FR_PENDING, &req->flags);
1891 		fuse_dev_end_requests(&to_queue);
1892 		return;
1893 	}
1894 	/* iq and pq requests are both oldest to newest */
1895 	list_splice(&to_queue, &fiq->pending);
1896 	fuse_dev_wake_and_unlock(fiq);
1897 }
1898 
1899 static int fuse_notify_resend(struct fuse_conn *fc)
1900 {
1901 	fuse_resend(fc);
1902 	return 0;
1903 }
1904 
1905 static int fuse_notify(struct fuse_conn *fc, enum fuse_notify_code code,
1906 		       unsigned int size, struct fuse_copy_state *cs)
1907 {
1908 	/* Don't try to move pages (yet) */
1909 	cs->move_pages = 0;
1910 
1911 	switch (code) {
1912 	case FUSE_NOTIFY_POLL:
1913 		return fuse_notify_poll(fc, size, cs);
1914 
1915 	case FUSE_NOTIFY_INVAL_INODE:
1916 		return fuse_notify_inval_inode(fc, size, cs);
1917 
1918 	case FUSE_NOTIFY_INVAL_ENTRY:
1919 		return fuse_notify_inval_entry(fc, size, cs);
1920 
1921 	case FUSE_NOTIFY_STORE:
1922 		return fuse_notify_store(fc, size, cs);
1923 
1924 	case FUSE_NOTIFY_RETRIEVE:
1925 		return fuse_notify_retrieve(fc, size, cs);
1926 
1927 	case FUSE_NOTIFY_DELETE:
1928 		return fuse_notify_delete(fc, size, cs);
1929 
1930 	case FUSE_NOTIFY_RESEND:
1931 		return fuse_notify_resend(fc);
1932 
1933 	default:
1934 		fuse_copy_finish(cs);
1935 		return -EINVAL;
1936 	}
1937 }
1938 
1939 /* Look up request on processing list by unique ID */
1940 struct fuse_req *fuse_request_find(struct fuse_pqueue *fpq, u64 unique)
1941 {
1942 	unsigned int hash = fuse_req_hash(unique);
1943 	struct fuse_req *req;
1944 
1945 	list_for_each_entry(req, &fpq->processing[hash], list) {
1946 		if (req->in.h.unique == unique)
1947 			return req;
1948 	}
1949 	return NULL;
1950 }
1951 
1952 int fuse_copy_out_args(struct fuse_copy_state *cs, struct fuse_args *args,
1953 		       unsigned nbytes)
1954 {
1955 
1956 	unsigned int reqsize = 0;
1957 
1958 	/*
1959 	 * Uring has all headers separated from args - args is payload only
1960 	 */
1961 	if (!cs->is_uring)
1962 		reqsize = sizeof(struct fuse_out_header);
1963 
1964 	reqsize += fuse_len_args(args->out_numargs, args->out_args);
1965 
1966 	if (reqsize < nbytes || (reqsize > nbytes && !args->out_argvar))
1967 		return -EINVAL;
1968 	else if (reqsize > nbytes) {
1969 		struct fuse_arg *lastarg = &args->out_args[args->out_numargs-1];
1970 		unsigned diffsize = reqsize - nbytes;
1971 
1972 		if (diffsize > lastarg->size)
1973 			return -EINVAL;
1974 		lastarg->size -= diffsize;
1975 	}
1976 	return fuse_copy_args(cs, args->out_numargs, args->out_pages,
1977 			      args->out_args, args->page_zeroing);
1978 }
1979 
1980 /*
1981  * Write a single reply to a request.  First the header is copied from
1982  * the write buffer.  The request is then searched on the processing
1983  * list by the unique ID found in the header.  If found, then remove
1984  * it from the list and copy the rest of the buffer to the request.
1985  * The request is finished by calling fuse_request_end().
1986  */
1987 static ssize_t fuse_dev_do_write(struct fuse_dev *fud,
1988 				 struct fuse_copy_state *cs, size_t nbytes)
1989 {
1990 	int err;
1991 	struct fuse_conn *fc = fud->fc;
1992 	struct fuse_pqueue *fpq = &fud->pq;
1993 	struct fuse_req *req;
1994 	struct fuse_out_header oh;
1995 
1996 	err = -EINVAL;
1997 	if (nbytes < sizeof(struct fuse_out_header))
1998 		goto out;
1999 
2000 	err = fuse_copy_one(cs, &oh, sizeof(oh));
2001 	if (err)
2002 		goto copy_finish;
2003 
2004 	err = -EINVAL;
2005 	if (oh.len != nbytes)
2006 		goto copy_finish;
2007 
2008 	/*
2009 	 * Zero oh.unique indicates unsolicited notification message
2010 	 * and error contains notification code.
2011 	 */
2012 	if (!oh.unique) {
2013 		err = fuse_notify(fc, oh.error, nbytes - sizeof(oh), cs);
2014 		goto out;
2015 	}
2016 
2017 	err = -EINVAL;
2018 	if (oh.error <= -512 || oh.error > 0)
2019 		goto copy_finish;
2020 
2021 	spin_lock(&fpq->lock);
2022 	req = NULL;
2023 	if (fpq->connected)
2024 		req = fuse_request_find(fpq, oh.unique & ~FUSE_INT_REQ_BIT);
2025 
2026 	err = -ENOENT;
2027 	if (!req) {
2028 		spin_unlock(&fpq->lock);
2029 		goto copy_finish;
2030 	}
2031 
2032 	/* Is it an interrupt reply ID? */
2033 	if (oh.unique & FUSE_INT_REQ_BIT) {
2034 		__fuse_get_request(req);
2035 		spin_unlock(&fpq->lock);
2036 
2037 		err = 0;
2038 		if (nbytes != sizeof(struct fuse_out_header))
2039 			err = -EINVAL;
2040 		else if (oh.error == -ENOSYS)
2041 			fc->no_interrupt = 1;
2042 		else if (oh.error == -EAGAIN)
2043 			err = queue_interrupt(req);
2044 
2045 		fuse_put_request(req);
2046 
2047 		goto copy_finish;
2048 	}
2049 
2050 	clear_bit(FR_SENT, &req->flags);
2051 	list_move(&req->list, &fpq->io);
2052 	req->out.h = oh;
2053 	set_bit(FR_LOCKED, &req->flags);
2054 	spin_unlock(&fpq->lock);
2055 	cs->req = req;
2056 	if (!req->args->page_replace)
2057 		cs->move_pages = 0;
2058 
2059 	if (oh.error)
2060 		err = nbytes != sizeof(oh) ? -EINVAL : 0;
2061 	else
2062 		err = fuse_copy_out_args(cs, req->args, nbytes);
2063 	fuse_copy_finish(cs);
2064 
2065 	spin_lock(&fpq->lock);
2066 	clear_bit(FR_LOCKED, &req->flags);
2067 	if (!fpq->connected)
2068 		err = -ENOENT;
2069 	else if (err)
2070 		req->out.h.error = -EIO;
2071 	if (!test_bit(FR_PRIVATE, &req->flags))
2072 		list_del_init(&req->list);
2073 	spin_unlock(&fpq->lock);
2074 
2075 	fuse_request_end(req);
2076 out:
2077 	return err ? err : nbytes;
2078 
2079 copy_finish:
2080 	fuse_copy_finish(cs);
2081 	goto out;
2082 }
2083 
2084 static ssize_t fuse_dev_write(struct kiocb *iocb, struct iov_iter *from)
2085 {
2086 	struct fuse_copy_state cs;
2087 	struct fuse_dev *fud = fuse_get_dev(iocb->ki_filp);
2088 
2089 	if (!fud)
2090 		return -EPERM;
2091 
2092 	if (!user_backed_iter(from))
2093 		return -EINVAL;
2094 
2095 	fuse_copy_init(&cs, 0, from);
2096 
2097 	return fuse_dev_do_write(fud, &cs, iov_iter_count(from));
2098 }
2099 
2100 static ssize_t fuse_dev_splice_write(struct pipe_inode_info *pipe,
2101 				     struct file *out, loff_t *ppos,
2102 				     size_t len, unsigned int flags)
2103 {
2104 	unsigned int head, tail, mask, count;
2105 	unsigned nbuf;
2106 	unsigned idx;
2107 	struct pipe_buffer *bufs;
2108 	struct fuse_copy_state cs;
2109 	struct fuse_dev *fud;
2110 	size_t rem;
2111 	ssize_t ret;
2112 
2113 	fud = fuse_get_dev(out);
2114 	if (!fud)
2115 		return -EPERM;
2116 
2117 	pipe_lock(pipe);
2118 
2119 	head = pipe->head;
2120 	tail = pipe->tail;
2121 	mask = pipe->ring_size - 1;
2122 	count = head - tail;
2123 
2124 	bufs = kvmalloc_array(count, sizeof(struct pipe_buffer), GFP_KERNEL);
2125 	if (!bufs) {
2126 		pipe_unlock(pipe);
2127 		return -ENOMEM;
2128 	}
2129 
2130 	nbuf = 0;
2131 	rem = 0;
2132 	for (idx = tail; idx != head && rem < len; idx++)
2133 		rem += pipe->bufs[idx & mask].len;
2134 
2135 	ret = -EINVAL;
2136 	if (rem < len)
2137 		goto out_free;
2138 
2139 	rem = len;
2140 	while (rem) {
2141 		struct pipe_buffer *ibuf;
2142 		struct pipe_buffer *obuf;
2143 
2144 		if (WARN_ON(nbuf >= count || tail == head))
2145 			goto out_free;
2146 
2147 		ibuf = &pipe->bufs[tail & mask];
2148 		obuf = &bufs[nbuf];
2149 
2150 		if (rem >= ibuf->len) {
2151 			*obuf = *ibuf;
2152 			ibuf->ops = NULL;
2153 			tail++;
2154 			pipe->tail = tail;
2155 		} else {
2156 			if (!pipe_buf_get(pipe, ibuf))
2157 				goto out_free;
2158 
2159 			*obuf = *ibuf;
2160 			obuf->flags &= ~PIPE_BUF_FLAG_GIFT;
2161 			obuf->len = rem;
2162 			ibuf->offset += obuf->len;
2163 			ibuf->len -= obuf->len;
2164 		}
2165 		nbuf++;
2166 		rem -= obuf->len;
2167 	}
2168 	pipe_unlock(pipe);
2169 
2170 	fuse_copy_init(&cs, 0, NULL);
2171 	cs.pipebufs = bufs;
2172 	cs.nr_segs = nbuf;
2173 	cs.pipe = pipe;
2174 
2175 	if (flags & SPLICE_F_MOVE)
2176 		cs.move_pages = 1;
2177 
2178 	ret = fuse_dev_do_write(fud, &cs, len);
2179 
2180 	pipe_lock(pipe);
2181 out_free:
2182 	for (idx = 0; idx < nbuf; idx++) {
2183 		struct pipe_buffer *buf = &bufs[idx];
2184 
2185 		if (buf->ops)
2186 			pipe_buf_release(pipe, buf);
2187 	}
2188 	pipe_unlock(pipe);
2189 
2190 	kvfree(bufs);
2191 	return ret;
2192 }
2193 
2194 static __poll_t fuse_dev_poll(struct file *file, poll_table *wait)
2195 {
2196 	__poll_t mask = EPOLLOUT | EPOLLWRNORM;
2197 	struct fuse_iqueue *fiq;
2198 	struct fuse_dev *fud = fuse_get_dev(file);
2199 
2200 	if (!fud)
2201 		return EPOLLERR;
2202 
2203 	fiq = &fud->fc->iq;
2204 	poll_wait(file, &fiq->waitq, wait);
2205 
2206 	spin_lock(&fiq->lock);
2207 	if (!fiq->connected)
2208 		mask = EPOLLERR;
2209 	else if (request_pending(fiq))
2210 		mask |= EPOLLIN | EPOLLRDNORM;
2211 	spin_unlock(&fiq->lock);
2212 
2213 	return mask;
2214 }
2215 
2216 /* Abort all requests on the given list (pending or processing) */
2217 void fuse_dev_end_requests(struct list_head *head)
2218 {
2219 	while (!list_empty(head)) {
2220 		struct fuse_req *req;
2221 		req = list_entry(head->next, struct fuse_req, list);
2222 		req->out.h.error = -ECONNABORTED;
2223 		clear_bit(FR_SENT, &req->flags);
2224 		list_del_init(&req->list);
2225 		fuse_request_end(req);
2226 	}
2227 }
2228 
2229 static void end_polls(struct fuse_conn *fc)
2230 {
2231 	struct rb_node *p;
2232 
2233 	p = rb_first(&fc->polled_files);
2234 
2235 	while (p) {
2236 		struct fuse_file *ff;
2237 		ff = rb_entry(p, struct fuse_file, polled_node);
2238 		wake_up_interruptible_all(&ff->poll_wait);
2239 
2240 		p = rb_next(p);
2241 	}
2242 }
2243 
2244 /*
2245  * Abort all requests.
2246  *
2247  * Emergency exit in case of a malicious or accidental deadlock, or just a hung
2248  * filesystem.
2249  *
2250  * The same effect is usually achievable through killing the filesystem daemon
2251  * and all users of the filesystem.  The exception is the combination of an
2252  * asynchronous request and the tricky deadlock (see
2253  * Documentation/filesystems/fuse.rst).
2254  *
2255  * Aborting requests under I/O goes as follows: 1: Separate out unlocked
2256  * requests, they should be finished off immediately.  Locked requests will be
2257  * finished after unlock; see unlock_request(). 2: Finish off the unlocked
2258  * requests.  It is possible that some request will finish before we can.  This
2259  * is OK, the request will in that case be removed from the list before we touch
2260  * it.
2261  */
2262 void fuse_abort_conn(struct fuse_conn *fc)
2263 {
2264 	struct fuse_iqueue *fiq = &fc->iq;
2265 
2266 	spin_lock(&fc->lock);
2267 	if (fc->connected) {
2268 		struct fuse_dev *fud;
2269 		struct fuse_req *req, *next;
2270 		LIST_HEAD(to_end);
2271 		unsigned int i;
2272 
2273 		/* Background queuing checks fc->connected under bg_lock */
2274 		spin_lock(&fc->bg_lock);
2275 		fc->connected = 0;
2276 		spin_unlock(&fc->bg_lock);
2277 
2278 		fuse_set_initialized(fc);
2279 		list_for_each_entry(fud, &fc->devices, entry) {
2280 			struct fuse_pqueue *fpq = &fud->pq;
2281 
2282 			spin_lock(&fpq->lock);
2283 			fpq->connected = 0;
2284 			list_for_each_entry_safe(req, next, &fpq->io, list) {
2285 				req->out.h.error = -ECONNABORTED;
2286 				spin_lock(&req->waitq.lock);
2287 				set_bit(FR_ABORTED, &req->flags);
2288 				if (!test_bit(FR_LOCKED, &req->flags)) {
2289 					set_bit(FR_PRIVATE, &req->flags);
2290 					__fuse_get_request(req);
2291 					list_move(&req->list, &to_end);
2292 				}
2293 				spin_unlock(&req->waitq.lock);
2294 			}
2295 			for (i = 0; i < FUSE_PQ_HASH_SIZE; i++)
2296 				list_splice_tail_init(&fpq->processing[i],
2297 						      &to_end);
2298 			spin_unlock(&fpq->lock);
2299 		}
2300 		spin_lock(&fc->bg_lock);
2301 		fc->blocked = 0;
2302 		fc->max_background = UINT_MAX;
2303 		flush_bg_queue(fc);
2304 		spin_unlock(&fc->bg_lock);
2305 
2306 		spin_lock(&fiq->lock);
2307 		fiq->connected = 0;
2308 		list_for_each_entry(req, &fiq->pending, list)
2309 			clear_bit(FR_PENDING, &req->flags);
2310 		list_splice_tail_init(&fiq->pending, &to_end);
2311 		while (forget_pending(fiq))
2312 			kfree(fuse_dequeue_forget(fiq, 1, NULL));
2313 		wake_up_all(&fiq->waitq);
2314 		spin_unlock(&fiq->lock);
2315 		kill_fasync(&fiq->fasync, SIGIO, POLL_IN);
2316 		end_polls(fc);
2317 		wake_up_all(&fc->blocked_waitq);
2318 		spin_unlock(&fc->lock);
2319 
2320 		fuse_dev_end_requests(&to_end);
2321 
2322 		/*
2323 		 * fc->lock must not be taken to avoid conflicts with io-uring
2324 		 * locks
2325 		 */
2326 		fuse_uring_abort(fc);
2327 	} else {
2328 		spin_unlock(&fc->lock);
2329 	}
2330 }
2331 EXPORT_SYMBOL_GPL(fuse_abort_conn);
2332 
2333 void fuse_wait_aborted(struct fuse_conn *fc)
2334 {
2335 	/* matches implicit memory barrier in fuse_drop_waiting() */
2336 	smp_mb();
2337 	wait_event(fc->blocked_waitq, atomic_read(&fc->num_waiting) == 0);
2338 
2339 	fuse_uring_wait_stopped_queues(fc);
2340 }
2341 
2342 int fuse_dev_release(struct inode *inode, struct file *file)
2343 {
2344 	struct fuse_dev *fud = fuse_get_dev(file);
2345 
2346 	if (fud) {
2347 		struct fuse_conn *fc = fud->fc;
2348 		struct fuse_pqueue *fpq = &fud->pq;
2349 		LIST_HEAD(to_end);
2350 		unsigned int i;
2351 
2352 		spin_lock(&fpq->lock);
2353 		WARN_ON(!list_empty(&fpq->io));
2354 		for (i = 0; i < FUSE_PQ_HASH_SIZE; i++)
2355 			list_splice_init(&fpq->processing[i], &to_end);
2356 		spin_unlock(&fpq->lock);
2357 
2358 		fuse_dev_end_requests(&to_end);
2359 
2360 		/* Are we the last open device? */
2361 		if (atomic_dec_and_test(&fc->dev_count)) {
2362 			WARN_ON(fc->iq.fasync != NULL);
2363 			fuse_abort_conn(fc);
2364 		}
2365 		fuse_dev_free(fud);
2366 	}
2367 	return 0;
2368 }
2369 EXPORT_SYMBOL_GPL(fuse_dev_release);
2370 
2371 static int fuse_dev_fasync(int fd, struct file *file, int on)
2372 {
2373 	struct fuse_dev *fud = fuse_get_dev(file);
2374 
2375 	if (!fud)
2376 		return -EPERM;
2377 
2378 	/* No locking - fasync_helper does its own locking */
2379 	return fasync_helper(fd, file, on, &fud->fc->iq.fasync);
2380 }
2381 
2382 static int fuse_device_clone(struct fuse_conn *fc, struct file *new)
2383 {
2384 	struct fuse_dev *fud;
2385 
2386 	if (new->private_data)
2387 		return -EINVAL;
2388 
2389 	fud = fuse_dev_alloc_install(fc);
2390 	if (!fud)
2391 		return -ENOMEM;
2392 
2393 	new->private_data = fud;
2394 	atomic_inc(&fc->dev_count);
2395 
2396 	return 0;
2397 }
2398 
2399 static long fuse_dev_ioctl_clone(struct file *file, __u32 __user *argp)
2400 {
2401 	int res;
2402 	int oldfd;
2403 	struct fuse_dev *fud = NULL;
2404 
2405 	if (get_user(oldfd, argp))
2406 		return -EFAULT;
2407 
2408 	CLASS(fd, f)(oldfd);
2409 	if (fd_empty(f))
2410 		return -EINVAL;
2411 
2412 	/*
2413 	 * Check against file->f_op because CUSE
2414 	 * uses the same ioctl handler.
2415 	 */
2416 	if (fd_file(f)->f_op == file->f_op)
2417 		fud = fuse_get_dev(fd_file(f));
2418 
2419 	res = -EINVAL;
2420 	if (fud) {
2421 		mutex_lock(&fuse_mutex);
2422 		res = fuse_device_clone(fud->fc, file);
2423 		mutex_unlock(&fuse_mutex);
2424 	}
2425 
2426 	return res;
2427 }
2428 
2429 static long fuse_dev_ioctl_backing_open(struct file *file,
2430 					struct fuse_backing_map __user *argp)
2431 {
2432 	struct fuse_dev *fud = fuse_get_dev(file);
2433 	struct fuse_backing_map map;
2434 
2435 	if (!fud)
2436 		return -EPERM;
2437 
2438 	if (!IS_ENABLED(CONFIG_FUSE_PASSTHROUGH))
2439 		return -EOPNOTSUPP;
2440 
2441 	if (copy_from_user(&map, argp, sizeof(map)))
2442 		return -EFAULT;
2443 
2444 	return fuse_backing_open(fud->fc, &map);
2445 }
2446 
2447 static long fuse_dev_ioctl_backing_close(struct file *file, __u32 __user *argp)
2448 {
2449 	struct fuse_dev *fud = fuse_get_dev(file);
2450 	int backing_id;
2451 
2452 	if (!fud)
2453 		return -EPERM;
2454 
2455 	if (!IS_ENABLED(CONFIG_FUSE_PASSTHROUGH))
2456 		return -EOPNOTSUPP;
2457 
2458 	if (get_user(backing_id, argp))
2459 		return -EFAULT;
2460 
2461 	return fuse_backing_close(fud->fc, backing_id);
2462 }
2463 
2464 static long fuse_dev_ioctl(struct file *file, unsigned int cmd,
2465 			   unsigned long arg)
2466 {
2467 	void __user *argp = (void __user *)arg;
2468 
2469 	switch (cmd) {
2470 	case FUSE_DEV_IOC_CLONE:
2471 		return fuse_dev_ioctl_clone(file, argp);
2472 
2473 	case FUSE_DEV_IOC_BACKING_OPEN:
2474 		return fuse_dev_ioctl_backing_open(file, argp);
2475 
2476 	case FUSE_DEV_IOC_BACKING_CLOSE:
2477 		return fuse_dev_ioctl_backing_close(file, argp);
2478 
2479 	default:
2480 		return -ENOTTY;
2481 	}
2482 }
2483 
2484 const struct file_operations fuse_dev_operations = {
2485 	.owner		= THIS_MODULE,
2486 	.open		= fuse_dev_open,
2487 	.read_iter	= fuse_dev_read,
2488 	.splice_read	= fuse_dev_splice_read,
2489 	.write_iter	= fuse_dev_write,
2490 	.splice_write	= fuse_dev_splice_write,
2491 	.poll		= fuse_dev_poll,
2492 	.release	= fuse_dev_release,
2493 	.fasync		= fuse_dev_fasync,
2494 	.unlocked_ioctl = fuse_dev_ioctl,
2495 	.compat_ioctl   = compat_ptr_ioctl,
2496 #ifdef CONFIG_FUSE_IO_URING
2497 	.uring_cmd	= fuse_uring_cmd,
2498 #endif
2499 };
2500 EXPORT_SYMBOL_GPL(fuse_dev_operations);
2501 
2502 static struct miscdevice fuse_miscdevice = {
2503 	.minor = FUSE_MINOR,
2504 	.name  = "fuse",
2505 	.fops = &fuse_dev_operations,
2506 };
2507 
2508 int __init fuse_dev_init(void)
2509 {
2510 	int err = -ENOMEM;
2511 	fuse_req_cachep = kmem_cache_create("fuse_request",
2512 					    sizeof(struct fuse_req),
2513 					    0, 0, NULL);
2514 	if (!fuse_req_cachep)
2515 		goto out;
2516 
2517 	err = misc_register(&fuse_miscdevice);
2518 	if (err)
2519 		goto out_cache_clean;
2520 
2521 	return 0;
2522 
2523  out_cache_clean:
2524 	kmem_cache_destroy(fuse_req_cachep);
2525  out:
2526 	return err;
2527 }
2528 
2529 void fuse_dev_cleanup(void)
2530 {
2531 	misc_deregister(&fuse_miscdevice);
2532 	kmem_cache_destroy(fuse_req_cachep);
2533 }
2534