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