xref: /linux/fs/ceph/file.c (revision 8b82cacad92ebae9619872a5a69c570eba30140b)
1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/ceph/ceph_debug.h>
3 #include <linux/ceph/striper.h>
4 
5 #include <linux/module.h>
6 #include <linux/sched.h>
7 #include <linux/slab.h>
8 #include <linux/file.h>
9 #include <linux/mount.h>
10 #include <linux/namei.h>
11 #include <linux/writeback.h>
12 #include <linux/falloc.h>
13 #include <linux/iversion.h>
14 #include <linux/ktime.h>
15 #include <linux/splice.h>
16 
17 #include "super.h"
18 #include "mds_client.h"
19 #include "cache.h"
20 #include "io.h"
21 #include "metric.h"
22 #include "subvolume_metrics.h"
23 
24 /*
25  * Record I/O for subvolume metrics tracking.
26  *
27  * Callers must ensure bytes > 0 for reads (ret > 0 check) to avoid counting
28  * EOF as an I/O operation. For writes, the condition is (ret >= 0 && len > 0).
29  */
30 static inline void ceph_record_subvolume_io(struct inode *inode, bool is_write,
31 					    ktime_t start, ktime_t end,
32 					    size_t bytes)
33 {
34 	if (!bytes)
35 		return;
36 
37 	ceph_subvolume_metrics_record_io(ceph_sb_to_mdsc(inode->i_sb),
38 					 ceph_inode(inode),
39 					 is_write, bytes, start, end);
40 }
41 
42 static __le32 ceph_flags_sys2wire(struct ceph_mds_client *mdsc, u32 flags)
43 {
44 	struct ceph_client *cl = mdsc->fsc->client;
45 	u32 wire_flags = 0;
46 
47 	switch (flags & O_ACCMODE) {
48 	case O_RDONLY:
49 		wire_flags |= CEPH_O_RDONLY;
50 		break;
51 	case O_WRONLY:
52 		wire_flags |= CEPH_O_WRONLY;
53 		break;
54 	case O_RDWR:
55 		wire_flags |= CEPH_O_RDWR;
56 		break;
57 	}
58 
59 	flags &= ~O_ACCMODE;
60 
61 #define ceph_sys2wire(a) if (flags & a) { wire_flags |= CEPH_##a; flags &= ~a; }
62 
63 	ceph_sys2wire(O_CREAT);
64 	ceph_sys2wire(O_EXCL);
65 	ceph_sys2wire(O_TRUNC);
66 	ceph_sys2wire(O_DIRECTORY);
67 	ceph_sys2wire(O_NOFOLLOW);
68 
69 #undef ceph_sys2wire
70 
71 	if (flags)
72 		doutc(cl, "unused open flags: %x\n", flags);
73 
74 	return cpu_to_le32(wire_flags);
75 }
76 
77 /*
78  * Ceph file operations
79  *
80  * Implement basic open/close functionality, and implement
81  * read/write.
82  *
83  * We implement three modes of file I/O:
84  *  - buffered uses the generic_file_aio_{read,write} helpers
85  *
86  *  - synchronous is used when there is multi-client read/write
87  *    sharing, avoids the page cache, and synchronously waits for an
88  *    ack from the OSD.
89  *
90  *  - direct io takes the variant of the sync path that references
91  *    user pages directly.
92  *
93  * fsync() flushes and waits on dirty pages, but just queues metadata
94  * for writeback: since the MDS can recover size and mtime there is no
95  * need to wait for MDS acknowledgement.
96  */
97 
98 /*
99  * How many pages to get in one call to iov_iter_get_pages().  This
100  * determines the size of the on-stack array used as a buffer.
101  */
102 #define ITER_GET_BVECS_PAGES	64
103 
104 static ssize_t __iter_get_bvecs(struct iov_iter *iter, size_t maxsize,
105 				struct bio_vec *bvecs)
106 {
107 	size_t size = 0;
108 	int bvec_idx = 0;
109 
110 	if (maxsize > iov_iter_count(iter))
111 		maxsize = iov_iter_count(iter);
112 
113 	while (size < maxsize) {
114 		struct page *pages[ITER_GET_BVECS_PAGES];
115 		ssize_t bytes;
116 		size_t start;
117 		int idx = 0;
118 
119 		bytes = iov_iter_get_pages2(iter, pages, maxsize - size,
120 					   ITER_GET_BVECS_PAGES, &start);
121 		if (bytes < 0)
122 			return size ?: bytes;
123 
124 		size += bytes;
125 
126 		for ( ; bytes; idx++, bvec_idx++) {
127 			int len = min_t(int, bytes, PAGE_SIZE - start);
128 
129 			bvec_set_page(&bvecs[bvec_idx], pages[idx], len, start);
130 			bytes -= len;
131 			start = 0;
132 		}
133 	}
134 
135 	return size;
136 }
137 
138 /*
139  * iov_iter_get_pages() only considers one iov_iter segment, no matter
140  * what maxsize or maxpages are given.  For ITER_BVEC that is a single
141  * page.
142  *
143  * Attempt to get up to @maxsize bytes worth of pages from @iter.
144  * Return the number of bytes in the created bio_vec array, or an error.
145  */
146 static ssize_t iter_get_bvecs_alloc(struct iov_iter *iter, size_t maxsize,
147 				    struct bio_vec **bvecs, int *num_bvecs)
148 {
149 	struct bio_vec *bv;
150 	size_t orig_count = iov_iter_count(iter);
151 	ssize_t bytes;
152 	int npages;
153 
154 	iov_iter_truncate(iter, maxsize);
155 	npages = iov_iter_npages(iter, INT_MAX);
156 	iov_iter_reexpand(iter, orig_count);
157 
158 	/*
159 	 * __iter_get_bvecs() may populate only part of the array -- zero it
160 	 * out.
161 	 */
162 	bv = kvmalloc_objs(*bv, npages, GFP_KERNEL | __GFP_ZERO);
163 	if (!bv)
164 		return -ENOMEM;
165 
166 	bytes = __iter_get_bvecs(iter, maxsize, bv);
167 	if (bytes < 0) {
168 		/*
169 		 * No pages were pinned -- just free the array.
170 		 */
171 		kvfree(bv);
172 		return bytes;
173 	}
174 
175 	*bvecs = bv;
176 	*num_bvecs = npages;
177 	return bytes;
178 }
179 
180 static void put_bvecs(struct bio_vec *bvecs, int num_bvecs, bool should_dirty)
181 {
182 	int i;
183 
184 	for (i = 0; i < num_bvecs; i++) {
185 		if (bvecs[i].bv_page) {
186 			if (should_dirty)
187 				set_page_dirty_lock(bvecs[i].bv_page);
188 			put_page(bvecs[i].bv_page);
189 		}
190 	}
191 	kvfree(bvecs);
192 }
193 
194 /*
195  * Prepare an open request.  Preallocate ceph_cap to avoid an
196  * inopportune ENOMEM later.
197  */
198 static struct ceph_mds_request *
199 prepare_open_request(struct super_block *sb, int flags, int create_mode)
200 {
201 	struct ceph_mds_client *mdsc = ceph_sb_to_mdsc(sb);
202 	struct ceph_mds_request *req;
203 	int want_auth = USE_ANY_MDS;
204 	int op = (flags & O_CREAT) ? CEPH_MDS_OP_CREATE : CEPH_MDS_OP_OPEN;
205 
206 	if (flags & (O_WRONLY|O_RDWR|O_CREAT|O_TRUNC))
207 		want_auth = USE_AUTH_MDS;
208 
209 	req = ceph_mdsc_create_request(mdsc, op, want_auth);
210 	if (IS_ERR(req))
211 		goto out;
212 	req->r_fmode = ceph_flags_to_mode(flags);
213 	req->r_args.open.flags = ceph_flags_sys2wire(mdsc, flags);
214 	req->r_args.open.mode = cpu_to_le32(create_mode);
215 out:
216 	return req;
217 }
218 
219 static int ceph_init_file_info(struct inode *inode, struct file *file,
220 					int fmode, bool isdir)
221 {
222 	struct ceph_inode_info *ci = ceph_inode(inode);
223 	struct ceph_mount_options *opt =
224 		ceph_inode_to_fs_client(&ci->netfs.inode)->mount_options;
225 	struct ceph_client *cl = ceph_inode_to_client(inode);
226 	struct ceph_file_info *fi;
227 	int ret;
228 
229 	doutc(cl, "%p %llx.%llx %p 0%o (%s)\n", inode, ceph_vinop(inode),
230 	      file, inode->i_mode, isdir ? "dir" : "regular");
231 	BUG_ON(inode->i_fop->release != ceph_release);
232 
233 	if (isdir) {
234 		struct ceph_dir_file_info *dfi =
235 			kmem_cache_zalloc(ceph_dir_file_cachep, GFP_KERNEL);
236 		if (!dfi)
237 			return -ENOMEM;
238 
239 		file->private_data = dfi;
240 		fi = &dfi->file_info;
241 		dfi->next_offset = 2;
242 		dfi->readdir_cache_idx = -1;
243 	} else {
244 		fi = kmem_cache_zalloc(ceph_file_cachep, GFP_KERNEL);
245 		if (!fi)
246 			return -ENOMEM;
247 
248 		if (opt->flags & CEPH_MOUNT_OPT_NOPAGECACHE)
249 			fi->flags |= CEPH_F_SYNC;
250 
251 		file->private_data = fi;
252 	}
253 
254 	ceph_get_fmode(ci, fmode, 1);
255 	fi->fmode = fmode;
256 
257 	spin_lock_init(&fi->rw_contexts_lock);
258 	INIT_LIST_HEAD(&fi->rw_contexts);
259 	fi->filp_gen = READ_ONCE(ceph_inode_to_fs_client(inode)->filp_gen);
260 
261 	if ((file->f_mode & FMODE_WRITE) && ceph_has_inline_data(ci)) {
262 		ret = ceph_uninline_data(file);
263 		if (ret < 0)
264 			goto error;
265 	}
266 
267 	return 0;
268 
269 error:
270 	ceph_fscache_unuse_cookie(inode, file->f_mode & FMODE_WRITE);
271 	ceph_put_fmode(ci, fi->fmode, 1);
272 	kmem_cache_free(ceph_file_cachep, fi);
273 	/* wake up anyone waiting for caps on this inode */
274 	wake_up_all(&ci->i_cap_wq);
275 	return ret;
276 }
277 
278 /*
279  * initialize private struct file data.
280  * if we fail, clean up by dropping fmode reference on the ceph_inode
281  */
282 static int ceph_init_file(struct inode *inode, struct file *file, int fmode)
283 {
284 	struct ceph_client *cl = ceph_inode_to_client(inode);
285 	int ret = 0;
286 
287 	switch (inode->i_mode & S_IFMT) {
288 	case S_IFREG:
289 		ceph_fscache_use_cookie(inode, file->f_mode & FMODE_WRITE);
290 		fallthrough;
291 	case S_IFDIR:
292 		ret = ceph_init_file_info(inode, file, fmode,
293 						S_ISDIR(inode->i_mode));
294 		break;
295 
296 	case S_IFLNK:
297 		doutc(cl, "%p %llx.%llx %p 0%o (symlink)\n", inode,
298 		      ceph_vinop(inode), file, inode->i_mode);
299 		break;
300 
301 	default:
302 		doutc(cl, "%p %llx.%llx %p 0%o (special)\n", inode,
303 		      ceph_vinop(inode), file, inode->i_mode);
304 		/*
305 		 * we need to drop the open ref now, since we don't
306 		 * have .release set to ceph_release.
307 		 */
308 		BUG_ON(inode->i_fop->release == ceph_release);
309 
310 		/* call the proper open fop */
311 		ret = inode->i_fop->open(inode, file);
312 	}
313 	return ret;
314 }
315 
316 /*
317  * try renew caps after session gets killed.
318  */
319 int ceph_renew_caps(struct inode *inode, int fmode)
320 {
321 	struct ceph_mds_client *mdsc = ceph_sb_to_mdsc(inode->i_sb);
322 	struct ceph_client *cl = mdsc->fsc->client;
323 	struct ceph_inode_info *ci = ceph_inode(inode);
324 	struct ceph_mds_request *req;
325 	int err, flags, wanted;
326 
327 	spin_lock(&ci->i_ceph_lock);
328 	__ceph_touch_fmode(ci, mdsc, fmode);
329 	wanted = __ceph_caps_file_wanted(ci);
330 	if (__ceph_is_any_real_caps(ci) &&
331 	    (!(wanted & CEPH_CAP_ANY_WR) || ci->i_auth_cap)) {
332 		int issued = __ceph_caps_issued(ci, NULL);
333 		spin_unlock(&ci->i_ceph_lock);
334 		doutc(cl, "%p %llx.%llx want %s issued %s updating mds_wanted\n",
335 		      inode, ceph_vinop(inode), ceph_cap_string(wanted),
336 		      ceph_cap_string(issued));
337 		ceph_check_caps(ci, 0);
338 		return 0;
339 	}
340 	spin_unlock(&ci->i_ceph_lock);
341 
342 	flags = 0;
343 	if ((wanted & CEPH_CAP_FILE_RD) && (wanted & CEPH_CAP_FILE_WR))
344 		flags = O_RDWR;
345 	else if (wanted & CEPH_CAP_FILE_RD)
346 		flags = O_RDONLY;
347 	else if (wanted & CEPH_CAP_FILE_WR)
348 		flags = O_WRONLY;
349 #ifdef O_LAZY
350 	if (wanted & CEPH_CAP_FILE_LAZYIO)
351 		flags |= O_LAZY;
352 #endif
353 
354 	req = prepare_open_request(inode->i_sb, flags, 0);
355 	if (IS_ERR(req)) {
356 		err = PTR_ERR(req);
357 		goto out;
358 	}
359 
360 	req->r_inode = inode;
361 	ihold(inode);
362 	req->r_num_caps = 1;
363 
364 	err = ceph_mdsc_do_request(mdsc, NULL, req);
365 	ceph_mdsc_put_request(req);
366 out:
367 	doutc(cl, "%p %llx.%llx open result=%d\n", inode, ceph_vinop(inode),
368 	      err);
369 	return err < 0 ? err : 0;
370 }
371 
372 /*
373  * If we already have the requisite capabilities, we can satisfy
374  * the open request locally (no need to request new caps from the
375  * MDS).  We do, however, need to inform the MDS (asynchronously)
376  * if our wanted caps set expands.
377  */
378 int ceph_open(struct inode *inode, struct file *file)
379 {
380 	struct ceph_inode_info *ci = ceph_inode(inode);
381 	struct ceph_fs_client *fsc = ceph_sb_to_fs_client(inode->i_sb);
382 	struct ceph_client *cl = fsc->client;
383 	struct ceph_mds_client *mdsc = fsc->mdsc;
384 	struct ceph_mds_request *req;
385 	struct ceph_file_info *fi = file->private_data;
386 	int err;
387 	int flags, fmode, wanted;
388 	struct dentry *dentry;
389 	char *path;
390 	bool do_sync = false;
391 	int mask = MAY_READ;
392 
393 	if (fi) {
394 		doutc(cl, "file %p is already opened\n", file);
395 		return 0;
396 	}
397 
398 	/* filter out O_CREAT|O_EXCL; vfs did that already.  yuck. */
399 	flags = file->f_flags & ~(O_CREAT|O_EXCL);
400 	if (S_ISDIR(inode->i_mode)) {
401 		flags = O_DIRECTORY;  /* mds likes to know */
402 	} else if (S_ISREG(inode->i_mode)) {
403 		err = fscrypt_file_open(inode, file);
404 		if (err)
405 			return err;
406 	}
407 
408 	doutc(cl, "%p %llx.%llx file %p flags %d (%d)\n", inode,
409 	      ceph_vinop(inode), file, flags, file->f_flags);
410 	fmode = ceph_flags_to_mode(flags);
411 	wanted = ceph_caps_for_mode(fmode);
412 
413 	if (fmode & CEPH_FILE_MODE_WR)
414 		mask |= MAY_WRITE;
415 	dentry = d_find_alias(inode);
416 	if (!dentry) {
417 		do_sync = true;
418 	} else {
419 		struct ceph_path_info path_info = {0};
420 		path = ceph_mdsc_build_path(mdsc, dentry, &path_info, 0);
421 		if (IS_ERR(path)) {
422 			do_sync = true;
423 			err = 0;
424 		} else {
425 			err = ceph_mds_check_access(mdsc, path, mask);
426 		}
427 		ceph_mdsc_free_path_info(&path_info);
428 		dput(dentry);
429 
430 		/* For none EACCES cases will let the MDS do the mds auth check */
431 		if (err == -EACCES) {
432 			return err;
433 		} else if (err < 0) {
434 			do_sync = true;
435 			err = 0;
436 		}
437 	}
438 
439 	/* snapped files are read-only */
440 	if (ceph_snap(inode) != CEPH_NOSNAP && (file->f_mode & FMODE_WRITE))
441 		return -EROFS;
442 
443 	/* trivially open snapdir */
444 	if (ceph_snap(inode) == CEPH_SNAPDIR) {
445 		return ceph_init_file(inode, file, fmode);
446 	}
447 
448 	/*
449 	 * No need to block if we have caps on the auth MDS (for
450 	 * write) or any MDS (for read).  Update wanted set
451 	 * asynchronously.
452 	 */
453 	spin_lock(&ci->i_ceph_lock);
454 	if (!do_sync && __ceph_is_any_real_caps(ci) &&
455 	    (((fmode & CEPH_FILE_MODE_WR) == 0) || ci->i_auth_cap)) {
456 		int mds_wanted = __ceph_caps_mds_wanted(ci, true);
457 		int issued = __ceph_caps_issued(ci, NULL);
458 
459 		doutc(cl, "open %p fmode %d want %s issued %s using existing\n",
460 		      inode, fmode, ceph_cap_string(wanted),
461 		      ceph_cap_string(issued));
462 		__ceph_touch_fmode(ci, mdsc, fmode);
463 		spin_unlock(&ci->i_ceph_lock);
464 
465 		/* adjust wanted? */
466 		if ((issued & wanted) != wanted &&
467 		    (mds_wanted & wanted) != wanted &&
468 		    ceph_snap(inode) != CEPH_SNAPDIR)
469 			ceph_check_caps(ci, 0);
470 
471 		return ceph_init_file(inode, file, fmode);
472 	} else if (!do_sync && ceph_snap(inode) != CEPH_NOSNAP &&
473 		   (ci->i_snap_caps & wanted) == wanted) {
474 		__ceph_touch_fmode(ci, mdsc, fmode);
475 		spin_unlock(&ci->i_ceph_lock);
476 		return ceph_init_file(inode, file, fmode);
477 	}
478 
479 	spin_unlock(&ci->i_ceph_lock);
480 
481 	doutc(cl, "open fmode %d wants %s\n", fmode, ceph_cap_string(wanted));
482 	req = prepare_open_request(inode->i_sb, flags, 0);
483 	if (IS_ERR(req)) {
484 		err = PTR_ERR(req);
485 		goto out;
486 	}
487 	req->r_inode = inode;
488 	ihold(inode);
489 
490 	req->r_num_caps = 1;
491 	err = ceph_mdsc_do_request(mdsc, NULL, req);
492 	if (!err)
493 		err = ceph_init_file(inode, file, req->r_fmode);
494 	ceph_mdsc_put_request(req);
495 	doutc(cl, "open result=%d on %llx.%llx\n", err, ceph_vinop(inode));
496 out:
497 	return err;
498 }
499 
500 /* Clone the layout from a synchronous create, if the dir now has Dc caps */
501 static void
502 cache_file_layout(struct inode *dst, struct inode *src)
503 {
504 	struct ceph_inode_info *cdst = ceph_inode(dst);
505 	struct ceph_inode_info *csrc = ceph_inode(src);
506 
507 	spin_lock(&cdst->i_ceph_lock);
508 	if ((__ceph_caps_issued(cdst, NULL) & CEPH_CAP_DIR_CREATE) &&
509 	    !ceph_file_layout_is_valid(&cdst->i_cached_layout)) {
510 		memcpy(&cdst->i_cached_layout, &csrc->i_layout,
511 			sizeof(cdst->i_cached_layout));
512 		rcu_assign_pointer(cdst->i_cached_layout.pool_ns,
513 				   ceph_try_get_string(csrc->i_layout.pool_ns));
514 	}
515 	spin_unlock(&cdst->i_ceph_lock);
516 }
517 
518 /*
519  * Try to set up an async create. We need caps, a file layout, and inode number,
520  * and either a lease on the dentry or complete dir info. If any of those
521  * criteria are not satisfied, then return false and the caller can go
522  * synchronous.
523  */
524 static int try_prep_async_create(struct inode *dir, struct dentry *dentry,
525 				 struct ceph_file_layout *lo, u64 *pino)
526 {
527 	struct ceph_inode_info *ci = ceph_inode(dir);
528 	struct ceph_dentry_info *di = ceph_dentry(dentry);
529 	int got = 0, want = CEPH_CAP_FILE_EXCL | CEPH_CAP_DIR_CREATE;
530 	u64 ino;
531 
532 	spin_lock(&ci->i_ceph_lock);
533 	/* No auth cap means no chance for Dc caps */
534 	if (!ci->i_auth_cap)
535 		goto no_async;
536 
537 	/* Any delegated inos? */
538 	if (xa_empty(&ci->i_auth_cap->session->s_delegated_inos))
539 		goto no_async;
540 
541 	if (!ceph_file_layout_is_valid(&ci->i_cached_layout))
542 		goto no_async;
543 
544 	if ((__ceph_caps_issued(ci, NULL) & want) != want)
545 		goto no_async;
546 
547 	if (d_in_lookup(dentry)) {
548 		if (!__ceph_dir_is_complete(ci))
549 			goto no_async;
550 		spin_lock(&dentry->d_lock);
551 		di->lease_shared_gen = atomic_read(&ci->i_shared_gen);
552 		spin_unlock(&dentry->d_lock);
553 	} else if (atomic_read(&ci->i_shared_gen) !=
554 		   READ_ONCE(di->lease_shared_gen)) {
555 		goto no_async;
556 	}
557 
558 	ino = ceph_get_deleg_ino(ci->i_auth_cap->session);
559 	if (!ino)
560 		goto no_async;
561 
562 	*pino = ino;
563 	ceph_take_cap_refs(ci, want, false);
564 	memcpy(lo, &ci->i_cached_layout, sizeof(*lo));
565 	rcu_assign_pointer(lo->pool_ns,
566 			   ceph_try_get_string(ci->i_cached_layout.pool_ns));
567 	got = want;
568 no_async:
569 	spin_unlock(&ci->i_ceph_lock);
570 	return got;
571 }
572 
573 static void restore_deleg_ino(struct inode *dir, u64 ino)
574 {
575 	struct ceph_client *cl = ceph_inode_to_client(dir);
576 	struct ceph_inode_info *ci = ceph_inode(dir);
577 	struct ceph_mds_session *s = NULL;
578 
579 	spin_lock(&ci->i_ceph_lock);
580 	if (ci->i_auth_cap)
581 		s = ceph_get_mds_session(ci->i_auth_cap->session);
582 	spin_unlock(&ci->i_ceph_lock);
583 	if (s) {
584 		int err = ceph_restore_deleg_ino(s, ino);
585 		if (err)
586 			pr_warn_client(cl,
587 				"unable to restore delegated ino 0x%llx to session: %d\n",
588 				ino, err);
589 		ceph_put_mds_session(s);
590 	}
591 }
592 
593 static void wake_async_create_waiters(struct inode *inode,
594 				      struct ceph_mds_session *session)
595 {
596 	struct ceph_inode_info *ci = ceph_inode(inode);
597 	bool check_cap = false;
598 
599 	spin_lock(&ci->i_ceph_lock);
600 	if (ci->i_ceph_flags & CEPH_I_ASYNC_CREATE) {
601 		clear_and_wake_up_bit(CEPH_ASYNC_CREATE_BIT, &ci->i_ceph_flags);
602 
603 		if (ci->i_ceph_flags & CEPH_I_ASYNC_CHECK_CAPS) {
604 			ci->i_ceph_flags &= ~CEPH_I_ASYNC_CHECK_CAPS;
605 			check_cap = true;
606 		}
607 	}
608 	ceph_kick_flushing_inode_caps(session, ci);
609 	spin_unlock(&ci->i_ceph_lock);
610 
611 	if (check_cap)
612 		ceph_check_caps(ci, CHECK_CAPS_FLUSH);
613 }
614 
615 static void ceph_async_create_cb(struct ceph_mds_client *mdsc,
616                                  struct ceph_mds_request *req)
617 {
618 	struct ceph_client *cl = mdsc->fsc->client;
619 	struct dentry *dentry = req->r_dentry;
620 	struct inode *dinode = d_inode(dentry);
621 	struct inode *tinode = req->r_target_inode;
622 	int result = req->r_err ? req->r_err :
623 			le32_to_cpu(req->r_reply_info.head->result);
624 
625 	WARN_ON_ONCE(dinode && tinode && dinode != tinode);
626 
627 	/* MDS changed -- caller must resubmit */
628 	if (result == -EJUKEBOX)
629 		goto out;
630 
631 	mapping_set_error(req->r_parent->i_mapping, result);
632 
633 	if (result) {
634 		struct ceph_path_info path_info = {0};
635 		char *path = ceph_mdsc_build_path(mdsc, req->r_dentry, &path_info, 0);
636 
637 		pr_warn_client(cl,
638 			"async create failure path=(%llx)%s result=%d!\n",
639 			path_info.vino.ino, IS_ERR(path) ? "<<bad>>" : path, result);
640 		ceph_mdsc_free_path_info(&path_info);
641 
642 		ceph_dir_clear_complete(req->r_parent);
643 		if (!d_unhashed(dentry))
644 			d_drop(dentry);
645 
646 		if (dinode) {
647 			mapping_set_error(dinode->i_mapping, result);
648 			ceph_inode_shutdown(dinode);
649 			wake_async_create_waiters(dinode, req->r_session);
650 		}
651 	}
652 
653 	if (tinode) {
654 		u64 ino = ceph_vino(tinode).ino;
655 
656 		if (req->r_deleg_ino != ino)
657 			pr_warn_client(cl,
658 				"inode number mismatch! err=%d deleg_ino=0x%llx target=0x%llx\n",
659 				req->r_err, req->r_deleg_ino, ino);
660 
661 		mapping_set_error(tinode->i_mapping, result);
662 		wake_async_create_waiters(tinode, req->r_session);
663 	} else if (!result) {
664 		pr_warn_client(cl, "no req->r_target_inode for 0x%llx\n",
665 			       req->r_deleg_ino);
666 	}
667 out:
668 	ceph_mdsc_release_dir_caps(req);
669 }
670 
671 static int ceph_finish_async_create(struct inode *dir, struct inode *inode,
672 				    struct dentry *dentry,
673 				    struct file *file, umode_t mode,
674 				    struct ceph_mds_request *req,
675 				    struct ceph_acl_sec_ctx *as_ctx,
676 				    struct ceph_file_layout *lo)
677 {
678 	int ret;
679 	char xattr_buf[4];
680 	struct ceph_mds_reply_inode in = { };
681 	struct ceph_mds_reply_info_in iinfo = { .in = &in };
682 	struct ceph_inode_info *ci = ceph_inode(dir);
683 	struct ceph_dentry_info *di = ceph_dentry(dentry);
684 	struct timespec64 now;
685 	struct ceph_string *pool_ns;
686 	struct ceph_mds_client *mdsc = ceph_sb_to_mdsc(dir->i_sb);
687 	struct ceph_client *cl = mdsc->fsc->client;
688 	struct ceph_vino vino = { .ino = req->r_deleg_ino,
689 				  .snap = CEPH_NOSNAP };
690 
691 	ktime_get_real_ts64(&now);
692 
693 	iinfo.inline_version = CEPH_INLINE_NONE;
694 	iinfo.change_attr = 1;
695 	ceph_encode_timespec64(&iinfo.btime, &now);
696 
697 	if (req->r_pagelist) {
698 		iinfo.xattr_len = req->r_pagelist->length;
699 		iinfo.xattr_data = req->r_pagelist->mapped_tail;
700 	} else {
701 		/* fake it */
702 		iinfo.xattr_len = ARRAY_SIZE(xattr_buf);
703 		iinfo.xattr_data = xattr_buf;
704 		memset(iinfo.xattr_data, 0, iinfo.xattr_len);
705 	}
706 
707 	in.ino = cpu_to_le64(vino.ino);
708 	in.snapid = cpu_to_le64(CEPH_NOSNAP);
709 	in.version = cpu_to_le64(1);	// ???
710 	in.cap.caps = in.cap.wanted = cpu_to_le32(CEPH_CAP_ALL_FILE);
711 	in.cap.cap_id = cpu_to_le64(1);
712 	in.cap.realm = cpu_to_le64(ci->i_snap_realm->ino);
713 	in.cap.flags = CEPH_CAP_FLAG_AUTH;
714 	in.ctime = in.mtime = in.atime = iinfo.btime;
715 	in.truncate_seq = cpu_to_le32(1);
716 	in.truncate_size = cpu_to_le64(-1ULL);
717 	in.xattr_version = cpu_to_le64(1);
718 	in.uid = cpu_to_le32(from_kuid(&init_user_ns,
719 				       mapped_fsuid(req->r_mnt_idmap,
720 						    &init_user_ns)));
721 	if (dir->i_mode & S_ISGID) {
722 		in.gid = cpu_to_le32(from_kgid(&init_user_ns, dir->i_gid));
723 
724 		/* Directories always inherit the setgid bit. */
725 		if (S_ISDIR(mode))
726 			mode |= S_ISGID;
727 	} else {
728 		in.gid = cpu_to_le32(from_kgid(&init_user_ns,
729 				     mapped_fsgid(req->r_mnt_idmap,
730 						  &init_user_ns)));
731 	}
732 	in.mode = cpu_to_le32((u32)mode);
733 
734 	in.nlink = cpu_to_le32(1);
735 	in.max_size = cpu_to_le64(lo->stripe_unit);
736 
737 	ceph_file_layout_to_legacy(lo, &in.layout);
738 	/* lo is private, so pool_ns can't change */
739 	pool_ns = rcu_dereference_raw(lo->pool_ns);
740 	if (pool_ns) {
741 		iinfo.pool_ns_len = pool_ns->len;
742 		iinfo.pool_ns_data = pool_ns->str;
743 	}
744 
745 	down_read(&mdsc->snap_rwsem);
746 	ret = ceph_fill_inode(inode, NULL, &iinfo, NULL, req->r_session,
747 			      req->r_fmode, NULL);
748 	up_read(&mdsc->snap_rwsem);
749 	if (ret) {
750 		doutc(cl, "failed to fill inode: %d\n", ret);
751 		ceph_dir_clear_complete(dir);
752 		if (!d_unhashed(dentry))
753 			d_drop(dentry);
754 		discard_new_inode(inode);
755 	} else {
756 		struct dentry *dn;
757 
758 		doutc(cl, "d_adding new inode 0x%llx to 0x%llx/%s\n",
759 		      vino.ino, ceph_ino(dir), dentry->d_name.name);
760 		ceph_dir_clear_ordered(dir);
761 		ceph_init_inode_acls(inode, as_ctx);
762 		if (inode_state_read_once(inode) & I_NEW) {
763 			/*
764 			 * If it's not I_NEW, then someone created this before
765 			 * we got here. Assume the server is aware of it at
766 			 * that point and don't worry about setting
767 			 * CEPH_I_ASYNC_CREATE.
768 			 */
769 			ceph_inode(inode)->i_ceph_flags = CEPH_I_ASYNC_CREATE;
770 			unlock_new_inode(inode);
771 		}
772 		if (d_in_lookup(dentry) || d_really_is_negative(dentry)) {
773 			if (!d_unhashed(dentry))
774 				d_drop(dentry);
775 			dn = d_splice_alias(inode, dentry);
776 			WARN_ON_ONCE(dn && dn != dentry);
777 		}
778 		file->f_mode |= FMODE_CREATED;
779 		ret = finish_open(file, dentry, ceph_open);
780 	}
781 
782 	spin_lock(&dentry->d_lock);
783 	clear_and_wake_up_bit(CEPH_DENTRY_ASYNC_CREATE_BIT, &di->flags);
784 	spin_unlock(&dentry->d_lock);
785 
786 	return ret;
787 }
788 
789 /*
790  * Do a lookup + open with a single request.  If we get a non-existent
791  * file or symlink, return 1 so the VFS can retry.
792  */
793 int ceph_atomic_open(struct inode *dir, struct dentry *dentry,
794 		     struct file *file, unsigned flags, umode_t mode)
795 {
796 	struct mnt_idmap *idmap = file_mnt_idmap(file);
797 	struct ceph_fs_client *fsc = ceph_sb_to_fs_client(dir->i_sb);
798 	struct ceph_client *cl = fsc->client;
799 	struct ceph_mds_client *mdsc = fsc->mdsc;
800 	struct ceph_mds_request *req;
801 	struct inode *new_inode = NULL;
802 	struct dentry *dn;
803 	struct ceph_acl_sec_ctx as_ctx = {};
804 	bool try_async = ceph_test_mount_opt(fsc, ASYNC_DIROPS);
805 	int mask;
806 	int err;
807 	char *path;
808 
809 	doutc(cl, "%p %llx.%llx dentry %p '%pd' %s flags %d mode 0%o\n",
810 	      dir, ceph_vinop(dir), dentry, dentry,
811 	      d_unhashed(dentry) ? "unhashed" : "hashed", flags, mode);
812 
813 	if (dentry->d_name.len > NAME_MAX)
814 		return -ENAMETOOLONG;
815 
816 	err = ceph_wait_on_conflict_unlink(dentry);
817 	if (err)
818 		return err;
819 	/*
820 	 * Do not truncate the file, since atomic_open is called before the
821 	 * permission check. The caller will do the truncation afterward.
822 	 */
823 	flags &= ~O_TRUNC;
824 
825 	dn = d_find_alias(dir);
826 	if (!dn) {
827 		try_async = false;
828 	} else {
829 		struct ceph_path_info path_info = {0};
830 		path = ceph_mdsc_build_path(mdsc, dn, &path_info, 0);
831 		if (IS_ERR(path)) {
832 			try_async = false;
833 			err = 0;
834 		} else {
835 			int fmode = ceph_flags_to_mode(flags);
836 
837 			mask = MAY_READ;
838 			if (fmode & CEPH_FILE_MODE_WR)
839 				mask |= MAY_WRITE;
840 			err = ceph_mds_check_access(mdsc, path, mask);
841 		}
842 		ceph_mdsc_free_path_info(&path_info);
843 		dput(dn);
844 
845 		/* For none EACCES cases will let the MDS do the mds auth check */
846 		if (err == -EACCES) {
847 			return err;
848 		} else if (err < 0) {
849 			try_async = false;
850 			err = 0;
851 		}
852 	}
853 
854 retry:
855 	if (flags & O_CREAT) {
856 		if (ceph_quota_is_max_files_exceeded(dir))
857 			return -EDQUOT;
858 
859 		new_inode = ceph_new_inode(dir, dentry, &mode, &as_ctx);
860 		if (IS_ERR(new_inode)) {
861 			err = PTR_ERR(new_inode);
862 			goto out_ctx;
863 		}
864 		/* Async create can't handle more than a page of xattrs */
865 		if (as_ctx.pagelist &&
866 		    !list_is_singular(&as_ctx.pagelist->head))
867 			try_async = false;
868 	} else if (!d_in_lookup(dentry)) {
869 		/* If it's not being looked up, it's negative */
870 		return -ENOENT;
871 	}
872 
873 	/* do the open */
874 	req = prepare_open_request(dir->i_sb, flags, mode);
875 	if (IS_ERR(req)) {
876 		err = PTR_ERR(req);
877 		goto out_ctx;
878 	}
879 	req->r_dentry = dget(dentry);
880 	req->r_num_caps = 2;
881 	mask = CEPH_STAT_CAP_INODE | CEPH_CAP_AUTH_SHARED;
882 	if (ceph_security_xattr_wanted(dir))
883 		mask |= CEPH_CAP_XATTR_SHARED;
884 	req->r_args.open.mask = cpu_to_le32(mask);
885 	req->r_parent = dir;
886 	if (req->r_op == CEPH_MDS_OP_CREATE)
887 		req->r_mnt_idmap = mnt_idmap_get(idmap);
888 	ihold(dir);
889 	if (IS_ENCRYPTED(dir)) {
890 		set_bit(CEPH_MDS_R_FSCRYPT_FILE, &req->r_req_flags);
891 		err = fscrypt_prepare_lookup_partial(dir, dentry);
892 		if (err < 0)
893 			goto out_req;
894 	}
895 
896 	if (flags & O_CREAT) {
897 		struct ceph_file_layout lo;
898 
899 		req->r_dentry_drop = CEPH_CAP_FILE_SHARED | CEPH_CAP_AUTH_EXCL |
900 				     CEPH_CAP_XATTR_EXCL;
901 		req->r_dentry_unless = CEPH_CAP_FILE_EXCL;
902 
903 		ceph_as_ctx_to_req(req, &as_ctx);
904 
905 		if (try_async && (req->r_dir_caps =
906 				  try_prep_async_create(dir, dentry, &lo,
907 							&req->r_deleg_ino))) {
908 			struct ceph_vino vino = { .ino = req->r_deleg_ino,
909 						  .snap = CEPH_NOSNAP };
910 			struct ceph_dentry_info *di = ceph_dentry(dentry);
911 
912 			set_bit(CEPH_MDS_R_ASYNC, &req->r_req_flags);
913 			req->r_args.open.flags |= cpu_to_le32(CEPH_O_EXCL);
914 			req->r_callback = ceph_async_create_cb;
915 
916 			/* Hash inode before RPC */
917 			new_inode = ceph_get_inode(dir->i_sb, vino, new_inode);
918 			if (IS_ERR(new_inode)) {
919 				err = PTR_ERR(new_inode);
920 				new_inode = NULL;
921 				goto out_req;
922 			}
923 			WARN_ON_ONCE(!(inode_state_read_once(new_inode) & I_NEW));
924 
925 			spin_lock(&dentry->d_lock);
926 			di->flags |= CEPH_DENTRY_ASYNC_CREATE;
927 			spin_unlock(&dentry->d_lock);
928 
929 			err = ceph_mdsc_submit_request(mdsc, dir, req);
930 			if (!err) {
931 				err = ceph_finish_async_create(dir, new_inode,
932 							       dentry, file,
933 							       mode, req,
934 							       &as_ctx, &lo);
935 				new_inode = NULL;
936 			} else if (err == -EJUKEBOX) {
937 				restore_deleg_ino(dir, req->r_deleg_ino);
938 				ceph_mdsc_put_request(req);
939 				discard_new_inode(new_inode);
940 				ceph_release_acl_sec_ctx(&as_ctx);
941 				memset(&as_ctx, 0, sizeof(as_ctx));
942 				new_inode = NULL;
943 				try_async = false;
944 				ceph_put_string(rcu_dereference_raw(lo.pool_ns));
945 				goto retry;
946 			}
947 			ceph_put_string(rcu_dereference_raw(lo.pool_ns));
948 			goto out_req;
949 		}
950 	}
951 
952 	set_bit(CEPH_MDS_R_PARENT_LOCKED, &req->r_req_flags);
953 	req->r_new_inode = new_inode;
954 	new_inode = NULL;
955 	err = ceph_mdsc_do_request(mdsc, (flags & O_CREAT) ? dir : NULL, req);
956 	if (err == -ENOENT) {
957 		dentry = ceph_handle_snapdir(req, dentry);
958 		if (IS_ERR(dentry)) {
959 			err = PTR_ERR(dentry);
960 			goto out_req;
961 		}
962 		err = 0;
963 	}
964 
965 	if (!err && (flags & O_CREAT) && !req->r_reply_info.head->is_dentry)
966 		err = ceph_handle_notrace_create(dir, dentry);
967 
968 	if (d_in_lookup(dentry)) {
969 		dn = ceph_finish_lookup(req, dentry, err);
970 		if (IS_ERR(dn))
971 			err = PTR_ERR(dn);
972 	} else {
973 		/* we were given a hashed negative dentry */
974 		dn = NULL;
975 	}
976 	if (err)
977 		goto out_req;
978 	if (dn || d_really_is_negative(dentry) || d_is_symlink(dentry)) {
979 		/* make vfs retry on splice, ENOENT, or symlink */
980 		doutc(cl, "finish_no_open on dn %p\n", dn);
981 		err = finish_no_open(file, dn);
982 	} else {
983 		if (IS_ENCRYPTED(dir) &&
984 		    !fscrypt_has_permitted_context(dir, d_inode(dentry))) {
985 			pr_warn_client(cl,
986 				"Inconsistent encryption context (parent %llx:%llx child %llx:%llx)\n",
987 				ceph_vinop(dir), ceph_vinop(d_inode(dentry)));
988 			goto out_req;
989 		}
990 
991 		doutc(cl, "finish_open on dn %p\n", dn);
992 		if (req->r_op == CEPH_MDS_OP_CREATE && req->r_reply_info.has_create_ino) {
993 			struct inode *newino = d_inode(dentry);
994 
995 			cache_file_layout(dir, newino);
996 			ceph_init_inode_acls(newino, &as_ctx);
997 			file->f_mode |= FMODE_CREATED;
998 		}
999 		if ((flags & __O_REGULAR) && !d_is_reg(dentry)) {
1000 			err = -EFTYPE;
1001 			goto out_req;
1002 		}
1003 		err = finish_open(file, dentry, ceph_open);
1004 	}
1005 out_req:
1006 	ceph_mdsc_put_request(req);
1007 	iput(new_inode);
1008 out_ctx:
1009 	ceph_release_acl_sec_ctx(&as_ctx);
1010 	doutc(cl, "result=%d\n", err);
1011 	return err;
1012 }
1013 
1014 int ceph_release(struct inode *inode, struct file *file)
1015 {
1016 	struct ceph_client *cl = ceph_inode_to_client(inode);
1017 	struct ceph_inode_info *ci = ceph_inode(inode);
1018 
1019 	if (S_ISDIR(inode->i_mode)) {
1020 		struct ceph_dir_file_info *dfi = file->private_data;
1021 		doutc(cl, "%p %llx.%llx dir file %p\n", inode,
1022 		      ceph_vinop(inode), file);
1023 		WARN_ON(!list_empty(&dfi->file_info.rw_contexts));
1024 
1025 		ceph_put_fmode(ci, dfi->file_info.fmode, 1);
1026 
1027 		if (dfi->last_readdir)
1028 			ceph_mdsc_put_request(dfi->last_readdir);
1029 		kfree(dfi->last_name);
1030 		kfree(dfi->dir_info);
1031 		kmem_cache_free(ceph_dir_file_cachep, dfi);
1032 	} else {
1033 		struct ceph_file_info *fi = file->private_data;
1034 		doutc(cl, "%p %llx.%llx regular file %p\n", inode,
1035 		      ceph_vinop(inode), file);
1036 		WARN_ON(!list_empty(&fi->rw_contexts));
1037 
1038 		ceph_fscache_unuse_cookie(inode, file->f_mode & FMODE_WRITE);
1039 		ceph_put_fmode(ci, fi->fmode, 1);
1040 
1041 		kmem_cache_free(ceph_file_cachep, fi);
1042 	}
1043 
1044 	/* wake up anyone waiting for caps on this inode */
1045 	wake_up_all(&ci->i_cap_wq);
1046 	return 0;
1047 }
1048 
1049 enum {
1050 	HAVE_RETRIED = 1,
1051 	CHECK_EOF =    2,
1052 	READ_INLINE =  3,
1053 };
1054 
1055 /*
1056  * Completely synchronous read and write methods.  Direct from __user
1057  * buffer to osd, or directly to user pages (if O_DIRECT).
1058  *
1059  * If the read spans object boundary, just do multiple reads.  (That's not
1060  * atomic, but good enough for now.)
1061  *
1062  * If we get a short result from the OSD, check against i_size; we need to
1063  * only return a short read to the caller if we hit EOF.
1064  */
1065 ssize_t __ceph_sync_read(struct inode *inode, loff_t *ki_pos,
1066 			 struct iov_iter *to, int *retry_op,
1067 			 u64 *last_objver)
1068 {
1069 	struct ceph_inode_info *ci = ceph_inode(inode);
1070 	struct ceph_fs_client *fsc = ceph_inode_to_fs_client(inode);
1071 	struct ceph_client *cl = fsc->client;
1072 	struct ceph_osd_client *osdc = &fsc->client->osdc;
1073 	ssize_t ret;
1074 	u64 off = *ki_pos;
1075 	u64 len = iov_iter_count(to);
1076 	u64 i_size = i_size_read(inode);
1077 	bool sparse = IS_ENCRYPTED(inode) || ceph_test_mount_opt(fsc, SPARSEREAD);
1078 	u64 objver = 0;
1079 
1080 	doutc(cl, "on inode %p %llx.%llx %llx~%llx\n", inode,
1081 	      ceph_vinop(inode), *ki_pos, len);
1082 
1083 	if (ceph_inode_is_shutdown(inode))
1084 		return -EIO;
1085 
1086 	if (!len || !i_size)
1087 		return 0;
1088 	/*
1089 	 * flush any page cache pages in this range.  this
1090 	 * will make concurrent normal and sync io slow,
1091 	 * but it will at least behave sensibly when they are
1092 	 * in sequence.
1093 	 */
1094 	ret = filemap_write_and_wait_range(inode->i_mapping,
1095 					   off, off + len - 1);
1096 	if (ret < 0)
1097 		return ret;
1098 
1099 	ret = 0;
1100 	while ((len = iov_iter_count(to)) > 0) {
1101 		struct ceph_osd_request *req;
1102 		struct page **pages;
1103 		int num_pages;
1104 		size_t page_off;
1105 		bool more;
1106 		int idx = 0;
1107 		size_t left;
1108 		struct ceph_osd_req_op *op;
1109 		u64 read_off = off;
1110 		u64 read_len = len;
1111 		int extent_cnt;
1112 
1113 		/* determine new offset/length if encrypted */
1114 		ceph_fscrypt_adjust_off_and_len(inode, &read_off, &read_len);
1115 
1116 		doutc(cl, "orig %llu~%llu reading %llu~%llu", off, len,
1117 		      read_off, read_len);
1118 
1119 		req = ceph_osdc_new_request(osdc, &ci->i_layout,
1120 					ci->i_vino, read_off, &read_len, 0, 1,
1121 					sparse ? CEPH_OSD_OP_SPARSE_READ :
1122 						 CEPH_OSD_OP_READ,
1123 					CEPH_OSD_FLAG_READ,
1124 					NULL, ci->i_truncate_seq,
1125 					ci->i_truncate_size, false);
1126 		if (IS_ERR(req)) {
1127 			ret = PTR_ERR(req);
1128 			break;
1129 		}
1130 
1131 		/* adjust len downward if the request truncated the len */
1132 		if (off + len > read_off + read_len)
1133 			len = read_off + read_len - off;
1134 		more = len < iov_iter_count(to);
1135 
1136 		op = &req->r_ops[0];
1137 		if (sparse) {
1138 			extent_cnt = __ceph_sparse_read_ext_count(inode, read_len);
1139 			ret = ceph_alloc_sparse_ext_map(op, extent_cnt);
1140 			if (ret) {
1141 				ceph_osdc_put_request(req);
1142 				break;
1143 			}
1144 		}
1145 
1146 		num_pages = calc_pages_for(read_off, read_len);
1147 		page_off = offset_in_page(off);
1148 		pages = ceph_alloc_page_vector(num_pages, GFP_KERNEL);
1149 		if (IS_ERR(pages)) {
1150 			ceph_osdc_put_request(req);
1151 			ret = PTR_ERR(pages);
1152 			break;
1153 		}
1154 
1155 		osd_req_op_extent_osd_data_pages(req, 0, pages, read_len,
1156 						 offset_in_page(read_off),
1157 						 false, true);
1158 
1159 		ceph_osdc_start_request(osdc, req);
1160 		ret = ceph_osdc_wait_request(osdc, req);
1161 
1162 		ceph_update_read_metrics(&fsc->mdsc->metric,
1163 					 req->r_start_latency,
1164 					 req->r_end_latency,
1165 					 read_len, ret);
1166 		/*
1167 		 * Only record subvolume metrics for actual bytes read.
1168 		 * ret == 0 means EOF (no data), not an I/O operation.
1169 		 */
1170 		if (ret > 0)
1171 			ceph_record_subvolume_io(inode, false,
1172 						 req->r_start_latency,
1173 						 req->r_end_latency,
1174 						 ret);
1175 
1176 		if (ret > 0)
1177 			objver = req->r_version;
1178 
1179 		i_size = i_size_read(inode);
1180 		doutc(cl, "%llu~%llu got %zd i_size %llu%s\n", off, len,
1181 		      ret, i_size, (more ? " MORE" : ""));
1182 
1183 		/* Fix it to go to end of extent map */
1184 		if (sparse && ret >= 0)
1185 			ret = ceph_sparse_ext_map_end(op);
1186 		else if (ret == -ENOENT)
1187 			ret = 0;
1188 
1189 		if (ret < 0) {
1190 			ceph_osdc_put_request(req);
1191 			if (ret == -EBLOCKLISTED)
1192 				fsc->blocklisted = true;
1193 			break;
1194 		}
1195 
1196 		if (IS_ENCRYPTED(inode)) {
1197 			int fret;
1198 
1199 			fret = ceph_fscrypt_decrypt_extents(inode, pages,
1200 					read_off, op->extent.sparse_ext,
1201 					op->extent.sparse_ext_cnt);
1202 			if (fret < 0) {
1203 				ret = fret;
1204 				ceph_osdc_put_request(req);
1205 				break;
1206 			}
1207 
1208 			/* account for any partial block at the beginning */
1209 			fret -= (off - read_off);
1210 
1211 			/*
1212 			 * Short read after big offset adjustment?
1213 			 * Nothing is usable, just call it a zero
1214 			 * len read.
1215 			 */
1216 			fret = max(fret, 0);
1217 
1218 			/* account for partial block at the end */
1219 			ret = min_t(ssize_t, fret, len);
1220 		}
1221 
1222 		/* Short read but not EOF? Zero out the remainder. */
1223 		if (ret < len && (off + ret < i_size)) {
1224 			int zlen = min(len - ret, i_size - off - ret);
1225 			int zoff = page_off + ret;
1226 
1227 			doutc(cl, "zero gap %llu~%llu\n", off + ret,
1228 			      off + ret + zlen);
1229 			ceph_zero_page_vector_range(zoff, zlen, pages);
1230 			ret += zlen;
1231 		}
1232 
1233 		if (off + ret > i_size)
1234 			left = (i_size > off) ? i_size - off : 0;
1235 		else
1236 			left = ret;
1237 
1238 		while (left > 0) {
1239 			size_t plen, copied;
1240 
1241 			plen = min_t(size_t, left, PAGE_SIZE - page_off);
1242 			SetPageUptodate(pages[idx]);
1243 			copied = copy_page_to_iter(pages[idx++],
1244 						   page_off, plen, to);
1245 			off += copied;
1246 			left -= copied;
1247 			page_off = 0;
1248 			if (copied < plen) {
1249 				ret = -EFAULT;
1250 				break;
1251 			}
1252 		}
1253 
1254 		ceph_osdc_put_request(req);
1255 
1256 		if (off >= i_size || !more)
1257 			break;
1258 	}
1259 
1260 	if (ret > 0) {
1261 		if (off >= i_size) {
1262 			*retry_op = CHECK_EOF;
1263 			ret = i_size - *ki_pos;
1264 			*ki_pos = i_size;
1265 		} else {
1266 			ret = off - *ki_pos;
1267 			*ki_pos = off;
1268 		}
1269 
1270 		if (last_objver)
1271 			*last_objver = objver;
1272 	}
1273 	doutc(cl, "result %zd retry_op %d\n", ret, *retry_op);
1274 	return ret;
1275 }
1276 
1277 static ssize_t ceph_sync_read(struct kiocb *iocb, struct iov_iter *to,
1278 			      int *retry_op)
1279 {
1280 	struct file *file = iocb->ki_filp;
1281 	struct inode *inode = file_inode(file);
1282 	struct ceph_client *cl = ceph_inode_to_client(inode);
1283 
1284 	doutc(cl, "on file %p %llx~%zx %s\n", file, iocb->ki_pos,
1285 	      iov_iter_count(to),
1286 	      (file->f_flags & O_DIRECT) ? "O_DIRECT" : "");
1287 
1288 	return __ceph_sync_read(inode, &iocb->ki_pos, to, retry_op, NULL);
1289 }
1290 
1291 struct ceph_aio_request {
1292 	struct kiocb *iocb;
1293 	size_t total_len;
1294 	bool write;
1295 	bool should_dirty;
1296 	int error;
1297 	struct list_head osd_reqs;
1298 	unsigned num_reqs;
1299 	atomic_t pending_reqs;
1300 	struct timespec64 mtime;
1301 	struct ceph_cap_flush *prealloc_cf;
1302 };
1303 
1304 struct ceph_aio_work {
1305 	struct work_struct work;
1306 	struct ceph_osd_request *req;
1307 };
1308 
1309 static void ceph_aio_retry_work(struct work_struct *work);
1310 
1311 static void ceph_aio_complete(struct inode *inode,
1312 			      struct ceph_aio_request *aio_req)
1313 {
1314 	struct ceph_client *cl = ceph_inode_to_client(inode);
1315 	struct ceph_inode_info *ci = ceph_inode(inode);
1316 	int ret;
1317 
1318 	if (!atomic_dec_and_test(&aio_req->pending_reqs))
1319 		return;
1320 
1321 	if (aio_req->iocb->ki_flags & IOCB_DIRECT)
1322 		inode_dio_end(inode);
1323 
1324 	ret = aio_req->error;
1325 	if (!ret)
1326 		ret = aio_req->total_len;
1327 
1328 	doutc(cl, "%p %llx.%llx rc %d\n", inode, ceph_vinop(inode), ret);
1329 
1330 	if (ret >= 0 && aio_req->write) {
1331 		int dirty;
1332 
1333 		loff_t endoff = aio_req->iocb->ki_pos + aio_req->total_len;
1334 		if (endoff > i_size_read(inode)) {
1335 			if (ceph_inode_set_size(inode, endoff))
1336 				ceph_check_caps(ci, CHECK_CAPS_AUTHONLY);
1337 		}
1338 
1339 		spin_lock(&ci->i_ceph_lock);
1340 		dirty = __ceph_mark_dirty_caps(ci, CEPH_CAP_FILE_WR,
1341 					       &aio_req->prealloc_cf);
1342 		spin_unlock(&ci->i_ceph_lock);
1343 		if (dirty)
1344 			__mark_inode_dirty(inode, dirty);
1345 
1346 	}
1347 
1348 	ceph_put_cap_refs(ci, (aio_req->write ? CEPH_CAP_FILE_WR :
1349 						CEPH_CAP_FILE_RD));
1350 
1351 	aio_req->iocb->ki_complete(aio_req->iocb, ret);
1352 
1353 	ceph_free_cap_flush(aio_req->prealloc_cf);
1354 	kfree(aio_req);
1355 }
1356 
1357 static void ceph_aio_complete_req(struct ceph_osd_request *req)
1358 {
1359 	int rc = req->r_result;
1360 	struct inode *inode = req->r_inode;
1361 	struct ceph_aio_request *aio_req = req->r_priv;
1362 	struct ceph_osd_data *osd_data = osd_req_op_extent_osd_data(req, 0);
1363 	struct ceph_osd_req_op *op = &req->r_ops[0];
1364 	struct ceph_client_metric *metric = &ceph_sb_to_mdsc(inode->i_sb)->metric;
1365 	unsigned int len = osd_data->bvec_pos.iter.bi_size;
1366 	bool sparse = (op->op == CEPH_OSD_OP_SPARSE_READ);
1367 	struct ceph_client *cl = ceph_inode_to_client(inode);
1368 
1369 	BUG_ON(osd_data->type != CEPH_OSD_DATA_TYPE_BVECS);
1370 	BUG_ON(!osd_data->num_bvecs);
1371 
1372 	doutc(cl, "req %p inode %p %llx.%llx, rc %d bytes %u\n", req,
1373 	      inode, ceph_vinop(inode), rc, len);
1374 
1375 	if (rc == -EOLDSNAPC) {
1376 		struct ceph_aio_work *aio_work;
1377 		BUG_ON(!aio_req->write);
1378 
1379 		aio_work = kmalloc_obj(*aio_work, GFP_NOFS);
1380 		if (aio_work) {
1381 			INIT_WORK(&aio_work->work, ceph_aio_retry_work);
1382 			aio_work->req = req;
1383 			queue_work(ceph_inode_to_fs_client(inode)->inode_wq,
1384 				   &aio_work->work);
1385 			return;
1386 		}
1387 		rc = -ENOMEM;
1388 	} else if (!aio_req->write) {
1389 		if (sparse && rc >= 0)
1390 			rc = ceph_sparse_ext_map_end(op);
1391 		if (rc == -ENOENT)
1392 			rc = 0;
1393 		if (rc >= 0 && len > rc) {
1394 			struct iov_iter i;
1395 			int zlen = len - rc;
1396 
1397 			/*
1398 			 * If read is satisfied by single OSD request,
1399 			 * it can pass EOF. Otherwise read is within
1400 			 * i_size.
1401 			 */
1402 			if (aio_req->num_reqs == 1) {
1403 				loff_t i_size = i_size_read(inode);
1404 				loff_t endoff = aio_req->iocb->ki_pos + rc;
1405 				if (endoff < i_size)
1406 					zlen = min_t(size_t, zlen,
1407 						     i_size - endoff);
1408 				aio_req->total_len = rc + zlen;
1409 			}
1410 
1411 			iov_iter_bvec(&i, ITER_DEST, osd_data->bvec_pos.bvecs,
1412 				      osd_data->num_bvecs, len);
1413 			iov_iter_advance(&i, rc);
1414 			iov_iter_zero(zlen, &i);
1415 		}
1416 	}
1417 
1418 	/* r_start_latency == 0 means the request was not submitted */
1419 	if (req->r_start_latency) {
1420 		if (aio_req->write) {
1421 			ceph_update_write_metrics(metric, req->r_start_latency,
1422 						  req->r_end_latency, len, rc);
1423 			if (rc >= 0 && len)
1424 				ceph_record_subvolume_io(inode, true,
1425 							 req->r_start_latency,
1426 							 req->r_end_latency,
1427 							 len);
1428 		} else {
1429 			ceph_update_read_metrics(metric, req->r_start_latency,
1430 						 req->r_end_latency, len, rc);
1431 			if (rc > 0)
1432 				ceph_record_subvolume_io(inode, false,
1433 							 req->r_start_latency,
1434 							 req->r_end_latency,
1435 							 rc);
1436 		}
1437 	}
1438 
1439 	put_bvecs(osd_data->bvec_pos.bvecs, osd_data->num_bvecs,
1440 		  aio_req->should_dirty);
1441 	ceph_osdc_put_request(req);
1442 
1443 	if (rc < 0)
1444 		cmpxchg(&aio_req->error, 0, rc);
1445 
1446 	ceph_aio_complete(inode, aio_req);
1447 	return;
1448 }
1449 
1450 static void ceph_aio_retry_work(struct work_struct *work)
1451 {
1452 	struct ceph_aio_work *aio_work =
1453 		container_of(work, struct ceph_aio_work, work);
1454 	struct ceph_osd_request *orig_req = aio_work->req;
1455 	struct ceph_aio_request *aio_req = orig_req->r_priv;
1456 	struct inode *inode = orig_req->r_inode;
1457 	struct ceph_inode_info *ci = ceph_inode(inode);
1458 	struct ceph_snap_context *snapc;
1459 	struct ceph_osd_request *req;
1460 	int ret;
1461 
1462 	spin_lock(&ci->i_ceph_lock);
1463 	if (__ceph_have_pending_cap_snap(ci)) {
1464 		struct ceph_cap_snap *capsnap =
1465 			list_last_entry(&ci->i_cap_snaps,
1466 					struct ceph_cap_snap,
1467 					ci_item);
1468 		snapc = ceph_get_snap_context(capsnap->context);
1469 	} else {
1470 		BUG_ON(!ci->i_head_snapc);
1471 		snapc = ceph_get_snap_context(ci->i_head_snapc);
1472 	}
1473 	spin_unlock(&ci->i_ceph_lock);
1474 
1475 	req = ceph_osdc_alloc_request(orig_req->r_osdc, snapc, 1,
1476 			false, GFP_NOFS);
1477 	if (!req) {
1478 		ret = -ENOMEM;
1479 		req = orig_req;
1480 		goto out;
1481 	}
1482 
1483 	req->r_flags = /* CEPH_OSD_FLAG_ORDERSNAP | */ CEPH_OSD_FLAG_WRITE;
1484 	ceph_oloc_copy(&req->r_base_oloc, &orig_req->r_base_oloc);
1485 	ceph_oid_copy(&req->r_base_oid, &orig_req->r_base_oid);
1486 
1487 	req->r_ops[0] = orig_req->r_ops[0];
1488 
1489 	req->r_mtime = aio_req->mtime;
1490 	req->r_data_offset = req->r_ops[0].extent.offset;
1491 
1492 	ret = ceph_osdc_alloc_messages(req, GFP_NOFS);
1493 	if (ret) {
1494 		ceph_osdc_put_request(req);
1495 		req = orig_req;
1496 		goto out;
1497 	}
1498 
1499 	ceph_osdc_put_request(orig_req);
1500 
1501 	req->r_callback = ceph_aio_complete_req;
1502 	req->r_inode = inode;
1503 	req->r_priv = aio_req;
1504 
1505 	ceph_osdc_start_request(req->r_osdc, req);
1506 out:
1507 	if (ret < 0) {
1508 		req->r_result = ret;
1509 		ceph_aio_complete_req(req);
1510 	}
1511 
1512 	ceph_put_snap_context(snapc);
1513 	kfree(aio_work);
1514 }
1515 
1516 static ssize_t
1517 ceph_direct_read_write(struct kiocb *iocb, struct iov_iter *iter,
1518 		       struct ceph_snap_context *snapc,
1519 		       struct ceph_cap_flush **pcf)
1520 {
1521 	struct file *file = iocb->ki_filp;
1522 	struct inode *inode = file_inode(file);
1523 	struct ceph_inode_info *ci = ceph_inode(inode);
1524 	struct ceph_fs_client *fsc = ceph_inode_to_fs_client(inode);
1525 	struct ceph_client *cl = fsc->client;
1526 	struct ceph_client_metric *metric = &fsc->mdsc->metric;
1527 	struct ceph_vino vino;
1528 	struct ceph_osd_request *req;
1529 	struct bio_vec *bvecs;
1530 	struct ceph_aio_request *aio_req = NULL;
1531 	int num_pages = 0;
1532 	int flags;
1533 	int ret = 0;
1534 	struct timespec64 mtime = current_time(inode);
1535 	size_t count = iov_iter_count(iter);
1536 	loff_t pos = iocb->ki_pos;
1537 	bool write = iov_iter_rw(iter) == WRITE;
1538 	bool should_dirty = !write && user_backed_iter(iter);
1539 	bool sparse = ceph_test_mount_opt(fsc, SPARSEREAD);
1540 
1541 	if (write && ceph_snap(file_inode(file)) != CEPH_NOSNAP)
1542 		return -EROFS;
1543 
1544 	doutc(cl, "sync_direct_%s on file %p %lld~%u snapc %p seq %lld\n",
1545 	      (write ? "write" : "read"), file, pos, (unsigned)count,
1546 	      snapc, snapc ? snapc->seq : 0);
1547 
1548 	if (write) {
1549 		int ret2;
1550 
1551 		ceph_fscache_invalidate(inode, true);
1552 
1553 		ret2 = invalidate_inode_pages2_range(inode->i_mapping,
1554 					pos >> PAGE_SHIFT,
1555 					(pos + count - 1) >> PAGE_SHIFT);
1556 		if (ret2 < 0)
1557 			doutc(cl, "invalidate_inode_pages2_range returned %d\n",
1558 			      ret2);
1559 
1560 		flags = /* CEPH_OSD_FLAG_ORDERSNAP | */ CEPH_OSD_FLAG_WRITE;
1561 	} else {
1562 		flags = CEPH_OSD_FLAG_READ;
1563 	}
1564 
1565 	while (iov_iter_count(iter) > 0) {
1566 		u64 size = iov_iter_count(iter);
1567 		ssize_t len;
1568 		struct ceph_osd_req_op *op;
1569 		int readop = sparse ? CEPH_OSD_OP_SPARSE_READ : CEPH_OSD_OP_READ;
1570 		int extent_cnt;
1571 
1572 		if (write)
1573 			size = min_t(u64, size, fsc->mount_options->wsize);
1574 		else
1575 			size = min_t(u64, size, fsc->mount_options->rsize);
1576 
1577 		vino = ceph_vino(inode);
1578 		req = ceph_osdc_new_request(&fsc->client->osdc, &ci->i_layout,
1579 					    vino, pos, &size, 0,
1580 					    1,
1581 					    write ? CEPH_OSD_OP_WRITE : readop,
1582 					    flags, snapc,
1583 					    ci->i_truncate_seq,
1584 					    ci->i_truncate_size,
1585 					    false);
1586 		if (IS_ERR(req)) {
1587 			ret = PTR_ERR(req);
1588 			break;
1589 		}
1590 
1591 		op = &req->r_ops[0];
1592 		if (!write && sparse) {
1593 			extent_cnt = __ceph_sparse_read_ext_count(inode, size);
1594 			ret = ceph_alloc_sparse_ext_map(op, extent_cnt);
1595 			if (ret) {
1596 				ceph_osdc_put_request(req);
1597 				break;
1598 			}
1599 		}
1600 
1601 		len = iter_get_bvecs_alloc(iter, size, &bvecs, &num_pages);
1602 		if (len < 0) {
1603 			ceph_osdc_put_request(req);
1604 			ret = len;
1605 			break;
1606 		}
1607 		if (len != size)
1608 			osd_req_op_extent_update(req, 0, len);
1609 
1610 		osd_req_op_extent_osd_data_bvecs(req, 0, bvecs, num_pages, len);
1611 
1612 		/*
1613 		 * To simplify error handling, allow AIO when IO within i_size
1614 		 * or IO can be satisfied by single OSD request.
1615 		 */
1616 		if (pos == iocb->ki_pos && !is_sync_kiocb(iocb) &&
1617 		    (len == count || pos + count <= i_size_read(inode))) {
1618 			aio_req = kzalloc_obj(*aio_req);
1619 			if (aio_req) {
1620 				aio_req->iocb = iocb;
1621 				aio_req->write = write;
1622 				aio_req->should_dirty = should_dirty;
1623 				INIT_LIST_HEAD(&aio_req->osd_reqs);
1624 				if (write) {
1625 					aio_req->mtime = mtime;
1626 					swap(aio_req->prealloc_cf, *pcf);
1627 				}
1628 			}
1629 			/* ignore error */
1630 		}
1631 
1632 		if (write) {
1633 			/*
1634 			 * throw out any page cache pages in this range. this
1635 			 * may block.
1636 			 */
1637 			truncate_inode_pages_range(inode->i_mapping, pos,
1638 						   PAGE_ALIGN(pos + len) - 1);
1639 
1640 			req->r_mtime = mtime;
1641 		}
1642 
1643 		if (aio_req) {
1644 			aio_req->total_len += len;
1645 			aio_req->num_reqs++;
1646 			atomic_inc(&aio_req->pending_reqs);
1647 
1648 			req->r_callback = ceph_aio_complete_req;
1649 			req->r_inode = inode;
1650 			req->r_priv = aio_req;
1651 			list_add_tail(&req->r_private_item, &aio_req->osd_reqs);
1652 
1653 			pos += len;
1654 			continue;
1655 		}
1656 
1657 		ceph_osdc_start_request(req->r_osdc, req);
1658 		ret = ceph_osdc_wait_request(&fsc->client->osdc, req);
1659 
1660 		if (write) {
1661 			ceph_update_write_metrics(metric, req->r_start_latency,
1662 						  req->r_end_latency, len, ret);
1663 			if (ret >= 0 && len)
1664 				ceph_record_subvolume_io(inode, true,
1665 							 req->r_start_latency,
1666 							 req->r_end_latency,
1667 							 len);
1668 		} else {
1669 			ceph_update_read_metrics(metric, req->r_start_latency,
1670 						 req->r_end_latency, len, ret);
1671 			if (ret > 0)
1672 				ceph_record_subvolume_io(inode, false,
1673 							 req->r_start_latency,
1674 							 req->r_end_latency,
1675 							 ret);
1676 		}
1677 
1678 		size = i_size_read(inode);
1679 		if (!write) {
1680 			if (sparse && ret >= 0)
1681 				ret = ceph_sparse_ext_map_end(op);
1682 			else if (ret == -ENOENT)
1683 				ret = 0;
1684 
1685 			if (ret >= 0 && ret < len && pos + ret < size) {
1686 				struct iov_iter i;
1687 				int zlen = min_t(size_t, len - ret,
1688 						 size - pos - ret);
1689 
1690 				iov_iter_bvec(&i, ITER_DEST, bvecs, num_pages, len);
1691 				iov_iter_advance(&i, ret);
1692 				iov_iter_zero(zlen, &i);
1693 				ret += zlen;
1694 			}
1695 			if (ret >= 0)
1696 				len = ret;
1697 		}
1698 
1699 		put_bvecs(bvecs, num_pages, should_dirty);
1700 		ceph_osdc_put_request(req);
1701 		if (ret < 0)
1702 			break;
1703 
1704 		pos += len;
1705 		if (!write && pos >= size)
1706 			break;
1707 
1708 		if (write && pos > size) {
1709 			if (ceph_inode_set_size(inode, pos))
1710 				ceph_check_caps(ceph_inode(inode),
1711 						CHECK_CAPS_AUTHONLY);
1712 		}
1713 	}
1714 
1715 	if (aio_req) {
1716 		LIST_HEAD(osd_reqs);
1717 
1718 		if (aio_req->num_reqs == 0) {
1719 			kfree(aio_req);
1720 			return ret;
1721 		}
1722 
1723 		ceph_get_cap_refs(ci, write ? CEPH_CAP_FILE_WR :
1724 					      CEPH_CAP_FILE_RD);
1725 
1726 		list_splice(&aio_req->osd_reqs, &osd_reqs);
1727 		inode_dio_begin(inode);
1728 		while (!list_empty(&osd_reqs)) {
1729 			req = list_first_entry(&osd_reqs,
1730 					       struct ceph_osd_request,
1731 					       r_private_item);
1732 			list_del_init(&req->r_private_item);
1733 			if (ret >= 0)
1734 				ceph_osdc_start_request(req->r_osdc, req);
1735 			if (ret < 0) {
1736 				req->r_result = ret;
1737 				ceph_aio_complete_req(req);
1738 			}
1739 		}
1740 		return -EIOCBQUEUED;
1741 	}
1742 
1743 	if (ret != -EOLDSNAPC && pos > iocb->ki_pos) {
1744 		ret = pos - iocb->ki_pos;
1745 		iocb->ki_pos = pos;
1746 	}
1747 	return ret;
1748 }
1749 
1750 /*
1751  * Synchronous write, straight from __user pointer or user pages.
1752  *
1753  * If write spans object boundary, just do multiple writes.  (For a
1754  * correct atomic write, we should e.g. take write locks on all
1755  * objects, rollback on failure, etc.)
1756  */
1757 static ssize_t
1758 ceph_sync_write(struct kiocb *iocb, struct iov_iter *from, loff_t pos,
1759 		struct ceph_snap_context *snapc)
1760 {
1761 	struct file *file = iocb->ki_filp;
1762 	struct inode *inode = file_inode(file);
1763 	struct ceph_inode_info *ci = ceph_inode(inode);
1764 	struct ceph_fs_client *fsc = ceph_inode_to_fs_client(inode);
1765 	struct ceph_client *cl = fsc->client;
1766 	struct ceph_osd_client *osdc = &fsc->client->osdc;
1767 	struct ceph_osd_request *req;
1768 	struct page **pages;
1769 	u64 len;
1770 	int num_pages;
1771 	int written = 0;
1772 	int ret;
1773 	bool check_caps = false;
1774 	struct timespec64 mtime = current_time(inode);
1775 	size_t count = iov_iter_count(from);
1776 
1777 	if (ceph_snap(file_inode(file)) != CEPH_NOSNAP)
1778 		return -EROFS;
1779 
1780 	doutc(cl, "on file %p %lld~%u snapc %p seq %lld\n", file, pos,
1781 	      (unsigned)count, snapc, snapc->seq);
1782 
1783 	ret = filemap_write_and_wait_range(inode->i_mapping,
1784 					   pos, pos + count - 1);
1785 	if (ret < 0)
1786 		return ret;
1787 
1788 	ceph_fscache_invalidate(inode, false);
1789 
1790 	while ((len = iov_iter_count(from)) > 0) {
1791 		size_t left;
1792 		int n;
1793 		u64 write_pos = pos;
1794 		u64 write_len = len;
1795 		u64 objnum, objoff;
1796 		u32 xlen;
1797 		u64 assert_ver = 0;
1798 		bool rmw;
1799 		bool first, last;
1800 		struct iov_iter saved_iter = *from;
1801 		size_t off;
1802 
1803 		ceph_fscrypt_adjust_off_and_len(inode, &write_pos, &write_len);
1804 
1805 		/* clamp the length to the end of first object */
1806 		ceph_calc_file_object_mapping(&ci->i_layout, write_pos,
1807 					      write_len, &objnum, &objoff,
1808 					      &xlen);
1809 		write_len = xlen;
1810 
1811 		/* adjust len downward if it goes beyond current object */
1812 		if (pos + len > write_pos + write_len)
1813 			len = write_pos + write_len - pos;
1814 
1815 		/*
1816 		 * If we had to adjust the length or position to align with a
1817 		 * crypto block, then we must do a read/modify/write cycle. We
1818 		 * use a version assertion to redrive the thing if something
1819 		 * changes in between.
1820 		 */
1821 		first = pos != write_pos;
1822 		last = (pos + len) != (write_pos + write_len);
1823 		rmw = first || last;
1824 
1825 		doutc(cl, "ino %llx %lld~%llu adjusted %lld~%llu -- %srmw\n",
1826 		      ci->i_vino.ino, pos, len, write_pos, write_len,
1827 		      rmw ? "" : "no ");
1828 
1829 		/*
1830 		 * The data is emplaced into the page as it would be if it were
1831 		 * in an array of pagecache pages.
1832 		 */
1833 		num_pages = calc_pages_for(write_pos, write_len);
1834 		pages = ceph_alloc_page_vector(num_pages, GFP_KERNEL);
1835 		if (IS_ERR(pages)) {
1836 			ret = PTR_ERR(pages);
1837 			break;
1838 		}
1839 
1840 		/* Do we need to preload the pages? */
1841 		if (rmw) {
1842 			u64 first_pos = write_pos;
1843 			u64 last_pos = (write_pos + write_len) - CEPH_FSCRYPT_BLOCK_SIZE;
1844 			u64 read_len = CEPH_FSCRYPT_BLOCK_SIZE;
1845 			struct ceph_osd_req_op *op;
1846 
1847 			/* We should only need to do this for encrypted inodes */
1848 			WARN_ON_ONCE(!IS_ENCRYPTED(inode));
1849 
1850 			/* No need to do two reads if first and last blocks are same */
1851 			if (first && last_pos == first_pos)
1852 				last = false;
1853 
1854 			/*
1855 			 * Allocate a read request for one or two extents,
1856 			 * depending on how the request was aligned.
1857 			 */
1858 			req = ceph_osdc_new_request(osdc, &ci->i_layout,
1859 					ci->i_vino, first ? first_pos : last_pos,
1860 					&read_len, 0, (first && last) ? 2 : 1,
1861 					CEPH_OSD_OP_SPARSE_READ, CEPH_OSD_FLAG_READ,
1862 					NULL, ci->i_truncate_seq,
1863 					ci->i_truncate_size, false);
1864 			if (IS_ERR(req)) {
1865 				ceph_release_page_vector(pages, num_pages);
1866 				ret = PTR_ERR(req);
1867 				break;
1868 			}
1869 
1870 			/* Something is misaligned! */
1871 			if (read_len != CEPH_FSCRYPT_BLOCK_SIZE) {
1872 				ceph_osdc_put_request(req);
1873 				ceph_release_page_vector(pages, num_pages);
1874 				ret = -EIO;
1875 				break;
1876 			}
1877 
1878 			/* Add extent for first block? */
1879 			op = &req->r_ops[0];
1880 
1881 			if (first) {
1882 				osd_req_op_extent_osd_data_pages(req, 0, pages,
1883 							 CEPH_FSCRYPT_BLOCK_SIZE,
1884 							 offset_in_page(first_pos),
1885 							 false, false);
1886 				/* We only expect a single extent here */
1887 				ret = __ceph_alloc_sparse_ext_map(op, 1);
1888 				if (ret) {
1889 					ceph_osdc_put_request(req);
1890 					ceph_release_page_vector(pages, num_pages);
1891 					break;
1892 				}
1893 			}
1894 
1895 			/* Add extent for last block */
1896 			if (last) {
1897 				/* Init the other extent if first extent has been used */
1898 				if (first) {
1899 					op = &req->r_ops[1];
1900 					osd_req_op_extent_init(req, 1,
1901 							CEPH_OSD_OP_SPARSE_READ,
1902 							last_pos, CEPH_FSCRYPT_BLOCK_SIZE,
1903 							ci->i_truncate_size,
1904 							ci->i_truncate_seq);
1905 				}
1906 
1907 				ret = __ceph_alloc_sparse_ext_map(op, 1);
1908 				if (ret) {
1909 					ceph_osdc_put_request(req);
1910 					ceph_release_page_vector(pages, num_pages);
1911 					break;
1912 				}
1913 
1914 				osd_req_op_extent_osd_data_pages(req, first ? 1 : 0,
1915 							&pages[num_pages - 1],
1916 							CEPH_FSCRYPT_BLOCK_SIZE,
1917 							offset_in_page(last_pos),
1918 							false, false);
1919 			}
1920 
1921 			ceph_osdc_start_request(osdc, req);
1922 			ret = ceph_osdc_wait_request(osdc, req);
1923 
1924 			/* FIXME: length field is wrong if there are 2 extents */
1925 			ceph_update_read_metrics(&fsc->mdsc->metric,
1926 						 req->r_start_latency,
1927 						 req->r_end_latency,
1928 						 read_len, ret);
1929 			if (ret > 0)
1930 				ceph_record_subvolume_io(inode, false,
1931 							 req->r_start_latency,
1932 							 req->r_end_latency,
1933 							 ret);
1934 
1935 			/* Ok if object is not already present */
1936 			if (ret == -ENOENT) {
1937 				/*
1938 				 * If there is no object, then we can't assert
1939 				 * on its version. Set it to 0, and we'll use an
1940 				 * exclusive create instead.
1941 				 */
1942 				ceph_osdc_put_request(req);
1943 				ret = 0;
1944 
1945 				/*
1946 				 * zero out the soon-to-be uncopied parts of the
1947 				 * first and last pages.
1948 				 */
1949 				if (first)
1950 					zero_user_segment(pages[0], 0,
1951 							  offset_in_page(first_pos));
1952 				if (last)
1953 					zero_user_segment(pages[num_pages - 1],
1954 							  offset_in_page(last_pos),
1955 							  PAGE_SIZE);
1956 			} else {
1957 				if (ret < 0) {
1958 					ceph_osdc_put_request(req);
1959 					ceph_release_page_vector(pages, num_pages);
1960 					break;
1961 				}
1962 
1963 				op = &req->r_ops[0];
1964 				if (op->extent.sparse_ext_cnt == 0) {
1965 					if (first)
1966 						zero_user_segment(pages[0], 0,
1967 								  offset_in_page(first_pos));
1968 					else
1969 						zero_user_segment(pages[num_pages - 1],
1970 								  offset_in_page(last_pos),
1971 								  PAGE_SIZE);
1972 				} else if (op->extent.sparse_ext_cnt != 1 ||
1973 					   ceph_sparse_ext_map_end(op) !=
1974 						CEPH_FSCRYPT_BLOCK_SIZE) {
1975 					ret = -EIO;
1976 					ceph_osdc_put_request(req);
1977 					ceph_release_page_vector(pages, num_pages);
1978 					break;
1979 				}
1980 
1981 				if (first && last) {
1982 					op = &req->r_ops[1];
1983 					if (op->extent.sparse_ext_cnt == 0) {
1984 						zero_user_segment(pages[num_pages - 1],
1985 								  offset_in_page(last_pos),
1986 								  PAGE_SIZE);
1987 					} else if (op->extent.sparse_ext_cnt != 1 ||
1988 						   ceph_sparse_ext_map_end(op) !=
1989 							CEPH_FSCRYPT_BLOCK_SIZE) {
1990 						ret = -EIO;
1991 						ceph_osdc_put_request(req);
1992 						ceph_release_page_vector(pages, num_pages);
1993 						break;
1994 					}
1995 				}
1996 
1997 				/* Grab assert version. It must be non-zero. */
1998 				assert_ver = req->r_version;
1999 				WARN_ON_ONCE(ret > 0 && assert_ver == 0);
2000 
2001 				ceph_osdc_put_request(req);
2002 				if (first) {
2003 					ret = ceph_fscrypt_decrypt_block_inplace(inode,
2004 							pages[0], CEPH_FSCRYPT_BLOCK_SIZE,
2005 							offset_in_page(first_pos),
2006 							first_pos >> CEPH_FSCRYPT_BLOCK_SHIFT);
2007 					if (ret < 0) {
2008 						ceph_release_page_vector(pages, num_pages);
2009 						break;
2010 					}
2011 				}
2012 				if (last) {
2013 					ret = ceph_fscrypt_decrypt_block_inplace(inode,
2014 							pages[num_pages - 1],
2015 							CEPH_FSCRYPT_BLOCK_SIZE,
2016 							offset_in_page(last_pos),
2017 							last_pos >> CEPH_FSCRYPT_BLOCK_SHIFT);
2018 					if (ret < 0) {
2019 						ceph_release_page_vector(pages, num_pages);
2020 						break;
2021 					}
2022 				}
2023 			}
2024 		}
2025 
2026 		left = len;
2027 		off = offset_in_page(pos);
2028 		for (n = 0; n < num_pages; n++) {
2029 			size_t plen = min_t(size_t, left, PAGE_SIZE - off);
2030 
2031 			/* copy the data */
2032 			ret = copy_page_from_iter(pages[n], off, plen, from);
2033 			if (ret != plen) {
2034 				ret = -EFAULT;
2035 				break;
2036 			}
2037 			off = 0;
2038 			left -= ret;
2039 		}
2040 		if (ret < 0) {
2041 			doutc(cl, "write failed with %d\n", ret);
2042 			ceph_release_page_vector(pages, num_pages);
2043 			break;
2044 		}
2045 
2046 		if (IS_ENCRYPTED(inode)) {
2047 			ret = ceph_fscrypt_encrypt_pages(inode, pages,
2048 							 write_pos, write_len);
2049 			if (ret < 0) {
2050 				doutc(cl, "encryption failed with %d\n", ret);
2051 				ceph_release_page_vector(pages, num_pages);
2052 				break;
2053 			}
2054 		}
2055 
2056 		req = ceph_osdc_new_request(osdc, &ci->i_layout,
2057 					    ci->i_vino, write_pos, &write_len,
2058 					    rmw ? 1 : 0, rmw ? 2 : 1,
2059 					    CEPH_OSD_OP_WRITE,
2060 					    CEPH_OSD_FLAG_WRITE,
2061 					    snapc, ci->i_truncate_seq,
2062 					    ci->i_truncate_size, false);
2063 		if (IS_ERR(req)) {
2064 			ret = PTR_ERR(req);
2065 			ceph_release_page_vector(pages, num_pages);
2066 			break;
2067 		}
2068 
2069 		doutc(cl, "write op %lld~%llu\n", write_pos, write_len);
2070 		osd_req_op_extent_osd_data_pages(req, rmw ? 1 : 0, pages, write_len,
2071 						 offset_in_page(write_pos), false,
2072 						 true);
2073 		req->r_inode = inode;
2074 		req->r_mtime = mtime;
2075 
2076 		/* Set up the assertion */
2077 		if (rmw) {
2078 			/*
2079 			 * Set up the assertion. If we don't have a version
2080 			 * number, then the object doesn't exist yet. Use an
2081 			 * exclusive create instead of a version assertion in
2082 			 * that case.
2083 			 */
2084 			if (assert_ver) {
2085 				osd_req_op_init(req, 0, CEPH_OSD_OP_ASSERT_VER, 0);
2086 				req->r_ops[0].assert_ver.ver = assert_ver;
2087 			} else {
2088 				osd_req_op_init(req, 0, CEPH_OSD_OP_CREATE,
2089 						CEPH_OSD_OP_FLAG_EXCL);
2090 			}
2091 		}
2092 
2093 		ceph_osdc_start_request(osdc, req);
2094 		ret = ceph_osdc_wait_request(osdc, req);
2095 
2096 		ceph_update_write_metrics(&fsc->mdsc->metric, req->r_start_latency,
2097 					  req->r_end_latency, len, ret);
2098 		if (ret >= 0 && write_len)
2099 			ceph_record_subvolume_io(inode, true,
2100 						 req->r_start_latency,
2101 						 req->r_end_latency,
2102 						 write_len);
2103 		ceph_osdc_put_request(req);
2104 		if (ret != 0) {
2105 			doutc(cl, "osd write returned %d\n", ret);
2106 			/* Version changed! Must re-do the rmw cycle */
2107 			if ((assert_ver && (ret == -ERANGE || ret == -EOVERFLOW)) ||
2108 			    (!assert_ver && ret == -EEXIST)) {
2109 				/* We should only ever see this on a rmw */
2110 				WARN_ON_ONCE(!rmw);
2111 
2112 				/* The version should never go backward */
2113 				WARN_ON_ONCE(ret == -EOVERFLOW);
2114 
2115 				*from = saved_iter;
2116 
2117 				/* FIXME: limit number of times we loop? */
2118 				continue;
2119 			}
2120 			ceph_set_error_write(ci);
2121 			break;
2122 		}
2123 
2124 		ceph_clear_error_write(ci);
2125 
2126 		/*
2127 		 * We successfully wrote to a range of the file. Declare
2128 		 * that region of the pagecache invalid.
2129 		 */
2130 		ret = invalidate_inode_pages2_range(
2131 				inode->i_mapping,
2132 				pos >> PAGE_SHIFT,
2133 				(pos + len - 1) >> PAGE_SHIFT);
2134 		if (ret < 0) {
2135 			doutc(cl, "invalidate_inode_pages2_range returned %d\n",
2136 			      ret);
2137 			ret = 0;
2138 		}
2139 		pos += len;
2140 		written += len;
2141 		doutc(cl, "written %d\n", written);
2142 		if (pos > i_size_read(inode)) {
2143 			check_caps = ceph_inode_set_size(inode, pos);
2144 			if (check_caps)
2145 				ceph_check_caps(ceph_inode(inode),
2146 						CHECK_CAPS_AUTHONLY);
2147 		}
2148 
2149 	}
2150 
2151 	if (ret != -EOLDSNAPC && written > 0) {
2152 		ret = written;
2153 		iocb->ki_pos = pos;
2154 	}
2155 	doutc(cl, "returning %d\n", ret);
2156 	return ret;
2157 }
2158 
2159 /*
2160  * Wrap generic_file_aio_read with checks for cap bits on the inode.
2161  * Atomically grab references, so that those bits are not released
2162  * back to the MDS mid-read.
2163  *
2164  * Hmm, the sync read case isn't actually async... should it be?
2165  */
2166 static ssize_t ceph_read_iter(struct kiocb *iocb, struct iov_iter *to)
2167 {
2168 	struct file *filp = iocb->ki_filp;
2169 	struct ceph_file_info *fi = filp->private_data;
2170 	size_t len = iov_iter_count(to);
2171 	struct inode *inode = file_inode(filp);
2172 	struct ceph_inode_info *ci = ceph_inode(inode);
2173 	bool direct_lock = iocb->ki_flags & IOCB_DIRECT;
2174 	struct ceph_client *cl = ceph_inode_to_client(inode);
2175 	ssize_t ret;
2176 	int want = 0, got = 0;
2177 	int retry_op = 0, read = 0;
2178 
2179 again:
2180 	doutc(cl, "%llu~%u trying to get caps on %p %llx.%llx\n",
2181 	      iocb->ki_pos, (unsigned)len, inode, ceph_vinop(inode));
2182 
2183 	if (ceph_inode_is_shutdown(inode))
2184 		return -ESTALE;
2185 
2186 	ret = direct_lock ? ceph_start_io_direct(inode) :
2187 			    ceph_start_io_read(inode);
2188 	if (ret)
2189 		return ret;
2190 
2191 	if (!(fi->flags & CEPH_F_SYNC) && !direct_lock)
2192 		want |= CEPH_CAP_FILE_CACHE;
2193 	if (fi->fmode & CEPH_FILE_MODE_LAZY)
2194 		want |= CEPH_CAP_FILE_LAZYIO;
2195 
2196 	ret = ceph_get_caps(filp, CEPH_CAP_FILE_RD, want, -1, &got);
2197 	if (ret < 0) {
2198 		if (direct_lock)
2199 			ceph_end_io_direct(inode);
2200 		else
2201 			ceph_end_io_read(inode);
2202 		return ret;
2203 	}
2204 
2205 	if ((got & (CEPH_CAP_FILE_CACHE|CEPH_CAP_FILE_LAZYIO)) == 0 ||
2206 	    (iocb->ki_flags & IOCB_DIRECT) ||
2207 	    (fi->flags & CEPH_F_SYNC)) {
2208 
2209 		doutc(cl, "sync %p %llx.%llx %llu~%u got cap refs on %s\n",
2210 		      inode, ceph_vinop(inode), iocb->ki_pos, (unsigned)len,
2211 		      ceph_cap_string(got));
2212 
2213 		if (!ceph_has_inline_data(ci)) {
2214 			if (!retry_op &&
2215 			    (iocb->ki_flags & IOCB_DIRECT) &&
2216 			    !IS_ENCRYPTED(inode)) {
2217 				ret = ceph_direct_read_write(iocb, to,
2218 							     NULL, NULL);
2219 				if (ret >= 0 && ret < len)
2220 					retry_op = CHECK_EOF;
2221 			} else {
2222 				ret = ceph_sync_read(iocb, to, &retry_op);
2223 			}
2224 		} else {
2225 			retry_op = READ_INLINE;
2226 		}
2227 	} else {
2228 		CEPH_DEFINE_RW_CONTEXT(rw_ctx, got);
2229 		doutc(cl, "async %p %llx.%llx %llu~%u got cap refs on %s\n",
2230 		      inode, ceph_vinop(inode), iocb->ki_pos, (unsigned)len,
2231 		      ceph_cap_string(got));
2232 		ceph_add_rw_context(fi, &rw_ctx);
2233 		ret = generic_file_read_iter(iocb, to);
2234 		ceph_del_rw_context(fi, &rw_ctx);
2235 	}
2236 
2237 	doutc(cl, "%p %llx.%llx dropping cap refs on %s = %d\n",
2238 	      inode, ceph_vinop(inode), ceph_cap_string(got), (int)ret);
2239 	ceph_put_cap_refs(ci, got);
2240 
2241 	if (direct_lock)
2242 		ceph_end_io_direct(inode);
2243 	else
2244 		ceph_end_io_read(inode);
2245 
2246 	if (retry_op > HAVE_RETRIED && ret >= 0) {
2247 		int statret;
2248 		struct page *page = NULL;
2249 		loff_t i_size;
2250 		int mask = CEPH_STAT_CAP_SIZE;
2251 		if (retry_op == READ_INLINE) {
2252 			page = __page_cache_alloc(GFP_KERNEL);
2253 			if (!page)
2254 				return -ENOMEM;
2255 
2256 			mask = CEPH_STAT_CAP_INLINE_DATA;
2257 		}
2258 
2259 		statret = __ceph_do_getattr(inode, page, mask, !!page);
2260 		if (statret < 0) {
2261 			if (page)
2262 				__free_page(page);
2263 			if (statret == -ENODATA) {
2264 				BUG_ON(retry_op != READ_INLINE);
2265 				goto again;
2266 			}
2267 			return statret;
2268 		}
2269 
2270 		i_size = i_size_read(inode);
2271 		if (retry_op == READ_INLINE) {
2272 			BUG_ON(ret > 0 || read > 0);
2273 			if (iocb->ki_pos < i_size &&
2274 			    iocb->ki_pos < PAGE_SIZE) {
2275 				loff_t end = min_t(loff_t, i_size,
2276 						   iocb->ki_pos + len);
2277 				end = min_t(loff_t, end, PAGE_SIZE);
2278 				if (statret < end)
2279 					zero_user_segment(page, statret, end);
2280 				ret = copy_page_to_iter(page,
2281 						iocb->ki_pos & ~PAGE_MASK,
2282 						end - iocb->ki_pos, to);
2283 				iocb->ki_pos += ret;
2284 				read += ret;
2285 			}
2286 			if (iocb->ki_pos < i_size && read < len) {
2287 				size_t zlen = min_t(size_t, len - read,
2288 						    i_size - iocb->ki_pos);
2289 				ret = iov_iter_zero(zlen, to);
2290 				iocb->ki_pos += ret;
2291 				read += ret;
2292 			}
2293 			__free_pages(page, 0);
2294 			return read;
2295 		}
2296 
2297 		/* hit EOF or hole? */
2298 		if (retry_op == CHECK_EOF && iocb->ki_pos < i_size &&
2299 		    ret < len) {
2300 			doutc(cl, "may hit hole, ppos %lld < size %lld, reading more\n",
2301 			      iocb->ki_pos, i_size);
2302 
2303 			read += ret;
2304 			len -= ret;
2305 			retry_op = HAVE_RETRIED;
2306 			goto again;
2307 		}
2308 	}
2309 
2310 	if (ret >= 0)
2311 		ret += read;
2312 
2313 	return ret;
2314 }
2315 
2316 /*
2317  * Wrap filemap_splice_read with checks for cap bits on the inode.
2318  * Atomically grab references, so that those bits are not released
2319  * back to the MDS mid-read.
2320  */
2321 static ssize_t ceph_splice_read(struct file *in, loff_t *ppos,
2322 				struct pipe_inode_info *pipe,
2323 				size_t len, unsigned int flags)
2324 {
2325 	struct ceph_file_info *fi = in->private_data;
2326 	struct inode *inode = file_inode(in);
2327 	struct ceph_inode_info *ci = ceph_inode(inode);
2328 	ssize_t ret;
2329 	int want = 0, got = 0;
2330 	CEPH_DEFINE_RW_CONTEXT(rw_ctx, 0);
2331 
2332 	dout("splice_read %p %llx.%llx %llu~%zu trying to get caps on %p\n",
2333 	     inode, ceph_vinop(inode), *ppos, len, inode);
2334 
2335 	if (ceph_inode_is_shutdown(inode))
2336 		return -ESTALE;
2337 
2338 	if (ceph_has_inline_data(ci) ||
2339 	    (fi->flags & CEPH_F_SYNC))
2340 		return copy_splice_read(in, ppos, pipe, len, flags);
2341 
2342 	ret = ceph_start_io_read(inode);
2343 	if (ret)
2344 		return ret;
2345 
2346 	want = CEPH_CAP_FILE_CACHE;
2347 	if (fi->fmode & CEPH_FILE_MODE_LAZY)
2348 		want |= CEPH_CAP_FILE_LAZYIO;
2349 
2350 	ret = ceph_get_caps(in, CEPH_CAP_FILE_RD, want, -1, &got);
2351 	if (ret < 0)
2352 		goto out_end;
2353 
2354 	if ((got & (CEPH_CAP_FILE_CACHE | CEPH_CAP_FILE_LAZYIO)) == 0) {
2355 		dout("splice_read/sync %p %llx.%llx %llu~%zu got cap refs on %s\n",
2356 		     inode, ceph_vinop(inode), *ppos, len,
2357 		     ceph_cap_string(got));
2358 
2359 		ceph_put_cap_refs(ci, got);
2360 		ceph_end_io_read(inode);
2361 		return copy_splice_read(in, ppos, pipe, len, flags);
2362 	}
2363 
2364 	dout("splice_read %p %llx.%llx %llu~%zu got cap refs on %s\n",
2365 	     inode, ceph_vinop(inode), *ppos, len, ceph_cap_string(got));
2366 
2367 	rw_ctx.caps = got;
2368 	ceph_add_rw_context(fi, &rw_ctx);
2369 	ret = filemap_splice_read(in, ppos, pipe, len, flags);
2370 	ceph_del_rw_context(fi, &rw_ctx);
2371 
2372 	dout("splice_read %p %llx.%llx dropping cap refs on %s = %zd\n",
2373 	     inode, ceph_vinop(inode), ceph_cap_string(got), ret);
2374 
2375 	ceph_put_cap_refs(ci, got);
2376 out_end:
2377 	ceph_end_io_read(inode);
2378 	return ret;
2379 }
2380 
2381 /*
2382  * Take cap references to avoid releasing caps to MDS mid-write.
2383  *
2384  * If we are synchronous, and write with an old snap context, the OSD
2385  * may return EOLDSNAPC.  In that case, retry the write.. _after_
2386  * dropping our cap refs and allowing the pending snap to logically
2387  * complete _before_ this write occurs.
2388  *
2389  * If we are near ENOSPC, write synchronously.
2390  */
2391 static ssize_t ceph_write_iter(struct kiocb *iocb, struct iov_iter *from)
2392 {
2393 	struct file *file = iocb->ki_filp;
2394 	struct ceph_file_info *fi = file->private_data;
2395 	struct inode *inode = file_inode(file);
2396 	struct ceph_inode_info *ci = ceph_inode(inode);
2397 	struct ceph_fs_client *fsc = ceph_inode_to_fs_client(inode);
2398 	struct ceph_client *cl = fsc->client;
2399 	struct ceph_osd_client *osdc = &fsc->client->osdc;
2400 	struct ceph_cap_flush *prealloc_cf;
2401 	ssize_t count, written = 0;
2402 	int err, want = 0, got;
2403 	bool direct_lock = false;
2404 	u32 map_flags;
2405 	u64 pool_flags;
2406 	loff_t pos;
2407 	loff_t limit = max(i_size_read(inode), fsc->max_file_size);
2408 
2409 	if (ceph_inode_is_shutdown(inode))
2410 		return -ESTALE;
2411 
2412 	if (ceph_snap(inode) != CEPH_NOSNAP)
2413 		return -EROFS;
2414 
2415 	prealloc_cf = ceph_alloc_cap_flush();
2416 	if (!prealloc_cf)
2417 		return -ENOMEM;
2418 
2419 	if ((iocb->ki_flags & (IOCB_DIRECT | IOCB_APPEND)) == IOCB_DIRECT)
2420 		direct_lock = true;
2421 
2422 retry_snap:
2423 	err = direct_lock ? ceph_start_io_direct(inode) :
2424 			    ceph_start_io_write(inode);
2425 	if (err)
2426 		goto out_unlocked;
2427 
2428 	if (iocb->ki_flags & IOCB_APPEND) {
2429 		err = ceph_do_getattr(inode, CEPH_STAT_CAP_SIZE, false);
2430 		if (err < 0)
2431 			goto out;
2432 	}
2433 
2434 	err = generic_write_checks(iocb, from);
2435 	if (err <= 0)
2436 		goto out;
2437 
2438 	pos = iocb->ki_pos;
2439 	if (unlikely(pos >= limit)) {
2440 		err = -EFBIG;
2441 		goto out;
2442 	} else {
2443 		iov_iter_truncate(from, limit - pos);
2444 	}
2445 
2446 	count = iov_iter_count(from);
2447 	if (ceph_quota_is_max_bytes_exceeded(inode, pos + count)) {
2448 		err = -EDQUOT;
2449 		goto out;
2450 	}
2451 
2452 	down_read(&osdc->lock);
2453 	map_flags = osdc->osdmap->flags;
2454 	pool_flags = ceph_pg_pool_flags(osdc->osdmap, ci->i_layout.pool_id);
2455 	up_read(&osdc->lock);
2456 	if ((map_flags & CEPH_OSDMAP_FULL) ||
2457 	    (pool_flags & CEPH_POOL_FLAG_FULL)) {
2458 		err = -ENOSPC;
2459 		goto out;
2460 	}
2461 
2462 	err = file_remove_privs(file);
2463 	if (err)
2464 		goto out;
2465 
2466 	doutc(cl, "%p %llx.%llx %llu~%zd getting caps. i_size %llu\n",
2467 	      inode, ceph_vinop(inode), pos, count,
2468 	      i_size_read(inode));
2469 	if (!(fi->flags & CEPH_F_SYNC) && !direct_lock)
2470 		want |= CEPH_CAP_FILE_BUFFER;
2471 	if (fi->fmode & CEPH_FILE_MODE_LAZY)
2472 		want |= CEPH_CAP_FILE_LAZYIO;
2473 	got = 0;
2474 	err = ceph_get_caps(file, CEPH_CAP_FILE_WR, want, pos + count, &got);
2475 	if (err < 0)
2476 		goto out;
2477 
2478 	err = file_update_time(file);
2479 	if (err)
2480 		goto out_caps;
2481 
2482 	inode_inc_iversion_raw(inode);
2483 
2484 	doutc(cl, "%p %llx.%llx %llu~%zd got cap refs on %s\n",
2485 	      inode, ceph_vinop(inode), pos, count, ceph_cap_string(got));
2486 
2487 	if ((got & (CEPH_CAP_FILE_BUFFER|CEPH_CAP_FILE_LAZYIO)) == 0 ||
2488 	    (iocb->ki_flags & IOCB_DIRECT) || (fi->flags & CEPH_F_SYNC) ||
2489 	    (ci->i_ceph_flags & CEPH_I_ERROR_WRITE)) {
2490 		struct ceph_snap_context *snapc;
2491 		struct iov_iter data;
2492 
2493 		spin_lock(&ci->i_ceph_lock);
2494 		if (__ceph_have_pending_cap_snap(ci)) {
2495 			struct ceph_cap_snap *capsnap =
2496 					list_last_entry(&ci->i_cap_snaps,
2497 							struct ceph_cap_snap,
2498 							ci_item);
2499 			snapc = ceph_get_snap_context(capsnap->context);
2500 		} else {
2501 			BUG_ON(!ci->i_head_snapc);
2502 			snapc = ceph_get_snap_context(ci->i_head_snapc);
2503 		}
2504 		spin_unlock(&ci->i_ceph_lock);
2505 
2506 		/* we might need to revert back to that point */
2507 		data = *from;
2508 		if ((iocb->ki_flags & IOCB_DIRECT) && !IS_ENCRYPTED(inode))
2509 			written = ceph_direct_read_write(iocb, &data, snapc,
2510 							 &prealloc_cf);
2511 		else
2512 			written = ceph_sync_write(iocb, &data, pos, snapc);
2513 		if (direct_lock)
2514 			ceph_end_io_direct(inode);
2515 		else
2516 			ceph_end_io_write(inode);
2517 		if (written > 0)
2518 			iov_iter_advance(from, written);
2519 		ceph_put_snap_context(snapc);
2520 	} else {
2521 		/*
2522 		 * No need to acquire the i_truncate_mutex. Because
2523 		 * the MDS revokes Fwb caps before sending truncate
2524 		 * message to us. We can't get Fwb cap while there
2525 		 * are pending vmtruncate. So write and vmtruncate
2526 		 * can not run at the same time
2527 		 */
2528 		written = generic_perform_write(iocb, from);
2529 		ceph_end_io_write(inode);
2530 	}
2531 
2532 	if (written >= 0) {
2533 		int dirty;
2534 
2535 		spin_lock(&ci->i_ceph_lock);
2536 		dirty = __ceph_mark_dirty_caps(ci, CEPH_CAP_FILE_WR,
2537 					       &prealloc_cf);
2538 		spin_unlock(&ci->i_ceph_lock);
2539 		if (dirty)
2540 			__mark_inode_dirty(inode, dirty);
2541 		if (ceph_quota_is_max_bytes_approaching(inode, iocb->ki_pos))
2542 			ceph_check_caps(ci, CHECK_CAPS_FLUSH);
2543 	}
2544 
2545 	doutc(cl, "%p %llx.%llx %llu~%u  dropping cap refs on %s\n",
2546 	      inode, ceph_vinop(inode), pos, (unsigned)count,
2547 	      ceph_cap_string(got));
2548 	ceph_put_cap_refs(ci, got);
2549 
2550 	if (written == -EOLDSNAPC) {
2551 		doutc(cl, "%p %llx.%llx %llu~%u" "got EOLDSNAPC, retrying\n",
2552 		      inode, ceph_vinop(inode), pos, (unsigned)count);
2553 		goto retry_snap;
2554 	}
2555 
2556 	if (written >= 0) {
2557 		if ((map_flags & CEPH_OSDMAP_NEARFULL) ||
2558 		    (pool_flags & CEPH_POOL_FLAG_NEARFULL))
2559 			iocb->ki_flags |= IOCB_DSYNC;
2560 		written = generic_write_sync(iocb, written);
2561 	}
2562 
2563 	goto out_unlocked;
2564 out_caps:
2565 	ceph_put_cap_refs(ci, got);
2566 out:
2567 	if (direct_lock)
2568 		ceph_end_io_direct(inode);
2569 	else
2570 		ceph_end_io_write(inode);
2571 out_unlocked:
2572 	ceph_free_cap_flush(prealloc_cf);
2573 	return written ? written : err;
2574 }
2575 
2576 /*
2577  * llseek.  be sure to verify file size on SEEK_END.
2578  */
2579 static loff_t ceph_llseek(struct file *file, loff_t offset, int whence)
2580 {
2581 	if (whence == SEEK_END || whence == SEEK_DATA || whence == SEEK_HOLE) {
2582 		struct inode *inode = file_inode(file);
2583 		int ret;
2584 
2585 		ret = ceph_do_getattr(inode, CEPH_STAT_CAP_SIZE, false);
2586 		if (ret < 0)
2587 			return ret;
2588 	}
2589 	return generic_file_llseek(file, offset, whence);
2590 }
2591 
2592 static inline void ceph_zero_partial_page(struct inode *inode,
2593 		loff_t offset, size_t size)
2594 {
2595 	struct folio *folio;
2596 
2597 	folio = filemap_lock_folio(inode->i_mapping, offset >> PAGE_SHIFT);
2598 	if (IS_ERR(folio))
2599 		return;
2600 
2601 	folio_wait_writeback(folio);
2602 	folio_zero_range(folio, offset_in_folio(folio, offset), size);
2603 	folio_unlock(folio);
2604 	folio_put(folio);
2605 }
2606 
2607 static void ceph_zero_pagecache_range(struct inode *inode, loff_t offset,
2608 				      loff_t length)
2609 {
2610 	loff_t nearly = round_up(offset, PAGE_SIZE);
2611 	if (offset < nearly) {
2612 		loff_t size = nearly - offset;
2613 		if (length < size)
2614 			size = length;
2615 		ceph_zero_partial_page(inode, offset, size);
2616 		offset += size;
2617 		length -= size;
2618 	}
2619 	if (length >= PAGE_SIZE) {
2620 		loff_t size = round_down(length, PAGE_SIZE);
2621 		truncate_pagecache_range(inode, offset, offset + size - 1);
2622 		offset += size;
2623 		length -= size;
2624 	}
2625 	if (length)
2626 		ceph_zero_partial_page(inode, offset, length);
2627 }
2628 
2629 static int ceph_zero_partial_object(struct inode *inode,
2630 				    loff_t offset, loff_t *length)
2631 {
2632 	struct ceph_inode_info *ci = ceph_inode(inode);
2633 	struct ceph_fs_client *fsc = ceph_inode_to_fs_client(inode);
2634 	struct ceph_osd_request *req;
2635 	struct ceph_snap_context *snapc;
2636 	int ret = 0;
2637 	loff_t zero = 0;
2638 	int op;
2639 
2640 	if (ceph_inode_is_shutdown(inode))
2641 		return -EIO;
2642 
2643 	if (!length) {
2644 		op = offset ? CEPH_OSD_OP_DELETE : CEPH_OSD_OP_TRUNCATE;
2645 		length = &zero;
2646 	} else {
2647 		op = CEPH_OSD_OP_ZERO;
2648 	}
2649 
2650 	spin_lock(&ci->i_ceph_lock);
2651 	if (__ceph_have_pending_cap_snap(ci)) {
2652 		struct ceph_cap_snap *capsnap =
2653 				list_last_entry(&ci->i_cap_snaps,
2654 						struct ceph_cap_snap,
2655 						ci_item);
2656 		snapc = ceph_get_snap_context(capsnap->context);
2657 	} else {
2658 		BUG_ON(!ci->i_head_snapc);
2659 		snapc = ceph_get_snap_context(ci->i_head_snapc);
2660 	}
2661 	spin_unlock(&ci->i_ceph_lock);
2662 
2663 	req = ceph_osdc_new_request(&fsc->client->osdc, &ci->i_layout,
2664 					ceph_vino(inode),
2665 					offset, length,
2666 					0, 1, op,
2667 					CEPH_OSD_FLAG_WRITE,
2668 					snapc, 0, 0, false);
2669 	if (IS_ERR(req)) {
2670 		ret = PTR_ERR(req);
2671 		goto out;
2672 	}
2673 
2674 	req->r_mtime = inode_get_mtime(inode);
2675 	ceph_osdc_start_request(&fsc->client->osdc, req);
2676 	ret = ceph_osdc_wait_request(&fsc->client->osdc, req);
2677 	if (ret == -ENOENT)
2678 		ret = 0;
2679 	ceph_osdc_put_request(req);
2680 
2681 out:
2682 	ceph_put_snap_context(snapc);
2683 	return ret;
2684 }
2685 
2686 static int ceph_zero_objects(struct inode *inode, loff_t offset, loff_t length)
2687 {
2688 	int ret = 0;
2689 	struct ceph_inode_info *ci = ceph_inode(inode);
2690 	s32 stripe_unit = ci->i_layout.stripe_unit;
2691 	s32 stripe_count = ci->i_layout.stripe_count;
2692 	s32 object_size = ci->i_layout.object_size;
2693 	u64 object_set_size = (u64) object_size * stripe_count;
2694 	u64 nearly, t;
2695 
2696 	/* round offset up to next period boundary */
2697 	nearly = offset + object_set_size - 1;
2698 	t = nearly;
2699 	nearly -= do_div(t, object_set_size);
2700 
2701 	while (length && offset < nearly) {
2702 		loff_t size = length;
2703 		ret = ceph_zero_partial_object(inode, offset, &size);
2704 		if (ret < 0)
2705 			return ret;
2706 		offset += size;
2707 		length -= size;
2708 	}
2709 	while (length >= object_set_size) {
2710 		int i;
2711 		loff_t pos = offset;
2712 		for (i = 0; i < stripe_count; ++i) {
2713 			ret = ceph_zero_partial_object(inode, pos, NULL);
2714 			if (ret < 0)
2715 				return ret;
2716 			pos += stripe_unit;
2717 		}
2718 		offset += object_set_size;
2719 		length -= object_set_size;
2720 	}
2721 	while (length) {
2722 		loff_t size = length;
2723 		ret = ceph_zero_partial_object(inode, offset, &size);
2724 		if (ret < 0)
2725 			return ret;
2726 		offset += size;
2727 		length -= size;
2728 	}
2729 	return ret;
2730 }
2731 
2732 static long ceph_fallocate(struct file *file, int mode,
2733 				loff_t offset, loff_t length)
2734 {
2735 	struct ceph_file_info *fi = file->private_data;
2736 	struct inode *inode = file_inode(file);
2737 	struct ceph_inode_info *ci = ceph_inode(inode);
2738 	struct ceph_cap_flush *prealloc_cf;
2739 	struct ceph_client *cl = ceph_inode_to_client(inode);
2740 	int want, got = 0;
2741 	int dirty;
2742 	int ret = 0;
2743 	loff_t endoff = 0;
2744 	loff_t size;
2745 
2746 	doutc(cl, "%p %llx.%llx mode %x, offset %llu length %llu\n",
2747 	      inode, ceph_vinop(inode), mode, offset, length);
2748 
2749 	if (mode != (FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE))
2750 		return -EOPNOTSUPP;
2751 
2752 	if (!S_ISREG(inode->i_mode))
2753 		return -EOPNOTSUPP;
2754 
2755 	if (IS_ENCRYPTED(inode))
2756 		return -EOPNOTSUPP;
2757 
2758 	prealloc_cf = ceph_alloc_cap_flush();
2759 	if (!prealloc_cf)
2760 		return -ENOMEM;
2761 
2762 	inode_lock(inode);
2763 
2764 	if (ceph_snap(inode) != CEPH_NOSNAP) {
2765 		ret = -EROFS;
2766 		goto unlock;
2767 	}
2768 
2769 	size = i_size_read(inode);
2770 
2771 	/* Are we punching a hole beyond EOF? */
2772 	if (offset >= size)
2773 		goto unlock;
2774 	if ((offset + length) > size)
2775 		length = size - offset;
2776 
2777 	if (fi->fmode & CEPH_FILE_MODE_LAZY)
2778 		want = CEPH_CAP_FILE_BUFFER | CEPH_CAP_FILE_LAZYIO;
2779 	else
2780 		want = CEPH_CAP_FILE_BUFFER;
2781 
2782 	ret = ceph_get_caps(file, CEPH_CAP_FILE_WR, want, endoff, &got);
2783 	if (ret < 0)
2784 		goto unlock;
2785 
2786 	ret = file_modified(file);
2787 	if (ret)
2788 		goto put_caps;
2789 
2790 	filemap_invalidate_lock(inode->i_mapping);
2791 	ceph_fscache_invalidate(inode, false);
2792 	ceph_zero_pagecache_range(inode, offset, length);
2793 	ret = ceph_zero_objects(inode, offset, length);
2794 
2795 	if (!ret) {
2796 		spin_lock(&ci->i_ceph_lock);
2797 		dirty = __ceph_mark_dirty_caps(ci, CEPH_CAP_FILE_WR,
2798 					       &prealloc_cf);
2799 		spin_unlock(&ci->i_ceph_lock);
2800 		if (dirty)
2801 			__mark_inode_dirty(inode, dirty);
2802 	}
2803 	filemap_invalidate_unlock(inode->i_mapping);
2804 
2805 put_caps:
2806 	ceph_put_cap_refs(ci, got);
2807 unlock:
2808 	inode_unlock(inode);
2809 	ceph_free_cap_flush(prealloc_cf);
2810 	return ret;
2811 }
2812 
2813 /*
2814  * This function tries to get FILE_WR capabilities for dst_ci and FILE_RD for
2815  * src_ci.  Two attempts are made to obtain both caps, and an error is return if
2816  * this fails; zero is returned on success.
2817  */
2818 static int get_rd_wr_caps(struct file *src_filp, int *src_got,
2819 			  struct file *dst_filp,
2820 			  loff_t dst_endoff, int *dst_got)
2821 {
2822 	int ret = 0;
2823 	bool retrying = false;
2824 
2825 retry_caps:
2826 	ret = ceph_get_caps(dst_filp, CEPH_CAP_FILE_WR, CEPH_CAP_FILE_BUFFER,
2827 			    dst_endoff, dst_got);
2828 	if (ret < 0)
2829 		return ret;
2830 
2831 	/*
2832 	 * Since we're already holding the FILE_WR capability for the dst file,
2833 	 * we would risk a deadlock by using ceph_get_caps.  Thus, we'll do some
2834 	 * retry dance instead to try to get both capabilities.
2835 	 */
2836 	ret = ceph_try_get_caps(file_inode(src_filp),
2837 				CEPH_CAP_FILE_RD, CEPH_CAP_FILE_SHARED,
2838 				false, src_got);
2839 	if (ret <= 0) {
2840 		/* Start by dropping dst_ci caps and getting src_ci caps */
2841 		ceph_put_cap_refs(ceph_inode(file_inode(dst_filp)), *dst_got);
2842 		if (retrying) {
2843 			if (!ret)
2844 				/* ceph_try_get_caps masks EAGAIN */
2845 				ret = -EAGAIN;
2846 			return ret;
2847 		}
2848 		ret = ceph_get_caps(src_filp, CEPH_CAP_FILE_RD,
2849 				    CEPH_CAP_FILE_SHARED, -1, src_got);
2850 		if (ret < 0)
2851 			return ret;
2852 		/*... drop src_ci caps too, and retry */
2853 		ceph_put_cap_refs(ceph_inode(file_inode(src_filp)), *src_got);
2854 		retrying = true;
2855 		goto retry_caps;
2856 	}
2857 	return ret;
2858 }
2859 
2860 static void put_rd_wr_caps(struct ceph_inode_info *src_ci, int src_got,
2861 			   struct ceph_inode_info *dst_ci, int dst_got)
2862 {
2863 	ceph_put_cap_refs(src_ci, src_got);
2864 	ceph_put_cap_refs(dst_ci, dst_got);
2865 }
2866 
2867 /*
2868  * This function does several size-related checks, returning an error if:
2869  *  - source file is smaller than off+len
2870  *  - destination file size is not OK (inode_newsize_ok())
2871  *  - max bytes quotas is exceeded
2872  */
2873 static int is_file_size_ok(struct inode *src_inode, struct inode *dst_inode,
2874 			   loff_t src_off, loff_t dst_off, size_t len)
2875 {
2876 	struct ceph_client *cl = ceph_inode_to_client(src_inode);
2877 	loff_t size, endoff;
2878 
2879 	size = i_size_read(src_inode);
2880 	/*
2881 	 * Don't copy beyond source file EOF.  Instead of simply setting length
2882 	 * to (size - src_off), just drop to VFS default implementation, as the
2883 	 * local i_size may be stale due to other clients writing to the source
2884 	 * inode.
2885 	 */
2886 	if (src_off + len > size) {
2887 		doutc(cl, "Copy beyond EOF (%llu + %zu > %llu)\n", src_off,
2888 		      len, size);
2889 		return -EOPNOTSUPP;
2890 	}
2891 	size = i_size_read(dst_inode);
2892 
2893 	endoff = dst_off + len;
2894 	if (inode_newsize_ok(dst_inode, endoff))
2895 		return -EOPNOTSUPP;
2896 
2897 	if (ceph_quota_is_max_bytes_exceeded(dst_inode, endoff))
2898 		return -EDQUOT;
2899 
2900 	return 0;
2901 }
2902 
2903 static struct ceph_osd_request *
2904 ceph_alloc_copyfrom_request(struct ceph_osd_client *osdc,
2905 			    u64 src_snapid,
2906 			    struct ceph_object_id *src_oid,
2907 			    struct ceph_object_locator *src_oloc,
2908 			    struct ceph_object_id *dst_oid,
2909 			    struct ceph_object_locator *dst_oloc,
2910 			    u32 truncate_seq, u64 truncate_size)
2911 {
2912 	struct ceph_osd_request *req;
2913 	int ret;
2914 	u32 src_fadvise_flags =
2915 		CEPH_OSD_OP_FLAG_FADVISE_SEQUENTIAL |
2916 		CEPH_OSD_OP_FLAG_FADVISE_NOCACHE;
2917 	u32 dst_fadvise_flags =
2918 		CEPH_OSD_OP_FLAG_FADVISE_SEQUENTIAL |
2919 		CEPH_OSD_OP_FLAG_FADVISE_DONTNEED;
2920 
2921 	req = ceph_osdc_alloc_request(osdc, NULL, 1, false, GFP_KERNEL);
2922 	if (!req)
2923 		return ERR_PTR(-ENOMEM);
2924 
2925 	req->r_flags = CEPH_OSD_FLAG_WRITE;
2926 
2927 	ceph_oloc_copy(&req->r_t.base_oloc, dst_oloc);
2928 	ceph_oid_copy(&req->r_t.base_oid, dst_oid);
2929 
2930 	ret = osd_req_op_copy_from_init(req, src_snapid, 0,
2931 					src_oid, src_oloc,
2932 					src_fadvise_flags,
2933 					dst_fadvise_flags,
2934 					truncate_seq,
2935 					truncate_size,
2936 					CEPH_OSD_COPY_FROM_FLAG_TRUNCATE_SEQ);
2937 	if (ret)
2938 		goto out;
2939 
2940 	ret = ceph_osdc_alloc_messages(req, GFP_KERNEL);
2941 	if (ret)
2942 		goto out;
2943 
2944 	return req;
2945 
2946 out:
2947 	ceph_osdc_put_request(req);
2948 	return ERR_PTR(ret);
2949 }
2950 
2951 static ssize_t ceph_do_objects_copy(struct ceph_inode_info *src_ci, u64 *src_off,
2952 				    struct ceph_inode_info *dst_ci, u64 *dst_off,
2953 				    struct ceph_fs_client *fsc,
2954 				    size_t len, unsigned int flags)
2955 {
2956 	struct ceph_object_locator src_oloc, dst_oloc;
2957 	struct ceph_object_id src_oid, dst_oid;
2958 	struct ceph_osd_client *osdc;
2959 	struct ceph_osd_request *req;
2960 	ssize_t bytes = 0;
2961 	u64 src_objnum, src_objoff, dst_objnum, dst_objoff;
2962 	u32 src_objlen, dst_objlen;
2963 	u32 object_size = src_ci->i_layout.object_size;
2964 	struct ceph_client *cl = fsc->client;
2965 	int ret;
2966 
2967 	src_oloc.pool = src_ci->i_layout.pool_id;
2968 	src_oloc.pool_ns = ceph_try_get_string(src_ci->i_layout.pool_ns);
2969 	dst_oloc.pool = dst_ci->i_layout.pool_id;
2970 	dst_oloc.pool_ns = ceph_try_get_string(dst_ci->i_layout.pool_ns);
2971 	osdc = &fsc->client->osdc;
2972 
2973 	while (len >= object_size) {
2974 		ceph_calc_file_object_mapping(&src_ci->i_layout, *src_off,
2975 					      object_size, &src_objnum,
2976 					      &src_objoff, &src_objlen);
2977 		ceph_calc_file_object_mapping(&dst_ci->i_layout, *dst_off,
2978 					      object_size, &dst_objnum,
2979 					      &dst_objoff, &dst_objlen);
2980 		ceph_oid_init(&src_oid);
2981 		ceph_oid_printf(&src_oid, "%llx.%08llx",
2982 				src_ci->i_vino.ino, src_objnum);
2983 		ceph_oid_init(&dst_oid);
2984 		ceph_oid_printf(&dst_oid, "%llx.%08llx",
2985 				dst_ci->i_vino.ino, dst_objnum);
2986 		/* Do an object remote copy */
2987 		req = ceph_alloc_copyfrom_request(osdc, src_ci->i_vino.snap,
2988 						  &src_oid, &src_oloc,
2989 						  &dst_oid, &dst_oloc,
2990 						  dst_ci->i_truncate_seq,
2991 						  dst_ci->i_truncate_size);
2992 		if (IS_ERR(req))
2993 			ret = PTR_ERR(req);
2994 		else {
2995 			ceph_osdc_start_request(osdc, req);
2996 			ret = ceph_osdc_wait_request(osdc, req);
2997 			ceph_update_copyfrom_metrics(&fsc->mdsc->metric,
2998 						     req->r_start_latency,
2999 						     req->r_end_latency,
3000 						     object_size, ret);
3001 			ceph_osdc_put_request(req);
3002 		}
3003 		if (ret) {
3004 			if (ret == -EOPNOTSUPP) {
3005 				fsc->have_copy_from2 = false;
3006 				pr_notice_client(cl,
3007 					"OSDs don't support copy-from2; disabling copy offload\n");
3008 			}
3009 			doutc(cl, "returned %d\n", ret);
3010 			if (bytes <= 0)
3011 				bytes = ret;
3012 			goto out;
3013 		}
3014 		len -= object_size;
3015 		bytes += object_size;
3016 		*src_off += object_size;
3017 		*dst_off += object_size;
3018 	}
3019 
3020 out:
3021 	ceph_oloc_destroy(&src_oloc);
3022 	ceph_oloc_destroy(&dst_oloc);
3023 	return bytes;
3024 }
3025 
3026 static ssize_t __ceph_copy_file_range(struct file *src_file, loff_t src_off,
3027 				      struct file *dst_file, loff_t dst_off,
3028 				      size_t len, unsigned int flags)
3029 {
3030 	struct inode *src_inode = file_inode(src_file);
3031 	struct inode *dst_inode = file_inode(dst_file);
3032 	struct ceph_inode_info *src_ci = ceph_inode(src_inode);
3033 	struct ceph_inode_info *dst_ci = ceph_inode(dst_inode);
3034 	struct ceph_cap_flush *prealloc_cf;
3035 	struct ceph_fs_client *src_fsc = ceph_inode_to_fs_client(src_inode);
3036 	struct ceph_client *cl = src_fsc->client;
3037 	loff_t size;
3038 	ssize_t ret = -EIO, bytes;
3039 	u64 src_objnum, dst_objnum, src_objoff, dst_objoff;
3040 	u32 src_objlen, dst_objlen;
3041 	int src_got = 0, dst_got = 0, err, dirty;
3042 
3043 	if (src_inode->i_sb != dst_inode->i_sb) {
3044 		struct ceph_fs_client *dst_fsc = ceph_inode_to_fs_client(dst_inode);
3045 
3046 		if (ceph_fsid_compare(&src_fsc->client->fsid,
3047 				      &dst_fsc->client->fsid)) {
3048 			dout("Copying files across clusters: src: %pU dst: %pU\n",
3049 			     &src_fsc->client->fsid, &dst_fsc->client->fsid);
3050 			return -EXDEV;
3051 		}
3052 	}
3053 	if (ceph_snap(dst_inode) != CEPH_NOSNAP)
3054 		return -EROFS;
3055 
3056 	/*
3057 	 * Some of the checks below will return -EOPNOTSUPP, which will force a
3058 	 * fallback to the default VFS copy_file_range implementation.  This is
3059 	 * desirable in several cases (for ex, the 'len' is smaller than the
3060 	 * size of the objects, or in cases where that would be more
3061 	 * efficient).
3062 	 */
3063 
3064 	if (ceph_test_mount_opt(src_fsc, NOCOPYFROM))
3065 		return -EOPNOTSUPP;
3066 
3067 	if (!src_fsc->have_copy_from2)
3068 		return -EOPNOTSUPP;
3069 
3070 	/*
3071 	 * Striped file layouts require that we copy partial objects, but the
3072 	 * OSD copy-from operation only supports full-object copies.  Limit
3073 	 * this to non-striped file layouts for now.
3074 	 */
3075 	if ((src_ci->i_layout.stripe_unit != dst_ci->i_layout.stripe_unit) ||
3076 	    (src_ci->i_layout.stripe_count != 1) ||
3077 	    (dst_ci->i_layout.stripe_count != 1) ||
3078 	    (src_ci->i_layout.object_size != dst_ci->i_layout.object_size)) {
3079 		doutc(cl, "Invalid src/dst files layout\n");
3080 		return -EOPNOTSUPP;
3081 	}
3082 
3083 	/* Every encrypted inode gets its own key, so we can't offload them */
3084 	if (IS_ENCRYPTED(src_inode) || IS_ENCRYPTED(dst_inode))
3085 		return -EOPNOTSUPP;
3086 
3087 	if (len < src_ci->i_layout.object_size)
3088 		return -EOPNOTSUPP; /* no remote copy will be done */
3089 
3090 	prealloc_cf = ceph_alloc_cap_flush();
3091 	if (!prealloc_cf)
3092 		return -ENOMEM;
3093 
3094 	/* Start by sync'ing the source and destination files */
3095 	ret = file_write_and_wait_range(src_file, src_off, (src_off + len));
3096 	if (ret < 0) {
3097 		doutc(cl, "failed to write src file (%zd)\n", ret);
3098 		goto out;
3099 	}
3100 	ret = file_write_and_wait_range(dst_file, dst_off, (dst_off + len));
3101 	if (ret < 0) {
3102 		doutc(cl, "failed to write dst file (%zd)\n", ret);
3103 		goto out;
3104 	}
3105 
3106 	/*
3107 	 * We need FILE_WR caps for dst_ci and FILE_RD for src_ci as other
3108 	 * clients may have dirty data in their caches.  And OSDs know nothing
3109 	 * about caps, so they can't safely do the remote object copies.
3110 	 */
3111 	err = get_rd_wr_caps(src_file, &src_got,
3112 			     dst_file, (dst_off + len), &dst_got);
3113 	if (err < 0) {
3114 		doutc(cl, "get_rd_wr_caps returned %d\n", err);
3115 		ret = -EOPNOTSUPP;
3116 		goto out;
3117 	}
3118 
3119 	ret = is_file_size_ok(src_inode, dst_inode, src_off, dst_off, len);
3120 	if (ret < 0)
3121 		goto out_caps;
3122 
3123 	/* Drop dst file cached pages */
3124 	ceph_fscache_invalidate(dst_inode, false);
3125 	ret = invalidate_inode_pages2_range(dst_inode->i_mapping,
3126 					    dst_off >> PAGE_SHIFT,
3127 					    (dst_off + len) >> PAGE_SHIFT);
3128 	if (ret < 0) {
3129 		doutc(cl, "Failed to invalidate inode pages (%zd)\n",
3130 			    ret);
3131 		ret = 0; /* XXX */
3132 	}
3133 	ceph_calc_file_object_mapping(&src_ci->i_layout, src_off,
3134 				      src_ci->i_layout.object_size,
3135 				      &src_objnum, &src_objoff, &src_objlen);
3136 	ceph_calc_file_object_mapping(&dst_ci->i_layout, dst_off,
3137 				      dst_ci->i_layout.object_size,
3138 				      &dst_objnum, &dst_objoff, &dst_objlen);
3139 	/* object-level offsets need to the same */
3140 	if (src_objoff != dst_objoff) {
3141 		ret = -EOPNOTSUPP;
3142 		goto out_caps;
3143 	}
3144 
3145 	/*
3146 	 * Do a manual copy if the object offset isn't object aligned.
3147 	 * 'src_objlen' contains the bytes left until the end of the object,
3148 	 * starting at the src_off
3149 	 */
3150 	if (src_objoff) {
3151 		doutc(cl, "Initial partial copy of %u bytes\n", src_objlen);
3152 
3153 		/*
3154 		 * we need to temporarily drop all caps as we'll be calling
3155 		 * {read,write}_iter, which will get caps again.
3156 		 */
3157 		put_rd_wr_caps(src_ci, src_got, dst_ci, dst_got);
3158 		ret = splice_file_range(src_file, &src_off, dst_file, &dst_off,
3159 					src_objlen);
3160 		/* Abort on short copies or on error */
3161 		if (ret < (long)src_objlen) {
3162 			doutc(cl, "Failed partial copy (%zd)\n", ret);
3163 			goto out;
3164 		}
3165 		len -= ret;
3166 		err = get_rd_wr_caps(src_file, &src_got,
3167 				     dst_file, (dst_off + len), &dst_got);
3168 		if (err < 0)
3169 			goto out;
3170 		err = is_file_size_ok(src_inode, dst_inode,
3171 				      src_off, dst_off, len);
3172 		if (err < 0)
3173 			goto out_caps;
3174 	}
3175 
3176 	size = i_size_read(dst_inode);
3177 	bytes = ceph_do_objects_copy(src_ci, &src_off, dst_ci, &dst_off,
3178 				     src_fsc, len, flags);
3179 	if (bytes <= 0) {
3180 		if (!ret)
3181 			ret = bytes;
3182 		goto out_caps;
3183 	}
3184 	doutc(cl, "Copied %zu bytes out of %zu\n", bytes, len);
3185 	len -= bytes;
3186 	ret += bytes;
3187 
3188 	file_update_time(dst_file);
3189 	inode_inc_iversion_raw(dst_inode);
3190 
3191 	if (dst_off > size) {
3192 		/* Let the MDS know about dst file size change */
3193 		if (ceph_inode_set_size(dst_inode, dst_off) ||
3194 		    ceph_quota_is_max_bytes_approaching(dst_inode, dst_off))
3195 			ceph_check_caps(dst_ci, CHECK_CAPS_AUTHONLY | CHECK_CAPS_FLUSH);
3196 	}
3197 	/* Mark Fw dirty */
3198 	spin_lock(&dst_ci->i_ceph_lock);
3199 	dirty = __ceph_mark_dirty_caps(dst_ci, CEPH_CAP_FILE_WR, &prealloc_cf);
3200 	spin_unlock(&dst_ci->i_ceph_lock);
3201 	if (dirty)
3202 		__mark_inode_dirty(dst_inode, dirty);
3203 
3204 out_caps:
3205 	put_rd_wr_caps(src_ci, src_got, dst_ci, dst_got);
3206 
3207 	/*
3208 	 * Do the final manual copy if we still have some bytes left, unless
3209 	 * there were errors in remote object copies (len >= object_size).
3210 	 */
3211 	if (len && (len < src_ci->i_layout.object_size)) {
3212 		doutc(cl, "Final partial copy of %zu bytes\n", len);
3213 		bytes = splice_file_range(src_file, &src_off, dst_file,
3214 					  &dst_off, len);
3215 		if (bytes > 0)
3216 			ret += bytes;
3217 		else
3218 			doutc(cl, "Failed partial copy (%zd)\n", bytes);
3219 	}
3220 
3221 out:
3222 	ceph_free_cap_flush(prealloc_cf);
3223 
3224 	return ret;
3225 }
3226 
3227 static ssize_t ceph_copy_file_range(struct file *src_file, loff_t src_off,
3228 				    struct file *dst_file, loff_t dst_off,
3229 				    size_t len, unsigned int flags)
3230 {
3231 	ssize_t ret;
3232 
3233 	ret = __ceph_copy_file_range(src_file, src_off, dst_file, dst_off,
3234 				     len, flags);
3235 
3236 	if (ret == -EOPNOTSUPP || ret == -EXDEV)
3237 		ret = splice_copy_file_range(src_file, src_off, dst_file,
3238 					     dst_off, len);
3239 	return ret;
3240 }
3241 
3242 const struct file_operations ceph_file_fops = {
3243 	.open = ceph_open,
3244 	.release = ceph_release,
3245 	.llseek = ceph_llseek,
3246 	.read_iter = ceph_read_iter,
3247 	.write_iter = ceph_write_iter,
3248 	.mmap_prepare = ceph_mmap_prepare,
3249 	.fsync = ceph_fsync,
3250 	.lock = ceph_lock,
3251 	.flock = ceph_flock,
3252 	.splice_read = ceph_splice_read,
3253 	.splice_write = iter_file_splice_write,
3254 	.unlocked_ioctl = ceph_ioctl,
3255 	.compat_ioctl = compat_ptr_ioctl,
3256 	.fallocate	= ceph_fallocate,
3257 	.copy_file_range = ceph_copy_file_range,
3258 };
3259