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