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