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