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