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