OSDN Git Service

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