Merge branch 'for-linus' of git://git.kernel.org/pub/scm/linux/kernel/git/mszeredi...
[linux-2.6-block.git] / fs / fuse / file.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/pagemap.h>
12 #include <linux/slab.h>
13 #include <linux/kernel.h>
14 #include <linux/sched.h>
15 #include <linux/module.h>
16 #include <linux/compat.h>
17 #include <linux/swap.h>
18
19 static const struct file_operations fuse_direct_io_file_operations;
20
21 static int fuse_send_open(struct fuse_conn *fc, u64 nodeid, struct file *file,
22                           int opcode, struct fuse_open_out *outargp)
23 {
24         struct fuse_open_in inarg;
25         struct fuse_req *req;
26         int err;
27
28         req = fuse_get_req_nopages(fc);
29         if (IS_ERR(req))
30                 return PTR_ERR(req);
31
32         memset(&inarg, 0, sizeof(inarg));
33         inarg.flags = file->f_flags & ~(O_CREAT | O_EXCL | O_NOCTTY);
34         if (!fc->atomic_o_trunc)
35                 inarg.flags &= ~O_TRUNC;
36         req->in.h.opcode = opcode;
37         req->in.h.nodeid = nodeid;
38         req->in.numargs = 1;
39         req->in.args[0].size = sizeof(inarg);
40         req->in.args[0].value = &inarg;
41         req->out.numargs = 1;
42         req->out.args[0].size = sizeof(*outargp);
43         req->out.args[0].value = outargp;
44         fuse_request_send(fc, req);
45         err = req->out.h.error;
46         fuse_put_request(fc, req);
47
48         return err;
49 }
50
51 struct fuse_file *fuse_file_alloc(struct fuse_conn *fc)
52 {
53         struct fuse_file *ff;
54
55         ff = kmalloc(sizeof(struct fuse_file), GFP_KERNEL);
56         if (unlikely(!ff))
57                 return NULL;
58
59         ff->fc = fc;
60         ff->reserved_req = fuse_request_alloc(0);
61         if (unlikely(!ff->reserved_req)) {
62                 kfree(ff);
63                 return NULL;
64         }
65
66         INIT_LIST_HEAD(&ff->write_entry);
67         atomic_set(&ff->count, 0);
68         RB_CLEAR_NODE(&ff->polled_node);
69         init_waitqueue_head(&ff->poll_wait);
70
71         spin_lock(&fc->lock);
72         ff->kh = ++fc->khctr;
73         spin_unlock(&fc->lock);
74
75         return ff;
76 }
77
78 void fuse_file_free(struct fuse_file *ff)
79 {
80         fuse_request_free(ff->reserved_req);
81         kfree(ff);
82 }
83
84 struct fuse_file *fuse_file_get(struct fuse_file *ff)
85 {
86         atomic_inc(&ff->count);
87         return ff;
88 }
89
90 static void fuse_release_async(struct work_struct *work)
91 {
92         struct fuse_req *req;
93         struct fuse_conn *fc;
94         struct path path;
95
96         req = container_of(work, struct fuse_req, misc.release.work);
97         path = req->misc.release.path;
98         fc = get_fuse_conn(path.dentry->d_inode);
99
100         fuse_put_request(fc, req);
101         path_put(&path);
102 }
103
104 static void fuse_release_end(struct fuse_conn *fc, struct fuse_req *req)
105 {
106         if (fc->destroy_req) {
107                 /*
108                  * If this is a fuseblk mount, then it's possible that
109                  * releasing the path will result in releasing the
110                  * super block and sending the DESTROY request.  If
111                  * the server is single threaded, this would hang.
112                  * For this reason do the path_put() in a separate
113                  * thread.
114                  */
115                 atomic_inc(&req->count);
116                 INIT_WORK(&req->misc.release.work, fuse_release_async);
117                 schedule_work(&req->misc.release.work);
118         } else {
119                 path_put(&req->misc.release.path);
120         }
121 }
122
123 static void fuse_file_put(struct fuse_file *ff, bool sync)
124 {
125         if (atomic_dec_and_test(&ff->count)) {
126                 struct fuse_req *req = ff->reserved_req;
127
128                 if (sync) {
129                         req->background = 0;
130                         fuse_request_send(ff->fc, req);
131                         path_put(&req->misc.release.path);
132                         fuse_put_request(ff->fc, req);
133                 } else {
134                         req->end = fuse_release_end;
135                         req->background = 1;
136                         fuse_request_send_background(ff->fc, req);
137                 }
138                 kfree(ff);
139         }
140 }
141
142 int fuse_do_open(struct fuse_conn *fc, u64 nodeid, struct file *file,
143                  bool isdir)
144 {
145         struct fuse_open_out outarg;
146         struct fuse_file *ff;
147         int err;
148         int opcode = isdir ? FUSE_OPENDIR : FUSE_OPEN;
149
150         ff = fuse_file_alloc(fc);
151         if (!ff)
152                 return -ENOMEM;
153
154         err = fuse_send_open(fc, nodeid, file, opcode, &outarg);
155         if (err) {
156                 fuse_file_free(ff);
157                 return err;
158         }
159
160         if (isdir)
161                 outarg.open_flags &= ~FOPEN_DIRECT_IO;
162
163         ff->fh = outarg.fh;
164         ff->nodeid = nodeid;
165         ff->open_flags = outarg.open_flags;
166         file->private_data = fuse_file_get(ff);
167
168         return 0;
169 }
170 EXPORT_SYMBOL_GPL(fuse_do_open);
171
172 void fuse_finish_open(struct inode *inode, struct file *file)
173 {
174         struct fuse_file *ff = file->private_data;
175         struct fuse_conn *fc = get_fuse_conn(inode);
176
177         if (ff->open_flags & FOPEN_DIRECT_IO)
178                 file->f_op = &fuse_direct_io_file_operations;
179         if (!(ff->open_flags & FOPEN_KEEP_CACHE))
180                 invalidate_inode_pages2(inode->i_mapping);
181         if (ff->open_flags & FOPEN_NONSEEKABLE)
182                 nonseekable_open(inode, file);
183         if (fc->atomic_o_trunc && (file->f_flags & O_TRUNC)) {
184                 struct fuse_inode *fi = get_fuse_inode(inode);
185
186                 spin_lock(&fc->lock);
187                 fi->attr_version = ++fc->attr_version;
188                 i_size_write(inode, 0);
189                 spin_unlock(&fc->lock);
190                 fuse_invalidate_attr(inode);
191         }
192 }
193
194 int fuse_open_common(struct inode *inode, struct file *file, bool isdir)
195 {
196         struct fuse_conn *fc = get_fuse_conn(inode);
197         int err;
198
199         err = generic_file_open(inode, file);
200         if (err)
201                 return err;
202
203         err = fuse_do_open(fc, get_node_id(inode), file, isdir);
204         if (err)
205                 return err;
206
207         fuse_finish_open(inode, file);
208
209         return 0;
210 }
211
212 static void fuse_prepare_release(struct fuse_file *ff, int flags, int opcode)
213 {
214         struct fuse_conn *fc = ff->fc;
215         struct fuse_req *req = ff->reserved_req;
216         struct fuse_release_in *inarg = &req->misc.release.in;
217
218         spin_lock(&fc->lock);
219         list_del(&ff->write_entry);
220         if (!RB_EMPTY_NODE(&ff->polled_node))
221                 rb_erase(&ff->polled_node, &fc->polled_files);
222         spin_unlock(&fc->lock);
223
224         wake_up_interruptible_all(&ff->poll_wait);
225
226         inarg->fh = ff->fh;
227         inarg->flags = flags;
228         req->in.h.opcode = opcode;
229         req->in.h.nodeid = ff->nodeid;
230         req->in.numargs = 1;
231         req->in.args[0].size = sizeof(struct fuse_release_in);
232         req->in.args[0].value = inarg;
233 }
234
235 void fuse_release_common(struct file *file, int opcode)
236 {
237         struct fuse_file *ff;
238         struct fuse_req *req;
239
240         ff = file->private_data;
241         if (unlikely(!ff))
242                 return;
243
244         req = ff->reserved_req;
245         fuse_prepare_release(ff, file->f_flags, opcode);
246
247         if (ff->flock) {
248                 struct fuse_release_in *inarg = &req->misc.release.in;
249                 inarg->release_flags |= FUSE_RELEASE_FLOCK_UNLOCK;
250                 inarg->lock_owner = fuse_lock_owner_id(ff->fc,
251                                                        (fl_owner_t) file);
252         }
253         /* Hold vfsmount and dentry until release is finished */
254         path_get(&file->f_path);
255         req->misc.release.path = file->f_path;
256
257         /*
258          * Normally this will send the RELEASE request, however if
259          * some asynchronous READ or WRITE requests are outstanding,
260          * the sending will be delayed.
261          *
262          * Make the release synchronous if this is a fuseblk mount,
263          * synchronous RELEASE is allowed (and desirable) in this case
264          * because the server can be trusted not to screw up.
265          */
266         fuse_file_put(ff, ff->fc->destroy_req != NULL);
267 }
268
269 static int fuse_open(struct inode *inode, struct file *file)
270 {
271         return fuse_open_common(inode, file, false);
272 }
273
274 static int fuse_release(struct inode *inode, struct file *file)
275 {
276         fuse_release_common(file, FUSE_RELEASE);
277
278         /* return value is ignored by VFS */
279         return 0;
280 }
281
282 void fuse_sync_release(struct fuse_file *ff, int flags)
283 {
284         WARN_ON(atomic_read(&ff->count) > 1);
285         fuse_prepare_release(ff, flags, FUSE_RELEASE);
286         ff->reserved_req->force = 1;
287         ff->reserved_req->background = 0;
288         fuse_request_send(ff->fc, ff->reserved_req);
289         fuse_put_request(ff->fc, ff->reserved_req);
290         kfree(ff);
291 }
292 EXPORT_SYMBOL_GPL(fuse_sync_release);
293
294 /*
295  * Scramble the ID space with XTEA, so that the value of the files_struct
296  * pointer is not exposed to userspace.
297  */
298 u64 fuse_lock_owner_id(struct fuse_conn *fc, fl_owner_t id)
299 {
300         u32 *k = fc->scramble_key;
301         u64 v = (unsigned long) id;
302         u32 v0 = v;
303         u32 v1 = v >> 32;
304         u32 sum = 0;
305         int i;
306
307         for (i = 0; i < 32; i++) {
308                 v0 += ((v1 << 4 ^ v1 >> 5) + v1) ^ (sum + k[sum & 3]);
309                 sum += 0x9E3779B9;
310                 v1 += ((v0 << 4 ^ v0 >> 5) + v0) ^ (sum + k[sum>>11 & 3]);
311         }
312
313         return (u64) v0 + ((u64) v1 << 32);
314 }
315
316 /*
317  * Check if page is under writeback
318  *
319  * This is currently done by walking the list of writepage requests
320  * for the inode, which can be pretty inefficient.
321  */
322 static bool fuse_page_is_writeback(struct inode *inode, pgoff_t index)
323 {
324         struct fuse_conn *fc = get_fuse_conn(inode);
325         struct fuse_inode *fi = get_fuse_inode(inode);
326         struct fuse_req *req;
327         bool found = false;
328
329         spin_lock(&fc->lock);
330         list_for_each_entry(req, &fi->writepages, writepages_entry) {
331                 pgoff_t curr_index;
332
333                 BUG_ON(req->inode != inode);
334                 curr_index = req->misc.write.in.offset >> PAGE_CACHE_SHIFT;
335                 if (curr_index == index) {
336                         found = true;
337                         break;
338                 }
339         }
340         spin_unlock(&fc->lock);
341
342         return found;
343 }
344
345 /*
346  * Wait for page writeback to be completed.
347  *
348  * Since fuse doesn't rely on the VM writeback tracking, this has to
349  * use some other means.
350  */
351 static int fuse_wait_on_page_writeback(struct inode *inode, pgoff_t index)
352 {
353         struct fuse_inode *fi = get_fuse_inode(inode);
354
355         wait_event(fi->page_waitq, !fuse_page_is_writeback(inode, index));
356         return 0;
357 }
358
359 static int fuse_flush(struct file *file, fl_owner_t id)
360 {
361         struct inode *inode = file_inode(file);
362         struct fuse_conn *fc = get_fuse_conn(inode);
363         struct fuse_file *ff = file->private_data;
364         struct fuse_req *req;
365         struct fuse_flush_in inarg;
366         int err;
367
368         if (is_bad_inode(inode))
369                 return -EIO;
370
371         if (fc->no_flush)
372                 return 0;
373
374         req = fuse_get_req_nofail_nopages(fc, file);
375         memset(&inarg, 0, sizeof(inarg));
376         inarg.fh = ff->fh;
377         inarg.lock_owner = fuse_lock_owner_id(fc, id);
378         req->in.h.opcode = FUSE_FLUSH;
379         req->in.h.nodeid = get_node_id(inode);
380         req->in.numargs = 1;
381         req->in.args[0].size = sizeof(inarg);
382         req->in.args[0].value = &inarg;
383         req->force = 1;
384         fuse_request_send(fc, req);
385         err = req->out.h.error;
386         fuse_put_request(fc, req);
387         if (err == -ENOSYS) {
388                 fc->no_flush = 1;
389                 err = 0;
390         }
391         return err;
392 }
393
394 /*
395  * Wait for all pending writepages on the inode to finish.
396  *
397  * This is currently done by blocking further writes with FUSE_NOWRITE
398  * and waiting for all sent writes to complete.
399  *
400  * This must be called under i_mutex, otherwise the FUSE_NOWRITE usage
401  * could conflict with truncation.
402  */
403 static void fuse_sync_writes(struct inode *inode)
404 {
405         fuse_set_nowrite(inode);
406         fuse_release_nowrite(inode);
407 }
408
409 int fuse_fsync_common(struct file *file, loff_t start, loff_t end,
410                       int datasync, int isdir)
411 {
412         struct inode *inode = file->f_mapping->host;
413         struct fuse_conn *fc = get_fuse_conn(inode);
414         struct fuse_file *ff = file->private_data;
415         struct fuse_req *req;
416         struct fuse_fsync_in inarg;
417         int err;
418
419         if (is_bad_inode(inode))
420                 return -EIO;
421
422         err = filemap_write_and_wait_range(inode->i_mapping, start, end);
423         if (err)
424                 return err;
425
426         if ((!isdir && fc->no_fsync) || (isdir && fc->no_fsyncdir))
427                 return 0;
428
429         mutex_lock(&inode->i_mutex);
430
431         /*
432          * Start writeback against all dirty pages of the inode, then
433          * wait for all outstanding writes, before sending the FSYNC
434          * request.
435          */
436         err = write_inode_now(inode, 0);
437         if (err)
438                 goto out;
439
440         fuse_sync_writes(inode);
441
442         req = fuse_get_req_nopages(fc);
443         if (IS_ERR(req)) {
444                 err = PTR_ERR(req);
445                 goto out;
446         }
447
448         memset(&inarg, 0, sizeof(inarg));
449         inarg.fh = ff->fh;
450         inarg.fsync_flags = datasync ? 1 : 0;
451         req->in.h.opcode = isdir ? FUSE_FSYNCDIR : FUSE_FSYNC;
452         req->in.h.nodeid = get_node_id(inode);
453         req->in.numargs = 1;
454         req->in.args[0].size = sizeof(inarg);
455         req->in.args[0].value = &inarg;
456         fuse_request_send(fc, req);
457         err = req->out.h.error;
458         fuse_put_request(fc, req);
459         if (err == -ENOSYS) {
460                 if (isdir)
461                         fc->no_fsyncdir = 1;
462                 else
463                         fc->no_fsync = 1;
464                 err = 0;
465         }
466 out:
467         mutex_unlock(&inode->i_mutex);
468         return err;
469 }
470
471 static int fuse_fsync(struct file *file, loff_t start, loff_t end,
472                       int datasync)
473 {
474         return fuse_fsync_common(file, start, end, datasync, 0);
475 }
476
477 void fuse_read_fill(struct fuse_req *req, struct file *file, loff_t pos,
478                     size_t count, int opcode)
479 {
480         struct fuse_read_in *inarg = &req->misc.read.in;
481         struct fuse_file *ff = file->private_data;
482
483         inarg->fh = ff->fh;
484         inarg->offset = pos;
485         inarg->size = count;
486         inarg->flags = file->f_flags;
487         req->in.h.opcode = opcode;
488         req->in.h.nodeid = ff->nodeid;
489         req->in.numargs = 1;
490         req->in.args[0].size = sizeof(struct fuse_read_in);
491         req->in.args[0].value = inarg;
492         req->out.argvar = 1;
493         req->out.numargs = 1;
494         req->out.args[0].size = count;
495 }
496
497 static void fuse_release_user_pages(struct fuse_req *req, int write)
498 {
499         unsigned i;
500
501         for (i = 0; i < req->num_pages; i++) {
502                 struct page *page = req->pages[i];
503                 if (write)
504                         set_page_dirty_lock(page);
505                 put_page(page);
506         }
507 }
508
509 /**
510  * In case of short read, the caller sets 'pos' to the position of
511  * actual end of fuse request in IO request. Otherwise, if bytes_requested
512  * == bytes_transferred or rw == WRITE, the caller sets 'pos' to -1.
513  *
514  * An example:
515  * User requested DIO read of 64K. It was splitted into two 32K fuse requests,
516  * both submitted asynchronously. The first of them was ACKed by userspace as
517  * fully completed (req->out.args[0].size == 32K) resulting in pos == -1. The
518  * second request was ACKed as short, e.g. only 1K was read, resulting in
519  * pos == 33K.
520  *
521  * Thus, when all fuse requests are completed, the minimal non-negative 'pos'
522  * will be equal to the length of the longest contiguous fragment of
523  * transferred data starting from the beginning of IO request.
524  */
525 static void fuse_aio_complete(struct fuse_io_priv *io, int err, ssize_t pos)
526 {
527         int left;
528
529         spin_lock(&io->lock);
530         if (err)
531                 io->err = io->err ? : err;
532         else if (pos >= 0 && (io->bytes < 0 || pos < io->bytes))
533                 io->bytes = pos;
534
535         left = --io->reqs;
536         spin_unlock(&io->lock);
537
538         if (!left) {
539                 long res;
540
541                 if (io->err)
542                         res = io->err;
543                 else if (io->bytes >= 0 && io->write)
544                         res = -EIO;
545                 else {
546                         res = io->bytes < 0 ? io->size : io->bytes;
547
548                         if (!is_sync_kiocb(io->iocb)) {
549                                 struct path *path = &io->iocb->ki_filp->f_path;
550                                 struct inode *inode = path->dentry->d_inode;
551                                 struct fuse_conn *fc = get_fuse_conn(inode);
552                                 struct fuse_inode *fi = get_fuse_inode(inode);
553
554                                 spin_lock(&fc->lock);
555                                 fi->attr_version = ++fc->attr_version;
556                                 spin_unlock(&fc->lock);
557                         }
558                 }
559
560                 aio_complete(io->iocb, res, 0);
561                 kfree(io);
562         }
563 }
564
565 static void fuse_aio_complete_req(struct fuse_conn *fc, struct fuse_req *req)
566 {
567         struct fuse_io_priv *io = req->io;
568         ssize_t pos = -1;
569
570         fuse_release_user_pages(req, !io->write);
571
572         if (io->write) {
573                 if (req->misc.write.in.size != req->misc.write.out.size)
574                         pos = req->misc.write.in.offset - io->offset +
575                                 req->misc.write.out.size;
576         } else {
577                 if (req->misc.read.in.size != req->out.args[0].size)
578                         pos = req->misc.read.in.offset - io->offset +
579                                 req->out.args[0].size;
580         }
581
582         fuse_aio_complete(io, req->out.h.error, pos);
583 }
584
585 static size_t fuse_async_req_send(struct fuse_conn *fc, struct fuse_req *req,
586                 size_t num_bytes, struct fuse_io_priv *io)
587 {
588         spin_lock(&io->lock);
589         io->size += num_bytes;
590         io->reqs++;
591         spin_unlock(&io->lock);
592
593         req->io = io;
594         req->end = fuse_aio_complete_req;
595
596         __fuse_get_request(req);
597         fuse_request_send_background(fc, req);
598
599         return num_bytes;
600 }
601
602 static size_t fuse_send_read(struct fuse_req *req, struct fuse_io_priv *io,
603                              loff_t pos, size_t count, fl_owner_t owner)
604 {
605         struct file *file = io->file;
606         struct fuse_file *ff = file->private_data;
607         struct fuse_conn *fc = ff->fc;
608
609         fuse_read_fill(req, file, pos, count, FUSE_READ);
610         if (owner != NULL) {
611                 struct fuse_read_in *inarg = &req->misc.read.in;
612
613                 inarg->read_flags |= FUSE_READ_LOCKOWNER;
614                 inarg->lock_owner = fuse_lock_owner_id(fc, owner);
615         }
616
617         if (io->async)
618                 return fuse_async_req_send(fc, req, count, io);
619
620         fuse_request_send(fc, req);
621         return req->out.args[0].size;
622 }
623
624 static void fuse_read_update_size(struct inode *inode, loff_t size,
625                                   u64 attr_ver)
626 {
627         struct fuse_conn *fc = get_fuse_conn(inode);
628         struct fuse_inode *fi = get_fuse_inode(inode);
629
630         spin_lock(&fc->lock);
631         if (attr_ver == fi->attr_version && size < inode->i_size) {
632                 fi->attr_version = ++fc->attr_version;
633                 i_size_write(inode, size);
634         }
635         spin_unlock(&fc->lock);
636 }
637
638 static int fuse_readpage(struct file *file, struct page *page)
639 {
640         struct fuse_io_priv io = { .async = 0, .file = file };
641         struct inode *inode = page->mapping->host;
642         struct fuse_conn *fc = get_fuse_conn(inode);
643         struct fuse_req *req;
644         size_t num_read;
645         loff_t pos = page_offset(page);
646         size_t count = PAGE_CACHE_SIZE;
647         u64 attr_ver;
648         int err;
649
650         err = -EIO;
651         if (is_bad_inode(inode))
652                 goto out;
653
654         /*
655          * Page writeback can extend beyond the lifetime of the
656          * page-cache page, so make sure we read a properly synced
657          * page.
658          */
659         fuse_wait_on_page_writeback(inode, page->index);
660
661         req = fuse_get_req(fc, 1);
662         err = PTR_ERR(req);
663         if (IS_ERR(req))
664                 goto out;
665
666         attr_ver = fuse_get_attr_version(fc);
667
668         req->out.page_zeroing = 1;
669         req->out.argpages = 1;
670         req->num_pages = 1;
671         req->pages[0] = page;
672         req->page_descs[0].length = count;
673         num_read = fuse_send_read(req, &io, pos, count, NULL);
674         err = req->out.h.error;
675         fuse_put_request(fc, req);
676
677         if (!err) {
678                 /*
679                  * Short read means EOF.  If file size is larger, truncate it
680                  */
681                 if (num_read < count)
682                         fuse_read_update_size(inode, pos + num_read, attr_ver);
683
684                 SetPageUptodate(page);
685         }
686
687         fuse_invalidate_attr(inode); /* atime changed */
688  out:
689         unlock_page(page);
690         return err;
691 }
692
693 static void fuse_readpages_end(struct fuse_conn *fc, struct fuse_req *req)
694 {
695         int i;
696         size_t count = req->misc.read.in.size;
697         size_t num_read = req->out.args[0].size;
698         struct address_space *mapping = NULL;
699
700         for (i = 0; mapping == NULL && i < req->num_pages; i++)
701                 mapping = req->pages[i]->mapping;
702
703         if (mapping) {
704                 struct inode *inode = mapping->host;
705
706                 /*
707                  * Short read means EOF. If file size is larger, truncate it
708                  */
709                 if (!req->out.h.error && num_read < count) {
710                         loff_t pos;
711
712                         pos = page_offset(req->pages[0]) + num_read;
713                         fuse_read_update_size(inode, pos,
714                                               req->misc.read.attr_ver);
715                 }
716                 fuse_invalidate_attr(inode); /* atime changed */
717         }
718
719         for (i = 0; i < req->num_pages; i++) {
720                 struct page *page = req->pages[i];
721                 if (!req->out.h.error)
722                         SetPageUptodate(page);
723                 else
724                         SetPageError(page);
725                 unlock_page(page);
726                 page_cache_release(page);
727         }
728         if (req->ff)
729                 fuse_file_put(req->ff, false);
730 }
731
732 static void fuse_send_readpages(struct fuse_req *req, struct file *file)
733 {
734         struct fuse_file *ff = file->private_data;
735         struct fuse_conn *fc = ff->fc;
736         loff_t pos = page_offset(req->pages[0]);
737         size_t count = req->num_pages << PAGE_CACHE_SHIFT;
738
739         req->out.argpages = 1;
740         req->out.page_zeroing = 1;
741         req->out.page_replace = 1;
742         fuse_read_fill(req, file, pos, count, FUSE_READ);
743         req->misc.read.attr_ver = fuse_get_attr_version(fc);
744         if (fc->async_read) {
745                 req->ff = fuse_file_get(ff);
746                 req->end = fuse_readpages_end;
747                 fuse_request_send_background(fc, req);
748         } else {
749                 fuse_request_send(fc, req);
750                 fuse_readpages_end(fc, req);
751                 fuse_put_request(fc, req);
752         }
753 }
754
755 struct fuse_fill_data {
756         struct fuse_req *req;
757         struct file *file;
758         struct inode *inode;
759         unsigned nr_pages;
760 };
761
762 static int fuse_readpages_fill(void *_data, struct page *page)
763 {
764         struct fuse_fill_data *data = _data;
765         struct fuse_req *req = data->req;
766         struct inode *inode = data->inode;
767         struct fuse_conn *fc = get_fuse_conn(inode);
768
769         fuse_wait_on_page_writeback(inode, page->index);
770
771         if (req->num_pages &&
772             (req->num_pages == FUSE_MAX_PAGES_PER_REQ ||
773              (req->num_pages + 1) * PAGE_CACHE_SIZE > fc->max_read ||
774              req->pages[req->num_pages - 1]->index + 1 != page->index)) {
775                 int nr_alloc = min_t(unsigned, data->nr_pages,
776                                      FUSE_MAX_PAGES_PER_REQ);
777                 fuse_send_readpages(req, data->file);
778                 if (fc->async_read)
779                         req = fuse_get_req_for_background(fc, nr_alloc);
780                 else
781                         req = fuse_get_req(fc, nr_alloc);
782
783                 data->req = req;
784                 if (IS_ERR(req)) {
785                         unlock_page(page);
786                         return PTR_ERR(req);
787                 }
788         }
789
790         if (WARN_ON(req->num_pages >= req->max_pages)) {
791                 fuse_put_request(fc, req);
792                 return -EIO;
793         }
794
795         page_cache_get(page);
796         req->pages[req->num_pages] = page;
797         req->page_descs[req->num_pages].length = PAGE_SIZE;
798         req->num_pages++;
799         data->nr_pages--;
800         return 0;
801 }
802
803 static int fuse_readpages(struct file *file, struct address_space *mapping,
804                           struct list_head *pages, unsigned nr_pages)
805 {
806         struct inode *inode = mapping->host;
807         struct fuse_conn *fc = get_fuse_conn(inode);
808         struct fuse_fill_data data;
809         int err;
810         int nr_alloc = min_t(unsigned, nr_pages, FUSE_MAX_PAGES_PER_REQ);
811
812         err = -EIO;
813         if (is_bad_inode(inode))
814                 goto out;
815
816         data.file = file;
817         data.inode = inode;
818         if (fc->async_read)
819                 data.req = fuse_get_req_for_background(fc, nr_alloc);
820         else
821                 data.req = fuse_get_req(fc, nr_alloc);
822         data.nr_pages = nr_pages;
823         err = PTR_ERR(data.req);
824         if (IS_ERR(data.req))
825                 goto out;
826
827         err = read_cache_pages(mapping, pages, fuse_readpages_fill, &data);
828         if (!err) {
829                 if (data.req->num_pages)
830                         fuse_send_readpages(data.req, file);
831                 else
832                         fuse_put_request(fc, data.req);
833         }
834 out:
835         return err;
836 }
837
838 static ssize_t fuse_file_aio_read(struct kiocb *iocb, const struct iovec *iov,
839                                   unsigned long nr_segs, loff_t pos)
840 {
841         struct inode *inode = iocb->ki_filp->f_mapping->host;
842         struct fuse_conn *fc = get_fuse_conn(inode);
843
844         /*
845          * In auto invalidate mode, always update attributes on read.
846          * Otherwise, only update if we attempt to read past EOF (to ensure
847          * i_size is up to date).
848          */
849         if (fc->auto_inval_data ||
850             (pos + iov_length(iov, nr_segs) > i_size_read(inode))) {
851                 int err;
852                 err = fuse_update_attributes(inode, NULL, iocb->ki_filp, NULL);
853                 if (err)
854                         return err;
855         }
856
857         return generic_file_aio_read(iocb, iov, nr_segs, pos);
858 }
859
860 static void fuse_write_fill(struct fuse_req *req, struct fuse_file *ff,
861                             loff_t pos, size_t count)
862 {
863         struct fuse_write_in *inarg = &req->misc.write.in;
864         struct fuse_write_out *outarg = &req->misc.write.out;
865
866         inarg->fh = ff->fh;
867         inarg->offset = pos;
868         inarg->size = count;
869         req->in.h.opcode = FUSE_WRITE;
870         req->in.h.nodeid = ff->nodeid;
871         req->in.numargs = 2;
872         if (ff->fc->minor < 9)
873                 req->in.args[0].size = FUSE_COMPAT_WRITE_IN_SIZE;
874         else
875                 req->in.args[0].size = sizeof(struct fuse_write_in);
876         req->in.args[0].value = inarg;
877         req->in.args[1].size = count;
878         req->out.numargs = 1;
879         req->out.args[0].size = sizeof(struct fuse_write_out);
880         req->out.args[0].value = outarg;
881 }
882
883 static size_t fuse_send_write(struct fuse_req *req, struct fuse_io_priv *io,
884                               loff_t pos, size_t count, fl_owner_t owner)
885 {
886         struct file *file = io->file;
887         struct fuse_file *ff = file->private_data;
888         struct fuse_conn *fc = ff->fc;
889         struct fuse_write_in *inarg = &req->misc.write.in;
890
891         fuse_write_fill(req, ff, pos, count);
892         inarg->flags = file->f_flags;
893         if (owner != NULL) {
894                 inarg->write_flags |= FUSE_WRITE_LOCKOWNER;
895                 inarg->lock_owner = fuse_lock_owner_id(fc, owner);
896         }
897
898         if (io->async)
899                 return fuse_async_req_send(fc, req, count, io);
900
901         fuse_request_send(fc, req);
902         return req->misc.write.out.size;
903 }
904
905 void fuse_write_update_size(struct inode *inode, loff_t pos)
906 {
907         struct fuse_conn *fc = get_fuse_conn(inode);
908         struct fuse_inode *fi = get_fuse_inode(inode);
909
910         spin_lock(&fc->lock);
911         fi->attr_version = ++fc->attr_version;
912         if (pos > inode->i_size)
913                 i_size_write(inode, pos);
914         spin_unlock(&fc->lock);
915 }
916
917 static size_t fuse_send_write_pages(struct fuse_req *req, struct file *file,
918                                     struct inode *inode, loff_t pos,
919                                     size_t count)
920 {
921         size_t res;
922         unsigned offset;
923         unsigned i;
924         struct fuse_io_priv io = { .async = 0, .file = file };
925
926         for (i = 0; i < req->num_pages; i++)
927                 fuse_wait_on_page_writeback(inode, req->pages[i]->index);
928
929         res = fuse_send_write(req, &io, pos, count, NULL);
930
931         offset = req->page_descs[0].offset;
932         count = res;
933         for (i = 0; i < req->num_pages; i++) {
934                 struct page *page = req->pages[i];
935
936                 if (!req->out.h.error && !offset && count >= PAGE_CACHE_SIZE)
937                         SetPageUptodate(page);
938
939                 if (count > PAGE_CACHE_SIZE - offset)
940                         count -= PAGE_CACHE_SIZE - offset;
941                 else
942                         count = 0;
943                 offset = 0;
944
945                 unlock_page(page);
946                 page_cache_release(page);
947         }
948
949         return res;
950 }
951
952 static ssize_t fuse_fill_write_pages(struct fuse_req *req,
953                                struct address_space *mapping,
954                                struct iov_iter *ii, loff_t pos)
955 {
956         struct fuse_conn *fc = get_fuse_conn(mapping->host);
957         unsigned offset = pos & (PAGE_CACHE_SIZE - 1);
958         size_t count = 0;
959         int err;
960
961         req->in.argpages = 1;
962         req->page_descs[0].offset = offset;
963
964         do {
965                 size_t tmp;
966                 struct page *page;
967                 pgoff_t index = pos >> PAGE_CACHE_SHIFT;
968                 size_t bytes = min_t(size_t, PAGE_CACHE_SIZE - offset,
969                                      iov_iter_count(ii));
970
971                 bytes = min_t(size_t, bytes, fc->max_write - count);
972
973  again:
974                 err = -EFAULT;
975                 if (iov_iter_fault_in_readable(ii, bytes))
976                         break;
977
978                 err = -ENOMEM;
979                 page = grab_cache_page_write_begin(mapping, index, 0);
980                 if (!page)
981                         break;
982
983                 if (mapping_writably_mapped(mapping))
984                         flush_dcache_page(page);
985
986                 pagefault_disable();
987                 tmp = iov_iter_copy_from_user_atomic(page, ii, offset, bytes);
988                 pagefault_enable();
989                 flush_dcache_page(page);
990
991                 mark_page_accessed(page);
992
993                 if (!tmp) {
994                         unlock_page(page);
995                         page_cache_release(page);
996                         bytes = min(bytes, iov_iter_single_seg_count(ii));
997                         goto again;
998                 }
999
1000                 err = 0;
1001                 req->pages[req->num_pages] = page;
1002                 req->page_descs[req->num_pages].length = tmp;
1003                 req->num_pages++;
1004
1005                 iov_iter_advance(ii, tmp);
1006                 count += tmp;
1007                 pos += tmp;
1008                 offset += tmp;
1009                 if (offset == PAGE_CACHE_SIZE)
1010                         offset = 0;
1011
1012                 if (!fc->big_writes)
1013                         break;
1014         } while (iov_iter_count(ii) && count < fc->max_write &&
1015                  req->num_pages < req->max_pages && offset == 0);
1016
1017         return count > 0 ? count : err;
1018 }
1019
1020 static inline unsigned fuse_wr_pages(loff_t pos, size_t len)
1021 {
1022         return min_t(unsigned,
1023                      ((pos + len - 1) >> PAGE_CACHE_SHIFT) -
1024                      (pos >> PAGE_CACHE_SHIFT) + 1,
1025                      FUSE_MAX_PAGES_PER_REQ);
1026 }
1027
1028 static ssize_t fuse_perform_write(struct file *file,
1029                                   struct address_space *mapping,
1030                                   struct iov_iter *ii, loff_t pos)
1031 {
1032         struct inode *inode = mapping->host;
1033         struct fuse_conn *fc = get_fuse_conn(inode);
1034         int err = 0;
1035         ssize_t res = 0;
1036
1037         if (is_bad_inode(inode))
1038                 return -EIO;
1039
1040         do {
1041                 struct fuse_req *req;
1042                 ssize_t count;
1043                 unsigned nr_pages = fuse_wr_pages(pos, iov_iter_count(ii));
1044
1045                 req = fuse_get_req(fc, nr_pages);
1046                 if (IS_ERR(req)) {
1047                         err = PTR_ERR(req);
1048                         break;
1049                 }
1050
1051                 count = fuse_fill_write_pages(req, mapping, ii, pos);
1052                 if (count <= 0) {
1053                         err = count;
1054                 } else {
1055                         size_t num_written;
1056
1057                         num_written = fuse_send_write_pages(req, file, inode,
1058                                                             pos, count);
1059                         err = req->out.h.error;
1060                         if (!err) {
1061                                 res += num_written;
1062                                 pos += num_written;
1063
1064                                 /* break out of the loop on short write */
1065                                 if (num_written != count)
1066                                         err = -EIO;
1067                         }
1068                 }
1069                 fuse_put_request(fc, req);
1070         } while (!err && iov_iter_count(ii));
1071
1072         if (res > 0)
1073                 fuse_write_update_size(inode, pos);
1074
1075         fuse_invalidate_attr(inode);
1076
1077         return res > 0 ? res : err;
1078 }
1079
1080 static ssize_t fuse_file_aio_write(struct kiocb *iocb, const struct iovec *iov,
1081                                    unsigned long nr_segs, loff_t pos)
1082 {
1083         struct file *file = iocb->ki_filp;
1084         struct address_space *mapping = file->f_mapping;
1085         size_t count = 0;
1086         size_t ocount = 0;
1087         ssize_t written = 0;
1088         ssize_t written_buffered = 0;
1089         struct inode *inode = mapping->host;
1090         ssize_t err;
1091         struct iov_iter i;
1092         loff_t endbyte = 0;
1093
1094         WARN_ON(iocb->ki_pos != pos);
1095
1096         ocount = 0;
1097         err = generic_segment_checks(iov, &nr_segs, &ocount, VERIFY_READ);
1098         if (err)
1099                 return err;
1100
1101         count = ocount;
1102         mutex_lock(&inode->i_mutex);
1103
1104         /* We can write back this queue in page reclaim */
1105         current->backing_dev_info = mapping->backing_dev_info;
1106
1107         err = generic_write_checks(file, &pos, &count, S_ISBLK(inode->i_mode));
1108         if (err)
1109                 goto out;
1110
1111         if (count == 0)
1112                 goto out;
1113
1114         err = file_remove_suid(file);
1115         if (err)
1116                 goto out;
1117
1118         err = file_update_time(file);
1119         if (err)
1120                 goto out;
1121
1122         if (file->f_flags & O_DIRECT) {
1123                 written = generic_file_direct_write(iocb, iov, &nr_segs,
1124                                                     pos, &iocb->ki_pos,
1125                                                     count, ocount);
1126                 if (written < 0 || written == count)
1127                         goto out;
1128
1129                 pos += written;
1130                 count -= written;
1131
1132                 iov_iter_init(&i, iov, nr_segs, count, written);
1133                 written_buffered = fuse_perform_write(file, mapping, &i, pos);
1134                 if (written_buffered < 0) {
1135                         err = written_buffered;
1136                         goto out;
1137                 }
1138                 endbyte = pos + written_buffered - 1;
1139
1140                 err = filemap_write_and_wait_range(file->f_mapping, pos,
1141                                                    endbyte);
1142                 if (err)
1143                         goto out;
1144
1145                 invalidate_mapping_pages(file->f_mapping,
1146                                          pos >> PAGE_CACHE_SHIFT,
1147                                          endbyte >> PAGE_CACHE_SHIFT);
1148
1149                 written += written_buffered;
1150                 iocb->ki_pos = pos + written_buffered;
1151         } else {
1152                 iov_iter_init(&i, iov, nr_segs, count, 0);
1153                 written = fuse_perform_write(file, mapping, &i, pos);
1154                 if (written >= 0)
1155                         iocb->ki_pos = pos + written;
1156         }
1157 out:
1158         current->backing_dev_info = NULL;
1159         mutex_unlock(&inode->i_mutex);
1160
1161         return written ? written : err;
1162 }
1163
1164 static inline void fuse_page_descs_length_init(struct fuse_req *req,
1165                 unsigned index, unsigned nr_pages)
1166 {
1167         int i;
1168
1169         for (i = index; i < index + nr_pages; i++)
1170                 req->page_descs[i].length = PAGE_SIZE -
1171                         req->page_descs[i].offset;
1172 }
1173
1174 static inline unsigned long fuse_get_user_addr(const struct iov_iter *ii)
1175 {
1176         return (unsigned long)ii->iov->iov_base + ii->iov_offset;
1177 }
1178
1179 static inline size_t fuse_get_frag_size(const struct iov_iter *ii,
1180                                         size_t max_size)
1181 {
1182         return min(iov_iter_single_seg_count(ii), max_size);
1183 }
1184
1185 static int fuse_get_user_pages(struct fuse_req *req, struct iov_iter *ii,
1186                                size_t *nbytesp, int write)
1187 {
1188         size_t nbytes = 0;  /* # bytes already packed in req */
1189
1190         /* Special case for kernel I/O: can copy directly into the buffer */
1191         if (segment_eq(get_fs(), KERNEL_DS)) {
1192                 unsigned long user_addr = fuse_get_user_addr(ii);
1193                 size_t frag_size = fuse_get_frag_size(ii, *nbytesp);
1194
1195                 if (write)
1196                         req->in.args[1].value = (void *) user_addr;
1197                 else
1198                         req->out.args[0].value = (void *) user_addr;
1199
1200                 iov_iter_advance(ii, frag_size);
1201                 *nbytesp = frag_size;
1202                 return 0;
1203         }
1204
1205         while (nbytes < *nbytesp && req->num_pages < req->max_pages) {
1206                 unsigned npages;
1207                 unsigned long user_addr = fuse_get_user_addr(ii);
1208                 unsigned offset = user_addr & ~PAGE_MASK;
1209                 size_t frag_size = fuse_get_frag_size(ii, *nbytesp - nbytes);
1210                 int ret;
1211
1212                 unsigned n = req->max_pages - req->num_pages;
1213                 frag_size = min_t(size_t, frag_size, n << PAGE_SHIFT);
1214
1215                 npages = (frag_size + offset + PAGE_SIZE - 1) >> PAGE_SHIFT;
1216                 npages = clamp(npages, 1U, n);
1217
1218                 ret = get_user_pages_fast(user_addr, npages, !write,
1219                                           &req->pages[req->num_pages]);
1220                 if (ret < 0)
1221                         return ret;
1222
1223                 npages = ret;
1224                 frag_size = min_t(size_t, frag_size,
1225                                   (npages << PAGE_SHIFT) - offset);
1226                 iov_iter_advance(ii, frag_size);
1227
1228                 req->page_descs[req->num_pages].offset = offset;
1229                 fuse_page_descs_length_init(req, req->num_pages, npages);
1230
1231                 req->num_pages += npages;
1232                 req->page_descs[req->num_pages - 1].length -=
1233                         (npages << PAGE_SHIFT) - offset - frag_size;
1234
1235                 nbytes += frag_size;
1236         }
1237
1238         if (write)
1239                 req->in.argpages = 1;
1240         else
1241                 req->out.argpages = 1;
1242
1243         *nbytesp = nbytes;
1244
1245         return 0;
1246 }
1247
1248 static inline int fuse_iter_npages(const struct iov_iter *ii_p)
1249 {
1250         struct iov_iter ii = *ii_p;
1251         int npages = 0;
1252
1253         while (iov_iter_count(&ii) && npages < FUSE_MAX_PAGES_PER_REQ) {
1254                 unsigned long user_addr = fuse_get_user_addr(&ii);
1255                 unsigned offset = user_addr & ~PAGE_MASK;
1256                 size_t frag_size = iov_iter_single_seg_count(&ii);
1257
1258                 npages += (frag_size + offset + PAGE_SIZE - 1) >> PAGE_SHIFT;
1259                 iov_iter_advance(&ii, frag_size);
1260         }
1261
1262         return min(npages, FUSE_MAX_PAGES_PER_REQ);
1263 }
1264
1265 ssize_t fuse_direct_io(struct fuse_io_priv *io, const struct iovec *iov,
1266                        unsigned long nr_segs, size_t count, loff_t *ppos,
1267                        int write)
1268 {
1269         struct file *file = io->file;
1270         struct fuse_file *ff = file->private_data;
1271         struct fuse_conn *fc = ff->fc;
1272         size_t nmax = write ? fc->max_write : fc->max_read;
1273         loff_t pos = *ppos;
1274         ssize_t res = 0;
1275         struct fuse_req *req;
1276         struct iov_iter ii;
1277
1278         iov_iter_init(&ii, iov, nr_segs, count, 0);
1279
1280         req = fuse_get_req(fc, fuse_iter_npages(&ii));
1281         if (IS_ERR(req))
1282                 return PTR_ERR(req);
1283
1284         while (count) {
1285                 size_t nres;
1286                 fl_owner_t owner = current->files;
1287                 size_t nbytes = min(count, nmax);
1288                 int err = fuse_get_user_pages(req, &ii, &nbytes, write);
1289                 if (err) {
1290                         res = err;
1291                         break;
1292                 }
1293
1294                 if (write)
1295                         nres = fuse_send_write(req, io, pos, nbytes, owner);
1296                 else
1297                         nres = fuse_send_read(req, io, pos, nbytes, owner);
1298
1299                 if (!io->async)
1300                         fuse_release_user_pages(req, !write);
1301                 if (req->out.h.error) {
1302                         if (!res)
1303                                 res = req->out.h.error;
1304                         break;
1305                 } else if (nres > nbytes) {
1306                         res = -EIO;
1307                         break;
1308                 }
1309                 count -= nres;
1310                 res += nres;
1311                 pos += nres;
1312                 if (nres != nbytes)
1313                         break;
1314                 if (count) {
1315                         fuse_put_request(fc, req);
1316                         req = fuse_get_req(fc, fuse_iter_npages(&ii));
1317                         if (IS_ERR(req))
1318                                 break;
1319                 }
1320         }
1321         if (!IS_ERR(req))
1322                 fuse_put_request(fc, req);
1323         if (res > 0)
1324                 *ppos = pos;
1325
1326         return res;
1327 }
1328 EXPORT_SYMBOL_GPL(fuse_direct_io);
1329
1330 static ssize_t __fuse_direct_read(struct fuse_io_priv *io,
1331                                   const struct iovec *iov,
1332                                   unsigned long nr_segs, loff_t *ppos,
1333                                   size_t count)
1334 {
1335         ssize_t res;
1336         struct file *file = io->file;
1337         struct inode *inode = file_inode(file);
1338
1339         if (is_bad_inode(inode))
1340                 return -EIO;
1341
1342         res = fuse_direct_io(io, iov, nr_segs, count, ppos, 0);
1343
1344         fuse_invalidate_attr(inode);
1345
1346         return res;
1347 }
1348
1349 static ssize_t fuse_direct_read(struct file *file, char __user *buf,
1350                                      size_t count, loff_t *ppos)
1351 {
1352         struct fuse_io_priv io = { .async = 0, .file = file };
1353         struct iovec iov = { .iov_base = buf, .iov_len = count };
1354         return __fuse_direct_read(&io, &iov, 1, ppos, count);
1355 }
1356
1357 static ssize_t __fuse_direct_write(struct fuse_io_priv *io,
1358                                    const struct iovec *iov,
1359                                    unsigned long nr_segs, loff_t *ppos)
1360 {
1361         struct file *file = io->file;
1362         struct inode *inode = file_inode(file);
1363         size_t count = iov_length(iov, nr_segs);
1364         ssize_t res;
1365
1366         res = generic_write_checks(file, ppos, &count, 0);
1367         if (!res)
1368                 res = fuse_direct_io(io, iov, nr_segs, count, ppos, 1);
1369
1370         fuse_invalidate_attr(inode);
1371
1372         return res;
1373 }
1374
1375 static ssize_t fuse_direct_write(struct file *file, const char __user *buf,
1376                                  size_t count, loff_t *ppos)
1377 {
1378         struct iovec iov = { .iov_base = (void __user *)buf, .iov_len = count };
1379         struct inode *inode = file_inode(file);
1380         ssize_t res;
1381         struct fuse_io_priv io = { .async = 0, .file = file };
1382
1383         if (is_bad_inode(inode))
1384                 return -EIO;
1385
1386         /* Don't allow parallel writes to the same file */
1387         mutex_lock(&inode->i_mutex);
1388         res = __fuse_direct_write(&io, &iov, 1, ppos);
1389         if (res > 0)
1390                 fuse_write_update_size(inode, *ppos);
1391         mutex_unlock(&inode->i_mutex);
1392
1393         return res;
1394 }
1395
1396 static void fuse_writepage_free(struct fuse_conn *fc, struct fuse_req *req)
1397 {
1398         __free_page(req->pages[0]);
1399         fuse_file_put(req->ff, false);
1400 }
1401
1402 static void fuse_writepage_finish(struct fuse_conn *fc, struct fuse_req *req)
1403 {
1404         struct inode *inode = req->inode;
1405         struct fuse_inode *fi = get_fuse_inode(inode);
1406         struct backing_dev_info *bdi = inode->i_mapping->backing_dev_info;
1407
1408         list_del(&req->writepages_entry);
1409         dec_bdi_stat(bdi, BDI_WRITEBACK);
1410         dec_zone_page_state(req->pages[0], NR_WRITEBACK_TEMP);
1411         bdi_writeout_inc(bdi);
1412         wake_up(&fi->page_waitq);
1413 }
1414
1415 /* Called under fc->lock, may release and reacquire it */
1416 static void fuse_send_writepage(struct fuse_conn *fc, struct fuse_req *req)
1417 __releases(fc->lock)
1418 __acquires(fc->lock)
1419 {
1420         struct fuse_inode *fi = get_fuse_inode(req->inode);
1421         loff_t size = i_size_read(req->inode);
1422         struct fuse_write_in *inarg = &req->misc.write.in;
1423
1424         if (!fc->connected)
1425                 goto out_free;
1426
1427         if (inarg->offset + PAGE_CACHE_SIZE <= size) {
1428                 inarg->size = PAGE_CACHE_SIZE;
1429         } else if (inarg->offset < size) {
1430                 inarg->size = size & (PAGE_CACHE_SIZE - 1);
1431         } else {
1432                 /* Got truncated off completely */
1433                 goto out_free;
1434         }
1435
1436         req->in.args[1].size = inarg->size;
1437         fi->writectr++;
1438         fuse_request_send_background_locked(fc, req);
1439         return;
1440
1441  out_free:
1442         fuse_writepage_finish(fc, req);
1443         spin_unlock(&fc->lock);
1444         fuse_writepage_free(fc, req);
1445         fuse_put_request(fc, req);
1446         spin_lock(&fc->lock);
1447 }
1448
1449 /*
1450  * If fi->writectr is positive (no truncate or fsync going on) send
1451  * all queued writepage requests.
1452  *
1453  * Called with fc->lock
1454  */
1455 void fuse_flush_writepages(struct inode *inode)
1456 __releases(fc->lock)
1457 __acquires(fc->lock)
1458 {
1459         struct fuse_conn *fc = get_fuse_conn(inode);
1460         struct fuse_inode *fi = get_fuse_inode(inode);
1461         struct fuse_req *req;
1462
1463         while (fi->writectr >= 0 && !list_empty(&fi->queued_writes)) {
1464                 req = list_entry(fi->queued_writes.next, struct fuse_req, list);
1465                 list_del_init(&req->list);
1466                 fuse_send_writepage(fc, req);
1467         }
1468 }
1469
1470 static void fuse_writepage_end(struct fuse_conn *fc, struct fuse_req *req)
1471 {
1472         struct inode *inode = req->inode;
1473         struct fuse_inode *fi = get_fuse_inode(inode);
1474
1475         mapping_set_error(inode->i_mapping, req->out.h.error);
1476         spin_lock(&fc->lock);
1477         fi->writectr--;
1478         fuse_writepage_finish(fc, req);
1479         spin_unlock(&fc->lock);
1480         fuse_writepage_free(fc, req);
1481 }
1482
1483 static int fuse_writepage_locked(struct page *page)
1484 {
1485         struct address_space *mapping = page->mapping;
1486         struct inode *inode = mapping->host;
1487         struct fuse_conn *fc = get_fuse_conn(inode);
1488         struct fuse_inode *fi = get_fuse_inode(inode);
1489         struct fuse_req *req;
1490         struct fuse_file *ff;
1491         struct page *tmp_page;
1492
1493         set_page_writeback(page);
1494
1495         req = fuse_request_alloc_nofs(1);
1496         if (!req)
1497                 goto err;
1498
1499         req->background = 1; /* writeback always goes to bg_queue */
1500         tmp_page = alloc_page(GFP_NOFS | __GFP_HIGHMEM);
1501         if (!tmp_page)
1502                 goto err_free;
1503
1504         spin_lock(&fc->lock);
1505         BUG_ON(list_empty(&fi->write_files));
1506         ff = list_entry(fi->write_files.next, struct fuse_file, write_entry);
1507         req->ff = fuse_file_get(ff);
1508         spin_unlock(&fc->lock);
1509
1510         fuse_write_fill(req, ff, page_offset(page), 0);
1511
1512         copy_highpage(tmp_page, page);
1513         req->misc.write.in.write_flags |= FUSE_WRITE_CACHE;
1514         req->in.argpages = 1;
1515         req->num_pages = 1;
1516         req->pages[0] = tmp_page;
1517         req->page_descs[0].offset = 0;
1518         req->page_descs[0].length = PAGE_SIZE;
1519         req->end = fuse_writepage_end;
1520         req->inode = inode;
1521
1522         inc_bdi_stat(mapping->backing_dev_info, BDI_WRITEBACK);
1523         inc_zone_page_state(tmp_page, NR_WRITEBACK_TEMP);
1524         end_page_writeback(page);
1525
1526         spin_lock(&fc->lock);
1527         list_add(&req->writepages_entry, &fi->writepages);
1528         list_add_tail(&req->list, &fi->queued_writes);
1529         fuse_flush_writepages(inode);
1530         spin_unlock(&fc->lock);
1531
1532         return 0;
1533
1534 err_free:
1535         fuse_request_free(req);
1536 err:
1537         end_page_writeback(page);
1538         return -ENOMEM;
1539 }
1540
1541 static int fuse_writepage(struct page *page, struct writeback_control *wbc)
1542 {
1543         int err;
1544
1545         err = fuse_writepage_locked(page);
1546         unlock_page(page);
1547
1548         return err;
1549 }
1550
1551 static int fuse_launder_page(struct page *page)
1552 {
1553         int err = 0;
1554         if (clear_page_dirty_for_io(page)) {
1555                 struct inode *inode = page->mapping->host;
1556                 err = fuse_writepage_locked(page);
1557                 if (!err)
1558                         fuse_wait_on_page_writeback(inode, page->index);
1559         }
1560         return err;
1561 }
1562
1563 /*
1564  * Write back dirty pages now, because there may not be any suitable
1565  * open files later
1566  */
1567 static void fuse_vma_close(struct vm_area_struct *vma)
1568 {
1569         filemap_write_and_wait(vma->vm_file->f_mapping);
1570 }
1571
1572 /*
1573  * Wait for writeback against this page to complete before allowing it
1574  * to be marked dirty again, and hence written back again, possibly
1575  * before the previous writepage completed.
1576  *
1577  * Block here, instead of in ->writepage(), so that the userspace fs
1578  * can only block processes actually operating on the filesystem.
1579  *
1580  * Otherwise unprivileged userspace fs would be able to block
1581  * unrelated:
1582  *
1583  * - page migration
1584  * - sync(2)
1585  * - try_to_free_pages() with order > PAGE_ALLOC_COSTLY_ORDER
1586  */
1587 static int fuse_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
1588 {
1589         struct page *page = vmf->page;
1590         /*
1591          * Don't use page->mapping as it may become NULL from a
1592          * concurrent truncate.
1593          */
1594         struct inode *inode = vma->vm_file->f_mapping->host;
1595
1596         fuse_wait_on_page_writeback(inode, page->index);
1597         return 0;
1598 }
1599
1600 static const struct vm_operations_struct fuse_file_vm_ops = {
1601         .close          = fuse_vma_close,
1602         .fault          = filemap_fault,
1603         .page_mkwrite   = fuse_page_mkwrite,
1604         .remap_pages    = generic_file_remap_pages,
1605 };
1606
1607 static int fuse_file_mmap(struct file *file, struct vm_area_struct *vma)
1608 {
1609         if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_MAYWRITE)) {
1610                 struct inode *inode = file_inode(file);
1611                 struct fuse_conn *fc = get_fuse_conn(inode);
1612                 struct fuse_inode *fi = get_fuse_inode(inode);
1613                 struct fuse_file *ff = file->private_data;
1614                 /*
1615                  * file may be written through mmap, so chain it onto the
1616                  * inodes's write_file list
1617                  */
1618                 spin_lock(&fc->lock);
1619                 if (list_empty(&ff->write_entry))
1620                         list_add(&ff->write_entry, &fi->write_files);
1621                 spin_unlock(&fc->lock);
1622         }
1623         file_accessed(file);
1624         vma->vm_ops = &fuse_file_vm_ops;
1625         return 0;
1626 }
1627
1628 static int fuse_direct_mmap(struct file *file, struct vm_area_struct *vma)
1629 {
1630         /* Can't provide the coherency needed for MAP_SHARED */
1631         if (vma->vm_flags & VM_MAYSHARE)
1632                 return -ENODEV;
1633
1634         invalidate_inode_pages2(file->f_mapping);
1635
1636         return generic_file_mmap(file, vma);
1637 }
1638
1639 static int convert_fuse_file_lock(const struct fuse_file_lock *ffl,
1640                                   struct file_lock *fl)
1641 {
1642         switch (ffl->type) {
1643         case F_UNLCK:
1644                 break;
1645
1646         case F_RDLCK:
1647         case F_WRLCK:
1648                 if (ffl->start > OFFSET_MAX || ffl->end > OFFSET_MAX ||
1649                     ffl->end < ffl->start)
1650                         return -EIO;
1651
1652                 fl->fl_start = ffl->start;
1653                 fl->fl_end = ffl->end;
1654                 fl->fl_pid = ffl->pid;
1655                 break;
1656
1657         default:
1658                 return -EIO;
1659         }
1660         fl->fl_type = ffl->type;
1661         return 0;
1662 }
1663
1664 static void fuse_lk_fill(struct fuse_req *req, struct file *file,
1665                          const struct file_lock *fl, int opcode, pid_t pid,
1666                          int flock)
1667 {
1668         struct inode *inode = file_inode(file);
1669         struct fuse_conn *fc = get_fuse_conn(inode);
1670         struct fuse_file *ff = file->private_data;
1671         struct fuse_lk_in *arg = &req->misc.lk_in;
1672
1673         arg->fh = ff->fh;
1674         arg->owner = fuse_lock_owner_id(fc, fl->fl_owner);
1675         arg->lk.start = fl->fl_start;
1676         arg->lk.end = fl->fl_end;
1677         arg->lk.type = fl->fl_type;
1678         arg->lk.pid = pid;
1679         if (flock)
1680                 arg->lk_flags |= FUSE_LK_FLOCK;
1681         req->in.h.opcode = opcode;
1682         req->in.h.nodeid = get_node_id(inode);
1683         req->in.numargs = 1;
1684         req->in.args[0].size = sizeof(*arg);
1685         req->in.args[0].value = arg;
1686 }
1687
1688 static int fuse_getlk(struct file *file, struct file_lock *fl)
1689 {
1690         struct inode *inode = file_inode(file);
1691         struct fuse_conn *fc = get_fuse_conn(inode);
1692         struct fuse_req *req;
1693         struct fuse_lk_out outarg;
1694         int err;
1695
1696         req = fuse_get_req_nopages(fc);
1697         if (IS_ERR(req))
1698                 return PTR_ERR(req);
1699
1700         fuse_lk_fill(req, file, fl, FUSE_GETLK, 0, 0);
1701         req->out.numargs = 1;
1702         req->out.args[0].size = sizeof(outarg);
1703         req->out.args[0].value = &outarg;
1704         fuse_request_send(fc, req);
1705         err = req->out.h.error;
1706         fuse_put_request(fc, req);
1707         if (!err)
1708                 err = convert_fuse_file_lock(&outarg.lk, fl);
1709
1710         return err;
1711 }
1712
1713 static int fuse_setlk(struct file *file, struct file_lock *fl, int flock)
1714 {
1715         struct inode *inode = file_inode(file);
1716         struct fuse_conn *fc = get_fuse_conn(inode);
1717         struct fuse_req *req;
1718         int opcode = (fl->fl_flags & FL_SLEEP) ? FUSE_SETLKW : FUSE_SETLK;
1719         pid_t pid = fl->fl_type != F_UNLCK ? current->tgid : 0;
1720         int err;
1721
1722         if (fl->fl_lmops && fl->fl_lmops->lm_grant) {
1723                 /* NLM needs asynchronous locks, which we don't support yet */
1724                 return -ENOLCK;
1725         }
1726
1727         /* Unlock on close is handled by the flush method */
1728         if (fl->fl_flags & FL_CLOSE)
1729                 return 0;
1730
1731         req = fuse_get_req_nopages(fc);
1732         if (IS_ERR(req))
1733                 return PTR_ERR(req);
1734
1735         fuse_lk_fill(req, file, fl, opcode, pid, flock);
1736         fuse_request_send(fc, req);
1737         err = req->out.h.error;
1738         /* locking is restartable */
1739         if (err == -EINTR)
1740                 err = -ERESTARTSYS;
1741         fuse_put_request(fc, req);
1742         return err;
1743 }
1744
1745 static int fuse_file_lock(struct file *file, int cmd, struct file_lock *fl)
1746 {
1747         struct inode *inode = file_inode(file);
1748         struct fuse_conn *fc = get_fuse_conn(inode);
1749         int err;
1750
1751         if (cmd == F_CANCELLK) {
1752                 err = 0;
1753         } else if (cmd == F_GETLK) {
1754                 if (fc->no_lock) {
1755                         posix_test_lock(file, fl);
1756                         err = 0;
1757                 } else
1758                         err = fuse_getlk(file, fl);
1759         } else {
1760                 if (fc->no_lock)
1761                         err = posix_lock_file(file, fl, NULL);
1762                 else
1763                         err = fuse_setlk(file, fl, 0);
1764         }
1765         return err;
1766 }
1767
1768 static int fuse_file_flock(struct file *file, int cmd, struct file_lock *fl)
1769 {
1770         struct inode *inode = file_inode(file);
1771         struct fuse_conn *fc = get_fuse_conn(inode);
1772         int err;
1773
1774         if (fc->no_flock) {
1775                 err = flock_lock_file_wait(file, fl);
1776         } else {
1777                 struct fuse_file *ff = file->private_data;
1778
1779                 /* emulate flock with POSIX locks */
1780                 fl->fl_owner = (fl_owner_t) file;
1781                 ff->flock = true;
1782                 err = fuse_setlk(file, fl, 1);
1783         }
1784
1785         return err;
1786 }
1787
1788 static sector_t fuse_bmap(struct address_space *mapping, sector_t block)
1789 {
1790         struct inode *inode = mapping->host;
1791         struct fuse_conn *fc = get_fuse_conn(inode);
1792         struct fuse_req *req;
1793         struct fuse_bmap_in inarg;
1794         struct fuse_bmap_out outarg;
1795         int err;
1796
1797         if (!inode->i_sb->s_bdev || fc->no_bmap)
1798                 return 0;
1799
1800         req = fuse_get_req_nopages(fc);
1801         if (IS_ERR(req))
1802                 return 0;
1803
1804         memset(&inarg, 0, sizeof(inarg));
1805         inarg.block = block;
1806         inarg.blocksize = inode->i_sb->s_blocksize;
1807         req->in.h.opcode = FUSE_BMAP;
1808         req->in.h.nodeid = get_node_id(inode);
1809         req->in.numargs = 1;
1810         req->in.args[0].size = sizeof(inarg);
1811         req->in.args[0].value = &inarg;
1812         req->out.numargs = 1;
1813         req->out.args[0].size = sizeof(outarg);
1814         req->out.args[0].value = &outarg;
1815         fuse_request_send(fc, req);
1816         err = req->out.h.error;
1817         fuse_put_request(fc, req);
1818         if (err == -ENOSYS)
1819                 fc->no_bmap = 1;
1820
1821         return err ? 0 : outarg.block;
1822 }
1823
1824 static loff_t fuse_file_llseek(struct file *file, loff_t offset, int whence)
1825 {
1826         loff_t retval;
1827         struct inode *inode = file_inode(file);
1828
1829         /* No i_mutex protection necessary for SEEK_CUR and SEEK_SET */
1830         if (whence == SEEK_CUR || whence == SEEK_SET)
1831                 return generic_file_llseek(file, offset, whence);
1832
1833         mutex_lock(&inode->i_mutex);
1834         retval = fuse_update_attributes(inode, NULL, file, NULL);
1835         if (!retval)
1836                 retval = generic_file_llseek(file, offset, whence);
1837         mutex_unlock(&inode->i_mutex);
1838
1839         return retval;
1840 }
1841
1842 static int fuse_ioctl_copy_user(struct page **pages, struct iovec *iov,
1843                         unsigned int nr_segs, size_t bytes, bool to_user)
1844 {
1845         struct iov_iter ii;
1846         int page_idx = 0;
1847
1848         if (!bytes)
1849                 return 0;
1850
1851         iov_iter_init(&ii, iov, nr_segs, bytes, 0);
1852
1853         while (iov_iter_count(&ii)) {
1854                 struct page *page = pages[page_idx++];
1855                 size_t todo = min_t(size_t, PAGE_SIZE, iov_iter_count(&ii));
1856                 void *kaddr;
1857
1858                 kaddr = kmap(page);
1859
1860                 while (todo) {
1861                         char __user *uaddr = ii.iov->iov_base + ii.iov_offset;
1862                         size_t iov_len = ii.iov->iov_len - ii.iov_offset;
1863                         size_t copy = min(todo, iov_len);
1864                         size_t left;
1865
1866                         if (!to_user)
1867                                 left = copy_from_user(kaddr, uaddr, copy);
1868                         else
1869                                 left = copy_to_user(uaddr, kaddr, copy);
1870
1871                         if (unlikely(left))
1872                                 return -EFAULT;
1873
1874                         iov_iter_advance(&ii, copy);
1875                         todo -= copy;
1876                         kaddr += copy;
1877                 }
1878
1879                 kunmap(page);
1880         }
1881
1882         return 0;
1883 }
1884
1885 /*
1886  * CUSE servers compiled on 32bit broke on 64bit kernels because the
1887  * ABI was defined to be 'struct iovec' which is different on 32bit
1888  * and 64bit.  Fortunately we can determine which structure the server
1889  * used from the size of the reply.
1890  */
1891 static int fuse_copy_ioctl_iovec_old(struct iovec *dst, void *src,
1892                                      size_t transferred, unsigned count,
1893                                      bool is_compat)
1894 {
1895 #ifdef CONFIG_COMPAT
1896         if (count * sizeof(struct compat_iovec) == transferred) {
1897                 struct compat_iovec *ciov = src;
1898                 unsigned i;
1899
1900                 /*
1901                  * With this interface a 32bit server cannot support
1902                  * non-compat (i.e. ones coming from 64bit apps) ioctl
1903                  * requests
1904                  */
1905                 if (!is_compat)
1906                         return -EINVAL;
1907
1908                 for (i = 0; i < count; i++) {
1909                         dst[i].iov_base = compat_ptr(ciov[i].iov_base);
1910                         dst[i].iov_len = ciov[i].iov_len;
1911                 }
1912                 return 0;
1913         }
1914 #endif
1915
1916         if (count * sizeof(struct iovec) != transferred)
1917                 return -EIO;
1918
1919         memcpy(dst, src, transferred);
1920         return 0;
1921 }
1922
1923 /* Make sure iov_length() won't overflow */
1924 static int fuse_verify_ioctl_iov(struct iovec *iov, size_t count)
1925 {
1926         size_t n;
1927         u32 max = FUSE_MAX_PAGES_PER_REQ << PAGE_SHIFT;
1928
1929         for (n = 0; n < count; n++, iov++) {
1930                 if (iov->iov_len > (size_t) max)
1931                         return -ENOMEM;
1932                 max -= iov->iov_len;
1933         }
1934         return 0;
1935 }
1936
1937 static int fuse_copy_ioctl_iovec(struct fuse_conn *fc, struct iovec *dst,
1938                                  void *src, size_t transferred, unsigned count,
1939                                  bool is_compat)
1940 {
1941         unsigned i;
1942         struct fuse_ioctl_iovec *fiov = src;
1943
1944         if (fc->minor < 16) {
1945                 return fuse_copy_ioctl_iovec_old(dst, src, transferred,
1946                                                  count, is_compat);
1947         }
1948
1949         if (count * sizeof(struct fuse_ioctl_iovec) != transferred)
1950                 return -EIO;
1951
1952         for (i = 0; i < count; i++) {
1953                 /* Did the server supply an inappropriate value? */
1954                 if (fiov[i].base != (unsigned long) fiov[i].base ||
1955                     fiov[i].len != (unsigned long) fiov[i].len)
1956                         return -EIO;
1957
1958                 dst[i].iov_base = (void __user *) (unsigned long) fiov[i].base;
1959                 dst[i].iov_len = (size_t) fiov[i].len;
1960
1961 #ifdef CONFIG_COMPAT
1962                 if (is_compat &&
1963                     (ptr_to_compat(dst[i].iov_base) != fiov[i].base ||
1964                      (compat_size_t) dst[i].iov_len != fiov[i].len))
1965                         return -EIO;
1966 #endif
1967         }
1968
1969         return 0;
1970 }
1971
1972
1973 /*
1974  * For ioctls, there is no generic way to determine how much memory
1975  * needs to be read and/or written.  Furthermore, ioctls are allowed
1976  * to dereference the passed pointer, so the parameter requires deep
1977  * copying but FUSE has no idea whatsoever about what to copy in or
1978  * out.
1979  *
1980  * This is solved by allowing FUSE server to retry ioctl with
1981  * necessary in/out iovecs.  Let's assume the ioctl implementation
1982  * needs to read in the following structure.
1983  *
1984  * struct a {
1985  *      char    *buf;
1986  *      size_t  buflen;
1987  * }
1988  *
1989  * On the first callout to FUSE server, inarg->in_size and
1990  * inarg->out_size will be NULL; then, the server completes the ioctl
1991  * with FUSE_IOCTL_RETRY set in out->flags, out->in_iovs set to 1 and
1992  * the actual iov array to
1993  *
1994  * { { .iov_base = inarg.arg,   .iov_len = sizeof(struct a) } }
1995  *
1996  * which tells FUSE to copy in the requested area and retry the ioctl.
1997  * On the second round, the server has access to the structure and
1998  * from that it can tell what to look for next, so on the invocation,
1999  * it sets FUSE_IOCTL_RETRY, out->in_iovs to 2 and iov array to
2000  *
2001  * { { .iov_base = inarg.arg,   .iov_len = sizeof(struct a)     },
2002  *   { .iov_base = a.buf,       .iov_len = a.buflen             } }
2003  *
2004  * FUSE will copy both struct a and the pointed buffer from the
2005  * process doing the ioctl and retry ioctl with both struct a and the
2006  * buffer.
2007  *
2008  * This time, FUSE server has everything it needs and completes ioctl
2009  * without FUSE_IOCTL_RETRY which finishes the ioctl call.
2010  *
2011  * Copying data out works the same way.
2012  *
2013  * Note that if FUSE_IOCTL_UNRESTRICTED is clear, the kernel
2014  * automatically initializes in and out iovs by decoding @cmd with
2015  * _IOC_* macros and the server is not allowed to request RETRY.  This
2016  * limits ioctl data transfers to well-formed ioctls and is the forced
2017  * behavior for all FUSE servers.
2018  */
2019 long fuse_do_ioctl(struct file *file, unsigned int cmd, unsigned long arg,
2020                    unsigned int flags)
2021 {
2022         struct fuse_file *ff = file->private_data;
2023         struct fuse_conn *fc = ff->fc;
2024         struct fuse_ioctl_in inarg = {
2025                 .fh = ff->fh,
2026                 .cmd = cmd,
2027                 .arg = arg,
2028                 .flags = flags
2029         };
2030         struct fuse_ioctl_out outarg;
2031         struct fuse_req *req = NULL;
2032         struct page **pages = NULL;
2033         struct iovec *iov_page = NULL;
2034         struct iovec *in_iov = NULL, *out_iov = NULL;
2035         unsigned int in_iovs = 0, out_iovs = 0, num_pages = 0, max_pages;
2036         size_t in_size, out_size, transferred;
2037         int err;
2038
2039 #if BITS_PER_LONG == 32
2040         inarg.flags |= FUSE_IOCTL_32BIT;
2041 #else
2042         if (flags & FUSE_IOCTL_COMPAT)
2043                 inarg.flags |= FUSE_IOCTL_32BIT;
2044 #endif
2045
2046         /* assume all the iovs returned by client always fits in a page */
2047         BUILD_BUG_ON(sizeof(struct fuse_ioctl_iovec) * FUSE_IOCTL_MAX_IOV > PAGE_SIZE);
2048
2049         err = -ENOMEM;
2050         pages = kcalloc(FUSE_MAX_PAGES_PER_REQ, sizeof(pages[0]), GFP_KERNEL);
2051         iov_page = (struct iovec *) __get_free_page(GFP_KERNEL);
2052         if (!pages || !iov_page)
2053                 goto out;
2054
2055         /*
2056          * If restricted, initialize IO parameters as encoded in @cmd.
2057          * RETRY from server is not allowed.
2058          */
2059         if (!(flags & FUSE_IOCTL_UNRESTRICTED)) {
2060                 struct iovec *iov = iov_page;
2061
2062                 iov->iov_base = (void __user *)arg;
2063                 iov->iov_len = _IOC_SIZE(cmd);
2064
2065                 if (_IOC_DIR(cmd) & _IOC_WRITE) {
2066                         in_iov = iov;
2067                         in_iovs = 1;
2068                 }
2069
2070                 if (_IOC_DIR(cmd) & _IOC_READ) {
2071                         out_iov = iov;
2072                         out_iovs = 1;
2073                 }
2074         }
2075
2076  retry:
2077         inarg.in_size = in_size = iov_length(in_iov, in_iovs);
2078         inarg.out_size = out_size = iov_length(out_iov, out_iovs);
2079
2080         /*
2081          * Out data can be used either for actual out data or iovs,
2082          * make sure there always is at least one page.
2083          */
2084         out_size = max_t(size_t, out_size, PAGE_SIZE);
2085         max_pages = DIV_ROUND_UP(max(in_size, out_size), PAGE_SIZE);
2086
2087         /* make sure there are enough buffer pages and init request with them */
2088         err = -ENOMEM;
2089         if (max_pages > FUSE_MAX_PAGES_PER_REQ)
2090                 goto out;
2091         while (num_pages < max_pages) {
2092                 pages[num_pages] = alloc_page(GFP_KERNEL | __GFP_HIGHMEM);
2093                 if (!pages[num_pages])
2094                         goto out;
2095                 num_pages++;
2096         }
2097
2098         req = fuse_get_req(fc, num_pages);
2099         if (IS_ERR(req)) {
2100                 err = PTR_ERR(req);
2101                 req = NULL;
2102                 goto out;
2103         }
2104         memcpy(req->pages, pages, sizeof(req->pages[0]) * num_pages);
2105         req->num_pages = num_pages;
2106         fuse_page_descs_length_init(req, 0, req->num_pages);
2107
2108         /* okay, let's send it to the client */
2109         req->in.h.opcode = FUSE_IOCTL;
2110         req->in.h.nodeid = ff->nodeid;
2111         req->in.numargs = 1;
2112         req->in.args[0].size = sizeof(inarg);
2113         req->in.args[0].value = &inarg;
2114         if (in_size) {
2115                 req->in.numargs++;
2116                 req->in.args[1].size = in_size;
2117                 req->in.argpages = 1;
2118
2119                 err = fuse_ioctl_copy_user(pages, in_iov, in_iovs, in_size,
2120                                            false);
2121                 if (err)
2122                         goto out;
2123         }
2124
2125         req->out.numargs = 2;
2126         req->out.args[0].size = sizeof(outarg);
2127         req->out.args[0].value = &outarg;
2128         req->out.args[1].size = out_size;
2129         req->out.argpages = 1;
2130         req->out.argvar = 1;
2131
2132         fuse_request_send(fc, req);
2133         err = req->out.h.error;
2134         transferred = req->out.args[1].size;
2135         fuse_put_request(fc, req);
2136         req = NULL;
2137         if (err)
2138                 goto out;
2139
2140         /* did it ask for retry? */
2141         if (outarg.flags & FUSE_IOCTL_RETRY) {
2142                 void *vaddr;
2143
2144                 /* no retry if in restricted mode */
2145                 err = -EIO;
2146                 if (!(flags & FUSE_IOCTL_UNRESTRICTED))
2147                         goto out;
2148
2149                 in_iovs = outarg.in_iovs;
2150                 out_iovs = outarg.out_iovs;
2151
2152                 /*
2153                  * Make sure things are in boundary, separate checks
2154                  * are to protect against overflow.
2155                  */
2156                 err = -ENOMEM;
2157                 if (in_iovs > FUSE_IOCTL_MAX_IOV ||
2158                     out_iovs > FUSE_IOCTL_MAX_IOV ||
2159                     in_iovs + out_iovs > FUSE_IOCTL_MAX_IOV)
2160                         goto out;
2161
2162                 vaddr = kmap_atomic(pages[0]);
2163                 err = fuse_copy_ioctl_iovec(fc, iov_page, vaddr,
2164                                             transferred, in_iovs + out_iovs,
2165                                             (flags & FUSE_IOCTL_COMPAT) != 0);
2166                 kunmap_atomic(vaddr);
2167                 if (err)
2168                         goto out;
2169
2170                 in_iov = iov_page;
2171                 out_iov = in_iov + in_iovs;
2172
2173                 err = fuse_verify_ioctl_iov(in_iov, in_iovs);
2174                 if (err)
2175                         goto out;
2176
2177                 err = fuse_verify_ioctl_iov(out_iov, out_iovs);
2178                 if (err)
2179                         goto out;
2180
2181                 goto retry;
2182         }
2183
2184         err = -EIO;
2185         if (transferred > inarg.out_size)
2186                 goto out;
2187
2188         err = fuse_ioctl_copy_user(pages, out_iov, out_iovs, transferred, true);
2189  out:
2190         if (req)
2191                 fuse_put_request(fc, req);
2192         free_page((unsigned long) iov_page);
2193         while (num_pages)
2194                 __free_page(pages[--num_pages]);
2195         kfree(pages);
2196
2197         return err ? err : outarg.result;
2198 }
2199 EXPORT_SYMBOL_GPL(fuse_do_ioctl);
2200
2201 long fuse_ioctl_common(struct file *file, unsigned int cmd,
2202                        unsigned long arg, unsigned int flags)
2203 {
2204         struct inode *inode = file_inode(file);
2205         struct fuse_conn *fc = get_fuse_conn(inode);
2206
2207         if (!fuse_allow_current_process(fc))
2208                 return -EACCES;
2209
2210         if (is_bad_inode(inode))
2211                 return -EIO;
2212
2213         return fuse_do_ioctl(file, cmd, arg, flags);
2214 }
2215
2216 static long fuse_file_ioctl(struct file *file, unsigned int cmd,
2217                             unsigned long arg)
2218 {
2219         return fuse_ioctl_common(file, cmd, arg, 0);
2220 }
2221
2222 static long fuse_file_compat_ioctl(struct file *file, unsigned int cmd,
2223                                    unsigned long arg)
2224 {
2225         return fuse_ioctl_common(file, cmd, arg, FUSE_IOCTL_COMPAT);
2226 }
2227
2228 /*
2229  * All files which have been polled are linked to RB tree
2230  * fuse_conn->polled_files which is indexed by kh.  Walk the tree and
2231  * find the matching one.
2232  */
2233 static struct rb_node **fuse_find_polled_node(struct fuse_conn *fc, u64 kh,
2234                                               struct rb_node **parent_out)
2235 {
2236         struct rb_node **link = &fc->polled_files.rb_node;
2237         struct rb_node *last = NULL;
2238
2239         while (*link) {
2240                 struct fuse_file *ff;
2241
2242                 last = *link;
2243                 ff = rb_entry(last, struct fuse_file, polled_node);
2244
2245                 if (kh < ff->kh)
2246                         link = &last->rb_left;
2247                 else if (kh > ff->kh)
2248                         link = &last->rb_right;
2249                 else
2250                         return link;
2251         }
2252
2253         if (parent_out)
2254                 *parent_out = last;
2255         return link;
2256 }
2257
2258 /*
2259  * The file is about to be polled.  Make sure it's on the polled_files
2260  * RB tree.  Note that files once added to the polled_files tree are
2261  * not removed before the file is released.  This is because a file
2262  * polled once is likely to be polled again.
2263  */
2264 static void fuse_register_polled_file(struct fuse_conn *fc,
2265                                       struct fuse_file *ff)
2266 {
2267         spin_lock(&fc->lock);
2268         if (RB_EMPTY_NODE(&ff->polled_node)) {
2269                 struct rb_node **link, *parent;
2270
2271                 link = fuse_find_polled_node(fc, ff->kh, &parent);
2272                 BUG_ON(*link);
2273                 rb_link_node(&ff->polled_node, parent, link);
2274                 rb_insert_color(&ff->polled_node, &fc->polled_files);
2275         }
2276         spin_unlock(&fc->lock);
2277 }
2278
2279 unsigned fuse_file_poll(struct file *file, poll_table *wait)
2280 {
2281         struct fuse_file *ff = file->private_data;
2282         struct fuse_conn *fc = ff->fc;
2283         struct fuse_poll_in inarg = { .fh = ff->fh, .kh = ff->kh };
2284         struct fuse_poll_out outarg;
2285         struct fuse_req *req;
2286         int err;
2287
2288         if (fc->no_poll)
2289                 return DEFAULT_POLLMASK;
2290
2291         poll_wait(file, &ff->poll_wait, wait);
2292         inarg.events = (__u32)poll_requested_events(wait);
2293
2294         /*
2295          * Ask for notification iff there's someone waiting for it.
2296          * The client may ignore the flag and always notify.
2297          */
2298         if (waitqueue_active(&ff->poll_wait)) {
2299                 inarg.flags |= FUSE_POLL_SCHEDULE_NOTIFY;
2300                 fuse_register_polled_file(fc, ff);
2301         }
2302
2303         req = fuse_get_req_nopages(fc);
2304         if (IS_ERR(req))
2305                 return POLLERR;
2306
2307         req->in.h.opcode = FUSE_POLL;
2308         req->in.h.nodeid = ff->nodeid;
2309         req->in.numargs = 1;
2310         req->in.args[0].size = sizeof(inarg);
2311         req->in.args[0].value = &inarg;
2312         req->out.numargs = 1;
2313         req->out.args[0].size = sizeof(outarg);
2314         req->out.args[0].value = &outarg;
2315         fuse_request_send(fc, req);
2316         err = req->out.h.error;
2317         fuse_put_request(fc, req);
2318
2319         if (!err)
2320                 return outarg.revents;
2321         if (err == -ENOSYS) {
2322                 fc->no_poll = 1;
2323                 return DEFAULT_POLLMASK;
2324         }
2325         return POLLERR;
2326 }
2327 EXPORT_SYMBOL_GPL(fuse_file_poll);
2328
2329 /*
2330  * This is called from fuse_handle_notify() on FUSE_NOTIFY_POLL and
2331  * wakes up the poll waiters.
2332  */
2333 int fuse_notify_poll_wakeup(struct fuse_conn *fc,
2334                             struct fuse_notify_poll_wakeup_out *outarg)
2335 {
2336         u64 kh = outarg->kh;
2337         struct rb_node **link;
2338
2339         spin_lock(&fc->lock);
2340
2341         link = fuse_find_polled_node(fc, kh, NULL);
2342         if (*link) {
2343                 struct fuse_file *ff;
2344
2345                 ff = rb_entry(*link, struct fuse_file, polled_node);
2346                 wake_up_interruptible_sync(&ff->poll_wait);
2347         }
2348
2349         spin_unlock(&fc->lock);
2350         return 0;
2351 }
2352
2353 static void fuse_do_truncate(struct file *file)
2354 {
2355         struct inode *inode = file->f_mapping->host;
2356         struct iattr attr;
2357
2358         attr.ia_valid = ATTR_SIZE;
2359         attr.ia_size = i_size_read(inode);
2360
2361         attr.ia_file = file;
2362         attr.ia_valid |= ATTR_FILE;
2363
2364         fuse_do_setattr(inode, &attr, file);
2365 }
2366
2367 static ssize_t
2368 fuse_direct_IO(int rw, struct kiocb *iocb, const struct iovec *iov,
2369                         loff_t offset, unsigned long nr_segs)
2370 {
2371         ssize_t ret = 0;
2372         struct file *file = iocb->ki_filp;
2373         struct fuse_file *ff = file->private_data;
2374         loff_t pos = 0;
2375         struct inode *inode;
2376         loff_t i_size;
2377         size_t count = iov_length(iov, nr_segs);
2378         struct fuse_io_priv *io;
2379
2380         pos = offset;
2381         inode = file->f_mapping->host;
2382         i_size = i_size_read(inode);
2383
2384         /* optimization for short read */
2385         if (rw != WRITE && offset + count > i_size) {
2386                 if (offset >= i_size)
2387                         return 0;
2388                 count = i_size - offset;
2389         }
2390
2391         io = kmalloc(sizeof(struct fuse_io_priv), GFP_KERNEL);
2392         if (!io)
2393                 return -ENOMEM;
2394         spin_lock_init(&io->lock);
2395         io->reqs = 1;
2396         io->bytes = -1;
2397         io->size = 0;
2398         io->offset = offset;
2399         io->write = (rw == WRITE);
2400         io->err = 0;
2401         io->file = file;
2402         /*
2403          * By default, we want to optimize all I/Os with async request
2404          * submission to the client filesystem if supported.
2405          */
2406         io->async = ff->fc->async_dio;
2407         io->iocb = iocb;
2408
2409         /*
2410          * We cannot asynchronously extend the size of a file. We have no method
2411          * to wait on real async I/O requests, so we must submit this request
2412          * synchronously.
2413          */
2414         if (!is_sync_kiocb(iocb) && (offset + count > i_size))
2415                 io->async = false;
2416
2417         if (rw == WRITE)
2418                 ret = __fuse_direct_write(io, iov, nr_segs, &pos);
2419         else
2420                 ret = __fuse_direct_read(io, iov, nr_segs, &pos, count);
2421
2422         if (io->async) {
2423                 fuse_aio_complete(io, ret < 0 ? ret : 0, -1);
2424
2425                 /* we have a non-extending, async request, so return */
2426                 if (ret > 0 && !is_sync_kiocb(iocb))
2427                         return -EIOCBQUEUED;
2428
2429                 ret = wait_on_sync_kiocb(iocb);
2430         } else {
2431                 kfree(io);
2432         }
2433
2434         if (rw == WRITE) {
2435                 if (ret > 0)
2436                         fuse_write_update_size(inode, pos);
2437                 else if (ret < 0 && offset + count > i_size)
2438                         fuse_do_truncate(file);
2439         }
2440
2441         return ret;
2442 }
2443
2444 static long fuse_file_fallocate(struct file *file, int mode, loff_t offset,
2445                                 loff_t length)
2446 {
2447         struct fuse_file *ff = file->private_data;
2448         struct fuse_conn *fc = ff->fc;
2449         struct fuse_req *req;
2450         struct fuse_fallocate_in inarg = {
2451                 .fh = ff->fh,
2452                 .offset = offset,
2453                 .length = length,
2454                 .mode = mode
2455         };
2456         int err;
2457
2458         if (fc->no_fallocate)
2459                 return -EOPNOTSUPP;
2460
2461         req = fuse_get_req_nopages(fc);
2462         if (IS_ERR(req))
2463                 return PTR_ERR(req);
2464
2465         req->in.h.opcode = FUSE_FALLOCATE;
2466         req->in.h.nodeid = ff->nodeid;
2467         req->in.numargs = 1;
2468         req->in.args[0].size = sizeof(inarg);
2469         req->in.args[0].value = &inarg;
2470         fuse_request_send(fc, req);
2471         err = req->out.h.error;
2472         if (err == -ENOSYS) {
2473                 fc->no_fallocate = 1;
2474                 err = -EOPNOTSUPP;
2475         }
2476         fuse_put_request(fc, req);
2477
2478         return err;
2479 }
2480
2481 static const struct file_operations fuse_file_operations = {
2482         .llseek         = fuse_file_llseek,
2483         .read           = do_sync_read,
2484         .aio_read       = fuse_file_aio_read,
2485         .write          = do_sync_write,
2486         .aio_write      = fuse_file_aio_write,
2487         .mmap           = fuse_file_mmap,
2488         .open           = fuse_open,
2489         .flush          = fuse_flush,
2490         .release        = fuse_release,
2491         .fsync          = fuse_fsync,
2492         .lock           = fuse_file_lock,
2493         .flock          = fuse_file_flock,
2494         .splice_read    = generic_file_splice_read,
2495         .unlocked_ioctl = fuse_file_ioctl,
2496         .compat_ioctl   = fuse_file_compat_ioctl,
2497         .poll           = fuse_file_poll,
2498         .fallocate      = fuse_file_fallocate,
2499 };
2500
2501 static const struct file_operations fuse_direct_io_file_operations = {
2502         .llseek         = fuse_file_llseek,
2503         .read           = fuse_direct_read,
2504         .write          = fuse_direct_write,
2505         .mmap           = fuse_direct_mmap,
2506         .open           = fuse_open,
2507         .flush          = fuse_flush,
2508         .release        = fuse_release,
2509         .fsync          = fuse_fsync,
2510         .lock           = fuse_file_lock,
2511         .flock          = fuse_file_flock,
2512         .unlocked_ioctl = fuse_file_ioctl,
2513         .compat_ioctl   = fuse_file_compat_ioctl,
2514         .poll           = fuse_file_poll,
2515         .fallocate      = fuse_file_fallocate,
2516         /* no splice_read */
2517 };
2518
2519 static const struct address_space_operations fuse_file_aops  = {
2520         .readpage       = fuse_readpage,
2521         .writepage      = fuse_writepage,
2522         .launder_page   = fuse_launder_page,
2523         .readpages      = fuse_readpages,
2524         .set_page_dirty = __set_page_dirty_nobuffers,
2525         .bmap           = fuse_bmap,
2526         .direct_IO      = fuse_direct_IO,
2527 };
2528
2529 void fuse_init_file_inode(struct inode *inode)
2530 {
2531         inode->i_fop = &fuse_file_operations;
2532         inode->i_data.a_ops = &fuse_file_aops;
2533 }