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