~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/fs/fuse/file.c

Version: ~ [ linux-5.7 ] ~ [ linux-5.6.15 ] ~ [ linux-5.5.19 ] ~ [ linux-5.4.43 ] ~ [ linux-5.3.18 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.125 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.182 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.225 ] ~ [ linux-4.8.17 ] ~ [ linux-4.7.10 ] ~ [ linux-4.6.7 ] ~ [ linux-4.5.7 ] ~ [ linux-4.4.225 ] ~ [ linux-4.3.6 ] ~ [ linux-4.2.8 ] ~ [ linux-4.1.52 ] ~ [ linux-4.0.9 ] ~ [ linux-3.19.8 ] ~ [ linux-3.18.140 ] ~ [ linux-3.17.8 ] ~ [ linux-3.16.84 ] ~ [ linux-3.15.10 ] ~ [ linux-3.14.79 ] ~ [ linux-3.13.11 ] ~ [ linux-3.12.74 ] ~ [ linux-3.11.10 ] ~ [ linux-3.10.108 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.5 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

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

~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

kernel.org | git.kernel.org | LWN.net | Project Home | Wiki (Japanese) | Wiki (English) | SVN repository | Mail admin

Linux® is a registered trademark of Linus Torvalds in the United States and other countries.
TOMOYO® is a registered trademark of NTT DATA CORPORATION.

osdn.jp