file.c 67.2 KB
Newer Older
1
// SPDX-License-Identifier: GPL-2.0
2
#include <linux/ceph/ceph_debug.h>
3
#include <linux/ceph/striper.h>
S
Sage Weil 已提交
4

5
#include <linux/module.h>
S
Sage Weil 已提交
6
#include <linux/sched.h>
7
#include <linux/slab.h>
S
Sage Weil 已提交
8
#include <linux/file.h>
S
Sage Weil 已提交
9
#include <linux/mount.h>
S
Sage Weil 已提交
10 11
#include <linux/namei.h>
#include <linux/writeback.h>
L
Li Wang 已提交
12
#include <linux/falloc.h>
13
#include <linux/iversion.h>
14
#include <linux/ktime.h>
S
Sage Weil 已提交
15 16 17

#include "super.h"
#include "mds_client.h"
18
#include "cache.h"
19
#include "io.h"
20
#include "metric.h"
S
Sage Weil 已提交
21

22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
static __le32 ceph_flags_sys2wire(u32 flags)
{
	u32 wire_flags = 0;

	switch (flags & O_ACCMODE) {
	case O_RDONLY:
		wire_flags |= CEPH_O_RDONLY;
		break;
	case O_WRONLY:
		wire_flags |= CEPH_O_WRONLY;
		break;
	case O_RDWR:
		wire_flags |= CEPH_O_RDWR;
		break;
	}

38 39
	flags &= ~O_ACCMODE;

40 41 42 43 44 45 46 47 48 49 50
#define ceph_sys2wire(a) if (flags & a) { wire_flags |= CEPH_##a; flags &= ~a; }

	ceph_sys2wire(O_CREAT);
	ceph_sys2wire(O_EXCL);
	ceph_sys2wire(O_TRUNC);
	ceph_sys2wire(O_DIRECTORY);
	ceph_sys2wire(O_NOFOLLOW);

#undef ceph_sys2wire

	if (flags)
51
		dout("unused open flags: %x\n", flags);
52 53 54 55

	return cpu_to_le32(wire_flags);
}

S
Sage Weil 已提交
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
/*
 * Ceph file operations
 *
 * Implement basic open/close functionality, and implement
 * read/write.
 *
 * We implement three modes of file I/O:
 *  - buffered uses the generic_file_aio_{read,write} helpers
 *
 *  - synchronous is used when there is multi-client read/write
 *    sharing, avoids the page cache, and synchronously waits for an
 *    ack from the OSD.
 *
 *  - direct io takes the variant of the sync path that references
 *    user pages directly.
 *
 * fsync() flushes and waits on dirty pages, but just queues metadata
 * for writeback: since the MDS can recover size and mtime there is no
 * need to wait for MDS acknowledgement.
 */

77
/*
78 79
 * How many pages to get in one call to iov_iter_get_pages().  This
 * determines the size of the on-stack array used as a buffer.
80
 */
81 82 83 84
#define ITER_GET_BVECS_PAGES	64

static ssize_t __iter_get_bvecs(struct iov_iter *iter, size_t maxsize,
				struct bio_vec *bvecs)
85
{
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
	size_t size = 0;
	int bvec_idx = 0;

	if (maxsize > iov_iter_count(iter))
		maxsize = iov_iter_count(iter);

	while (size < maxsize) {
		struct page *pages[ITER_GET_BVECS_PAGES];
		ssize_t bytes;
		size_t start;
		int idx = 0;

		bytes = iov_iter_get_pages(iter, pages, maxsize - size,
					   ITER_GET_BVECS_PAGES, &start);
		if (bytes < 0)
			return size ?: bytes;

		iov_iter_advance(iter, bytes);
		size += bytes;

		for ( ; bytes; idx++, bvec_idx++) {
			struct bio_vec bv = {
				.bv_page = pages[idx],
				.bv_len = min_t(int, bytes, PAGE_SIZE - start),
				.bv_offset = start,
			};

			bvecs[bvec_idx] = bv;
			bytes -= bv.bv_len;
			start = 0;
		}
	}

	return size;
120 121 122
}

/*
123 124 125 126 127 128
 * iov_iter_get_pages() only considers one iov_iter segment, no matter
 * what maxsize or maxpages are given.  For ITER_BVEC that is a single
 * page.
 *
 * Attempt to get up to @maxsize bytes worth of pages from @iter.
 * Return the number of bytes in the created bio_vec array, or an error.
129
 */
130 131
static ssize_t iter_get_bvecs_alloc(struct iov_iter *iter, size_t maxsize,
				    struct bio_vec **bvecs, int *num_bvecs)
132
{
133 134 135 136
	struct bio_vec *bv;
	size_t orig_count = iov_iter_count(iter);
	ssize_t bytes;
	int npages;
137

138 139 140
	iov_iter_truncate(iter, maxsize);
	npages = iov_iter_npages(iter, INT_MAX);
	iov_iter_reexpand(iter, orig_count);
141

142 143 144 145 146 147 148
	/*
	 * __iter_get_bvecs() may populate only part of the array -- zero it
	 * out.
	 */
	bv = kvmalloc_array(npages, sizeof(*bv), GFP_KERNEL | __GFP_ZERO);
	if (!bv)
		return -ENOMEM;
149

150 151 152 153 154 155 156
	bytes = __iter_get_bvecs(iter, maxsize, bv);
	if (bytes < 0) {
		/*
		 * No pages were pinned -- just free the array.
		 */
		kvfree(bv);
		return bytes;
157 158
	}

159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
	*bvecs = bv;
	*num_bvecs = npages;
	return bytes;
}

static void put_bvecs(struct bio_vec *bvecs, int num_bvecs, bool should_dirty)
{
	int i;

	for (i = 0; i < num_bvecs; i++) {
		if (bvecs[i].bv_page) {
			if (should_dirty)
				set_page_dirty_lock(bvecs[i].bv_page);
			put_page(bvecs[i].bv_page);
		}
	}
	kvfree(bvecs);
176
}
S
Sage Weil 已提交
177 178 179 180 181 182 183 184

/*
 * Prepare an open request.  Preallocate ceph_cap to avoid an
 * inopportune ENOMEM later.
 */
static struct ceph_mds_request *
prepare_open_request(struct super_block *sb, int flags, int create_mode)
{
185
	struct ceph_mds_client *mdsc = ceph_sb_to_mdsc(sb);
S
Sage Weil 已提交
186 187 188 189 190 191 192 193 194 195 196
	struct ceph_mds_request *req;
	int want_auth = USE_ANY_MDS;
	int op = (flags & O_CREAT) ? CEPH_MDS_OP_CREATE : CEPH_MDS_OP_OPEN;

	if (flags & (O_WRONLY|O_RDWR|O_CREAT|O_TRUNC))
		want_auth = USE_AUTH_MDS;

	req = ceph_mdsc_create_request(mdsc, op, want_auth);
	if (IS_ERR(req))
		goto out;
	req->r_fmode = ceph_flags_to_mode(flags);
197
	req->r_args.open.flags = ceph_flags_sys2wire(flags);
S
Sage Weil 已提交
198 199 200 201 202
	req->r_args.open.mode = cpu_to_le32(create_mode);
out:
	return req;
}

C
Chengguang Xu 已提交
203 204 205
static int ceph_init_file_info(struct inode *inode, struct file *file,
					int fmode, bool isdir)
{
206
	struct ceph_inode_info *ci = ceph_inode(inode);
J
Jeff Layton 已提交
207 208
	struct ceph_mount_options *opt =
		ceph_inode_to_client(&ci->vfs_inode)->mount_options;
C
Chengguang Xu 已提交
209 210 211 212 213 214 215 216 217
	struct ceph_file_info *fi;

	dout("%s %p %p 0%o (%s)\n", __func__, inode, file,
			inode->i_mode, isdir ? "dir" : "regular");
	BUG_ON(inode->i_fop->release != ceph_release);

	if (isdir) {
		struct ceph_dir_file_info *dfi =
			kmem_cache_zalloc(ceph_dir_file_cachep, GFP_KERNEL);
218
		if (!dfi)
C
Chengguang Xu 已提交
219 220 221 222 223 224 225 226
			return -ENOMEM;

		file->private_data = dfi;
		fi = &dfi->file_info;
		dfi->next_offset = 2;
		dfi->readdir_cache_idx = -1;
	} else {
		fi = kmem_cache_zalloc(ceph_file_cachep, GFP_KERNEL);
227
		if (!fi)
C
Chengguang Xu 已提交
228 229
			return -ENOMEM;

J
Jeff Layton 已提交
230 231 232
		if (opt->flags & CEPH_MOUNT_OPT_NOPAGECACHE)
			fi->flags |= CEPH_F_SYNC;

C
Chengguang Xu 已提交
233 234 235
		file->private_data = fi;
	}

236
	ceph_get_fmode(ci, fmode, 1);
C
Chengguang Xu 已提交
237
	fi->fmode = fmode;
238

C
Chengguang Xu 已提交
239 240
	spin_lock_init(&fi->rw_contexts_lock);
	INIT_LIST_HEAD(&fi->rw_contexts);
241
	fi->filp_gen = READ_ONCE(ceph_inode_to_client(inode)->filp_gen);
C
Chengguang Xu 已提交
242 243 244 245

	return 0;
}

S
Sage Weil 已提交
246 247 248 249 250 251 252 253 254 255
/*
 * initialize private struct file data.
 * if we fail, clean up by dropping fmode reference on the ceph_inode
 */
static int ceph_init_file(struct inode *inode, struct file *file, int fmode)
{
	int ret = 0;

	switch (inode->i_mode & S_IFMT) {
	case S_IFREG:
256
		ceph_fscache_use_cookie(inode, file->f_mode & FMODE_WRITE);
257
		fallthrough;
S
Sage Weil 已提交
258
	case S_IFDIR:
C
Chengguang Xu 已提交
259 260
		ret = ceph_init_file_info(inode, file, fmode,
						S_ISDIR(inode->i_mode));
S
Sage Weil 已提交
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
		break;

	case S_IFLNK:
		dout("init_file %p %p 0%o (symlink)\n", inode, file,
		     inode->i_mode);
		break;

	default:
		dout("init_file %p %p 0%o (special)\n", inode, file,
		     inode->i_mode);
		/*
		 * we need to drop the open ref now, since we don't
		 * have .release set to ceph_release.
		 */
		BUG_ON(inode->i_fop->release == ceph_release);

		/* call the proper open fop */
		ret = inode->i_fop->open(inode, file);
	}
	return ret;
}

283 284 285
/*
 * try renew caps after session gets killed.
 */
286
int ceph_renew_caps(struct inode *inode, int fmode)
287
{
288
	struct ceph_mds_client *mdsc = ceph_sb_to_mdsc(inode->i_sb);
289 290 291 292 293
	struct ceph_inode_info *ci = ceph_inode(inode);
	struct ceph_mds_request *req;
	int err, flags, wanted;

	spin_lock(&ci->i_ceph_lock);
294
	__ceph_touch_fmode(ci, mdsc, fmode);
295 296
	wanted = __ceph_caps_file_wanted(ci);
	if (__ceph_is_any_real_caps(ci) &&
297
	    (!(wanted & CEPH_CAP_ANY_WR) || ci->i_auth_cap)) {
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
		int issued = __ceph_caps_issued(ci, NULL);
		spin_unlock(&ci->i_ceph_lock);
		dout("renew caps %p want %s issued %s updating mds_wanted\n",
		     inode, ceph_cap_string(wanted), ceph_cap_string(issued));
		ceph_check_caps(ci, 0, NULL);
		return 0;
	}
	spin_unlock(&ci->i_ceph_lock);

	flags = 0;
	if ((wanted & CEPH_CAP_FILE_RD) && (wanted & CEPH_CAP_FILE_WR))
		flags = O_RDWR;
	else if (wanted & CEPH_CAP_FILE_RD)
		flags = O_RDONLY;
	else if (wanted & CEPH_CAP_FILE_WR)
		flags = O_WRONLY;
#ifdef O_LAZY
	if (wanted & CEPH_CAP_FILE_LAZYIO)
		flags |= O_LAZY;
#endif

	req = prepare_open_request(inode->i_sb, flags, 0);
	if (IS_ERR(req)) {
		err = PTR_ERR(req);
		goto out;
	}

	req->r_inode = inode;
	ihold(inode);
	req->r_num_caps = 1;

	err = ceph_mdsc_do_request(mdsc, NULL, req);
	ceph_mdsc_put_request(req);
out:
	dout("renew caps %p open result=%d\n", inode, err);
	return err < 0 ? err : 0;
}

S
Sage Weil 已提交
336 337 338 339 340 341 342 343 344
/*
 * If we already have the requisite capabilities, we can satisfy
 * the open request locally (no need to request new caps from the
 * MDS).  We do, however, need to inform the MDS (asynchronously)
 * if our wanted caps set expands.
 */
int ceph_open(struct inode *inode, struct file *file)
{
	struct ceph_inode_info *ci = ceph_inode(inode);
345 346
	struct ceph_fs_client *fsc = ceph_sb_to_client(inode->i_sb);
	struct ceph_mds_client *mdsc = fsc->mdsc;
S
Sage Weil 已提交
347
	struct ceph_mds_request *req;
348
	struct ceph_file_info *fi = file->private_data;
S
Sage Weil 已提交
349 350 351
	int err;
	int flags, fmode, wanted;

352
	if (fi) {
S
Sage Weil 已提交
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
		dout("open file %p is already opened\n", file);
		return 0;
	}

	/* filter out O_CREAT|O_EXCL; vfs did that already.  yuck. */
	flags = file->f_flags & ~(O_CREAT|O_EXCL);
	if (S_ISDIR(inode->i_mode))
		flags = O_DIRECTORY;  /* mds likes to know */

	dout("open inode %p ino %llx.%llx file %p flags %d (%d)\n", inode,
	     ceph_vinop(inode), file, flags, file->f_flags);
	fmode = ceph_flags_to_mode(flags);
	wanted = ceph_caps_for_mode(fmode);

	/* snapped files are read-only */
	if (ceph_snap(inode) != CEPH_NOSNAP && (file->f_mode & FMODE_WRITE))
		return -EROFS;

	/* trivially open snapdir */
	if (ceph_snap(inode) == CEPH_SNAPDIR) {
		return ceph_init_file(inode, file, fmode);
	}

	/*
377 378
	 * No need to block if we have caps on the auth MDS (for
	 * write) or any MDS (for read).  Update wanted set
S
Sage Weil 已提交
379 380
	 * asynchronously.
	 */
381
	spin_lock(&ci->i_ceph_lock);
382 383
	if (__ceph_is_any_real_caps(ci) &&
	    (((fmode & CEPH_FILE_MODE_WR) == 0) || ci->i_auth_cap)) {
384
		int mds_wanted = __ceph_caps_mds_wanted(ci, true);
S
Sage Weil 已提交
385 386 387 388 389
		int issued = __ceph_caps_issued(ci, NULL);

		dout("open %p fmode %d want %s issued %s using existing\n",
		     inode, fmode, ceph_cap_string(wanted),
		     ceph_cap_string(issued));
390
		__ceph_touch_fmode(ci, mdsc, fmode);
391
		spin_unlock(&ci->i_ceph_lock);
S
Sage Weil 已提交
392 393 394 395 396 397 398 399 400 401

		/* adjust wanted? */
		if ((issued & wanted) != wanted &&
		    (mds_wanted & wanted) != wanted &&
		    ceph_snap(inode) != CEPH_SNAPDIR)
			ceph_check_caps(ci, 0, NULL);

		return ceph_init_file(inode, file, fmode);
	} else if (ceph_snap(inode) != CEPH_NOSNAP &&
		   (ci->i_snap_caps & wanted) == wanted) {
402
		__ceph_touch_fmode(ci, mdsc, fmode);
403
		spin_unlock(&ci->i_ceph_lock);
S
Sage Weil 已提交
404 405
		return ceph_init_file(inode, file, fmode);
	}
406

407
	spin_unlock(&ci->i_ceph_lock);
S
Sage Weil 已提交
408 409 410 411 412 413 414

	dout("open fmode %d wants %s\n", fmode, ceph_cap_string(wanted));
	req = prepare_open_request(inode->i_sb, flags, 0);
	if (IS_ERR(req)) {
		err = PTR_ERR(req);
		goto out;
	}
415 416
	req->r_inode = inode;
	ihold(inode);
417

S
Sage Weil 已提交
418
	req->r_num_caps = 1;
419
	err = ceph_mdsc_do_request(mdsc, NULL, req);
S
Sage Weil 已提交
420 421 422 423 424 425 426 427
	if (!err)
		err = ceph_init_file(inode, file, req->r_fmode);
	ceph_mdsc_put_request(req);
	dout("open result=%d on %llx.%llx\n", err, ceph_vinop(inode));
out:
	return err;
}

428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
/* Clone the layout from a synchronous create, if the dir now has Dc caps */
static void
cache_file_layout(struct inode *dst, struct inode *src)
{
	struct ceph_inode_info *cdst = ceph_inode(dst);
	struct ceph_inode_info *csrc = ceph_inode(src);

	spin_lock(&cdst->i_ceph_lock);
	if ((__ceph_caps_issued(cdst, NULL) & CEPH_CAP_DIR_CREATE) &&
	    !ceph_file_layout_is_valid(&cdst->i_cached_layout)) {
		memcpy(&cdst->i_cached_layout, &csrc->i_layout,
			sizeof(cdst->i_cached_layout));
		rcu_assign_pointer(cdst->i_cached_layout.pool_ns,
				   ceph_try_get_string(csrc->i_layout.pool_ns));
	}
	spin_unlock(&cdst->i_ceph_lock);
}
S
Sage Weil 已提交
445

446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
/*
 * Try to set up an async create. We need caps, a file layout, and inode number,
 * and either a lease on the dentry or complete dir info. If any of those
 * criteria are not satisfied, then return false and the caller can go
 * synchronous.
 */
static int try_prep_async_create(struct inode *dir, struct dentry *dentry,
				 struct ceph_file_layout *lo, u64 *pino)
{
	struct ceph_inode_info *ci = ceph_inode(dir);
	struct ceph_dentry_info *di = ceph_dentry(dentry);
	int got = 0, want = CEPH_CAP_FILE_EXCL | CEPH_CAP_DIR_CREATE;
	u64 ino;

	spin_lock(&ci->i_ceph_lock);
	/* No auth cap means no chance for Dc caps */
	if (!ci->i_auth_cap)
		goto no_async;

	/* Any delegated inos? */
	if (xa_empty(&ci->i_auth_cap->session->s_delegated_inos))
		goto no_async;

	if (!ceph_file_layout_is_valid(&ci->i_cached_layout))
		goto no_async;

	if ((__ceph_caps_issued(ci, NULL) & want) != want)
		goto no_async;

	if (d_in_lookup(dentry)) {
		if (!__ceph_dir_is_complete(ci))
			goto no_async;
478 479 480
		spin_lock(&dentry->d_lock);
		di->lease_shared_gen = atomic_read(&ci->i_shared_gen);
		spin_unlock(&dentry->d_lock);
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
	} else if (atomic_read(&ci->i_shared_gen) !=
		   READ_ONCE(di->lease_shared_gen)) {
		goto no_async;
	}

	ino = ceph_get_deleg_ino(ci->i_auth_cap->session);
	if (!ino)
		goto no_async;

	*pino = ino;
	ceph_take_cap_refs(ci, want, false);
	memcpy(lo, &ci->i_cached_layout, sizeof(*lo));
	rcu_assign_pointer(lo->pool_ns,
			   ceph_try_get_string(ci->i_cached_layout.pool_ns));
	got = want;
no_async:
	spin_unlock(&ci->i_ceph_lock);
	return got;
}

static void restore_deleg_ino(struct inode *dir, u64 ino)
{
	struct ceph_inode_info *ci = ceph_inode(dir);
	struct ceph_mds_session *s = NULL;

	spin_lock(&ci->i_ceph_lock);
	if (ci->i_auth_cap)
		s = ceph_get_mds_session(ci->i_auth_cap->session);
	spin_unlock(&ci->i_ceph_lock);
	if (s) {
		int err = ceph_restore_deleg_ino(s, ino);
		if (err)
			pr_warn("ceph: unable to restore delegated ino 0x%llx to session: %d\n",
				ino, err);
		ceph_put_mds_session(s);
	}
}

static void ceph_async_create_cb(struct ceph_mds_client *mdsc,
                                 struct ceph_mds_request *req)
{
	int result = req->r_err ? req->r_err :
			le32_to_cpu(req->r_reply_info.head->result);

	if (result == -EJUKEBOX)
		goto out;

	mapping_set_error(req->r_parent->i_mapping, result);

	if (result) {
		struct dentry *dentry = req->r_dentry;
532
		struct inode *inode = d_inode(dentry);
533 534
		int pathlen = 0;
		u64 base = 0;
535 536 537 538 539 540 541
		char *path = ceph_mdsc_build_path(req->r_dentry, &pathlen,
						  &base, 0);

		ceph_dir_clear_complete(req->r_parent);
		if (!d_unhashed(dentry))
			d_drop(dentry);

542 543
		ceph_inode_shutdown(inode);

544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
		pr_warn("ceph: async create failure path=(%llx)%s result=%d!\n",
			base, IS_ERR(path) ? "<<bad>>" : path, result);
		ceph_mdsc_free_path(path, pathlen);
	}

	if (req->r_target_inode) {
		struct ceph_inode_info *ci = ceph_inode(req->r_target_inode);
		u64 ino = ceph_vino(req->r_target_inode).ino;

		if (req->r_deleg_ino != ino)
			pr_warn("%s: inode number mismatch! err=%d deleg_ino=0x%llx target=0x%llx\n",
				__func__, req->r_err, req->r_deleg_ino, ino);
		mapping_set_error(req->r_target_inode->i_mapping, result);

		spin_lock(&ci->i_ceph_lock);
		if (ci->i_ceph_flags & CEPH_I_ASYNC_CREATE) {
			ci->i_ceph_flags &= ~CEPH_I_ASYNC_CREATE;
			wake_up_bit(&ci->i_ceph_flags, CEPH_ASYNC_CREATE_BIT);
		}
		ceph_kick_flushing_inode_caps(req->r_session, ci);
		spin_unlock(&ci->i_ceph_lock);
565
	} else if (!result) {
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
		pr_warn("%s: no req->r_target_inode for 0x%llx\n", __func__,
			req->r_deleg_ino);
	}
out:
	ceph_mdsc_release_dir_caps(req);
}

static int ceph_finish_async_create(struct inode *dir, struct dentry *dentry,
				    struct file *file, umode_t mode,
				    struct ceph_mds_request *req,
				    struct ceph_acl_sec_ctx *as_ctx,
				    struct ceph_file_layout *lo)
{
	int ret;
	char xattr_buf[4];
	struct ceph_mds_reply_inode in = { };
	struct ceph_mds_reply_info_in iinfo = { .in = &in };
	struct ceph_inode_info *ci = ceph_inode(dir);
	struct inode *inode;
	struct timespec64 now;
586
	struct ceph_mds_client *mdsc = ceph_sb_to_mdsc(dir->i_sb);
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
	struct ceph_vino vino = { .ino = req->r_deleg_ino,
				  .snap = CEPH_NOSNAP };

	ktime_get_real_ts64(&now);

	inode = ceph_get_inode(dentry->d_sb, vino);
	if (IS_ERR(inode))
		return PTR_ERR(inode);

	iinfo.inline_version = CEPH_INLINE_NONE;
	iinfo.change_attr = 1;
	ceph_encode_timespec64(&iinfo.btime, &now);

	iinfo.xattr_len = ARRAY_SIZE(xattr_buf);
	iinfo.xattr_data = xattr_buf;
	memset(iinfo.xattr_data, 0, iinfo.xattr_len);

	in.ino = cpu_to_le64(vino.ino);
	in.snapid = cpu_to_le64(CEPH_NOSNAP);
	in.version = cpu_to_le64(1);	// ???
	in.cap.caps = in.cap.wanted = cpu_to_le32(CEPH_CAP_ALL_FILE);
	in.cap.cap_id = cpu_to_le64(1);
	in.cap.realm = cpu_to_le64(ci->i_snap_realm->ino);
	in.cap.flags = CEPH_CAP_FLAG_AUTH;
	in.ctime = in.mtime = in.atime = iinfo.btime;
	in.truncate_seq = cpu_to_le32(1);
	in.truncate_size = cpu_to_le64(-1ULL);
	in.xattr_version = cpu_to_le64(1);
	in.uid = cpu_to_le32(from_kuid(&init_user_ns, current_fsuid()));
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
	if (dir->i_mode & S_ISGID) {
		in.gid = cpu_to_le32(from_kgid(&init_user_ns, dir->i_gid));

		/* Directories always inherit the setgid bit. */
		if (S_ISDIR(mode))
			mode |= S_ISGID;
		else if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP) &&
			 !in_group_p(dir->i_gid) &&
			 !capable_wrt_inode_uidgid(&init_user_ns, dir, CAP_FSETID))
			mode &= ~S_ISGID;
	} else {
		in.gid = cpu_to_le32(from_kgid(&init_user_ns, current_fsgid()));
	}
	in.mode = cpu_to_le32((u32)mode);

631 632 633 634 635
	in.nlink = cpu_to_le32(1);
	in.max_size = cpu_to_le64(lo->stripe_unit);

	ceph_file_layout_to_legacy(lo, &in.layout);

636
	down_read(&mdsc->snap_rwsem);
637 638
	ret = ceph_fill_inode(inode, NULL, &iinfo, NULL, req->r_session,
			      req->r_fmode, NULL);
639
	up_read(&mdsc->snap_rwsem);
640 641 642 643 644 645 646 647 648 649
	if (ret) {
		dout("%s failed to fill inode: %d\n", __func__, ret);
		ceph_dir_clear_complete(dir);
		if (!d_unhashed(dentry))
			d_drop(dentry);
		if (inode->i_state & I_NEW)
			discard_new_inode(inode);
	} else {
		struct dentry *dn;

650 651
		dout("%s d_adding new inode 0x%llx to 0x%llx/%s\n", __func__,
			vino.ino, ceph_ino(dir), dentry->d_name.name);
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
		ceph_dir_clear_ordered(dir);
		ceph_init_inode_acls(inode, as_ctx);
		if (inode->i_state & I_NEW) {
			/*
			 * If it's not I_NEW, then someone created this before
			 * we got here. Assume the server is aware of it at
			 * that point and don't worry about setting
			 * CEPH_I_ASYNC_CREATE.
			 */
			ceph_inode(inode)->i_ceph_flags = CEPH_I_ASYNC_CREATE;
			unlock_new_inode(inode);
		}
		if (d_in_lookup(dentry) || d_really_is_negative(dentry)) {
			if (!d_unhashed(dentry))
				d_drop(dentry);
			dn = d_splice_alias(inode, dentry);
			WARN_ON_ONCE(dn && dn != dentry);
		}
		file->f_mode |= FMODE_CREATED;
		ret = finish_open(file, dentry, ceph_open);
	}
	return ret;
}

S
Sage Weil 已提交
676
/*
S
Sage Weil 已提交
677 678
 * Do a lookup + open with a single request.  If we get a non-existent
 * file or symlink, return 1 so the VFS can retry.
S
Sage Weil 已提交
679
 */
S
Sage Weil 已提交
680
int ceph_atomic_open(struct inode *dir, struct dentry *dentry,
681
		     struct file *file, unsigned flags, umode_t mode)
S
Sage Weil 已提交
682
{
683 684
	struct ceph_fs_client *fsc = ceph_sb_to_client(dir->i_sb);
	struct ceph_mds_client *mdsc = fsc->mdsc;
S
Sage Weil 已提交
685
	struct ceph_mds_request *req;
S
Sage Weil 已提交
686
	struct dentry *dn;
687
	struct ceph_acl_sec_ctx as_ctx = {};
688
	bool try_async = ceph_test_mount_opt(fsc, ASYNC_DIROPS);
689
	int mask;
S
Sage Weil 已提交
690 691
	int err;

A
Al Viro 已提交
692 693
	dout("atomic_open %p dentry %p '%pd' %s flags %d mode 0%o\n",
	     dir, dentry, dentry,
S
Sage Weil 已提交
694 695 696 697 698
	     d_unhashed(dentry) ? "unhashed" : "hashed", flags, mode);

	if (dentry->d_name.len > NAME_MAX)
		return -ENAMETOOLONG;

699
	if (flags & O_CREAT) {
700 701
		if (ceph_quota_is_max_files_exceeded(dir))
			return -EDQUOT;
702
		err = ceph_pre_init_acls(dir, &mode, &as_ctx);
703 704
		if (err < 0)
			return err;
Y
Yan, Zheng 已提交
705 706 707
		err = ceph_security_init_secctx(dentry, mode, &as_ctx);
		if (err < 0)
			goto out_ctx;
708 709 710
	} else if (!d_in_lookup(dentry)) {
		/* If it's not being looked up, it's negative */
		return -ENOENT;
711
	}
712
retry:
S
Sage Weil 已提交
713 714
	/* do the open */
	req = prepare_open_request(dir->i_sb, flags, mode);
715 716
	if (IS_ERR(req)) {
		err = PTR_ERR(req);
717
		goto out_ctx;
718
	}
S
Sage Weil 已提交
719 720
	req->r_dentry = dget(dentry);
	req->r_num_caps = 2;
721 722 723 724 725
	mask = CEPH_STAT_CAP_INODE | CEPH_CAP_AUTH_SHARED;
	if (ceph_security_xattr_wanted(dir))
		mask |= CEPH_CAP_XATTR_SHARED;
	req->r_args.open.mask = cpu_to_le32(mask);
	req->r_parent = dir;
726
	ihold(dir);
727

S
Sage Weil 已提交
728
	if (flags & O_CREAT) {
729 730
		struct ceph_file_layout lo;

731
		req->r_dentry_drop = CEPH_CAP_FILE_SHARED | CEPH_CAP_AUTH_EXCL;
S
Sage Weil 已提交
732
		req->r_dentry_unless = CEPH_CAP_FILE_EXCL;
733 734 735
		if (as_ctx.pagelist) {
			req->r_pagelist = as_ctx.pagelist;
			as_ctx.pagelist = NULL;
736
		}
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
		if (try_async &&
		    (req->r_dir_caps =
		      try_prep_async_create(dir, dentry, &lo,
					    &req->r_deleg_ino))) {
			set_bit(CEPH_MDS_R_ASYNC, &req->r_req_flags);
			req->r_args.open.flags |= cpu_to_le32(CEPH_O_EXCL);
			req->r_callback = ceph_async_create_cb;
			err = ceph_mdsc_submit_request(mdsc, dir, req);
			if (!err) {
				err = ceph_finish_async_create(dir, dentry,
							file, mode, req,
							&as_ctx, &lo);
			} else if (err == -EJUKEBOX) {
				restore_deleg_ino(dir, req->r_deleg_ino);
				ceph_mdsc_put_request(req);
				try_async = false;
753
				ceph_put_string(rcu_dereference_raw(lo.pool_ns));
754 755
				goto retry;
			}
756
			ceph_put_string(rcu_dereference_raw(lo.pool_ns));
757 758
			goto out_req;
		}
S
Sage Weil 已提交
759
	}
Y
Yan, Zheng 已提交
760

761
	set_bit(CEPH_MDS_R_PARENT_LOCKED, &req->r_req_flags);
762 763 764
	err = ceph_mdsc_do_request(mdsc,
				   (flags & (O_CREAT|O_TRUNC)) ? dir : NULL,
				   req);
765 766 767 768 769 770 771
	if (err == -ENOENT) {
		dentry = ceph_handle_snapdir(req, dentry);
		if (IS_ERR(dentry)) {
			err = PTR_ERR(dentry);
			goto out_req;
		}
		err = 0;
772
	}
773

774
	if (!err && (flags & O_CREAT) && !req->r_reply_info.head->is_dentry)
S
Sage Weil 已提交
775
		err = ceph_handle_notrace_create(dir, dentry);
776

777
	if (d_in_lookup(dentry)) {
S
Sage Weil 已提交
778 779 780 781 782 783 784 785
		dn = ceph_finish_lookup(req, dentry, err);
		if (IS_ERR(dn))
			err = PTR_ERR(dn);
	} else {
		/* we were given a hashed negative dentry */
		dn = NULL;
	}
	if (err)
786
		goto out_req;
787
	if (dn || d_really_is_negative(dentry) || d_is_symlink(dentry)) {
S
Sage Weil 已提交
788 789 790 791 792
		/* make vfs retry on splice, ENOENT, or symlink */
		dout("atomic_open finish_no_open on dn %p\n", dn);
		err = finish_no_open(file, dn);
	} else {
		dout("atomic_open finish_open on dn %p\n", dn);
793
		if (req->r_op == CEPH_MDS_OP_CREATE && req->r_reply_info.has_create_ino) {
794 795 796 797
			struct inode *newino = d_inode(dentry);

			cache_file_layout(dir, newino);
			ceph_init_inode_acls(newino, &as_ctx);
798
			file->f_mode |= FMODE_CREATED;
799
		}
800
		err = finish_open(file, dentry, ceph_open);
S
Sage Weil 已提交
801
	}
802
out_req:
S
Sage Weil 已提交
803
	ceph_mdsc_put_request(req);
804 805
out_ctx:
	ceph_release_acl_sec_ctx(&as_ctx);
S
Sage Weil 已提交
806
	dout("atomic_open result=%d\n", err);
A
Al Viro 已提交
807
	return err;
S
Sage Weil 已提交
808 809 810 811 812 813
}

int ceph_release(struct inode *inode, struct file *file)
{
	struct ceph_inode_info *ci = ceph_inode(inode);

C
Chengguang Xu 已提交
814 815 816 817 818
	if (S_ISDIR(inode->i_mode)) {
		struct ceph_dir_file_info *dfi = file->private_data;
		dout("release inode %p dir file %p\n", inode, file);
		WARN_ON(!list_empty(&dfi->file_info.rw_contexts));

819
		ceph_put_fmode(ci, dfi->file_info.fmode, 1);
C
Chengguang Xu 已提交
820 821 822 823 824 825 826 827 828 829 830

		if (dfi->last_readdir)
			ceph_mdsc_put_request(dfi->last_readdir);
		kfree(dfi->last_name);
		kfree(dfi->dir_info);
		kmem_cache_free(ceph_dir_file_cachep, dfi);
	} else {
		struct ceph_file_info *fi = file->private_data;
		dout("release inode %p regular file %p\n", inode, file);
		WARN_ON(!list_empty(&fi->rw_contexts));

831
		ceph_fscache_unuse_cookie(inode, file->f_mode & FMODE_WRITE);
832 833
		ceph_put_fmode(ci, fi->fmode, 1);

C
Chengguang Xu 已提交
834 835
		kmem_cache_free(ceph_file_cachep, fi);
	}
836 837

	/* wake up anyone waiting for caps on this inode */
838
	wake_up_all(&ci->i_cap_wq);
S
Sage Weil 已提交
839 840 841
	return 0;
}

Y
Yan, Zheng 已提交
842
enum {
Y
Yan, Zheng 已提交
843 844 845
	HAVE_RETRIED = 1,
	CHECK_EOF =    2,
	READ_INLINE =  3,
Y
Yan, Zheng 已提交
846 847
};

S
Sage Weil 已提交
848 849 850 851
/*
 * Completely synchronous read and write methods.  Direct from __user
 * buffer to osd, or directly to user pages (if O_DIRECT).
 *
Y
Yan, Zheng 已提交
852 853 854 855 856
 * If the read spans object boundary, just do multiple reads.  (That's not
 * atomic, but good enough for now.)
 *
 * If we get a short result from the OSD, check against i_size; we need to
 * only return a short read to the caller if we hit EOF.
S
Sage Weil 已提交
857
 */
858
static ssize_t ceph_sync_read(struct kiocb *iocb, struct iov_iter *to,
Y
Yan, Zheng 已提交
859
			      int *retry_op)
S
Sage Weil 已提交
860
{
861
	struct file *file = iocb->ki_filp;
A
Al Viro 已提交
862
	struct inode *inode = file_inode(file);
Y
Yan, Zheng 已提交
863 864 865
	struct ceph_inode_info *ci = ceph_inode(inode);
	struct ceph_fs_client *fsc = ceph_inode_to_client(inode);
	struct ceph_osd_client *osdc = &fsc->client->osdc;
866
	ssize_t ret;
Y
Yan, Zheng 已提交
867 868
	u64 off = iocb->ki_pos;
	u64 len = iov_iter_count(to);
869
	u64 i_size = i_size_read(inode);
S
Sage Weil 已提交
870

871
	dout("sync_read on file %p %llu~%u %s\n", file, off, (unsigned)len,
S
Sage Weil 已提交
872
	     (file->f_flags & O_DIRECT) ? "O_DIRECT" : "");
873 874 875

	if (!len)
		return 0;
876 877 878 879 880 881
	/*
	 * flush any page cache pages in this range.  this
	 * will make concurrent normal and sync io slow,
	 * but it will at least behave sensibly when they are
	 * in sequence.
	 */
882 883
	ret = filemap_write_and_wait_range(inode->i_mapping,
					   off, off + len - 1);
884
	if (ret < 0)
885
		return ret;
886

Y
Yan, Zheng 已提交
887 888 889 890 891
	ret = 0;
	while ((len = iov_iter_count(to)) > 0) {
		struct ceph_osd_request *req;
		struct page **pages;
		int num_pages;
892
		size_t page_off;
Y
Yan, Zheng 已提交
893
		bool more;
894 895
		int idx;
		size_t left;
Y
Yan, Zheng 已提交
896 897 898 899 900 901 902 903 904 905

		req = ceph_osdc_new_request(osdc, &ci->i_layout,
					ci->i_vino, off, &len, 0, 1,
					CEPH_OSD_OP_READ, CEPH_OSD_FLAG_READ,
					NULL, ci->i_truncate_seq,
					ci->i_truncate_size, false);
		if (IS_ERR(req)) {
			ret = PTR_ERR(req);
			break;
		}
906

Y
Yan, Zheng 已提交
907 908
		more = len < iov_iter_count(to);

909 910 911 912 913 914 915
		num_pages = calc_pages_for(off, len);
		page_off = off & ~PAGE_MASK;
		pages = ceph_alloc_page_vector(num_pages, GFP_KERNEL);
		if (IS_ERR(pages)) {
			ceph_osdc_put_request(req);
			ret = PTR_ERR(pages);
			break;
916
		}
Y
Yan, Zheng 已提交
917 918 919 920 921 922

		osd_req_op_extent_osd_data_pages(req, 0, pages, len, page_off,
						 false, false);
		ret = ceph_osdc_start_request(osdc, req, false);
		if (!ret)
			ret = ceph_osdc_wait_request(osdc, req);
923

X
Xiubo Li 已提交
924
		ceph_update_read_metrics(&fsc->mdsc->metric,
925 926
					 req->r_start_latency,
					 req->r_end_latency,
X
Xiubo Li 已提交
927
					 len, ret);
928

Y
Yan, Zheng 已提交
929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945
		ceph_osdc_put_request(req);

		i_size = i_size_read(inode);
		dout("sync_read %llu~%llu got %zd i_size %llu%s\n",
		     off, len, ret, i_size, (more ? " MORE" : ""));

		if (ret == -ENOENT)
			ret = 0;
		if (ret >= 0 && ret < len && (off + ret < i_size)) {
			int zlen = min(len - ret, i_size - off - ret);
			int zoff = page_off + ret;
			dout("sync_read zero gap %llu~%llu\n",
                             off + ret, off + ret + zlen);
			ceph_zero_page_vector_range(zoff, zlen, pages);
			ret += zlen;
		}

946 947 948 949 950 951 952 953 954 955 956 957 958 959
		idx = 0;
		left = ret > 0 ? ret : 0;
		while (left > 0) {
			size_t len, copied;
			page_off = off & ~PAGE_MASK;
			len = min_t(size_t, left, PAGE_SIZE - page_off);
			SetPageUptodate(pages[idx]);
			copied = copy_page_to_iter(pages[idx++],
						   page_off, len, to);
			off += copied;
			left -= copied;
			if (copied < len) {
				ret = -EFAULT;
				break;
960
			}
961
		}
962
		ceph_release_page_vector(pages, num_pages);
Y
Yan, Zheng 已提交
963

964
		if (ret < 0) {
965 966
			if (ret == -EBLOCKLISTED)
				fsc->blocklisted = true;
967 968 969 970
			break;
		}

		if (off >= i_size || !more)
Y
Yan, Zheng 已提交
971
			break;
972
	}
S
Sage Weil 已提交
973

974
	if (off > iocb->ki_pos) {
975
		if (off >= i_size) {
Y
Yan, Zheng 已提交
976
			*retry_op = CHECK_EOF;
977 978 979 980 981 982
			ret = i_size - iocb->ki_pos;
			iocb->ki_pos = i_size;
		} else {
			ret = off - iocb->ki_pos;
			iocb->ki_pos = off;
		}
983
	}
S
Sage Weil 已提交
984

Y
Yan, Zheng 已提交
985
	dout("sync_read result %zd retry_op %d\n", ret, *retry_op);
S
Sage Weil 已提交
986 987 988
	return ret;
}

Y
Yan, Zheng 已提交
989 990 991
struct ceph_aio_request {
	struct kiocb *iocb;
	size_t total_len;
992 993
	bool write;
	bool should_dirty;
Y
Yan, Zheng 已提交
994 995 996 997
	int error;
	struct list_head osd_reqs;
	unsigned num_reqs;
	atomic_t pending_reqs;
998
	struct timespec64 mtime;
Y
Yan, Zheng 已提交
999 1000 1001
	struct ceph_cap_flush *prealloc_cf;
};

1002 1003 1004 1005 1006 1007 1008
struct ceph_aio_work {
	struct work_struct work;
	struct ceph_osd_request *req;
};

static void ceph_aio_retry_work(struct work_struct *work);

Y
Yan, Zheng 已提交
1009 1010 1011 1012 1013 1014 1015 1016 1017
static void ceph_aio_complete(struct inode *inode,
			      struct ceph_aio_request *aio_req)
{
	struct ceph_inode_info *ci = ceph_inode(inode);
	int ret;

	if (!atomic_dec_and_test(&aio_req->pending_reqs))
		return;

1018 1019 1020
	if (aio_req->iocb->ki_flags & IOCB_DIRECT)
		inode_dio_end(inode);

Y
Yan, Zheng 已提交
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
	ret = aio_req->error;
	if (!ret)
		ret = aio_req->total_len;

	dout("ceph_aio_complete %p rc %d\n", inode, ret);

	if (ret >= 0 && aio_req->write) {
		int dirty;

		loff_t endoff = aio_req->iocb->ki_pos + aio_req->total_len;
		if (endoff > i_size_read(inode)) {
			if (ceph_inode_set_size(inode, endoff))
				ceph_check_caps(ci, CHECK_CAPS_AUTHONLY, NULL);
		}

		spin_lock(&ci->i_ceph_lock);
		ci->i_inline_version = CEPH_INLINE_NONE;
		dirty = __ceph_mark_dirty_caps(ci, CEPH_CAP_FILE_WR,
					       &aio_req->prealloc_cf);
		spin_unlock(&ci->i_ceph_lock);
		if (dirty)
			__mark_inode_dirty(inode, dirty);

	}

	ceph_put_cap_refs(ci, (aio_req->write ? CEPH_CAP_FILE_WR :
						CEPH_CAP_FILE_RD));

1049
	aio_req->iocb->ki_complete(aio_req->iocb, ret);
Y
Yan, Zheng 已提交
1050 1051 1052 1053 1054

	ceph_free_cap_flush(aio_req->prealloc_cf);
	kfree(aio_req);
}

1055
static void ceph_aio_complete_req(struct ceph_osd_request *req)
Y
Yan, Zheng 已提交
1056 1057 1058 1059 1060
{
	int rc = req->r_result;
	struct inode *inode = req->r_inode;
	struct ceph_aio_request *aio_req = req->r_priv;
	struct ceph_osd_data *osd_data = osd_req_op_extent_osd_data(req, 0);
1061
	struct ceph_client_metric *metric = &ceph_sb_to_mdsc(inode->i_sb)->metric;
X
Xiubo Li 已提交
1062
	unsigned int len = osd_data->bvec_pos.iter.bi_size;
Y
Yan, Zheng 已提交
1063

1064 1065 1066
	BUG_ON(osd_data->type != CEPH_OSD_DATA_TYPE_BVECS);
	BUG_ON(!osd_data->num_bvecs);

X
Xiubo Li 已提交
1067
	dout("ceph_aio_complete_req %p rc %d bytes %u\n", inode, rc, len);
Y
Yan, Zheng 已提交
1068 1069

	if (rc == -EOLDSNAPC) {
1070 1071 1072 1073 1074 1075 1076
		struct ceph_aio_work *aio_work;
		BUG_ON(!aio_req->write);

		aio_work = kmalloc(sizeof(*aio_work), GFP_NOFS);
		if (aio_work) {
			INIT_WORK(&aio_work->work, ceph_aio_retry_work);
			aio_work->req = req;
1077
			queue_work(ceph_inode_to_client(inode)->inode_wq,
1078 1079 1080 1081 1082
				   &aio_work->work);
			return;
		}
		rc = -ENOMEM;
	} else if (!aio_req->write) {
Y
Yan, Zheng 已提交
1083 1084
		if (rc == -ENOENT)
			rc = 0;
X
Xiubo Li 已提交
1085
		if (rc >= 0 && len > rc) {
1086
			struct iov_iter i;
X
Xiubo Li 已提交
1087
			int zlen = len - rc;
1088

Y
Yan, Zheng 已提交
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
			/*
			 * If read is satisfied by single OSD request,
			 * it can pass EOF. Otherwise read is within
			 * i_size.
			 */
			if (aio_req->num_reqs == 1) {
				loff_t i_size = i_size_read(inode);
				loff_t endoff = aio_req->iocb->ki_pos + rc;
				if (endoff < i_size)
					zlen = min_t(size_t, zlen,
						     i_size - endoff);
				aio_req->total_len = rc + zlen;
			}

1103
			iov_iter_bvec(&i, READ, osd_data->bvec_pos.bvecs,
X
Xiubo Li 已提交
1104
				      osd_data->num_bvecs, len);
1105 1106
			iov_iter_advance(&i, rc);
			iov_iter_zero(zlen, &i);
Y
Yan, Zheng 已提交
1107 1108 1109
		}
	}

1110 1111 1112 1113
	/* r_start_latency == 0 means the request was not submitted */
	if (req->r_start_latency) {
		if (aio_req->write)
			ceph_update_write_metrics(metric, req->r_start_latency,
X
Xiubo Li 已提交
1114
						  req->r_end_latency, len, rc);
1115 1116
		else
			ceph_update_read_metrics(metric, req->r_start_latency,
X
Xiubo Li 已提交
1117
						 req->r_end_latency, len, rc);
1118 1119
	}

1120 1121
	put_bvecs(osd_data->bvec_pos.bvecs, osd_data->num_bvecs,
		  aio_req->should_dirty);
Y
Yan, Zheng 已提交
1122 1123 1124 1125 1126 1127 1128 1129 1130
	ceph_osdc_put_request(req);

	if (rc < 0)
		cmpxchg(&aio_req->error, 0, rc);

	ceph_aio_complete(inode, aio_req);
	return;
}

1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155
static void ceph_aio_retry_work(struct work_struct *work)
{
	struct ceph_aio_work *aio_work =
		container_of(work, struct ceph_aio_work, work);
	struct ceph_osd_request *orig_req = aio_work->req;
	struct ceph_aio_request *aio_req = orig_req->r_priv;
	struct inode *inode = orig_req->r_inode;
	struct ceph_inode_info *ci = ceph_inode(inode);
	struct ceph_snap_context *snapc;
	struct ceph_osd_request *req;
	int ret;

	spin_lock(&ci->i_ceph_lock);
	if (__ceph_have_pending_cap_snap(ci)) {
		struct ceph_cap_snap *capsnap =
			list_last_entry(&ci->i_cap_snaps,
					struct ceph_cap_snap,
					ci_item);
		snapc = ceph_get_snap_context(capsnap->context);
	} else {
		BUG_ON(!ci->i_head_snapc);
		snapc = ceph_get_snap_context(ci->i_head_snapc);
	}
	spin_unlock(&ci->i_ceph_lock);

1156
	req = ceph_osdc_alloc_request(orig_req->r_osdc, snapc, 1,
1157
			false, GFP_NOFS);
1158 1159
	if (!req) {
		ret = -ENOMEM;
1160 1161 1162 1163
		req = orig_req;
		goto out;
	}

1164
	req->r_flags = /* CEPH_OSD_FLAG_ORDERSNAP | */ CEPH_OSD_FLAG_WRITE;
1165
	ceph_oloc_copy(&req->r_base_oloc, &orig_req->r_base_oloc);
1166
	ceph_oid_copy(&req->r_base_oid, &orig_req->r_base_oid);
1167

1168 1169 1170 1171 1172
	req->r_ops[0] = orig_req->r_ops[0];

	req->r_mtime = aio_req->mtime;
	req->r_data_offset = req->r_ops[0].extent.offset;

1173 1174 1175 1176 1177 1178
	ret = ceph_osdc_alloc_messages(req, GFP_NOFS);
	if (ret) {
		ceph_osdc_put_request(req);
		req = orig_req;
		goto out;
	}
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189

	ceph_osdc_put_request(orig_req);

	req->r_callback = ceph_aio_complete_req;
	req->r_inode = inode;
	req->r_priv = aio_req;

	ret = ceph_osdc_start_request(req->r_osdc, req, false);
out:
	if (ret < 0) {
		req->r_result = ret;
1190
		ceph_aio_complete_req(req);
1191 1192
	}

1193
	ceph_put_snap_context(snapc);
1194 1195 1196
	kfree(aio_work);
}

1197
static ssize_t
Y
Yan, Zheng 已提交
1198 1199 1200
ceph_direct_read_write(struct kiocb *iocb, struct iov_iter *iter,
		       struct ceph_snap_context *snapc,
		       struct ceph_cap_flush **pcf)
S
Sage Weil 已提交
1201
{
1202
	struct file *file = iocb->ki_filp;
A
Al Viro 已提交
1203
	struct inode *inode = file_inode(file);
S
Sage Weil 已提交
1204
	struct ceph_inode_info *ci = ceph_inode(inode);
1205
	struct ceph_fs_client *fsc = ceph_inode_to_client(inode);
1206
	struct ceph_client_metric *metric = &fsc->mdsc->metric;
1207
	struct ceph_vino vino;
S
Sage Weil 已提交
1208
	struct ceph_osd_request *req;
1209
	struct bio_vec *bvecs;
Y
Yan, Zheng 已提交
1210 1211
	struct ceph_aio_request *aio_req = NULL;
	int num_pages = 0;
S
Sage Weil 已提交
1212
	int flags;
1213
	int ret = 0;
1214
	struct timespec64 mtime = current_time(inode);
Y
Yan, Zheng 已提交
1215 1216 1217
	size_t count = iov_iter_count(iter);
	loff_t pos = iocb->ki_pos;
	bool write = iov_iter_rw(iter) == WRITE;
1218
	bool should_dirty = !write && iter_is_iovec(iter);
S
Sage Weil 已提交
1219

Y
Yan, Zheng 已提交
1220
	if (write && ceph_snap(file_inode(file)) != CEPH_NOSNAP)
S
Sage Weil 已提交
1221 1222
		return -EROFS;

1223 1224
	dout("sync_direct_%s on file %p %lld~%u snapc %p seq %lld\n",
	     (write ? "write" : "read"), file, pos, (unsigned)count,
1225
	     snapc, snapc ? snapc->seq : 0);
S
Sage Weil 已提交
1226

Y
Yan, Zheng 已提交
1227
	if (write) {
1228 1229 1230 1231 1232
		int ret2;

		ceph_fscache_invalidate(inode, true);

		ret2 = invalidate_inode_pages2_range(inode->i_mapping,
1233
					pos >> PAGE_SHIFT,
1234
					(pos + count - 1) >> PAGE_SHIFT);
1235
		if (ret2 < 0)
1236
			dout("invalidate_inode_pages2_range returned %d\n", ret2);
1237

1238
		flags = /* CEPH_OSD_FLAG_ORDERSNAP | */ CEPH_OSD_FLAG_WRITE;
Y
Yan, Zheng 已提交
1239 1240 1241
	} else {
		flags = CEPH_OSD_FLAG_READ;
	}
S
Sage Weil 已提交
1242

Y
Yan, Zheng 已提交
1243
	while (iov_iter_count(iter) > 0) {
1244
		u64 size = iov_iter_count(iter);
Y
Yan, Zheng 已提交
1245
		ssize_t len;
1246

1247 1248 1249 1250 1251
		if (write)
			size = min_t(u64, size, fsc->mount_options->wsize);
		else
			size = min_t(u64, size, fsc->mount_options->rsize);

1252 1253
		vino = ceph_vino(inode);
		req = ceph_osdc_new_request(&fsc->client->osdc, &ci->i_layout,
Y
Yan, Zheng 已提交
1254
					    vino, pos, &size, 0,
Y
Yanhu Cao 已提交
1255
					    1,
Y
Yan, Zheng 已提交
1256 1257 1258
					    write ? CEPH_OSD_OP_WRITE :
						    CEPH_OSD_OP_READ,
					    flags, snapc,
1259 1260 1261 1262 1263
					    ci->i_truncate_seq,
					    ci->i_truncate_size,
					    false);
		if (IS_ERR(req)) {
			ret = PTR_ERR(req);
1264
			break;
1265
		}
S
Sage Weil 已提交
1266

1267 1268
		len = iter_get_bvecs_alloc(iter, size, &bvecs, &num_pages);
		if (len < 0) {
1269
			ceph_osdc_put_request(req);
1270
			ret = len;
1271
			break;
S
Sage Weil 已提交
1272
		}
1273 1274
		if (len != size)
			osd_req_op_extent_update(req, 0, len);
S
Sage Weil 已提交
1275 1276

		/*
Y
Yan, Zheng 已提交
1277 1278
		 * To simplify error handling, allow AIO when IO within i_size
		 * or IO can be satisfied by single OSD request.
S
Sage Weil 已提交
1279
		 */
Y
Yan, Zheng 已提交
1280 1281 1282 1283 1284 1285
		if (pos == iocb->ki_pos && !is_sync_kiocb(iocb) &&
		    (len == count || pos + count <= i_size_read(inode))) {
			aio_req = kzalloc(sizeof(*aio_req), GFP_KERNEL);
			if (aio_req) {
				aio_req->iocb = iocb;
				aio_req->write = write;
1286
				aio_req->should_dirty = should_dirty;
Y
Yan, Zheng 已提交
1287 1288
				INIT_LIST_HEAD(&aio_req->osd_reqs);
				if (write) {
1289
					aio_req->mtime = mtime;
Y
Yan, Zheng 已提交
1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
					swap(aio_req->prealloc_cf, *pcf);
				}
			}
			/* ignore error */
		}

		if (write) {
			/*
			 * throw out any page cache pages in this range. this
			 * may block.
			 */
			truncate_inode_pages_range(inode->i_mapping, pos,
1302
						   PAGE_ALIGN(pos + len) - 1);
Y
Yan, Zheng 已提交
1303

1304
			req->r_mtime = mtime;
Y
Yan, Zheng 已提交
1305 1306
		}

1307
		osd_req_op_extent_osd_data_bvecs(req, 0, bvecs, num_pages, len);
1308

Y
Yan, Zheng 已提交
1309 1310 1311 1312 1313 1314 1315 1316
		if (aio_req) {
			aio_req->total_len += len;
			aio_req->num_reqs++;
			atomic_inc(&aio_req->pending_reqs);

			req->r_callback = ceph_aio_complete_req;
			req->r_inode = inode;
			req->r_priv = aio_req;
1317
			list_add_tail(&req->r_private_item, &aio_req->osd_reqs);
Y
Yan, Zheng 已提交
1318 1319 1320 1321 1322 1323

			pos += len;
			continue;
		}

		ret = ceph_osdc_start_request(req->r_osdc, req, false);
1324 1325 1326
		if (!ret)
			ret = ceph_osdc_wait_request(&fsc->client->osdc, req);

1327
		if (write)
X
Xiubo Li 已提交
1328
			ceph_update_write_metrics(metric, req->r_start_latency,
X
Xiubo Li 已提交
1329
						  req->r_end_latency, len, ret);
1330
		else
X
Xiubo Li 已提交
1331
			ceph_update_read_metrics(metric, req->r_start_latency,
X
Xiubo Li 已提交
1332
						 req->r_end_latency, len, ret);
1333

Y
Yan, Zheng 已提交
1334 1335 1336 1337 1338
		size = i_size_read(inode);
		if (!write) {
			if (ret == -ENOENT)
				ret = 0;
			if (ret >= 0 && ret < len && pos + ret < size) {
1339
				struct iov_iter i;
Y
Yan, Zheng 已提交
1340 1341
				int zlen = min_t(size_t, len - ret,
						 size - pos - ret);
1342

1343
				iov_iter_bvec(&i, READ, bvecs, num_pages, len);
1344 1345
				iov_iter_advance(&i, ret);
				iov_iter_zero(zlen, &i);
Y
Yan, Zheng 已提交
1346 1347 1348 1349 1350 1351
				ret += zlen;
			}
			if (ret >= 0)
				len = ret;
		}

1352
		put_bvecs(bvecs, num_pages, should_dirty);
1353
		ceph_osdc_put_request(req);
Y
Yan, Zheng 已提交
1354
		if (ret < 0)
1355
			break;
1356

Y
Yan, Zheng 已提交
1357 1358
		pos += len;
		if (!write && pos >= size)
1359
			break;
1360

Y
Yan, Zheng 已提交
1361 1362
		if (write && pos > size) {
			if (ceph_inode_set_size(inode, pos))
1363 1364 1365 1366
				ceph_check_caps(ceph_inode(inode),
						CHECK_CAPS_AUTHONLY,
						NULL);
		}
1367 1368
	}

Y
Yan, Zheng 已提交
1369
	if (aio_req) {
1370 1371
		LIST_HEAD(osd_reqs);

Y
Yan, Zheng 已提交
1372 1373 1374 1375 1376 1377 1378 1379
		if (aio_req->num_reqs == 0) {
			kfree(aio_req);
			return ret;
		}

		ceph_get_cap_refs(ci, write ? CEPH_CAP_FILE_WR :
					      CEPH_CAP_FILE_RD);

1380
		list_splice(&aio_req->osd_reqs, &osd_reqs);
1381
		inode_dio_begin(inode);
1382 1383
		while (!list_empty(&osd_reqs)) {
			req = list_first_entry(&osd_reqs,
Y
Yan, Zheng 已提交
1384
					       struct ceph_osd_request,
1385 1386
					       r_private_item);
			list_del_init(&req->r_private_item);
Y
Yan, Zheng 已提交
1387 1388 1389 1390 1391
			if (ret >= 0)
				ret = ceph_osdc_start_request(req->r_osdc,
							      req, false);
			if (ret < 0) {
				req->r_result = ret;
1392
				ceph_aio_complete_req(req);
Y
Yan, Zheng 已提交
1393 1394 1395 1396 1397 1398 1399
			}
		}
		return -EIOCBQUEUED;
	}

	if (ret != -EOLDSNAPC && pos > iocb->ki_pos) {
		ret = pos - iocb->ki_pos;
1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411
		iocb->ki_pos = pos;
	}
	return ret;
}

/*
 * Synchronous write, straight from __user pointer or user pages.
 *
 * If write spans object boundary, just do multiple writes.  (For a
 * correct atomic write, we should e.g. take write locks on all
 * objects, rollback on failure, etc.)
 */
Y
Yan, Zheng 已提交
1412
static ssize_t
1413 1414
ceph_sync_write(struct kiocb *iocb, struct iov_iter *from, loff_t pos,
		struct ceph_snap_context *snapc)
1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427
{
	struct file *file = iocb->ki_filp;
	struct inode *inode = file_inode(file);
	struct ceph_inode_info *ci = ceph_inode(inode);
	struct ceph_fs_client *fsc = ceph_inode_to_client(inode);
	struct ceph_vino vino;
	struct ceph_osd_request *req;
	struct page **pages;
	u64 len;
	int num_pages;
	int written = 0;
	int flags;
	int ret;
1428
	bool check_caps = false;
1429
	struct timespec64 mtime = current_time(inode);
A
Al Viro 已提交
1430
	size_t count = iov_iter_count(from);
1431 1432 1433 1434

	if (ceph_snap(file_inode(file)) != CEPH_NOSNAP)
		return -EROFS;

1435 1436
	dout("sync_write on file %p %lld~%u snapc %p seq %lld\n",
	     file, pos, (unsigned)count, snapc, snapc->seq);
1437

1438 1439
	ret = filemap_write_and_wait_range(inode->i_mapping,
					   pos, pos + count - 1);
1440 1441 1442
	if (ret < 0)
		return ret;

1443
	ceph_fscache_invalidate(inode, false);
1444
	ret = invalidate_inode_pages2_range(inode->i_mapping,
1445
					    pos >> PAGE_SHIFT,
1446
					    (pos + count - 1) >> PAGE_SHIFT);
1447 1448 1449
	if (ret < 0)
		dout("invalidate_inode_pages2_range returned %d\n", ret);

1450
	flags = /* CEPH_OSD_FLAG_ORDERSNAP | */ CEPH_OSD_FLAG_WRITE;
1451

A
Al Viro 已提交
1452
	while ((len = iov_iter_count(from)) > 0) {
1453 1454 1455 1456 1457
		size_t left;
		int n;

		vino = ceph_vino(inode);
		req = ceph_osdc_new_request(&fsc->client->osdc, &ci->i_layout,
1458
					    vino, pos, &len, 0, 1,
1459 1460 1461 1462 1463 1464
					    CEPH_OSD_OP_WRITE, flags, snapc,
					    ci->i_truncate_seq,
					    ci->i_truncate_size,
					    false);
		if (IS_ERR(req)) {
			ret = PTR_ERR(req);
1465
			break;
1466 1467 1468 1469 1470 1471
		}

		/*
		 * write from beginning of first page,
		 * regardless of io alignment
		 */
1472
		num_pages = (len + PAGE_SIZE - 1) >> PAGE_SHIFT;
1473

1474
		pages = ceph_alloc_page_vector(num_pages, GFP_KERNEL);
S
Sage Weil 已提交
1475 1476 1477 1478
		if (IS_ERR(pages)) {
			ret = PTR_ERR(pages);
			goto out;
		}
1479 1480 1481

		left = len;
		for (n = 0; n < num_pages; n++) {
1482
			size_t plen = min_t(size_t, left, PAGE_SIZE);
A
Al Viro 已提交
1483
			ret = copy_page_from_iter(pages[n], 0, plen, from);
1484 1485 1486 1487 1488 1489 1490
			if (ret != plen) {
				ret = -EFAULT;
				break;
			}
			left -= ret;
		}

S
Sage Weil 已提交
1491 1492 1493 1494 1495
		if (ret < 0) {
			ceph_release_page_vector(pages, num_pages);
			goto out;
		}

1496
		req->r_inode = inode;
S
Sage Weil 已提交
1497

1498 1499
		osd_req_op_extent_osd_data_pages(req, 0, pages, len, 0,
						false, true);
1500

1501
		req->r_mtime = mtime;
1502 1503 1504
		ret = ceph_osdc_start_request(&fsc->client->osdc, req, false);
		if (!ret)
			ret = ceph_osdc_wait_request(&fsc->client->osdc, req);
S
Sage Weil 已提交
1505

X
Xiubo Li 已提交
1506
		ceph_update_write_metrics(&fsc->mdsc->metric, req->r_start_latency,
X
Xiubo Li 已提交
1507
					  req->r_end_latency, len, ret);
S
Sage Weil 已提交
1508
out:
1509
		ceph_osdc_put_request(req);
1510 1511
		if (ret != 0) {
			ceph_set_error_write(ci);
1512
			break;
1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525
		}

		ceph_clear_error_write(ci);
		pos += len;
		written += len;
		if (pos > i_size_read(inode)) {
			check_caps = ceph_inode_set_size(inode, pos);
			if (check_caps)
				ceph_check_caps(ceph_inode(inode),
						CHECK_CAPS_AUTHONLY,
						NULL);
		}

1526
	}
S
Sage Weil 已提交
1527

1528
	if (ret != -EOLDSNAPC && written > 0) {
S
Sage Weil 已提交
1529
		ret = written;
1530
		iocb->ki_pos = pos;
S
Sage Weil 已提交
1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541
	}
	return ret;
}

/*
 * Wrap generic_file_aio_read with checks for cap bits on the inode.
 * Atomically grab references, so that those bits are not released
 * back to the MDS mid-read.
 *
 * Hmm, the sync read case isn't actually async... should it be?
 */
A
Al Viro 已提交
1542
static ssize_t ceph_read_iter(struct kiocb *iocb, struct iov_iter *to)
S
Sage Weil 已提交
1543 1544
{
	struct file *filp = iocb->ki_filp;
1545
	struct ceph_file_info *fi = filp->private_data;
C
Christoph Hellwig 已提交
1546
	size_t len = iov_iter_count(to);
A
Al Viro 已提交
1547
	struct inode *inode = file_inode(filp);
S
Sage Weil 已提交
1548
	struct ceph_inode_info *ci = ceph_inode(inode);
1549
	bool direct_lock = iocb->ki_flags & IOCB_DIRECT;
S
Sage Weil 已提交
1550
	ssize_t ret;
J
Jeff Layton 已提交
1551
	int want = 0, got = 0;
Y
Yan, Zheng 已提交
1552
	int retry_op = 0, read = 0;
S
Sage Weil 已提交
1553

1554
again:
1555 1556 1557
	dout("aio_read %p %llx.%llx %llu~%u trying to get caps on %p\n",
	     inode, ceph_vinop(inode), iocb->ki_pos, (unsigned)len, inode);

1558 1559 1560
	if (ceph_inode_is_shutdown(inode))
		return -ESTALE;

1561
	if (direct_lock)
1562 1563 1564 1565
		ceph_start_io_direct(inode);
	else
		ceph_start_io_read(inode);

J
Jeff Layton 已提交
1566 1567
	if (!(fi->flags & CEPH_F_SYNC) && !direct_lock)
		want |= CEPH_CAP_FILE_CACHE;
1568
	if (fi->fmode & CEPH_FILE_MODE_LAZY)
J
Jeff Layton 已提交
1569 1570
		want |= CEPH_CAP_FILE_LAZYIO;

1571
	ret = ceph_get_caps(filp, CEPH_CAP_FILE_RD, want, -1, &got);
1572
	if (ret < 0) {
J
Jeff Layton 已提交
1573
		if (direct_lock)
1574 1575 1576
			ceph_end_io_direct(inode);
		else
			ceph_end_io_read(inode);
1577
		return ret;
1578
	}
S
Sage Weil 已提交
1579

1580
	if ((got & (CEPH_CAP_FILE_CACHE|CEPH_CAP_FILE_LAZYIO)) == 0 ||
1581
	    (iocb->ki_flags & IOCB_DIRECT) ||
1582 1583 1584 1585 1586 1587
	    (fi->flags & CEPH_F_SYNC)) {

		dout("aio_sync_read %p %llx.%llx %llu~%u got cap refs on %s\n",
		     inode, ceph_vinop(inode), iocb->ki_pos, (unsigned)len,
		     ceph_cap_string(got));

Y
Yan, Zheng 已提交
1588
		if (ci->i_inline_version == CEPH_INLINE_NONE) {
Y
Yan, Zheng 已提交
1589 1590 1591 1592 1593 1594 1595 1596
			if (!retry_op && (iocb->ki_flags & IOCB_DIRECT)) {
				ret = ceph_direct_read_write(iocb, to,
							     NULL, NULL);
				if (ret >= 0 && ret < len)
					retry_op = CHECK_EOF;
			} else {
				ret = ceph_sync_read(iocb, to, &retry_op);
			}
Y
Yan, Zheng 已提交
1597 1598 1599
		} else {
			retry_op = READ_INLINE;
		}
1600
	} else {
1601
		CEPH_DEFINE_RW_CONTEXT(rw_ctx, got);
1602
		dout("aio_read %p %llx.%llx %llu~%u got cap refs on %s\n",
A
Al Viro 已提交
1603
		     inode, ceph_vinop(inode), iocb->ki_pos, (unsigned)len,
1604
		     ceph_cap_string(got));
1605
		ceph_add_rw_context(fi, &rw_ctx);
A
Al Viro 已提交
1606
		ret = generic_file_read_iter(iocb, to);
1607
		ceph_del_rw_context(fi, &rw_ctx);
1608
	}
1609

S
Sage Weil 已提交
1610 1611 1612
	dout("aio_read %p %llx.%llx dropping cap refs on %s = %d\n",
	     inode, ceph_vinop(inode), ceph_cap_string(got), (int)ret);
	ceph_put_cap_refs(ci, got);
1613

1614
	if (direct_lock)
1615 1616 1617 1618
		ceph_end_io_direct(inode);
	else
		ceph_end_io_read(inode);

Y
Yan, Zheng 已提交
1619
	if (retry_op > HAVE_RETRIED && ret >= 0) {
Y
Yan, Zheng 已提交
1620 1621 1622 1623
		int statret;
		struct page *page = NULL;
		loff_t i_size;
		if (retry_op == READ_INLINE) {
1624
			page = __page_cache_alloc(GFP_KERNEL);
Y
Yan, Zheng 已提交
1625 1626 1627
			if (!page)
				return -ENOMEM;
		}
1628

Y
Yan, Zheng 已提交
1629 1630 1631
		statret = __ceph_do_getattr(inode, page,
					    CEPH_STAT_CAP_INLINE_DATA, !!page);
		if (statret < 0) {
1632 1633
			if (page)
				__free_page(page);
Y
Yan, Zheng 已提交
1634 1635 1636 1637 1638 1639
			if (statret == -ENODATA) {
				BUG_ON(retry_op != READ_INLINE);
				goto again;
			}
			return statret;
		}
1640

Y
Yan, Zheng 已提交
1641 1642
		i_size = i_size_read(inode);
		if (retry_op == READ_INLINE) {
1643 1644
			BUG_ON(ret > 0 || read > 0);
			if (iocb->ki_pos < i_size &&
1645
			    iocb->ki_pos < PAGE_SIZE) {
Y
Yan, Zheng 已提交
1646 1647
				loff_t end = min_t(loff_t, i_size,
						   iocb->ki_pos + len);
1648
				end = min_t(loff_t, end, PAGE_SIZE);
Y
Yan, Zheng 已提交
1649 1650 1651 1652 1653 1654
				if (statret < end)
					zero_user_segment(page, statret, end);
				ret = copy_page_to_iter(page,
						iocb->ki_pos & ~PAGE_MASK,
						end - iocb->ki_pos, to);
				iocb->ki_pos += ret;
1655 1656 1657 1658 1659 1660 1661 1662
				read += ret;
			}
			if (iocb->ki_pos < i_size && read < len) {
				size_t zlen = min_t(size_t, len - read,
						    i_size - iocb->ki_pos);
				ret = iov_iter_zero(zlen, to);
				iocb->ki_pos += ret;
				read += ret;
Y
Yan, Zheng 已提交
1663 1664
			}
			__free_pages(page, 0);
1665
			return read;
Y
Yan, Zheng 已提交
1666
		}
1667 1668

		/* hit EOF or hole? */
Y
Yan, Zheng 已提交
1669
		if (retry_op == CHECK_EOF && iocb->ki_pos < i_size &&
1670
		    ret < len) {
1671
			dout("sync_read hit hole, ppos %lld < size %lld"
1672
			     ", reading more\n", iocb->ki_pos, i_size);
1673

1674 1675
			read += ret;
			len -= ret;
Y
Yan, Zheng 已提交
1676
			retry_op = HAVE_RETRIED;
1677 1678 1679
			goto again;
		}
	}
1680

1681 1682 1683
	if (ret >= 0)
		ret += read;

S
Sage Weil 已提交
1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696
	return ret;
}

/*
 * Take cap references to avoid releasing caps to MDS mid-write.
 *
 * If we are synchronous, and write with an old snap context, the OSD
 * may return EOLDSNAPC.  In that case, retry the write.. _after_
 * dropping our cap refs and allowing the pending snap to logically
 * complete _before_ this write occurs.
 *
 * If we are near ENOSPC, write synchronously.
 */
A
Al Viro 已提交
1697
static ssize_t ceph_write_iter(struct kiocb *iocb, struct iov_iter *from)
S
Sage Weil 已提交
1698 1699
{
	struct file *file = iocb->ki_filp;
1700
	struct ceph_file_info *fi = file->private_data;
A
Al Viro 已提交
1701
	struct inode *inode = file_inode(file);
S
Sage Weil 已提交
1702
	struct ceph_inode_info *ci = ceph_inode(inode);
1703
	struct ceph_fs_client *fsc = ceph_inode_to_client(inode);
1704
	struct ceph_osd_client *osdc = &fsc->client->osdc;
1705
	struct ceph_cap_flush *prealloc_cf;
1706
	ssize_t count, written = 0;
J
Jeff Layton 已提交
1707
	int err, want = 0, got;
1708
	bool direct_lock = false;
1709 1710
	u32 map_flags;
	u64 pool_flags;
1711
	loff_t pos;
1712
	loff_t limit = max(i_size_read(inode), fsc->max_file_size);
S
Sage Weil 已提交
1713

1714 1715 1716
	if (ceph_inode_is_shutdown(inode))
		return -ESTALE;

S
Sage Weil 已提交
1717 1718 1719
	if (ceph_snap(inode) != CEPH_NOSNAP)
		return -EROFS;

1720 1721 1722 1723
	prealloc_cf = ceph_alloc_cap_flush();
	if (!prealloc_cf)
		return -ENOMEM;

1724 1725 1726
	if ((iocb->ki_flags & (IOCB_DIRECT | IOCB_APPEND)) == IOCB_DIRECT)
		direct_lock = true;

Y
Yan, Zheng 已提交
1727
retry_snap:
1728
	if (direct_lock)
1729 1730 1731
		ceph_start_io_direct(inode);
	else
		ceph_start_io_write(inode);
1732 1733

	/* We can write back this queue in page reclaim */
1734
	current->backing_dev_info = inode_to_bdi(inode);
1735

1736 1737 1738 1739 1740 1741
	if (iocb->ki_flags & IOCB_APPEND) {
		err = ceph_do_getattr(inode, CEPH_STAT_CAP_SIZE, false);
		if (err < 0)
			goto out;
	}

1742 1743
	err = generic_write_checks(iocb, from);
	if (err <= 0)
1744 1745
		goto out;

1746
	pos = iocb->ki_pos;
1747 1748 1749 1750 1751 1752 1753
	if (unlikely(pos >= limit)) {
		err = -EFBIG;
		goto out;
	} else {
		iov_iter_truncate(from, limit - pos);
	}

1754
	count = iov_iter_count(from);
1755 1756 1757 1758 1759
	if (ceph_quota_is_max_bytes_exceeded(inode, pos + count)) {
		err = -EDQUOT;
		goto out;
	}

1760 1761 1762 1763 1764 1765 1766
	down_read(&osdc->lock);
	map_flags = osdc->osdmap->flags;
	pool_flags = ceph_pg_pool_flags(osdc->osdmap, ci->i_layout.pool_id);
	up_read(&osdc->lock);
	if ((map_flags & CEPH_OSDMAP_FULL) ||
	    (pool_flags & CEPH_POOL_FLAG_FULL)) {
		err = -ENOSPC;
1767
		goto out;
1768
	}
1769

1770
	err = file_remove_privs(file);
1771 1772 1773
	if (err)
		goto out;

1774 1775 1776 1777 1778 1779
	if (ci->i_inline_version != CEPH_INLINE_NONE) {
		err = ceph_uninline_data(file, NULL);
		if (err < 0)
			goto out;
	}

1780
	dout("aio_write %p %llx.%llx %llu~%zd getting caps. i_size %llu\n",
1781
	     inode, ceph_vinop(inode), pos, count, i_size_read(inode));
J
Jeff Layton 已提交
1782 1783
	if (!(fi->flags & CEPH_F_SYNC) && !direct_lock)
		want |= CEPH_CAP_FILE_BUFFER;
S
Sage Weil 已提交
1784
	if (fi->fmode & CEPH_FILE_MODE_LAZY)
J
Jeff Layton 已提交
1785
		want |= CEPH_CAP_FILE_LAZYIO;
1786
	got = 0;
1787
	err = ceph_get_caps(file, CEPH_CAP_FILE_WR, want, pos + count, &got);
1788
	if (err < 0)
1789
		goto out;
S
Sage Weil 已提交
1790

1791 1792 1793 1794 1795 1796
	err = file_update_time(file);
	if (err)
		goto out_caps;

	inode_inc_iversion_raw(inode);

1797
	dout("aio_write %p %llx.%llx %llu~%zd got cap refs on %s\n",
1798
	     inode, ceph_vinop(inode), pos, count, ceph_cap_string(got));
S
Sage Weil 已提交
1799 1800

	if ((got & (CEPH_CAP_FILE_BUFFER|CEPH_CAP_FILE_LAZYIO)) == 0 ||
1801 1802
	    (iocb->ki_flags & IOCB_DIRECT) || (fi->flags & CEPH_F_SYNC) ||
	    (ci->i_ceph_flags & CEPH_I_ERROR_WRITE)) {
1803
		struct ceph_snap_context *snapc;
A
Al Viro 已提交
1804
		struct iov_iter data;
1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818

		spin_lock(&ci->i_ceph_lock);
		if (__ceph_have_pending_cap_snap(ci)) {
			struct ceph_cap_snap *capsnap =
					list_last_entry(&ci->i_cap_snaps,
							struct ceph_cap_snap,
							ci_item);
			snapc = ceph_get_snap_context(capsnap->context);
		} else {
			BUG_ON(!ci->i_head_snapc);
			snapc = ceph_get_snap_context(ci->i_head_snapc);
		}
		spin_unlock(&ci->i_ceph_lock);

A
Al Viro 已提交
1819 1820
		/* we might need to revert back to that point */
		data = *from;
1821
		if (iocb->ki_flags & IOCB_DIRECT)
Y
Yan, Zheng 已提交
1822 1823
			written = ceph_direct_read_write(iocb, &data, snapc,
							 &prealloc_cf);
1824
		else
1825
			written = ceph_sync_write(iocb, &data, pos, snapc);
1826 1827 1828
		if (direct_lock)
			ceph_end_io_direct(inode);
		else
1829
			ceph_end_io_write(inode);
A
Al Viro 已提交
1830 1831
		if (written > 0)
			iov_iter_advance(from, written);
1832
		ceph_put_snap_context(snapc);
S
Sage Weil 已提交
1833
	} else {
Y
Yan, Zheng 已提交
1834 1835 1836 1837 1838 1839 1840
		/*
		 * No need to acquire the i_truncate_mutex. Because
		 * the MDS revokes Fwb caps before sending truncate
		 * message to us. We can't get Fwb cap while there
		 * are pending vmtruncate. So write and vmtruncate
		 * can not run at the same time
		 */
A
Al Viro 已提交
1841
		written = generic_perform_write(file, from, pos);
1842 1843
		if (likely(written >= 0))
			iocb->ki_pos = pos + written;
1844
		ceph_end_io_write(inode);
S
Sage Weil 已提交
1845
	}
1846

1847
	if (written >= 0) {
1848
		int dirty;
1849

1850
		spin_lock(&ci->i_ceph_lock);
1851
		ci->i_inline_version = CEPH_INLINE_NONE;
1852 1853
		dirty = __ceph_mark_dirty_caps(ci, CEPH_CAP_FILE_WR,
					       &prealloc_cf);
1854
		spin_unlock(&ci->i_ceph_lock);
1855 1856
		if (dirty)
			__mark_inode_dirty(inode, dirty);
1857
		if (ceph_quota_is_max_bytes_approaching(inode, iocb->ki_pos))
1858
			ceph_check_caps(ci, 0, NULL);
S
Sage Weil 已提交
1859
	}
S
Sage Weil 已提交
1860

S
Sage Weil 已提交
1861
	dout("aio_write %p %llx.%llx %llu~%u  dropping cap refs on %s\n",
A
Al Viro 已提交
1862
	     inode, ceph_vinop(inode), pos, (unsigned)count,
S
Sage Weil 已提交
1863
	     ceph_cap_string(got));
S
Sage Weil 已提交
1864
	ceph_put_cap_refs(ci, got);
S
Sage Weil 已提交
1865

Y
Yan, Zheng 已提交
1866 1867 1868 1869 1870 1871
	if (written == -EOLDSNAPC) {
		dout("aio_write %p %llx.%llx %llu~%u" "got EOLDSNAPC, retrying\n",
		     inode, ceph_vinop(inode), pos, (unsigned)count);
		goto retry_snap;
	}

C
Christoph Hellwig 已提交
1872
	if (written >= 0) {
1873 1874
		if ((map_flags & CEPH_OSDMAP_NEARFULL) ||
		    (pool_flags & CEPH_POOL_FLAG_NEARFULL))
C
Christoph Hellwig 已提交
1875 1876
			iocb->ki_flags |= IOCB_DSYNC;
		written = generic_write_sync(iocb, written);
Y
Yan, Zheng 已提交
1877
	}
1878

1879
	goto out_unlocked;
1880 1881
out_caps:
	ceph_put_cap_refs(ci, got);
1882
out:
1883
	if (direct_lock)
1884 1885 1886
		ceph_end_io_direct(inode);
	else
		ceph_end_io_write(inode);
1887
out_unlocked:
1888
	ceph_free_cap_flush(prealloc_cf);
1889 1890
	current->backing_dev_info = NULL;
	return written ? written : err;
S
Sage Weil 已提交
1891 1892 1893 1894 1895
}

/*
 * llseek.  be sure to verify file size on SEEK_END.
 */
1896
static loff_t ceph_llseek(struct file *file, loff_t offset, int whence)
S
Sage Weil 已提交
1897 1898
{
	struct inode *inode = file->f_mapping->host;
1899
	struct ceph_fs_client *fsc = ceph_inode_to_client(inode);
1900
	loff_t i_size;
1901
	loff_t ret;
S
Sage Weil 已提交
1902

A
Al Viro 已提交
1903
	inode_lock(inode);
1904

1905
	if (whence == SEEK_END || whence == SEEK_DATA || whence == SEEK_HOLE) {
1906
		ret = ceph_do_getattr(inode, CEPH_STAT_CAP_SIZE, false);
1907
		if (ret < 0)
S
Sage Weil 已提交
1908
			goto out;
1909 1910
	}

1911
	i_size = i_size_read(inode);
1912
	switch (whence) {
1913
	case SEEK_END:
1914
		offset += i_size;
S
Sage Weil 已提交
1915 1916 1917 1918 1919 1920 1921 1922 1923
		break;
	case SEEK_CUR:
		/*
		 * Here we special-case the lseek(fd, 0, SEEK_CUR)
		 * position-querying operation.  Avoid rewriting the "same"
		 * f_pos value back to the file because a concurrent read(),
		 * write() or lseek() might have altered it
		 */
		if (offset == 0) {
1924
			ret = file->f_pos;
S
Sage Weil 已提交
1925 1926 1927 1928
			goto out;
		}
		offset += file->f_pos;
		break;
1929
	case SEEK_DATA:
1930
		if (offset < 0 || offset >= i_size) {
1931 1932 1933 1934 1935
			ret = -ENXIO;
			goto out;
		}
		break;
	case SEEK_HOLE:
1936
		if (offset < 0 || offset >= i_size) {
1937 1938 1939
			ret = -ENXIO;
			goto out;
		}
1940
		offset = i_size;
1941
		break;
S
Sage Weil 已提交
1942 1943
	}

1944
	ret = vfs_setpos(file, offset, max(i_size, fsc->max_file_size));
S
Sage Weil 已提交
1945 1946

out:
A
Al Viro 已提交
1947
	inode_unlock(inode);
1948
	return ret;
S
Sage Weil 已提交
1949 1950
}

L
Li Wang 已提交
1951 1952 1953 1954
static inline void ceph_zero_partial_page(
	struct inode *inode, loff_t offset, unsigned size)
{
	struct page *page;
1955
	pgoff_t index = offset >> PAGE_SHIFT;
L
Li Wang 已提交
1956 1957 1958 1959

	page = find_lock_page(inode->i_mapping, index);
	if (page) {
		wait_on_page_writeback(page);
1960
		zero_user(page, offset & (PAGE_SIZE - 1), size);
L
Li Wang 已提交
1961
		unlock_page(page);
1962
		put_page(page);
L
Li Wang 已提交
1963 1964 1965 1966 1967 1968
	}
}

static void ceph_zero_pagecache_range(struct inode *inode, loff_t offset,
				      loff_t length)
{
1969
	loff_t nearly = round_up(offset, PAGE_SIZE);
L
Li Wang 已提交
1970 1971 1972 1973 1974 1975 1976 1977
	if (offset < nearly) {
		loff_t size = nearly - offset;
		if (length < size)
			size = length;
		ceph_zero_partial_page(inode, offset, size);
		offset += size;
		length -= size;
	}
1978 1979
	if (length >= PAGE_SIZE) {
		loff_t size = round_down(length, PAGE_SIZE);
L
Li Wang 已提交
1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007
		truncate_pagecache_range(inode, offset, offset + size - 1);
		offset += size;
		length -= size;
	}
	if (length)
		ceph_zero_partial_page(inode, offset, length);
}

static int ceph_zero_partial_object(struct inode *inode,
				    loff_t offset, loff_t *length)
{
	struct ceph_inode_info *ci = ceph_inode(inode);
	struct ceph_fs_client *fsc = ceph_inode_to_client(inode);
	struct ceph_osd_request *req;
	int ret = 0;
	loff_t zero = 0;
	int op;

	if (!length) {
		op = offset ? CEPH_OSD_OP_DELETE : CEPH_OSD_OP_TRUNCATE;
		length = &zero;
	} else {
		op = CEPH_OSD_OP_ZERO;
	}

	req = ceph_osdc_new_request(&fsc->client->osdc, &ci->i_layout,
					ceph_vino(inode),
					offset, length,
2008
					0, 1, op,
2009
					CEPH_OSD_FLAG_WRITE,
L
Li Wang 已提交
2010 2011 2012 2013 2014 2015
					NULL, 0, 0, false);
	if (IS_ERR(req)) {
		ret = PTR_ERR(req);
		goto out;
	}

2016
	req->r_mtime = inode->i_mtime;
L
Li Wang 已提交
2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032
	ret = ceph_osdc_start_request(&fsc->client->osdc, req, false);
	if (!ret) {
		ret = ceph_osdc_wait_request(&fsc->client->osdc, req);
		if (ret == -ENOENT)
			ret = 0;
	}
	ceph_osdc_put_request(req);

out:
	return ret;
}

static int ceph_zero_objects(struct inode *inode, loff_t offset, loff_t length)
{
	int ret = 0;
	struct ceph_inode_info *ci = ceph_inode(inode);
2033 2034 2035
	s32 stripe_unit = ci->i_layout.stripe_unit;
	s32 stripe_count = ci->i_layout.stripe_count;
	s32 object_size = ci->i_layout.object_size;
S
Sage Weil 已提交
2036 2037 2038 2039 2040 2041 2042
	u64 object_set_size = object_size * stripe_count;
	u64 nearly, t;

	/* round offset up to next period boundary */
	nearly = offset + object_set_size - 1;
	t = nearly;
	nearly -= do_div(t, object_set_size);
L
Li Wang 已提交
2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078

	while (length && offset < nearly) {
		loff_t size = length;
		ret = ceph_zero_partial_object(inode, offset, &size);
		if (ret < 0)
			return ret;
		offset += size;
		length -= size;
	}
	while (length >= object_set_size) {
		int i;
		loff_t pos = offset;
		for (i = 0; i < stripe_count; ++i) {
			ret = ceph_zero_partial_object(inode, pos, NULL);
			if (ret < 0)
				return ret;
			pos += stripe_unit;
		}
		offset += object_set_size;
		length -= object_set_size;
	}
	while (length) {
		loff_t size = length;
		ret = ceph_zero_partial_object(inode, offset, &size);
		if (ret < 0)
			return ret;
		offset += size;
		length -= size;
	}
	return ret;
}

static long ceph_fallocate(struct file *file, int mode,
				loff_t offset, loff_t length)
{
	struct ceph_file_info *fi = file->private_data;
L
Libo Chen 已提交
2079
	struct inode *inode = file_inode(file);
L
Li Wang 已提交
2080
	struct ceph_inode_info *ci = ceph_inode(inode);
2081
	struct ceph_cap_flush *prealloc_cf;
L
Li Wang 已提交
2082 2083 2084 2085 2086 2087
	int want, got = 0;
	int dirty;
	int ret = 0;
	loff_t endoff = 0;
	loff_t size;

2088
	if (mode != (FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE))
2089 2090
		return -EOPNOTSUPP;

L
Li Wang 已提交
2091 2092 2093
	if (!S_ISREG(inode->i_mode))
		return -EOPNOTSUPP;

2094 2095 2096 2097
	prealloc_cf = ceph_alloc_cap_flush();
	if (!prealloc_cf)
		return -ENOMEM;

A
Al Viro 已提交
2098
	inode_lock(inode);
L
Li Wang 已提交
2099 2100 2101 2102 2103 2104

	if (ceph_snap(inode) != CEPH_NOSNAP) {
		ret = -EROFS;
		goto unlock;
	}

2105 2106 2107 2108 2109 2110
	if (ci->i_inline_version != CEPH_INLINE_NONE) {
		ret = ceph_uninline_data(file, NULL);
		if (ret < 0)
			goto unlock;
	}

L
Li Wang 已提交
2111
	size = i_size_read(inode);
2112 2113 2114 2115 2116 2117

	/* Are we punching a hole beyond EOF? */
	if (offset >= size)
		goto unlock;
	if ((offset + length) > size)
		length = size - offset;
L
Li Wang 已提交
2118 2119 2120 2121 2122 2123

	if (fi->fmode & CEPH_FILE_MODE_LAZY)
		want = CEPH_CAP_FILE_BUFFER | CEPH_CAP_FILE_LAZYIO;
	else
		want = CEPH_CAP_FILE_BUFFER;

2124
	ret = ceph_get_caps(file, CEPH_CAP_FILE_WR, want, endoff, &got);
L
Li Wang 已提交
2125 2126 2127
	if (ret < 0)
		goto unlock;

2128
	filemap_invalidate_lock(inode->i_mapping);
2129
	ceph_fscache_invalidate(inode, false);
2130 2131
	ceph_zero_pagecache_range(inode, offset, length);
	ret = ceph_zero_objects(inode, offset, length);
L
Li Wang 已提交
2132 2133 2134

	if (!ret) {
		spin_lock(&ci->i_ceph_lock);
2135
		ci->i_inline_version = CEPH_INLINE_NONE;
2136 2137
		dirty = __ceph_mark_dirty_caps(ci, CEPH_CAP_FILE_WR,
					       &prealloc_cf);
L
Li Wang 已提交
2138 2139 2140 2141
		spin_unlock(&ci->i_ceph_lock);
		if (dirty)
			__mark_inode_dirty(inode, dirty);
	}
2142
	filemap_invalidate_unlock(inode->i_mapping);
L
Li Wang 已提交
2143 2144 2145

	ceph_put_cap_refs(ci, got);
unlock:
A
Al Viro 已提交
2146
	inode_unlock(inode);
2147
	ceph_free_cap_flush(prealloc_cf);
L
Li Wang 已提交
2148 2149 2150
	return ret;
}

2151 2152 2153 2154 2155
/*
 * This function tries to get FILE_WR capabilities for dst_ci and FILE_RD for
 * src_ci.  Two attempts are made to obtain both caps, and an error is return if
 * this fails; zero is returned on success.
 */
Y
Yan, Zheng 已提交
2156 2157
static int get_rd_wr_caps(struct file *src_filp, int *src_got,
			  struct file *dst_filp,
2158 2159 2160 2161 2162 2163
			  loff_t dst_endoff, int *dst_got)
{
	int ret = 0;
	bool retrying = false;

retry_caps:
Y
Yan, Zheng 已提交
2164
	ret = ceph_get_caps(dst_filp, CEPH_CAP_FILE_WR, CEPH_CAP_FILE_BUFFER,
2165
			    dst_endoff, dst_got);
2166 2167 2168 2169 2170 2171 2172 2173
	if (ret < 0)
		return ret;

	/*
	 * Since we're already holding the FILE_WR capability for the dst file,
	 * we would risk a deadlock by using ceph_get_caps.  Thus, we'll do some
	 * retry dance instead to try to get both capabilities.
	 */
Y
Yan, Zheng 已提交
2174 2175
	ret = ceph_try_get_caps(file_inode(src_filp),
				CEPH_CAP_FILE_RD, CEPH_CAP_FILE_SHARED,
2176 2177 2178
				false, src_got);
	if (ret <= 0) {
		/* Start by dropping dst_ci caps and getting src_ci caps */
Y
Yan, Zheng 已提交
2179
		ceph_put_cap_refs(ceph_inode(file_inode(dst_filp)), *dst_got);
2180 2181 2182 2183 2184 2185
		if (retrying) {
			if (!ret)
				/* ceph_try_get_caps masks EAGAIN */
				ret = -EAGAIN;
			return ret;
		}
Y
Yan, Zheng 已提交
2186
		ret = ceph_get_caps(src_filp, CEPH_CAP_FILE_RD,
2187
				    CEPH_CAP_FILE_SHARED, -1, src_got);
2188 2189 2190
		if (ret < 0)
			return ret;
		/*... drop src_ci caps too, and retry */
Y
Yan, Zheng 已提交
2191
		ceph_put_cap_refs(ceph_inode(file_inode(src_filp)), *src_got);
2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239
		retrying = true;
		goto retry_caps;
	}
	return ret;
}

static void put_rd_wr_caps(struct ceph_inode_info *src_ci, int src_got,
			   struct ceph_inode_info *dst_ci, int dst_got)
{
	ceph_put_cap_refs(src_ci, src_got);
	ceph_put_cap_refs(dst_ci, dst_got);
}

/*
 * This function does several size-related checks, returning an error if:
 *  - source file is smaller than off+len
 *  - destination file size is not OK (inode_newsize_ok())
 *  - max bytes quotas is exceeded
 */
static int is_file_size_ok(struct inode *src_inode, struct inode *dst_inode,
			   loff_t src_off, loff_t dst_off, size_t len)
{
	loff_t size, endoff;

	size = i_size_read(src_inode);
	/*
	 * Don't copy beyond source file EOF.  Instead of simply setting length
	 * to (size - src_off), just drop to VFS default implementation, as the
	 * local i_size may be stale due to other clients writing to the source
	 * inode.
	 */
	if (src_off + len > size) {
		dout("Copy beyond EOF (%llu + %zu > %llu)\n",
		     src_off, len, size);
		return -EOPNOTSUPP;
	}
	size = i_size_read(dst_inode);

	endoff = dst_off + len;
	if (inode_newsize_ok(dst_inode, endoff))
		return -EOPNOTSUPP;

	if (ceph_quota_is_max_bytes_exceeded(dst_inode, endoff))
		return -EDQUOT;

	return 0;
}

2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287
static struct ceph_osd_request *
ceph_alloc_copyfrom_request(struct ceph_osd_client *osdc,
			    u64 src_snapid,
			    struct ceph_object_id *src_oid,
			    struct ceph_object_locator *src_oloc,
			    struct ceph_object_id *dst_oid,
			    struct ceph_object_locator *dst_oloc,
			    u32 truncate_seq, u64 truncate_size)
{
	struct ceph_osd_request *req;
	int ret;
	u32 src_fadvise_flags =
		CEPH_OSD_OP_FLAG_FADVISE_SEQUENTIAL |
		CEPH_OSD_OP_FLAG_FADVISE_NOCACHE;
	u32 dst_fadvise_flags =
		CEPH_OSD_OP_FLAG_FADVISE_SEQUENTIAL |
		CEPH_OSD_OP_FLAG_FADVISE_DONTNEED;

	req = ceph_osdc_alloc_request(osdc, NULL, 1, false, GFP_KERNEL);
	if (!req)
		return ERR_PTR(-ENOMEM);

	req->r_flags = CEPH_OSD_FLAG_WRITE;

	ceph_oloc_copy(&req->r_t.base_oloc, dst_oloc);
	ceph_oid_copy(&req->r_t.base_oid, dst_oid);

	ret = osd_req_op_copy_from_init(req, src_snapid, 0,
					src_oid, src_oloc,
					src_fadvise_flags,
					dst_fadvise_flags,
					truncate_seq,
					truncate_size,
					CEPH_OSD_COPY_FROM_FLAG_TRUNCATE_SEQ);
	if (ret)
		goto out;

	ret = ceph_osdc_alloc_messages(req, GFP_KERNEL);
	if (ret)
		goto out;

	return req;

out:
	ceph_osdc_put_request(req);
	return ERR_PTR(ret);
}

2288 2289 2290 2291 2292 2293 2294
static ssize_t ceph_do_objects_copy(struct ceph_inode_info *src_ci, u64 *src_off,
				    struct ceph_inode_info *dst_ci, u64 *dst_off,
				    struct ceph_fs_client *fsc,
				    size_t len, unsigned int flags)
{
	struct ceph_object_locator src_oloc, dst_oloc;
	struct ceph_object_id src_oid, dst_oid;
2295 2296
	struct ceph_osd_client *osdc;
	struct ceph_osd_request *req;
2297 2298 2299 2300 2301 2302 2303 2304 2305 2306
	size_t bytes = 0;
	u64 src_objnum, src_objoff, dst_objnum, dst_objoff;
	u32 src_objlen, dst_objlen;
	u32 object_size = src_ci->i_layout.object_size;
	int ret;

	src_oloc.pool = src_ci->i_layout.pool_id;
	src_oloc.pool_ns = ceph_try_get_string(src_ci->i_layout.pool_ns);
	dst_oloc.pool = dst_ci->i_layout.pool_id;
	dst_oloc.pool_ns = ceph_try_get_string(dst_ci->i_layout.pool_ns);
2307
	osdc = &fsc->client->osdc;
2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322

	while (len >= object_size) {
		ceph_calc_file_object_mapping(&src_ci->i_layout, *src_off,
					      object_size, &src_objnum,
					      &src_objoff, &src_objlen);
		ceph_calc_file_object_mapping(&dst_ci->i_layout, *dst_off,
					      object_size, &dst_objnum,
					      &dst_objoff, &dst_objlen);
		ceph_oid_init(&src_oid);
		ceph_oid_printf(&src_oid, "%llx.%08llx",
				src_ci->i_vino.ino, src_objnum);
		ceph_oid_init(&dst_oid);
		ceph_oid_printf(&dst_oid, "%llx.%08llx",
				dst_ci->i_vino.ino, dst_objnum);
		/* Do an object remote copy */
2323 2324 2325 2326 2327 2328 2329 2330 2331 2332
		req = ceph_alloc_copyfrom_request(osdc, src_ci->i_vino.snap,
						  &src_oid, &src_oloc,
						  &dst_oid, &dst_oloc,
						  dst_ci->i_truncate_seq,
						  dst_ci->i_truncate_size);
		if (IS_ERR(req))
			ret = PTR_ERR(req);
		else {
			ceph_osdc_start_request(osdc, req, false);
			ret = ceph_osdc_wait_request(osdc, req);
2333 2334 2335 2336
			ceph_update_copyfrom_metrics(&fsc->mdsc->metric,
						     req->r_start_latency,
						     req->r_end_latency,
						     object_size, ret);
2337 2338
			ceph_osdc_put_request(req);
		}
2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360
		if (ret) {
			if (ret == -EOPNOTSUPP) {
				fsc->have_copy_from2 = false;
				pr_notice("OSDs don't support copy-from2; disabling copy offload\n");
			}
			dout("ceph_osdc_copy_from returned %d\n", ret);
			if (!bytes)
				bytes = ret;
			goto out;
		}
		len -= object_size;
		bytes += object_size;
		*src_off += object_size;
		*dst_off += object_size;
	}

out:
	ceph_oloc_destroy(&src_oloc);
	ceph_oloc_destroy(&dst_oloc);
	return bytes;
}

2361 2362 2363
static ssize_t __ceph_copy_file_range(struct file *src_file, loff_t src_off,
				      struct file *dst_file, loff_t dst_off,
				      size_t len, unsigned int flags)
2364 2365 2366 2367 2368 2369
{
	struct inode *src_inode = file_inode(src_file);
	struct inode *dst_inode = file_inode(dst_file);
	struct ceph_inode_info *src_ci = ceph_inode(src_inode);
	struct ceph_inode_info *dst_ci = ceph_inode(dst_inode);
	struct ceph_cap_flush *prealloc_cf;
2370
	struct ceph_fs_client *src_fsc = ceph_inode_to_client(src_inode);
2371 2372
	loff_t size;
	ssize_t ret = -EIO, bytes;
2373
	u64 src_objnum, dst_objnum, src_objoff, dst_objoff;
2374
	u32 src_objlen, dst_objlen;
2375 2376
	int src_got = 0, dst_got = 0, err, dirty;

2377 2378 2379 2380 2381 2382 2383 2384 2385 2386
	if (src_inode->i_sb != dst_inode->i_sb) {
		struct ceph_fs_client *dst_fsc = ceph_inode_to_client(dst_inode);

		if (ceph_fsid_compare(&src_fsc->client->fsid,
				      &dst_fsc->client->fsid)) {
			dout("Copying files across clusters: src: %pU dst: %pU\n",
			     &src_fsc->client->fsid, &dst_fsc->client->fsid);
			return -EXDEV;
		}
	}
2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397
	if (ceph_snap(dst_inode) != CEPH_NOSNAP)
		return -EROFS;

	/*
	 * Some of the checks below will return -EOPNOTSUPP, which will force a
	 * fallback to the default VFS copy_file_range implementation.  This is
	 * desirable in several cases (for ex, the 'len' is smaller than the
	 * size of the objects, or in cases where that would be more
	 * efficient).
	 */

2398
	if (ceph_test_mount_opt(src_fsc, NOCOPYFROM))
2399 2400
		return -EOPNOTSUPP;

2401 2402 2403
	if (!src_fsc->have_copy_from2)
		return -EOPNOTSUPP;

2404 2405 2406 2407 2408
	/*
	 * Striped file layouts require that we copy partial objects, but the
	 * OSD copy-from operation only supports full-object copies.  Limit
	 * this to non-striped file layouts for now.
	 */
2409
	if ((src_ci->i_layout.stripe_unit != dst_ci->i_layout.stripe_unit) ||
2410 2411 2412 2413
	    (src_ci->i_layout.stripe_count != 1) ||
	    (dst_ci->i_layout.stripe_count != 1) ||
	    (src_ci->i_layout.object_size != dst_ci->i_layout.object_size)) {
		dout("Invalid src/dst files layout\n");
2414
		return -EOPNOTSUPP;
2415
	}
2416 2417 2418 2419 2420 2421 2422 2423

	if (len < src_ci->i_layout.object_size)
		return -EOPNOTSUPP; /* no remote copy will be done */

	prealloc_cf = ceph_alloc_cap_flush();
	if (!prealloc_cf)
		return -ENOMEM;

2424
	/* Start by sync'ing the source and destination files */
2425
	ret = file_write_and_wait_range(src_file, src_off, (src_off + len));
2426 2427 2428 2429 2430 2431 2432
	if (ret < 0) {
		dout("failed to write src file (%zd)\n", ret);
		goto out;
	}
	ret = file_write_and_wait_range(dst_file, dst_off, (dst_off + len));
	if (ret < 0) {
		dout("failed to write dst file (%zd)\n", ret);
2433
		goto out;
2434
	}
2435 2436 2437 2438 2439 2440

	/*
	 * We need FILE_WR caps for dst_ci and FILE_RD for src_ci as other
	 * clients may have dirty data in their caches.  And OSDs know nothing
	 * about caps, so they can't safely do the remote object copies.
	 */
Y
Yan, Zheng 已提交
2441 2442
	err = get_rd_wr_caps(src_file, &src_got,
			     dst_file, (dst_off + len), &dst_got);
2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453
	if (err < 0) {
		dout("get_rd_wr_caps returned %d\n", err);
		ret = -EOPNOTSUPP;
		goto out;
	}

	ret = is_file_size_ok(src_inode, dst_inode, src_off, dst_off, len);
	if (ret < 0)
		goto out_caps;

	/* Drop dst file cached pages */
2454
	ceph_fscache_invalidate(dst_inode, false);
2455 2456
	ret = invalidate_inode_pages2_range(dst_inode->i_mapping,
					    dst_off >> PAGE_SHIFT,
2457
					    (dst_off + len) >> PAGE_SHIFT);
2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479
	if (ret < 0) {
		dout("Failed to invalidate inode pages (%zd)\n", ret);
		ret = 0; /* XXX */
	}
	ceph_calc_file_object_mapping(&src_ci->i_layout, src_off,
				      src_ci->i_layout.object_size,
				      &src_objnum, &src_objoff, &src_objlen);
	ceph_calc_file_object_mapping(&dst_ci->i_layout, dst_off,
				      dst_ci->i_layout.object_size,
				      &dst_objnum, &dst_objoff, &dst_objlen);
	/* object-level offsets need to the same */
	if (src_objoff != dst_objoff) {
		ret = -EOPNOTSUPP;
		goto out_caps;
	}

	/*
	 * Do a manual copy if the object offset isn't object aligned.
	 * 'src_objlen' contains the bytes left until the end of the object,
	 * starting at the src_off
	 */
	if (src_objoff) {
2480 2481
		dout("Initial partial copy of %u bytes\n", src_objlen);

2482 2483 2484 2485 2486 2487 2488
		/*
		 * we need to temporarily drop all caps as we'll be calling
		 * {read,write}_iter, which will get caps again.
		 */
		put_rd_wr_caps(src_ci, src_got, dst_ci, dst_got);
		ret = do_splice_direct(src_file, &src_off, dst_file,
				       &dst_off, src_objlen, flags);
2489 2490 2491
		/* Abort on short copies or on error */
		if (ret < src_objlen) {
			dout("Failed partial copy (%zd)\n", ret);
2492 2493 2494
			goto out;
		}
		len -= ret;
Y
Yan, Zheng 已提交
2495 2496
		err = get_rd_wr_caps(src_file, &src_got,
				     dst_file, (dst_off + len), &dst_got);
2497 2498 2499 2500 2501 2502 2503 2504
		if (err < 0)
			goto out;
		err = is_file_size_ok(src_inode, dst_inode,
				      src_off, dst_off, len);
		if (err < 0)
			goto out_caps;
	}

2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515
	size = i_size_read(dst_inode);
	bytes = ceph_do_objects_copy(src_ci, &src_off, dst_ci, &dst_off,
				     src_fsc, len, flags);
	if (bytes <= 0) {
		if (!ret)
			ret = bytes;
		goto out_caps;
	}
	dout("Copied %zu bytes out of %zu\n", bytes, len);
	len -= bytes;
	ret += bytes;
2516 2517

	file_update_time(dst_file);
2518 2519
	inode_inc_iversion_raw(dst_inode);

2520
	if (dst_off > size) {
2521
		/* Let the MDS know about dst file size change */
2522 2523 2524
		if (ceph_inode_set_size(dst_inode, dst_off) ||
		    ceph_quota_is_max_bytes_approaching(dst_inode, dst_off))
			ceph_check_caps(dst_ci, CHECK_CAPS_AUTHONLY, NULL);
2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536
	}
	/* Mark Fw dirty */
	spin_lock(&dst_ci->i_ceph_lock);
	dst_ci->i_inline_version = CEPH_INLINE_NONE;
	dirty = __ceph_mark_dirty_caps(dst_ci, CEPH_CAP_FILE_WR, &prealloc_cf);
	spin_unlock(&dst_ci->i_ceph_lock);
	if (dirty)
		__mark_inode_dirty(dst_inode, dirty);

out_caps:
	put_rd_wr_caps(src_ci, src_got, dst_ci, dst_got);

2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548
	/*
	 * Do the final manual copy if we still have some bytes left, unless
	 * there were errors in remote object copies (len >= object_size).
	 */
	if (len && (len < src_ci->i_layout.object_size)) {
		dout("Final partial copy of %zu bytes\n", len);
		bytes = do_splice_direct(src_file, &src_off, dst_file,
					 &dst_off, len, flags);
		if (bytes > 0)
			ret += bytes;
		else
			dout("Failed partial copy (%zd)\n", bytes);
2549 2550 2551 2552 2553 2554 2555 2556
	}

out:
	ceph_free_cap_flush(prealloc_cf);

	return ret;
}

2557 2558 2559 2560 2561 2562 2563 2564 2565
static ssize_t ceph_copy_file_range(struct file *src_file, loff_t src_off,
				    struct file *dst_file, loff_t dst_off,
				    size_t len, unsigned int flags)
{
	ssize_t ret;

	ret = __ceph_copy_file_range(src_file, src_off, dst_file, dst_off,
				     len, flags);

2566
	if (ret == -EOPNOTSUPP || ret == -EXDEV)
2567 2568 2569 2570 2571
		ret = generic_copy_file_range(src_file, src_off, dst_file,
					      dst_off, len, flags);
	return ret;
}

S
Sage Weil 已提交
2572 2573 2574 2575
const struct file_operations ceph_file_fops = {
	.open = ceph_open,
	.release = ceph_release,
	.llseek = ceph_llseek,
A
Al Viro 已提交
2576
	.read_iter = ceph_read_iter,
A
Al Viro 已提交
2577
	.write_iter = ceph_write_iter,
S
Sage Weil 已提交
2578 2579
	.mmap = ceph_mmap,
	.fsync = ceph_fsync,
G
Greg Farnum 已提交
2580
	.lock = ceph_lock,
2581
	.setlease = simple_nosetlease,
G
Greg Farnum 已提交
2582
	.flock = ceph_flock,
2583
	.splice_read = generic_file_splice_read,
2584
	.splice_write = iter_file_splice_write,
S
Sage Weil 已提交
2585
	.unlocked_ioctl = ceph_ioctl,
2586
	.compat_ioctl = compat_ptr_ioctl,
L
Li Wang 已提交
2587
	.fallocate	= ceph_fallocate,
2588
	.copy_file_range = ceph_copy_file_range,
S
Sage Weil 已提交
2589
};