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