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