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