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