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