fuse: don't use inode in helpers called by fuse_direct_io()
[linux-3.10.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
16 static const struct file_operations fuse_direct_io_file_operations;
17
18 static int fuse_send_open(struct inode *inode, struct file *file, int isdir,
19                           struct fuse_open_out *outargp)
20 {
21         struct fuse_conn *fc = get_fuse_conn(inode);
22         struct fuse_open_in inarg;
23         struct fuse_req *req;
24         int err;
25
26         req = fuse_get_req(fc);
27         if (IS_ERR(req))
28                 return PTR_ERR(req);
29
30         memset(&inarg, 0, sizeof(inarg));
31         inarg.flags = file->f_flags & ~(O_CREAT | O_EXCL | O_NOCTTY);
32         if (!fc->atomic_o_trunc)
33                 inarg.flags &= ~O_TRUNC;
34         req->in.h.opcode = isdir ? FUSE_OPENDIR : FUSE_OPEN;
35         req->in.h.nodeid = get_node_id(inode);
36         req->in.numargs = 1;
37         req->in.args[0].size = sizeof(inarg);
38         req->in.args[0].value = &inarg;
39         req->out.numargs = 1;
40         req->out.args[0].size = sizeof(*outargp);
41         req->out.args[0].value = outargp;
42         fuse_request_send(fc, req);
43         err = req->out.h.error;
44         fuse_put_request(fc, req);
45
46         return err;
47 }
48
49 struct fuse_file *fuse_file_alloc(struct fuse_conn *fc)
50 {
51         struct fuse_file *ff;
52
53         ff = kmalloc(sizeof(struct fuse_file), GFP_KERNEL);
54         if (unlikely(!ff))
55                 return NULL;
56
57         ff->fc = fc;
58         ff->reserved_req = fuse_request_alloc();
59         if (unlikely(!ff->reserved_req)) {
60                 kfree(ff);
61                 return NULL;
62         }
63
64         INIT_LIST_HEAD(&ff->write_entry);
65         atomic_set(&ff->count, 0);
66         RB_CLEAR_NODE(&ff->polled_node);
67         init_waitqueue_head(&ff->poll_wait);
68
69         spin_lock(&fc->lock);
70         ff->kh = ++fc->khctr;
71         spin_unlock(&fc->lock);
72
73         return ff;
74 }
75
76 void fuse_file_free(struct fuse_file *ff)
77 {
78         fuse_request_free(ff->reserved_req);
79         kfree(ff);
80 }
81
82 static struct fuse_file *fuse_file_get(struct fuse_file *ff)
83 {
84         atomic_inc(&ff->count);
85         return ff;
86 }
87
88 static void fuse_release_end(struct fuse_conn *fc, struct fuse_req *req)
89 {
90         path_put(&req->misc.release.path);
91 }
92
93 static void fuse_file_put(struct fuse_file *ff)
94 {
95         if (atomic_dec_and_test(&ff->count)) {
96                 struct fuse_req *req = ff->reserved_req;
97                 struct inode *inode = req->misc.release.path.dentry->d_inode;
98                 struct fuse_conn *fc = get_fuse_conn(inode);
99                 req->end = fuse_release_end;
100                 fuse_request_send_background(fc, req);
101                 kfree(ff);
102         }
103 }
104
105 void fuse_finish_open(struct inode *inode, struct file *file,
106                       struct fuse_file *ff, struct fuse_open_out *outarg)
107 {
108         if (outarg->open_flags & FOPEN_DIRECT_IO)
109                 file->f_op = &fuse_direct_io_file_operations;
110         if (!(outarg->open_flags & FOPEN_KEEP_CACHE))
111                 invalidate_inode_pages2(inode->i_mapping);
112         if (outarg->open_flags & FOPEN_NONSEEKABLE)
113                 nonseekable_open(inode, file);
114         ff->fh = outarg->fh;
115         ff->nodeid = get_node_id(inode);
116         file->private_data = fuse_file_get(ff);
117 }
118
119 int fuse_open_common(struct inode *inode, struct file *file, int isdir)
120 {
121         struct fuse_conn *fc = get_fuse_conn(inode);
122         struct fuse_open_out outarg;
123         struct fuse_file *ff;
124         int err;
125
126         /* VFS checks this, but only _after_ ->open() */
127         if (file->f_flags & O_DIRECT)
128                 return -EINVAL;
129
130         err = generic_file_open(inode, file);
131         if (err)
132                 return err;
133
134         ff = fuse_file_alloc(fc);
135         if (!ff)
136                 return -ENOMEM;
137
138         err = fuse_send_open(inode, file, isdir, &outarg);
139         if (err)
140                 fuse_file_free(ff);
141         else {
142                 if (isdir)
143                         outarg.open_flags &= ~FOPEN_DIRECT_IO;
144                 fuse_finish_open(inode, file, ff, &outarg);
145         }
146
147         return err;
148 }
149
150 void fuse_release_fill(struct fuse_file *ff, u64 nodeid, int flags, int opcode)
151 {
152         struct fuse_req *req = ff->reserved_req;
153         struct fuse_release_in *inarg = &req->misc.release.in;
154
155         inarg->fh = ff->fh;
156         inarg->flags = flags;
157         req->in.h.opcode = opcode;
158         req->in.h.nodeid = nodeid;
159         req->in.numargs = 1;
160         req->in.args[0].size = sizeof(struct fuse_release_in);
161         req->in.args[0].value = inarg;
162 }
163
164 int fuse_release_common(struct inode *inode, struct file *file, int isdir)
165 {
166         struct fuse_conn *fc;
167         struct fuse_file *ff;
168         struct fuse_req *req;
169
170         ff = file->private_data;
171         if (unlikely(!ff))
172                 return 0;       /* return value is ignored by VFS */
173
174         fc = get_fuse_conn(inode);
175         req = ff->reserved_req;
176
177         fuse_release_fill(ff, get_node_id(inode), file->f_flags,
178                           isdir ? FUSE_RELEASEDIR : FUSE_RELEASE);
179
180         /* Hold vfsmount and dentry until release is finished */
181         path_get(&file->f_path);
182         req->misc.release.path = file->f_path;
183
184         spin_lock(&fc->lock);
185         list_del(&ff->write_entry);
186         if (!RB_EMPTY_NODE(&ff->polled_node))
187                 rb_erase(&ff->polled_node, &fc->polled_files);
188         spin_unlock(&fc->lock);
189
190         wake_up_interruptible_sync(&ff->poll_wait);
191         /*
192          * Normally this will send the RELEASE request, however if
193          * some asynchronous READ or WRITE requests are outstanding,
194          * the sending will be delayed.
195          */
196         fuse_file_put(ff);
197         return 0;
198 }
199
200 static int fuse_open(struct inode *inode, struct file *file)
201 {
202         return fuse_open_common(inode, file, 0);
203 }
204
205 static int fuse_release(struct inode *inode, struct file *file)
206 {
207         return fuse_release_common(inode, file, 0);
208 }
209
210 /*
211  * Scramble the ID space with XTEA, so that the value of the files_struct
212  * pointer is not exposed to userspace.
213  */
214 u64 fuse_lock_owner_id(struct fuse_conn *fc, fl_owner_t id)
215 {
216         u32 *k = fc->scramble_key;
217         u64 v = (unsigned long) id;
218         u32 v0 = v;
219         u32 v1 = v >> 32;
220         u32 sum = 0;
221         int i;
222
223         for (i = 0; i < 32; i++) {
224                 v0 += ((v1 << 4 ^ v1 >> 5) + v1) ^ (sum + k[sum & 3]);
225                 sum += 0x9E3779B9;
226                 v1 += ((v0 << 4 ^ v0 >> 5) + v0) ^ (sum + k[sum>>11 & 3]);
227         }
228
229         return (u64) v0 + ((u64) v1 << 32);
230 }
231
232 /*
233  * Check if page is under writeback
234  *
235  * This is currently done by walking the list of writepage requests
236  * for the inode, which can be pretty inefficient.
237  */
238 static bool fuse_page_is_writeback(struct inode *inode, pgoff_t index)
239 {
240         struct fuse_conn *fc = get_fuse_conn(inode);
241         struct fuse_inode *fi = get_fuse_inode(inode);
242         struct fuse_req *req;
243         bool found = false;
244
245         spin_lock(&fc->lock);
246         list_for_each_entry(req, &fi->writepages, writepages_entry) {
247                 pgoff_t curr_index;
248
249                 BUG_ON(req->inode != inode);
250                 curr_index = req->misc.write.in.offset >> PAGE_CACHE_SHIFT;
251                 if (curr_index == index) {
252                         found = true;
253                         break;
254                 }
255         }
256         spin_unlock(&fc->lock);
257
258         return found;
259 }
260
261 /*
262  * Wait for page writeback to be completed.
263  *
264  * Since fuse doesn't rely on the VM writeback tracking, this has to
265  * use some other means.
266  */
267 static int fuse_wait_on_page_writeback(struct inode *inode, pgoff_t index)
268 {
269         struct fuse_inode *fi = get_fuse_inode(inode);
270
271         wait_event(fi->page_waitq, !fuse_page_is_writeback(inode, index));
272         return 0;
273 }
274
275 static int fuse_flush(struct file *file, fl_owner_t id)
276 {
277         struct inode *inode = file->f_path.dentry->d_inode;
278         struct fuse_conn *fc = get_fuse_conn(inode);
279         struct fuse_file *ff = file->private_data;
280         struct fuse_req *req;
281         struct fuse_flush_in inarg;
282         int err;
283
284         if (is_bad_inode(inode))
285                 return -EIO;
286
287         if (fc->no_flush)
288                 return 0;
289
290         req = fuse_get_req_nofail(fc, file);
291         memset(&inarg, 0, sizeof(inarg));
292         inarg.fh = ff->fh;
293         inarg.lock_owner = fuse_lock_owner_id(fc, id);
294         req->in.h.opcode = FUSE_FLUSH;
295         req->in.h.nodeid = get_node_id(inode);
296         req->in.numargs = 1;
297         req->in.args[0].size = sizeof(inarg);
298         req->in.args[0].value = &inarg;
299         req->force = 1;
300         fuse_request_send(fc, req);
301         err = req->out.h.error;
302         fuse_put_request(fc, req);
303         if (err == -ENOSYS) {
304                 fc->no_flush = 1;
305                 err = 0;
306         }
307         return err;
308 }
309
310 /*
311  * Wait for all pending writepages on the inode to finish.
312  *
313  * This is currently done by blocking further writes with FUSE_NOWRITE
314  * and waiting for all sent writes to complete.
315  *
316  * This must be called under i_mutex, otherwise the FUSE_NOWRITE usage
317  * could conflict with truncation.
318  */
319 static void fuse_sync_writes(struct inode *inode)
320 {
321         fuse_set_nowrite(inode);
322         fuse_release_nowrite(inode);
323 }
324
325 int fuse_fsync_common(struct file *file, struct dentry *de, int datasync,
326                       int isdir)
327 {
328         struct inode *inode = de->d_inode;
329         struct fuse_conn *fc = get_fuse_conn(inode);
330         struct fuse_file *ff = file->private_data;
331         struct fuse_req *req;
332         struct fuse_fsync_in inarg;
333         int err;
334
335         if (is_bad_inode(inode))
336                 return -EIO;
337
338         if ((!isdir && fc->no_fsync) || (isdir && fc->no_fsyncdir))
339                 return 0;
340
341         /*
342          * Start writeback against all dirty pages of the inode, then
343          * wait for all outstanding writes, before sending the FSYNC
344          * request.
345          */
346         err = write_inode_now(inode, 0);
347         if (err)
348                 return err;
349
350         fuse_sync_writes(inode);
351
352         req = fuse_get_req(fc);
353         if (IS_ERR(req))
354                 return PTR_ERR(req);
355
356         memset(&inarg, 0, sizeof(inarg));
357         inarg.fh = ff->fh;
358         inarg.fsync_flags = datasync ? 1 : 0;
359         req->in.h.opcode = isdir ? FUSE_FSYNCDIR : FUSE_FSYNC;
360         req->in.h.nodeid = get_node_id(inode);
361         req->in.numargs = 1;
362         req->in.args[0].size = sizeof(inarg);
363         req->in.args[0].value = &inarg;
364         fuse_request_send(fc, req);
365         err = req->out.h.error;
366         fuse_put_request(fc, req);
367         if (err == -ENOSYS) {
368                 if (isdir)
369                         fc->no_fsyncdir = 1;
370                 else
371                         fc->no_fsync = 1;
372                 err = 0;
373         }
374         return err;
375 }
376
377 static int fuse_fsync(struct file *file, struct dentry *de, int datasync)
378 {
379         return fuse_fsync_common(file, de, datasync, 0);
380 }
381
382 void fuse_read_fill(struct fuse_req *req, struct file *file, loff_t pos,
383                     size_t count, int opcode)
384 {
385         struct fuse_read_in *inarg = &req->misc.read.in;
386         struct fuse_file *ff = file->private_data;
387
388         inarg->fh = ff->fh;
389         inarg->offset = pos;
390         inarg->size = count;
391         inarg->flags = file->f_flags;
392         req->in.h.opcode = opcode;
393         req->in.h.nodeid = ff->nodeid;
394         req->in.numargs = 1;
395         req->in.args[0].size = sizeof(struct fuse_read_in);
396         req->in.args[0].value = inarg;
397         req->out.argvar = 1;
398         req->out.numargs = 1;
399         req->out.args[0].size = count;
400 }
401
402 static size_t fuse_send_read(struct fuse_req *req, struct file *file,
403                              loff_t pos, size_t count, fl_owner_t owner)
404 {
405         struct fuse_file *ff = file->private_data;
406         struct fuse_conn *fc = ff->fc;
407
408         fuse_read_fill(req, file, pos, count, FUSE_READ);
409         if (owner != NULL) {
410                 struct fuse_read_in *inarg = &req->misc.read.in;
411
412                 inarg->read_flags |= FUSE_READ_LOCKOWNER;
413                 inarg->lock_owner = fuse_lock_owner_id(fc, owner);
414         }
415         fuse_request_send(fc, req);
416         return req->out.args[0].size;
417 }
418
419 static void fuse_read_update_size(struct inode *inode, loff_t size,
420                                   u64 attr_ver)
421 {
422         struct fuse_conn *fc = get_fuse_conn(inode);
423         struct fuse_inode *fi = get_fuse_inode(inode);
424
425         spin_lock(&fc->lock);
426         if (attr_ver == fi->attr_version && size < inode->i_size) {
427                 fi->attr_version = ++fc->attr_version;
428                 i_size_write(inode, size);
429         }
430         spin_unlock(&fc->lock);
431 }
432
433 static int fuse_readpage(struct file *file, struct page *page)
434 {
435         struct inode *inode = page->mapping->host;
436         struct fuse_conn *fc = get_fuse_conn(inode);
437         struct fuse_req *req;
438         size_t num_read;
439         loff_t pos = page_offset(page);
440         size_t count = PAGE_CACHE_SIZE;
441         u64 attr_ver;
442         int err;
443
444         err = -EIO;
445         if (is_bad_inode(inode))
446                 goto out;
447
448         /*
449          * Page writeback can extend beyond the liftime of the
450          * page-cache page, so make sure we read a properly synced
451          * page.
452          */
453         fuse_wait_on_page_writeback(inode, page->index);
454
455         req = fuse_get_req(fc);
456         err = PTR_ERR(req);
457         if (IS_ERR(req))
458                 goto out;
459
460         attr_ver = fuse_get_attr_version(fc);
461
462         req->out.page_zeroing = 1;
463         req->out.argpages = 1;
464         req->num_pages = 1;
465         req->pages[0] = page;
466         num_read = fuse_send_read(req, file, pos, count, NULL);
467         err = req->out.h.error;
468         fuse_put_request(fc, req);
469
470         if (!err) {
471                 /*
472                  * Short read means EOF.  If file size is larger, truncate it
473                  */
474                 if (num_read < count)
475                         fuse_read_update_size(inode, pos + num_read, attr_ver);
476
477                 SetPageUptodate(page);
478         }
479
480         fuse_invalidate_attr(inode); /* atime changed */
481  out:
482         unlock_page(page);
483         return err;
484 }
485
486 static void fuse_readpages_end(struct fuse_conn *fc, struct fuse_req *req)
487 {
488         int i;
489         size_t count = req->misc.read.in.size;
490         size_t num_read = req->out.args[0].size;
491         struct inode *inode = req->pages[0]->mapping->host;
492
493         /*
494          * Short read means EOF.  If file size is larger, truncate it
495          */
496         if (!req->out.h.error && num_read < count) {
497                 loff_t pos = page_offset(req->pages[0]) + num_read;
498                 fuse_read_update_size(inode, pos, req->misc.read.attr_ver);
499         }
500
501         fuse_invalidate_attr(inode); /* atime changed */
502
503         for (i = 0; i < req->num_pages; i++) {
504                 struct page *page = req->pages[i];
505                 if (!req->out.h.error)
506                         SetPageUptodate(page);
507                 else
508                         SetPageError(page);
509                 unlock_page(page);
510         }
511         if (req->ff)
512                 fuse_file_put(req->ff);
513 }
514
515 static void fuse_send_readpages(struct fuse_req *req, struct file *file)
516 {
517         struct fuse_file *ff = file->private_data;
518         struct fuse_conn *fc = ff->fc;
519         loff_t pos = page_offset(req->pages[0]);
520         size_t count = req->num_pages << PAGE_CACHE_SHIFT;
521
522         req->out.argpages = 1;
523         req->out.page_zeroing = 1;
524         fuse_read_fill(req, file, pos, count, FUSE_READ);
525         req->misc.read.attr_ver = fuse_get_attr_version(fc);
526         if (fc->async_read) {
527                 req->ff = fuse_file_get(ff);
528                 req->end = fuse_readpages_end;
529                 fuse_request_send_background(fc, req);
530         } else {
531                 fuse_request_send(fc, req);
532                 fuse_readpages_end(fc, req);
533                 fuse_put_request(fc, req);
534         }
535 }
536
537 struct fuse_fill_data {
538         struct fuse_req *req;
539         struct file *file;
540         struct inode *inode;
541 };
542
543 static int fuse_readpages_fill(void *_data, struct page *page)
544 {
545         struct fuse_fill_data *data = _data;
546         struct fuse_req *req = data->req;
547         struct inode *inode = data->inode;
548         struct fuse_conn *fc = get_fuse_conn(inode);
549
550         fuse_wait_on_page_writeback(inode, page->index);
551
552         if (req->num_pages &&
553             (req->num_pages == FUSE_MAX_PAGES_PER_REQ ||
554              (req->num_pages + 1) * PAGE_CACHE_SIZE > fc->max_read ||
555              req->pages[req->num_pages - 1]->index + 1 != page->index)) {
556                 fuse_send_readpages(req, data->file);
557                 data->req = req = fuse_get_req(fc);
558                 if (IS_ERR(req)) {
559                         unlock_page(page);
560                         return PTR_ERR(req);
561                 }
562         }
563         req->pages[req->num_pages] = page;
564         req->num_pages++;
565         return 0;
566 }
567
568 static int fuse_readpages(struct file *file, struct address_space *mapping,
569                           struct list_head *pages, unsigned nr_pages)
570 {
571         struct inode *inode = mapping->host;
572         struct fuse_conn *fc = get_fuse_conn(inode);
573         struct fuse_fill_data data;
574         int err;
575
576         err = -EIO;
577         if (is_bad_inode(inode))
578                 goto out;
579
580         data.file = file;
581         data.inode = inode;
582         data.req = fuse_get_req(fc);
583         err = PTR_ERR(data.req);
584         if (IS_ERR(data.req))
585                 goto out;
586
587         err = read_cache_pages(mapping, pages, fuse_readpages_fill, &data);
588         if (!err) {
589                 if (data.req->num_pages)
590                         fuse_send_readpages(data.req, file);
591                 else
592                         fuse_put_request(fc, data.req);
593         }
594 out:
595         return err;
596 }
597
598 static ssize_t fuse_file_aio_read(struct kiocb *iocb, const struct iovec *iov,
599                                   unsigned long nr_segs, loff_t pos)
600 {
601         struct inode *inode = iocb->ki_filp->f_mapping->host;
602
603         if (pos + iov_length(iov, nr_segs) > i_size_read(inode)) {
604                 int err;
605                 /*
606                  * If trying to read past EOF, make sure the i_size
607                  * attribute is up-to-date.
608                  */
609                 err = fuse_update_attributes(inode, NULL, iocb->ki_filp, NULL);
610                 if (err)
611                         return err;
612         }
613
614         return generic_file_aio_read(iocb, iov, nr_segs, pos);
615 }
616
617 static void fuse_write_fill(struct fuse_req *req, struct fuse_file *ff,
618                             loff_t pos, size_t count)
619 {
620         struct fuse_write_in *inarg = &req->misc.write.in;
621         struct fuse_write_out *outarg = &req->misc.write.out;
622
623         inarg->fh = ff->fh;
624         inarg->offset = pos;
625         inarg->size = count;
626         req->in.h.opcode = FUSE_WRITE;
627         req->in.h.nodeid = ff->nodeid;
628         req->in.numargs = 2;
629         if (ff->fc->minor < 9)
630                 req->in.args[0].size = FUSE_COMPAT_WRITE_IN_SIZE;
631         else
632                 req->in.args[0].size = sizeof(struct fuse_write_in);
633         req->in.args[0].value = inarg;
634         req->in.args[1].size = count;
635         req->out.numargs = 1;
636         req->out.args[0].size = sizeof(struct fuse_write_out);
637         req->out.args[0].value = outarg;
638 }
639
640 static size_t fuse_send_write(struct fuse_req *req, struct file *file,
641                               loff_t pos, size_t count, fl_owner_t owner)
642 {
643         struct fuse_file *ff = file->private_data;
644         struct fuse_conn *fc = ff->fc;
645         struct fuse_write_in *inarg = &req->misc.write.in;
646
647         fuse_write_fill(req, ff, pos, count);
648         inarg->flags = file->f_flags;
649         if (owner != NULL) {
650                 inarg->write_flags |= FUSE_WRITE_LOCKOWNER;
651                 inarg->lock_owner = fuse_lock_owner_id(fc, owner);
652         }
653         fuse_request_send(fc, req);
654         return req->misc.write.out.size;
655 }
656
657 static int fuse_write_begin(struct file *file, struct address_space *mapping,
658                         loff_t pos, unsigned len, unsigned flags,
659                         struct page **pagep, void **fsdata)
660 {
661         pgoff_t index = pos >> PAGE_CACHE_SHIFT;
662
663         *pagep = grab_cache_page_write_begin(mapping, index, flags);
664         if (!*pagep)
665                 return -ENOMEM;
666         return 0;
667 }
668
669 static void fuse_write_update_size(struct inode *inode, loff_t pos)
670 {
671         struct fuse_conn *fc = get_fuse_conn(inode);
672         struct fuse_inode *fi = get_fuse_inode(inode);
673
674         spin_lock(&fc->lock);
675         fi->attr_version = ++fc->attr_version;
676         if (pos > inode->i_size)
677                 i_size_write(inode, pos);
678         spin_unlock(&fc->lock);
679 }
680
681 static int fuse_buffered_write(struct file *file, struct inode *inode,
682                                loff_t pos, unsigned count, struct page *page)
683 {
684         int err;
685         size_t nres;
686         struct fuse_conn *fc = get_fuse_conn(inode);
687         unsigned offset = pos & (PAGE_CACHE_SIZE - 1);
688         struct fuse_req *req;
689
690         if (is_bad_inode(inode))
691                 return -EIO;
692
693         /*
694          * Make sure writepages on the same page are not mixed up with
695          * plain writes.
696          */
697         fuse_wait_on_page_writeback(inode, page->index);
698
699         req = fuse_get_req(fc);
700         if (IS_ERR(req))
701                 return PTR_ERR(req);
702
703         req->in.argpages = 1;
704         req->num_pages = 1;
705         req->pages[0] = page;
706         req->page_offset = offset;
707         nres = fuse_send_write(req, file, pos, count, NULL);
708         err = req->out.h.error;
709         fuse_put_request(fc, req);
710         if (!err && !nres)
711                 err = -EIO;
712         if (!err) {
713                 pos += nres;
714                 fuse_write_update_size(inode, pos);
715                 if (count == PAGE_CACHE_SIZE)
716                         SetPageUptodate(page);
717         }
718         fuse_invalidate_attr(inode);
719         return err ? err : nres;
720 }
721
722 static int fuse_write_end(struct file *file, struct address_space *mapping,
723                         loff_t pos, unsigned len, unsigned copied,
724                         struct page *page, void *fsdata)
725 {
726         struct inode *inode = mapping->host;
727         int res = 0;
728
729         if (copied)
730                 res = fuse_buffered_write(file, inode, pos, copied, page);
731
732         unlock_page(page);
733         page_cache_release(page);
734         return res;
735 }
736
737 static size_t fuse_send_write_pages(struct fuse_req *req, struct file *file,
738                                     struct inode *inode, loff_t pos,
739                                     size_t count)
740 {
741         size_t res;
742         unsigned offset;
743         unsigned i;
744
745         for (i = 0; i < req->num_pages; i++)
746                 fuse_wait_on_page_writeback(inode, req->pages[i]->index);
747
748         res = fuse_send_write(req, file, pos, count, NULL);
749
750         offset = req->page_offset;
751         count = res;
752         for (i = 0; i < req->num_pages; i++) {
753                 struct page *page = req->pages[i];
754
755                 if (!req->out.h.error && !offset && count >= PAGE_CACHE_SIZE)
756                         SetPageUptodate(page);
757
758                 if (count > PAGE_CACHE_SIZE - offset)
759                         count -= PAGE_CACHE_SIZE - offset;
760                 else
761                         count = 0;
762                 offset = 0;
763
764                 unlock_page(page);
765                 page_cache_release(page);
766         }
767
768         return res;
769 }
770
771 static ssize_t fuse_fill_write_pages(struct fuse_req *req,
772                                struct address_space *mapping,
773                                struct iov_iter *ii, loff_t pos)
774 {
775         struct fuse_conn *fc = get_fuse_conn(mapping->host);
776         unsigned offset = pos & (PAGE_CACHE_SIZE - 1);
777         size_t count = 0;
778         int err;
779
780         req->in.argpages = 1;
781         req->page_offset = offset;
782
783         do {
784                 size_t tmp;
785                 struct page *page;
786                 pgoff_t index = pos >> PAGE_CACHE_SHIFT;
787                 size_t bytes = min_t(size_t, PAGE_CACHE_SIZE - offset,
788                                      iov_iter_count(ii));
789
790                 bytes = min_t(size_t, bytes, fc->max_write - count);
791
792  again:
793                 err = -EFAULT;
794                 if (iov_iter_fault_in_readable(ii, bytes))
795                         break;
796
797                 err = -ENOMEM;
798                 page = grab_cache_page_write_begin(mapping, index, 0);
799                 if (!page)
800                         break;
801
802                 pagefault_disable();
803                 tmp = iov_iter_copy_from_user_atomic(page, ii, offset, bytes);
804                 pagefault_enable();
805                 flush_dcache_page(page);
806
807                 if (!tmp) {
808                         unlock_page(page);
809                         page_cache_release(page);
810                         bytes = min(bytes, iov_iter_single_seg_count(ii));
811                         goto again;
812                 }
813
814                 err = 0;
815                 req->pages[req->num_pages] = page;
816                 req->num_pages++;
817
818                 iov_iter_advance(ii, tmp);
819                 count += tmp;
820                 pos += tmp;
821                 offset += tmp;
822                 if (offset == PAGE_CACHE_SIZE)
823                         offset = 0;
824
825                 if (!fc->big_writes)
826                         break;
827         } while (iov_iter_count(ii) && count < fc->max_write &&
828                  req->num_pages < FUSE_MAX_PAGES_PER_REQ && offset == 0);
829
830         return count > 0 ? count : err;
831 }
832
833 static ssize_t fuse_perform_write(struct file *file,
834                                   struct address_space *mapping,
835                                   struct iov_iter *ii, loff_t pos)
836 {
837         struct inode *inode = mapping->host;
838         struct fuse_conn *fc = get_fuse_conn(inode);
839         int err = 0;
840         ssize_t res = 0;
841
842         if (is_bad_inode(inode))
843                 return -EIO;
844
845         do {
846                 struct fuse_req *req;
847                 ssize_t count;
848
849                 req = fuse_get_req(fc);
850                 if (IS_ERR(req)) {
851                         err = PTR_ERR(req);
852                         break;
853                 }
854
855                 count = fuse_fill_write_pages(req, mapping, ii, pos);
856                 if (count <= 0) {
857                         err = count;
858                 } else {
859                         size_t num_written;
860
861                         num_written = fuse_send_write_pages(req, file, inode,
862                                                             pos, count);
863                         err = req->out.h.error;
864                         if (!err) {
865                                 res += num_written;
866                                 pos += num_written;
867
868                                 /* break out of the loop on short write */
869                                 if (num_written != count)
870                                         err = -EIO;
871                         }
872                 }
873                 fuse_put_request(fc, req);
874         } while (!err && iov_iter_count(ii));
875
876         if (res > 0)
877                 fuse_write_update_size(inode, pos);
878
879         fuse_invalidate_attr(inode);
880
881         return res > 0 ? res : err;
882 }
883
884 static ssize_t fuse_file_aio_write(struct kiocb *iocb, const struct iovec *iov,
885                                    unsigned long nr_segs, loff_t pos)
886 {
887         struct file *file = iocb->ki_filp;
888         struct address_space *mapping = file->f_mapping;
889         size_t count = 0;
890         ssize_t written = 0;
891         struct inode *inode = mapping->host;
892         ssize_t err;
893         struct iov_iter i;
894
895         WARN_ON(iocb->ki_pos != pos);
896
897         err = generic_segment_checks(iov, &nr_segs, &count, VERIFY_READ);
898         if (err)
899                 return err;
900
901         mutex_lock(&inode->i_mutex);
902         vfs_check_frozen(inode->i_sb, SB_FREEZE_WRITE);
903
904         /* We can write back this queue in page reclaim */
905         current->backing_dev_info = mapping->backing_dev_info;
906
907         err = generic_write_checks(file, &pos, &count, S_ISBLK(inode->i_mode));
908         if (err)
909                 goto out;
910
911         if (count == 0)
912                 goto out;
913
914         err = file_remove_suid(file);
915         if (err)
916                 goto out;
917
918         file_update_time(file);
919
920         iov_iter_init(&i, iov, nr_segs, count, 0);
921         written = fuse_perform_write(file, mapping, &i, pos);
922         if (written >= 0)
923                 iocb->ki_pos = pos + written;
924
925 out:
926         current->backing_dev_info = NULL;
927         mutex_unlock(&inode->i_mutex);
928
929         return written ? written : err;
930 }
931
932 static void fuse_release_user_pages(struct fuse_req *req, int write)
933 {
934         unsigned i;
935
936         for (i = 0; i < req->num_pages; i++) {
937                 struct page *page = req->pages[i];
938                 if (write)
939                         set_page_dirty_lock(page);
940                 put_page(page);
941         }
942 }
943
944 static int fuse_get_user_pages(struct fuse_req *req, const char __user *buf,
945                                size_t *nbytesp, int write)
946 {
947         size_t nbytes = *nbytesp;
948         unsigned long user_addr = (unsigned long) buf;
949         unsigned offset = user_addr & ~PAGE_MASK;
950         int npages;
951
952         /* Special case for kernel I/O: can copy directly into the buffer */
953         if (segment_eq(get_fs(), KERNEL_DS)) {
954                 if (write)
955                         req->in.args[1].value = (void *) user_addr;
956                 else
957                         req->out.args[0].value = (void *) user_addr;
958
959                 return 0;
960         }
961
962         nbytes = min_t(size_t, nbytes, FUSE_MAX_PAGES_PER_REQ << PAGE_SHIFT);
963         npages = (nbytes + offset + PAGE_SIZE - 1) >> PAGE_SHIFT;
964         npages = clamp(npages, 1, FUSE_MAX_PAGES_PER_REQ);
965         down_read(&current->mm->mmap_sem);
966         npages = get_user_pages(current, current->mm, user_addr, npages, !write,
967                                 0, req->pages, NULL);
968         up_read(&current->mm->mmap_sem);
969         if (npages < 0)
970                 return npages;
971
972         req->num_pages = npages;
973         req->page_offset = offset;
974
975         if (write)
976                 req->in.argpages = 1;
977         else
978                 req->out.argpages = 1;
979
980         nbytes = (req->num_pages << PAGE_SHIFT) - req->page_offset;
981         *nbytesp = min(*nbytesp, nbytes);
982
983         return 0;
984 }
985
986 static ssize_t fuse_direct_io(struct file *file, const char __user *buf,
987                               size_t count, loff_t *ppos, int write)
988 {
989         struct fuse_file *ff = file->private_data;
990         struct fuse_conn *fc = ff->fc;
991         size_t nmax = write ? fc->max_write : fc->max_read;
992         loff_t pos = *ppos;
993         ssize_t res = 0;
994         struct fuse_req *req;
995
996         req = fuse_get_req(fc);
997         if (IS_ERR(req))
998                 return PTR_ERR(req);
999
1000         while (count) {
1001                 size_t nres;
1002                 fl_owner_t owner = current->files;
1003                 size_t nbytes = min(count, nmax);
1004                 int err = fuse_get_user_pages(req, buf, &nbytes, write);
1005                 if (err) {
1006                         res = err;
1007                         break;
1008                 }
1009
1010                 if (write)
1011                         nres = fuse_send_write(req, file, pos, nbytes, owner);
1012                 else
1013                         nres = fuse_send_read(req, file, pos, nbytes, owner);
1014
1015                 fuse_release_user_pages(req, !write);
1016                 if (req->out.h.error) {
1017                         if (!res)
1018                                 res = req->out.h.error;
1019                         break;
1020                 } else if (nres > nbytes) {
1021                         res = -EIO;
1022                         break;
1023                 }
1024                 count -= nres;
1025                 res += nres;
1026                 pos += nres;
1027                 buf += nres;
1028                 if (nres != nbytes)
1029                         break;
1030                 if (count) {
1031                         fuse_put_request(fc, req);
1032                         req = fuse_get_req(fc);
1033                         if (IS_ERR(req))
1034                                 break;
1035                 }
1036         }
1037         fuse_put_request(fc, req);
1038         if (res > 0)
1039                 *ppos = pos;
1040
1041         return res;
1042 }
1043
1044 static ssize_t fuse_direct_read(struct file *file, char __user *buf,
1045                                      size_t count, loff_t *ppos)
1046 {
1047         ssize_t res;
1048         struct inode *inode = file->f_path.dentry->d_inode;
1049
1050         if (is_bad_inode(inode))
1051                 return -EIO;
1052
1053         res = fuse_direct_io(file, buf, count, ppos, 0);
1054
1055         fuse_invalidate_attr(inode);
1056
1057         return res;
1058 }
1059
1060 static ssize_t fuse_direct_write(struct file *file, const char __user *buf,
1061                                  size_t count, loff_t *ppos)
1062 {
1063         struct inode *inode = file->f_path.dentry->d_inode;
1064         ssize_t res;
1065
1066         if (is_bad_inode(inode))
1067                 return -EIO;
1068
1069         /* Don't allow parallel writes to the same file */
1070         mutex_lock(&inode->i_mutex);
1071         res = generic_write_checks(file, ppos, &count, 0);
1072         if (!res) {
1073                 res = fuse_direct_io(file, buf, count, ppos, 1);
1074                 if (res > 0)
1075                         fuse_write_update_size(inode, *ppos);
1076         }
1077         mutex_unlock(&inode->i_mutex);
1078
1079         fuse_invalidate_attr(inode);
1080
1081         return res;
1082 }
1083
1084 static void fuse_writepage_free(struct fuse_conn *fc, struct fuse_req *req)
1085 {
1086         __free_page(req->pages[0]);
1087         fuse_file_put(req->ff);
1088 }
1089
1090 static void fuse_writepage_finish(struct fuse_conn *fc, struct fuse_req *req)
1091 {
1092         struct inode *inode = req->inode;
1093         struct fuse_inode *fi = get_fuse_inode(inode);
1094         struct backing_dev_info *bdi = inode->i_mapping->backing_dev_info;
1095
1096         list_del(&req->writepages_entry);
1097         dec_bdi_stat(bdi, BDI_WRITEBACK);
1098         dec_zone_page_state(req->pages[0], NR_WRITEBACK_TEMP);
1099         bdi_writeout_inc(bdi);
1100         wake_up(&fi->page_waitq);
1101 }
1102
1103 /* Called under fc->lock, may release and reacquire it */
1104 static void fuse_send_writepage(struct fuse_conn *fc, struct fuse_req *req)
1105 __releases(&fc->lock)
1106 __acquires(&fc->lock)
1107 {
1108         struct fuse_inode *fi = get_fuse_inode(req->inode);
1109         loff_t size = i_size_read(req->inode);
1110         struct fuse_write_in *inarg = &req->misc.write.in;
1111
1112         if (!fc->connected)
1113                 goto out_free;
1114
1115         if (inarg->offset + PAGE_CACHE_SIZE <= size) {
1116                 inarg->size = PAGE_CACHE_SIZE;
1117         } else if (inarg->offset < size) {
1118                 inarg->size = size & (PAGE_CACHE_SIZE - 1);
1119         } else {
1120                 /* Got truncated off completely */
1121                 goto out_free;
1122         }
1123
1124         req->in.args[1].size = inarg->size;
1125         fi->writectr++;
1126         fuse_request_send_background_locked(fc, req);
1127         return;
1128
1129  out_free:
1130         fuse_writepage_finish(fc, req);
1131         spin_unlock(&fc->lock);
1132         fuse_writepage_free(fc, req);
1133         fuse_put_request(fc, req);
1134         spin_lock(&fc->lock);
1135 }
1136
1137 /*
1138  * If fi->writectr is positive (no truncate or fsync going on) send
1139  * all queued writepage requests.
1140  *
1141  * Called with fc->lock
1142  */
1143 void fuse_flush_writepages(struct inode *inode)
1144 __releases(&fc->lock)
1145 __acquires(&fc->lock)
1146 {
1147         struct fuse_conn *fc = get_fuse_conn(inode);
1148         struct fuse_inode *fi = get_fuse_inode(inode);
1149         struct fuse_req *req;
1150
1151         while (fi->writectr >= 0 && !list_empty(&fi->queued_writes)) {
1152                 req = list_entry(fi->queued_writes.next, struct fuse_req, list);
1153                 list_del_init(&req->list);
1154                 fuse_send_writepage(fc, req);
1155         }
1156 }
1157
1158 static void fuse_writepage_end(struct fuse_conn *fc, struct fuse_req *req)
1159 {
1160         struct inode *inode = req->inode;
1161         struct fuse_inode *fi = get_fuse_inode(inode);
1162
1163         mapping_set_error(inode->i_mapping, req->out.h.error);
1164         spin_lock(&fc->lock);
1165         fi->writectr--;
1166         fuse_writepage_finish(fc, req);
1167         spin_unlock(&fc->lock);
1168         fuse_writepage_free(fc, req);
1169 }
1170
1171 static int fuse_writepage_locked(struct page *page)
1172 {
1173         struct address_space *mapping = page->mapping;
1174         struct inode *inode = mapping->host;
1175         struct fuse_conn *fc = get_fuse_conn(inode);
1176         struct fuse_inode *fi = get_fuse_inode(inode);
1177         struct fuse_req *req;
1178         struct fuse_file *ff;
1179         struct page *tmp_page;
1180
1181         set_page_writeback(page);
1182
1183         req = fuse_request_alloc_nofs();
1184         if (!req)
1185                 goto err;
1186
1187         tmp_page = alloc_page(GFP_NOFS | __GFP_HIGHMEM);
1188         if (!tmp_page)
1189                 goto err_free;
1190
1191         spin_lock(&fc->lock);
1192         BUG_ON(list_empty(&fi->write_files));
1193         ff = list_entry(fi->write_files.next, struct fuse_file, write_entry);
1194         req->ff = fuse_file_get(ff);
1195         spin_unlock(&fc->lock);
1196
1197         fuse_write_fill(req, ff, page_offset(page), 0);
1198
1199         copy_highpage(tmp_page, page);
1200         req->misc.write.in.write_flags |= FUSE_WRITE_CACHE;
1201         req->in.argpages = 1;
1202         req->num_pages = 1;
1203         req->pages[0] = tmp_page;
1204         req->page_offset = 0;
1205         req->end = fuse_writepage_end;
1206         req->inode = inode;
1207
1208         inc_bdi_stat(mapping->backing_dev_info, BDI_WRITEBACK);
1209         inc_zone_page_state(tmp_page, NR_WRITEBACK_TEMP);
1210         end_page_writeback(page);
1211
1212         spin_lock(&fc->lock);
1213         list_add(&req->writepages_entry, &fi->writepages);
1214         list_add_tail(&req->list, &fi->queued_writes);
1215         fuse_flush_writepages(inode);
1216         spin_unlock(&fc->lock);
1217
1218         return 0;
1219
1220 err_free:
1221         fuse_request_free(req);
1222 err:
1223         end_page_writeback(page);
1224         return -ENOMEM;
1225 }
1226
1227 static int fuse_writepage(struct page *page, struct writeback_control *wbc)
1228 {
1229         int err;
1230
1231         err = fuse_writepage_locked(page);
1232         unlock_page(page);
1233
1234         return err;
1235 }
1236
1237 static int fuse_launder_page(struct page *page)
1238 {
1239         int err = 0;
1240         if (clear_page_dirty_for_io(page)) {
1241                 struct inode *inode = page->mapping->host;
1242                 err = fuse_writepage_locked(page);
1243                 if (!err)
1244                         fuse_wait_on_page_writeback(inode, page->index);
1245         }
1246         return err;
1247 }
1248
1249 /*
1250  * Write back dirty pages now, because there may not be any suitable
1251  * open files later
1252  */
1253 static void fuse_vma_close(struct vm_area_struct *vma)
1254 {
1255         filemap_write_and_wait(vma->vm_file->f_mapping);
1256 }
1257
1258 /*
1259  * Wait for writeback against this page to complete before allowing it
1260  * to be marked dirty again, and hence written back again, possibly
1261  * before the previous writepage completed.
1262  *
1263  * Block here, instead of in ->writepage(), so that the userspace fs
1264  * can only block processes actually operating on the filesystem.
1265  *
1266  * Otherwise unprivileged userspace fs would be able to block
1267  * unrelated:
1268  *
1269  * - page migration
1270  * - sync(2)
1271  * - try_to_free_pages() with order > PAGE_ALLOC_COSTLY_ORDER
1272  */
1273 static int fuse_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
1274 {
1275         struct page *page = vmf->page;
1276         /*
1277          * Don't use page->mapping as it may become NULL from a
1278          * concurrent truncate.
1279          */
1280         struct inode *inode = vma->vm_file->f_mapping->host;
1281
1282         fuse_wait_on_page_writeback(inode, page->index);
1283         return 0;
1284 }
1285
1286 static struct vm_operations_struct fuse_file_vm_ops = {
1287         .close          = fuse_vma_close,
1288         .fault          = filemap_fault,
1289         .page_mkwrite   = fuse_page_mkwrite,
1290 };
1291
1292 static int fuse_file_mmap(struct file *file, struct vm_area_struct *vma)
1293 {
1294         if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_MAYWRITE)) {
1295                 struct inode *inode = file->f_dentry->d_inode;
1296                 struct fuse_conn *fc = get_fuse_conn(inode);
1297                 struct fuse_inode *fi = get_fuse_inode(inode);
1298                 struct fuse_file *ff = file->private_data;
1299                 /*
1300                  * file may be written through mmap, so chain it onto the
1301                  * inodes's write_file list
1302                  */
1303                 spin_lock(&fc->lock);
1304                 if (list_empty(&ff->write_entry))
1305                         list_add(&ff->write_entry, &fi->write_files);
1306                 spin_unlock(&fc->lock);
1307         }
1308         file_accessed(file);
1309         vma->vm_ops = &fuse_file_vm_ops;
1310         return 0;
1311 }
1312
1313 static int fuse_direct_mmap(struct file *file, struct vm_area_struct *vma)
1314 {
1315         /* Can't provide the coherency needed for MAP_SHARED */
1316         if (vma->vm_flags & VM_MAYSHARE)
1317                 return -ENODEV;
1318
1319         invalidate_inode_pages2(file->f_mapping);
1320
1321         return generic_file_mmap(file, vma);
1322 }
1323
1324 static int convert_fuse_file_lock(const struct fuse_file_lock *ffl,
1325                                   struct file_lock *fl)
1326 {
1327         switch (ffl->type) {
1328         case F_UNLCK:
1329                 break;
1330
1331         case F_RDLCK:
1332         case F_WRLCK:
1333                 if (ffl->start > OFFSET_MAX || ffl->end > OFFSET_MAX ||
1334                     ffl->end < ffl->start)
1335                         return -EIO;
1336
1337                 fl->fl_start = ffl->start;
1338                 fl->fl_end = ffl->end;
1339                 fl->fl_pid = ffl->pid;
1340                 break;
1341
1342         default:
1343                 return -EIO;
1344         }
1345         fl->fl_type = ffl->type;
1346         return 0;
1347 }
1348
1349 static void fuse_lk_fill(struct fuse_req *req, struct file *file,
1350                          const struct file_lock *fl, int opcode, pid_t pid,
1351                          int flock)
1352 {
1353         struct inode *inode = file->f_path.dentry->d_inode;
1354         struct fuse_conn *fc = get_fuse_conn(inode);
1355         struct fuse_file *ff = file->private_data;
1356         struct fuse_lk_in *arg = &req->misc.lk_in;
1357
1358         arg->fh = ff->fh;
1359         arg->owner = fuse_lock_owner_id(fc, fl->fl_owner);
1360         arg->lk.start = fl->fl_start;
1361         arg->lk.end = fl->fl_end;
1362         arg->lk.type = fl->fl_type;
1363         arg->lk.pid = pid;
1364         if (flock)
1365                 arg->lk_flags |= FUSE_LK_FLOCK;
1366         req->in.h.opcode = opcode;
1367         req->in.h.nodeid = get_node_id(inode);
1368         req->in.numargs = 1;
1369         req->in.args[0].size = sizeof(*arg);
1370         req->in.args[0].value = arg;
1371 }
1372
1373 static int fuse_getlk(struct file *file, struct file_lock *fl)
1374 {
1375         struct inode *inode = file->f_path.dentry->d_inode;
1376         struct fuse_conn *fc = get_fuse_conn(inode);
1377         struct fuse_req *req;
1378         struct fuse_lk_out outarg;
1379         int err;
1380
1381         req = fuse_get_req(fc);
1382         if (IS_ERR(req))
1383                 return PTR_ERR(req);
1384
1385         fuse_lk_fill(req, file, fl, FUSE_GETLK, 0, 0);
1386         req->out.numargs = 1;
1387         req->out.args[0].size = sizeof(outarg);
1388         req->out.args[0].value = &outarg;
1389         fuse_request_send(fc, req);
1390         err = req->out.h.error;
1391         fuse_put_request(fc, req);
1392         if (!err)
1393                 err = convert_fuse_file_lock(&outarg.lk, fl);
1394
1395         return err;
1396 }
1397
1398 static int fuse_setlk(struct file *file, struct file_lock *fl, int flock)
1399 {
1400         struct inode *inode = file->f_path.dentry->d_inode;
1401         struct fuse_conn *fc = get_fuse_conn(inode);
1402         struct fuse_req *req;
1403         int opcode = (fl->fl_flags & FL_SLEEP) ? FUSE_SETLKW : FUSE_SETLK;
1404         pid_t pid = fl->fl_type != F_UNLCK ? current->tgid : 0;
1405         int err;
1406
1407         if (fl->fl_lmops && fl->fl_lmops->fl_grant) {
1408                 /* NLM needs asynchronous locks, which we don't support yet */
1409                 return -ENOLCK;
1410         }
1411
1412         /* Unlock on close is handled by the flush method */
1413         if (fl->fl_flags & FL_CLOSE)
1414                 return 0;
1415
1416         req = fuse_get_req(fc);
1417         if (IS_ERR(req))
1418                 return PTR_ERR(req);
1419
1420         fuse_lk_fill(req, file, fl, opcode, pid, flock);
1421         fuse_request_send(fc, req);
1422         err = req->out.h.error;
1423         /* locking is restartable */
1424         if (err == -EINTR)
1425                 err = -ERESTARTSYS;
1426         fuse_put_request(fc, req);
1427         return err;
1428 }
1429
1430 static int fuse_file_lock(struct file *file, int cmd, struct file_lock *fl)
1431 {
1432         struct inode *inode = file->f_path.dentry->d_inode;
1433         struct fuse_conn *fc = get_fuse_conn(inode);
1434         int err;
1435
1436         if (cmd == F_CANCELLK) {
1437                 err = 0;
1438         } else if (cmd == F_GETLK) {
1439                 if (fc->no_lock) {
1440                         posix_test_lock(file, fl);
1441                         err = 0;
1442                 } else
1443                         err = fuse_getlk(file, fl);
1444         } else {
1445                 if (fc->no_lock)
1446                         err = posix_lock_file(file, fl, NULL);
1447                 else
1448                         err = fuse_setlk(file, fl, 0);
1449         }
1450         return err;
1451 }
1452
1453 static int fuse_file_flock(struct file *file, int cmd, struct file_lock *fl)
1454 {
1455         struct inode *inode = file->f_path.dentry->d_inode;
1456         struct fuse_conn *fc = get_fuse_conn(inode);
1457         int err;
1458
1459         if (fc->no_lock) {
1460                 err = flock_lock_file_wait(file, fl);
1461         } else {
1462                 /* emulate flock with POSIX locks */
1463                 fl->fl_owner = (fl_owner_t) file;
1464                 err = fuse_setlk(file, fl, 1);
1465         }
1466
1467         return err;
1468 }
1469
1470 static sector_t fuse_bmap(struct address_space *mapping, sector_t block)
1471 {
1472         struct inode *inode = mapping->host;
1473         struct fuse_conn *fc = get_fuse_conn(inode);
1474         struct fuse_req *req;
1475         struct fuse_bmap_in inarg;
1476         struct fuse_bmap_out outarg;
1477         int err;
1478
1479         if (!inode->i_sb->s_bdev || fc->no_bmap)
1480                 return 0;
1481
1482         req = fuse_get_req(fc);
1483         if (IS_ERR(req))
1484                 return 0;
1485
1486         memset(&inarg, 0, sizeof(inarg));
1487         inarg.block = block;
1488         inarg.blocksize = inode->i_sb->s_blocksize;
1489         req->in.h.opcode = FUSE_BMAP;
1490         req->in.h.nodeid = get_node_id(inode);
1491         req->in.numargs = 1;
1492         req->in.args[0].size = sizeof(inarg);
1493         req->in.args[0].value = &inarg;
1494         req->out.numargs = 1;
1495         req->out.args[0].size = sizeof(outarg);
1496         req->out.args[0].value = &outarg;
1497         fuse_request_send(fc, req);
1498         err = req->out.h.error;
1499         fuse_put_request(fc, req);
1500         if (err == -ENOSYS)
1501                 fc->no_bmap = 1;
1502
1503         return err ? 0 : outarg.block;
1504 }
1505
1506 static loff_t fuse_file_llseek(struct file *file, loff_t offset, int origin)
1507 {
1508         loff_t retval;
1509         struct inode *inode = file->f_path.dentry->d_inode;
1510
1511         mutex_lock(&inode->i_mutex);
1512         switch (origin) {
1513         case SEEK_END:
1514                 retval = fuse_update_attributes(inode, NULL, file, NULL);
1515                 if (retval)
1516                         goto exit;
1517                 offset += i_size_read(inode);
1518                 break;
1519         case SEEK_CUR:
1520                 offset += file->f_pos;
1521         }
1522         retval = -EINVAL;
1523         if (offset >= 0 && offset <= inode->i_sb->s_maxbytes) {
1524                 if (offset != file->f_pos) {
1525                         file->f_pos = offset;
1526                         file->f_version = 0;
1527                 }
1528                 retval = offset;
1529         }
1530 exit:
1531         mutex_unlock(&inode->i_mutex);
1532         return retval;
1533 }
1534
1535 static int fuse_ioctl_copy_user(struct page **pages, struct iovec *iov,
1536                         unsigned int nr_segs, size_t bytes, bool to_user)
1537 {
1538         struct iov_iter ii;
1539         int page_idx = 0;
1540
1541         if (!bytes)
1542                 return 0;
1543
1544         iov_iter_init(&ii, iov, nr_segs, bytes, 0);
1545
1546         while (iov_iter_count(&ii)) {
1547                 struct page *page = pages[page_idx++];
1548                 size_t todo = min_t(size_t, PAGE_SIZE, iov_iter_count(&ii));
1549                 void *kaddr, *map;
1550
1551                 kaddr = map = kmap(page);
1552
1553                 while (todo) {
1554                         char __user *uaddr = ii.iov->iov_base + ii.iov_offset;
1555                         size_t iov_len = ii.iov->iov_len - ii.iov_offset;
1556                         size_t copy = min(todo, iov_len);
1557                         size_t left;
1558
1559                         if (!to_user)
1560                                 left = copy_from_user(kaddr, uaddr, copy);
1561                         else
1562                                 left = copy_to_user(uaddr, kaddr, copy);
1563
1564                         if (unlikely(left))
1565                                 return -EFAULT;
1566
1567                         iov_iter_advance(&ii, copy);
1568                         todo -= copy;
1569                         kaddr += copy;
1570                 }
1571
1572                 kunmap(map);
1573         }
1574
1575         return 0;
1576 }
1577
1578 /*
1579  * For ioctls, there is no generic way to determine how much memory
1580  * needs to be read and/or written.  Furthermore, ioctls are allowed
1581  * to dereference the passed pointer, so the parameter requires deep
1582  * copying but FUSE has no idea whatsoever about what to copy in or
1583  * out.
1584  *
1585  * This is solved by allowing FUSE server to retry ioctl with
1586  * necessary in/out iovecs.  Let's assume the ioctl implementation
1587  * needs to read in the following structure.
1588  *
1589  * struct a {
1590  *      char    *buf;
1591  *      size_t  buflen;
1592  * }
1593  *
1594  * On the first callout to FUSE server, inarg->in_size and
1595  * inarg->out_size will be NULL; then, the server completes the ioctl
1596  * with FUSE_IOCTL_RETRY set in out->flags, out->in_iovs set to 1 and
1597  * the actual iov array to
1598  *
1599  * { { .iov_base = inarg.arg,   .iov_len = sizeof(struct a) } }
1600  *
1601  * which tells FUSE to copy in the requested area and retry the ioctl.
1602  * On the second round, the server has access to the structure and
1603  * from that it can tell what to look for next, so on the invocation,
1604  * it sets FUSE_IOCTL_RETRY, out->in_iovs to 2 and iov array to
1605  *
1606  * { { .iov_base = inarg.arg,   .iov_len = sizeof(struct a)     },
1607  *   { .iov_base = a.buf,       .iov_len = a.buflen             } }
1608  *
1609  * FUSE will copy both struct a and the pointed buffer from the
1610  * process doing the ioctl and retry ioctl with both struct a and the
1611  * buffer.
1612  *
1613  * This time, FUSE server has everything it needs and completes ioctl
1614  * without FUSE_IOCTL_RETRY which finishes the ioctl call.
1615  *
1616  * Copying data out works the same way.
1617  *
1618  * Note that if FUSE_IOCTL_UNRESTRICTED is clear, the kernel
1619  * automatically initializes in and out iovs by decoding @cmd with
1620  * _IOC_* macros and the server is not allowed to request RETRY.  This
1621  * limits ioctl data transfers to well-formed ioctls and is the forced
1622  * behavior for all FUSE servers.
1623  */
1624 static long fuse_file_do_ioctl(struct file *file, unsigned int cmd,
1625                                unsigned long arg, unsigned int flags)
1626 {
1627         struct inode *inode = file->f_dentry->d_inode;
1628         struct fuse_file *ff = file->private_data;
1629         struct fuse_conn *fc = get_fuse_conn(inode);
1630         struct fuse_ioctl_in inarg = {
1631                 .fh = ff->fh,
1632                 .cmd = cmd,
1633                 .arg = arg,
1634                 .flags = flags
1635         };
1636         struct fuse_ioctl_out outarg;
1637         struct fuse_req *req = NULL;
1638         struct page **pages = NULL;
1639         struct page *iov_page = NULL;
1640         struct iovec *in_iov = NULL, *out_iov = NULL;
1641         unsigned int in_iovs = 0, out_iovs = 0, num_pages = 0, max_pages;
1642         size_t in_size, out_size, transferred;
1643         int err;
1644
1645         /* assume all the iovs returned by client always fits in a page */
1646         BUILD_BUG_ON(sizeof(struct iovec) * FUSE_IOCTL_MAX_IOV > PAGE_SIZE);
1647
1648         if (!fuse_allow_task(fc, current))
1649                 return -EACCES;
1650
1651         err = -EIO;
1652         if (is_bad_inode(inode))
1653                 goto out;
1654
1655         err = -ENOMEM;
1656         pages = kzalloc(sizeof(pages[0]) * FUSE_MAX_PAGES_PER_REQ, GFP_KERNEL);
1657         iov_page = alloc_page(GFP_KERNEL);
1658         if (!pages || !iov_page)
1659                 goto out;
1660
1661         /*
1662          * If restricted, initialize IO parameters as encoded in @cmd.
1663          * RETRY from server is not allowed.
1664          */
1665         if (!(flags & FUSE_IOCTL_UNRESTRICTED)) {
1666                 struct iovec *iov = page_address(iov_page);
1667
1668                 iov->iov_base = (void __user *)arg;
1669                 iov->iov_len = _IOC_SIZE(cmd);
1670
1671                 if (_IOC_DIR(cmd) & _IOC_WRITE) {
1672                         in_iov = iov;
1673                         in_iovs = 1;
1674                 }
1675
1676                 if (_IOC_DIR(cmd) & _IOC_READ) {
1677                         out_iov = iov;
1678                         out_iovs = 1;
1679                 }
1680         }
1681
1682  retry:
1683         inarg.in_size = in_size = iov_length(in_iov, in_iovs);
1684         inarg.out_size = out_size = iov_length(out_iov, out_iovs);
1685
1686         /*
1687          * Out data can be used either for actual out data or iovs,
1688          * make sure there always is at least one page.
1689          */
1690         out_size = max_t(size_t, out_size, PAGE_SIZE);
1691         max_pages = DIV_ROUND_UP(max(in_size, out_size), PAGE_SIZE);
1692
1693         /* make sure there are enough buffer pages and init request with them */
1694         err = -ENOMEM;
1695         if (max_pages > FUSE_MAX_PAGES_PER_REQ)
1696                 goto out;
1697         while (num_pages < max_pages) {
1698                 pages[num_pages] = alloc_page(GFP_KERNEL | __GFP_HIGHMEM);
1699                 if (!pages[num_pages])
1700                         goto out;
1701                 num_pages++;
1702         }
1703
1704         req = fuse_get_req(fc);
1705         if (IS_ERR(req)) {
1706                 err = PTR_ERR(req);
1707                 req = NULL;
1708                 goto out;
1709         }
1710         memcpy(req->pages, pages, sizeof(req->pages[0]) * num_pages);
1711         req->num_pages = num_pages;
1712
1713         /* okay, let's send it to the client */
1714         req->in.h.opcode = FUSE_IOCTL;
1715         req->in.h.nodeid = get_node_id(inode);
1716         req->in.numargs = 1;
1717         req->in.args[0].size = sizeof(inarg);
1718         req->in.args[0].value = &inarg;
1719         if (in_size) {
1720                 req->in.numargs++;
1721                 req->in.args[1].size = in_size;
1722                 req->in.argpages = 1;
1723
1724                 err = fuse_ioctl_copy_user(pages, in_iov, in_iovs, in_size,
1725                                            false);
1726                 if (err)
1727                         goto out;
1728         }
1729
1730         req->out.numargs = 2;
1731         req->out.args[0].size = sizeof(outarg);
1732         req->out.args[0].value = &outarg;
1733         req->out.args[1].size = out_size;
1734         req->out.argpages = 1;
1735         req->out.argvar = 1;
1736
1737         fuse_request_send(fc, req);
1738         err = req->out.h.error;
1739         transferred = req->out.args[1].size;
1740         fuse_put_request(fc, req);
1741         req = NULL;
1742         if (err)
1743                 goto out;
1744
1745         /* did it ask for retry? */
1746         if (outarg.flags & FUSE_IOCTL_RETRY) {
1747                 char *vaddr;
1748
1749                 /* no retry if in restricted mode */
1750                 err = -EIO;
1751                 if (!(flags & FUSE_IOCTL_UNRESTRICTED))
1752                         goto out;
1753
1754                 in_iovs = outarg.in_iovs;
1755                 out_iovs = outarg.out_iovs;
1756
1757                 /*
1758                  * Make sure things are in boundary, separate checks
1759                  * are to protect against overflow.
1760                  */
1761                 err = -ENOMEM;
1762                 if (in_iovs > FUSE_IOCTL_MAX_IOV ||
1763                     out_iovs > FUSE_IOCTL_MAX_IOV ||
1764                     in_iovs + out_iovs > FUSE_IOCTL_MAX_IOV)
1765                         goto out;
1766
1767                 err = -EIO;
1768                 if ((in_iovs + out_iovs) * sizeof(struct iovec) != transferred)
1769                         goto out;
1770
1771                 /* okay, copy in iovs and retry */
1772                 vaddr = kmap_atomic(pages[0], KM_USER0);
1773                 memcpy(page_address(iov_page), vaddr, transferred);
1774                 kunmap_atomic(vaddr, KM_USER0);
1775
1776                 in_iov = page_address(iov_page);
1777                 out_iov = in_iov + in_iovs;
1778
1779                 goto retry;
1780         }
1781
1782         err = -EIO;
1783         if (transferred > inarg.out_size)
1784                 goto out;
1785
1786         err = fuse_ioctl_copy_user(pages, out_iov, out_iovs, transferred, true);
1787  out:
1788         if (req)
1789                 fuse_put_request(fc, req);
1790         if (iov_page)
1791                 __free_page(iov_page);
1792         while (num_pages)
1793                 __free_page(pages[--num_pages]);
1794         kfree(pages);
1795
1796         return err ? err : outarg.result;
1797 }
1798
1799 static long fuse_file_ioctl(struct file *file, unsigned int cmd,
1800                             unsigned long arg)
1801 {
1802         return fuse_file_do_ioctl(file, cmd, arg, 0);
1803 }
1804
1805 static long fuse_file_compat_ioctl(struct file *file, unsigned int cmd,
1806                                    unsigned long arg)
1807 {
1808         return fuse_file_do_ioctl(file, cmd, arg, FUSE_IOCTL_COMPAT);
1809 }
1810
1811 /*
1812  * All files which have been polled are linked to RB tree
1813  * fuse_conn->polled_files which is indexed by kh.  Walk the tree and
1814  * find the matching one.
1815  */
1816 static struct rb_node **fuse_find_polled_node(struct fuse_conn *fc, u64 kh,
1817                                               struct rb_node **parent_out)
1818 {
1819         struct rb_node **link = &fc->polled_files.rb_node;
1820         struct rb_node *last = NULL;
1821
1822         while (*link) {
1823                 struct fuse_file *ff;
1824
1825                 last = *link;
1826                 ff = rb_entry(last, struct fuse_file, polled_node);
1827
1828                 if (kh < ff->kh)
1829                         link = &last->rb_left;
1830                 else if (kh > ff->kh)
1831                         link = &last->rb_right;
1832                 else
1833                         return link;
1834         }
1835
1836         if (parent_out)
1837                 *parent_out = last;
1838         return link;
1839 }
1840
1841 /*
1842  * The file is about to be polled.  Make sure it's on the polled_files
1843  * RB tree.  Note that files once added to the polled_files tree are
1844  * not removed before the file is released.  This is because a file
1845  * polled once is likely to be polled again.
1846  */
1847 static void fuse_register_polled_file(struct fuse_conn *fc,
1848                                       struct fuse_file *ff)
1849 {
1850         spin_lock(&fc->lock);
1851         if (RB_EMPTY_NODE(&ff->polled_node)) {
1852                 struct rb_node **link, *parent;
1853
1854                 link = fuse_find_polled_node(fc, ff->kh, &parent);
1855                 BUG_ON(*link);
1856                 rb_link_node(&ff->polled_node, parent, link);
1857                 rb_insert_color(&ff->polled_node, &fc->polled_files);
1858         }
1859         spin_unlock(&fc->lock);
1860 }
1861
1862 static unsigned fuse_file_poll(struct file *file, poll_table *wait)
1863 {
1864         struct inode *inode = file->f_dentry->d_inode;
1865         struct fuse_file *ff = file->private_data;
1866         struct fuse_conn *fc = get_fuse_conn(inode);
1867         struct fuse_poll_in inarg = { .fh = ff->fh, .kh = ff->kh };
1868         struct fuse_poll_out outarg;
1869         struct fuse_req *req;
1870         int err;
1871
1872         if (fc->no_poll)
1873                 return DEFAULT_POLLMASK;
1874
1875         poll_wait(file, &ff->poll_wait, wait);
1876
1877         /*
1878          * Ask for notification iff there's someone waiting for it.
1879          * The client may ignore the flag and always notify.
1880          */
1881         if (waitqueue_active(&ff->poll_wait)) {
1882                 inarg.flags |= FUSE_POLL_SCHEDULE_NOTIFY;
1883                 fuse_register_polled_file(fc, ff);
1884         }
1885
1886         req = fuse_get_req(fc);
1887         if (IS_ERR(req))
1888                 return PTR_ERR(req);
1889
1890         req->in.h.opcode = FUSE_POLL;
1891         req->in.h.nodeid = get_node_id(inode);
1892         req->in.numargs = 1;
1893         req->in.args[0].size = sizeof(inarg);
1894         req->in.args[0].value = &inarg;
1895         req->out.numargs = 1;
1896         req->out.args[0].size = sizeof(outarg);
1897         req->out.args[0].value = &outarg;
1898         fuse_request_send(fc, req);
1899         err = req->out.h.error;
1900         fuse_put_request(fc, req);
1901
1902         if (!err)
1903                 return outarg.revents;
1904         if (err == -ENOSYS) {
1905                 fc->no_poll = 1;
1906                 return DEFAULT_POLLMASK;
1907         }
1908         return POLLERR;
1909 }
1910
1911 /*
1912  * This is called from fuse_handle_notify() on FUSE_NOTIFY_POLL and
1913  * wakes up the poll waiters.
1914  */
1915 int fuse_notify_poll_wakeup(struct fuse_conn *fc,
1916                             struct fuse_notify_poll_wakeup_out *outarg)
1917 {
1918         u64 kh = outarg->kh;
1919         struct rb_node **link;
1920
1921         spin_lock(&fc->lock);
1922
1923         link = fuse_find_polled_node(fc, kh, NULL);
1924         if (*link) {
1925                 struct fuse_file *ff;
1926
1927                 ff = rb_entry(*link, struct fuse_file, polled_node);
1928                 wake_up_interruptible_sync(&ff->poll_wait);
1929         }
1930
1931         spin_unlock(&fc->lock);
1932         return 0;
1933 }
1934
1935 static const struct file_operations fuse_file_operations = {
1936         .llseek         = fuse_file_llseek,
1937         .read           = do_sync_read,
1938         .aio_read       = fuse_file_aio_read,
1939         .write          = do_sync_write,
1940         .aio_write      = fuse_file_aio_write,
1941         .mmap           = fuse_file_mmap,
1942         .open           = fuse_open,
1943         .flush          = fuse_flush,
1944         .release        = fuse_release,
1945         .fsync          = fuse_fsync,
1946         .lock           = fuse_file_lock,
1947         .flock          = fuse_file_flock,
1948         .splice_read    = generic_file_splice_read,
1949         .unlocked_ioctl = fuse_file_ioctl,
1950         .compat_ioctl   = fuse_file_compat_ioctl,
1951         .poll           = fuse_file_poll,
1952 };
1953
1954 static const struct file_operations fuse_direct_io_file_operations = {
1955         .llseek         = fuse_file_llseek,
1956         .read           = fuse_direct_read,
1957         .write          = fuse_direct_write,
1958         .mmap           = fuse_direct_mmap,
1959         .open           = fuse_open,
1960         .flush          = fuse_flush,
1961         .release        = fuse_release,
1962         .fsync          = fuse_fsync,
1963         .lock           = fuse_file_lock,
1964         .flock          = fuse_file_flock,
1965         .unlocked_ioctl = fuse_file_ioctl,
1966         .compat_ioctl   = fuse_file_compat_ioctl,
1967         .poll           = fuse_file_poll,
1968         /* no splice_read */
1969 };
1970
1971 static const struct address_space_operations fuse_file_aops  = {
1972         .readpage       = fuse_readpage,
1973         .writepage      = fuse_writepage,
1974         .launder_page   = fuse_launder_page,
1975         .write_begin    = fuse_write_begin,
1976         .write_end      = fuse_write_end,
1977         .readpages      = fuse_readpages,
1978         .set_page_dirty = __set_page_dirty_nobuffers,
1979         .bmap           = fuse_bmap,
1980 };
1981
1982 void fuse_init_file_inode(struct inode *inode)
1983 {
1984         inode->i_fop = &fuse_file_operations;
1985         inode->i_data.a_ops = &fuse_file_aops;
1986 }