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