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