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