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