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