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