GNU Linux-libre 5.4.257-gnu1
[releases.git] / fs / fuse / dev.c
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 FR_INTERRUPTED check. Pairs with
286          * smp_mb() from queue_interrupt().
287          */
288         if (test_bit(FR_INTERRUPTED, &req->flags)) {
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->buffers)
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->flags & PAGE_FLAGS_CHECK_AT_PREP &
768              ~(1 << PG_locked |
769                1 << PG_referenced |
770                1 << PG_uptodate |
771                1 << PG_lru |
772                1 << PG_active |
773                1 << PG_workingset |
774                1 << PG_reclaim |
775                1 << PG_waiters))) {
776                 pr_warn("trying to steal weird page\n");
777                 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);
778                 return 1;
779         }
780         return 0;
781 }
782
783 static int fuse_try_move_page(struct fuse_copy_state *cs, struct page **pagep)
784 {
785         int err;
786         struct page *oldpage = *pagep;
787         struct page *newpage;
788         struct pipe_buffer *buf = cs->pipebufs;
789
790         get_page(oldpage);
791         err = unlock_request(cs->req);
792         if (err)
793                 goto out_put_old;
794
795         fuse_copy_finish(cs);
796
797         err = pipe_buf_confirm(cs->pipe, buf);
798         if (err)
799                 goto out_put_old;
800
801         BUG_ON(!cs->nr_segs);
802         cs->currbuf = buf;
803         cs->len = buf->len;
804         cs->pipebufs++;
805         cs->nr_segs--;
806
807         if (cs->len != PAGE_SIZE)
808                 goto out_fallback;
809
810         if (pipe_buf_steal(cs->pipe, buf) != 0)
811                 goto out_fallback;
812
813         newpage = buf->page;
814
815         if (!PageUptodate(newpage))
816                 SetPageUptodate(newpage);
817
818         ClearPageMappedToDisk(newpage);
819
820         if (fuse_check_page(newpage) != 0)
821                 goto out_fallback_unlock;
822
823         /*
824          * This is a new and locked page, it shouldn't be mapped or
825          * have any special flags on it
826          */
827         if (WARN_ON(page_mapped(oldpage)))
828                 goto out_fallback_unlock;
829         if (WARN_ON(page_has_private(oldpage)))
830                 goto out_fallback_unlock;
831         if (WARN_ON(PageDirty(oldpage) || PageWriteback(oldpage)))
832                 goto out_fallback_unlock;
833         if (WARN_ON(PageMlocked(oldpage)))
834                 goto out_fallback_unlock;
835
836         err = replace_page_cache_page(oldpage, newpage, GFP_KERNEL);
837         if (err) {
838                 unlock_page(newpage);
839                 goto out_put_old;
840         }
841
842         get_page(newpage);
843
844         if (!(buf->flags & PIPE_BUF_FLAG_LRU))
845                 lru_cache_add_file(newpage);
846
847         /*
848          * Release while we have extra ref on stolen page.  Otherwise
849          * anon_pipe_buf_release() might think the page can be reused.
850          */
851         pipe_buf_release(cs->pipe, buf);
852
853         err = 0;
854         spin_lock(&cs->req->waitq.lock);
855         if (test_bit(FR_ABORTED, &cs->req->flags))
856                 err = -ENOENT;
857         else
858                 *pagep = newpage;
859         spin_unlock(&cs->req->waitq.lock);
860
861         if (err) {
862                 unlock_page(newpage);
863                 put_page(newpage);
864                 goto out_put_old;
865         }
866
867         unlock_page(oldpage);
868         /* Drop ref for ap->pages[] array */
869         put_page(oldpage);
870         cs->len = 0;
871
872         err = 0;
873 out_put_old:
874         /* Drop ref obtained in this function */
875         put_page(oldpage);
876         return err;
877
878 out_fallback_unlock:
879         unlock_page(newpage);
880 out_fallback:
881         cs->pg = buf->page;
882         cs->offset = buf->offset;
883
884         err = lock_request(cs->req);
885         if (!err)
886                 err = 1;
887
888         goto out_put_old;
889 }
890
891 static int fuse_ref_page(struct fuse_copy_state *cs, struct page *page,
892                          unsigned offset, unsigned count)
893 {
894         struct pipe_buffer *buf;
895         int err;
896
897         if (cs->nr_segs == cs->pipe->buffers)
898                 return -EIO;
899
900         get_page(page);
901         err = unlock_request(cs->req);
902         if (err) {
903                 put_page(page);
904                 return err;
905         }
906
907         fuse_copy_finish(cs);
908
909         buf = cs->pipebufs;
910         buf->page = page;
911         buf->offset = offset;
912         buf->len = count;
913
914         cs->pipebufs++;
915         cs->nr_segs++;
916         cs->len = 0;
917
918         return 0;
919 }
920
921 /*
922  * Copy a page in the request to/from the userspace buffer.  Must be
923  * done atomically
924  */
925 static int fuse_copy_page(struct fuse_copy_state *cs, struct page **pagep,
926                           unsigned offset, unsigned count, int zeroing)
927 {
928         int err;
929         struct page *page = *pagep;
930
931         if (page && zeroing && count < PAGE_SIZE)
932                 clear_highpage(page);
933
934         while (count) {
935                 if (cs->write && cs->pipebufs && page) {
936                         /*
937                          * Can't control lifetime of pipe buffers, so always
938                          * copy user pages.
939                          */
940                         if (cs->req->args->user_pages) {
941                                 err = fuse_copy_fill(cs);
942                                 if (err)
943                                         return err;
944                         } else {
945                                 return fuse_ref_page(cs, page, offset, count);
946                         }
947                 } else if (!cs->len) {
948                         if (cs->move_pages && page &&
949                             offset == 0 && count == PAGE_SIZE) {
950                                 err = fuse_try_move_page(cs, pagep);
951                                 if (err <= 0)
952                                         return err;
953                         } else {
954                                 err = fuse_copy_fill(cs);
955                                 if (err)
956                                         return err;
957                         }
958                 }
959                 if (page) {
960                         void *mapaddr = kmap_atomic(page);
961                         void *buf = mapaddr + offset;
962                         offset += fuse_copy_do(cs, &buf, &count);
963                         kunmap_atomic(mapaddr);
964                 } else
965                         offset += fuse_copy_do(cs, NULL, &count);
966         }
967         if (page && !cs->write)
968                 flush_dcache_page(page);
969         return 0;
970 }
971
972 /* Copy pages in the request to/from userspace buffer */
973 static int fuse_copy_pages(struct fuse_copy_state *cs, unsigned nbytes,
974                            int zeroing)
975 {
976         unsigned i;
977         struct fuse_req *req = cs->req;
978         struct fuse_args_pages *ap = container_of(req->args, typeof(*ap), args);
979
980
981         for (i = 0; i < ap->num_pages && (nbytes || zeroing); i++) {
982                 int err;
983                 unsigned int offset = ap->descs[i].offset;
984                 unsigned int count = min(nbytes, ap->descs[i].length);
985
986                 err = fuse_copy_page(cs, &ap->pages[i], offset, count, zeroing);
987                 if (err)
988                         return err;
989
990                 nbytes -= count;
991         }
992         return 0;
993 }
994
995 /* Copy a single argument in the request to/from userspace buffer */
996 static int fuse_copy_one(struct fuse_copy_state *cs, void *val, unsigned size)
997 {
998         while (size) {
999                 if (!cs->len) {
1000                         int err = fuse_copy_fill(cs);
1001                         if (err)
1002                                 return err;
1003                 }
1004                 fuse_copy_do(cs, &val, &size);
1005         }
1006         return 0;
1007 }
1008
1009 /* Copy request arguments to/from userspace buffer */
1010 static int fuse_copy_args(struct fuse_copy_state *cs, unsigned numargs,
1011                           unsigned argpages, struct fuse_arg *args,
1012                           int zeroing)
1013 {
1014         int err = 0;
1015         unsigned i;
1016
1017         for (i = 0; !err && i < numargs; i++)  {
1018                 struct fuse_arg *arg = &args[i];
1019                 if (i == numargs - 1 && argpages)
1020                         err = fuse_copy_pages(cs, arg->size, zeroing);
1021                 else
1022                         err = fuse_copy_one(cs, arg->value, arg->size);
1023         }
1024         return err;
1025 }
1026
1027 static int forget_pending(struct fuse_iqueue *fiq)
1028 {
1029         return fiq->forget_list_head.next != NULL;
1030 }
1031
1032 static int request_pending(struct fuse_iqueue *fiq)
1033 {
1034         return !list_empty(&fiq->pending) || !list_empty(&fiq->interrupts) ||
1035                 forget_pending(fiq);
1036 }
1037
1038 /*
1039  * Transfer an interrupt request to userspace
1040  *
1041  * Unlike other requests this is assembled on demand, without a need
1042  * to allocate a separate fuse_req structure.
1043  *
1044  * Called with fiq->lock held, releases it
1045  */
1046 static int fuse_read_interrupt(struct fuse_iqueue *fiq,
1047                                struct fuse_copy_state *cs,
1048                                size_t nbytes, struct fuse_req *req)
1049 __releases(fiq->lock)
1050 {
1051         struct fuse_in_header ih;
1052         struct fuse_interrupt_in arg;
1053         unsigned reqsize = sizeof(ih) + sizeof(arg);
1054         int err;
1055
1056         list_del_init(&req->intr_entry);
1057         memset(&ih, 0, sizeof(ih));
1058         memset(&arg, 0, sizeof(arg));
1059         ih.len = reqsize;
1060         ih.opcode = FUSE_INTERRUPT;
1061         ih.unique = (req->in.h.unique | FUSE_INT_REQ_BIT);
1062         arg.unique = req->in.h.unique;
1063
1064         spin_unlock(&fiq->lock);
1065         if (nbytes < reqsize)
1066                 return -EINVAL;
1067
1068         err = fuse_copy_one(cs, &ih, sizeof(ih));
1069         if (!err)
1070                 err = fuse_copy_one(cs, &arg, sizeof(arg));
1071         fuse_copy_finish(cs);
1072
1073         return err ? err : reqsize;
1074 }
1075
1076 struct fuse_forget_link *fuse_dequeue_forget(struct fuse_iqueue *fiq,
1077                                              unsigned int max,
1078                                              unsigned int *countp)
1079 {
1080         struct fuse_forget_link *head = fiq->forget_list_head.next;
1081         struct fuse_forget_link **newhead = &head;
1082         unsigned count;
1083
1084         for (count = 0; *newhead != NULL && count < max; count++)
1085                 newhead = &(*newhead)->next;
1086
1087         fiq->forget_list_head.next = *newhead;
1088         *newhead = NULL;
1089         if (fiq->forget_list_head.next == NULL)
1090                 fiq->forget_list_tail = &fiq->forget_list_head;
1091
1092         if (countp != NULL)
1093                 *countp = count;
1094
1095         return head;
1096 }
1097 EXPORT_SYMBOL(fuse_dequeue_forget);
1098
1099 static int fuse_read_single_forget(struct fuse_iqueue *fiq,
1100                                    struct fuse_copy_state *cs,
1101                                    size_t nbytes)
1102 __releases(fiq->lock)
1103 {
1104         int err;
1105         struct fuse_forget_link *forget = fuse_dequeue_forget(fiq, 1, NULL);
1106         struct fuse_forget_in arg = {
1107                 .nlookup = forget->forget_one.nlookup,
1108         };
1109         struct fuse_in_header ih = {
1110                 .opcode = FUSE_FORGET,
1111                 .nodeid = forget->forget_one.nodeid,
1112                 .unique = fuse_get_unique(fiq),
1113                 .len = sizeof(ih) + sizeof(arg),
1114         };
1115
1116         spin_unlock(&fiq->lock);
1117         kfree(forget);
1118         if (nbytes < ih.len)
1119                 return -EINVAL;
1120
1121         err = fuse_copy_one(cs, &ih, sizeof(ih));
1122         if (!err)
1123                 err = fuse_copy_one(cs, &arg, sizeof(arg));
1124         fuse_copy_finish(cs);
1125
1126         if (err)
1127                 return err;
1128
1129         return ih.len;
1130 }
1131
1132 static int fuse_read_batch_forget(struct fuse_iqueue *fiq,
1133                                    struct fuse_copy_state *cs, size_t nbytes)
1134 __releases(fiq->lock)
1135 {
1136         int err;
1137         unsigned max_forgets;
1138         unsigned count;
1139         struct fuse_forget_link *head;
1140         struct fuse_batch_forget_in arg = { .count = 0 };
1141         struct fuse_in_header ih = {
1142                 .opcode = FUSE_BATCH_FORGET,
1143                 .unique = fuse_get_unique(fiq),
1144                 .len = sizeof(ih) + sizeof(arg),
1145         };
1146
1147         if (nbytes < ih.len) {
1148                 spin_unlock(&fiq->lock);
1149                 return -EINVAL;
1150         }
1151
1152         max_forgets = (nbytes - ih.len) / sizeof(struct fuse_forget_one);
1153         head = fuse_dequeue_forget(fiq, max_forgets, &count);
1154         spin_unlock(&fiq->lock);
1155
1156         arg.count = count;
1157         ih.len += count * sizeof(struct fuse_forget_one);
1158         err = fuse_copy_one(cs, &ih, sizeof(ih));
1159         if (!err)
1160                 err = fuse_copy_one(cs, &arg, sizeof(arg));
1161
1162         while (head) {
1163                 struct fuse_forget_link *forget = head;
1164
1165                 if (!err) {
1166                         err = fuse_copy_one(cs, &forget->forget_one,
1167                                             sizeof(forget->forget_one));
1168                 }
1169                 head = forget->next;
1170                 kfree(forget);
1171         }
1172
1173         fuse_copy_finish(cs);
1174
1175         if (err)
1176                 return err;
1177
1178         return ih.len;
1179 }
1180
1181 static int fuse_read_forget(struct fuse_conn *fc, struct fuse_iqueue *fiq,
1182                             struct fuse_copy_state *cs,
1183                             size_t nbytes)
1184 __releases(fiq->lock)
1185 {
1186         if (fc->minor < 16 || fiq->forget_list_head.next->next == NULL)
1187                 return fuse_read_single_forget(fiq, cs, nbytes);
1188         else
1189                 return fuse_read_batch_forget(fiq, cs, nbytes);
1190 }
1191
1192 /*
1193  * Read a single request into the userspace filesystem's buffer.  This
1194  * function waits until a request is available, then removes it from
1195  * the pending list and copies request data to userspace buffer.  If
1196  * no reply is needed (FORGET) or request has been aborted or there
1197  * was an error during the copying then it's finished by calling
1198  * fuse_request_end().  Otherwise add it to the processing list, and set
1199  * the 'sent' flag.
1200  */
1201 static ssize_t fuse_dev_do_read(struct fuse_dev *fud, struct file *file,
1202                                 struct fuse_copy_state *cs, size_t nbytes)
1203 {
1204         ssize_t err;
1205         struct fuse_conn *fc = fud->fc;
1206         struct fuse_iqueue *fiq = &fc->iq;
1207         struct fuse_pqueue *fpq = &fud->pq;
1208         struct fuse_req *req;
1209         struct fuse_args *args;
1210         unsigned reqsize;
1211         unsigned int hash;
1212
1213         /*
1214          * Require sane minimum read buffer - that has capacity for fixed part
1215          * of any request header + negotiated max_write room for data.
1216          *
1217          * Historically libfuse reserves 4K for fixed header room, but e.g.
1218          * GlusterFS reserves only 80 bytes
1219          *
1220          *      = `sizeof(fuse_in_header) + sizeof(fuse_write_in)`
1221          *
1222          * which is the absolute minimum any sane filesystem should be using
1223          * for header room.
1224          */
1225         if (nbytes < max_t(size_t, FUSE_MIN_READ_BUFFER,
1226                            sizeof(struct fuse_in_header) +
1227                            sizeof(struct fuse_write_in) +
1228                            fc->max_write))
1229                 return -EINVAL;
1230
1231  restart:
1232         for (;;) {
1233                 spin_lock(&fiq->lock);
1234                 if (!fiq->connected || request_pending(fiq))
1235                         break;
1236                 spin_unlock(&fiq->lock);
1237
1238                 if (file->f_flags & O_NONBLOCK)
1239                         return -EAGAIN;
1240                 err = wait_event_interruptible_exclusive(fiq->waitq,
1241                                 !fiq->connected || request_pending(fiq));
1242                 if (err)
1243                         return err;
1244         }
1245
1246         if (!fiq->connected) {
1247                 err = fc->aborted ? -ECONNABORTED : -ENODEV;
1248                 goto err_unlock;
1249         }
1250
1251         if (!list_empty(&fiq->interrupts)) {
1252                 req = list_entry(fiq->interrupts.next, struct fuse_req,
1253                                  intr_entry);
1254                 return fuse_read_interrupt(fiq, cs, nbytes, req);
1255         }
1256
1257         if (forget_pending(fiq)) {
1258                 if (list_empty(&fiq->pending) || fiq->forget_batch-- > 0)
1259                         return fuse_read_forget(fc, fiq, cs, nbytes);
1260
1261                 if (fiq->forget_batch <= -8)
1262                         fiq->forget_batch = 16;
1263         }
1264
1265         req = list_entry(fiq->pending.next, struct fuse_req, list);
1266         clear_bit(FR_PENDING, &req->flags);
1267         list_del_init(&req->list);
1268         spin_unlock(&fiq->lock);
1269
1270         args = req->args;
1271         reqsize = req->in.h.len;
1272
1273         /* If request is too large, reply with an error and restart the read */
1274         if (nbytes < reqsize) {
1275                 req->out.h.error = -EIO;
1276                 /* SETXATTR is special, since it may contain too large data */
1277                 if (args->opcode == FUSE_SETXATTR)
1278                         req->out.h.error = -E2BIG;
1279                 fuse_request_end(fc, req);
1280                 goto restart;
1281         }
1282         spin_lock(&fpq->lock);
1283         /*
1284          *  Must not put request on fpq->io queue after having been shut down by
1285          *  fuse_abort_conn()
1286          */
1287         if (!fpq->connected) {
1288                 req->out.h.error = err = -ECONNABORTED;
1289                 goto out_end;
1290
1291         }
1292         list_add(&req->list, &fpq->io);
1293         spin_unlock(&fpq->lock);
1294         cs->req = req;
1295         err = fuse_copy_one(cs, &req->in.h, sizeof(req->in.h));
1296         if (!err)
1297                 err = fuse_copy_args(cs, args->in_numargs, args->in_pages,
1298                                      (struct fuse_arg *) args->in_args, 0);
1299         fuse_copy_finish(cs);
1300         spin_lock(&fpq->lock);
1301         clear_bit(FR_LOCKED, &req->flags);
1302         if (!fpq->connected) {
1303                 err = fc->aborted ? -ECONNABORTED : -ENODEV;
1304                 goto out_end;
1305         }
1306         if (err) {
1307                 req->out.h.error = -EIO;
1308                 goto out_end;
1309         }
1310         if (!test_bit(FR_ISREPLY, &req->flags)) {
1311                 err = reqsize;
1312                 goto out_end;
1313         }
1314         hash = fuse_req_hash(req->in.h.unique);
1315         list_move_tail(&req->list, &fpq->processing[hash]);
1316         __fuse_get_request(req);
1317         set_bit(FR_SENT, &req->flags);
1318         spin_unlock(&fpq->lock);
1319         /* matches barrier in request_wait_answer() */
1320         smp_mb__after_atomic();
1321         if (test_bit(FR_INTERRUPTED, &req->flags))
1322                 queue_interrupt(fiq, req);
1323         fuse_put_request(fc, req);
1324
1325         return reqsize;
1326
1327 out_end:
1328         if (!test_bit(FR_PRIVATE, &req->flags))
1329                 list_del_init(&req->list);
1330         spin_unlock(&fpq->lock);
1331         fuse_request_end(fc, req);
1332         return err;
1333
1334  err_unlock:
1335         spin_unlock(&fiq->lock);
1336         return err;
1337 }
1338
1339 static int fuse_dev_open(struct inode *inode, struct file *file)
1340 {
1341         /*
1342          * The fuse device's file's private_data is used to hold
1343          * the fuse_conn(ection) when it is mounted, and is used to
1344          * keep track of whether the file has been mounted already.
1345          */
1346         file->private_data = NULL;
1347         return 0;
1348 }
1349
1350 static ssize_t fuse_dev_read(struct kiocb *iocb, struct iov_iter *to)
1351 {
1352         struct fuse_copy_state cs;
1353         struct file *file = iocb->ki_filp;
1354         struct fuse_dev *fud = fuse_get_dev(file);
1355
1356         if (!fud)
1357                 return -EPERM;
1358
1359         if (!iter_is_iovec(to))
1360                 return -EINVAL;
1361
1362         fuse_copy_init(&cs, 1, to);
1363
1364         return fuse_dev_do_read(fud, file, &cs, iov_iter_count(to));
1365 }
1366
1367 static ssize_t fuse_dev_splice_read(struct file *in, loff_t *ppos,
1368                                     struct pipe_inode_info *pipe,
1369                                     size_t len, unsigned int flags)
1370 {
1371         int total, ret;
1372         int page_nr = 0;
1373         struct pipe_buffer *bufs;
1374         struct fuse_copy_state cs;
1375         struct fuse_dev *fud = fuse_get_dev(in);
1376
1377         if (!fud)
1378                 return -EPERM;
1379
1380         bufs = kvmalloc_array(pipe->buffers, sizeof(struct pipe_buffer),
1381                               GFP_KERNEL);
1382         if (!bufs)
1383                 return -ENOMEM;
1384
1385         fuse_copy_init(&cs, 1, NULL);
1386         cs.pipebufs = bufs;
1387         cs.pipe = pipe;
1388         ret = fuse_dev_do_read(fud, in, &cs, len);
1389         if (ret < 0)
1390                 goto out;
1391
1392         if (pipe->nrbufs + cs.nr_segs > pipe->buffers) {
1393                 ret = -EIO;
1394                 goto out;
1395         }
1396
1397         for (ret = total = 0; page_nr < cs.nr_segs; total += ret) {
1398                 /*
1399                  * Need to be careful about this.  Having buf->ops in module
1400                  * code can Oops if the buffer persists after module unload.
1401                  */
1402                 bufs[page_nr].ops = &nosteal_pipe_buf_ops;
1403                 bufs[page_nr].flags = 0;
1404                 ret = add_to_pipe(pipe, &bufs[page_nr++]);
1405                 if (unlikely(ret < 0))
1406                         break;
1407         }
1408         if (total)
1409                 ret = total;
1410 out:
1411         for (; page_nr < cs.nr_segs; page_nr++)
1412                 put_page(bufs[page_nr].page);
1413
1414         kvfree(bufs);
1415         return ret;
1416 }
1417
1418 static int fuse_notify_poll(struct fuse_conn *fc, unsigned int size,
1419                             struct fuse_copy_state *cs)
1420 {
1421         struct fuse_notify_poll_wakeup_out outarg;
1422         int err = -EINVAL;
1423
1424         if (size != sizeof(outarg))
1425                 goto err;
1426
1427         err = fuse_copy_one(cs, &outarg, sizeof(outarg));
1428         if (err)
1429                 goto err;
1430
1431         fuse_copy_finish(cs);
1432         return fuse_notify_poll_wakeup(fc, &outarg);
1433
1434 err:
1435         fuse_copy_finish(cs);
1436         return err;
1437 }
1438
1439 static int fuse_notify_inval_inode(struct fuse_conn *fc, unsigned int size,
1440                                    struct fuse_copy_state *cs)
1441 {
1442         struct fuse_notify_inval_inode_out outarg;
1443         int err = -EINVAL;
1444
1445         if (size != sizeof(outarg))
1446                 goto err;
1447
1448         err = fuse_copy_one(cs, &outarg, sizeof(outarg));
1449         if (err)
1450                 goto err;
1451         fuse_copy_finish(cs);
1452
1453         down_read(&fc->killsb);
1454         err = -ENOENT;
1455         if (fc->sb) {
1456                 err = fuse_reverse_inval_inode(fc->sb, outarg.ino,
1457                                                outarg.off, outarg.len);
1458         }
1459         up_read(&fc->killsb);
1460         return err;
1461
1462 err:
1463         fuse_copy_finish(cs);
1464         return err;
1465 }
1466
1467 static int fuse_notify_inval_entry(struct fuse_conn *fc, unsigned int size,
1468                                    struct fuse_copy_state *cs)
1469 {
1470         struct fuse_notify_inval_entry_out outarg;
1471         int err = -ENOMEM;
1472         char *buf;
1473         struct qstr name;
1474
1475         buf = kzalloc(FUSE_NAME_MAX + 1, GFP_KERNEL);
1476         if (!buf)
1477                 goto err;
1478
1479         err = -EINVAL;
1480         if (size < sizeof(outarg))
1481                 goto err;
1482
1483         err = fuse_copy_one(cs, &outarg, sizeof(outarg));
1484         if (err)
1485                 goto err;
1486
1487         err = -ENAMETOOLONG;
1488         if (outarg.namelen > FUSE_NAME_MAX)
1489                 goto err;
1490
1491         err = -EINVAL;
1492         if (size != sizeof(outarg) + outarg.namelen + 1)
1493                 goto err;
1494
1495         name.name = buf;
1496         name.len = outarg.namelen;
1497         err = fuse_copy_one(cs, buf, outarg.namelen + 1);
1498         if (err)
1499                 goto err;
1500         fuse_copy_finish(cs);
1501         buf[outarg.namelen] = 0;
1502
1503         down_read(&fc->killsb);
1504         err = -ENOENT;
1505         if (fc->sb)
1506                 err = fuse_reverse_inval_entry(fc->sb, outarg.parent, 0, &name);
1507         up_read(&fc->killsb);
1508         kfree(buf);
1509         return err;
1510
1511 err:
1512         kfree(buf);
1513         fuse_copy_finish(cs);
1514         return err;
1515 }
1516
1517 static int fuse_notify_delete(struct fuse_conn *fc, unsigned int size,
1518                               struct fuse_copy_state *cs)
1519 {
1520         struct fuse_notify_delete_out outarg;
1521         int err = -ENOMEM;
1522         char *buf;
1523         struct qstr name;
1524
1525         buf = kzalloc(FUSE_NAME_MAX + 1, GFP_KERNEL);
1526         if (!buf)
1527                 goto err;
1528
1529         err = -EINVAL;
1530         if (size < sizeof(outarg))
1531                 goto err;
1532
1533         err = fuse_copy_one(cs, &outarg, sizeof(outarg));
1534         if (err)
1535                 goto err;
1536
1537         err = -ENAMETOOLONG;
1538         if (outarg.namelen > FUSE_NAME_MAX)
1539                 goto err;
1540
1541         err = -EINVAL;
1542         if (size != sizeof(outarg) + outarg.namelen + 1)
1543                 goto err;
1544
1545         name.name = buf;
1546         name.len = outarg.namelen;
1547         err = fuse_copy_one(cs, buf, outarg.namelen + 1);
1548         if (err)
1549                 goto err;
1550         fuse_copy_finish(cs);
1551         buf[outarg.namelen] = 0;
1552
1553         down_read(&fc->killsb);
1554         err = -ENOENT;
1555         if (fc->sb)
1556                 err = fuse_reverse_inval_entry(fc->sb, outarg.parent,
1557                                                outarg.child, &name);
1558         up_read(&fc->killsb);
1559         kfree(buf);
1560         return err;
1561
1562 err:
1563         kfree(buf);
1564         fuse_copy_finish(cs);
1565         return err;
1566 }
1567
1568 static int fuse_notify_store(struct fuse_conn *fc, unsigned int size,
1569                              struct fuse_copy_state *cs)
1570 {
1571         struct fuse_notify_store_out outarg;
1572         struct inode *inode;
1573         struct address_space *mapping;
1574         u64 nodeid;
1575         int err;
1576         pgoff_t index;
1577         unsigned int offset;
1578         unsigned int num;
1579         loff_t file_size;
1580         loff_t end;
1581
1582         err = -EINVAL;
1583         if (size < sizeof(outarg))
1584                 goto out_finish;
1585
1586         err = fuse_copy_one(cs, &outarg, sizeof(outarg));
1587         if (err)
1588                 goto out_finish;
1589
1590         err = -EINVAL;
1591         if (size - sizeof(outarg) != outarg.size)
1592                 goto out_finish;
1593
1594         nodeid = outarg.nodeid;
1595
1596         down_read(&fc->killsb);
1597
1598         err = -ENOENT;
1599         if (!fc->sb)
1600                 goto out_up_killsb;
1601
1602         inode = ilookup5(fc->sb, nodeid, fuse_inode_eq, &nodeid);
1603         if (!inode)
1604                 goto out_up_killsb;
1605
1606         mapping = inode->i_mapping;
1607         index = outarg.offset >> PAGE_SHIFT;
1608         offset = outarg.offset & ~PAGE_MASK;
1609         file_size = i_size_read(inode);
1610         end = outarg.offset + outarg.size;
1611         if (end > file_size) {
1612                 file_size = end;
1613                 fuse_write_update_size(inode, file_size);
1614         }
1615
1616         num = outarg.size;
1617         while (num) {
1618                 struct page *page;
1619                 unsigned int this_num;
1620
1621                 err = -ENOMEM;
1622                 page = find_or_create_page(mapping, index,
1623                                            mapping_gfp_mask(mapping));
1624                 if (!page)
1625                         goto out_iput;
1626
1627                 this_num = min_t(unsigned, num, PAGE_SIZE - offset);
1628                 err = fuse_copy_page(cs, &page, offset, this_num, 0);
1629                 if (!err && offset == 0 &&
1630                     (this_num == PAGE_SIZE || file_size == end))
1631                         SetPageUptodate(page);
1632                 unlock_page(page);
1633                 put_page(page);
1634
1635                 if (err)
1636                         goto out_iput;
1637
1638                 num -= this_num;
1639                 offset = 0;
1640                 index++;
1641         }
1642
1643         err = 0;
1644
1645 out_iput:
1646         iput(inode);
1647 out_up_killsb:
1648         up_read(&fc->killsb);
1649 out_finish:
1650         fuse_copy_finish(cs);
1651         return err;
1652 }
1653
1654 struct fuse_retrieve_args {
1655         struct fuse_args_pages ap;
1656         struct fuse_notify_retrieve_in inarg;
1657 };
1658
1659 static void fuse_retrieve_end(struct fuse_conn *fc, struct fuse_args *args,
1660                               int error)
1661 {
1662         struct fuse_retrieve_args *ra =
1663                 container_of(args, typeof(*ra), ap.args);
1664
1665         release_pages(ra->ap.pages, ra->ap.num_pages);
1666         kfree(ra);
1667 }
1668
1669 static int fuse_retrieve(struct fuse_conn *fc, struct inode *inode,
1670                          struct fuse_notify_retrieve_out *outarg)
1671 {
1672         int err;
1673         struct address_space *mapping = inode->i_mapping;
1674         pgoff_t index;
1675         loff_t file_size;
1676         unsigned int num;
1677         unsigned int offset;
1678         size_t total_len = 0;
1679         unsigned int num_pages;
1680         struct fuse_retrieve_args *ra;
1681         size_t args_size = sizeof(*ra);
1682         struct fuse_args_pages *ap;
1683         struct fuse_args *args;
1684
1685         offset = outarg->offset & ~PAGE_MASK;
1686         file_size = i_size_read(inode);
1687
1688         num = min(outarg->size, fc->max_write);
1689         if (outarg->offset > file_size)
1690                 num = 0;
1691         else if (outarg->offset + num > file_size)
1692                 num = file_size - outarg->offset;
1693
1694         num_pages = (num + offset + PAGE_SIZE - 1) >> PAGE_SHIFT;
1695         num_pages = min(num_pages, fc->max_pages);
1696
1697         args_size += num_pages * (sizeof(ap->pages[0]) + sizeof(ap->descs[0]));
1698
1699         ra = kzalloc(args_size, GFP_KERNEL);
1700         if (!ra)
1701                 return -ENOMEM;
1702
1703         ap = &ra->ap;
1704         ap->pages = (void *) (ra + 1);
1705         ap->descs = (void *) (ap->pages + num_pages);
1706
1707         args = &ap->args;
1708         args->nodeid = outarg->nodeid;
1709         args->opcode = FUSE_NOTIFY_REPLY;
1710         args->in_numargs = 2;
1711         args->in_pages = true;
1712         args->end = fuse_retrieve_end;
1713
1714         index = outarg->offset >> PAGE_SHIFT;
1715
1716         while (num && ap->num_pages < num_pages) {
1717                 struct page *page;
1718                 unsigned int this_num;
1719
1720                 page = find_get_page(mapping, index);
1721                 if (!page)
1722                         break;
1723
1724                 this_num = min_t(unsigned, num, PAGE_SIZE - offset);
1725                 ap->pages[ap->num_pages] = page;
1726                 ap->descs[ap->num_pages].offset = offset;
1727                 ap->descs[ap->num_pages].length = this_num;
1728                 ap->num_pages++;
1729
1730                 offset = 0;
1731                 num -= this_num;
1732                 total_len += this_num;
1733                 index++;
1734         }
1735         ra->inarg.offset = outarg->offset;
1736         ra->inarg.size = total_len;
1737         args->in_args[0].size = sizeof(ra->inarg);
1738         args->in_args[0].value = &ra->inarg;
1739         args->in_args[1].size = total_len;
1740
1741         err = fuse_simple_notify_reply(fc, args, outarg->notify_unique);
1742         if (err)
1743                 fuse_retrieve_end(fc, args, err);
1744
1745         return err;
1746 }
1747
1748 static int fuse_notify_retrieve(struct fuse_conn *fc, unsigned int size,
1749                                 struct fuse_copy_state *cs)
1750 {
1751         struct fuse_notify_retrieve_out outarg;
1752         struct inode *inode;
1753         int err;
1754
1755         err = -EINVAL;
1756         if (size != sizeof(outarg))
1757                 goto copy_finish;
1758
1759         err = fuse_copy_one(cs, &outarg, sizeof(outarg));
1760         if (err)
1761                 goto copy_finish;
1762
1763         fuse_copy_finish(cs);
1764
1765         down_read(&fc->killsb);
1766         err = -ENOENT;
1767         if (fc->sb) {
1768                 u64 nodeid = outarg.nodeid;
1769
1770                 inode = ilookup5(fc->sb, nodeid, fuse_inode_eq, &nodeid);
1771                 if (inode) {
1772                         err = fuse_retrieve(fc, inode, &outarg);
1773                         iput(inode);
1774                 }
1775         }
1776         up_read(&fc->killsb);
1777
1778         return err;
1779
1780 copy_finish:
1781         fuse_copy_finish(cs);
1782         return err;
1783 }
1784
1785 static int fuse_notify(struct fuse_conn *fc, enum fuse_notify_code code,
1786                        unsigned int size, struct fuse_copy_state *cs)
1787 {
1788         /* Don't try to move pages (yet) */
1789         cs->move_pages = 0;
1790
1791         switch (code) {
1792         case FUSE_NOTIFY_POLL:
1793                 return fuse_notify_poll(fc, size, cs);
1794
1795         case FUSE_NOTIFY_INVAL_INODE:
1796                 return fuse_notify_inval_inode(fc, size, cs);
1797
1798         case FUSE_NOTIFY_INVAL_ENTRY:
1799                 return fuse_notify_inval_entry(fc, size, cs);
1800
1801         case FUSE_NOTIFY_STORE:
1802                 return fuse_notify_store(fc, size, cs);
1803
1804         case FUSE_NOTIFY_RETRIEVE:
1805                 return fuse_notify_retrieve(fc, size, cs);
1806
1807         case FUSE_NOTIFY_DELETE:
1808                 return fuse_notify_delete(fc, size, cs);
1809
1810         default:
1811                 fuse_copy_finish(cs);
1812                 return -EINVAL;
1813         }
1814 }
1815
1816 /* Look up request on processing list by unique ID */
1817 static struct fuse_req *request_find(struct fuse_pqueue *fpq, u64 unique)
1818 {
1819         unsigned int hash = fuse_req_hash(unique);
1820         struct fuse_req *req;
1821
1822         list_for_each_entry(req, &fpq->processing[hash], list) {
1823                 if (req->in.h.unique == unique)
1824                         return req;
1825         }
1826         return NULL;
1827 }
1828
1829 static int copy_out_args(struct fuse_copy_state *cs, struct fuse_args *args,
1830                          unsigned nbytes)
1831 {
1832         unsigned reqsize = sizeof(struct fuse_out_header);
1833
1834         reqsize += fuse_len_args(args->out_numargs, args->out_args);
1835
1836         if (reqsize < nbytes || (reqsize > nbytes && !args->out_argvar))
1837                 return -EINVAL;
1838         else if (reqsize > nbytes) {
1839                 struct fuse_arg *lastarg = &args->out_args[args->out_numargs-1];
1840                 unsigned diffsize = reqsize - nbytes;
1841
1842                 if (diffsize > lastarg->size)
1843                         return -EINVAL;
1844                 lastarg->size -= diffsize;
1845         }
1846         return fuse_copy_args(cs, args->out_numargs, args->out_pages,
1847                               args->out_args, args->page_zeroing);
1848 }
1849
1850 /*
1851  * Write a single reply to a request.  First the header is copied from
1852  * the write buffer.  The request is then searched on the processing
1853  * list by the unique ID found in the header.  If found, then remove
1854  * it from the list and copy the rest of the buffer to the request.
1855  * The request is finished by calling fuse_request_end().
1856  */
1857 static ssize_t fuse_dev_do_write(struct fuse_dev *fud,
1858                                  struct fuse_copy_state *cs, size_t nbytes)
1859 {
1860         int err;
1861         struct fuse_conn *fc = fud->fc;
1862         struct fuse_pqueue *fpq = &fud->pq;
1863         struct fuse_req *req;
1864         struct fuse_out_header oh;
1865
1866         err = -EINVAL;
1867         if (nbytes < sizeof(struct fuse_out_header))
1868                 goto out;
1869
1870         err = fuse_copy_one(cs, &oh, sizeof(oh));
1871         if (err)
1872                 goto copy_finish;
1873
1874         err = -EINVAL;
1875         if (oh.len != nbytes)
1876                 goto copy_finish;
1877
1878         /*
1879          * Zero oh.unique indicates unsolicited notification message
1880          * and error contains notification code.
1881          */
1882         if (!oh.unique) {
1883                 err = fuse_notify(fc, oh.error, nbytes - sizeof(oh), cs);
1884                 goto out;
1885         }
1886
1887         err = -EINVAL;
1888         if (oh.error <= -512 || oh.error > 0)
1889                 goto copy_finish;
1890
1891         spin_lock(&fpq->lock);
1892         req = NULL;
1893         if (fpq->connected)
1894                 req = request_find(fpq, oh.unique & ~FUSE_INT_REQ_BIT);
1895
1896         err = -ENOENT;
1897         if (!req) {
1898                 spin_unlock(&fpq->lock);
1899                 goto copy_finish;
1900         }
1901
1902         /* Is it an interrupt reply ID? */
1903         if (oh.unique & FUSE_INT_REQ_BIT) {
1904                 __fuse_get_request(req);
1905                 spin_unlock(&fpq->lock);
1906
1907                 err = 0;
1908                 if (nbytes != sizeof(struct fuse_out_header))
1909                         err = -EINVAL;
1910                 else if (oh.error == -ENOSYS)
1911                         fc->no_interrupt = 1;
1912                 else if (oh.error == -EAGAIN)
1913                         err = queue_interrupt(&fc->iq, req);
1914
1915                 fuse_put_request(fc, req);
1916
1917                 goto copy_finish;
1918         }
1919
1920         clear_bit(FR_SENT, &req->flags);
1921         list_move(&req->list, &fpq->io);
1922         req->out.h = oh;
1923         set_bit(FR_LOCKED, &req->flags);
1924         spin_unlock(&fpq->lock);
1925         cs->req = req;
1926         if (!req->args->page_replace)
1927                 cs->move_pages = 0;
1928
1929         if (oh.error)
1930                 err = nbytes != sizeof(oh) ? -EINVAL : 0;
1931         else
1932                 err = copy_out_args(cs, req->args, nbytes);
1933         fuse_copy_finish(cs);
1934
1935         spin_lock(&fpq->lock);
1936         clear_bit(FR_LOCKED, &req->flags);
1937         if (!fpq->connected)
1938                 err = -ENOENT;
1939         else if (err)
1940                 req->out.h.error = -EIO;
1941         if (!test_bit(FR_PRIVATE, &req->flags))
1942                 list_del_init(&req->list);
1943         spin_unlock(&fpq->lock);
1944
1945         fuse_request_end(fc, req);
1946 out:
1947         return err ? err : nbytes;
1948
1949 copy_finish:
1950         fuse_copy_finish(cs);
1951         goto out;
1952 }
1953
1954 static ssize_t fuse_dev_write(struct kiocb *iocb, struct iov_iter *from)
1955 {
1956         struct fuse_copy_state cs;
1957         struct fuse_dev *fud = fuse_get_dev(iocb->ki_filp);
1958
1959         if (!fud)
1960                 return -EPERM;
1961
1962         if (!iter_is_iovec(from))
1963                 return -EINVAL;
1964
1965         fuse_copy_init(&cs, 0, from);
1966
1967         return fuse_dev_do_write(fud, &cs, iov_iter_count(from));
1968 }
1969
1970 static ssize_t fuse_dev_splice_write(struct pipe_inode_info *pipe,
1971                                      struct file *out, loff_t *ppos,
1972                                      size_t len, unsigned int flags)
1973 {
1974         unsigned nbuf;
1975         unsigned idx;
1976         struct pipe_buffer *bufs;
1977         struct fuse_copy_state cs;
1978         struct fuse_dev *fud;
1979         size_t rem;
1980         ssize_t ret;
1981
1982         fud = fuse_get_dev(out);
1983         if (!fud)
1984                 return -EPERM;
1985
1986         pipe_lock(pipe);
1987
1988         bufs = kvmalloc_array(pipe->nrbufs, sizeof(struct pipe_buffer),
1989                               GFP_KERNEL);
1990         if (!bufs) {
1991                 pipe_unlock(pipe);
1992                 return -ENOMEM;
1993         }
1994
1995         nbuf = 0;
1996         rem = 0;
1997         for (idx = 0; idx < pipe->nrbufs && rem < len; idx++)
1998                 rem += pipe->bufs[(pipe->curbuf + idx) & (pipe->buffers - 1)].len;
1999
2000         ret = -EINVAL;
2001         if (rem < len)
2002                 goto out_free;
2003
2004         rem = len;
2005         while (rem) {
2006                 struct pipe_buffer *ibuf;
2007                 struct pipe_buffer *obuf;
2008
2009                 BUG_ON(nbuf >= pipe->buffers);
2010                 BUG_ON(!pipe->nrbufs);
2011                 ibuf = &pipe->bufs[pipe->curbuf];
2012                 obuf = &bufs[nbuf];
2013
2014                 if (rem >= ibuf->len) {
2015                         *obuf = *ibuf;
2016                         ibuf->ops = NULL;
2017                         pipe->curbuf = (pipe->curbuf + 1) & (pipe->buffers - 1);
2018                         pipe->nrbufs--;
2019                 } else {
2020                         if (!pipe_buf_get(pipe, ibuf))
2021                                 goto out_free;
2022
2023                         *obuf = *ibuf;
2024                         obuf->flags &= ~PIPE_BUF_FLAG_GIFT;
2025                         obuf->len = rem;
2026                         ibuf->offset += obuf->len;
2027                         ibuf->len -= obuf->len;
2028                 }
2029                 nbuf++;
2030                 rem -= obuf->len;
2031         }
2032         pipe_unlock(pipe);
2033
2034         fuse_copy_init(&cs, 0, NULL);
2035         cs.pipebufs = bufs;
2036         cs.nr_segs = nbuf;
2037         cs.pipe = pipe;
2038
2039         if (flags & SPLICE_F_MOVE)
2040                 cs.move_pages = 1;
2041
2042         ret = fuse_dev_do_write(fud, &cs, len);
2043
2044         pipe_lock(pipe);
2045 out_free:
2046         for (idx = 0; idx < nbuf; idx++) {
2047                 struct pipe_buffer *buf = &bufs[idx];
2048
2049                 if (buf->ops)
2050                         pipe_buf_release(pipe, buf);
2051         }
2052         pipe_unlock(pipe);
2053
2054         kvfree(bufs);
2055         return ret;
2056 }
2057
2058 static __poll_t fuse_dev_poll(struct file *file, poll_table *wait)
2059 {
2060         __poll_t mask = EPOLLOUT | EPOLLWRNORM;
2061         struct fuse_iqueue *fiq;
2062         struct fuse_dev *fud = fuse_get_dev(file);
2063
2064         if (!fud)
2065                 return EPOLLERR;
2066
2067         fiq = &fud->fc->iq;
2068         poll_wait(file, &fiq->waitq, wait);
2069
2070         spin_lock(&fiq->lock);
2071         if (!fiq->connected)
2072                 mask = EPOLLERR;
2073         else if (request_pending(fiq))
2074                 mask |= EPOLLIN | EPOLLRDNORM;
2075         spin_unlock(&fiq->lock);
2076
2077         return mask;
2078 }
2079
2080 /* Abort all requests on the given list (pending or processing) */
2081 static void end_requests(struct fuse_conn *fc, struct list_head *head)
2082 {
2083         while (!list_empty(head)) {
2084                 struct fuse_req *req;
2085                 req = list_entry(head->next, struct fuse_req, list);
2086                 req->out.h.error = -ECONNABORTED;
2087                 clear_bit(FR_SENT, &req->flags);
2088                 list_del_init(&req->list);
2089                 fuse_request_end(fc, req);
2090         }
2091 }
2092
2093 static void end_polls(struct fuse_conn *fc)
2094 {
2095         struct rb_node *p;
2096
2097         p = rb_first(&fc->polled_files);
2098
2099         while (p) {
2100                 struct fuse_file *ff;
2101                 ff = rb_entry(p, struct fuse_file, polled_node);
2102                 wake_up_interruptible_all(&ff->poll_wait);
2103
2104                 p = rb_next(p);
2105         }
2106 }
2107
2108 /*
2109  * Abort all requests.
2110  *
2111  * Emergency exit in case of a malicious or accidental deadlock, or just a hung
2112  * filesystem.
2113  *
2114  * The same effect is usually achievable through killing the filesystem daemon
2115  * and all users of the filesystem.  The exception is the combination of an
2116  * asynchronous request and the tricky deadlock (see
2117  * Documentation/filesystems/fuse.txt).
2118  *
2119  * Aborting requests under I/O goes as follows: 1: Separate out unlocked
2120  * requests, they should be finished off immediately.  Locked requests will be
2121  * finished after unlock; see unlock_request(). 2: Finish off the unlocked
2122  * requests.  It is possible that some request will finish before we can.  This
2123  * is OK, the request will in that case be removed from the list before we touch
2124  * it.
2125  */
2126 void fuse_abort_conn(struct fuse_conn *fc)
2127 {
2128         struct fuse_iqueue *fiq = &fc->iq;
2129
2130         spin_lock(&fc->lock);
2131         if (fc->connected) {
2132                 struct fuse_dev *fud;
2133                 struct fuse_req *req, *next;
2134                 LIST_HEAD(to_end);
2135                 unsigned int i;
2136
2137                 /* Background queuing checks fc->connected under bg_lock */
2138                 spin_lock(&fc->bg_lock);
2139                 fc->connected = 0;
2140                 spin_unlock(&fc->bg_lock);
2141
2142                 fuse_set_initialized(fc);
2143                 list_for_each_entry(fud, &fc->devices, entry) {
2144                         struct fuse_pqueue *fpq = &fud->pq;
2145
2146                         spin_lock(&fpq->lock);
2147                         fpq->connected = 0;
2148                         list_for_each_entry_safe(req, next, &fpq->io, list) {
2149                                 req->out.h.error = -ECONNABORTED;
2150                                 spin_lock(&req->waitq.lock);
2151                                 set_bit(FR_ABORTED, &req->flags);
2152                                 if (!test_bit(FR_LOCKED, &req->flags)) {
2153                                         set_bit(FR_PRIVATE, &req->flags);
2154                                         __fuse_get_request(req);
2155                                         list_move(&req->list, &to_end);
2156                                 }
2157                                 spin_unlock(&req->waitq.lock);
2158                         }
2159                         for (i = 0; i < FUSE_PQ_HASH_SIZE; i++)
2160                                 list_splice_tail_init(&fpq->processing[i],
2161                                                       &to_end);
2162                         spin_unlock(&fpq->lock);
2163                 }
2164                 spin_lock(&fc->bg_lock);
2165                 fc->blocked = 0;
2166                 fc->max_background = UINT_MAX;
2167                 flush_bg_queue(fc);
2168                 spin_unlock(&fc->bg_lock);
2169
2170                 spin_lock(&fiq->lock);
2171                 fiq->connected = 0;
2172                 list_for_each_entry(req, &fiq->pending, list)
2173                         clear_bit(FR_PENDING, &req->flags);
2174                 list_splice_tail_init(&fiq->pending, &to_end);
2175                 while (forget_pending(fiq))
2176                         kfree(fuse_dequeue_forget(fiq, 1, NULL));
2177                 wake_up_all(&fiq->waitq);
2178                 spin_unlock(&fiq->lock);
2179                 kill_fasync(&fiq->fasync, SIGIO, POLL_IN);
2180                 end_polls(fc);
2181                 wake_up_all(&fc->blocked_waitq);
2182                 spin_unlock(&fc->lock);
2183
2184                 end_requests(fc, &to_end);
2185         } else {
2186                 spin_unlock(&fc->lock);
2187         }
2188 }
2189 EXPORT_SYMBOL_GPL(fuse_abort_conn);
2190
2191 void fuse_wait_aborted(struct fuse_conn *fc)
2192 {
2193         /* matches implicit memory barrier in fuse_drop_waiting() */
2194         smp_mb();
2195         wait_event(fc->blocked_waitq, atomic_read(&fc->num_waiting) == 0);
2196 }
2197
2198 int fuse_dev_release(struct inode *inode, struct file *file)
2199 {
2200         struct fuse_dev *fud = fuse_get_dev(file);
2201
2202         if (fud) {
2203                 struct fuse_conn *fc = fud->fc;
2204                 struct fuse_pqueue *fpq = &fud->pq;
2205                 LIST_HEAD(to_end);
2206                 unsigned int i;
2207
2208                 spin_lock(&fpq->lock);
2209                 WARN_ON(!list_empty(&fpq->io));
2210                 for (i = 0; i < FUSE_PQ_HASH_SIZE; i++)
2211                         list_splice_init(&fpq->processing[i], &to_end);
2212                 spin_unlock(&fpq->lock);
2213
2214                 end_requests(fc, &to_end);
2215
2216                 /* Are we the last open device? */
2217                 if (atomic_dec_and_test(&fc->dev_count)) {
2218                         WARN_ON(fc->iq.fasync != NULL);
2219                         fuse_abort_conn(fc);
2220                 }
2221                 fuse_dev_free(fud);
2222         }
2223         return 0;
2224 }
2225 EXPORT_SYMBOL_GPL(fuse_dev_release);
2226
2227 static int fuse_dev_fasync(int fd, struct file *file, int on)
2228 {
2229         struct fuse_dev *fud = fuse_get_dev(file);
2230
2231         if (!fud)
2232                 return -EPERM;
2233
2234         /* No locking - fasync_helper does its own locking */
2235         return fasync_helper(fd, file, on, &fud->fc->iq.fasync);
2236 }
2237
2238 static int fuse_device_clone(struct fuse_conn *fc, struct file *new)
2239 {
2240         struct fuse_dev *fud;
2241
2242         if (new->private_data)
2243                 return -EINVAL;
2244
2245         fud = fuse_dev_alloc_install(fc);
2246         if (!fud)
2247                 return -ENOMEM;
2248
2249         new->private_data = fud;
2250         atomic_inc(&fc->dev_count);
2251
2252         return 0;
2253 }
2254
2255 static long fuse_dev_ioctl(struct file *file, unsigned int cmd,
2256                            unsigned long arg)
2257 {
2258         int err = -ENOTTY;
2259
2260         if (cmd == FUSE_DEV_IOC_CLONE) {
2261                 int oldfd;
2262
2263                 err = -EFAULT;
2264                 if (!get_user(oldfd, (__u32 __user *) arg)) {
2265                         struct file *old = fget(oldfd);
2266
2267                         err = -EINVAL;
2268                         if (old) {
2269                                 struct fuse_dev *fud = NULL;
2270
2271                                 /*
2272                                  * Check against file->f_op because CUSE
2273                                  * uses the same ioctl handler.
2274                                  */
2275                                 if (old->f_op == file->f_op &&
2276                                     old->f_cred->user_ns == file->f_cred->user_ns)
2277                                         fud = fuse_get_dev(old);
2278
2279                                 if (fud) {
2280                                         mutex_lock(&fuse_mutex);
2281                                         err = fuse_device_clone(fud->fc, file);
2282                                         mutex_unlock(&fuse_mutex);
2283                                 }
2284                                 fput(old);
2285                         }
2286                 }
2287         }
2288         return err;
2289 }
2290
2291 const struct file_operations fuse_dev_operations = {
2292         .owner          = THIS_MODULE,
2293         .open           = fuse_dev_open,
2294         .llseek         = no_llseek,
2295         .read_iter      = fuse_dev_read,
2296         .splice_read    = fuse_dev_splice_read,
2297         .write_iter     = fuse_dev_write,
2298         .splice_write   = fuse_dev_splice_write,
2299         .poll           = fuse_dev_poll,
2300         .release        = fuse_dev_release,
2301         .fasync         = fuse_dev_fasync,
2302         .unlocked_ioctl = fuse_dev_ioctl,
2303         .compat_ioctl   = fuse_dev_ioctl,
2304 };
2305 EXPORT_SYMBOL_GPL(fuse_dev_operations);
2306
2307 static struct miscdevice fuse_miscdevice = {
2308         .minor = FUSE_MINOR,
2309         .name  = "fuse",
2310         .fops = &fuse_dev_operations,
2311 };
2312
2313 int __init fuse_dev_init(void)
2314 {
2315         int err = -ENOMEM;
2316         fuse_req_cachep = kmem_cache_create("fuse_request",
2317                                             sizeof(struct fuse_req),
2318                                             0, 0, NULL);
2319         if (!fuse_req_cachep)
2320                 goto out;
2321
2322         err = misc_register(&fuse_miscdevice);
2323         if (err)
2324                 goto out_cache_clean;
2325
2326         return 0;
2327
2328  out_cache_clean:
2329         kmem_cache_destroy(fuse_req_cachep);
2330  out:
2331         return err;
2332 }
2333
2334 void fuse_dev_cleanup(void)
2335 {
2336         misc_deregister(&fuse_miscdevice);
2337         kmem_cache_destroy(fuse_req_cachep);
2338 }