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