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