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