Merge branch 'stable-3.2' into pandora-3.2
[pandora-kernel.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/uio.h>
15 #include <linux/miscdevice.h>
16 #include <linux/pagemap.h>
17 #include <linux/file.h>
18 #include <linux/slab.h>
19 #include <linux/pipe_fs_i.h>
20 #include <linux/swap.h>
21 #include <linux/splice.h>
22
23 MODULE_ALIAS_MISCDEV(FUSE_MINOR);
24 MODULE_ALIAS("devname:fuse");
25
26 static struct kmem_cache *fuse_req_cachep;
27
28 static struct fuse_conn *fuse_get_conn(struct file *file)
29 {
30         /*
31          * Lockless access is OK, because file->private data is set
32          * once during mount and is valid until the file is released.
33          */
34         return file->private_data;
35 }
36
37 static void fuse_request_init(struct fuse_req *req)
38 {
39         memset(req, 0, sizeof(*req));
40         INIT_LIST_HEAD(&req->list);
41         INIT_LIST_HEAD(&req->intr_entry);
42         init_waitqueue_head(&req->waitq);
43         atomic_set(&req->count, 1);
44 }
45
46 struct fuse_req *fuse_request_alloc(void)
47 {
48         struct fuse_req *req = kmem_cache_alloc(fuse_req_cachep, GFP_KERNEL);
49         if (req)
50                 fuse_request_init(req);
51         return req;
52 }
53 EXPORT_SYMBOL_GPL(fuse_request_alloc);
54
55 struct fuse_req *fuse_request_alloc_nofs(void)
56 {
57         struct fuse_req *req = kmem_cache_alloc(fuse_req_cachep, GFP_NOFS);
58         if (req)
59                 fuse_request_init(req);
60         return req;
61 }
62
63 void fuse_request_free(struct fuse_req *req)
64 {
65         kmem_cache_free(fuse_req_cachep, req);
66 }
67
68 static void block_sigs(sigset_t *oldset)
69 {
70         sigset_t mask;
71
72         siginitsetinv(&mask, sigmask(SIGKILL));
73         sigprocmask(SIG_BLOCK, &mask, oldset);
74 }
75
76 static void restore_sigs(sigset_t *oldset)
77 {
78         sigprocmask(SIG_SETMASK, oldset, NULL);
79 }
80
81 static void __fuse_get_request(struct fuse_req *req)
82 {
83         atomic_inc(&req->count);
84 }
85
86 /* Must be called with > 1 refcount */
87 static void __fuse_put_request(struct fuse_req *req)
88 {
89         BUG_ON(atomic_read(&req->count) < 2);
90         atomic_dec(&req->count);
91 }
92
93 static void fuse_req_init_context(struct fuse_req *req)
94 {
95         req->in.h.uid = current_fsuid();
96         req->in.h.gid = current_fsgid();
97         req->in.h.pid = current->pid;
98 }
99
100 struct fuse_req *fuse_get_req(struct fuse_conn *fc)
101 {
102         struct fuse_req *req;
103         sigset_t oldset;
104         int intr;
105         int err;
106
107         atomic_inc(&fc->num_waiting);
108         block_sigs(&oldset);
109         intr = wait_event_interruptible(fc->blocked_waitq, !fc->blocked);
110         restore_sigs(&oldset);
111         err = -EINTR;
112         if (intr)
113                 goto out;
114
115         err = -ENOTCONN;
116         if (!fc->connected)
117                 goto out;
118
119         req = fuse_request_alloc();
120         err = -ENOMEM;
121         if (!req)
122                 goto out;
123
124         fuse_req_init_context(req);
125         req->waiting = 1;
126         return req;
127
128  out:
129         atomic_dec(&fc->num_waiting);
130         return ERR_PTR(err);
131 }
132 EXPORT_SYMBOL_GPL(fuse_get_req);
133
134 /*
135  * Return request in fuse_file->reserved_req.  However that may
136  * currently be in use.  If that is the case, wait for it to become
137  * available.
138  */
139 static struct fuse_req *get_reserved_req(struct fuse_conn *fc,
140                                          struct file *file)
141 {
142         struct fuse_req *req = NULL;
143         struct fuse_file *ff = file->private_data;
144
145         do {
146                 wait_event(fc->reserved_req_waitq, ff->reserved_req);
147                 spin_lock(&fc->lock);
148                 if (ff->reserved_req) {
149                         req = ff->reserved_req;
150                         ff->reserved_req = NULL;
151                         req->stolen_file = get_file(file);
152                 }
153                 spin_unlock(&fc->lock);
154         } while (!req);
155
156         return req;
157 }
158
159 /*
160  * Put stolen request back into fuse_file->reserved_req
161  */
162 static void put_reserved_req(struct fuse_conn *fc, struct fuse_req *req)
163 {
164         struct file *file = req->stolen_file;
165         struct fuse_file *ff = file->private_data;
166
167         spin_lock(&fc->lock);
168         fuse_request_init(req);
169         BUG_ON(ff->reserved_req);
170         ff->reserved_req = req;
171         wake_up_all(&fc->reserved_req_waitq);
172         spin_unlock(&fc->lock);
173         fput(file);
174 }
175
176 /*
177  * Gets a requests for a file operation, always succeeds
178  *
179  * This is used for sending the FLUSH request, which must get to
180  * userspace, due to POSIX locks which may need to be unlocked.
181  *
182  * If allocation fails due to OOM, use the reserved request in
183  * fuse_file.
184  *
185  * This is very unlikely to deadlock accidentally, since the
186  * filesystem should not have it's own file open.  If deadlock is
187  * intentional, it can still be broken by "aborting" the filesystem.
188  */
189 struct fuse_req *fuse_get_req_nofail(struct fuse_conn *fc, struct file *file)
190 {
191         struct fuse_req *req;
192
193         atomic_inc(&fc->num_waiting);
194         wait_event(fc->blocked_waitq, !fc->blocked);
195         req = fuse_request_alloc();
196         if (!req)
197                 req = get_reserved_req(fc, file);
198
199         fuse_req_init_context(req);
200         req->waiting = 1;
201         return req;
202 }
203
204 void fuse_put_request(struct fuse_conn *fc, struct fuse_req *req)
205 {
206         if (atomic_dec_and_test(&req->count)) {
207                 if (req->waiting)
208                         atomic_dec(&fc->num_waiting);
209
210                 if (req->stolen_file)
211                         put_reserved_req(fc, req);
212                 else
213                         fuse_request_free(req);
214         }
215 }
216 EXPORT_SYMBOL_GPL(fuse_put_request);
217
218 static unsigned len_args(unsigned numargs, struct fuse_arg *args)
219 {
220         unsigned nbytes = 0;
221         unsigned i;
222
223         for (i = 0; i < numargs; i++)
224                 nbytes += args[i].size;
225
226         return nbytes;
227 }
228
229 static u64 fuse_get_unique(struct fuse_conn *fc)
230 {
231         fc->reqctr++;
232         /* zero is special */
233         if (fc->reqctr == 0)
234                 fc->reqctr = 1;
235
236         return fc->reqctr;
237 }
238
239 static void queue_request(struct fuse_conn *fc, struct fuse_req *req)
240 {
241         req->in.h.len = sizeof(struct fuse_in_header) +
242                 len_args(req->in.numargs, (struct fuse_arg *) req->in.args);
243         list_add_tail(&req->list, &fc->pending);
244         req->state = FUSE_REQ_PENDING;
245         if (!req->waiting) {
246                 req->waiting = 1;
247                 atomic_inc(&fc->num_waiting);
248         }
249         wake_up(&fc->waitq);
250         kill_fasync(&fc->fasync, SIGIO, POLL_IN);
251 }
252
253 void fuse_queue_forget(struct fuse_conn *fc, struct fuse_forget_link *forget,
254                        u64 nodeid, u64 nlookup)
255 {
256         forget->forget_one.nodeid = nodeid;
257         forget->forget_one.nlookup = nlookup;
258
259         spin_lock(&fc->lock);
260         if (fc->connected) {
261                 fc->forget_list_tail->next = forget;
262                 fc->forget_list_tail = forget;
263                 wake_up(&fc->waitq);
264                 kill_fasync(&fc->fasync, SIGIO, POLL_IN);
265         } else {
266                 kfree(forget);
267         }
268         spin_unlock(&fc->lock);
269 }
270
271 static void flush_bg_queue(struct fuse_conn *fc)
272 {
273         while (fc->active_background < fc->max_background &&
274                !list_empty(&fc->bg_queue)) {
275                 struct fuse_req *req;
276
277                 req = list_entry(fc->bg_queue.next, struct fuse_req, list);
278                 list_del(&req->list);
279                 fc->active_background++;
280                 req->in.h.unique = fuse_get_unique(fc);
281                 queue_request(fc, req);
282         }
283 }
284
285 /*
286  * This function is called when a request is finished.  Either a reply
287  * has arrived or it was aborted (and not yet sent) or some error
288  * occurred during communication with userspace, or the device file
289  * was closed.  The requester thread is woken up (if still waiting),
290  * the 'end' callback is called if given, else the reference to the
291  * request is released
292  *
293  * Called with fc->lock, unlocks it
294  */
295 static void request_end(struct fuse_conn *fc, struct fuse_req *req)
296 __releases(fc->lock)
297 {
298         void (*end) (struct fuse_conn *, struct fuse_req *) = req->end;
299         req->end = NULL;
300         list_del(&req->list);
301         list_del(&req->intr_entry);
302         req->state = FUSE_REQ_FINISHED;
303         if (req->background) {
304                 if (fc->num_background == fc->max_background) {
305                         fc->blocked = 0;
306                         wake_up_all(&fc->blocked_waitq);
307                 }
308                 if (fc->num_background == fc->congestion_threshold &&
309                     fc->connected && fc->bdi_initialized) {
310                         clear_bdi_congested(&fc->bdi, BLK_RW_SYNC);
311                         clear_bdi_congested(&fc->bdi, BLK_RW_ASYNC);
312                 }
313                 fc->num_background--;
314                 fc->active_background--;
315                 flush_bg_queue(fc);
316         }
317         spin_unlock(&fc->lock);
318         wake_up(&req->waitq);
319         if (end)
320                 end(fc, req);
321         fuse_put_request(fc, req);
322 }
323
324 static void wait_answer_interruptible(struct fuse_conn *fc,
325                                       struct fuse_req *req)
326 __releases(fc->lock)
327 __acquires(fc->lock)
328 {
329         if (signal_pending(current))
330                 return;
331
332         spin_unlock(&fc->lock);
333         wait_event_interruptible(req->waitq, req->state == FUSE_REQ_FINISHED);
334         spin_lock(&fc->lock);
335 }
336
337 static void queue_interrupt(struct fuse_conn *fc, struct fuse_req *req)
338 {
339         list_add_tail(&req->intr_entry, &fc->interrupts);
340         wake_up(&fc->waitq);
341         kill_fasync(&fc->fasync, SIGIO, POLL_IN);
342 }
343
344 static void request_wait_answer(struct fuse_conn *fc, struct fuse_req *req)
345 __releases(fc->lock)
346 __acquires(fc->lock)
347 {
348         if (!fc->no_interrupt) {
349                 /* Any signal may interrupt this */
350                 wait_answer_interruptible(fc, req);
351
352                 if (req->aborted)
353                         goto aborted;
354                 if (req->state == FUSE_REQ_FINISHED)
355                         return;
356
357                 req->interrupted = 1;
358                 if (req->state == FUSE_REQ_SENT)
359                         queue_interrupt(fc, req);
360         }
361
362         if (!req->force) {
363                 sigset_t oldset;
364
365                 /* Only fatal signals may interrupt this */
366                 block_sigs(&oldset);
367                 wait_answer_interruptible(fc, req);
368                 restore_sigs(&oldset);
369
370                 if (req->aborted)
371                         goto aborted;
372                 if (req->state == FUSE_REQ_FINISHED)
373                         return;
374
375                 /* Request is not yet in userspace, bail out */
376                 if (req->state == FUSE_REQ_PENDING) {
377                         list_del(&req->list);
378                         __fuse_put_request(req);
379                         req->out.h.error = -EINTR;
380                         return;
381                 }
382         }
383
384         /*
385          * Either request is already in userspace, or it was forced.
386          * Wait it out.
387          */
388         spin_unlock(&fc->lock);
389         wait_event(req->waitq, req->state == FUSE_REQ_FINISHED);
390         spin_lock(&fc->lock);
391
392         if (!req->aborted)
393                 return;
394
395  aborted:
396         BUG_ON(req->state != FUSE_REQ_FINISHED);
397         if (req->locked) {
398                 /* This is uninterruptible sleep, because data is
399                    being copied to/from the buffers of req.  During
400                    locked state, there mustn't be any filesystem
401                    operation (e.g. page fault), since that could lead
402                    to deadlock */
403                 spin_unlock(&fc->lock);
404                 wait_event(req->waitq, !req->locked);
405                 spin_lock(&fc->lock);
406         }
407 }
408
409 void fuse_request_send(struct fuse_conn *fc, struct fuse_req *req)
410 {
411         req->isreply = 1;
412         spin_lock(&fc->lock);
413         if (!fc->connected)
414                 req->out.h.error = -ENOTCONN;
415         else if (fc->conn_error)
416                 req->out.h.error = -ECONNREFUSED;
417         else {
418                 req->in.h.unique = fuse_get_unique(fc);
419                 queue_request(fc, req);
420                 /* acquire extra reference, since request is still needed
421                    after request_end() */
422                 __fuse_get_request(req);
423
424                 request_wait_answer(fc, req);
425         }
426         spin_unlock(&fc->lock);
427 }
428 EXPORT_SYMBOL_GPL(fuse_request_send);
429
430 static void fuse_request_send_nowait_locked(struct fuse_conn *fc,
431                                             struct fuse_req *req)
432 {
433         req->background = 1;
434         fc->num_background++;
435         if (fc->num_background == fc->max_background)
436                 fc->blocked = 1;
437         if (fc->num_background == fc->congestion_threshold &&
438             fc->bdi_initialized) {
439                 set_bdi_congested(&fc->bdi, BLK_RW_SYNC);
440                 set_bdi_congested(&fc->bdi, BLK_RW_ASYNC);
441         }
442         list_add_tail(&req->list, &fc->bg_queue);
443         flush_bg_queue(fc);
444 }
445
446 static void fuse_request_send_nowait(struct fuse_conn *fc, struct fuse_req *req)
447 {
448         spin_lock(&fc->lock);
449         if (fc->connected) {
450                 fuse_request_send_nowait_locked(fc, req);
451                 spin_unlock(&fc->lock);
452         } else {
453                 req->out.h.error = -ENOTCONN;
454                 request_end(fc, req);
455         }
456 }
457
458 void fuse_request_send_background(struct fuse_conn *fc, struct fuse_req *req)
459 {
460         req->isreply = 1;
461         fuse_request_send_nowait(fc, req);
462 }
463 EXPORT_SYMBOL_GPL(fuse_request_send_background);
464
465 static int fuse_request_send_notify_reply(struct fuse_conn *fc,
466                                           struct fuse_req *req, u64 unique)
467 {
468         int err = -ENODEV;
469
470         req->isreply = 0;
471         req->in.h.unique = unique;
472         spin_lock(&fc->lock);
473         if (fc->connected) {
474                 queue_request(fc, req);
475                 err = 0;
476         }
477         spin_unlock(&fc->lock);
478
479         return err;
480 }
481
482 /*
483  * Called under fc->lock
484  *
485  * fc->connected must have been checked previously
486  */
487 void fuse_request_send_background_locked(struct fuse_conn *fc,
488                                          struct fuse_req *req)
489 {
490         req->isreply = 1;
491         fuse_request_send_nowait_locked(fc, req);
492 }
493
494 /*
495  * Lock the request.  Up to the next unlock_request() there mustn't be
496  * anything that could cause a page-fault.  If the request was already
497  * aborted bail out.
498  */
499 static int lock_request(struct fuse_conn *fc, struct fuse_req *req)
500 {
501         int err = 0;
502         if (req) {
503                 spin_lock(&fc->lock);
504                 if (req->aborted)
505                         err = -ENOENT;
506                 else
507                         req->locked = 1;
508                 spin_unlock(&fc->lock);
509         }
510         return err;
511 }
512
513 /*
514  * Unlock request.  If it was aborted during being locked, the
515  * requester thread is currently waiting for it to be unlocked, so
516  * wake it up.
517  */
518 static void unlock_request(struct fuse_conn *fc, struct fuse_req *req)
519 {
520         if (req) {
521                 spin_lock(&fc->lock);
522                 req->locked = 0;
523                 if (req->aborted)
524                         wake_up(&req->waitq);
525                 spin_unlock(&fc->lock);
526         }
527 }
528
529 struct fuse_copy_state {
530         struct fuse_conn *fc;
531         int write;
532         struct fuse_req *req;
533         const struct iovec *iov;
534         struct pipe_buffer *pipebufs;
535         struct pipe_buffer *currbuf;
536         struct pipe_inode_info *pipe;
537         unsigned long nr_segs;
538         unsigned long seglen;
539         unsigned long addr;
540         struct page *pg;
541         void *mapaddr;
542         void *buf;
543         unsigned len;
544         unsigned move_pages:1;
545 };
546
547 static void fuse_copy_init(struct fuse_copy_state *cs, struct fuse_conn *fc,
548                            int write,
549                            const struct iovec *iov, unsigned long nr_segs)
550 {
551         memset(cs, 0, sizeof(*cs));
552         cs->fc = fc;
553         cs->write = write;
554         cs->iov = iov;
555         cs->nr_segs = nr_segs;
556 }
557
558 /* Unmap and put previous page of userspace buffer */
559 static void fuse_copy_finish(struct fuse_copy_state *cs)
560 {
561         if (cs->currbuf) {
562                 struct pipe_buffer *buf = cs->currbuf;
563
564                 if (!cs->write) {
565                         buf->ops->unmap(cs->pipe, buf, cs->mapaddr);
566                 } else {
567                         kunmap(buf->page);
568                         buf->len = PAGE_SIZE - cs->len;
569                 }
570                 cs->currbuf = NULL;
571                 cs->mapaddr = NULL;
572         } else if (cs->mapaddr) {
573                 kunmap(cs->pg);
574                 if (cs->write) {
575                         flush_dcache_page(cs->pg);
576                         set_page_dirty_lock(cs->pg);
577                 }
578                 put_page(cs->pg);
579                 cs->mapaddr = NULL;
580         }
581 }
582
583 /*
584  * Get another pagefull of userspace buffer, and map it to kernel
585  * address space, and lock request
586  */
587 static int fuse_copy_fill(struct fuse_copy_state *cs)
588 {
589         unsigned long offset;
590         int err;
591
592         unlock_request(cs->fc, cs->req);
593         fuse_copy_finish(cs);
594         if (cs->pipebufs) {
595                 struct pipe_buffer *buf = cs->pipebufs;
596
597                 if (!cs->write) {
598                         err = buf->ops->confirm(cs->pipe, buf);
599                         if (err)
600                                 return err;
601
602                         BUG_ON(!cs->nr_segs);
603                         cs->currbuf = buf;
604                         cs->mapaddr = buf->ops->map(cs->pipe, buf, 0);
605                         cs->len = buf->len;
606                         cs->buf = cs->mapaddr + buf->offset;
607                         cs->pipebufs++;
608                         cs->nr_segs--;
609                 } else {
610                         struct page *page;
611
612                         if (cs->nr_segs == cs->pipe->buffers)
613                                 return -EIO;
614
615                         page = alloc_page(GFP_HIGHUSER);
616                         if (!page)
617                                 return -ENOMEM;
618
619                         buf->page = page;
620                         buf->offset = 0;
621                         buf->len = 0;
622
623                         cs->currbuf = buf;
624                         cs->mapaddr = kmap(page);
625                         cs->buf = cs->mapaddr;
626                         cs->len = PAGE_SIZE;
627                         cs->pipebufs++;
628                         cs->nr_segs++;
629                 }
630         } else {
631                 if (!cs->seglen) {
632                         BUG_ON(!cs->nr_segs);
633                         cs->seglen = cs->iov[0].iov_len;
634                         cs->addr = (unsigned long) cs->iov[0].iov_base;
635                         cs->iov++;
636                         cs->nr_segs--;
637                 }
638                 err = get_user_pages_fast(cs->addr, 1, cs->write, &cs->pg);
639                 if (err < 0)
640                         return err;
641                 BUG_ON(err != 1);
642                 offset = cs->addr % PAGE_SIZE;
643                 cs->mapaddr = kmap(cs->pg);
644                 cs->buf = cs->mapaddr + offset;
645                 cs->len = min(PAGE_SIZE - offset, cs->seglen);
646                 cs->seglen -= cs->len;
647                 cs->addr += cs->len;
648         }
649
650         return lock_request(cs->fc, cs->req);
651 }
652
653 /* Do as much copy to/from userspace buffer as we can */
654 static int fuse_copy_do(struct fuse_copy_state *cs, void **val, unsigned *size)
655 {
656         unsigned ncpy = min(*size, cs->len);
657         if (val) {
658                 if (cs->write)
659                         memcpy(cs->buf, *val, ncpy);
660                 else
661                         memcpy(*val, cs->buf, ncpy);
662                 *val += ncpy;
663         }
664         *size -= ncpy;
665         cs->len -= ncpy;
666         cs->buf += ncpy;
667         return ncpy;
668 }
669
670 static int fuse_check_page(struct page *page)
671 {
672         if (page_mapcount(page) ||
673             page->mapping != NULL ||
674             page_count(page) != 1 ||
675             (page->flags & PAGE_FLAGS_CHECK_AT_PREP &
676              ~(1 << PG_locked |
677                1 << PG_referenced |
678                1 << PG_uptodate |
679                1 << PG_lru |
680                1 << PG_active |
681                1 << PG_reclaim))) {
682                 printk(KERN_WARNING "fuse: trying to steal weird page\n");
683                 printk(KERN_WARNING "  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);
684                 return 1;
685         }
686         return 0;
687 }
688
689 static int fuse_try_move_page(struct fuse_copy_state *cs, struct page **pagep)
690 {
691         int err;
692         struct page *oldpage = *pagep;
693         struct page *newpage;
694         struct pipe_buffer *buf = cs->pipebufs;
695         struct address_space *mapping;
696         pgoff_t index;
697
698         unlock_request(cs->fc, cs->req);
699         fuse_copy_finish(cs);
700
701         err = buf->ops->confirm(cs->pipe, buf);
702         if (err)
703                 return err;
704
705         BUG_ON(!cs->nr_segs);
706         cs->currbuf = buf;
707         cs->len = buf->len;
708         cs->pipebufs++;
709         cs->nr_segs--;
710
711         if (cs->len != PAGE_SIZE)
712                 goto out_fallback;
713
714         if (buf->ops->steal(cs->pipe, buf) != 0)
715                 goto out_fallback;
716
717         newpage = buf->page;
718
719         if (!PageUptodate(newpage))
720                 SetPageUptodate(newpage);
721
722         ClearPageMappedToDisk(newpage);
723
724         if (fuse_check_page(newpage) != 0)
725                 goto out_fallback_unlock;
726
727         mapping = oldpage->mapping;
728         index = oldpage->index;
729
730         /*
731          * This is a new and locked page, it shouldn't be mapped or
732          * have any special flags on it
733          */
734         if (WARN_ON(page_mapped(oldpage)))
735                 goto out_fallback_unlock;
736         if (WARN_ON(page_has_private(oldpage)))
737                 goto out_fallback_unlock;
738         if (WARN_ON(PageDirty(oldpage) || PageWriteback(oldpage)))
739                 goto out_fallback_unlock;
740         if (WARN_ON(PageMlocked(oldpage)))
741                 goto out_fallback_unlock;
742
743         err = replace_page_cache_page(oldpage, newpage, GFP_KERNEL);
744         if (err) {
745                 unlock_page(newpage);
746                 return err;
747         }
748
749         page_cache_get(newpage);
750
751         if (!(buf->flags & PIPE_BUF_FLAG_LRU))
752                 lru_cache_add_file(newpage);
753
754         err = 0;
755         spin_lock(&cs->fc->lock);
756         if (cs->req->aborted)
757                 err = -ENOENT;
758         else
759                 *pagep = newpage;
760         spin_unlock(&cs->fc->lock);
761
762         if (err) {
763                 unlock_page(newpage);
764                 page_cache_release(newpage);
765                 return err;
766         }
767
768         unlock_page(oldpage);
769         page_cache_release(oldpage);
770         cs->len = 0;
771
772         return 0;
773
774 out_fallback_unlock:
775         unlock_page(newpage);
776 out_fallback:
777         cs->mapaddr = buf->ops->map(cs->pipe, buf, 1);
778         cs->buf = cs->mapaddr + buf->offset;
779
780         err = lock_request(cs->fc, cs->req);
781         if (err)
782                 return err;
783
784         return 1;
785 }
786
787 static int fuse_ref_page(struct fuse_copy_state *cs, struct page *page,
788                          unsigned offset, unsigned count)
789 {
790         struct pipe_buffer *buf;
791
792         if (cs->nr_segs == cs->pipe->buffers)
793                 return -EIO;
794
795         unlock_request(cs->fc, cs->req);
796         fuse_copy_finish(cs);
797
798         buf = cs->pipebufs;
799         page_cache_get(page);
800         buf->page = page;
801         buf->offset = offset;
802         buf->len = count;
803
804         cs->pipebufs++;
805         cs->nr_segs++;
806         cs->len = 0;
807
808         return 0;
809 }
810
811 /*
812  * Copy a page in the request to/from the userspace buffer.  Must be
813  * done atomically
814  */
815 static int fuse_copy_page(struct fuse_copy_state *cs, struct page **pagep,
816                           unsigned offset, unsigned count, int zeroing)
817 {
818         int err;
819         struct page *page = *pagep;
820
821         if (page && zeroing && count < PAGE_SIZE)
822                 clear_highpage(page);
823
824         while (count) {
825                 if (cs->write && cs->pipebufs && page) {
826                         return fuse_ref_page(cs, page, offset, count);
827                 } else if (!cs->len) {
828                         if (cs->move_pages && page &&
829                             offset == 0 && count == PAGE_SIZE) {
830                                 err = fuse_try_move_page(cs, pagep);
831                                 if (err <= 0)
832                                         return err;
833                         } else {
834                                 err = fuse_copy_fill(cs);
835                                 if (err)
836                                         return err;
837                         }
838                 }
839                 if (page) {
840                         void *mapaddr = kmap_atomic(page, KM_USER0);
841                         void *buf = mapaddr + offset;
842                         offset += fuse_copy_do(cs, &buf, &count);
843                         kunmap_atomic(mapaddr, KM_USER0);
844                 } else
845                         offset += fuse_copy_do(cs, NULL, &count);
846         }
847         if (page && !cs->write)
848                 flush_dcache_page(page);
849         return 0;
850 }
851
852 /* Copy pages in the request to/from userspace buffer */
853 static int fuse_copy_pages(struct fuse_copy_state *cs, unsigned nbytes,
854                            int zeroing)
855 {
856         unsigned i;
857         struct fuse_req *req = cs->req;
858         unsigned offset = req->page_offset;
859         unsigned count = min(nbytes, (unsigned) PAGE_SIZE - offset);
860
861         for (i = 0; i < req->num_pages && (nbytes || zeroing); i++) {
862                 int err;
863
864                 err = fuse_copy_page(cs, &req->pages[i], offset, count,
865                                      zeroing);
866                 if (err)
867                         return err;
868
869                 nbytes -= count;
870                 count = min(nbytes, (unsigned) PAGE_SIZE);
871                 offset = 0;
872         }
873         return 0;
874 }
875
876 /* Copy a single argument in the request to/from userspace buffer */
877 static int fuse_copy_one(struct fuse_copy_state *cs, void *val, unsigned size)
878 {
879         while (size) {
880                 if (!cs->len) {
881                         int err = fuse_copy_fill(cs);
882                         if (err)
883                                 return err;
884                 }
885                 fuse_copy_do(cs, &val, &size);
886         }
887         return 0;
888 }
889
890 /* Copy request arguments to/from userspace buffer */
891 static int fuse_copy_args(struct fuse_copy_state *cs, unsigned numargs,
892                           unsigned argpages, struct fuse_arg *args,
893                           int zeroing)
894 {
895         int err = 0;
896         unsigned i;
897
898         for (i = 0; !err && i < numargs; i++)  {
899                 struct fuse_arg *arg = &args[i];
900                 if (i == numargs - 1 && argpages)
901                         err = fuse_copy_pages(cs, arg->size, zeroing);
902                 else
903                         err = fuse_copy_one(cs, arg->value, arg->size);
904         }
905         return err;
906 }
907
908 static int forget_pending(struct fuse_conn *fc)
909 {
910         return fc->forget_list_head.next != NULL;
911 }
912
913 static int request_pending(struct fuse_conn *fc)
914 {
915         return !list_empty(&fc->pending) || !list_empty(&fc->interrupts) ||
916                 forget_pending(fc);
917 }
918
919 /* Wait until a request is available on the pending list */
920 static void request_wait(struct fuse_conn *fc)
921 __releases(fc->lock)
922 __acquires(fc->lock)
923 {
924         DECLARE_WAITQUEUE(wait, current);
925
926         add_wait_queue_exclusive(&fc->waitq, &wait);
927         while (fc->connected && !request_pending(fc)) {
928                 set_current_state(TASK_INTERRUPTIBLE);
929                 if (signal_pending(current))
930                         break;
931
932                 spin_unlock(&fc->lock);
933                 schedule();
934                 spin_lock(&fc->lock);
935         }
936         set_current_state(TASK_RUNNING);
937         remove_wait_queue(&fc->waitq, &wait);
938 }
939
940 /*
941  * Transfer an interrupt request to userspace
942  *
943  * Unlike other requests this is assembled on demand, without a need
944  * to allocate a separate fuse_req structure.
945  *
946  * Called with fc->lock held, releases it
947  */
948 static int fuse_read_interrupt(struct fuse_conn *fc, struct fuse_copy_state *cs,
949                                size_t nbytes, struct fuse_req *req)
950 __releases(fc->lock)
951 {
952         struct fuse_in_header ih;
953         struct fuse_interrupt_in arg;
954         unsigned reqsize = sizeof(ih) + sizeof(arg);
955         int err;
956
957         list_del_init(&req->intr_entry);
958         req->intr_unique = fuse_get_unique(fc);
959         memset(&ih, 0, sizeof(ih));
960         memset(&arg, 0, sizeof(arg));
961         ih.len = reqsize;
962         ih.opcode = FUSE_INTERRUPT;
963         ih.unique = req->intr_unique;
964         arg.unique = req->in.h.unique;
965
966         spin_unlock(&fc->lock);
967         if (nbytes < reqsize)
968                 return -EINVAL;
969
970         err = fuse_copy_one(cs, &ih, sizeof(ih));
971         if (!err)
972                 err = fuse_copy_one(cs, &arg, sizeof(arg));
973         fuse_copy_finish(cs);
974
975         return err ? err : reqsize;
976 }
977
978 static struct fuse_forget_link *dequeue_forget(struct fuse_conn *fc,
979                                                unsigned max,
980                                                unsigned *countp)
981 {
982         struct fuse_forget_link *head = fc->forget_list_head.next;
983         struct fuse_forget_link **newhead = &head;
984         unsigned count;
985
986         for (count = 0; *newhead != NULL && count < max; count++)
987                 newhead = &(*newhead)->next;
988
989         fc->forget_list_head.next = *newhead;
990         *newhead = NULL;
991         if (fc->forget_list_head.next == NULL)
992                 fc->forget_list_tail = &fc->forget_list_head;
993
994         if (countp != NULL)
995                 *countp = count;
996
997         return head;
998 }
999
1000 static int fuse_read_single_forget(struct fuse_conn *fc,
1001                                    struct fuse_copy_state *cs,
1002                                    size_t nbytes)
1003 __releases(fc->lock)
1004 {
1005         int err;
1006         struct fuse_forget_link *forget = dequeue_forget(fc, 1, NULL);
1007         struct fuse_forget_in arg = {
1008                 .nlookup = forget->forget_one.nlookup,
1009         };
1010         struct fuse_in_header ih = {
1011                 .opcode = FUSE_FORGET,
1012                 .nodeid = forget->forget_one.nodeid,
1013                 .unique = fuse_get_unique(fc),
1014                 .len = sizeof(ih) + sizeof(arg),
1015         };
1016
1017         spin_unlock(&fc->lock);
1018         kfree(forget);
1019         if (nbytes < ih.len)
1020                 return -EINVAL;
1021
1022         err = fuse_copy_one(cs, &ih, sizeof(ih));
1023         if (!err)
1024                 err = fuse_copy_one(cs, &arg, sizeof(arg));
1025         fuse_copy_finish(cs);
1026
1027         if (err)
1028                 return err;
1029
1030         return ih.len;
1031 }
1032
1033 static int fuse_read_batch_forget(struct fuse_conn *fc,
1034                                    struct fuse_copy_state *cs, size_t nbytes)
1035 __releases(fc->lock)
1036 {
1037         int err;
1038         unsigned max_forgets;
1039         unsigned count;
1040         struct fuse_forget_link *head;
1041         struct fuse_batch_forget_in arg = { .count = 0 };
1042         struct fuse_in_header ih = {
1043                 .opcode = FUSE_BATCH_FORGET,
1044                 .unique = fuse_get_unique(fc),
1045                 .len = sizeof(ih) + sizeof(arg),
1046         };
1047
1048         if (nbytes < ih.len) {
1049                 spin_unlock(&fc->lock);
1050                 return -EINVAL;
1051         }
1052
1053         max_forgets = (nbytes - ih.len) / sizeof(struct fuse_forget_one);
1054         head = dequeue_forget(fc, max_forgets, &count);
1055         spin_unlock(&fc->lock);
1056
1057         arg.count = count;
1058         ih.len += count * sizeof(struct fuse_forget_one);
1059         err = fuse_copy_one(cs, &ih, sizeof(ih));
1060         if (!err)
1061                 err = fuse_copy_one(cs, &arg, sizeof(arg));
1062
1063         while (head) {
1064                 struct fuse_forget_link *forget = head;
1065
1066                 if (!err) {
1067                         err = fuse_copy_one(cs, &forget->forget_one,
1068                                             sizeof(forget->forget_one));
1069                 }
1070                 head = forget->next;
1071                 kfree(forget);
1072         }
1073
1074         fuse_copy_finish(cs);
1075
1076         if (err)
1077                 return err;
1078
1079         return ih.len;
1080 }
1081
1082 static int fuse_read_forget(struct fuse_conn *fc, struct fuse_copy_state *cs,
1083                             size_t nbytes)
1084 __releases(fc->lock)
1085 {
1086         if (fc->minor < 16 || fc->forget_list_head.next->next == NULL)
1087                 return fuse_read_single_forget(fc, cs, nbytes);
1088         else
1089                 return fuse_read_batch_forget(fc, cs, nbytes);
1090 }
1091
1092 /*
1093  * Read a single request into the userspace filesystem's buffer.  This
1094  * function waits until a request is available, then removes it from
1095  * the pending list and copies request data to userspace buffer.  If
1096  * no reply is needed (FORGET) or request has been aborted or there
1097  * was an error during the copying then it's finished by calling
1098  * request_end().  Otherwise add it to the processing list, and set
1099  * the 'sent' flag.
1100  */
1101 static ssize_t fuse_dev_do_read(struct fuse_conn *fc, struct file *file,
1102                                 struct fuse_copy_state *cs, size_t nbytes)
1103 {
1104         int err;
1105         struct fuse_req *req;
1106         struct fuse_in *in;
1107         unsigned reqsize;
1108
1109  restart:
1110         spin_lock(&fc->lock);
1111         err = -EAGAIN;
1112         if ((file->f_flags & O_NONBLOCK) && fc->connected &&
1113             !request_pending(fc))
1114                 goto err_unlock;
1115
1116         request_wait(fc);
1117         err = -ENODEV;
1118         if (!fc->connected)
1119                 goto err_unlock;
1120         err = -ERESTARTSYS;
1121         if (!request_pending(fc))
1122                 goto err_unlock;
1123
1124         if (!list_empty(&fc->interrupts)) {
1125                 req = list_entry(fc->interrupts.next, struct fuse_req,
1126                                  intr_entry);
1127                 return fuse_read_interrupt(fc, cs, nbytes, req);
1128         }
1129
1130         if (forget_pending(fc)) {
1131                 if (list_empty(&fc->pending) || fc->forget_batch-- > 0)
1132                         return fuse_read_forget(fc, cs, nbytes);
1133
1134                 if (fc->forget_batch <= -8)
1135                         fc->forget_batch = 16;
1136         }
1137
1138         req = list_entry(fc->pending.next, struct fuse_req, list);
1139         req->state = FUSE_REQ_READING;
1140         list_move(&req->list, &fc->io);
1141
1142         in = &req->in;
1143         reqsize = in->h.len;
1144         /* If request is too large, reply with an error and restart the read */
1145         if (nbytes < reqsize) {
1146                 req->out.h.error = -EIO;
1147                 /* SETXATTR is special, since it may contain too large data */
1148                 if (in->h.opcode == FUSE_SETXATTR)
1149                         req->out.h.error = -E2BIG;
1150                 request_end(fc, req);
1151                 goto restart;
1152         }
1153         spin_unlock(&fc->lock);
1154         cs->req = req;
1155         err = fuse_copy_one(cs, &in->h, sizeof(in->h));
1156         if (!err)
1157                 err = fuse_copy_args(cs, in->numargs, in->argpages,
1158                                      (struct fuse_arg *) in->args, 0);
1159         fuse_copy_finish(cs);
1160         spin_lock(&fc->lock);
1161         req->locked = 0;
1162         if (req->aborted) {
1163                 request_end(fc, req);
1164                 return -ENODEV;
1165         }
1166         if (err) {
1167                 req->out.h.error = -EIO;
1168                 request_end(fc, req);
1169                 return err;
1170         }
1171         if (!req->isreply)
1172                 request_end(fc, req);
1173         else {
1174                 req->state = FUSE_REQ_SENT;
1175                 list_move_tail(&req->list, &fc->processing);
1176                 if (req->interrupted)
1177                         queue_interrupt(fc, req);
1178                 spin_unlock(&fc->lock);
1179         }
1180         return reqsize;
1181
1182  err_unlock:
1183         spin_unlock(&fc->lock);
1184         return err;
1185 }
1186
1187 static ssize_t fuse_dev_read(struct kiocb *iocb, const struct iovec *iov,
1188                               unsigned long nr_segs, loff_t pos)
1189 {
1190         struct fuse_copy_state cs;
1191         struct file *file = iocb->ki_filp;
1192         struct fuse_conn *fc = fuse_get_conn(file);
1193         if (!fc)
1194                 return -EPERM;
1195
1196         fuse_copy_init(&cs, fc, 1, iov, nr_segs);
1197
1198         return fuse_dev_do_read(fc, file, &cs, iov_length(iov, nr_segs));
1199 }
1200
1201 static ssize_t fuse_dev_splice_read(struct file *in, loff_t *ppos,
1202                                     struct pipe_inode_info *pipe,
1203                                     size_t len, unsigned int flags)
1204 {
1205         int ret;
1206         int page_nr = 0;
1207         int do_wakeup = 0;
1208         struct pipe_buffer *bufs;
1209         struct fuse_copy_state cs;
1210         struct fuse_conn *fc = fuse_get_conn(in);
1211         if (!fc)
1212                 return -EPERM;
1213
1214         bufs = kmalloc(pipe->buffers * sizeof(struct pipe_buffer), GFP_KERNEL);
1215         if (!bufs)
1216                 return -ENOMEM;
1217
1218         fuse_copy_init(&cs, fc, 1, NULL, 0);
1219         cs.pipebufs = bufs;
1220         cs.pipe = pipe;
1221         ret = fuse_dev_do_read(fc, in, &cs, len);
1222         if (ret < 0)
1223                 goto out;
1224
1225         ret = 0;
1226         pipe_lock(pipe);
1227
1228         if (!pipe->readers) {
1229                 send_sig(SIGPIPE, current, 0);
1230                 if (!ret)
1231                         ret = -EPIPE;
1232                 goto out_unlock;
1233         }
1234
1235         if (pipe->nrbufs + cs.nr_segs > pipe->buffers) {
1236                 ret = -EIO;
1237                 goto out_unlock;
1238         }
1239
1240         while (page_nr < cs.nr_segs) {
1241                 int newbuf = (pipe->curbuf + pipe->nrbufs) & (pipe->buffers - 1);
1242                 struct pipe_buffer *buf = pipe->bufs + newbuf;
1243
1244                 buf->page = bufs[page_nr].page;
1245                 buf->offset = bufs[page_nr].offset;
1246                 buf->len = bufs[page_nr].len;
1247                 /*
1248                  * Need to be careful about this.  Having buf->ops in module
1249                  * code can Oops if the buffer persists after module unload.
1250                  */
1251                 buf->ops = &nosteal_pipe_buf_ops;
1252
1253                 pipe->nrbufs++;
1254                 page_nr++;
1255                 ret += buf->len;
1256
1257                 if (pipe->inode)
1258                         do_wakeup = 1;
1259         }
1260
1261 out_unlock:
1262         pipe_unlock(pipe);
1263
1264         if (do_wakeup) {
1265                 smp_mb();
1266                 if (waitqueue_active(&pipe->wait))
1267                         wake_up_interruptible(&pipe->wait);
1268                 kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN);
1269         }
1270
1271 out:
1272         for (; page_nr < cs.nr_segs; page_nr++)
1273                 page_cache_release(bufs[page_nr].page);
1274
1275         kfree(bufs);
1276         return ret;
1277 }
1278
1279 static int fuse_notify_poll(struct fuse_conn *fc, unsigned int size,
1280                             struct fuse_copy_state *cs)
1281 {
1282         struct fuse_notify_poll_wakeup_out outarg;
1283         int err = -EINVAL;
1284
1285         if (size != sizeof(outarg))
1286                 goto err;
1287
1288         err = fuse_copy_one(cs, &outarg, sizeof(outarg));
1289         if (err)
1290                 goto err;
1291
1292         fuse_copy_finish(cs);
1293         return fuse_notify_poll_wakeup(fc, &outarg);
1294
1295 err:
1296         fuse_copy_finish(cs);
1297         return err;
1298 }
1299
1300 static int fuse_notify_inval_inode(struct fuse_conn *fc, unsigned int size,
1301                                    struct fuse_copy_state *cs)
1302 {
1303         struct fuse_notify_inval_inode_out outarg;
1304         int err = -EINVAL;
1305
1306         if (size != sizeof(outarg))
1307                 goto err;
1308
1309         err = fuse_copy_one(cs, &outarg, sizeof(outarg));
1310         if (err)
1311                 goto err;
1312         fuse_copy_finish(cs);
1313
1314         down_read(&fc->killsb);
1315         err = -ENOENT;
1316         if (fc->sb) {
1317                 err = fuse_reverse_inval_inode(fc->sb, outarg.ino,
1318                                                outarg.off, outarg.len);
1319         }
1320         up_read(&fc->killsb);
1321         return err;
1322
1323 err:
1324         fuse_copy_finish(cs);
1325         return err;
1326 }
1327
1328 static int fuse_notify_inval_entry(struct fuse_conn *fc, unsigned int size,
1329                                    struct fuse_copy_state *cs)
1330 {
1331         struct fuse_notify_inval_entry_out outarg;
1332         int err = -ENOMEM;
1333         char *buf;
1334         struct qstr name;
1335
1336         buf = kzalloc(FUSE_NAME_MAX + 1, GFP_KERNEL);
1337         if (!buf)
1338                 goto err;
1339
1340         err = -EINVAL;
1341         if (size < sizeof(outarg))
1342                 goto err;
1343
1344         err = fuse_copy_one(cs, &outarg, sizeof(outarg));
1345         if (err)
1346                 goto err;
1347
1348         err = -ENAMETOOLONG;
1349         if (outarg.namelen > FUSE_NAME_MAX)
1350                 goto err;
1351
1352         err = -EINVAL;
1353         if (size != sizeof(outarg) + outarg.namelen + 1)
1354                 goto err;
1355
1356         name.name = buf;
1357         name.len = outarg.namelen;
1358         err = fuse_copy_one(cs, buf, outarg.namelen + 1);
1359         if (err)
1360                 goto err;
1361         fuse_copy_finish(cs);
1362         buf[outarg.namelen] = 0;
1363         name.hash = full_name_hash(name.name, name.len);
1364
1365         down_read(&fc->killsb);
1366         err = -ENOENT;
1367         if (fc->sb)
1368                 err = fuse_reverse_inval_entry(fc->sb, outarg.parent, &name);
1369         up_read(&fc->killsb);
1370         kfree(buf);
1371         return err;
1372
1373 err:
1374         kfree(buf);
1375         fuse_copy_finish(cs);
1376         return err;
1377 }
1378
1379 static int fuse_notify_store(struct fuse_conn *fc, unsigned int size,
1380                              struct fuse_copy_state *cs)
1381 {
1382         struct fuse_notify_store_out outarg;
1383         struct inode *inode;
1384         struct address_space *mapping;
1385         u64 nodeid;
1386         int err;
1387         pgoff_t index;
1388         unsigned int offset;
1389         unsigned int num;
1390         loff_t file_size;
1391         loff_t end;
1392
1393         err = -EINVAL;
1394         if (size < sizeof(outarg))
1395                 goto out_finish;
1396
1397         err = fuse_copy_one(cs, &outarg, sizeof(outarg));
1398         if (err)
1399                 goto out_finish;
1400
1401         err = -EINVAL;
1402         if (size - sizeof(outarg) != outarg.size)
1403                 goto out_finish;
1404
1405         nodeid = outarg.nodeid;
1406
1407         down_read(&fc->killsb);
1408
1409         err = -ENOENT;
1410         if (!fc->sb)
1411                 goto out_up_killsb;
1412
1413         inode = ilookup5(fc->sb, nodeid, fuse_inode_eq, &nodeid);
1414         if (!inode)
1415                 goto out_up_killsb;
1416
1417         mapping = inode->i_mapping;
1418         index = outarg.offset >> PAGE_CACHE_SHIFT;
1419         offset = outarg.offset & ~PAGE_CACHE_MASK;
1420         file_size = i_size_read(inode);
1421         end = outarg.offset + outarg.size;
1422         if (end > file_size) {
1423                 file_size = end;
1424                 fuse_write_update_size(inode, file_size);
1425         }
1426
1427         num = outarg.size;
1428         while (num) {
1429                 struct page *page;
1430                 unsigned int this_num;
1431
1432                 err = -ENOMEM;
1433                 page = find_or_create_page(mapping, index,
1434                                            mapping_gfp_mask(mapping));
1435                 if (!page)
1436                         goto out_iput;
1437
1438                 this_num = min_t(unsigned, num, PAGE_CACHE_SIZE - offset);
1439                 err = fuse_copy_page(cs, &page, offset, this_num, 0);
1440                 if (!err && offset == 0 && (num != 0 || file_size == end))
1441                         SetPageUptodate(page);
1442                 unlock_page(page);
1443                 page_cache_release(page);
1444
1445                 if (err)
1446                         goto out_iput;
1447
1448                 num -= this_num;
1449                 offset = 0;
1450                 index++;
1451         }
1452
1453         err = 0;
1454
1455 out_iput:
1456         iput(inode);
1457 out_up_killsb:
1458         up_read(&fc->killsb);
1459 out_finish:
1460         fuse_copy_finish(cs);
1461         return err;
1462 }
1463
1464 static void fuse_retrieve_end(struct fuse_conn *fc, struct fuse_req *req)
1465 {
1466         release_pages(req->pages, req->num_pages, 0);
1467 }
1468
1469 static int fuse_retrieve(struct fuse_conn *fc, struct inode *inode,
1470                          struct fuse_notify_retrieve_out *outarg)
1471 {
1472         int err;
1473         struct address_space *mapping = inode->i_mapping;
1474         struct fuse_req *req;
1475         pgoff_t index;
1476         loff_t file_size;
1477         unsigned int num;
1478         unsigned int offset;
1479         size_t total_len = 0;
1480
1481         req = fuse_get_req(fc);
1482         if (IS_ERR(req))
1483                 return PTR_ERR(req);
1484
1485         offset = outarg->offset & ~PAGE_CACHE_MASK;
1486
1487         req->in.h.opcode = FUSE_NOTIFY_REPLY;
1488         req->in.h.nodeid = outarg->nodeid;
1489         req->in.numargs = 2;
1490         req->in.argpages = 1;
1491         req->page_offset = offset;
1492         req->end = fuse_retrieve_end;
1493
1494         index = outarg->offset >> PAGE_CACHE_SHIFT;
1495         file_size = i_size_read(inode);
1496         num = outarg->size;
1497         if (outarg->offset > file_size)
1498                 num = 0;
1499         else if (outarg->offset + num > file_size)
1500                 num = file_size - outarg->offset;
1501
1502         while (num && req->num_pages < FUSE_MAX_PAGES_PER_REQ) {
1503                 struct page *page;
1504                 unsigned int this_num;
1505
1506                 page = find_get_page(mapping, index);
1507                 if (!page)
1508                         break;
1509
1510                 this_num = min_t(unsigned, num, PAGE_CACHE_SIZE - offset);
1511                 req->pages[req->num_pages] = page;
1512                 req->num_pages++;
1513
1514                 offset = 0;
1515                 num -= this_num;
1516                 total_len += this_num;
1517                 index++;
1518         }
1519         req->misc.retrieve_in.offset = outarg->offset;
1520         req->misc.retrieve_in.size = total_len;
1521         req->in.args[0].size = sizeof(req->misc.retrieve_in);
1522         req->in.args[0].value = &req->misc.retrieve_in;
1523         req->in.args[1].size = total_len;
1524
1525         err = fuse_request_send_notify_reply(fc, req, outarg->notify_unique);
1526         if (err)
1527                 fuse_retrieve_end(fc, req);
1528
1529         return err;
1530 }
1531
1532 static int fuse_notify_retrieve(struct fuse_conn *fc, unsigned int size,
1533                                 struct fuse_copy_state *cs)
1534 {
1535         struct fuse_notify_retrieve_out outarg;
1536         struct inode *inode;
1537         int err;
1538
1539         err = -EINVAL;
1540         if (size != sizeof(outarg))
1541                 goto copy_finish;
1542
1543         err = fuse_copy_one(cs, &outarg, sizeof(outarg));
1544         if (err)
1545                 goto copy_finish;
1546
1547         fuse_copy_finish(cs);
1548
1549         down_read(&fc->killsb);
1550         err = -ENOENT;
1551         if (fc->sb) {
1552                 u64 nodeid = outarg.nodeid;
1553
1554                 inode = ilookup5(fc->sb, nodeid, fuse_inode_eq, &nodeid);
1555                 if (inode) {
1556                         err = fuse_retrieve(fc, inode, &outarg);
1557                         iput(inode);
1558                 }
1559         }
1560         up_read(&fc->killsb);
1561
1562         return err;
1563
1564 copy_finish:
1565         fuse_copy_finish(cs);
1566         return err;
1567 }
1568
1569 static int fuse_notify(struct fuse_conn *fc, enum fuse_notify_code code,
1570                        unsigned int size, struct fuse_copy_state *cs)
1571 {
1572         /* Don't try to move pages (yet) */
1573         cs->move_pages = 0;
1574
1575         switch (code) {
1576         case FUSE_NOTIFY_POLL:
1577                 return fuse_notify_poll(fc, size, cs);
1578
1579         case FUSE_NOTIFY_INVAL_INODE:
1580                 return fuse_notify_inval_inode(fc, size, cs);
1581
1582         case FUSE_NOTIFY_INVAL_ENTRY:
1583                 return fuse_notify_inval_entry(fc, size, cs);
1584
1585         case FUSE_NOTIFY_STORE:
1586                 return fuse_notify_store(fc, size, cs);
1587
1588         case FUSE_NOTIFY_RETRIEVE:
1589                 return fuse_notify_retrieve(fc, size, cs);
1590
1591         default:
1592                 fuse_copy_finish(cs);
1593                 return -EINVAL;
1594         }
1595 }
1596
1597 /* Look up request on processing list by unique ID */
1598 static struct fuse_req *request_find(struct fuse_conn *fc, u64 unique)
1599 {
1600         struct list_head *entry;
1601
1602         list_for_each(entry, &fc->processing) {
1603                 struct fuse_req *req;
1604                 req = list_entry(entry, struct fuse_req, list);
1605                 if (req->in.h.unique == unique || req->intr_unique == unique)
1606                         return req;
1607         }
1608         return NULL;
1609 }
1610
1611 static int copy_out_args(struct fuse_copy_state *cs, struct fuse_out *out,
1612                          unsigned nbytes)
1613 {
1614         unsigned reqsize = sizeof(struct fuse_out_header);
1615
1616         if (out->h.error)
1617                 return nbytes != reqsize ? -EINVAL : 0;
1618
1619         reqsize += len_args(out->numargs, out->args);
1620
1621         if (reqsize < nbytes || (reqsize > nbytes && !out->argvar))
1622                 return -EINVAL;
1623         else if (reqsize > nbytes) {
1624                 struct fuse_arg *lastarg = &out->args[out->numargs-1];
1625                 unsigned diffsize = reqsize - nbytes;
1626                 if (diffsize > lastarg->size)
1627                         return -EINVAL;
1628                 lastarg->size -= diffsize;
1629         }
1630         return fuse_copy_args(cs, out->numargs, out->argpages, out->args,
1631                               out->page_zeroing);
1632 }
1633
1634 /*
1635  * Write a single reply to a request.  First the header is copied from
1636  * the write buffer.  The request is then searched on the processing
1637  * list by the unique ID found in the header.  If found, then remove
1638  * it from the list and copy the rest of the buffer to the request.
1639  * The request is finished by calling request_end()
1640  */
1641 static ssize_t fuse_dev_do_write(struct fuse_conn *fc,
1642                                  struct fuse_copy_state *cs, size_t nbytes)
1643 {
1644         int err;
1645         struct fuse_req *req;
1646         struct fuse_out_header oh;
1647
1648         if (nbytes < sizeof(struct fuse_out_header))
1649                 return -EINVAL;
1650
1651         err = fuse_copy_one(cs, &oh, sizeof(oh));
1652         if (err)
1653                 goto err_finish;
1654
1655         err = -EINVAL;
1656         if (oh.len != nbytes)
1657                 goto err_finish;
1658
1659         /*
1660          * Zero oh.unique indicates unsolicited notification message
1661          * and error contains notification code.
1662          */
1663         if (!oh.unique) {
1664                 err = fuse_notify(fc, oh.error, nbytes - sizeof(oh), cs);
1665                 return err ? err : nbytes;
1666         }
1667
1668         err = -EINVAL;
1669         if (oh.error <= -1000 || oh.error > 0)
1670                 goto err_finish;
1671
1672         spin_lock(&fc->lock);
1673         err = -ENOENT;
1674         if (!fc->connected)
1675                 goto err_unlock;
1676
1677         req = request_find(fc, oh.unique);
1678         if (!req)
1679                 goto err_unlock;
1680
1681         if (req->aborted) {
1682                 spin_unlock(&fc->lock);
1683                 fuse_copy_finish(cs);
1684                 spin_lock(&fc->lock);
1685                 request_end(fc, req);
1686                 return -ENOENT;
1687         }
1688         /* Is it an interrupt reply? */
1689         if (req->intr_unique == oh.unique) {
1690                 err = -EINVAL;
1691                 if (nbytes != sizeof(struct fuse_out_header))
1692                         goto err_unlock;
1693
1694                 if (oh.error == -ENOSYS)
1695                         fc->no_interrupt = 1;
1696                 else if (oh.error == -EAGAIN)
1697                         queue_interrupt(fc, req);
1698
1699                 spin_unlock(&fc->lock);
1700                 fuse_copy_finish(cs);
1701                 return nbytes;
1702         }
1703
1704         req->state = FUSE_REQ_WRITING;
1705         list_move(&req->list, &fc->io);
1706         req->out.h = oh;
1707         req->locked = 1;
1708         cs->req = req;
1709         if (!req->out.page_replace)
1710                 cs->move_pages = 0;
1711         spin_unlock(&fc->lock);
1712
1713         err = copy_out_args(cs, &req->out, nbytes);
1714         fuse_copy_finish(cs);
1715
1716         spin_lock(&fc->lock);
1717         req->locked = 0;
1718         if (!err) {
1719                 if (req->aborted)
1720                         err = -ENOENT;
1721         } else if (!req->aborted)
1722                 req->out.h.error = -EIO;
1723         request_end(fc, req);
1724
1725         return err ? err : nbytes;
1726
1727  err_unlock:
1728         spin_unlock(&fc->lock);
1729  err_finish:
1730         fuse_copy_finish(cs);
1731         return err;
1732 }
1733
1734 static ssize_t fuse_dev_write(struct kiocb *iocb, const struct iovec *iov,
1735                               unsigned long nr_segs, loff_t pos)
1736 {
1737         struct fuse_copy_state cs;
1738         struct fuse_conn *fc = fuse_get_conn(iocb->ki_filp);
1739         if (!fc)
1740                 return -EPERM;
1741
1742         fuse_copy_init(&cs, fc, 0, iov, nr_segs);
1743
1744         return fuse_dev_do_write(fc, &cs, iov_length(iov, nr_segs));
1745 }
1746
1747 static ssize_t fuse_dev_splice_write(struct pipe_inode_info *pipe,
1748                                      struct file *out, loff_t *ppos,
1749                                      size_t len, unsigned int flags)
1750 {
1751         unsigned nbuf;
1752         unsigned idx;
1753         struct pipe_buffer *bufs;
1754         struct fuse_copy_state cs;
1755         struct fuse_conn *fc;
1756         size_t rem;
1757         ssize_t ret;
1758
1759         fc = fuse_get_conn(out);
1760         if (!fc)
1761                 return -EPERM;
1762
1763         bufs = kmalloc(pipe->buffers * sizeof(struct pipe_buffer), GFP_KERNEL);
1764         if (!bufs)
1765                 return -ENOMEM;
1766
1767         pipe_lock(pipe);
1768         nbuf = 0;
1769         rem = 0;
1770         for (idx = 0; idx < pipe->nrbufs && rem < len; idx++)
1771                 rem += pipe->bufs[(pipe->curbuf + idx) & (pipe->buffers - 1)].len;
1772
1773         ret = -EINVAL;
1774         if (rem < len) {
1775                 pipe_unlock(pipe);
1776                 goto out;
1777         }
1778
1779         rem = len;
1780         while (rem) {
1781                 struct pipe_buffer *ibuf;
1782                 struct pipe_buffer *obuf;
1783
1784                 BUG_ON(nbuf >= pipe->buffers);
1785                 BUG_ON(!pipe->nrbufs);
1786                 ibuf = &pipe->bufs[pipe->curbuf];
1787                 obuf = &bufs[nbuf];
1788
1789                 if (rem >= ibuf->len) {
1790                         *obuf = *ibuf;
1791                         ibuf->ops = NULL;
1792                         pipe->curbuf = (pipe->curbuf + 1) & (pipe->buffers - 1);
1793                         pipe->nrbufs--;
1794                 } else {
1795                         ibuf->ops->get(pipe, ibuf);
1796                         *obuf = *ibuf;
1797                         obuf->flags &= ~PIPE_BUF_FLAG_GIFT;
1798                         obuf->len = rem;
1799                         ibuf->offset += obuf->len;
1800                         ibuf->len -= obuf->len;
1801                 }
1802                 nbuf++;
1803                 rem -= obuf->len;
1804         }
1805         pipe_unlock(pipe);
1806
1807         fuse_copy_init(&cs, fc, 0, NULL, nbuf);
1808         cs.pipebufs = bufs;
1809         cs.pipe = pipe;
1810
1811         if (flags & SPLICE_F_MOVE)
1812                 cs.move_pages = 1;
1813
1814         ret = fuse_dev_do_write(fc, &cs, len);
1815
1816         for (idx = 0; idx < nbuf; idx++) {
1817                 struct pipe_buffer *buf = &bufs[idx];
1818                 buf->ops->release(pipe, buf);
1819         }
1820 out:
1821         kfree(bufs);
1822         return ret;
1823 }
1824
1825 static unsigned fuse_dev_poll(struct file *file, poll_table *wait)
1826 {
1827         unsigned mask = POLLOUT | POLLWRNORM;
1828         struct fuse_conn *fc = fuse_get_conn(file);
1829         if (!fc)
1830                 return POLLERR;
1831
1832         poll_wait(file, &fc->waitq, wait);
1833
1834         spin_lock(&fc->lock);
1835         if (!fc->connected)
1836                 mask = POLLERR;
1837         else if (request_pending(fc))
1838                 mask |= POLLIN | POLLRDNORM;
1839         spin_unlock(&fc->lock);
1840
1841         return mask;
1842 }
1843
1844 /*
1845  * Abort all requests on the given list (pending or processing)
1846  *
1847  * This function releases and reacquires fc->lock
1848  */
1849 static void end_requests(struct fuse_conn *fc, struct list_head *head)
1850 __releases(fc->lock)
1851 __acquires(fc->lock)
1852 {
1853         while (!list_empty(head)) {
1854                 struct fuse_req *req;
1855                 req = list_entry(head->next, struct fuse_req, list);
1856                 req->out.h.error = -ECONNABORTED;
1857                 request_end(fc, req);
1858                 spin_lock(&fc->lock);
1859         }
1860 }
1861
1862 /*
1863  * Abort requests under I/O
1864  *
1865  * The requests are set to aborted and finished, and the request
1866  * waiter is woken up.  This will make request_wait_answer() wait
1867  * until the request is unlocked and then return.
1868  *
1869  * If the request is asynchronous, then the end function needs to be
1870  * called after waiting for the request to be unlocked (if it was
1871  * locked).
1872  */
1873 static void end_io_requests(struct fuse_conn *fc)
1874 __releases(fc->lock)
1875 __acquires(fc->lock)
1876 {
1877         while (!list_empty(&fc->io)) {
1878                 struct fuse_req *req =
1879                         list_entry(fc->io.next, struct fuse_req, list);
1880                 void (*end) (struct fuse_conn *, struct fuse_req *) = req->end;
1881
1882                 req->aborted = 1;
1883                 req->out.h.error = -ECONNABORTED;
1884                 req->state = FUSE_REQ_FINISHED;
1885                 list_del_init(&req->list);
1886                 wake_up(&req->waitq);
1887                 if (end) {
1888                         req->end = NULL;
1889                         __fuse_get_request(req);
1890                         spin_unlock(&fc->lock);
1891                         wait_event(req->waitq, !req->locked);
1892                         end(fc, req);
1893                         fuse_put_request(fc, req);
1894                         spin_lock(&fc->lock);
1895                 }
1896         }
1897 }
1898
1899 static void end_queued_requests(struct fuse_conn *fc)
1900 __releases(fc->lock)
1901 __acquires(fc->lock)
1902 {
1903         fc->max_background = UINT_MAX;
1904         flush_bg_queue(fc);
1905         end_requests(fc, &fc->pending);
1906         end_requests(fc, &fc->processing);
1907         while (forget_pending(fc))
1908                 kfree(dequeue_forget(fc, 1, NULL));
1909 }
1910
1911 static void end_polls(struct fuse_conn *fc)
1912 {
1913         struct rb_node *p;
1914
1915         p = rb_first(&fc->polled_files);
1916
1917         while (p) {
1918                 struct fuse_file *ff;
1919                 ff = rb_entry(p, struct fuse_file, polled_node);
1920                 wake_up_interruptible_all(&ff->poll_wait);
1921
1922                 p = rb_next(p);
1923         }
1924 }
1925
1926 /*
1927  * Abort all requests.
1928  *
1929  * Emergency exit in case of a malicious or accidental deadlock, or
1930  * just a hung filesystem.
1931  *
1932  * The same effect is usually achievable through killing the
1933  * filesystem daemon and all users of the filesystem.  The exception
1934  * is the combination of an asynchronous request and the tricky
1935  * deadlock (see Documentation/filesystems/fuse.txt).
1936  *
1937  * During the aborting, progression of requests from the pending and
1938  * processing lists onto the io list, and progression of new requests
1939  * onto the pending list is prevented by req->connected being false.
1940  *
1941  * Progression of requests under I/O to the processing list is
1942  * prevented by the req->aborted flag being true for these requests.
1943  * For this reason requests on the io list must be aborted first.
1944  */
1945 void fuse_abort_conn(struct fuse_conn *fc)
1946 {
1947         spin_lock(&fc->lock);
1948         if (fc->connected) {
1949                 fc->connected = 0;
1950                 fc->blocked = 0;
1951                 end_io_requests(fc);
1952                 end_queued_requests(fc);
1953                 end_polls(fc);
1954                 wake_up_all(&fc->waitq);
1955                 wake_up_all(&fc->blocked_waitq);
1956                 kill_fasync(&fc->fasync, SIGIO, POLL_IN);
1957         }
1958         spin_unlock(&fc->lock);
1959 }
1960 EXPORT_SYMBOL_GPL(fuse_abort_conn);
1961
1962 int fuse_dev_release(struct inode *inode, struct file *file)
1963 {
1964         struct fuse_conn *fc = fuse_get_conn(file);
1965         if (fc) {
1966                 spin_lock(&fc->lock);
1967                 fc->connected = 0;
1968                 fc->blocked = 0;
1969                 end_queued_requests(fc);
1970                 end_polls(fc);
1971                 wake_up_all(&fc->blocked_waitq);
1972                 spin_unlock(&fc->lock);
1973                 fuse_conn_put(fc);
1974         }
1975
1976         return 0;
1977 }
1978 EXPORT_SYMBOL_GPL(fuse_dev_release);
1979
1980 static int fuse_dev_fasync(int fd, struct file *file, int on)
1981 {
1982         struct fuse_conn *fc = fuse_get_conn(file);
1983         if (!fc)
1984                 return -EPERM;
1985
1986         /* No locking - fasync_helper does its own locking */
1987         return fasync_helper(fd, file, on, &fc->fasync);
1988 }
1989
1990 const struct file_operations fuse_dev_operations = {
1991         .owner          = THIS_MODULE,
1992         .llseek         = no_llseek,
1993         .read           = do_sync_read,
1994         .aio_read       = fuse_dev_read,
1995         .splice_read    = fuse_dev_splice_read,
1996         .write          = do_sync_write,
1997         .aio_write      = fuse_dev_write,
1998         .splice_write   = fuse_dev_splice_write,
1999         .poll           = fuse_dev_poll,
2000         .release        = fuse_dev_release,
2001         .fasync         = fuse_dev_fasync,
2002 };
2003 EXPORT_SYMBOL_GPL(fuse_dev_operations);
2004
2005 static struct miscdevice fuse_miscdevice = {
2006         .minor = FUSE_MINOR,
2007         .name  = "fuse",
2008         .fops = &fuse_dev_operations,
2009 };
2010
2011 int __init fuse_dev_init(void)
2012 {
2013         int err = -ENOMEM;
2014         fuse_req_cachep = kmem_cache_create("fuse_request",
2015                                             sizeof(struct fuse_req),
2016                                             0, 0, NULL);
2017         if (!fuse_req_cachep)
2018                 goto out;
2019
2020         err = misc_register(&fuse_miscdevice);
2021         if (err)
2022                 goto out_cache_clean;
2023
2024         return 0;
2025
2026  out_cache_clean:
2027         kmem_cache_destroy(fuse_req_cachep);
2028  out:
2029         return err;
2030 }
2031
2032 void fuse_dev_cleanup(void)
2033 {
2034         misc_deregister(&fuse_miscdevice);
2035         kmem_cache_destroy(fuse_req_cachep);
2036 }