inode.c 291.2 KB
Newer Older
1
// SPDX-License-Identifier: GPL-2.0
C
Chris Mason 已提交
2 3 4 5
/*
 * Copyright (C) 2007 Oracle.  All rights reserved.
 */

6
#include <linux/kernel.h>
7
#include <linux/bio.h>
C
Chris Mason 已提交
8
#include <linux/buffer_head.h>
S
Sage Weil 已提交
9
#include <linux/file.h>
C
Chris Mason 已提交
10 11 12 13 14 15 16 17 18 19 20
#include <linux/fs.h>
#include <linux/pagemap.h>
#include <linux/highmem.h>
#include <linux/time.h>
#include <linux/init.h>
#include <linux/string.h>
#include <linux/backing-dev.h>
#include <linux/mpage.h>
#include <linux/swap.h>
#include <linux/writeback.h>
#include <linux/compat.h>
C
Chris Mason 已提交
21
#include <linux/bit_spinlock.h>
J
Josef Bacik 已提交
22
#include <linux/xattr.h>
J
Josef Bacik 已提交
23
#include <linux/posix_acl.h>
Y
Yan Zheng 已提交
24
#include <linux/falloc.h>
25
#include <linux/slab.h>
26
#include <linux/ratelimit.h>
27
#include <linux/mount.h>
28
#include <linux/btrfs.h>
D
David Woodhouse 已提交
29
#include <linux/blkdev.h>
30
#include <linux/posix_acl_xattr.h>
31
#include <linux/uio.h>
32
#include <linux/magic.h>
33
#include <linux/iversion.h>
34
#include <asm/unaligned.h>
C
Chris Mason 已提交
35 36 37 38 39
#include "ctree.h"
#include "disk-io.h"
#include "transaction.h"
#include "btrfs_inode.h"
#include "print-tree.h"
40
#include "ordered-data.h"
41
#include "xattr.h"
42
#include "tree-log.h"
43
#include "volumes.h"
C
Chris Mason 已提交
44
#include "compression.h"
45
#include "locking.h"
46
#include "free-space-cache.h"
47
#include "inode-map.h"
L
Liu Bo 已提交
48
#include "backref.h"
49
#include "props.h"
50
#include "qgroup.h"
51
#include "dedupe.h"
C
Chris Mason 已提交
52 53

struct btrfs_iget_args {
54
	struct btrfs_key *location;
C
Chris Mason 已提交
55 56 57
	struct btrfs_root *root;
};

58 59 60 61
struct btrfs_dio_data {
	u64 reserve;
	u64 unsubmitted_oe_range_start;
	u64 unsubmitted_oe_range_end;
62
	int overwrite;
63 64
};

65 66 67 68 69
static const struct inode_operations btrfs_dir_inode_operations;
static const struct inode_operations btrfs_symlink_inode_operations;
static const struct inode_operations btrfs_dir_ro_inode_operations;
static const struct inode_operations btrfs_special_inode_operations;
static const struct inode_operations btrfs_file_inode_operations;
70 71
static const struct address_space_operations btrfs_aops;
static const struct address_space_operations btrfs_symlink_aops;
72
static const struct file_operations btrfs_dir_file_operations;
73
static const struct extent_io_ops btrfs_extent_io_ops;
C
Chris Mason 已提交
74 75 76 77

static struct kmem_cache *btrfs_inode_cachep;
struct kmem_cache *btrfs_trans_handle_cachep;
struct kmem_cache *btrfs_path_cachep;
78
struct kmem_cache *btrfs_free_space_cachep;
C
Chris Mason 已提交
79 80

#define S_SHIFT 12
D
David Sterba 已提交
81
static const unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
C
Chris Mason 已提交
82 83 84 85 86 87 88 89 90
	[S_IFREG >> S_SHIFT]	= BTRFS_FT_REG_FILE,
	[S_IFDIR >> S_SHIFT]	= BTRFS_FT_DIR,
	[S_IFCHR >> S_SHIFT]	= BTRFS_FT_CHRDEV,
	[S_IFBLK >> S_SHIFT]	= BTRFS_FT_BLKDEV,
	[S_IFIFO >> S_SHIFT]	= BTRFS_FT_FIFO,
	[S_IFSOCK >> S_SHIFT]	= BTRFS_FT_SOCK,
	[S_IFLNK >> S_SHIFT]	= BTRFS_FT_SYMLINK,
};

91
static int btrfs_setsize(struct inode *inode, struct iattr *attr);
92
static int btrfs_truncate(struct inode *inode, bool skip_writeback);
93
static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
94 95
static noinline int cow_file_range(struct inode *inode,
				   struct page *locked_page,
96 97 98
				   u64 start, u64 end, u64 delalloc_end,
				   int *page_started, unsigned long *nr_written,
				   int unlock, struct btrfs_dedupe_hash *hash);
99 100 101 102 103
static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
				       u64 orig_start, u64 block_start,
				       u64 block_len, u64 orig_block_len,
				       u64 ram_bytes, int compress_type,
				       int type);
104

105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
static void __endio_write_update_ordered(struct inode *inode,
					 const u64 offset, const u64 bytes,
					 const bool uptodate);

/*
 * Cleanup all submitted ordered extents in specified range to handle errors
 * from the fill_dellaloc() callback.
 *
 * NOTE: caller must ensure that when an error happens, it can not call
 * extent_clear_unlock_delalloc() to clear both the bits EXTENT_DO_ACCOUNTING
 * and EXTENT_DELALLOC simultaneously, because that causes the reserved metadata
 * to be released, which we want to happen only when finishing the ordered
 * extent (btrfs_finish_ordered_io()). Also note that the caller of the
 * fill_delalloc() callback already does proper cleanup for the first page of
 * the range, that is, it invokes the callback writepage_end_io_hook() for the
 * range of the first page.
 */
static inline void btrfs_cleanup_ordered_extents(struct inode *inode,
						 const u64 offset,
						 const u64 bytes)
{
126 127 128 129 130 131 132 133 134 135 136 137
	unsigned long index = offset >> PAGE_SHIFT;
	unsigned long end_index = (offset + bytes - 1) >> PAGE_SHIFT;
	struct page *page;

	while (index <= end_index) {
		page = find_get_page(inode->i_mapping, index);
		index++;
		if (!page)
			continue;
		ClearPagePrivate2(page);
		put_page(page);
	}
138 139 140 141
	return __endio_write_update_ordered(inode, offset + PAGE_SIZE,
					    bytes - PAGE_SIZE, false);
}

142
static int btrfs_dirty_inode(struct inode *inode);
143

144 145 146 147 148 149 150
#ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
void btrfs_test_inode_set_ops(struct inode *inode)
{
	BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
}
#endif

151
static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
152 153
				     struct inode *inode,  struct inode *dir,
				     const struct qstr *qstr)
J
Jim Owens 已提交
154 155 156
{
	int err;

157
	err = btrfs_init_acl(trans, inode, dir);
J
Jim Owens 已提交
158
	if (!err)
159
		err = btrfs_xattr_security_init(trans, inode, dir, qstr);
J
Jim Owens 已提交
160 161 162
	return err;
}

C
Chris Mason 已提交
163 164 165 166 167
/*
 * this does all the hard work for inserting an inline extent into
 * the btree.  The caller should have done a btrfs_drop_extents so that
 * no overlapping inline items exist in the btree
 */
168
static int insert_inline_extent(struct btrfs_trans_handle *trans,
169
				struct btrfs_path *path, int extent_inserted,
C
Chris Mason 已提交
170 171
				struct btrfs_root *root, struct inode *inode,
				u64 start, size_t size, size_t compressed_size,
172
				int compress_type,
C
Chris Mason 已提交
173 174 175 176 177 178 179 180 181 182 183
				struct page **compressed_pages)
{
	struct extent_buffer *leaf;
	struct page *page = NULL;
	char *kaddr;
	unsigned long ptr;
	struct btrfs_file_extent_item *ei;
	int ret;
	size_t cur_size = size;
	unsigned long offset;

184
	if (compressed_size && compressed_pages)
C
Chris Mason 已提交
185 186
		cur_size = compressed_size;

187
	inode_add_bytes(inode, size);
C
Chris Mason 已提交
188

189 190 191
	if (!extent_inserted) {
		struct btrfs_key key;
		size_t datasize;
C
Chris Mason 已提交
192

193
		key.objectid = btrfs_ino(BTRFS_I(inode));
194
		key.offset = start;
195
		key.type = BTRFS_EXTENT_DATA_KEY;
C
Chris Mason 已提交
196

197 198 199 200
		datasize = btrfs_file_extent_calc_inline_size(cur_size);
		path->leave_spinning = 1;
		ret = btrfs_insert_empty_item(trans, root, path, &key,
					      datasize);
201
		if (ret)
202
			goto fail;
C
Chris Mason 已提交
203 204 205 206 207 208 209 210 211 212 213
	}
	leaf = path->nodes[0];
	ei = btrfs_item_ptr(leaf, path->slots[0],
			    struct btrfs_file_extent_item);
	btrfs_set_file_extent_generation(leaf, ei, trans->transid);
	btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
	btrfs_set_file_extent_encryption(leaf, ei, 0);
	btrfs_set_file_extent_other_encoding(leaf, ei, 0);
	btrfs_set_file_extent_ram_bytes(leaf, ei, size);
	ptr = btrfs_file_extent_inline_start(ei);

214
	if (compress_type != BTRFS_COMPRESS_NONE) {
C
Chris Mason 已提交
215 216
		struct page *cpage;
		int i = 0;
C
Chris Mason 已提交
217
		while (compressed_size > 0) {
C
Chris Mason 已提交
218
			cpage = compressed_pages[i];
219
			cur_size = min_t(unsigned long, compressed_size,
220
				       PAGE_SIZE);
C
Chris Mason 已提交
221

222
			kaddr = kmap_atomic(cpage);
C
Chris Mason 已提交
223
			write_extent_buffer(leaf, kaddr, ptr, cur_size);
224
			kunmap_atomic(kaddr);
C
Chris Mason 已提交
225 226 227 228 229 230

			i++;
			ptr += cur_size;
			compressed_size -= cur_size;
		}
		btrfs_set_file_extent_compression(leaf, ei,
231
						  compress_type);
C
Chris Mason 已提交
232 233
	} else {
		page = find_get_page(inode->i_mapping,
234
				     start >> PAGE_SHIFT);
C
Chris Mason 已提交
235
		btrfs_set_file_extent_compression(leaf, ei, 0);
236
		kaddr = kmap_atomic(page);
237
		offset = start & (PAGE_SIZE - 1);
C
Chris Mason 已提交
238
		write_extent_buffer(leaf, kaddr + offset, ptr, size);
239
		kunmap_atomic(kaddr);
240
		put_page(page);
C
Chris Mason 已提交
241 242
	}
	btrfs_mark_buffer_dirty(leaf);
243
	btrfs_release_path(path);
C
Chris Mason 已提交
244

245 246 247 248 249 250 251 252 253
	/*
	 * we're an inline extent, so nobody can
	 * extend the file past i_size without locking
	 * a page we already have locked.
	 *
	 * We must do any isize and inode updates
	 * before we unlock the pages.  Otherwise we
	 * could end up racing with unlink.
	 */
C
Chris Mason 已提交
254
	BTRFS_I(inode)->disk_i_size = inode->i_size;
255
	ret = btrfs_update_inode(trans, root, inode);
256

C
Chris Mason 已提交
257
fail:
258
	return ret;
C
Chris Mason 已提交
259 260 261 262 263 264 265 266
}


/*
 * conditionally insert an inline extent into the file.  This
 * does the checks required to make sure the data is small enough
 * to fit as an inline extent.
 */
267
static noinline int cow_file_range_inline(struct inode *inode, u64 start,
268 269 270
					  u64 end, size_t compressed_size,
					  int compress_type,
					  struct page **compressed_pages)
C
Chris Mason 已提交
271
{
272
	struct btrfs_root *root = BTRFS_I(inode)->root;
273
	struct btrfs_fs_info *fs_info = root->fs_info;
274
	struct btrfs_trans_handle *trans;
C
Chris Mason 已提交
275 276 277
	u64 isize = i_size_read(inode);
	u64 actual_end = min(end + 1, isize);
	u64 inline_len = actual_end - start;
278
	u64 aligned_end = ALIGN(end, fs_info->sectorsize);
C
Chris Mason 已提交
279 280
	u64 data_len = inline_len;
	int ret;
281 282 283
	struct btrfs_path *path;
	int extent_inserted = 0;
	u32 extent_item_size;
C
Chris Mason 已提交
284 285 286 287 288

	if (compressed_size)
		data_len = compressed_size;

	if (start > 0 ||
289 290
	    actual_end > fs_info->sectorsize ||
	    data_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
C
Chris Mason 已提交
291
	    (!compressed_size &&
292
	    (actual_end & (fs_info->sectorsize - 1)) == 0) ||
C
Chris Mason 已提交
293
	    end + 1 < isize ||
294
	    data_len > fs_info->max_inline) {
C
Chris Mason 已提交
295 296 297
		return 1;
	}

298 299 300 301
	path = btrfs_alloc_path();
	if (!path)
		return -ENOMEM;

302
	trans = btrfs_join_transaction(root);
303 304
	if (IS_ERR(trans)) {
		btrfs_free_path(path);
305
		return PTR_ERR(trans);
306
	}
307
	trans->block_rsv = &BTRFS_I(inode)->block_rsv;
308

309 310 311 312 313 314 315 316 317 318
	if (compressed_size && compressed_pages)
		extent_item_size = btrfs_file_extent_calc_inline_size(
		   compressed_size);
	else
		extent_item_size = btrfs_file_extent_calc_inline_size(
		    inline_len);

	ret = __btrfs_drop_extents(trans, root, inode, path,
				   start, aligned_end, NULL,
				   1, 1, extent_item_size, &extent_inserted);
319
	if (ret) {
320
		btrfs_abort_transaction(trans, ret);
321 322
		goto out;
	}
C
Chris Mason 已提交
323 324 325

	if (isize > actual_end)
		inline_len = min_t(u64, isize, actual_end);
326 327
	ret = insert_inline_extent(trans, path, extent_inserted,
				   root, inode, start,
C
Chris Mason 已提交
328
				   inline_len, compressed_size,
329
				   compress_type, compressed_pages);
330
	if (ret && ret != -ENOSPC) {
331
		btrfs_abort_transaction(trans, ret);
332
		goto out;
333
	} else if (ret == -ENOSPC) {
334 335
		ret = 1;
		goto out;
336
	}
337

338
	set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
339
	btrfs_drop_extent_cache(BTRFS_I(inode), start, aligned_end - 1, 0);
340
out:
341 342 343 344 345 346
	/*
	 * Don't forget to free the reserved space, as for inlined extent
	 * it won't count as data extent, free them directly here.
	 * And at reserve time, it's always aligned to page size, so
	 * just free one page here.
	 */
347
	btrfs_qgroup_free_data(inode, NULL, 0, PAGE_SIZE);
348
	btrfs_free_path(path);
349
	btrfs_end_transaction(trans);
350
	return ret;
C
Chris Mason 已提交
351 352
}

353 354 355 356 357 358
struct async_extent {
	u64 start;
	u64 ram_size;
	u64 compressed_size;
	struct page **pages;
	unsigned long nr_pages;
359
	int compress_type;
360 361 362 363 364 365 366 367 368
	struct list_head list;
};

struct async_cow {
	struct inode *inode;
	struct btrfs_root *root;
	struct page *locked_page;
	u64 start;
	u64 end;
369
	unsigned int write_flags;
370 371 372 373 374 375 376 377
	struct list_head extents;
	struct btrfs_work work;
};

static noinline int add_async_extent(struct async_cow *cow,
				     u64 start, u64 ram_size,
				     u64 compressed_size,
				     struct page **pages,
378 379
				     unsigned long nr_pages,
				     int compress_type)
380 381 382 383
{
	struct async_extent *async_extent;

	async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
384
	BUG_ON(!async_extent); /* -ENOMEM */
385 386 387 388 389
	async_extent->start = start;
	async_extent->ram_size = ram_size;
	async_extent->compressed_size = compressed_size;
	async_extent->pages = pages;
	async_extent->nr_pages = nr_pages;
390
	async_extent->compress_type = compress_type;
391 392 393 394
	list_add_tail(&async_extent->list, &cow->extents);
	return 0;
}

395
static inline int inode_need_compress(struct inode *inode, u64 start, u64 end)
396
{
397
	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
398 399

	/* force compress */
400
	if (btrfs_test_opt(fs_info, FORCE_COMPRESS))
401
		return 1;
402 403 404
	/* defrag ioctl */
	if (BTRFS_I(inode)->defrag_compress)
		return 1;
405 406 407
	/* bad compression ratios */
	if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
		return 0;
408
	if (btrfs_test_opt(fs_info, COMPRESS) ||
409
	    BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS ||
410
	    BTRFS_I(inode)->prop_compress)
411
		return btrfs_compress_heuristic(inode, start, end);
412 413 414
	return 0;
}

415
static inline void inode_should_defrag(struct btrfs_inode *inode,
416 417 418 419
		u64 start, u64 end, u64 num_bytes, u64 small_write)
{
	/* If this is a small write inside eof, kick off a defrag */
	if (num_bytes < small_write &&
420
	    (start > 0 || end + 1 < inode->disk_i_size))
421 422 423
		btrfs_add_inode_defrag(NULL, inode);
}

C
Chris Mason 已提交
424
/*
425 426 427
 * we create compressed extents in two phases.  The first
 * phase compresses a range of pages that have already been
 * locked (both pages and state bits are locked).
C
Chris Mason 已提交
428
 *
429 430 431 432 433
 * This is done inside an ordered work queue, and the compression
 * is spread across many cpus.  The actual IO submission is step
 * two, and the ordered work queue takes care of making sure that
 * happens in the same order things were put onto the queue by
 * writepages and friends.
C
Chris Mason 已提交
434
 *
435 436 437
 * If this code finds it can't get good compression, it puts an
 * entry onto the work queue to write the uncompressed bytes.  This
 * makes sure that both compressed inodes and uncompressed inodes
438 439
 * are written in the same order that the flusher thread sent them
 * down.
C
Chris Mason 已提交
440
 */
441
static noinline void compress_file_range(struct inode *inode,
442 443 444 445
					struct page *locked_page,
					u64 start, u64 end,
					struct async_cow *async_cow,
					int *num_added)
446
{
447 448
	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
	u64 blocksize = fs_info->sectorsize;
C
Chris Mason 已提交
449
	u64 actual_end;
450
	u64 isize = i_size_read(inode);
451
	int ret = 0;
C
Chris Mason 已提交
452 453 454 455 456 457
	struct page **pages = NULL;
	unsigned long nr_pages;
	unsigned long total_compressed = 0;
	unsigned long total_in = 0;
	int i;
	int will_compress;
458
	int compress_type = fs_info->compress_type;
459
	int redirty = 0;
460

461 462
	inode_should_defrag(BTRFS_I(inode), start, end, end - start + 1,
			SZ_16K);
C
Chris Mason 已提交
463

464
	actual_end = min_t(u64, isize, end + 1);
C
Chris Mason 已提交
465 466
again:
	will_compress = 0;
467
	nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
468 469 470
	BUILD_BUG_ON((BTRFS_MAX_COMPRESSED % PAGE_SIZE) != 0);
	nr_pages = min_t(unsigned long, nr_pages,
			BTRFS_MAX_COMPRESSED / PAGE_SIZE);
471

472 473 474 475 476 477 478 479 480 481 482 483 484
	/*
	 * we don't want to send crud past the end of i_size through
	 * compression, that's just a waste of CPU time.  So, if the
	 * end of the file is before the start of our current
	 * requested range of bytes, we bail out to the uncompressed
	 * cleanup code that can deal with all of this.
	 *
	 * It isn't really the fastest way to fix things, but this is a
	 * very uncommon corner.
	 */
	if (actual_end <= start)
		goto cleanup_and_bail_uncompressed;

C
Chris Mason 已提交
485 486
	total_compressed = actual_end - start;

487 488
	/*
	 * skip compression for a small file range(<=blocksize) that
489
	 * isn't an inline extent, since it doesn't save disk space at all.
490 491 492 493 494
	 */
	if (total_compressed <= blocksize &&
	   (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
		goto cleanup_and_bail_uncompressed;

495 496
	total_compressed = min_t(unsigned long, total_compressed,
			BTRFS_MAX_UNCOMPRESSED);
C
Chris Mason 已提交
497 498
	total_in = 0;
	ret = 0;
499

500 501 502 503
	/*
	 * we do compression for mount -o compress and when the
	 * inode has not been flagged as nocompress.  This flag can
	 * change at any time if we discover bad compression ratios.
C
Chris Mason 已提交
504
	 */
505
	if (inode_need_compress(inode, start, end)) {
C
Chris Mason 已提交
506
		WARN_ON(pages);
507
		pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
508 509 510 511
		if (!pages) {
			/* just bail out to the uncompressed code */
			goto cont;
		}
C
Chris Mason 已提交
512

513 514 515
		if (BTRFS_I(inode)->defrag_compress)
			compress_type = BTRFS_I(inode)->defrag_compress;
		else if (BTRFS_I(inode)->prop_compress)
516
			compress_type = BTRFS_I(inode)->prop_compress;
517

518 519 520 521 522 523 524 525
		/*
		 * we need to call clear_page_dirty_for_io on each
		 * page in the range.  Otherwise applications with the file
		 * mmap'd can wander in and change the page contents while
		 * we are compressing them.
		 *
		 * If the compression fails for any reason, we set the pages
		 * dirty again later on.
526 527 528
		 *
		 * Note that the remaining part is redirtied, the start pointer
		 * has moved, the end is the original one.
529
		 */
530 531 532 533
		if (!redirty) {
			extent_range_clear_dirty_for_io(inode, start, end);
			redirty = 1;
		}
534 535 536 537

		/* Compression level is applied here and only here */
		ret = btrfs_compress_pages(
			compress_type | (fs_info->compress_level << 4),
538
					   inode->i_mapping, start,
539
					   pages,
540
					   &nr_pages,
541
					   &total_in,
542
					   &total_compressed);
C
Chris Mason 已提交
543 544 545

		if (!ret) {
			unsigned long offset = total_compressed &
546
				(PAGE_SIZE - 1);
547
			struct page *page = pages[nr_pages - 1];
C
Chris Mason 已提交
548 549 550 551 552 553
			char *kaddr;

			/* zero the tail end of the last page, we might be
			 * sending it down to disk
			 */
			if (offset) {
554
				kaddr = kmap_atomic(page);
C
Chris Mason 已提交
555
				memset(kaddr + offset, 0,
556
				       PAGE_SIZE - offset);
557
				kunmap_atomic(kaddr);
C
Chris Mason 已提交
558 559 560 561
			}
			will_compress = 1;
		}
	}
562
cont:
C
Chris Mason 已提交
563 564
	if (start == 0) {
		/* lets try to make an inline extent */
565
		if (ret || total_in < actual_end) {
C
Chris Mason 已提交
566
			/* we didn't compress the entire range, try
567
			 * to make an uncompressed inline extent.
C
Chris Mason 已提交
568
			 */
569 570
			ret = cow_file_range_inline(inode, start, end, 0,
						    BTRFS_COMPRESS_NONE, NULL);
C
Chris Mason 已提交
571
		} else {
572
			/* try making a compressed inline extent */
573
			ret = cow_file_range_inline(inode, start, end,
574 575
						    total_compressed,
						    compress_type, pages);
C
Chris Mason 已提交
576
		}
577
		if (ret <= 0) {
578
			unsigned long clear_flags = EXTENT_DELALLOC |
J
Josef Bacik 已提交
579 580
				EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
				EXTENT_DO_ACCOUNTING;
581 582 583
			unsigned long page_error_op;

			page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
584

585
			/*
586 587 588
			 * inline extent creation worked or returned error,
			 * we don't need to create any more async work items.
			 * Unlock and free up our temp pages.
J
Josef Bacik 已提交
589 590 591 592 593
			 *
			 * We use DO_ACCOUNTING here because we need the
			 * delalloc_release_metadata to be done _after_ we drop
			 * our outstanding extent for clearing delalloc for this
			 * range.
594
			 */
595 596 597
			extent_clear_unlock_delalloc(inode, start, end, end,
						     NULL, clear_flags,
						     PAGE_UNLOCK |
598 599
						     PAGE_CLEAR_DIRTY |
						     PAGE_SET_WRITEBACK |
600
						     page_error_op |
601
						     PAGE_END_WRITEBACK);
C
Chris Mason 已提交
602 603 604 605 606 607 608 609 610 611
			goto free_pages_out;
		}
	}

	if (will_compress) {
		/*
		 * we aren't doing an inline extent round the compressed size
		 * up to a block size boundary so the allocator does sane
		 * things
		 */
612
		total_compressed = ALIGN(total_compressed, blocksize);
C
Chris Mason 已提交
613 614 615

		/*
		 * one last check to make sure the compression is really a
616 617
		 * win, compare the page count read with the blocks on disk,
		 * compression must free at least one sector size
C
Chris Mason 已提交
618
		 */
619
		total_in = ALIGN(total_in, PAGE_SIZE);
620
		if (total_compressed + blocksize <= total_in) {
621 622 623 624 625 626 627
			*num_added += 1;

			/*
			 * The async work queues will take care of doing actual
			 * allocation on disk for these compressed pages, and
			 * will submit them to the elevator.
			 */
628
			add_async_extent(async_cow, start, total_in,
629
					total_compressed, pages, nr_pages,
630 631
					compress_type);

632 633
			if (start + total_in < end) {
				start += total_in;
634 635 636 637 638
				pages = NULL;
				cond_resched();
				goto again;
			}
			return;
C
Chris Mason 已提交
639 640
		}
	}
641
	if (pages) {
C
Chris Mason 已提交
642 643 644 645
		/*
		 * the compression code ran but failed to make things smaller,
		 * free any pages it allocated and our page pointer array
		 */
646
		for (i = 0; i < nr_pages; i++) {
C
Chris Mason 已提交
647
			WARN_ON(pages[i]->mapping);
648
			put_page(pages[i]);
C
Chris Mason 已提交
649 650 651 652
		}
		kfree(pages);
		pages = NULL;
		total_compressed = 0;
653
		nr_pages = 0;
C
Chris Mason 已提交
654 655

		/* flag the file so we don't compress in the future */
656
		if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) &&
657
		    !(BTRFS_I(inode)->prop_compress)) {
C
Chris Mason 已提交
658
			BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
C
Chris Mason 已提交
659
		}
C
Chris Mason 已提交
660
	}
661
cleanup_and_bail_uncompressed:
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677
	/*
	 * No compression, but we still need to write the pages in the file
	 * we've been given so far.  redirty the locked page if it corresponds
	 * to our extent and set things up for the async work queue to run
	 * cow_file_range to do the normal delalloc dance.
	 */
	if (page_offset(locked_page) >= start &&
	    page_offset(locked_page) <= end)
		__set_page_dirty_nobuffers(locked_page);
		/* unlocked later on in the async handlers */

	if (redirty)
		extent_range_redirty_for_io(inode, start, end);
	add_async_extent(async_cow, start, end - start + 1, 0, NULL, 0,
			 BTRFS_COMPRESS_NONE);
	*num_added += 1;
678

679
	return;
680 681

free_pages_out:
682
	for (i = 0; i < nr_pages; i++) {
683
		WARN_ON(pages[i]->mapping);
684
		put_page(pages[i]);
685
	}
C
Chris Mason 已提交
686
	kfree(pages);
687 688
}

689 690 691 692 693 694 695 696 697
static void free_async_extent_pages(struct async_extent *async_extent)
{
	int i;

	if (!async_extent->pages)
		return;

	for (i = 0; i < async_extent->nr_pages; i++) {
		WARN_ON(async_extent->pages[i]->mapping);
698
		put_page(async_extent->pages[i]);
699 700 701 702
	}
	kfree(async_extent->pages);
	async_extent->nr_pages = 0;
	async_extent->pages = NULL;
703 704 705 706 707 708 709 710
}

/*
 * phase two of compressed writeback.  This is the ordered portion
 * of the code, which only gets called in the order the work was
 * queued.  We walk all the async extents created by compress_file_range
 * and send them down to the disk.
 */
711
static noinline void submit_compressed_extents(struct inode *inode,
712 713
					      struct async_cow *async_cow)
{
714
	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
715 716 717 718 719 720
	struct async_extent *async_extent;
	u64 alloc_hint = 0;
	struct btrfs_key ins;
	struct extent_map *em;
	struct btrfs_root *root = BTRFS_I(inode)->root;
	struct extent_io_tree *io_tree;
721
	int ret = 0;
722

723
again:
C
Chris Mason 已提交
724
	while (!list_empty(&async_cow->extents)) {
725 726 727
		async_extent = list_entry(async_cow->extents.next,
					  struct async_extent, list);
		list_del(&async_extent->list);
C
Chris Mason 已提交
728

729 730
		io_tree = &BTRFS_I(inode)->io_tree;

731
retry:
732 733 734 735 736 737
		/* did the compression code fall back to uncompressed IO? */
		if (!async_extent->pages) {
			int page_started = 0;
			unsigned long nr_written = 0;

			lock_extent(io_tree, async_extent->start,
738
					 async_extent->start +
739
					 async_extent->ram_size - 1);
740 741

			/* allocate blocks */
742 743 744 745
			ret = cow_file_range(inode, async_cow->locked_page,
					     async_extent->start,
					     async_extent->start +
					     async_extent->ram_size - 1,
746 747 748 749
					     async_extent->start +
					     async_extent->ram_size - 1,
					     &page_started, &nr_written, 0,
					     NULL);
750

751 752
			/* JDM XXX */

753 754 755 756 757 758
			/*
			 * if page_started, cow_file_range inserted an
			 * inline extent and took care of all the unlocking
			 * and IO for us.  Otherwise, we need to submit
			 * all those pages down to the drive.
			 */
759
			if (!page_started && !ret)
760 761
				extent_write_locked_range(inode,
						  async_extent->start,
C
Chris Mason 已提交
762
						  async_extent->start +
763 764
						  async_extent->ram_size - 1,
						  WB_SYNC_ALL);
765 766
			else if (ret)
				unlock_page(async_cow->locked_page);
767 768 769 770 771 772
			kfree(async_extent);
			cond_resched();
			continue;
		}

		lock_extent(io_tree, async_extent->start,
773
			    async_extent->start + async_extent->ram_size - 1);
774

775
		ret = btrfs_reserve_extent(root, async_extent->ram_size,
776 777
					   async_extent->compressed_size,
					   async_extent->compressed_size,
778
					   0, alloc_hint, &ins, 1, 1);
779
		if (ret) {
780
			free_async_extent_pages(async_extent);
781

782 783 784 785
			if (ret == -ENOSPC) {
				unlock_extent(io_tree, async_extent->start,
					      async_extent->start +
					      async_extent->ram_size - 1);
786 787 788 789 790 791 792 793 794 795 796 797

				/*
				 * we need to redirty the pages if we decide to
				 * fallback to uncompressed IO, otherwise we
				 * will not submit these pages down to lower
				 * layers.
				 */
				extent_range_redirty_for_io(inode,
						async_extent->start,
						async_extent->start +
						async_extent->ram_size - 1);

798
				goto retry;
799
			}
800
			goto out_free;
801
		}
802 803 804 805
		/*
		 * here we're doing allocation and writeback of the
		 * compressed pages
		 */
806 807 808 809 810 811 812 813 814 815 816
		em = create_io_em(inode, async_extent->start,
				  async_extent->ram_size, /* len */
				  async_extent->start, /* orig_start */
				  ins.objectid, /* block_start */
				  ins.offset, /* block_len */
				  ins.offset, /* orig_block_len */
				  async_extent->ram_size, /* ram_bytes */
				  async_extent->compress_type,
				  BTRFS_ORDERED_COMPRESSED);
		if (IS_ERR(em))
			/* ret value is not necessary due to void function */
817
			goto out_free_reserve;
818
		free_extent_map(em);
819

820 821 822 823 824 825 826
		ret = btrfs_add_ordered_extent_compress(inode,
						async_extent->start,
						ins.objectid,
						async_extent->ram_size,
						ins.offset,
						BTRFS_ORDERED_COMPRESSED,
						async_extent->compress_type);
827
		if (ret) {
828 829
			btrfs_drop_extent_cache(BTRFS_I(inode),
						async_extent->start,
830 831
						async_extent->start +
						async_extent->ram_size - 1, 0);
832
			goto out_free_reserve;
833
		}
834
		btrfs_dec_block_group_reservations(fs_info, ins.objectid);
835 836 837 838

		/*
		 * clear dirty, set writeback and unlock the pages.
		 */
839
		extent_clear_unlock_delalloc(inode, async_extent->start,
840 841
				async_extent->start +
				async_extent->ram_size - 1,
842 843
				async_extent->start +
				async_extent->ram_size - 1,
844 845
				NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
				PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
846
				PAGE_SET_WRITEBACK);
847
		if (btrfs_submit_compressed_write(inode,
C
Chris Mason 已提交
848 849 850 851
				    async_extent->start,
				    async_extent->ram_size,
				    ins.objectid,
				    ins.offset, async_extent->pages,
852 853
				    async_extent->nr_pages,
				    async_cow->write_flags)) {
854 855 856 857 858 859 860 861 862
			struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
			struct page *p = async_extent->pages[0];
			const u64 start = async_extent->start;
			const u64 end = start + async_extent->ram_size - 1;

			p->mapping = inode->i_mapping;
			tree->ops->writepage_end_io_hook(p, start, end,
							 NULL, 0);
			p->mapping = NULL;
863 864
			extent_clear_unlock_delalloc(inode, start, end, end,
						     NULL, 0,
865 866
						     PAGE_END_WRITEBACK |
						     PAGE_SET_ERROR);
867
			free_async_extent_pages(async_extent);
868
		}
869 870 871 872
		alloc_hint = ins.objectid + ins.offset;
		kfree(async_extent);
		cond_resched();
	}
873
	return;
874
out_free_reserve:
875
	btrfs_dec_block_group_reservations(fs_info, ins.objectid);
876
	btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
877
out_free:
878
	extent_clear_unlock_delalloc(inode, async_extent->start,
879 880
				     async_extent->start +
				     async_extent->ram_size - 1,
881 882
				     async_extent->start +
				     async_extent->ram_size - 1,
883
				     NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
884
				     EXTENT_DELALLOC_NEW |
885 886
				     EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
				     PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
887 888
				     PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
				     PAGE_SET_ERROR);
889
	free_async_extent_pages(async_extent);
890
	kfree(async_extent);
891
	goto again;
892 893
}

894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925
static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
				      u64 num_bytes)
{
	struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
	struct extent_map *em;
	u64 alloc_hint = 0;

	read_lock(&em_tree->lock);
	em = search_extent_mapping(em_tree, start, num_bytes);
	if (em) {
		/*
		 * if block start isn't an actual block number then find the
		 * first block in this inode and use that as a hint.  If that
		 * block is also bogus then just don't worry about it.
		 */
		if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
			free_extent_map(em);
			em = search_extent_mapping(em_tree, 0, 0);
			if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
				alloc_hint = em->block_start;
			if (em)
				free_extent_map(em);
		} else {
			alloc_hint = em->block_start;
			free_extent_map(em);
		}
	}
	read_unlock(&em_tree->lock);

	return alloc_hint;
}

926 927 928 929 930 931 932 933 934 935 936 937 938
/*
 * when extent_io.c finds a delayed allocation range in the file,
 * the call backs end up in this code.  The basic idea is to
 * allocate extents on disk for the range, and create ordered data structs
 * in ram to track those extents.
 *
 * locked_page is the page that writepage had locked already.  We use
 * it to make sure we don't do extra locks or unlocks.
 *
 * *page_started is set to one if we unlock locked_page and do everything
 * required to start IO on it.  It may be clean and already done with
 * IO when we return.
 */
939 940
static noinline int cow_file_range(struct inode *inode,
				   struct page *locked_page,
941 942 943
				   u64 start, u64 end, u64 delalloc_end,
				   int *page_started, unsigned long *nr_written,
				   int unlock, struct btrfs_dedupe_hash *hash)
944
{
945
	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
946
	struct btrfs_root *root = BTRFS_I(inode)->root;
947 948 949
	u64 alloc_hint = 0;
	u64 num_bytes;
	unsigned long ram_size;
950
	u64 cur_alloc_size = 0;
951
	u64 blocksize = fs_info->sectorsize;
952 953
	struct btrfs_key ins;
	struct extent_map *em;
954 955 956
	unsigned clear_bits;
	unsigned long page_ops;
	bool extent_reserved = false;
957 958
	int ret = 0;

959
	if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
960
		WARN_ON_ONCE(1);
961 962
		ret = -EINVAL;
		goto out_unlock;
963
	}
964

965
	num_bytes = ALIGN(end - start + 1, blocksize);
966
	num_bytes = max(blocksize,  num_bytes);
967
	ASSERT(num_bytes <= btrfs_super_total_bytes(fs_info->super_copy));
968

969
	inode_should_defrag(BTRFS_I(inode), start, end, num_bytes, SZ_64K);
C
Chris Mason 已提交
970

971 972
	if (start == 0) {
		/* lets try to make an inline extent */
973 974
		ret = cow_file_range_inline(inode, start, end, 0,
					    BTRFS_COMPRESS_NONE, NULL);
975
		if (ret == 0) {
J
Josef Bacik 已提交
976 977 978 979 980 981
			/*
			 * We use DO_ACCOUNTING here because we need the
			 * delalloc_release_metadata to be run _after_ we drop
			 * our outstanding extent for clearing delalloc for this
			 * range.
			 */
982 983
			extent_clear_unlock_delalloc(inode, start, end,
				     delalloc_end, NULL,
984
				     EXTENT_LOCKED | EXTENT_DELALLOC |
J
Josef Bacik 已提交
985 986
				     EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
				     EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
987 988
				     PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
				     PAGE_END_WRITEBACK);
989
			*nr_written = *nr_written +
990
			     (end - start + PAGE_SIZE) / PAGE_SIZE;
991 992
			*page_started = 1;
			goto out;
993 994
		} else if (ret < 0) {
			goto out_unlock;
995 996 997
		}
	}

998
	alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
999 1000
	btrfs_drop_extent_cache(BTRFS_I(inode), start,
			start + num_bytes - 1, 0);
1001

1002 1003
	while (num_bytes > 0) {
		cur_alloc_size = num_bytes;
1004
		ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
1005
					   fs_info->sectorsize, 0, alloc_hint,
1006
					   &ins, 1, 1);
1007
		if (ret < 0)
1008
			goto out_unlock;
1009 1010
		cur_alloc_size = ins.offset;
		extent_reserved = true;
C
Chris Mason 已提交
1011

1012
		ram_size = ins.offset;
1013 1014 1015 1016 1017 1018 1019
		em = create_io_em(inode, start, ins.offset, /* len */
				  start, /* orig_start */
				  ins.objectid, /* block_start */
				  ins.offset, /* block_len */
				  ins.offset, /* orig_block_len */
				  ram_size, /* ram_bytes */
				  BTRFS_COMPRESS_NONE, /* compress_type */
1020
				  BTRFS_ORDERED_REGULAR /* type */);
1021
		if (IS_ERR(em))
1022
			goto out_reserve;
1023
		free_extent_map(em);
1024 1025

		ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
1026
					       ram_size, cur_alloc_size, 0);
1027
		if (ret)
1028
			goto out_drop_extent_cache;
C
Chris Mason 已提交
1029

1030 1031 1032 1033
		if (root->root_key.objectid ==
		    BTRFS_DATA_RELOC_TREE_OBJECTID) {
			ret = btrfs_reloc_clone_csums(inode, start,
						      cur_alloc_size);
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
			/*
			 * Only drop cache here, and process as normal.
			 *
			 * We must not allow extent_clear_unlock_delalloc()
			 * at out_unlock label to free meta of this ordered
			 * extent, as its meta should be freed by
			 * btrfs_finish_ordered_io().
			 *
			 * So we must continue until @start is increased to
			 * skip current ordered extent.
			 */
1045
			if (ret)
1046 1047
				btrfs_drop_extent_cache(BTRFS_I(inode), start,
						start + ram_size - 1, 0);
1048 1049
		}

1050
		btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1051

C
Chris Mason 已提交
1052 1053 1054
		/* we're not doing compressed IO, don't unlock the first
		 * page (which the caller expects to stay locked), don't
		 * clear any dirty bits and don't set any writeback bits
1055 1056 1057
		 *
		 * Do set the Private2 bit so we know this page was properly
		 * setup for writepage
C
Chris Mason 已提交
1058
		 */
1059 1060
		page_ops = unlock ? PAGE_UNLOCK : 0;
		page_ops |= PAGE_SET_PRIVATE2;
1061

1062
		extent_clear_unlock_delalloc(inode, start,
1063 1064
					     start + ram_size - 1,
					     delalloc_end, locked_page,
1065
					     EXTENT_LOCKED | EXTENT_DELALLOC,
1066
					     page_ops);
1067 1068
		if (num_bytes < cur_alloc_size)
			num_bytes = 0;
1069
		else
1070
			num_bytes -= cur_alloc_size;
1071 1072
		alloc_hint = ins.objectid + ins.offset;
		start += cur_alloc_size;
1073
		extent_reserved = false;
1074 1075 1076 1077 1078 1079 1080 1081

		/*
		 * btrfs_reloc_clone_csums() error, since start is increased
		 * extent_clear_unlock_delalloc() at out_unlock label won't
		 * free metadata of current ordered extent, we're OK to exit.
		 */
		if (ret)
			goto out_unlock;
1082
	}
1083
out:
1084
	return ret;
1085

1086
out_drop_extent_cache:
1087
	btrfs_drop_extent_cache(BTRFS_I(inode), start, start + ram_size - 1, 0);
1088
out_reserve:
1089
	btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1090
	btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1091
out_unlock:
1092 1093
	clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
		EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
	page_ops = PAGE_UNLOCK | PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
		PAGE_END_WRITEBACK;
	/*
	 * If we reserved an extent for our delalloc range (or a subrange) and
	 * failed to create the respective ordered extent, then it means that
	 * when we reserved the extent we decremented the extent's size from
	 * the data space_info's bytes_may_use counter and incremented the
	 * space_info's bytes_reserved counter by the same amount. We must make
	 * sure extent_clear_unlock_delalloc() does not try to decrement again
	 * the data space_info's bytes_may_use counter, therefore we do not pass
	 * it the flag EXTENT_CLEAR_DATA_RESV.
	 */
	if (extent_reserved) {
		extent_clear_unlock_delalloc(inode, start,
					     start + cur_alloc_size,
					     start + cur_alloc_size,
					     locked_page,
					     clear_bits,
					     page_ops);
		start += cur_alloc_size;
		if (start >= end)
			goto out;
	}
1117 1118
	extent_clear_unlock_delalloc(inode, start, end, delalloc_end,
				     locked_page,
1119 1120
				     clear_bits | EXTENT_CLEAR_DATA_RESV,
				     page_ops);
1121
	goto out;
1122
}
C
Chris Mason 已提交
1123

1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
/*
 * work queue call back to started compression on a file and pages
 */
static noinline void async_cow_start(struct btrfs_work *work)
{
	struct async_cow *async_cow;
	int num_added = 0;
	async_cow = container_of(work, struct async_cow, work);

	compress_file_range(async_cow->inode, async_cow->locked_page,
			    async_cow->start, async_cow->end, async_cow,
			    &num_added);
1136
	if (num_added == 0) {
1137
		btrfs_add_delayed_iput(async_cow->inode);
1138
		async_cow->inode = NULL;
1139
	}
1140 1141 1142 1143 1144 1145 1146
}

/*
 * work queue call back to submit previously compressed pages
 */
static noinline void async_cow_submit(struct btrfs_work *work)
{
1147
	struct btrfs_fs_info *fs_info;
1148 1149 1150 1151 1152 1153 1154
	struct async_cow *async_cow;
	struct btrfs_root *root;
	unsigned long nr_pages;

	async_cow = container_of(work, struct async_cow, work);

	root = async_cow->root;
1155
	fs_info = root->fs_info;
1156 1157
	nr_pages = (async_cow->end - async_cow->start + PAGE_SIZE) >>
		PAGE_SHIFT;
1158

1159 1160 1161
	/*
	 * atomic_sub_return implies a barrier for waitqueue_active
	 */
1162
	if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1163
	    5 * SZ_1M &&
1164 1165
	    waitqueue_active(&fs_info->async_submit_wait))
		wake_up(&fs_info->async_submit_wait);
1166

C
Chris Mason 已提交
1167
	if (async_cow->inode)
1168 1169
		submit_compressed_extents(async_cow->inode, async_cow);
}
C
Chris Mason 已提交
1170

1171 1172 1173 1174
static noinline void async_cow_free(struct btrfs_work *work)
{
	struct async_cow *async_cow;
	async_cow = container_of(work, struct async_cow, work);
1175
	if (async_cow->inode)
1176
		btrfs_add_delayed_iput(async_cow->inode);
1177 1178 1179 1180 1181
	kfree(async_cow);
}

static int cow_file_range_async(struct inode *inode, struct page *locked_page,
				u64 start, u64 end, int *page_started,
1182 1183
				unsigned long *nr_written,
				unsigned int write_flags)
1184
{
1185
	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1186 1187 1188 1189 1190
	struct async_cow *async_cow;
	struct btrfs_root *root = BTRFS_I(inode)->root;
	unsigned long nr_pages;
	u64 cur_end;

1191
	clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1192
			 1, 0, NULL);
C
Chris Mason 已提交
1193
	while (start < end) {
1194
		async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1195
		BUG_ON(!async_cow); /* -ENOMEM */
1196
		async_cow->inode = igrab(inode);
1197 1198 1199
		async_cow->root = root;
		async_cow->locked_page = locked_page;
		async_cow->start = start;
1200
		async_cow->write_flags = write_flags;
1201

1202
		if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
1203
		    !btrfs_test_opt(fs_info, FORCE_COMPRESS))
1204 1205
			cur_end = end;
		else
1206
			cur_end = min(end, start + SZ_512K - 1);
1207 1208 1209 1210

		async_cow->end = cur_end;
		INIT_LIST_HEAD(&async_cow->extents);

1211 1212 1213 1214
		btrfs_init_work(&async_cow->work,
				btrfs_delalloc_helper,
				async_cow_start, async_cow_submit,
				async_cow_free);
1215

1216 1217
		nr_pages = (cur_end - start + PAGE_SIZE) >>
			PAGE_SHIFT;
1218
		atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1219

1220
		btrfs_queue_work(fs_info->delalloc_workers, &async_cow->work);
1221 1222 1223 1224 1225 1226

		*nr_written += nr_pages;
		start = cur_end + 1;
	}
	*page_started = 1;
	return 0;
1227 1228
}

1229
static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
1230 1231 1232 1233 1234 1235
					u64 bytenr, u64 num_bytes)
{
	int ret;
	struct btrfs_ordered_sum *sums;
	LIST_HEAD(list);

1236
	ret = btrfs_lookup_csums_range(fs_info->csum_root, bytenr,
A
Arne Jansen 已提交
1237
				       bytenr + num_bytes - 1, &list, 0);
1238 1239 1240 1241 1242 1243 1244 1245
	if (ret == 0 && list_empty(&list))
		return 0;

	while (!list_empty(&list)) {
		sums = list_entry(list.next, struct btrfs_ordered_sum, list);
		list_del(&sums->list);
		kfree(sums);
	}
1246 1247
	if (ret < 0)
		return ret;
1248 1249 1250
	return 1;
}

C
Chris Mason 已提交
1251 1252 1253 1254 1255 1256 1257
/*
 * when nowcow writeback call back.  This checks for snapshots or COW copies
 * of the extents that exist in the file, and COWs the file as required.
 *
 * If no cow copies or snapshots exist, we write directly to the existing
 * blocks on disk
 */
1258 1259
static noinline int run_delalloc_nocow(struct inode *inode,
				       struct page *locked_page,
1260 1261
			      u64 start, u64 end, int *page_started, int force,
			      unsigned long *nr_written)
1262
{
1263
	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1264 1265 1266
	struct btrfs_root *root = BTRFS_I(inode)->root;
	struct extent_buffer *leaf;
	struct btrfs_path *path;
Y
Yan Zheng 已提交
1267
	struct btrfs_file_extent_item *fi;
1268
	struct btrfs_key found_key;
1269
	struct extent_map *em;
Y
Yan Zheng 已提交
1270 1271 1272
	u64 cow_start;
	u64 cur_offset;
	u64 extent_end;
1273
	u64 extent_offset;
Y
Yan Zheng 已提交
1274 1275
	u64 disk_bytenr;
	u64 num_bytes;
1276
	u64 disk_num_bytes;
J
Josef Bacik 已提交
1277
	u64 ram_bytes;
Y
Yan Zheng 已提交
1278
	int extent_type;
1279
	int ret, err;
Y
Yan Zheng 已提交
1280
	int type;
Y
Yan Zheng 已提交
1281 1282
	int nocow;
	int check_prev = 1;
1283
	bool nolock;
1284
	u64 ino = btrfs_ino(BTRFS_I(inode));
1285 1286

	path = btrfs_alloc_path();
1287
	if (!path) {
1288 1289
		extent_clear_unlock_delalloc(inode, start, end, end,
					     locked_page,
1290
					     EXTENT_LOCKED | EXTENT_DELALLOC |
1291 1292
					     EXTENT_DO_ACCOUNTING |
					     EXTENT_DEFRAG, PAGE_UNLOCK |
1293 1294 1295
					     PAGE_CLEAR_DIRTY |
					     PAGE_SET_WRITEBACK |
					     PAGE_END_WRITEBACK);
1296
		return -ENOMEM;
1297
	}
1298

1299
	nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
1300

Y
Yan Zheng 已提交
1301 1302 1303
	cow_start = (u64)-1;
	cur_offset = start;
	while (1) {
1304
		ret = btrfs_lookup_file_extent(NULL, root, path, ino,
Y
Yan Zheng 已提交
1305
					       cur_offset, 0);
1306
		if (ret < 0)
1307
			goto error;
Y
Yan Zheng 已提交
1308 1309 1310 1311
		if (ret > 0 && path->slots[0] > 0 && check_prev) {
			leaf = path->nodes[0];
			btrfs_item_key_to_cpu(leaf, &found_key,
					      path->slots[0] - 1);
L
Li Zefan 已提交
1312
			if (found_key.objectid == ino &&
Y
Yan Zheng 已提交
1313 1314 1315 1316 1317 1318 1319 1320
			    found_key.type == BTRFS_EXTENT_DATA_KEY)
				path->slots[0]--;
		}
		check_prev = 0;
next_slot:
		leaf = path->nodes[0];
		if (path->slots[0] >= btrfs_header_nritems(leaf)) {
			ret = btrfs_next_leaf(root, path);
1321 1322 1323
			if (ret < 0) {
				if (cow_start != (u64)-1)
					cur_offset = cow_start;
1324
				goto error;
1325
			}
Y
Yan Zheng 已提交
1326 1327 1328 1329
			if (ret > 0)
				break;
			leaf = path->nodes[0];
		}
1330

Y
Yan Zheng 已提交
1331 1332
		nocow = 0;
		disk_bytenr = 0;
1333
		num_bytes = 0;
Y
Yan Zheng 已提交
1334 1335
		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);

1336 1337 1338 1339 1340 1341 1342 1343
		if (found_key.objectid > ino)
			break;
		if (WARN_ON_ONCE(found_key.objectid < ino) ||
		    found_key.type < BTRFS_EXTENT_DATA_KEY) {
			path->slots[0]++;
			goto next_slot;
		}
		if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
Y
Yan Zheng 已提交
1344 1345 1346 1347 1348
		    found_key.offset > end)
			break;

		if (found_key.offset > cur_offset) {
			extent_end = found_key.offset;
1349
			extent_type = 0;
Y
Yan Zheng 已提交
1350 1351 1352 1353 1354 1355 1356
			goto out_check;
		}

		fi = btrfs_item_ptr(leaf, path->slots[0],
				    struct btrfs_file_extent_item);
		extent_type = btrfs_file_extent_type(leaf, fi);

J
Josef Bacik 已提交
1357
		ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
Y
Yan Zheng 已提交
1358 1359
		if (extent_type == BTRFS_FILE_EXTENT_REG ||
		    extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
Y
Yan Zheng 已提交
1360
			disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1361
			extent_offset = btrfs_file_extent_offset(leaf, fi);
Y
Yan Zheng 已提交
1362 1363
			extent_end = found_key.offset +
				btrfs_file_extent_num_bytes(leaf, fi);
1364 1365
			disk_num_bytes =
				btrfs_file_extent_disk_num_bytes(leaf, fi);
Y
Yan Zheng 已提交
1366 1367 1368 1369
			if (extent_end <= start) {
				path->slots[0]++;
				goto next_slot;
			}
1370 1371
			if (disk_bytenr == 0)
				goto out_check;
Y
Yan Zheng 已提交
1372 1373 1374 1375
			if (btrfs_file_extent_compression(leaf, fi) ||
			    btrfs_file_extent_encryption(leaf, fi) ||
			    btrfs_file_extent_other_encoding(leaf, fi))
				goto out_check;
Y
Yan Zheng 已提交
1376 1377
			if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
				goto out_check;
1378
			if (btrfs_extent_readonly(fs_info, disk_bytenr))
Y
Yan Zheng 已提交
1379
				goto out_check;
1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394
			ret = btrfs_cross_ref_exist(root, ino,
						    found_key.offset -
						    extent_offset, disk_bytenr);
			if (ret) {
				/*
				 * ret could be -EIO if the above fails to read
				 * metadata.
				 */
				if (ret < 0) {
					if (cow_start != (u64)-1)
						cur_offset = cow_start;
					goto error;
				}

				WARN_ON_ONCE(nolock);
1395
				goto out_check;
1396
			}
1397
			disk_bytenr += extent_offset;
1398 1399
			disk_bytenr += cur_offset - found_key.offset;
			num_bytes = min(end + 1, extent_end) - cur_offset;
1400 1401 1402 1403 1404
			/*
			 * if there are pending snapshots for this root,
			 * we fall into common COW way.
			 */
			if (!nolock) {
1405
				err = btrfs_start_write_no_snapshotting(root);
1406 1407 1408
				if (!err)
					goto out_check;
			}
1409 1410 1411 1412 1413
			/*
			 * force cow if csum exists in the range.
			 * this ensure that csum for a given extent are
			 * either valid or do not exist.
			 */
1414 1415 1416
			ret = csum_exist_in_range(fs_info, disk_bytenr,
						  num_bytes);
			if (ret) {
1417
				if (!nolock)
1418
					btrfs_end_write_no_snapshotting(root);
1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429

				/*
				 * ret could be -EIO if the above fails to read
				 * metadata.
				 */
				if (ret < 0) {
					if (cow_start != (u64)-1)
						cur_offset = cow_start;
					goto error;
				}
				WARN_ON_ONCE(nolock);
1430
				goto out_check;
1431 1432 1433
			}
			if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr)) {
				if (!nolock)
1434
					btrfs_end_write_no_snapshotting(root);
1435
				goto out_check;
1436
			}
Y
Yan Zheng 已提交
1437 1438 1439
			nocow = 1;
		} else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
			extent_end = found_key.offset +
1440 1441
				btrfs_file_extent_inline_len(leaf,
						     path->slots[0], fi);
1442
			extent_end = ALIGN(extent_end,
1443
					   fs_info->sectorsize);
Y
Yan Zheng 已提交
1444 1445 1446 1447 1448 1449
		} else {
			BUG_ON(1);
		}
out_check:
		if (extent_end <= start) {
			path->slots[0]++;
1450
			if (!nolock && nocow)
1451
				btrfs_end_write_no_snapshotting(root);
1452
			if (nocow)
1453
				btrfs_dec_nocow_writers(fs_info, disk_bytenr);
Y
Yan Zheng 已提交
1454 1455 1456 1457 1458 1459 1460 1461 1462 1463
			goto next_slot;
		}
		if (!nocow) {
			if (cow_start == (u64)-1)
				cow_start = cur_offset;
			cur_offset = extent_end;
			if (cur_offset > end)
				break;
			path->slots[0]++;
			goto next_slot;
1464 1465
		}

1466
		btrfs_release_path(path);
Y
Yan Zheng 已提交
1467
		if (cow_start != (u64)-1) {
1468 1469
			ret = cow_file_range(inode, locked_page,
					     cow_start, found_key.offset - 1,
1470 1471
					     end, page_started, nr_written, 1,
					     NULL);
1472 1473
			if (ret) {
				if (!nolock && nocow)
1474
					btrfs_end_write_no_snapshotting(root);
1475
				if (nocow)
1476
					btrfs_dec_nocow_writers(fs_info,
1477
								disk_bytenr);
1478
				goto error;
1479
			}
Y
Yan Zheng 已提交
1480
			cow_start = (u64)-1;
1481
		}
Y
Yan Zheng 已提交
1482

Y
Yan Zheng 已提交
1483
		if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494
			u64 orig_start = found_key.offset - extent_offset;

			em = create_io_em(inode, cur_offset, num_bytes,
					  orig_start,
					  disk_bytenr, /* block_start */
					  num_bytes, /* block_len */
					  disk_num_bytes, /* orig_block_len */
					  ram_bytes, BTRFS_COMPRESS_NONE,
					  BTRFS_ORDERED_PREALLOC);
			if (IS_ERR(em)) {
				if (!nolock && nocow)
1495
					btrfs_end_write_no_snapshotting(root);
1496 1497 1498 1499 1500
				if (nocow)
					btrfs_dec_nocow_writers(fs_info,
								disk_bytenr);
				ret = PTR_ERR(em);
				goto error;
Y
Yan Zheng 已提交
1501
			}
1502 1503 1504 1505
			free_extent_map(em);
		}

		if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
Y
Yan Zheng 已提交
1506 1507 1508 1509
			type = BTRFS_ORDERED_PREALLOC;
		} else {
			type = BTRFS_ORDERED_NOCOW;
		}
Y
Yan Zheng 已提交
1510 1511

		ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
Y
Yan Zheng 已提交
1512
					       num_bytes, num_bytes, type);
1513
		if (nocow)
1514
			btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1515
		BUG_ON(ret); /* -ENOMEM */
1516

1517
		if (root->root_key.objectid ==
1518 1519 1520 1521 1522 1523
		    BTRFS_DATA_RELOC_TREE_OBJECTID)
			/*
			 * Error handled later, as we must prevent
			 * extent_clear_unlock_delalloc() in error handler
			 * from freeing metadata of created ordered extent.
			 */
1524 1525 1526
			ret = btrfs_reloc_clone_csums(inode, cur_offset,
						      num_bytes);

1527
		extent_clear_unlock_delalloc(inode, cur_offset,
1528
					     cur_offset + num_bytes - 1, end,
1529
					     locked_page, EXTENT_LOCKED |
1530 1531 1532 1533
					     EXTENT_DELALLOC |
					     EXTENT_CLEAR_DATA_RESV,
					     PAGE_UNLOCK | PAGE_SET_PRIVATE2);

1534
		if (!nolock && nocow)
1535
			btrfs_end_write_no_snapshotting(root);
Y
Yan Zheng 已提交
1536
		cur_offset = extent_end;
1537 1538 1539 1540 1541 1542 1543 1544

		/*
		 * btrfs_reloc_clone_csums() error, now we're OK to call error
		 * handler, as metadata for created ordered extent will only
		 * be freed by btrfs_finish_ordered_io().
		 */
		if (ret)
			goto error;
Y
Yan Zheng 已提交
1545 1546
		if (cur_offset > end)
			break;
1547
	}
1548
	btrfs_release_path(path);
Y
Yan Zheng 已提交
1549

1550
	if (cur_offset <= end && cow_start == (u64)-1) {
Y
Yan Zheng 已提交
1551
		cow_start = cur_offset;
1552 1553 1554
		cur_offset = end;
	}

Y
Yan Zheng 已提交
1555
	if (cow_start != (u64)-1) {
1556 1557
		ret = cow_file_range(inode, locked_page, cow_start, end, end,
				     page_started, nr_written, 1, NULL);
1558
		if (ret)
1559
			goto error;
Y
Yan Zheng 已提交
1560 1561
	}

1562
error:
1563
	if (ret && cur_offset < end)
1564
		extent_clear_unlock_delalloc(inode, cur_offset, end, end,
1565
					     locked_page, EXTENT_LOCKED |
1566 1567 1568
					     EXTENT_DELALLOC | EXTENT_DEFRAG |
					     EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
					     PAGE_CLEAR_DIRTY |
1569 1570
					     PAGE_SET_WRITEBACK |
					     PAGE_END_WRITEBACK);
1571
	btrfs_free_path(path);
1572
	return ret;
1573 1574
}

1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594
static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
{

	if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
	    !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
		return 0;

	/*
	 * @defrag_bytes is a hint value, no spinlock held here,
	 * if is not zero, it means the file is defragging.
	 * Force cow if given extent needs to be defragged.
	 */
	if (BTRFS_I(inode)->defrag_bytes &&
	    test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
			   EXTENT_DEFRAG, 0, NULL))
		return 1;

	return 0;
}

C
Chris Mason 已提交
1595 1596 1597
/*
 * extent_io.c call back to do delayed allocation processing
 */
1598
static int run_delalloc_range(void *private_data, struct page *locked_page,
1599
			      u64 start, u64 end, int *page_started,
1600 1601
			      unsigned long *nr_written,
			      struct writeback_control *wbc)
1602
{
1603
	struct inode *inode = private_data;
1604
	int ret;
1605
	int force_cow = need_force_cow(inode, start, end);
1606
	unsigned int write_flags = wbc_to_write_flags(wbc);
1607

1608
	if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
C
Chris Mason 已提交
1609
		ret = run_delalloc_nocow(inode, locked_page, start, end,
C
Chris Mason 已提交
1610
					 page_started, 1, nr_written);
1611
	} else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
Y
Yan Zheng 已提交
1612
		ret = run_delalloc_nocow(inode, locked_page, start, end,
C
Chris Mason 已提交
1613
					 page_started, 0, nr_written);
1614
	} else if (!inode_need_compress(inode, start, end)) {
1615 1616
		ret = cow_file_range(inode, locked_page, start, end, end,
				      page_started, nr_written, 1, NULL);
1617 1618 1619
	} else {
		set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
			&BTRFS_I(inode)->runtime_flags);
1620
		ret = cow_file_range_async(inode, locked_page, start, end,
1621 1622
					   page_started, nr_written,
					   write_flags);
1623
	}
1624 1625
	if (ret)
		btrfs_cleanup_ordered_extents(inode, start, end - start + 1);
1626 1627 1628
	return ret;
}

1629
static void btrfs_split_extent_hook(void *private_data,
1630
				    struct extent_state *orig, u64 split)
J
Josef Bacik 已提交
1631
{
1632
	struct inode *inode = private_data;
1633 1634
	u64 size;

1635
	/* not delalloc, ignore it */
J
Josef Bacik 已提交
1636
	if (!(orig->state & EXTENT_DELALLOC))
1637
		return;
J
Josef Bacik 已提交
1638

1639 1640
	size = orig->end - orig->start + 1;
	if (size > BTRFS_MAX_EXTENT_SIZE) {
1641
		u32 num_extents;
1642 1643 1644
		u64 new_size;

		/*
1645 1646
		 * See the explanation in btrfs_merge_extent_hook, the same
		 * applies here, just in reverse.
1647 1648
		 */
		new_size = orig->end - split + 1;
1649
		num_extents = count_max_extents(new_size);
1650
		new_size = split - orig->start;
1651 1652
		num_extents += count_max_extents(new_size);
		if (count_max_extents(size) >= num_extents)
1653 1654 1655
			return;
	}

1656
	spin_lock(&BTRFS_I(inode)->lock);
J
Josef Bacik 已提交
1657
	btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
1658
	spin_unlock(&BTRFS_I(inode)->lock);
J
Josef Bacik 已提交
1659 1660 1661 1662 1663 1664 1665 1666
}

/*
 * extent_io.c merge_extent_hook, used to track merged delayed allocation
 * extents so we can keep track of new extents that are just merged onto old
 * extents, such as when we are doing sequential writes, so we can properly
 * account for the metadata space we'll need.
 */
1667
static void btrfs_merge_extent_hook(void *private_data,
1668 1669
				    struct extent_state *new,
				    struct extent_state *other)
J
Josef Bacik 已提交
1670
{
1671
	struct inode *inode = private_data;
1672
	u64 new_size, old_size;
1673
	u32 num_extents;
1674

J
Josef Bacik 已提交
1675 1676
	/* not delalloc, ignore it */
	if (!(other->state & EXTENT_DELALLOC))
1677
		return;
J
Josef Bacik 已提交
1678

J
Josef Bacik 已提交
1679 1680 1681 1682
	if (new->start > other->start)
		new_size = new->end - other->start + 1;
	else
		new_size = other->end - new->start + 1;
1683 1684 1685 1686

	/* we're not bigger than the max, unreserve the space and go */
	if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
		spin_lock(&BTRFS_I(inode)->lock);
J
Josef Bacik 已提交
1687
		btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1688 1689 1690 1691 1692
		spin_unlock(&BTRFS_I(inode)->lock);
		return;
	}

	/*
1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708
	 * We have to add up either side to figure out how many extents were
	 * accounted for before we merged into one big extent.  If the number of
	 * extents we accounted for is <= the amount we need for the new range
	 * then we can return, otherwise drop.  Think of it like this
	 *
	 * [ 4k][MAX_SIZE]
	 *
	 * So we've grown the extent by a MAX_SIZE extent, this would mean we
	 * need 2 outstanding extents, on one side we have 1 and the other side
	 * we have 1 so they are == and we can return.  But in this case
	 *
	 * [MAX_SIZE+4k][MAX_SIZE+4k]
	 *
	 * Each range on their own accounts for 2 extents, but merged together
	 * they are only 3 extents worth of accounting, so we need to drop in
	 * this case.
1709
	 */
1710
	old_size = other->end - other->start + 1;
1711
	num_extents = count_max_extents(old_size);
1712
	old_size = new->end - new->start + 1;
1713 1714
	num_extents += count_max_extents(old_size);
	if (count_max_extents(new_size) >= num_extents)
1715 1716
		return;

1717
	spin_lock(&BTRFS_I(inode)->lock);
J
Josef Bacik 已提交
1718
	btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1719
	spin_unlock(&BTRFS_I(inode)->lock);
J
Josef Bacik 已提交
1720 1721
}

1722 1723 1724
static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
				      struct inode *inode)
{
1725 1726
	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);

1727 1728 1729 1730 1731 1732 1733 1734
	spin_lock(&root->delalloc_lock);
	if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
		list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
			      &root->delalloc_inodes);
		set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
			&BTRFS_I(inode)->runtime_flags);
		root->nr_delalloc_inodes++;
		if (root->nr_delalloc_inodes == 1) {
1735
			spin_lock(&fs_info->delalloc_root_lock);
1736 1737
			BUG_ON(!list_empty(&root->delalloc_root));
			list_add_tail(&root->delalloc_root,
1738 1739
				      &fs_info->delalloc_roots);
			spin_unlock(&fs_info->delalloc_root_lock);
1740 1741 1742 1743 1744
		}
	}
	spin_unlock(&root->delalloc_lock);
}

1745 1746 1747

void __btrfs_del_delalloc_inode(struct btrfs_root *root,
				struct btrfs_inode *inode)
1748
{
1749
	struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
1750

1751 1752
	if (!list_empty(&inode->delalloc_inodes)) {
		list_del_init(&inode->delalloc_inodes);
1753
		clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1754
			  &inode->runtime_flags);
1755 1756
		root->nr_delalloc_inodes--;
		if (!root->nr_delalloc_inodes) {
1757
			spin_lock(&fs_info->delalloc_root_lock);
1758 1759
			BUG_ON(list_empty(&root->delalloc_root));
			list_del_init(&root->delalloc_root);
1760
			spin_unlock(&fs_info->delalloc_root_lock);
1761 1762
		}
	}
1763 1764 1765 1766 1767 1768 1769
}

static void btrfs_del_delalloc_inode(struct btrfs_root *root,
				     struct btrfs_inode *inode)
{
	spin_lock(&root->delalloc_lock);
	__btrfs_del_delalloc_inode(root, inode);
1770 1771 1772
	spin_unlock(&root->delalloc_lock);
}

C
Chris Mason 已提交
1773 1774 1775 1776 1777
/*
 * extent_io.c set_bit_hook, used to track delayed allocation
 * bytes in this file, and to maintain the list of inodes that
 * have pending delalloc work to be done.
 */
1778
static void btrfs_set_bit_hook(void *private_data,
1779
			       struct extent_state *state, unsigned *bits)
1780
{
1781
	struct inode *inode = private_data;
J
Josef Bacik 已提交
1782

1783 1784
	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);

1785 1786
	if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
		WARN_ON(1);
1787 1788
	/*
	 * set_bit and clear bit hooks normally require _irqsave/restore
1789
	 * but in this case, we are only testing for the DELALLOC
1790 1791
	 * bit, which is only set or cleared with irqs on
	 */
1792
	if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1793
		struct btrfs_root *root = BTRFS_I(inode)->root;
1794
		u64 len = state->end + 1 - state->start;
J
Josef Bacik 已提交
1795
		u32 num_extents = count_max_extents(len);
1796
		bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
J
Josef Bacik 已提交
1797

J
Josef Bacik 已提交
1798 1799 1800
		spin_lock(&BTRFS_I(inode)->lock);
		btrfs_mod_outstanding_extents(BTRFS_I(inode), num_extents);
		spin_unlock(&BTRFS_I(inode)->lock);
1801

1802
		/* For sanity tests */
1803
		if (btrfs_is_testing(fs_info))
1804 1805
			return;

1806 1807
		percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
					 fs_info->delalloc_batch);
1808
		spin_lock(&BTRFS_I(inode)->lock);
1809
		BTRFS_I(inode)->delalloc_bytes += len;
1810 1811
		if (*bits & EXTENT_DEFRAG)
			BTRFS_I(inode)->defrag_bytes += len;
1812
		if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1813 1814
					 &BTRFS_I(inode)->runtime_flags))
			btrfs_add_delalloc_inodes(root, inode);
1815
		spin_unlock(&BTRFS_I(inode)->lock);
1816
	}
1817 1818 1819 1820 1821 1822 1823 1824

	if (!(state->state & EXTENT_DELALLOC_NEW) &&
	    (*bits & EXTENT_DELALLOC_NEW)) {
		spin_lock(&BTRFS_I(inode)->lock);
		BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
			state->start;
		spin_unlock(&BTRFS_I(inode)->lock);
	}
1825 1826
}

C
Chris Mason 已提交
1827 1828 1829
/*
 * extent_io.c clear_bit_hook, see set_bit_hook for why
 */
1830
static void btrfs_clear_bit_hook(void *private_data,
1831
				 struct extent_state *state,
1832
				 unsigned *bits)
1833
{
1834
	struct btrfs_inode *inode = BTRFS_I((struct inode *)private_data);
1835
	struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
1836
	u64 len = state->end + 1 - state->start;
1837
	u32 num_extents = count_max_extents(len);
1838

1839 1840
	if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG)) {
		spin_lock(&inode->lock);
1841
		inode->defrag_bytes -= len;
1842 1843
		spin_unlock(&inode->lock);
	}
1844

1845 1846
	/*
	 * set_bit and clear bit hooks normally require _irqsave/restore
1847
	 * but in this case, we are only testing for the DELALLOC
1848 1849
	 * bit, which is only set or cleared with irqs on
	 */
1850
	if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1851
		struct btrfs_root *root = inode->root;
1852
		bool do_list = !btrfs_is_free_space_inode(inode);
1853

J
Josef Bacik 已提交
1854 1855 1856
		spin_lock(&inode->lock);
		btrfs_mod_outstanding_extents(inode, -num_extents);
		spin_unlock(&inode->lock);
1857

1858 1859 1860 1861 1862
		/*
		 * We don't reserve metadata space for space cache inodes so we
		 * don't need to call dellalloc_release_metadata if there is an
		 * error.
		 */
1863
		if (*bits & EXTENT_CLEAR_META_RESV &&
1864
		    root != fs_info->tree_root)
1865
			btrfs_delalloc_release_metadata(inode, len, false);
1866

1867
		/* For sanity tests. */
1868
		if (btrfs_is_testing(fs_info))
1869 1870
			return;

1871 1872 1873
		if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID &&
		    do_list && !(state->state & EXTENT_NORESERVE) &&
		    (*bits & EXTENT_CLEAR_DATA_RESV))
1874 1875
			btrfs_free_reserved_data_space_noquota(
					&inode->vfs_inode,
1876
					state->start, len);
J
Josef Bacik 已提交
1877

1878 1879
		percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
					 fs_info->delalloc_batch);
1880 1881 1882
		spin_lock(&inode->lock);
		inode->delalloc_bytes -= len;
		if (do_list && inode->delalloc_bytes == 0 &&
1883
		    test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1884
					&inode->runtime_flags))
1885
			btrfs_del_delalloc_inode(root, inode);
1886
		spin_unlock(&inode->lock);
1887
	}
1888 1889 1890 1891 1892 1893 1894 1895

	if ((state->state & EXTENT_DELALLOC_NEW) &&
	    (*bits & EXTENT_DELALLOC_NEW)) {
		spin_lock(&inode->lock);
		ASSERT(inode->new_delalloc_bytes >= len);
		inode->new_delalloc_bytes -= len;
		spin_unlock(&inode->lock);
	}
1896 1897
}

C
Chris Mason 已提交
1898 1899 1900
/*
 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
 * we don't create bios that span stripes or chunks
L
Liu Bo 已提交
1901 1902 1903 1904
 *
 * return 1 if page cannot be merged to bio
 * return 0 if page can be merged to bio
 * return error otherwise
C
Chris Mason 已提交
1905
 */
1906
int btrfs_merge_bio_hook(struct page *page, unsigned long offset,
C
Chris Mason 已提交
1907 1908
			 size_t size, struct bio *bio,
			 unsigned long bio_flags)
1909
{
1910 1911
	struct inode *inode = page->mapping->host;
	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1912
	u64 logical = (u64)bio->bi_iter.bi_sector << 9;
1913 1914 1915 1916
	u64 length = 0;
	u64 map_length;
	int ret;

1917 1918 1919
	if (bio_flags & EXTENT_BIO_COMPRESSED)
		return 0;

1920
	length = bio->bi_iter.bi_size;
1921
	map_length = length;
1922 1923
	ret = btrfs_map_block(fs_info, btrfs_op(bio), logical, &map_length,
			      NULL, 0);
L
Liu Bo 已提交
1924 1925
	if (ret < 0)
		return ret;
C
Chris Mason 已提交
1926
	if (map_length < length + size)
1927
		return 1;
1928
	return 0;
1929 1930
}

C
Chris Mason 已提交
1931 1932 1933 1934 1935 1936 1937 1938
/*
 * in order to insert checksums into the metadata in large chunks,
 * we wait until bio submission time.   All the pages in the bio are
 * checksummed and sums are attached onto the ordered extent record.
 *
 * At IO completion time the cums attached on the ordered extent record
 * are inserted into the btree
 */
1939
static blk_status_t btrfs_submit_bio_start(void *private_data, struct bio *bio,
1940
				    u64 bio_offset)
1941
{
1942
	struct inode *inode = private_data;
1943
	blk_status_t ret = 0;
1944

1945
	ret = btrfs_csum_one_bio(inode, bio, 0, 0);
1946
	BUG_ON(ret); /* -ENOMEM */
C
Chris Mason 已提交
1947 1948
	return 0;
}
1949

C
Chris Mason 已提交
1950 1951 1952 1953 1954 1955 1956 1957
/*
 * in order to insert checksums into the metadata in large chunks,
 * we wait until bio submission time.   All the pages in the bio are
 * checksummed and sums are attached onto the ordered extent record.
 *
 * At IO completion time the cums attached on the ordered extent record
 * are inserted into the btree
 */
1958
static blk_status_t btrfs_submit_bio_done(void *private_data, struct bio *bio,
1959
			  int mirror_num)
C
Chris Mason 已提交
1960
{
1961
	struct inode *inode = private_data;
1962
	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1963
	blk_status_t ret;
1964

1965
	ret = btrfs_map_bio(fs_info, bio, mirror_num, 1);
1966
	if (ret) {
1967
		bio->bi_status = ret;
1968 1969
		bio_endio(bio);
	}
1970
	return ret;
1971 1972
}

C
Chris Mason 已提交
1973
/*
1974
 * extent_io.c submission hook. This does the right thing for csum calculation
1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989
 * on write, or reading the csums from the tree before a read.
 *
 * Rules about async/sync submit,
 * a) read:				sync submit
 *
 * b) write without checksum:		sync submit
 *
 * c) write with checksum:
 *    c-1) if bio is issued by fsync:	sync submit
 *         (sync_writers != 0)
 *
 *    c-2) if root is reloc root:	sync submit
 *         (only in case of buffered IO)
 *
 *    c-3) otherwise:			async submit
C
Chris Mason 已提交
1990
 */
1991
static blk_status_t btrfs_submit_bio_hook(void *private_data, struct bio *bio,
1992 1993
				 int mirror_num, unsigned long bio_flags,
				 u64 bio_offset)
1994
{
1995
	struct inode *inode = private_data;
1996
	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1997
	struct btrfs_root *root = BTRFS_I(inode)->root;
1998
	enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
1999
	blk_status_t ret = 0;
2000
	int skip_sum;
2001
	int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
2002

2003
	skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
2004

2005
	if (btrfs_is_free_space_inode(BTRFS_I(inode)))
2006
		metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
2007

M
Mike Christie 已提交
2008
	if (bio_op(bio) != REQ_OP_WRITE) {
2009
		ret = btrfs_bio_wq_end_io(fs_info, bio, metadata);
2010
		if (ret)
2011
			goto out;
2012

2013
		if (bio_flags & EXTENT_BIO_COMPRESSED) {
2014 2015 2016 2017
			ret = btrfs_submit_compressed_read(inode, bio,
							   mirror_num,
							   bio_flags);
			goto out;
2018
		} else if (!skip_sum) {
2019
			ret = btrfs_lookup_bio_sums(inode, bio, NULL);
2020
			if (ret)
2021
				goto out;
2022
		}
2023
		goto mapit;
2024
	} else if (async && !skip_sum) {
2025 2026 2027
		/* csum items have already been cloned */
		if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
			goto mapit;
2028
		/* we're doing a write, do the async checksumming */
2029 2030
		ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, bio_flags,
					  bio_offset, inode,
2031 2032
					  btrfs_submit_bio_start,
					  btrfs_submit_bio_done);
2033
		goto out;
2034
	} else if (!skip_sum) {
2035
		ret = btrfs_csum_one_bio(inode, bio, 0, 0);
2036 2037
		if (ret)
			goto out;
2038 2039
	}

2040
mapit:
2041
	ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
2042 2043

out:
2044 2045
	if (ret) {
		bio->bi_status = ret;
2046 2047
		bio_endio(bio);
	}
2048
	return ret;
2049
}
C
Chris Mason 已提交
2050

C
Chris Mason 已提交
2051 2052 2053 2054
/*
 * given a list of ordered sums record them in the inode.  This happens
 * at IO completion time based on sums calculated at bio submission time.
 */
2055
static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
2056
			     struct inode *inode, struct list_head *list)
2057 2058
{
	struct btrfs_ordered_sum *sum;
2059
	int ret;
2060

Q
Qinghuang Feng 已提交
2061
	list_for_each_entry(sum, list, list) {
2062
		trans->adding_csums = true;
2063
		ret = btrfs_csum_file_blocks(trans,
2064
		       BTRFS_I(inode)->root->fs_info->csum_root, sum);
2065
		trans->adding_csums = false;
2066 2067
		if (ret)
			return ret;
2068 2069 2070 2071
	}
	return 0;
}

2072
int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
2073
			      unsigned int extra_bits,
2074
			      struct extent_state **cached_state, int dedupe)
2075
{
2076
	WARN_ON((end & (PAGE_SIZE - 1)) == 0);
2077
	return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
2078
				   extra_bits, cached_state);
2079 2080
}

C
Chris Mason 已提交
2081
/* see btrfs_writepage_start_hook for details on why this is required */
2082 2083 2084 2085 2086
struct btrfs_writepage_fixup {
	struct page *page;
	struct btrfs_work work;
};

2087
static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2088 2089 2090
{
	struct btrfs_writepage_fixup *fixup;
	struct btrfs_ordered_extent *ordered;
2091
	struct extent_state *cached_state = NULL;
2092
	struct extent_changeset *data_reserved = NULL;
2093 2094 2095 2096
	struct page *page;
	struct inode *inode;
	u64 page_start;
	u64 page_end;
2097
	int ret;
2098 2099 2100

	fixup = container_of(work, struct btrfs_writepage_fixup, work);
	page = fixup->page;
C
Chris Mason 已提交
2101
again:
2102 2103 2104 2105 2106 2107 2108 2109
	lock_page(page);
	if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
		ClearPageChecked(page);
		goto out_page;
	}

	inode = page->mapping->host;
	page_start = page_offset(page);
2110
	page_end = page_offset(page) + PAGE_SIZE - 1;
2111

2112
	lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end,
2113
			 &cached_state);
C
Chris Mason 已提交
2114 2115

	/* already ordered? We're done */
2116
	if (PagePrivate2(page))
2117
		goto out;
C
Chris Mason 已提交
2118

2119
	ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
2120
					PAGE_SIZE);
C
Chris Mason 已提交
2121
	if (ordered) {
2122
		unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
2123
				     page_end, &cached_state);
C
Chris Mason 已提交
2124 2125
		unlock_page(page);
		btrfs_start_ordered_extent(inode, ordered, 1);
2126
		btrfs_put_ordered_extent(ordered);
C
Chris Mason 已提交
2127 2128
		goto again;
	}
2129

2130
	ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2131
					   PAGE_SIZE);
2132 2133 2134 2135 2136 2137 2138
	if (ret) {
		mapping_set_error(page->mapping, ret);
		end_extent_writepage(page, ret, page_start, page_end);
		ClearPageChecked(page);
		goto out;
	 }

2139 2140 2141 2142 2143 2144 2145 2146 2147
	ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
					&cached_state, 0);
	if (ret) {
		mapping_set_error(page->mapping, ret);
		end_extent_writepage(page, ret, page_start, page_end);
		ClearPageChecked(page);
		goto out;
	}

2148
	ClearPageChecked(page);
2149
	set_page_dirty(page);
2150
	btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, false);
2151
out:
2152
	unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
2153
			     &cached_state);
2154 2155
out_page:
	unlock_page(page);
2156
	put_page(page);
2157
	kfree(fixup);
2158
	extent_changeset_free(data_reserved);
2159 2160 2161 2162 2163 2164 2165 2166
}

/*
 * There are a few paths in the higher layers of the kernel that directly
 * set the page dirty bit without asking the filesystem if it is a
 * good idea.  This causes problems because we want to make sure COW
 * properly happens and the data=ordered rules are followed.
 *
C
Chris Mason 已提交
2167
 * In our case any range that doesn't have the ORDERED bit set
2168 2169 2170 2171
 * hasn't been properly setup for IO.  We kick off an async process
 * to fix it up.  The async helper will wait for ordered extents, set
 * the delalloc bit and make it safe to write the page.
 */
2172
static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
2173 2174
{
	struct inode *inode = page->mapping->host;
2175
	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2176 2177
	struct btrfs_writepage_fixup *fixup;

2178 2179
	/* this page is properly in the ordered list */
	if (TestClearPagePrivate2(page))
2180 2181 2182 2183 2184 2185 2186 2187
		return 0;

	if (PageChecked(page))
		return -EAGAIN;

	fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
	if (!fixup)
		return -EAGAIN;
2188

2189
	SetPageChecked(page);
2190
	get_page(page);
2191 2192
	btrfs_init_work(&fixup->work, btrfs_fixup_helper,
			btrfs_writepage_fixup_worker, NULL, NULL);
2193
	fixup->page = page;
2194
	btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
2195
	return -EBUSY;
2196 2197
}

Y
Yan Zheng 已提交
2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209
static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
				       struct inode *inode, u64 file_pos,
				       u64 disk_bytenr, u64 disk_num_bytes,
				       u64 num_bytes, u64 ram_bytes,
				       u8 compression, u8 encryption,
				       u16 other_encoding, int extent_type)
{
	struct btrfs_root *root = BTRFS_I(inode)->root;
	struct btrfs_file_extent_item *fi;
	struct btrfs_path *path;
	struct extent_buffer *leaf;
	struct btrfs_key ins;
2210
	u64 qg_released;
2211
	int extent_inserted = 0;
Y
Yan Zheng 已提交
2212 2213 2214
	int ret;

	path = btrfs_alloc_path();
2215 2216
	if (!path)
		return -ENOMEM;
Y
Yan Zheng 已提交
2217

C
Chris Mason 已提交
2218 2219 2220 2221 2222 2223 2224 2225 2226
	/*
	 * we may be replacing one extent in the tree with another.
	 * The new extent is pinned in the extent map, and we don't want
	 * to drop it from the cache until it is completely in the btree.
	 *
	 * So, tell btrfs_drop_extents to leave this extent in the cache.
	 * the caller is expected to unpin it and allow it to be merged
	 * with the others.
	 */
2227 2228 2229
	ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
				   file_pos + num_bytes, NULL, 0,
				   1, sizeof(*fi), &extent_inserted);
2230 2231
	if (ret)
		goto out;
Y
Yan Zheng 已提交
2232

2233
	if (!extent_inserted) {
2234
		ins.objectid = btrfs_ino(BTRFS_I(inode));
2235 2236 2237 2238 2239 2240 2241 2242 2243
		ins.offset = file_pos;
		ins.type = BTRFS_EXTENT_DATA_KEY;

		path->leave_spinning = 1;
		ret = btrfs_insert_empty_item(trans, root, path, &ins,
					      sizeof(*fi));
		if (ret)
			goto out;
	}
Y
Yan Zheng 已提交
2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256
	leaf = path->nodes[0];
	fi = btrfs_item_ptr(leaf, path->slots[0],
			    struct btrfs_file_extent_item);
	btrfs_set_file_extent_generation(leaf, fi, trans->transid);
	btrfs_set_file_extent_type(leaf, fi, extent_type);
	btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
	btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
	btrfs_set_file_extent_offset(leaf, fi, 0);
	btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
	btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
	btrfs_set_file_extent_compression(leaf, fi, compression);
	btrfs_set_file_extent_encryption(leaf, fi, encryption);
	btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2257

Y
Yan Zheng 已提交
2258
	btrfs_mark_buffer_dirty(leaf);
2259
	btrfs_release_path(path);
Y
Yan Zheng 已提交
2260 2261 2262 2263 2264 2265

	inode_add_bytes(inode, num_bytes);

	ins.objectid = disk_bytenr;
	ins.offset = disk_num_bytes;
	ins.type = BTRFS_EXTENT_ITEM_KEY;
2266

2267
	/*
2268 2269
	 * Release the reserved range from inode dirty range map, as it is
	 * already moved into delayed_ref_head
2270
	 */
2271 2272 2273 2274
	ret = btrfs_qgroup_release_data(inode, file_pos, ram_bytes);
	if (ret < 0)
		goto out;
	qg_released = ret;
2275 2276 2277
	ret = btrfs_alloc_reserved_file_extent(trans, root,
					       btrfs_ino(BTRFS_I(inode)),
					       file_pos, qg_released, &ins);
2278
out:
Y
Yan Zheng 已提交
2279
	btrfs_free_path(path);
2280

2281
	return ret;
Y
Yan Zheng 已提交
2282 2283
}

L
Liu Bo 已提交
2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389
/* snapshot-aware defrag */
struct sa_defrag_extent_backref {
	struct rb_node node;
	struct old_sa_defrag_extent *old;
	u64 root_id;
	u64 inum;
	u64 file_pos;
	u64 extent_offset;
	u64 num_bytes;
	u64 generation;
};

struct old_sa_defrag_extent {
	struct list_head list;
	struct new_sa_defrag_extent *new;

	u64 extent_offset;
	u64 bytenr;
	u64 offset;
	u64 len;
	int count;
};

struct new_sa_defrag_extent {
	struct rb_root root;
	struct list_head head;
	struct btrfs_path *path;
	struct inode *inode;
	u64 file_pos;
	u64 len;
	u64 bytenr;
	u64 disk_len;
	u8 compress_type;
};

static int backref_comp(struct sa_defrag_extent_backref *b1,
			struct sa_defrag_extent_backref *b2)
{
	if (b1->root_id < b2->root_id)
		return -1;
	else if (b1->root_id > b2->root_id)
		return 1;

	if (b1->inum < b2->inum)
		return -1;
	else if (b1->inum > b2->inum)
		return 1;

	if (b1->file_pos < b2->file_pos)
		return -1;
	else if (b1->file_pos > b2->file_pos)
		return 1;

	/*
	 * [------------------------------] ===> (a range of space)
	 *     |<--->|   |<---->| =============> (fs/file tree A)
	 * |<---------------------------->| ===> (fs/file tree B)
	 *
	 * A range of space can refer to two file extents in one tree while
	 * refer to only one file extent in another tree.
	 *
	 * So we may process a disk offset more than one time(two extents in A)
	 * and locate at the same extent(one extent in B), then insert two same
	 * backrefs(both refer to the extent in B).
	 */
	return 0;
}

static void backref_insert(struct rb_root *root,
			   struct sa_defrag_extent_backref *backref)
{
	struct rb_node **p = &root->rb_node;
	struct rb_node *parent = NULL;
	struct sa_defrag_extent_backref *entry;
	int ret;

	while (*p) {
		parent = *p;
		entry = rb_entry(parent, struct sa_defrag_extent_backref, node);

		ret = backref_comp(backref, entry);
		if (ret < 0)
			p = &(*p)->rb_left;
		else
			p = &(*p)->rb_right;
	}

	rb_link_node(&backref->node, parent, p);
	rb_insert_color(&backref->node, root);
}

/*
 * Note the backref might has changed, and in this case we just return 0.
 */
static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
				       void *ctx)
{
	struct btrfs_file_extent_item *extent;
	struct old_sa_defrag_extent *old = ctx;
	struct new_sa_defrag_extent *new = old->new;
	struct btrfs_path *path = new->path;
	struct btrfs_key key;
	struct btrfs_root *root;
	struct sa_defrag_extent_backref *backref;
	struct extent_buffer *leaf;
	struct inode *inode = new->inode;
2390
	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
L
Liu Bo 已提交
2391 2392 2393 2394 2395 2396
	int slot;
	int ret;
	u64 extent_offset;
	u64 num_bytes;

	if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2397
	    inum == btrfs_ino(BTRFS_I(inode)))
L
Liu Bo 已提交
2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408
		return 0;

	key.objectid = root_id;
	key.type = BTRFS_ROOT_ITEM_KEY;
	key.offset = (u64)-1;

	root = btrfs_read_fs_root_no_name(fs_info, &key);
	if (IS_ERR(root)) {
		if (PTR_ERR(root) == -ENOENT)
			return 0;
		WARN_ON(1);
2409
		btrfs_debug(fs_info, "inum=%llu, offset=%llu, root_id=%llu",
L
Liu Bo 已提交
2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421
			 inum, offset, root_id);
		return PTR_ERR(root);
	}

	key.objectid = inum;
	key.type = BTRFS_EXTENT_DATA_KEY;
	if (offset > (u64)-1 << 32)
		key.offset = 0;
	else
		key.offset = offset;

	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2422
	if (WARN_ON(ret < 0))
L
Liu Bo 已提交
2423
		return ret;
2424
	ret = 0;
L
Liu Bo 已提交
2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458

	while (1) {
		cond_resched();

		leaf = path->nodes[0];
		slot = path->slots[0];

		if (slot >= btrfs_header_nritems(leaf)) {
			ret = btrfs_next_leaf(root, path);
			if (ret < 0) {
				goto out;
			} else if (ret > 0) {
				ret = 0;
				goto out;
			}
			continue;
		}

		path->slots[0]++;

		btrfs_item_key_to_cpu(leaf, &key, slot);

		if (key.objectid > inum)
			goto out;

		if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
			continue;

		extent = btrfs_item_ptr(leaf, slot,
					struct btrfs_file_extent_item);

		if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
			continue;

2459 2460 2461 2462 2463 2464
		/*
		 * 'offset' refers to the exact key.offset,
		 * NOT the 'offset' field in btrfs_extent_data_ref, ie.
		 * (key.offset - extent_offset).
		 */
		if (key.offset != offset)
L
Liu Bo 已提交
2465 2466
			continue;

2467
		extent_offset = btrfs_file_extent_offset(leaf, extent);
L
Liu Bo 已提交
2468
		num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2469

L
Liu Bo 已提交
2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484
		if (extent_offset >= old->extent_offset + old->offset +
		    old->len || extent_offset + num_bytes <=
		    old->extent_offset + old->offset)
			continue;
		break;
	}

	backref = kmalloc(sizeof(*backref), GFP_NOFS);
	if (!backref) {
		ret = -ENOENT;
		goto out;
	}

	backref->root_id = root_id;
	backref->inum = inum;
2485
	backref->file_pos = offset;
L
Liu Bo 已提交
2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500
	backref->num_bytes = num_bytes;
	backref->extent_offset = extent_offset;
	backref->generation = btrfs_file_extent_generation(leaf, extent);
	backref->old = old;
	backref_insert(&new->root, backref);
	old->count++;
out:
	btrfs_release_path(path);
	WARN_ON(ret);
	return ret;
}

static noinline bool record_extent_backrefs(struct btrfs_path *path,
				   struct new_sa_defrag_extent *new)
{
2501
	struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
L
Liu Bo 已提交
2502 2503 2504 2505 2506 2507
	struct old_sa_defrag_extent *old, *tmp;
	int ret;

	new->path = path;

	list_for_each_entry_safe(old, tmp, &new->head, list) {
2508 2509
		ret = iterate_inodes_from_logical(old->bytenr +
						  old->extent_offset, fs_info,
L
Liu Bo 已提交
2510
						  path, record_one_backref,
2511
						  old, false);
2512 2513
		if (ret < 0 && ret != -ENOENT)
			return false;
L
Liu Bo 已提交
2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529

		/* no backref to be processed for this extent */
		if (!old->count) {
			list_del(&old->list);
			kfree(old);
		}
	}

	if (list_empty(&new->head))
		return false;

	return true;
}

static int relink_is_mergable(struct extent_buffer *leaf,
			      struct btrfs_file_extent_item *fi,
2530
			      struct new_sa_defrag_extent *new)
L
Liu Bo 已提交
2531
{
2532
	if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
L
Liu Bo 已提交
2533 2534 2535 2536 2537
		return 0;

	if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
		return 0;

2538 2539 2540 2541
	if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
		return 0;

	if (btrfs_file_extent_encryption(leaf, fi) ||
L
Liu Bo 已提交
2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563
	    btrfs_file_extent_other_encoding(leaf, fi))
		return 0;

	return 1;
}

/*
 * Note the backref might has changed, and in this case we just return 0.
 */
static noinline int relink_extent_backref(struct btrfs_path *path,
				 struct sa_defrag_extent_backref *prev,
				 struct sa_defrag_extent_backref *backref)
{
	struct btrfs_file_extent_item *extent;
	struct btrfs_file_extent_item *item;
	struct btrfs_ordered_extent *ordered;
	struct btrfs_trans_handle *trans;
	struct btrfs_root *root;
	struct btrfs_key key;
	struct extent_buffer *leaf;
	struct old_sa_defrag_extent *old = backref->old;
	struct new_sa_defrag_extent *new = old->new;
2564
	struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
L
Liu Bo 已提交
2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594
	struct inode *inode;
	struct extent_state *cached = NULL;
	int ret = 0;
	u64 start;
	u64 len;
	u64 lock_start;
	u64 lock_end;
	bool merge = false;
	int index;

	if (prev && prev->root_id == backref->root_id &&
	    prev->inum == backref->inum &&
	    prev->file_pos + prev->num_bytes == backref->file_pos)
		merge = true;

	/* step 1: get root */
	key.objectid = backref->root_id;
	key.type = BTRFS_ROOT_ITEM_KEY;
	key.offset = (u64)-1;

	index = srcu_read_lock(&fs_info->subvol_srcu);

	root = btrfs_read_fs_root_no_name(fs_info, &key);
	if (IS_ERR(root)) {
		srcu_read_unlock(&fs_info->subvol_srcu, index);
		if (PTR_ERR(root) == -ENOENT)
			return 0;
		return PTR_ERR(root);
	}

2595 2596 2597 2598 2599
	if (btrfs_root_readonly(root)) {
		srcu_read_unlock(&fs_info->subvol_srcu, index);
		return 0;
	}

L
Liu Bo 已提交
2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616
	/* step 2: get inode */
	key.objectid = backref->inum;
	key.type = BTRFS_INODE_ITEM_KEY;
	key.offset = 0;

	inode = btrfs_iget(fs_info->sb, &key, root, NULL);
	if (IS_ERR(inode)) {
		srcu_read_unlock(&fs_info->subvol_srcu, index);
		return 0;
	}

	srcu_read_unlock(&fs_info->subvol_srcu, index);

	/* step 3: relink backref */
	lock_start = backref->file_pos;
	lock_end = backref->file_pos + backref->num_bytes - 1;
	lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2617
			 &cached);
L
Liu Bo 已提交
2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665

	ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
	if (ordered) {
		btrfs_put_ordered_extent(ordered);
		goto out_unlock;
	}

	trans = btrfs_join_transaction(root);
	if (IS_ERR(trans)) {
		ret = PTR_ERR(trans);
		goto out_unlock;
	}

	key.objectid = backref->inum;
	key.type = BTRFS_EXTENT_DATA_KEY;
	key.offset = backref->file_pos;

	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
	if (ret < 0) {
		goto out_free_path;
	} else if (ret > 0) {
		ret = 0;
		goto out_free_path;
	}

	extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
				struct btrfs_file_extent_item);

	if (btrfs_file_extent_generation(path->nodes[0], extent) !=
	    backref->generation)
		goto out_free_path;

	btrfs_release_path(path);

	start = backref->file_pos;
	if (backref->extent_offset < old->extent_offset + old->offset)
		start += old->extent_offset + old->offset -
			 backref->extent_offset;

	len = min(backref->extent_offset + backref->num_bytes,
		  old->extent_offset + old->offset + old->len);
	len -= max(backref->extent_offset, old->extent_offset + old->offset);

	ret = btrfs_drop_extents(trans, root, inode, start,
				 start + len, 1);
	if (ret)
		goto out_free_path;
again:
2666
	key.objectid = btrfs_ino(BTRFS_I(inode));
L
Liu Bo 已提交
2667 2668 2669
	key.type = BTRFS_EXTENT_DATA_KEY;
	key.offset = start;

2670
	path->leave_spinning = 1;
L
Liu Bo 已提交
2671 2672 2673 2674 2675
	if (merge) {
		struct btrfs_file_extent_item *fi;
		u64 extent_len;
		struct btrfs_key found_key;

2676
		ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
L
Liu Bo 已提交
2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687
		if (ret < 0)
			goto out_free_path;

		path->slots[0]--;
		leaf = path->nodes[0];
		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);

		fi = btrfs_item_ptr(leaf, path->slots[0],
				    struct btrfs_file_extent_item);
		extent_len = btrfs_file_extent_num_bytes(leaf, fi);

2688 2689
		if (extent_len + found_key.offset == start &&
		    relink_is_mergable(leaf, fi, new)) {
L
Liu Bo 已提交
2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706
			btrfs_set_file_extent_num_bytes(leaf, fi,
							extent_len + len);
			btrfs_mark_buffer_dirty(leaf);
			inode_add_bytes(inode, len);

			ret = 1;
			goto out_free_path;
		} else {
			merge = false;
			btrfs_release_path(path);
			goto again;
		}
	}

	ret = btrfs_insert_empty_item(trans, root, path, &key,
					sizeof(*extent));
	if (ret) {
2707
		btrfs_abort_transaction(trans, ret);
L
Liu Bo 已提交
2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726
		goto out_free_path;
	}

	leaf = path->nodes[0];
	item = btrfs_item_ptr(leaf, path->slots[0],
				struct btrfs_file_extent_item);
	btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
	btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
	btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
	btrfs_set_file_extent_num_bytes(leaf, item, len);
	btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
	btrfs_set_file_extent_generation(leaf, item, trans->transid);
	btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
	btrfs_set_file_extent_compression(leaf, item, new->compress_type);
	btrfs_set_file_extent_encryption(leaf, item, 0);
	btrfs_set_file_extent_other_encoding(leaf, item, 0);

	btrfs_mark_buffer_dirty(leaf);
	inode_add_bytes(inode, len);
2727
	btrfs_release_path(path);
L
Liu Bo 已提交
2728

2729
	ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
L
Liu Bo 已提交
2730 2731
			new->disk_len, 0,
			backref->root_id, backref->inum,
2732
			new->file_pos);	/* start - extent_offset */
L
Liu Bo 已提交
2733
	if (ret) {
2734
		btrfs_abort_transaction(trans, ret);
L
Liu Bo 已提交
2735 2736 2737 2738 2739 2740
		goto out_free_path;
	}

	ret = 1;
out_free_path:
	btrfs_release_path(path);
2741
	path->leave_spinning = 0;
2742
	btrfs_end_transaction(trans);
L
Liu Bo 已提交
2743 2744
out_unlock:
	unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2745
			     &cached);
L
Liu Bo 已提交
2746 2747 2748 2749
	iput(inode);
	return ret;
}

2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762
static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
{
	struct old_sa_defrag_extent *old, *tmp;

	if (!new)
		return;

	list_for_each_entry_safe(old, tmp, &new->head, list) {
		kfree(old);
	}
	kfree(new);
}

L
Liu Bo 已提交
2763 2764
static void relink_file_extents(struct new_sa_defrag_extent *new)
{
2765
	struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
L
Liu Bo 已提交
2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807
	struct btrfs_path *path;
	struct sa_defrag_extent_backref *backref;
	struct sa_defrag_extent_backref *prev = NULL;
	struct inode *inode;
	struct rb_node *node;
	int ret;

	inode = new->inode;

	path = btrfs_alloc_path();
	if (!path)
		return;

	if (!record_extent_backrefs(path, new)) {
		btrfs_free_path(path);
		goto out;
	}
	btrfs_release_path(path);

	while (1) {
		node = rb_first(&new->root);
		if (!node)
			break;
		rb_erase(node, &new->root);

		backref = rb_entry(node, struct sa_defrag_extent_backref, node);

		ret = relink_extent_backref(path, prev, backref);
		WARN_ON(ret < 0);

		kfree(prev);

		if (ret == 1)
			prev = backref;
		else
			prev = NULL;
		cond_resched();
	}
	kfree(prev);

	btrfs_free_path(path);
out:
2808 2809
	free_sa_defrag_extent(new);

2810 2811
	atomic_dec(&fs_info->defrag_running);
	wake_up(&fs_info->transaction_wait);
L
Liu Bo 已提交
2812 2813 2814 2815 2816 2817
}

static struct new_sa_defrag_extent *
record_old_file_extents(struct inode *inode,
			struct btrfs_ordered_extent *ordered)
{
2818
	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
L
Liu Bo 已提交
2819 2820 2821
	struct btrfs_root *root = BTRFS_I(inode)->root;
	struct btrfs_path *path;
	struct btrfs_key key;
2822
	struct old_sa_defrag_extent *old;
L
Liu Bo 已提交
2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842
	struct new_sa_defrag_extent *new;
	int ret;

	new = kmalloc(sizeof(*new), GFP_NOFS);
	if (!new)
		return NULL;

	new->inode = inode;
	new->file_pos = ordered->file_offset;
	new->len = ordered->len;
	new->bytenr = ordered->start;
	new->disk_len = ordered->disk_len;
	new->compress_type = ordered->compress_type;
	new->root = RB_ROOT;
	INIT_LIST_HEAD(&new->head);

	path = btrfs_alloc_path();
	if (!path)
		goto out_kfree;

2843
	key.objectid = btrfs_ino(BTRFS_I(inode));
L
Liu Bo 已提交
2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869
	key.type = BTRFS_EXTENT_DATA_KEY;
	key.offset = new->file_pos;

	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
	if (ret < 0)
		goto out_free_path;
	if (ret > 0 && path->slots[0] > 0)
		path->slots[0]--;

	/* find out all the old extents for the file range */
	while (1) {
		struct btrfs_file_extent_item *extent;
		struct extent_buffer *l;
		int slot;
		u64 num_bytes;
		u64 offset;
		u64 end;
		u64 disk_bytenr;
		u64 extent_offset;

		l = path->nodes[0];
		slot = path->slots[0];

		if (slot >= btrfs_header_nritems(l)) {
			ret = btrfs_next_leaf(root, path);
			if (ret < 0)
2870
				goto out_free_path;
L
Liu Bo 已提交
2871 2872 2873 2874 2875 2876 2877
			else if (ret > 0)
				break;
			continue;
		}

		btrfs_item_key_to_cpu(l, &key, slot);

2878
		if (key.objectid != btrfs_ino(BTRFS_I(inode)))
L
Liu Bo 已提交
2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898
			break;
		if (key.type != BTRFS_EXTENT_DATA_KEY)
			break;
		if (key.offset >= new->file_pos + new->len)
			break;

		extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);

		num_bytes = btrfs_file_extent_num_bytes(l, extent);
		if (key.offset + num_bytes < new->file_pos)
			goto next;

		disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
		if (!disk_bytenr)
			goto next;

		extent_offset = btrfs_file_extent_offset(l, extent);

		old = kmalloc(sizeof(*old), GFP_NOFS);
		if (!old)
2899
			goto out_free_path;
L
Liu Bo 已提交
2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916

		offset = max(new->file_pos, key.offset);
		end = min(new->file_pos + new->len, key.offset + num_bytes);

		old->bytenr = disk_bytenr;
		old->extent_offset = extent_offset;
		old->offset = offset - key.offset;
		old->len = end - offset;
		old->new = new;
		old->count = 0;
		list_add_tail(&old->list, &new->head);
next:
		path->slots[0]++;
		cond_resched();
	}

	btrfs_free_path(path);
2917
	atomic_inc(&fs_info->defrag_running);
L
Liu Bo 已提交
2918 2919 2920 2921 2922 2923

	return new;

out_free_path:
	btrfs_free_path(path);
out_kfree:
2924
	free_sa_defrag_extent(new);
L
Liu Bo 已提交
2925 2926 2927
	return NULL;
}

2928
static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
2929 2930 2931 2932
					 u64 start, u64 len)
{
	struct btrfs_block_group_cache *cache;

2933
	cache = btrfs_lookup_block_group(fs_info, start);
2934 2935 2936 2937 2938 2939 2940 2941 2942
	ASSERT(cache);

	spin_lock(&cache->lock);
	cache->delalloc_bytes -= len;
	spin_unlock(&cache->lock);

	btrfs_put_block_group(cache);
}

C
Chris Mason 已提交
2943 2944 2945 2946
/* as ordered data IO finishes, this gets called so we can finish
 * an ordered extent if the range of bytes in the file it covers are
 * fully written.
 */
2947
static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2948
{
2949
	struct inode *inode = ordered_extent->inode;
2950
	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2951
	struct btrfs_root *root = BTRFS_I(inode)->root;
2952
	struct btrfs_trans_handle *trans = NULL;
2953
	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2954
	struct extent_state *cached_state = NULL;
L
Liu Bo 已提交
2955
	struct new_sa_defrag_extent *new = NULL;
2956
	int compress_type = 0;
2957 2958
	int ret = 0;
	u64 logical_len = ordered_extent->len;
2959
	bool nolock;
2960
	bool truncated = false;
2961 2962 2963 2964 2965 2966 2967
	bool range_locked = false;
	bool clear_new_delalloc_bytes = false;

	if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
	    !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
	    !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags))
		clear_new_delalloc_bytes = true;
2968

2969
	nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
J
Josef Bacik 已提交
2970

2971 2972 2973 2974 2975
	if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
		ret = -EIO;
		goto out;
	}

2976 2977 2978 2979
	btrfs_free_io_failure_record(BTRFS_I(inode),
			ordered_extent->file_offset,
			ordered_extent->file_offset +
			ordered_extent->len - 1);
2980

2981 2982 2983 2984 2985 2986 2987 2988
	if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
		truncated = true;
		logical_len = ordered_extent->truncated_len;
		/* Truncated the entire extent, don't bother adding */
		if (!logical_len)
			goto out;
	}

2989
	if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2990
		BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2991 2992 2993 2994 2995 2996

		/*
		 * For mwrite(mmap + memset to write) case, we still reserve
		 * space for NOCOW range.
		 * As NOCOW won't cause a new delayed ref, just free the space
		 */
2997
		btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
2998
				       ordered_extent->len);
2999 3000 3001 3002 3003 3004 3005 3006 3007
		btrfs_ordered_update_i_size(inode, 0, ordered_extent);
		if (nolock)
			trans = btrfs_join_transaction_nolock(root);
		else
			trans = btrfs_join_transaction(root);
		if (IS_ERR(trans)) {
			ret = PTR_ERR(trans);
			trans = NULL;
			goto out;
3008
		}
3009
		trans->block_rsv = &BTRFS_I(inode)->block_rsv;
3010 3011
		ret = btrfs_update_inode_fallback(trans, root, inode);
		if (ret) /* -ENOMEM or corruption */
3012
			btrfs_abort_transaction(trans, ret);
3013 3014
		goto out;
	}
3015

3016
	range_locked = true;
3017 3018
	lock_extent_bits(io_tree, ordered_extent->file_offset,
			 ordered_extent->file_offset + ordered_extent->len - 1,
3019
			 &cached_state);
3020

L
Liu Bo 已提交
3021 3022
	ret = test_range_bit(io_tree, ordered_extent->file_offset,
			ordered_extent->file_offset + ordered_extent->len - 1,
3023
			EXTENT_DEFRAG, 0, cached_state);
L
Liu Bo 已提交
3024 3025
	if (ret) {
		u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
3026
		if (0 && last_snapshot >= BTRFS_I(inode)->generation)
L
Liu Bo 已提交
3027 3028 3029 3030 3031
			/* the inode is shared */
			new = record_old_file_extents(inode, ordered_extent);

		clear_extent_bit(io_tree, ordered_extent->file_offset,
			ordered_extent->file_offset + ordered_extent->len - 1,
3032
			EXTENT_DEFRAG, 0, 0, &cached_state);
L
Liu Bo 已提交
3033 3034
	}

J
Josef Bacik 已提交
3035
	if (nolock)
3036
		trans = btrfs_join_transaction_nolock(root);
J
Josef Bacik 已提交
3037
	else
3038
		trans = btrfs_join_transaction(root);
3039 3040 3041
	if (IS_ERR(trans)) {
		ret = PTR_ERR(trans);
		trans = NULL;
3042
		goto out;
3043
	}
C
Chris Mason 已提交
3044

3045
	trans->block_rsv = &BTRFS_I(inode)->block_rsv;
3046

C
Chris Mason 已提交
3047
	if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
3048
		compress_type = ordered_extent->compress_type;
Y
Yan Zheng 已提交
3049
	if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3050
		BUG_ON(compress_type);
3051 3052
		btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
				       ordered_extent->len);
3053
		ret = btrfs_mark_extent_written(trans, BTRFS_I(inode),
Y
Yan Zheng 已提交
3054 3055
						ordered_extent->file_offset,
						ordered_extent->file_offset +
3056
						logical_len);
Y
Yan Zheng 已提交
3057
	} else {
3058
		BUG_ON(root == fs_info->tree_root);
Y
Yan Zheng 已提交
3059 3060 3061 3062
		ret = insert_reserved_file_extent(trans, inode,
						ordered_extent->file_offset,
						ordered_extent->start,
						ordered_extent->disk_len,
3063
						logical_len, logical_len,
3064
						compress_type, 0, 0,
Y
Yan Zheng 已提交
3065
						BTRFS_FILE_EXTENT_REG);
3066
		if (!ret)
3067
			btrfs_release_delalloc_bytes(fs_info,
3068 3069
						     ordered_extent->start,
						     ordered_extent->disk_len);
Y
Yan Zheng 已提交
3070
	}
J
Josef Bacik 已提交
3071 3072 3073
	unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
			   ordered_extent->file_offset, ordered_extent->len,
			   trans->transid);
3074
	if (ret < 0) {
3075
		btrfs_abort_transaction(trans, ret);
3076
		goto out;
3077
	}
3078

3079 3080 3081 3082 3083
	ret = add_pending_csums(trans, inode, &ordered_extent->list);
	if (ret) {
		btrfs_abort_transaction(trans, ret);
		goto out;
	}
3084

3085 3086 3087
	btrfs_ordered_update_i_size(inode, 0, ordered_extent);
	ret = btrfs_update_inode_fallback(trans, root, inode);
	if (ret) { /* -ENOMEM or corruption */
3088
		btrfs_abort_transaction(trans, ret);
3089
		goto out;
3090 3091
	}
	ret = 0;
3092
out:
3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105
	if (range_locked || clear_new_delalloc_bytes) {
		unsigned int clear_bits = 0;

		if (range_locked)
			clear_bits |= EXTENT_LOCKED;
		if (clear_new_delalloc_bytes)
			clear_bits |= EXTENT_DELALLOC_NEW;
		clear_extent_bit(&BTRFS_I(inode)->io_tree,
				 ordered_extent->file_offset,
				 ordered_extent->file_offset +
				 ordered_extent->len - 1,
				 clear_bits,
				 (clear_bits & EXTENT_LOCKED) ? 1 : 0,
3106
				 0, &cached_state);
3107 3108
	}

3109
	if (trans)
3110
		btrfs_end_transaction(trans);
J
Josef Bacik 已提交
3111

3112 3113 3114 3115 3116 3117 3118 3119
	if (ret || truncated) {
		u64 start, end;

		if (truncated)
			start = ordered_extent->file_offset + logical_len;
		else
			start = ordered_extent->file_offset;
		end = ordered_extent->file_offset + ordered_extent->len - 1;
3120
		clear_extent_uptodate(io_tree, start, end, NULL);
3121 3122

		/* Drop the cache for the part of the extent we didn't write. */
3123
		btrfs_drop_extent_cache(BTRFS_I(inode), start, end, 0);
3124

3125 3126 3127
		/*
		 * If the ordered extent had an IOERR or something else went
		 * wrong we need to return the space for this ordered extent
3128 3129
		 * back to the allocator.  We only free the extent in the
		 * truncated case if we didn't write out the extent at all.
3130
		 */
3131 3132
		if ((ret || !logical_len) &&
		    !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3133
		    !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
3134 3135
			btrfs_free_reserved_extent(fs_info,
						   ordered_extent->start,
3136
						   ordered_extent->disk_len, 1);
3137 3138 3139
	}


3140
	/*
3141 3142
	 * This needs to be done to make sure anybody waiting knows we are done
	 * updating everything for this ordered extent.
3143 3144 3145
	 */
	btrfs_remove_ordered_extent(inode, ordered_extent);

L
Liu Bo 已提交
3146
	/* for snapshot-aware defrag */
3147 3148 3149
	if (new) {
		if (ret) {
			free_sa_defrag_extent(new);
3150
			atomic_dec(&fs_info->defrag_running);
3151 3152 3153 3154
		} else {
			relink_file_extents(new);
		}
	}
L
Liu Bo 已提交
3155

3156 3157 3158 3159 3160
	/* once for us */
	btrfs_put_ordered_extent(ordered_extent);
	/* once for the tree */
	btrfs_put_ordered_extent(ordered_extent);

3161 3162 3163 3164 3165 3166 3167 3168
	return ret;
}

static void finish_ordered_fn(struct btrfs_work *work)
{
	struct btrfs_ordered_extent *ordered_extent;
	ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
	btrfs_finish_ordered_io(ordered_extent);
3169 3170
}

3171
static void btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
3172 3173
				struct extent_state *state, int uptodate)
{
3174
	struct inode *inode = page->mapping->host;
3175
	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3176
	struct btrfs_ordered_extent *ordered_extent = NULL;
3177 3178
	struct btrfs_workqueue *wq;
	btrfs_work_func_t func;
3179

3180 3181
	trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);

3182
	ClearPagePrivate2(page);
3183 3184
	if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
					    end - start + 1, uptodate))
3185
		return;
3186

3187
	if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
3188
		wq = fs_info->endio_freespace_worker;
3189 3190
		func = btrfs_freespace_write_helper;
	} else {
3191
		wq = fs_info->endio_write_workers;
3192 3193
		func = btrfs_endio_write_helper;
	}
3194

3195 3196 3197
	btrfs_init_work(&ordered_extent->work, func, finish_ordered_fn, NULL,
			NULL);
	btrfs_queue_work(wq, &ordered_extent->work);
3198 3199
}

3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212
static int __readpage_endio_check(struct inode *inode,
				  struct btrfs_io_bio *io_bio,
				  int icsum, struct page *page,
				  int pgoff, u64 start, size_t len)
{
	char *kaddr;
	u32 csum_expected;
	u32 csum = ~(u32)0;

	csum_expected = *(((u32 *)io_bio->csum) + icsum);

	kaddr = kmap_atomic(page);
	csum = btrfs_csum_data(kaddr + pgoff, csum,  len);
3213
	btrfs_csum_final(csum, (u8 *)&csum);
3214 3215 3216 3217 3218 3219
	if (csum != csum_expected)
		goto zeroit;

	kunmap_atomic(kaddr);
	return 0;
zeroit:
3220
	btrfs_print_data_csum_error(BTRFS_I(inode), start, csum, csum_expected,
3221
				    io_bio->mirror_num);
3222 3223 3224 3225 3226 3227
	memset(kaddr + pgoff, 1, len);
	flush_dcache_page(page);
	kunmap_atomic(kaddr);
	return -EIO;
}

C
Chris Mason 已提交
3228 3229
/*
 * when reads are done, we need to check csums to verify the data is correct
3230 3231
 * if there's a match, we allow the bio to finish.  If not, the code in
 * extent_io.c will try to find good copies for us.
C
Chris Mason 已提交
3232
 */
3233 3234 3235
static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
				      u64 phy_offset, struct page *page,
				      u64 start, u64 end, int mirror)
3236
{
M
Miao Xie 已提交
3237
	size_t offset = start - page_offset(page);
3238
	struct inode *inode = page->mapping->host;
3239
	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3240
	struct btrfs_root *root = BTRFS_I(inode)->root;
3241

3242 3243
	if (PageChecked(page)) {
		ClearPageChecked(page);
3244
		return 0;
3245
	}
3246 3247

	if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
3248
		return 0;
3249 3250

	if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
3251
	    test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
3252
		clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM);
3253
		return 0;
3254
	}
3255

3256
	phy_offset >>= inode->i_sb->s_blocksize_bits;
3257 3258
	return __readpage_endio_check(inode, io_bio, phy_offset, page, offset,
				      start, (size_t)(end - start + 1));
3259
}
3260

3261 3262 3263 3264 3265 3266 3267 3268 3269 3270
/*
 * btrfs_add_delayed_iput - perform a delayed iput on @inode
 *
 * @inode: The inode we want to perform iput on
 *
 * This function uses the generic vfs_inode::i_count to track whether we should
 * just decrement it (in case it's > 1) or if this is the last iput then link
 * the inode to the delayed iput machinery. Delayed iputs are processed at
 * transaction commit time/superblock commit/cleaner kthread.
 */
Y
Yan, Zheng 已提交
3271 3272
void btrfs_add_delayed_iput(struct inode *inode)
{
3273
	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3274
	struct btrfs_inode *binode = BTRFS_I(inode);
Y
Yan, Zheng 已提交
3275 3276 3277 3278 3279

	if (atomic_add_unless(&inode->i_count, -1, 1))
		return;

	spin_lock(&fs_info->delayed_iput_lock);
3280 3281
	ASSERT(list_empty(&binode->delayed_iput));
	list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
Y
Yan, Zheng 已提交
3282 3283 3284
	spin_unlock(&fs_info->delayed_iput_lock);
}

3285
void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
Y
Yan, Zheng 已提交
3286 3287 3288
{

	spin_lock(&fs_info->delayed_iput_lock);
3289 3290 3291 3292 3293
	while (!list_empty(&fs_info->delayed_iputs)) {
		struct btrfs_inode *inode;

		inode = list_first_entry(&fs_info->delayed_iputs,
				struct btrfs_inode, delayed_iput);
3294
		list_del_init(&inode->delayed_iput);
3295 3296 3297
		spin_unlock(&fs_info->delayed_iput_lock);
		iput(&inode->vfs_inode);
		spin_lock(&fs_info->delayed_iput_lock);
Y
Yan, Zheng 已提交
3298
	}
3299
	spin_unlock(&fs_info->delayed_iput_lock);
Y
Yan, Zheng 已提交
3300 3301
}

3302
/*
3303
 * This is called in transaction commit time. If there are no orphan
3304 3305 3306 3307 3308 3309
 * files in the subvolume, it removes orphan item and frees block_rsv
 * structure.
 */
void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
			      struct btrfs_root *root)
{
3310
	struct btrfs_fs_info *fs_info = root->fs_info;
3311
	struct btrfs_block_rsv *block_rsv;
3312 3313
	int ret;

3314
	if (atomic_read(&root->orphan_inodes) ||
3315 3316 3317
	    root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
		return;

3318
	spin_lock(&root->orphan_lock);
3319
	if (atomic_read(&root->orphan_inodes)) {
3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332
		spin_unlock(&root->orphan_lock);
		return;
	}

	if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
		spin_unlock(&root->orphan_lock);
		return;
	}

	block_rsv = root->orphan_block_rsv;
	root->orphan_block_rsv = NULL;
	spin_unlock(&root->orphan_lock);

3333
	if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state) &&
3334
	    btrfs_root_refs(&root->root_item) > 0) {
3335
		ret = btrfs_del_orphan_item(trans, fs_info->tree_root,
3336
					    root->root_key.objectid);
3337
		if (ret)
3338
			btrfs_abort_transaction(trans, ret);
3339
		else
3340 3341
			clear_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED,
				  &root->state);
3342 3343
	}

3344 3345
	if (block_rsv) {
		WARN_ON(block_rsv->size > 0);
3346
		btrfs_free_block_rsv(fs_info, block_rsv);
3347 3348 3349
	}
}

3350 3351 3352
/*
 * This creates an orphan entry for the given inode in case something goes
 * wrong in the middle of an unlink/truncate.
3353 3354 3355
 *
 * NOTE: caller of this function should reserve 5 units of metadata for
 *	 this function.
3356
 */
3357 3358
int btrfs_orphan_add(struct btrfs_trans_handle *trans,
		struct btrfs_inode *inode)
3359
{
3360 3361
	struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
	struct btrfs_root *root = inode->root;
3362 3363
	struct btrfs_block_rsv *block_rsv = NULL;
	int reserve = 0;
3364
	bool insert = false;
3365
	int ret;
3366

3367
	if (!root->orphan_block_rsv) {
3368 3369
		block_rsv = btrfs_alloc_block_rsv(fs_info,
						  BTRFS_BLOCK_RSV_TEMP);
3370 3371
		if (!block_rsv)
			return -ENOMEM;
3372
	}
3373

3374
	if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3375 3376
			      &inode->runtime_flags))
		insert = true;
3377

3378
	if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3379
			      &inode->runtime_flags))
3380
		reserve = 1;
3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392

	spin_lock(&root->orphan_lock);
	/* If someone has created ->orphan_block_rsv, be happy to use it. */
	if (!root->orphan_block_rsv) {
		root->orphan_block_rsv = block_rsv;
	} else if (block_rsv) {
		btrfs_free_block_rsv(fs_info, block_rsv);
		block_rsv = NULL;
	}

	if (insert)
		atomic_inc(&root->orphan_inodes);
3393
	spin_unlock(&root->orphan_lock);
3394

3395 3396 3397
	/* grab metadata reservation from transaction handle */
	if (reserve) {
		ret = btrfs_orphan_reserve_metadata(trans, inode);
3398 3399
		ASSERT(!ret);
		if (ret) {
3400 3401 3402 3403 3404
			/*
			 * dec doesn't need spin_lock as ->orphan_block_rsv
			 * would be released only if ->orphan_inodes is
			 * zero.
			 */
3405 3406
			atomic_dec(&root->orphan_inodes);
			clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3407
				  &inode->runtime_flags);
3408 3409
			if (insert)
				clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3410
					  &inode->runtime_flags);
3411 3412
			return ret;
		}
3413
	}
3414

3415
	/* insert an orphan item to track this unlinked/truncated file */
3416
	if (insert) {
3417
		ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
3418 3419 3420
		if (ret) {
			if (reserve) {
				clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3421
					  &inode->runtime_flags);
3422 3423
				btrfs_orphan_release_metadata(inode);
			}
3424 3425 3426 3427 3428 3429
			/*
			 * btrfs_orphan_commit_root may race with us and set
			 * ->orphan_block_rsv to zero, in order to avoid that,
			 * decrease ->orphan_inodes after everything is done.
			 */
			atomic_dec(&root->orphan_inodes);
3430
			if (ret != -EEXIST) {
3431
				clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3432
					  &inode->runtime_flags);
3433
				btrfs_abort_transaction(trans, ret);
3434 3435
				return ret;
			}
3436 3437
		}
		ret = 0;
3438 3439 3440
	}

	return 0;
3441 3442 3443 3444 3445 3446
}

/*
 * We have done the truncate/delete so we can go ahead and remove the orphan
 * item for this particular inode.
 */
3447
static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3448
			    struct btrfs_inode *inode)
3449
{
3450
	struct btrfs_root *root = inode->root;
3451
	int delete_item = 0;
3452 3453
	int ret = 0;

3454
	if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3455
			       &inode->runtime_flags))
3456
		delete_item = 1;
3457

3458 3459 3460
	if (delete_item && trans)
		ret = btrfs_del_orphan_item(trans, root, btrfs_ino(inode));

3461
	if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3462
			       &inode->runtime_flags))
3463
		btrfs_orphan_release_metadata(inode);
3464

3465 3466 3467 3468 3469 3470
	/*
	 * btrfs_orphan_commit_root may race with us and set ->orphan_block_rsv
	 * to zero, in order to avoid that, decrease ->orphan_inodes after
	 * everything is done.
	 */
	if (delete_item)
3471
		atomic_dec(&root->orphan_inodes);
3472

3473
	return ret;
3474 3475 3476 3477 3478 3479
}

/*
 * this cleans up any orphans that may be left on the list from the last use
 * of this root.
 */
3480
int btrfs_orphan_cleanup(struct btrfs_root *root)
3481
{
3482
	struct btrfs_fs_info *fs_info = root->fs_info;
3483 3484 3485 3486 3487
	struct btrfs_path *path;
	struct extent_buffer *leaf;
	struct btrfs_key key, found_key;
	struct btrfs_trans_handle *trans;
	struct inode *inode;
3488
	u64 last_objectid = 0;
3489 3490
	int ret = 0, nr_unlink = 0, nr_truncate = 0;

3491
	if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3492
		return 0;
3493 3494

	path = btrfs_alloc_path();
3495 3496 3497 3498
	if (!path) {
		ret = -ENOMEM;
		goto out;
	}
3499
	path->reada = READA_BACK;
3500 3501

	key.objectid = BTRFS_ORPHAN_OBJECTID;
3502
	key.type = BTRFS_ORPHAN_ITEM_KEY;
3503 3504 3505 3506
	key.offset = (u64)-1;

	while (1) {
		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3507 3508
		if (ret < 0)
			goto out;
3509 3510 3511

		/*
		 * if ret == 0 means we found what we were searching for, which
L
Lucas De Marchi 已提交
3512
		 * is weird, but possible, so only screw with path if we didn't
3513 3514 3515
		 * find the key and see if we have stuff that matches
		 */
		if (ret > 0) {
3516
			ret = 0;
3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528
			if (path->slots[0] == 0)
				break;
			path->slots[0]--;
		}

		/* pull out the item */
		leaf = path->nodes[0];
		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);

		/* make sure the item matches what we want */
		if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
			break;
3529
		if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3530 3531 3532
			break;

		/* release the path since we're done with it */
3533
		btrfs_release_path(path);
3534 3535 3536 3537 3538 3539

		/*
		 * this is where we are basically btrfs_lookup, without the
		 * crossing root thing.  we store the inode number in the
		 * offset of the orphan item.
		 */
3540 3541

		if (found_key.offset == last_objectid) {
3542 3543
			btrfs_err(fs_info,
				  "Error removing orphan entry, stopping orphan cleanup");
3544 3545 3546 3547 3548 3549
			ret = -EINVAL;
			goto out;
		}

		last_objectid = found_key.offset;

3550 3551 3552
		found_key.objectid = found_key.offset;
		found_key.type = BTRFS_INODE_ITEM_KEY;
		found_key.offset = 0;
3553
		inode = btrfs_iget(fs_info->sb, &found_key, root, NULL);
3554
		ret = PTR_ERR_OR_ZERO(inode);
3555
		if (ret && ret != -ENOENT)
3556
			goto out;
3557

3558
		if (ret == -ENOENT && root == fs_info->tree_root) {
3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589
			struct btrfs_root *dead_root;
			struct btrfs_fs_info *fs_info = root->fs_info;
			int is_dead_root = 0;

			/*
			 * this is an orphan in the tree root. Currently these
			 * could come from 2 sources:
			 *  a) a snapshot deletion in progress
			 *  b) a free space cache inode
			 * We need to distinguish those two, as the snapshot
			 * orphan must not get deleted.
			 * find_dead_roots already ran before us, so if this
			 * is a snapshot deletion, we should find the root
			 * in the dead_roots list
			 */
			spin_lock(&fs_info->trans_lock);
			list_for_each_entry(dead_root, &fs_info->dead_roots,
					    root_list) {
				if (dead_root->root_key.objectid ==
				    found_key.objectid) {
					is_dead_root = 1;
					break;
				}
			}
			spin_unlock(&fs_info->trans_lock);
			if (is_dead_root) {
				/* prevent this orphan from being found again */
				key.offset = found_key.objectid - 1;
				continue;
			}
		}
3590
		/*
J
Josef Bacik 已提交
3591 3592
		 * Inode is already gone but the orphan item is still there,
		 * kill the orphan item.
3593
		 */
3594
		if (ret == -ENOENT) {
J
Josef Bacik 已提交
3595
			trans = btrfs_start_transaction(root, 1);
3596 3597 3598 3599
			if (IS_ERR(trans)) {
				ret = PTR_ERR(trans);
				goto out;
			}
3600 3601
			btrfs_debug(fs_info, "auto deleting %Lu",
				    found_key.objectid);
J
Josef Bacik 已提交
3602 3603
			ret = btrfs_del_orphan_item(trans, root,
						    found_key.objectid);
3604
			btrfs_end_transaction(trans);
3605 3606
			if (ret)
				goto out;
3607 3608 3609
			continue;
		}

J
Josef Bacik 已提交
3610 3611 3612 3613
		/*
		 * add this inode to the orphan list so btrfs_orphan_del does
		 * the proper thing when we hit it
		 */
3614 3615
		set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
			&BTRFS_I(inode)->runtime_flags);
3616
		atomic_inc(&root->orphan_inodes);
J
Josef Bacik 已提交
3617

3618 3619
		/* if we have links, this was a truncate, lets do that */
		if (inode->i_nlink) {
3620
			if (WARN_ON(!S_ISREG(inode->i_mode))) {
3621 3622 3623
				iput(inode);
				continue;
			}
3624
			nr_truncate++;
3625 3626 3627 3628

			/* 1 for the orphan item deletion. */
			trans = btrfs_start_transaction(root, 1);
			if (IS_ERR(trans)) {
3629
				iput(inode);
3630 3631 3632
				ret = PTR_ERR(trans);
				goto out;
			}
3633
			ret = btrfs_orphan_add(trans, BTRFS_I(inode));
3634
			btrfs_end_transaction(trans);
3635 3636
			if (ret) {
				iput(inode);
3637
				goto out;
3638
			}
3639

3640
			ret = btrfs_truncate(inode, false);
3641
			if (ret)
3642
				btrfs_orphan_del(NULL, BTRFS_I(inode));
3643 3644 3645 3646 3647 3648
		} else {
			nr_unlink++;
		}

		/* this will do delete_inode and everything for us */
		iput(inode);
3649 3650
		if (ret)
			goto out;
3651
	}
3652 3653 3654
	/* release the path since we're done with it */
	btrfs_release_path(path);

3655 3656 3657
	root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;

	if (root->orphan_block_rsv)
3658
		btrfs_block_rsv_release(fs_info, root->orphan_block_rsv,
3659 3660
					(u64)-1);

3661 3662
	if (root->orphan_block_rsv ||
	    test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3663
		trans = btrfs_join_transaction(root);
3664
		if (!IS_ERR(trans))
3665
			btrfs_end_transaction(trans);
3666
	}
3667 3668

	if (nr_unlink)
3669
		btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3670
	if (nr_truncate)
3671
		btrfs_debug(fs_info, "truncated %d orphans", nr_truncate);
3672 3673 3674

out:
	if (ret)
3675
		btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3676 3677
	btrfs_free_path(path);
	return ret;
3678 3679
}

3680 3681 3682 3683 3684 3685 3686
/*
 * very simple check to peek ahead in the leaf looking for xattrs.  If we
 * don't find any xattrs, we know there can't be any acls.
 *
 * slot is the slot the inode is in, objectid is the objectid of the inode
 */
static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3687 3688
					  int slot, u64 objectid,
					  int *first_xattr_slot)
3689 3690 3691
{
	u32 nritems = btrfs_header_nritems(leaf);
	struct btrfs_key found_key;
3692 3693
	static u64 xattr_access = 0;
	static u64 xattr_default = 0;
3694 3695
	int scanned = 0;

3696
	if (!xattr_access) {
3697 3698 3699 3700
		xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
					strlen(XATTR_NAME_POSIX_ACL_ACCESS));
		xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
					strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3701 3702
	}

3703
	slot++;
3704
	*first_xattr_slot = -1;
3705 3706 3707 3708 3709 3710 3711 3712
	while (slot < nritems) {
		btrfs_item_key_to_cpu(leaf, &found_key, slot);

		/* we found a different objectid, there must not be acls */
		if (found_key.objectid != objectid)
			return 0;

		/* we found an xattr, assume we've got an acl */
3713
		if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3714 3715
			if (*first_xattr_slot == -1)
				*first_xattr_slot = slot;
3716 3717 3718 3719
			if (found_key.offset == xattr_access ||
			    found_key.offset == xattr_default)
				return 1;
		}
3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743

		/*
		 * we found a key greater than an xattr key, there can't
		 * be any acls later on
		 */
		if (found_key.type > BTRFS_XATTR_ITEM_KEY)
			return 0;

		slot++;
		scanned++;

		/*
		 * it goes inode, inode backrefs, xattrs, extents,
		 * so if there are a ton of hard links to an inode there can
		 * be a lot of backrefs.  Don't waste time searching too hard,
		 * this is just an optimization
		 */
		if (scanned >= 8)
			break;
	}
	/* we hit the end of the leaf before we found an xattr or
	 * something larger than an xattr.  We have to assume the inode
	 * has acls
	 */
3744 3745
	if (*first_xattr_slot == -1)
		*first_xattr_slot = slot;
3746 3747 3748
	return 1;
}

C
Chris Mason 已提交
3749 3750 3751
/*
 * read an inode from the btree into the in-memory inode
 */
3752
static int btrfs_read_locked_inode(struct inode *inode)
C
Chris Mason 已提交
3753
{
3754
	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
C
Chris Mason 已提交
3755
	struct btrfs_path *path;
3756
	struct extent_buffer *leaf;
C
Chris Mason 已提交
3757 3758 3759
	struct btrfs_inode_item *inode_item;
	struct btrfs_root *root = BTRFS_I(inode)->root;
	struct btrfs_key location;
3760
	unsigned long ptr;
3761
	int maybe_acls;
J
Josef Bacik 已提交
3762
	u32 rdev;
C
Chris Mason 已提交
3763
	int ret;
3764
	bool filled = false;
3765
	int first_xattr_slot;
3766 3767 3768 3769

	ret = btrfs_fill_inode(inode, &rdev);
	if (!ret)
		filled = true;
C
Chris Mason 已提交
3770 3771

	path = btrfs_alloc_path();
3772 3773
	if (!path) {
		ret = -ENOMEM;
3774
		goto make_bad;
3775
	}
3776

C
Chris Mason 已提交
3777
	memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
C
Chris Mason 已提交
3778

C
Chris Mason 已提交
3779
	ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3780 3781 3782
	if (ret) {
		if (ret > 0)
			ret = -ENOENT;
C
Chris Mason 已提交
3783
		goto make_bad;
3784
	}
C
Chris Mason 已提交
3785

3786
	leaf = path->nodes[0];
3787 3788

	if (filled)
3789
		goto cache_index;
3790

3791 3792 3793
	inode_item = btrfs_item_ptr(leaf, path->slots[0],
				    struct btrfs_inode_item);
	inode->i_mode = btrfs_inode_mode(leaf, inode_item);
M
Miklos Szeredi 已提交
3794
	set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3795 3796
	i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
	i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3797
	btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
3798

3799 3800
	inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
	inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3801

3802 3803
	inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
	inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3804

3805 3806
	inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
	inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3807

3808 3809 3810 3811
	BTRFS_I(inode)->i_otime.tv_sec =
		btrfs_timespec_sec(leaf, &inode_item->otime);
	BTRFS_I(inode)->i_otime.tv_nsec =
		btrfs_timespec_nsec(leaf, &inode_item->otime);
3812

3813
	inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3814
	BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
J
Josef Bacik 已提交
3815 3816
	BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);

3817 3818
	inode_set_iversion_queried(inode,
				   btrfs_inode_sequence(leaf, inode_item));
3819 3820 3821 3822 3823 3824 3825 3826
	inode->i_generation = BTRFS_I(inode)->generation;
	inode->i_rdev = 0;
	rdev = btrfs_inode_rdev(leaf, inode_item);

	BTRFS_I(inode)->index_cnt = (u64)-1;
	BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);

cache_index:
J
Josef Bacik 已提交
3827 3828 3829 3830 3831
	/*
	 * If we were modified in the current generation and evicted from memory
	 * and then re-read we need to do a full sync since we don't have any
	 * idea about which extents were modified before we were evicted from
	 * cache.
3832 3833 3834
	 *
	 * This is required for both inode re-read from disk and delayed inode
	 * in delayed_nodes_tree.
J
Josef Bacik 已提交
3835
	 */
3836
	if (BTRFS_I(inode)->last_trans == fs_info->generation)
J
Josef Bacik 已提交
3837 3838 3839
		set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
			&BTRFS_I(inode)->runtime_flags);

3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862
	/*
	 * We don't persist the id of the transaction where an unlink operation
	 * against the inode was last made. So here we assume the inode might
	 * have been evicted, and therefore the exact value of last_unlink_trans
	 * lost, and set it to last_trans to avoid metadata inconsistencies
	 * between the inode and its parent if the inode is fsync'ed and the log
	 * replayed. For example, in the scenario:
	 *
	 * touch mydir/foo
	 * ln mydir/foo mydir/bar
	 * sync
	 * unlink mydir/bar
	 * echo 2 > /proc/sys/vm/drop_caches   # evicts inode
	 * xfs_io -c fsync mydir/foo
	 * <power failure>
	 * mount fs, triggers fsync log replay
	 *
	 * We must make sure that when we fsync our inode foo we also log its
	 * parent inode, otherwise after log replay the parent still has the
	 * dentry with the "bar" name but our inode foo has a link count of 1
	 * and doesn't have an inode ref with the name "bar" anymore.
	 *
	 * Setting last_unlink_trans to last_trans is a pessimistic approach,
3863
	 * but it guarantees correctness at the expense of occasional full
3864 3865 3866 3867 3868
	 * transaction commits on fsync if our inode is a directory, or if our
	 * inode is not a directory, logging its parent unnecessarily.
	 */
	BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;

3869 3870 3871 3872 3873 3874
	path->slots[0]++;
	if (inode->i_nlink != 1 ||
	    path->slots[0] >= btrfs_header_nritems(leaf))
		goto cache_acl;

	btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3875
	if (location.objectid != btrfs_ino(BTRFS_I(inode)))
3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890
		goto cache_acl;

	ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
	if (location.type == BTRFS_INODE_REF_KEY) {
		struct btrfs_inode_ref *ref;

		ref = (struct btrfs_inode_ref *)ptr;
		BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
	} else if (location.type == BTRFS_INODE_EXTREF_KEY) {
		struct btrfs_inode_extref *extref;

		extref = (struct btrfs_inode_extref *)ptr;
		BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
								     extref);
	}
3891
cache_acl:
3892 3893 3894 3895
	/*
	 * try to precache a NULL acl entry for files that don't have
	 * any xattrs or acls
	 */
L
Li Zefan 已提交
3896
	maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3897
			btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
3898 3899 3900 3901
	if (first_xattr_slot != -1) {
		path->slots[0] = first_xattr_slot;
		ret = btrfs_load_inode_props(inode, path);
		if (ret)
3902
			btrfs_err(fs_info,
3903
				  "error loading props for ino %llu (root %llu): %d",
3904
				  btrfs_ino(BTRFS_I(inode)),
3905 3906 3907 3908
				  root->root_key.objectid, ret);
	}
	btrfs_free_path(path);

3909 3910
	if (!maybe_acls)
		cache_no_acl(inode);
3911

C
Chris Mason 已提交
3912 3913 3914
	switch (inode->i_mode & S_IFMT) {
	case S_IFREG:
		inode->i_mapping->a_ops = &btrfs_aops;
3915
		BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
C
Chris Mason 已提交
3916 3917 3918 3919 3920
		inode->i_fop = &btrfs_file_operations;
		inode->i_op = &btrfs_file_inode_operations;
		break;
	case S_IFDIR:
		inode->i_fop = &btrfs_dir_file_operations;
3921
		inode->i_op = &btrfs_dir_inode_operations;
C
Chris Mason 已提交
3922 3923 3924
		break;
	case S_IFLNK:
		inode->i_op = &btrfs_symlink_inode_operations;
3925
		inode_nohighmem(inode);
C
Chris Mason 已提交
3926 3927
		inode->i_mapping->a_ops = &btrfs_symlink_aops;
		break;
J
Josef Bacik 已提交
3928
	default:
J
Jim Owens 已提交
3929
		inode->i_op = &btrfs_special_inode_operations;
J
Josef Bacik 已提交
3930 3931
		init_special_inode(inode, inode->i_mode, rdev);
		break;
C
Chris Mason 已提交
3932
	}
3933 3934

	btrfs_update_iflags(inode);
3935
	return 0;
C
Chris Mason 已提交
3936 3937 3938 3939

make_bad:
	btrfs_free_path(path);
	make_bad_inode(inode);
3940
	return ret;
C
Chris Mason 已提交
3941 3942
}

C
Chris Mason 已提交
3943 3944 3945
/*
 * given a leaf and an inode, copy the inode fields into the leaf
 */
3946 3947
static void fill_inode_item(struct btrfs_trans_handle *trans,
			    struct extent_buffer *leaf,
3948
			    struct btrfs_inode_item *item,
C
Chris Mason 已提交
3949 3950
			    struct inode *inode)
{
3951 3952 3953
	struct btrfs_map_token token;

	btrfs_init_map_token(&token);
3954

3955 3956 3957 3958 3959 3960
	btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
	btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
	btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
				   &token);
	btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
	btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3961

3962
	btrfs_set_token_timespec_sec(leaf, &item->atime,
3963
				     inode->i_atime.tv_sec, &token);
3964
	btrfs_set_token_timespec_nsec(leaf, &item->atime,
3965
				      inode->i_atime.tv_nsec, &token);
3966

3967
	btrfs_set_token_timespec_sec(leaf, &item->mtime,
3968
				     inode->i_mtime.tv_sec, &token);
3969
	btrfs_set_token_timespec_nsec(leaf, &item->mtime,
3970
				      inode->i_mtime.tv_nsec, &token);
3971

3972
	btrfs_set_token_timespec_sec(leaf, &item->ctime,
3973
				     inode->i_ctime.tv_sec, &token);
3974
	btrfs_set_token_timespec_nsec(leaf, &item->ctime,
3975
				      inode->i_ctime.tv_nsec, &token);
3976

3977 3978 3979 3980 3981
	btrfs_set_token_timespec_sec(leaf, &item->otime,
				     BTRFS_I(inode)->i_otime.tv_sec, &token);
	btrfs_set_token_timespec_nsec(leaf, &item->otime,
				      BTRFS_I(inode)->i_otime.tv_nsec, &token);

3982 3983 3984 3985
	btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
				     &token);
	btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
					 &token);
3986 3987
	btrfs_set_token_inode_sequence(leaf, item, inode_peek_iversion(inode),
				       &token);
3988 3989 3990 3991
	btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
	btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
	btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
	btrfs_set_token_inode_block_group(leaf, item, 0, &token);
C
Chris Mason 已提交
3992 3993
}

C
Chris Mason 已提交
3994 3995 3996
/*
 * copy everything in the in-memory inode into the btree.
 */
3997
static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
C
Chris Mason 已提交
3998
				struct btrfs_root *root, struct inode *inode)
C
Chris Mason 已提交
3999 4000 4001
{
	struct btrfs_inode_item *inode_item;
	struct btrfs_path *path;
4002
	struct extent_buffer *leaf;
C
Chris Mason 已提交
4003 4004 4005
	int ret;

	path = btrfs_alloc_path();
4006 4007 4008
	if (!path)
		return -ENOMEM;

4009
	path->leave_spinning = 1;
4010 4011
	ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
				 1);
C
Chris Mason 已提交
4012 4013 4014 4015 4016 4017
	if (ret) {
		if (ret > 0)
			ret = -ENOENT;
		goto failed;
	}

4018 4019
	leaf = path->nodes[0];
	inode_item = btrfs_item_ptr(leaf, path->slots[0],
4020
				    struct btrfs_inode_item);
C
Chris Mason 已提交
4021

4022
	fill_inode_item(trans, leaf, inode_item, inode);
4023
	btrfs_mark_buffer_dirty(leaf);
4024
	btrfs_set_inode_last_trans(trans, inode);
C
Chris Mason 已提交
4025 4026 4027 4028 4029 4030
	ret = 0;
failed:
	btrfs_free_path(path);
	return ret;
}

4031 4032 4033 4034 4035 4036
/*
 * copy everything in the in-memory inode into the btree.
 */
noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
				struct btrfs_root *root, struct inode *inode)
{
4037
	struct btrfs_fs_info *fs_info = root->fs_info;
4038 4039 4040 4041 4042 4043 4044 4045 4046
	int ret;

	/*
	 * If the inode is a free space inode, we can deadlock during commit
	 * if we put it into the delayed code.
	 *
	 * The data relocation inode should also be directly updated
	 * without delay
	 */
4047
	if (!btrfs_is_free_space_inode(BTRFS_I(inode))
4048
	    && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
4049
	    && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
4050 4051
		btrfs_update_root_times(trans, root);

4052 4053 4054 4055 4056 4057 4058 4059 4060
		ret = btrfs_delayed_update_inode(trans, root, inode);
		if (!ret)
			btrfs_set_inode_last_trans(trans, inode);
		return ret;
	}

	return btrfs_update_inode_item(trans, root, inode);
}

4061 4062 4063
noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
					 struct btrfs_root *root,
					 struct inode *inode)
4064 4065 4066 4067 4068 4069 4070 4071 4072
{
	int ret;

	ret = btrfs_update_inode(trans, root, inode);
	if (ret == -ENOSPC)
		return btrfs_update_inode_item(trans, root, inode);
	return ret;
}

C
Chris Mason 已提交
4073 4074 4075 4076 4077
/*
 * unlink helper that gets used here in inode.c and in the tree logging
 * recovery code.  It remove a link in a directory with a given name, and
 * also drops the back refs in the inode to the directory
 */
4078 4079
static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
				struct btrfs_root *root,
4080 4081
				struct btrfs_inode *dir,
				struct btrfs_inode *inode,
4082
				const char *name, int name_len)
C
Chris Mason 已提交
4083
{
4084
	struct btrfs_fs_info *fs_info = root->fs_info;
C
Chris Mason 已提交
4085 4086
	struct btrfs_path *path;
	int ret = 0;
4087
	struct extent_buffer *leaf;
C
Chris Mason 已提交
4088
	struct btrfs_dir_item *di;
4089
	struct btrfs_key key;
4090
	u64 index;
L
Li Zefan 已提交
4091 4092
	u64 ino = btrfs_ino(inode);
	u64 dir_ino = btrfs_ino(dir);
C
Chris Mason 已提交
4093 4094

	path = btrfs_alloc_path();
4095 4096
	if (!path) {
		ret = -ENOMEM;
4097
		goto out;
4098 4099
	}

4100
	path->leave_spinning = 1;
L
Li Zefan 已提交
4101
	di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
C
Chris Mason 已提交
4102 4103 4104 4105 4106 4107 4108 4109 4110
				    name, name_len, -1);
	if (IS_ERR(di)) {
		ret = PTR_ERR(di);
		goto err;
	}
	if (!di) {
		ret = -ENOENT;
		goto err;
	}
4111 4112
	leaf = path->nodes[0];
	btrfs_dir_item_key_to_cpu(leaf, di, &key);
C
Chris Mason 已提交
4113
	ret = btrfs_delete_one_dir_name(trans, root, path, di);
4114 4115
	if (ret)
		goto err;
4116
	btrfs_release_path(path);
C
Chris Mason 已提交
4117

4118 4119 4120 4121 4122 4123 4124 4125 4126 4127
	/*
	 * If we don't have dir index, we have to get it by looking up
	 * the inode ref, since we get the inode ref, remove it directly,
	 * it is unnecessary to do delayed deletion.
	 *
	 * But if we have dir index, needn't search inode ref to get it.
	 * Since the inode ref is close to the inode item, it is better
	 * that we delay to delete it, and just do this deletion when
	 * we update the inode item.
	 */
4128
	if (inode->dir_index) {
4129 4130
		ret = btrfs_delayed_delete_inode_ref(inode);
		if (!ret) {
4131
			index = inode->dir_index;
4132 4133 4134 4135
			goto skip_backref;
		}
	}

L
Li Zefan 已提交
4136 4137
	ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
				  dir_ino, &index);
4138
	if (ret) {
4139
		btrfs_info(fs_info,
4140
			"failed to delete reference to %.*s, inode %llu parent %llu",
4141
			name_len, name, ino, dir_ino);
4142
		btrfs_abort_transaction(trans, ret);
4143 4144
		goto err;
	}
4145
skip_backref:
4146
	ret = btrfs_delete_delayed_dir_index(trans, fs_info, dir, index);
4147
	if (ret) {
4148
		btrfs_abort_transaction(trans, ret);
C
Chris Mason 已提交
4149
		goto err;
4150
	}
C
Chris Mason 已提交
4151

4152 4153
	ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
			dir_ino);
4154
	if (ret != 0 && ret != -ENOENT) {
4155
		btrfs_abort_transaction(trans, ret);
4156 4157
		goto err;
	}
4158

4159 4160
	ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
			index);
4161 4162
	if (ret == -ENOENT)
		ret = 0;
4163
	else if (ret)
4164
		btrfs_abort_transaction(trans, ret);
C
Chris Mason 已提交
4165 4166
err:
	btrfs_free_path(path);
4167 4168 4169
	if (ret)
		goto out;

4170
	btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
4171 4172 4173 4174 4175
	inode_inc_iversion(&inode->vfs_inode);
	inode_inc_iversion(&dir->vfs_inode);
	inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime =
		dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
	ret = btrfs_update_inode(trans, root, &dir->vfs_inode);
4176
out:
C
Chris Mason 已提交
4177 4178 4179
	return ret;
}

4180 4181
int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
		       struct btrfs_root *root,
4182
		       struct btrfs_inode *dir, struct btrfs_inode *inode,
4183 4184 4185 4186 4187
		       const char *name, int name_len)
{
	int ret;
	ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
	if (!ret) {
4188 4189
		drop_nlink(&inode->vfs_inode);
		ret = btrfs_update_inode(trans, root, &inode->vfs_inode);
4190 4191 4192
	}
	return ret;
}
C
Chris Mason 已提交
4193

4194 4195 4196
/*
 * helper to start transaction for unlink and rmdir.
 *
4197 4198 4199 4200
 * unlink and rmdir are special in btrfs, they do not always free space, so
 * if we cannot make our reservations the normal way try and see if there is
 * plenty of slack room in the global reserve to migrate, otherwise we cannot
 * allow the unlink to occur.
4201
 */
4202
static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
4203
{
4204
	struct btrfs_root *root = BTRFS_I(dir)->root;
4205

4206 4207 4208 4209 4210 4211 4212
	/*
	 * 1 for the possible orphan item
	 * 1 for the dir item
	 * 1 for the dir index
	 * 1 for the inode ref
	 * 1 for the inode
	 */
4213
	return btrfs_start_transaction_fallback_global_rsv(root, 5, 5);
4214 4215 4216 4217 4218 4219
}

static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
{
	struct btrfs_root *root = BTRFS_I(dir)->root;
	struct btrfs_trans_handle *trans;
4220
	struct inode *inode = d_inode(dentry);
4221 4222
	int ret;

4223
	trans = __unlink_start_trans(dir);
4224 4225
	if (IS_ERR(trans))
		return PTR_ERR(trans);
4226

4227 4228
	btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
			0);
4229

4230 4231 4232
	ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
			BTRFS_I(d_inode(dentry)), dentry->d_name.name,
			dentry->d_name.len);
4233 4234
	if (ret)
		goto out;
4235

4236
	if (inode->i_nlink == 0) {
4237
		ret = btrfs_orphan_add(trans, BTRFS_I(inode));
4238 4239
		if (ret)
			goto out;
4240
	}
4241

4242
out:
4243
	btrfs_end_transaction(trans);
4244
	btrfs_btree_balance_dirty(root->fs_info);
C
Chris Mason 已提交
4245 4246 4247
	return ret;
}

4248
static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4249 4250 4251 4252
			struct btrfs_root *root,
			struct inode *dir, u64 objectid,
			const char *name, int name_len)
{
4253
	struct btrfs_fs_info *fs_info = root->fs_info;
4254 4255 4256 4257 4258 4259
	struct btrfs_path *path;
	struct extent_buffer *leaf;
	struct btrfs_dir_item *di;
	struct btrfs_key key;
	u64 index;
	int ret;
4260
	u64 dir_ino = btrfs_ino(BTRFS_I(dir));
4261 4262 4263 4264 4265

	path = btrfs_alloc_path();
	if (!path)
		return -ENOMEM;

L
Li Zefan 已提交
4266
	di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4267
				   name, name_len, -1);
4268 4269 4270 4271 4272 4273 4274
	if (IS_ERR_OR_NULL(di)) {
		if (!di)
			ret = -ENOENT;
		else
			ret = PTR_ERR(di);
		goto out;
	}
4275 4276 4277 4278 4279

	leaf = path->nodes[0];
	btrfs_dir_item_key_to_cpu(leaf, di, &key);
	WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
	ret = btrfs_delete_one_dir_name(trans, root, path, di);
4280
	if (ret) {
4281
		btrfs_abort_transaction(trans, ret);
4282 4283
		goto out;
	}
4284
	btrfs_release_path(path);
4285

4286 4287 4288
	ret = btrfs_del_root_ref(trans, fs_info, objectid,
				 root->root_key.objectid, dir_ino,
				 &index, name, name_len);
4289
	if (ret < 0) {
4290
		if (ret != -ENOENT) {
4291
			btrfs_abort_transaction(trans, ret);
4292 4293
			goto out;
		}
L
Li Zefan 已提交
4294
		di = btrfs_search_dir_index_item(root, path, dir_ino,
4295
						 name, name_len);
4296 4297 4298 4299 4300
		if (IS_ERR_OR_NULL(di)) {
			if (!di)
				ret = -ENOENT;
			else
				ret = PTR_ERR(di);
4301
			btrfs_abort_transaction(trans, ret);
4302 4303
			goto out;
		}
4304 4305 4306

		leaf = path->nodes[0];
		btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4307
		btrfs_release_path(path);
4308 4309
		index = key.offset;
	}
4310
	btrfs_release_path(path);
4311

4312
	ret = btrfs_delete_delayed_dir_index(trans, fs_info, BTRFS_I(dir), index);
4313
	if (ret) {
4314
		btrfs_abort_transaction(trans, ret);
4315 4316
		goto out;
	}
4317

4318
	btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
4319
	inode_inc_iversion(dir);
4320
	dir->i_mtime = dir->i_ctime = current_time(dir);
4321
	ret = btrfs_update_inode_fallback(trans, root, dir);
4322
	if (ret)
4323
		btrfs_abort_transaction(trans, ret);
4324
out:
4325
	btrfs_free_path(path);
4326
	return ret;
4327 4328
}

4329 4330 4331 4332
/*
 * Helper to check if the subvolume references other subvolumes or if it's
 * default.
 */
4333
static noinline int may_destroy_subvol(struct btrfs_root *root)
4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383
{
	struct btrfs_fs_info *fs_info = root->fs_info;
	struct btrfs_path *path;
	struct btrfs_dir_item *di;
	struct btrfs_key key;
	u64 dir_id;
	int ret;

	path = btrfs_alloc_path();
	if (!path)
		return -ENOMEM;

	/* Make sure this root isn't set as the default subvol */
	dir_id = btrfs_super_root_dir(fs_info->super_copy);
	di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
				   dir_id, "default", 7, 0);
	if (di && !IS_ERR(di)) {
		btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
		if (key.objectid == root->root_key.objectid) {
			ret = -EPERM;
			btrfs_err(fs_info,
				  "deleting default subvolume %llu is not allowed",
				  key.objectid);
			goto out;
		}
		btrfs_release_path(path);
	}

	key.objectid = root->root_key.objectid;
	key.type = BTRFS_ROOT_REF_KEY;
	key.offset = (u64)-1;

	ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
	if (ret < 0)
		goto out;
	BUG_ON(ret == 0);

	ret = 0;
	if (path->slots[0] > 0) {
		path->slots[0]--;
		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
		if (key.objectid == root->root_key.objectid &&
		    key.type == BTRFS_ROOT_REF_KEY)
			ret = -ENOTEMPTY;
	}
out:
	btrfs_free_path(path);
	return ret;
}

4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522
int btrfs_delete_subvolume(struct inode *dir, struct dentry *dentry)
{
	struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb);
	struct btrfs_root *root = BTRFS_I(dir)->root;
	struct inode *inode = d_inode(dentry);
	struct btrfs_root *dest = BTRFS_I(inode)->root;
	struct btrfs_trans_handle *trans;
	struct btrfs_block_rsv block_rsv;
	u64 root_flags;
	u64 qgroup_reserved;
	int ret;
	int err;

	/*
	 * Don't allow to delete a subvolume with send in progress. This is
	 * inside the inode lock so the error handling that has to drop the bit
	 * again is not run concurrently.
	 */
	spin_lock(&dest->root_item_lock);
	root_flags = btrfs_root_flags(&dest->root_item);
	if (dest->send_in_progress == 0) {
		btrfs_set_root_flags(&dest->root_item,
				root_flags | BTRFS_ROOT_SUBVOL_DEAD);
		spin_unlock(&dest->root_item_lock);
	} else {
		spin_unlock(&dest->root_item_lock);
		btrfs_warn(fs_info,
			   "attempt to delete subvolume %llu during send",
			   dest->root_key.objectid);
		return -EPERM;
	}

	down_write(&fs_info->subvol_sem);

	err = may_destroy_subvol(dest);
	if (err)
		goto out_up_write;

	btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
	/*
	 * One for dir inode,
	 * two for dir entries,
	 * two for root ref/backref.
	 */
	err = btrfs_subvolume_reserve_metadata(root, &block_rsv,
					       5, &qgroup_reserved, true);
	if (err)
		goto out_up_write;

	trans = btrfs_start_transaction(root, 0);
	if (IS_ERR(trans)) {
		err = PTR_ERR(trans);
		goto out_release;
	}
	trans->block_rsv = &block_rsv;
	trans->bytes_reserved = block_rsv.size;

	btrfs_record_snapshot_destroy(trans, BTRFS_I(dir));

	ret = btrfs_unlink_subvol(trans, root, dir,
				dest->root_key.objectid,
				dentry->d_name.name,
				dentry->d_name.len);
	if (ret) {
		err = ret;
		btrfs_abort_transaction(trans, ret);
		goto out_end_trans;
	}

	btrfs_record_root_in_trans(trans, dest);

	memset(&dest->root_item.drop_progress, 0,
		sizeof(dest->root_item.drop_progress));
	dest->root_item.drop_level = 0;
	btrfs_set_root_refs(&dest->root_item, 0);

	if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
		ret = btrfs_insert_orphan_item(trans,
					fs_info->tree_root,
					dest->root_key.objectid);
		if (ret) {
			btrfs_abort_transaction(trans, ret);
			err = ret;
			goto out_end_trans;
		}
	}

	ret = btrfs_uuid_tree_rem(trans, fs_info, dest->root_item.uuid,
				  BTRFS_UUID_KEY_SUBVOL,
				  dest->root_key.objectid);
	if (ret && ret != -ENOENT) {
		btrfs_abort_transaction(trans, ret);
		err = ret;
		goto out_end_trans;
	}
	if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
		ret = btrfs_uuid_tree_rem(trans, fs_info,
					  dest->root_item.received_uuid,
					  BTRFS_UUID_KEY_RECEIVED_SUBVOL,
					  dest->root_key.objectid);
		if (ret && ret != -ENOENT) {
			btrfs_abort_transaction(trans, ret);
			err = ret;
			goto out_end_trans;
		}
	}

out_end_trans:
	trans->block_rsv = NULL;
	trans->bytes_reserved = 0;
	ret = btrfs_end_transaction(trans);
	if (ret && !err)
		err = ret;
	inode->i_flags |= S_DEAD;
out_release:
	btrfs_subvolume_release_metadata(fs_info, &block_rsv);
out_up_write:
	up_write(&fs_info->subvol_sem);
	if (err) {
		spin_lock(&dest->root_item_lock);
		root_flags = btrfs_root_flags(&dest->root_item);
		btrfs_set_root_flags(&dest->root_item,
				root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
		spin_unlock(&dest->root_item_lock);
	} else {
		d_invalidate(dentry);
		btrfs_invalidate_inodes(dest);
		ASSERT(dest->send_in_progress == 0);

		/* the last ref */
		if (dest->ino_cache_inode) {
			iput(dest->ino_cache_inode);
			dest->ino_cache_inode = NULL;
		}
	}

	return err;
}

C
Chris Mason 已提交
4523 4524
static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
{
4525
	struct inode *inode = d_inode(dentry);
4526
	int err = 0;
C
Chris Mason 已提交
4527 4528
	struct btrfs_root *root = BTRFS_I(dir)->root;
	struct btrfs_trans_handle *trans;
4529
	u64 last_unlink_trans;
C
Chris Mason 已提交
4530

4531
	if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
Y
Yan 已提交
4532
		return -ENOTEMPTY;
4533
	if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID)
4534
		return -EPERM;
Y
Yan 已提交
4535

4536
	trans = __unlink_start_trans(dir);
4537
	if (IS_ERR(trans))
4538 4539
		return PTR_ERR(trans);

4540
	if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4541 4542 4543 4544 4545 4546 4547
		err = btrfs_unlink_subvol(trans, root, dir,
					  BTRFS_I(inode)->location.objectid,
					  dentry->d_name.name,
					  dentry->d_name.len);
		goto out;
	}

4548
	err = btrfs_orphan_add(trans, BTRFS_I(inode));
4549
	if (err)
4550
		goto out;
4551

4552 4553
	last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;

C
Chris Mason 已提交
4554
	/* now the directory is empty */
4555 4556 4557
	err = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
			BTRFS_I(d_inode(dentry)), dentry->d_name.name,
			dentry->d_name.len);
4558
	if (!err) {
4559
		btrfs_i_size_write(BTRFS_I(inode), 0);
4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573
		/*
		 * Propagate the last_unlink_trans value of the deleted dir to
		 * its parent directory. This is to prevent an unrecoverable
		 * log tree in the case we do something like this:
		 * 1) create dir foo
		 * 2) create snapshot under dir foo
		 * 3) delete the snapshot
		 * 4) rmdir foo
		 * 5) mkdir foo
		 * 6) fsync foo or some file inside foo
		 */
		if (last_unlink_trans >= trans->transid)
			BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
	}
4574
out:
4575
	btrfs_end_transaction(trans);
4576
	btrfs_btree_balance_dirty(root->fs_info);
4577

C
Chris Mason 已提交
4578 4579 4580
	return err;
}

4581 4582 4583 4584
static int truncate_space_check(struct btrfs_trans_handle *trans,
				struct btrfs_root *root,
				u64 bytes_deleted)
{
4585
	struct btrfs_fs_info *fs_info = root->fs_info;
4586 4587
	int ret;

J
Josef Bacik 已提交
4588 4589 4590 4591
	/*
	 * This is only used to apply pressure to the enospc system, we don't
	 * intend to use this reservation at all.
	 */
4592
	bytes_deleted = btrfs_csum_bytes_to_leaves(fs_info, bytes_deleted);
4593 4594
	bytes_deleted *= fs_info->nodesize;
	ret = btrfs_block_rsv_add(root, &fs_info->trans_block_rsv,
4595
				  bytes_deleted, BTRFS_RESERVE_NO_FLUSH);
J
Josef Bacik 已提交
4596
	if (!ret) {
4597
		trace_btrfs_space_reservation(fs_info, "transaction",
J
Josef Bacik 已提交
4598 4599
					      trans->transid,
					      bytes_deleted, 1);
4600
		trans->bytes_reserved += bytes_deleted;
J
Josef Bacik 已提交
4601
	}
4602 4603 4604 4605
	return ret;

}

4606 4607 4608 4609 4610
/*
 * Return this if we need to call truncate_block for the last bit of the
 * truncate.
 */
#define NEED_TRUNCATE_BLOCK 1
4611

C
Chris Mason 已提交
4612 4613 4614
/*
 * this can truncate away extent items, csum items and directory items.
 * It starts at a high offset and removes keys until it can't find
C
Chris Mason 已提交
4615
 * any higher than new_size
C
Chris Mason 已提交
4616 4617 4618
 *
 * csum items that cross the new i_size are truncated to the new size
 * as well.
4619 4620 4621
 *
 * min_type is the minimum key type to truncate down to.  If set to 0, this
 * will kill all the items on this inode, including the INODE_ITEM_KEY.
C
Chris Mason 已提交
4622
 */
4623 4624 4625 4626
int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
			       struct btrfs_root *root,
			       struct inode *inode,
			       u64 new_size, u32 min_type)
C
Chris Mason 已提交
4627
{
4628
	struct btrfs_fs_info *fs_info = root->fs_info;
C
Chris Mason 已提交
4629
	struct btrfs_path *path;
4630
	struct extent_buffer *leaf;
C
Chris Mason 已提交
4631
	struct btrfs_file_extent_item *fi;
4632 4633
	struct btrfs_key key;
	struct btrfs_key found_key;
C
Chris Mason 已提交
4634
	u64 extent_start = 0;
4635
	u64 extent_num_bytes = 0;
4636
	u64 extent_offset = 0;
C
Chris Mason 已提交
4637
	u64 item_end = 0;
4638
	u64 last_size = new_size;
4639
	u32 found_type = (u8)-1;
C
Chris Mason 已提交
4640 4641
	int found_extent;
	int del_item;
4642 4643
	int pending_del_nr = 0;
	int pending_del_slot = 0;
4644
	int extent_type = -1;
4645 4646
	int ret;
	int err = 0;
4647
	u64 ino = btrfs_ino(BTRFS_I(inode));
4648
	u64 bytes_deleted = 0;
4649 4650 4651
	bool be_nice = false;
	bool should_throttle = false;
	bool should_end = false;
4652 4653

	BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
C
Chris Mason 已提交
4654

4655 4656 4657 4658
	/*
	 * for non-free space inodes and ref cows, we want to back off from
	 * time to time
	 */
4659
	if (!btrfs_is_free_space_inode(BTRFS_I(inode)) &&
4660
	    test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4661
		be_nice = true;
4662

4663 4664 4665
	path = btrfs_alloc_path();
	if (!path)
		return -ENOMEM;
4666
	path->reada = READA_BACK;
4667

J
Josef Bacik 已提交
4668 4669 4670 4671 4672
	/*
	 * We want to drop from the next block forward in case this new size is
	 * not block aligned since we will be keeping the last block of the
	 * extent just the way it is.
	 */
4673
	if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4674
	    root == fs_info->tree_root)
4675
		btrfs_drop_extent_cache(BTRFS_I(inode), ALIGN(new_size,
4676
					fs_info->sectorsize),
4677
					(u64)-1, 0);
4678

4679 4680 4681 4682 4683 4684 4685
	/*
	 * This function is also used to drop the items in the log tree before
	 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
	 * it is used to drop the loged items. So we shouldn't kill the delayed
	 * items.
	 */
	if (min_type == 0 && root == BTRFS_I(inode)->root)
4686
		btrfs_kill_delayed_inode_items(BTRFS_I(inode));
4687

L
Li Zefan 已提交
4688
	key.objectid = ino;
C
Chris Mason 已提交
4689
	key.offset = (u64)-1;
4690 4691
	key.type = (u8)-1;

4692
search_again:
4693 4694 4695 4696 4697
	/*
	 * with a 16K leaf size and 128MB extents, you can actually queue
	 * up a huge file in a single leaf.  Most of the time that
	 * bytes_deleted is > 0, it will be huge by the time we get here
	 */
4698
	if (be_nice && bytes_deleted > SZ_32M) {
4699
		if (btrfs_should_end_transaction(trans)) {
4700 4701 4702 4703 4704 4705
			err = -EAGAIN;
			goto error;
		}
	}


4706
	path->leave_spinning = 1;
4707
	ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4708 4709 4710 4711
	if (ret < 0) {
		err = ret;
		goto out;
	}
C
Chris Mason 已提交
4712

4713
	if (ret > 0) {
4714 4715 4716
		/* there are no items in the tree for us to truncate, we're
		 * done
		 */
4717 4718
		if (path->slots[0] == 0)
			goto out;
4719 4720 4721
		path->slots[0]--;
	}

C
Chris Mason 已提交
4722
	while (1) {
C
Chris Mason 已提交
4723
		fi = NULL;
4724 4725
		leaf = path->nodes[0];
		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4726
		found_type = found_key.type;
C
Chris Mason 已提交
4727

L
Li Zefan 已提交
4728
		if (found_key.objectid != ino)
C
Chris Mason 已提交
4729
			break;
4730

4731
		if (found_type < min_type)
C
Chris Mason 已提交
4732 4733
			break;

4734
		item_end = found_key.offset;
C
Chris Mason 已提交
4735
		if (found_type == BTRFS_EXTENT_DATA_KEY) {
4736
			fi = btrfs_item_ptr(leaf, path->slots[0],
C
Chris Mason 已提交
4737
					    struct btrfs_file_extent_item);
4738 4739
			extent_type = btrfs_file_extent_type(leaf, fi);
			if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4740
				item_end +=
4741
				    btrfs_file_extent_num_bytes(leaf, fi);
L
Liu Bo 已提交
4742 4743 4744 4745

				trace_btrfs_truncate_show_fi_regular(
					BTRFS_I(inode), leaf, fi,
					found_key.offset);
4746 4747
			} else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
				item_end += btrfs_file_extent_inline_len(leaf,
4748
							 path->slots[0], fi);
L
Liu Bo 已提交
4749 4750 4751 4752

				trace_btrfs_truncate_show_fi_inline(
					BTRFS_I(inode), leaf, fi, path->slots[0],
					found_key.offset);
C
Chris Mason 已提交
4753
			}
4754
			item_end--;
C
Chris Mason 已提交
4755
		}
4756 4757 4758
		if (found_type > min_type) {
			del_item = 1;
		} else {
4759
			if (item_end < new_size)
4760
				break;
4761 4762 4763 4764
			if (found_key.offset >= new_size)
				del_item = 1;
			else
				del_item = 0;
C
Chris Mason 已提交
4765 4766 4767
		}
		found_extent = 0;
		/* FIXME, shrink the extent if the ref count is only 1 */
4768 4769 4770 4771
		if (found_type != BTRFS_EXTENT_DATA_KEY)
			goto delete;

		if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
C
Chris Mason 已提交
4772
			u64 num_dec;
4773
			extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4774
			if (!del_item) {
4775 4776
				u64 orig_num_bytes =
					btrfs_file_extent_num_bytes(leaf, fi);
4777 4778
				extent_num_bytes = ALIGN(new_size -
						found_key.offset,
4779
						fs_info->sectorsize);
4780 4781 4782
				btrfs_set_file_extent_num_bytes(leaf, fi,
							 extent_num_bytes);
				num_dec = (orig_num_bytes -
C
Chris Mason 已提交
4783
					   extent_num_bytes);
4784 4785 4786
				if (test_bit(BTRFS_ROOT_REF_COWS,
					     &root->state) &&
				    extent_start != 0)
4787
					inode_sub_bytes(inode, num_dec);
4788
				btrfs_mark_buffer_dirty(leaf);
C
Chris Mason 已提交
4789
			} else {
4790 4791 4792
				extent_num_bytes =
					btrfs_file_extent_disk_num_bytes(leaf,
									 fi);
4793 4794 4795
				extent_offset = found_key.offset -
					btrfs_file_extent_offset(leaf, fi);

C
Chris Mason 已提交
4796
				/* FIXME blocksize != 4096 */
C
Chris Mason 已提交
4797
				num_dec = btrfs_file_extent_num_bytes(leaf, fi);
C
Chris Mason 已提交
4798 4799
				if (extent_start != 0) {
					found_extent = 1;
4800 4801
					if (test_bit(BTRFS_ROOT_REF_COWS,
						     &root->state))
4802
						inode_sub_bytes(inode, num_dec);
4803
				}
C
Chris Mason 已提交
4804
			}
C
Chris Mason 已提交
4805
		} else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
C
Chris Mason 已提交
4806 4807 4808 4809 4810 4811
			/*
			 * we can't truncate inline items that have had
			 * special encodings
			 */
			if (!del_item &&
			    btrfs_file_extent_encryption(leaf, fi) == 0 &&
4812 4813 4814 4815 4816 4817 4818 4819
			    btrfs_file_extent_other_encoding(leaf, fi) == 0 &&
			    btrfs_file_extent_compression(leaf, fi) == 0) {
				u32 size = (u32)(new_size - found_key.offset);

				btrfs_set_file_extent_ram_bytes(leaf, fi, size);
				size = btrfs_file_extent_calc_inline_size(size);
				btrfs_truncate_item(root->fs_info, path, size, 1);
			} else if (!del_item) {
4820
				/*
4821 4822
				 * We have to bail so the last_size is set to
				 * just before this extent.
4823
				 */
4824 4825 4826
				err = NEED_TRUNCATE_BLOCK;
				break;
			}
4827

4828
			if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4829
				inode_sub_bytes(inode, item_end + 1 - new_size);
C
Chris Mason 已提交
4830
		}
4831
delete:
4832 4833 4834 4835
		if (del_item)
			last_size = found_key.offset;
		else
			last_size = new_size;
C
Chris Mason 已提交
4836
		if (del_item) {
4837 4838 4839 4840 4841 4842 4843 4844 4845 4846
			if (!pending_del_nr) {
				/* no pending yet, add ourselves */
				pending_del_slot = path->slots[0];
				pending_del_nr = 1;
			} else if (pending_del_nr &&
				   path->slots[0] + 1 == pending_del_slot) {
				/* hop on the pending chunk */
				pending_del_nr++;
				pending_del_slot = path->slots[0];
			} else {
C
Chris Mason 已提交
4847
				BUG();
4848
			}
C
Chris Mason 已提交
4849 4850 4851
		} else {
			break;
		}
4852
		should_throttle = false;
4853

4854 4855
		if (found_extent &&
		    (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4856
		     root == fs_info->tree_root)) {
4857
			btrfs_set_path_blocking(path);
4858
			bytes_deleted += extent_num_bytes;
4859
			ret = btrfs_free_extent(trans, root, extent_start,
4860 4861
						extent_num_bytes, 0,
						btrfs_header_owner(leaf),
4862
						ino, extent_offset);
C
Chris Mason 已提交
4863
			BUG_ON(ret);
4864 4865
			if (btrfs_should_throttle_delayed_refs(trans, fs_info))
				btrfs_async_run_delayed_refs(fs_info,
4866 4867
					trans->delayed_ref_updates * 2,
					trans->transid, 0);
4868 4869 4870
			if (be_nice) {
				if (truncate_space_check(trans, root,
							 extent_num_bytes)) {
4871
					should_end = true;
4872 4873
				}
				if (btrfs_should_throttle_delayed_refs(trans,
4874
								       fs_info))
4875
					should_throttle = true;
4876
			}
C
Chris Mason 已提交
4877
		}
4878

4879 4880 4881 4882
		if (found_type == BTRFS_INODE_ITEM_KEY)
			break;

		if (path->slots[0] == 0 ||
4883
		    path->slots[0] != pending_del_slot ||
4884
		    should_throttle || should_end) {
4885 4886 4887 4888
			if (pending_del_nr) {
				ret = btrfs_del_items(trans, root, path,
						pending_del_slot,
						pending_del_nr);
4889
				if (ret) {
4890
					btrfs_abort_transaction(trans, ret);
4891 4892
					goto error;
				}
4893 4894
				pending_del_nr = 0;
			}
4895
			btrfs_release_path(path);
4896
			if (should_throttle) {
4897 4898 4899
				unsigned long updates = trans->delayed_ref_updates;
				if (updates) {
					trans->delayed_ref_updates = 0;
4900 4901
					ret = btrfs_run_delayed_refs(trans,
								   updates * 2);
4902 4903 4904 4905
					if (ret && !err)
						err = ret;
				}
			}
4906 4907 4908 4909 4910 4911 4912 4913
			/*
			 * if we failed to refill our space rsv, bail out
			 * and let the transaction restart
			 */
			if (should_end) {
				err = -EAGAIN;
				goto error;
			}
4914
			goto search_again;
4915 4916
		} else {
			path->slots[0]--;
4917
		}
C
Chris Mason 已提交
4918
	}
4919
out:
4920 4921 4922
	if (pending_del_nr) {
		ret = btrfs_del_items(trans, root, path, pending_del_slot,
				      pending_del_nr);
4923
		if (ret)
4924
			btrfs_abort_transaction(trans, ret);
4925
	}
4926
error:
4927 4928 4929 4930
	if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
		ASSERT(last_size >= new_size);
		if (!err && last_size > new_size)
			last_size = new_size;
4931
		btrfs_ordered_update_i_size(inode, last_size, NULL);
4932
	}
4933

C
Chris Mason 已提交
4934
	btrfs_free_path(path);
4935

4936
	if (be_nice && bytes_deleted > SZ_32M) {
4937 4938 4939
		unsigned long updates = trans->delayed_ref_updates;
		if (updates) {
			trans->delayed_ref_updates = 0;
4940
			ret = btrfs_run_delayed_refs(trans, updates * 2);
4941 4942 4943 4944
			if (ret && !err)
				err = ret;
		}
	}
4945
	return err;
C
Chris Mason 已提交
4946 4947 4948
}

/*
4949
 * btrfs_truncate_block - read, zero a chunk and write a block
J
Josef Bacik 已提交
4950 4951 4952 4953 4954 4955
 * @inode - inode that we're zeroing
 * @from - the offset to start zeroing
 * @len - the length to zero, 0 to zero the entire range respective to the
 *	offset
 * @front - zero up to the offset instead of from the offset on
 *
4956
 * This will find the block for the "from" offset and cow the block and zero the
J
Josef Bacik 已提交
4957
 * part we want to zero.  This is used with truncate and hole punching.
C
Chris Mason 已提交
4958
 */
4959
int btrfs_truncate_block(struct inode *inode, loff_t from, loff_t len,
J
Josef Bacik 已提交
4960
			int front)
C
Chris Mason 已提交
4961
{
4962
	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
J
Josef Bacik 已提交
4963
	struct address_space *mapping = inode->i_mapping;
4964 4965
	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
	struct btrfs_ordered_extent *ordered;
4966
	struct extent_state *cached_state = NULL;
4967
	struct extent_changeset *data_reserved = NULL;
4968
	char *kaddr;
4969
	u32 blocksize = fs_info->sectorsize;
4970
	pgoff_t index = from >> PAGE_SHIFT;
4971
	unsigned offset = from & (blocksize - 1);
C
Chris Mason 已提交
4972
	struct page *page;
4973
	gfp_t mask = btrfs_alloc_write_mask(mapping);
C
Chris Mason 已提交
4974
	int ret = 0;
4975 4976
	u64 block_start;
	u64 block_end;
C
Chris Mason 已提交
4977

4978 4979
	if (IS_ALIGNED(offset, blocksize) &&
	    (!len || IS_ALIGNED(len, blocksize)))
C
Chris Mason 已提交
4980
		goto out;
4981

J
Josef Bacik 已提交
4982 4983 4984
	block_start = round_down(from, blocksize);
	block_end = block_start + blocksize - 1;

4985
	ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
J
Josef Bacik 已提交
4986
					   block_start, blocksize);
4987 4988
	if (ret)
		goto out;
C
Chris Mason 已提交
4989

4990
again:
4991
	page = find_or_create_page(mapping, index, mask);
4992
	if (!page) {
4993
		btrfs_delalloc_release_space(inode, data_reserved,
4994 4995
					     block_start, blocksize, true);
		btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize, true);
4996
		ret = -ENOMEM;
C
Chris Mason 已提交
4997
		goto out;
4998
	}
4999

C
Chris Mason 已提交
5000
	if (!PageUptodate(page)) {
C
Chris Mason 已提交
5001
		ret = btrfs_readpage(NULL, page);
C
Chris Mason 已提交
5002
		lock_page(page);
5003 5004
		if (page->mapping != mapping) {
			unlock_page(page);
5005
			put_page(page);
5006 5007
			goto again;
		}
C
Chris Mason 已提交
5008 5009
		if (!PageUptodate(page)) {
			ret = -EIO;
5010
			goto out_unlock;
C
Chris Mason 已提交
5011 5012
		}
	}
5013
	wait_on_page_writeback(page);
5014

5015
	lock_extent_bits(io_tree, block_start, block_end, &cached_state);
5016 5017
	set_page_extent_mapped(page);

5018
	ordered = btrfs_lookup_ordered_extent(inode, block_start);
5019
	if (ordered) {
5020
		unlock_extent_cached(io_tree, block_start, block_end,
5021
				     &cached_state);
5022
		unlock_page(page);
5023
		put_page(page);
5024
		btrfs_start_ordered_extent(inode, ordered, 1);
5025 5026 5027 5028
		btrfs_put_ordered_extent(ordered);
		goto again;
	}

5029
	clear_extent_bit(&BTRFS_I(inode)->io_tree, block_start, block_end,
5030 5031
			  EXTENT_DIRTY | EXTENT_DELALLOC |
			  EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
5032
			  0, 0, &cached_state);
5033

5034
	ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
5035
					&cached_state, 0);
J
Josef Bacik 已提交
5036
	if (ret) {
5037
		unlock_extent_cached(io_tree, block_start, block_end,
5038
				     &cached_state);
J
Josef Bacik 已提交
5039 5040 5041
		goto out_unlock;
	}

5042
	if (offset != blocksize) {
J
Josef Bacik 已提交
5043
		if (!len)
5044
			len = blocksize - offset;
5045
		kaddr = kmap(page);
J
Josef Bacik 已提交
5046
		if (front)
5047 5048
			memset(kaddr + (block_start - page_offset(page)),
				0, offset);
J
Josef Bacik 已提交
5049
		else
5050 5051
			memset(kaddr + (block_start - page_offset(page)) +  offset,
				0, len);
5052 5053 5054
		flush_dcache_page(page);
		kunmap(page);
	}
5055
	ClearPageChecked(page);
5056
	set_page_dirty(page);
5057
	unlock_extent_cached(io_tree, block_start, block_end, &cached_state);
C
Chris Mason 已提交
5058

5059
out_unlock:
5060
	if (ret)
5061
		btrfs_delalloc_release_space(inode, data_reserved, block_start,
5062 5063
					     blocksize, true);
	btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize, (ret != 0));
C
Chris Mason 已提交
5064
	unlock_page(page);
5065
	put_page(page);
C
Chris Mason 已提交
5066
out:
5067
	extent_changeset_free(data_reserved);
C
Chris Mason 已提交
5068 5069 5070
	return ret;
}

5071 5072 5073
static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
			     u64 offset, u64 len)
{
5074
	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5075 5076 5077 5078 5079 5080 5081
	struct btrfs_trans_handle *trans;
	int ret;

	/*
	 * Still need to make sure the inode looks like it's been updated so
	 * that any holes get logged if we fsync.
	 */
5082 5083
	if (btrfs_fs_incompat(fs_info, NO_HOLES)) {
		BTRFS_I(inode)->last_trans = fs_info->generation;
5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099
		BTRFS_I(inode)->last_sub_trans = root->log_transid;
		BTRFS_I(inode)->last_log_commit = root->last_log_commit;
		return 0;
	}

	/*
	 * 1 - for the one we're dropping
	 * 1 - for the one we're adding
	 * 1 - for updating the inode.
	 */
	trans = btrfs_start_transaction(root, 3);
	if (IS_ERR(trans))
		return PTR_ERR(trans);

	ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
	if (ret) {
5100
		btrfs_abort_transaction(trans, ret);
5101
		btrfs_end_transaction(trans);
5102 5103 5104
		return ret;
	}

5105 5106
	ret = btrfs_insert_file_extent(trans, root, btrfs_ino(BTRFS_I(inode)),
			offset, 0, 0, len, 0, len, 0, 0, 0);
5107
	if (ret)
5108
		btrfs_abort_transaction(trans, ret);
5109 5110
	else
		btrfs_update_inode(trans, root, inode);
5111
	btrfs_end_transaction(trans);
5112 5113 5114
	return ret;
}

5115 5116 5117 5118 5119 5120
/*
 * This function puts in dummy file extents for the area we're creating a hole
 * for.  So if we are truncating this file to a larger size we need to insert
 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
 * the range between oldsize and size
 */
5121
int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
C
Chris Mason 已提交
5122
{
5123
	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
Y
Yan Zheng 已提交
5124 5125
	struct btrfs_root *root = BTRFS_I(inode)->root;
	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5126
	struct extent_map *em = NULL;
5127
	struct extent_state *cached_state = NULL;
J
Josef Bacik 已提交
5128
	struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
5129 5130
	u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
	u64 block_end = ALIGN(size, fs_info->sectorsize);
Y
Yan Zheng 已提交
5131 5132 5133
	u64 last_byte;
	u64 cur_offset;
	u64 hole_size;
J
Josef Bacik 已提交
5134
	int err = 0;
C
Chris Mason 已提交
5135

5136
	/*
5137 5138
	 * If our size started in the middle of a block we need to zero out the
	 * rest of the block before we expand the i_size, otherwise we could
5139 5140
	 * expose stale data.
	 */
5141
	err = btrfs_truncate_block(inode, oldsize, 0, 0);
5142 5143 5144
	if (err)
		return err;

Y
Yan Zheng 已提交
5145 5146 5147 5148 5149
	if (size <= hole_start)
		return 0;

	while (1) {
		struct btrfs_ordered_extent *ordered;
5150

5151
		lock_extent_bits(io_tree, hole_start, block_end - 1,
5152
				 &cached_state);
5153
		ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), hole_start,
5154
						     block_end - hole_start);
Y
Yan Zheng 已提交
5155 5156
		if (!ordered)
			break;
5157
		unlock_extent_cached(io_tree, hole_start, block_end - 1,
5158
				     &cached_state);
5159
		btrfs_start_ordered_extent(inode, ordered, 1);
Y
Yan Zheng 已提交
5160 5161
		btrfs_put_ordered_extent(ordered);
	}
C
Chris Mason 已提交
5162

Y
Yan Zheng 已提交
5163 5164
	cur_offset = hole_start;
	while (1) {
5165
		em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, cur_offset,
Y
Yan Zheng 已提交
5166
				block_end - cur_offset, 0);
5167 5168
		if (IS_ERR(em)) {
			err = PTR_ERR(em);
5169
			em = NULL;
5170 5171
			break;
		}
Y
Yan Zheng 已提交
5172
		last_byte = min(extent_map_end(em), block_end);
5173
		last_byte = ALIGN(last_byte, fs_info->sectorsize);
5174
		if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
J
Josef Bacik 已提交
5175
			struct extent_map *hole_em;
Y
Yan Zheng 已提交
5176
			hole_size = last_byte - cur_offset;
J
Josef Bacik 已提交
5177

5178 5179 5180
			err = maybe_insert_hole(root, inode, cur_offset,
						hole_size);
			if (err)
5181
				break;
5182
			btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
J
Josef Bacik 已提交
5183 5184 5185 5186 5187 5188 5189 5190 5191 5192
						cur_offset + hole_size - 1, 0);
			hole_em = alloc_extent_map();
			if (!hole_em) {
				set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
					&BTRFS_I(inode)->runtime_flags);
				goto next;
			}
			hole_em->start = cur_offset;
			hole_em->len = hole_size;
			hole_em->orig_start = cur_offset;
5193

J
Josef Bacik 已提交
5194 5195
			hole_em->block_start = EXTENT_MAP_HOLE;
			hole_em->block_len = 0;
5196
			hole_em->orig_block_len = 0;
J
Josef Bacik 已提交
5197
			hole_em->ram_bytes = hole_size;
5198
			hole_em->bdev = fs_info->fs_devices->latest_bdev;
J
Josef Bacik 已提交
5199
			hole_em->compress_type = BTRFS_COMPRESS_NONE;
5200
			hole_em->generation = fs_info->generation;
5201

J
Josef Bacik 已提交
5202 5203
			while (1) {
				write_lock(&em_tree->lock);
J
Josef Bacik 已提交
5204
				err = add_extent_mapping(em_tree, hole_em, 1);
J
Josef Bacik 已提交
5205 5206 5207
				write_unlock(&em_tree->lock);
				if (err != -EEXIST)
					break;
5208 5209
				btrfs_drop_extent_cache(BTRFS_I(inode),
							cur_offset,
J
Josef Bacik 已提交
5210 5211 5212 5213
							cur_offset +
							hole_size - 1, 0);
			}
			free_extent_map(hole_em);
Y
Yan Zheng 已提交
5214
		}
5215
next:
Y
Yan Zheng 已提交
5216
		free_extent_map(em);
5217
		em = NULL;
Y
Yan Zheng 已提交
5218
		cur_offset = last_byte;
5219
		if (cur_offset >= block_end)
Y
Yan Zheng 已提交
5220 5221
			break;
	}
5222
	free_extent_map(em);
5223
	unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state);
Y
Yan Zheng 已提交
5224 5225
	return err;
}
C
Chris Mason 已提交
5226

5227
static int btrfs_setsize(struct inode *inode, struct iattr *attr)
5228
{
5229 5230
	struct btrfs_root *root = BTRFS_I(inode)->root;
	struct btrfs_trans_handle *trans;
5231
	loff_t oldsize = i_size_read(inode);
5232 5233
	loff_t newsize = attr->ia_size;
	int mask = attr->ia_valid;
5234 5235
	int ret;

5236 5237 5238 5239 5240 5241
	/*
	 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
	 * special case where we need to update the times despite not having
	 * these flags set.  For all other operations the VFS set these flags
	 * explicitly if it wants a timestamp update.
	 */
C
Christoph Hellwig 已提交
5242 5243 5244 5245
	if (newsize != oldsize) {
		inode_inc_iversion(inode);
		if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
			inode->i_ctime = inode->i_mtime =
5246
				current_time(inode);
C
Christoph Hellwig 已提交
5247
	}
5248

5249
	if (newsize > oldsize) {
5250
		/*
5251
		 * Don't do an expanding truncate while snapshotting is ongoing.
5252 5253 5254 5255 5256
		 * This is to ensure the snapshot captures a fully consistent
		 * state of this file - if the snapshot captures this expanding
		 * truncation, it must capture all writes that happened before
		 * this truncation.
		 */
5257
		btrfs_wait_for_snapshot_creation(root);
5258
		ret = btrfs_cont_expand(inode, oldsize, newsize);
5259
		if (ret) {
5260
			btrfs_end_write_no_snapshotting(root);
5261
			return ret;
5262
		}
5263

5264
		trans = btrfs_start_transaction(root, 1);
5265
		if (IS_ERR(trans)) {
5266
			btrfs_end_write_no_snapshotting(root);
5267
			return PTR_ERR(trans);
5268
		}
5269 5270 5271

		i_size_write(inode, newsize);
		btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
5272
		pagecache_isize_extended(inode, oldsize, newsize);
5273
		ret = btrfs_update_inode(trans, root, inode);
5274
		btrfs_end_write_no_snapshotting(root);
5275
		btrfs_end_transaction(trans);
5276
	} else {
5277

5278 5279 5280 5281 5282 5283
		/*
		 * We're truncating a file that used to have good data down to
		 * zero. Make sure it gets into the ordered flush list so that
		 * any new writes get down to disk quickly.
		 */
		if (newsize == 0)
5284 5285
			set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
				&BTRFS_I(inode)->runtime_flags);
5286

5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301
		/*
		 * 1 for the orphan item we're going to add
		 * 1 for the orphan item deletion.
		 */
		trans = btrfs_start_transaction(root, 2);
		if (IS_ERR(trans))
			return PTR_ERR(trans);

		/*
		 * We need to do this in case we fail at _any_ point during the
		 * actual truncate.  Once we do the truncate_setsize we could
		 * invalidate pages which forces any outstanding ordered io to
		 * be instantly completed which will give us extents that need
		 * to be truncated.  If we fail to get an orphan inode down we
		 * could have left over extents that were never meant to live,
5302
		 * so we need to guarantee from this point on that everything
5303 5304
		 * will be consistent.
		 */
5305
		ret = btrfs_orphan_add(trans, BTRFS_I(inode));
5306
		btrfs_end_transaction(trans);
5307 5308 5309
		if (ret)
			return ret;

5310 5311
		/* we don't support swapfiles, so vmtruncate shouldn't fail */
		truncate_setsize(inode, newsize);
5312 5313

		/* Disable nonlocked read DIO to avoid the end less truncate */
5314
		btrfs_inode_block_unlocked_dio(BTRFS_I(inode));
5315
		inode_dio_wait(inode);
5316
		btrfs_inode_resume_unlocked_dio(BTRFS_I(inode));
5317

5318
		ret = btrfs_truncate(inode, newsize == oldsize);
5319 5320 5321
		if (ret && inode->i_nlink) {
			int err;

5322 5323 5324
			/* To get a stable disk_i_size */
			err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
			if (err) {
5325
				btrfs_orphan_del(NULL, BTRFS_I(inode));
5326 5327 5328
				return err;
			}

5329 5330 5331 5332 5333 5334 5335 5336
			/*
			 * failed to truncate, disk_i_size is only adjusted down
			 * as we remove extents, so it should represent the true
			 * size of the inode, so reset the in memory size and
			 * delete our orphan entry.
			 */
			trans = btrfs_join_transaction(root);
			if (IS_ERR(trans)) {
5337
				btrfs_orphan_del(NULL, BTRFS_I(inode));
5338 5339 5340
				return ret;
			}
			i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5341
			err = btrfs_orphan_del(trans, BTRFS_I(inode));
5342
			if (err)
5343
				btrfs_abort_transaction(trans, err);
5344
			btrfs_end_transaction(trans);
5345
		}
5346 5347
	}

5348
	return ret;
5349 5350
}

Y
Yan Zheng 已提交
5351 5352
static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
{
5353
	struct inode *inode = d_inode(dentry);
L
Li Zefan 已提交
5354
	struct btrfs_root *root = BTRFS_I(inode)->root;
Y
Yan Zheng 已提交
5355
	int err;
C
Chris Mason 已提交
5356

L
Li Zefan 已提交
5357 5358 5359
	if (btrfs_root_readonly(root))
		return -EROFS;

5360
	err = setattr_prepare(dentry, attr);
Y
Yan Zheng 已提交
5361 5362
	if (err)
		return err;
C
Chris Mason 已提交
5363

5364
	if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5365
		err = btrfs_setsize(inode, attr);
5366 5367
		if (err)
			return err;
C
Chris Mason 已提交
5368
	}
Y
Yan Zheng 已提交
5369

C
Christoph Hellwig 已提交
5370 5371
	if (attr->ia_valid) {
		setattr_copy(inode, attr);
5372
		inode_inc_iversion(inode);
5373
		err = btrfs_dirty_inode(inode);
C
Christoph Hellwig 已提交
5374

5375
		if (!err && attr->ia_valid & ATTR_MODE)
5376
			err = posix_acl_chmod(inode, inode->i_mode);
C
Christoph Hellwig 已提交
5377
	}
J
Josef Bacik 已提交
5378

C
Chris Mason 已提交
5379 5380
	return err;
}
5381

5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400
/*
 * While truncating the inode pages during eviction, we get the VFS calling
 * btrfs_invalidatepage() against each page of the inode. This is slow because
 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
 * extent_state structures over and over, wasting lots of time.
 *
 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
 * those expensive operations on a per page basis and do only the ordered io
 * finishing, while we release here the extent_map and extent_state structures,
 * without the excessive merging and splitting.
 */
static void evict_inode_truncate_pages(struct inode *inode)
{
	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
	struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
	struct rb_node *node;

	ASSERT(inode->i_state & I_FREEING);
5401
	truncate_inode_pages_final(&inode->i_data);
5402 5403 5404 5405 5406 5407 5408

	write_lock(&map_tree->lock);
	while (!RB_EMPTY_ROOT(&map_tree->map)) {
		struct extent_map *em;

		node = rb_first(&map_tree->map);
		em = rb_entry(node, struct extent_map, rb_node);
5409 5410
		clear_bit(EXTENT_FLAG_PINNED, &em->flags);
		clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
5411 5412
		remove_extent_mapping(map_tree, em);
		free_extent_map(em);
5413 5414 5415 5416 5417
		if (need_resched()) {
			write_unlock(&map_tree->lock);
			cond_resched();
			write_lock(&map_tree->lock);
		}
5418 5419 5420
	}
	write_unlock(&map_tree->lock);

5421 5422 5423
	/*
	 * Keep looping until we have no more ranges in the io tree.
	 * We can have ongoing bios started by readpages (called from readahead)
5424 5425 5426
	 * that have their endio callback (extent_io.c:end_bio_extent_readpage)
	 * still in progress (unlocked the pages in the bio but did not yet
	 * unlocked the ranges in the io tree). Therefore this means some
5427 5428 5429 5430 5431 5432 5433 5434 5435 5436
	 * ranges can still be locked and eviction started because before
	 * submitting those bios, which are executed by a separate task (work
	 * queue kthread), inode references (inode->i_count) were not taken
	 * (which would be dropped in the end io callback of each bio).
	 * Therefore here we effectively end up waiting for those bios and
	 * anyone else holding locked ranges without having bumped the inode's
	 * reference count - if we don't do it, when they access the inode's
	 * io_tree to unlock a range it may be too late, leading to an
	 * use-after-free issue.
	 */
5437 5438 5439 5440
	spin_lock(&io_tree->lock);
	while (!RB_EMPTY_ROOT(&io_tree->state)) {
		struct extent_state *state;
		struct extent_state *cached_state = NULL;
5441 5442
		u64 start;
		u64 end;
5443 5444 5445

		node = rb_first(&io_tree->state);
		state = rb_entry(node, struct extent_state, rb_node);
5446 5447
		start = state->start;
		end = state->end;
5448 5449
		spin_unlock(&io_tree->lock);

5450
		lock_extent_bits(io_tree, start, end, &cached_state);
Q
Qu Wenruo 已提交
5451 5452 5453 5454 5455 5456 5457 5458 5459 5460

		/*
		 * If still has DELALLOC flag, the extent didn't reach disk,
		 * and its reserved space won't be freed by delayed_ref.
		 * So we need to free its reserved space here.
		 * (Refer to comment in btrfs_invalidatepage, case 2)
		 *
		 * Note, end is the bytenr of last byte, so we need + 1 here.
		 */
		if (state->state & EXTENT_DELALLOC)
5461
			btrfs_qgroup_free_data(inode, NULL, start, end - start + 1);
Q
Qu Wenruo 已提交
5462

5463
		clear_extent_bit(io_tree, start, end,
5464 5465
				 EXTENT_LOCKED | EXTENT_DIRTY |
				 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
5466
				 EXTENT_DEFRAG, 1, 1, &cached_state);
5467

5468
		cond_resched();
5469 5470 5471 5472 5473
		spin_lock(&io_tree->lock);
	}
	spin_unlock(&io_tree->lock);
}

A
Al Viro 已提交
5474
void btrfs_evict_inode(struct inode *inode)
C
Chris Mason 已提交
5475
{
5476
	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
C
Chris Mason 已提交
5477 5478
	struct btrfs_trans_handle *trans;
	struct btrfs_root *root = BTRFS_I(inode)->root;
5479
	struct btrfs_block_rsv *rsv, *global_rsv;
5480
	int steal_from_global = 0;
5481
	u64 min_size;
C
Chris Mason 已提交
5482 5483
	int ret;

5484 5485
	trace_btrfs_inode_evict(inode);

5486
	if (!root) {
5487
		clear_inode(inode);
5488 5489 5490
		return;
	}

5491
	min_size = btrfs_calc_trunc_metadata_size(fs_info, 1);
5492

5493 5494
	evict_inode_truncate_pages(inode);

5495 5496 5497
	if (inode->i_nlink &&
	    ((btrfs_root_refs(&root->root_item) != 0 &&
	      root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5498
	     btrfs_is_free_space_inode(BTRFS_I(inode))))
A
Al Viro 已提交
5499 5500
		goto no_delete;

C
Chris Mason 已提交
5501
	if (is_bad_inode(inode)) {
5502
		btrfs_orphan_del(NULL, BTRFS_I(inode));
C
Chris Mason 已提交
5503 5504
		goto no_delete;
	}
A
Al Viro 已提交
5505
	/* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
5506 5507
	if (!special_file(inode->i_mode))
		btrfs_wait_ordered_range(inode, 0, (u64)-1);
5508

5509
	btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
5510

5511
	if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
5512
		BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
5513
				 &BTRFS_I(inode)->runtime_flags));
5514 5515 5516
		goto no_delete;
	}

5517
	if (inode->i_nlink > 0) {
5518 5519
		BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
		       root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5520 5521 5522
		goto no_delete;
	}

5523
	ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5524
	if (ret) {
5525
		btrfs_orphan_del(NULL, BTRFS_I(inode));
5526 5527 5528
		goto no_delete;
	}

5529
	rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
5530
	if (!rsv) {
5531
		btrfs_orphan_del(NULL, BTRFS_I(inode));
5532 5533
		goto no_delete;
	}
J
Josef Bacik 已提交
5534
	rsv->size = min_size;
5535
	rsv->failfast = 1;
5536
	global_rsv = &fs_info->global_block_rsv;
5537

5538
	btrfs_i_size_write(BTRFS_I(inode), 0);
5539

5540
	/*
5541 5542 5543 5544
	 * This is a bit simpler than btrfs_truncate since we've already
	 * reserved our space for our orphan item in the unlink, so we just
	 * need to reserve some slack space in case we add bytes and update
	 * inode item when doing the truncate.
5545
	 */
5546
	while (1) {
M
Miao Xie 已提交
5547 5548
		ret = btrfs_block_rsv_refill(root, rsv, min_size,
					     BTRFS_RESERVE_FLUSH_LIMIT);
5549 5550 5551 5552 5553 5554 5555

		/*
		 * Try and steal from the global reserve since we will
		 * likely not use this space anyway, we want to try as
		 * hard as possible to get this to work.
		 */
		if (ret)
5556 5557 5558 5559
			steal_from_global++;
		else
			steal_from_global = 0;
		ret = 0;
5560

5561 5562 5563 5564 5565 5566 5567 5568 5569
		/*
		 * steal_from_global == 0: we reserved stuff, hooray!
		 * steal_from_global == 1: we didn't reserve stuff, boo!
		 * steal_from_global == 2: we've committed, still not a lot of
		 * room but maybe we'll have room in the global reserve this
		 * time.
		 * steal_from_global == 3: abandon all hope!
		 */
		if (steal_from_global > 2) {
5570 5571 5572
			btrfs_warn(fs_info,
				   "Could not get space for a delete, will truncate on mount %d",
				   ret);
5573
			btrfs_orphan_del(NULL, BTRFS_I(inode));
5574
			btrfs_free_block_rsv(fs_info, rsv);
5575
			goto no_delete;
5576
		}
5577

5578
		trans = btrfs_join_transaction(root);
5579
		if (IS_ERR(trans)) {
5580
			btrfs_orphan_del(NULL, BTRFS_I(inode));
5581
			btrfs_free_block_rsv(fs_info, rsv);
5582
			goto no_delete;
5583
		}
5584

5585
		/*
5586
		 * We can't just steal from the global reserve, we need to make
5587 5588 5589 5590
		 * sure there is room to do it, if not we need to commit and try
		 * again.
		 */
		if (steal_from_global) {
5591
			if (!btrfs_check_space_for_delayed_refs(trans, fs_info))
5592
				ret = btrfs_block_rsv_migrate(global_rsv, rsv,
5593
							      min_size, 0);
5594 5595 5596 5597 5598 5599 5600 5601 5602 5603
			else
				ret = -ENOSPC;
		}

		/*
		 * Couldn't steal from the global reserve, we have too much
		 * pending stuff built up, commit the transaction and try it
		 * again.
		 */
		if (ret) {
5604
			ret = btrfs_commit_transaction(trans);
5605
			if (ret) {
5606
				btrfs_orphan_del(NULL, BTRFS_I(inode));
5607
				btrfs_free_block_rsv(fs_info, rsv);
5608 5609 5610 5611 5612 5613 5614
				goto no_delete;
			}
			continue;
		} else {
			steal_from_global = 0;
		}

5615 5616
		trans->block_rsv = rsv;

5617
		ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
5618
		if (ret != -ENOSPC && ret != -EAGAIN)
5619
			break;
5620

5621
		trans->block_rsv = &fs_info->trans_block_rsv;
5622
		btrfs_end_transaction(trans);
5623
		trans = NULL;
5624
		btrfs_btree_balance_dirty(fs_info);
5625
	}
5626

5627
	btrfs_free_block_rsv(fs_info, rsv);
5628

5629 5630 5631 5632
	/*
	 * Errors here aren't a big deal, it just means we leave orphan items
	 * in the tree.  They will be cleaned up on the next mount.
	 */
5633
	if (ret == 0) {
5634
		trans->block_rsv = root->orphan_block_rsv;
5635
		btrfs_orphan_del(trans, BTRFS_I(inode));
5636
	} else {
5637
		btrfs_orphan_del(NULL, BTRFS_I(inode));
5638
	}
5639

5640 5641
	trans->block_rsv = &fs_info->trans_block_rsv;
	if (!(root == fs_info->tree_root ||
5642
	      root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
5643
		btrfs_return_ino(root, btrfs_ino(BTRFS_I(inode)));
5644

5645
	btrfs_end_transaction(trans);
5646
	btrfs_btree_balance_dirty(fs_info);
C
Chris Mason 已提交
5647
no_delete:
5648
	btrfs_remove_delayed_node(BTRFS_I(inode));
5649
	clear_inode(inode);
C
Chris Mason 已提交
5650 5651 5652 5653
}

/*
 * this returns the key found in the dir entry in the location pointer.
5654 5655
 * If no dir entries were found, returns -ENOENT.
 * If found a corrupted location in dir entry, returns -EUCLEAN.
C
Chris Mason 已提交
5656 5657 5658 5659 5660 5661 5662 5663 5664
 */
static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
			       struct btrfs_key *location)
{
	const char *name = dentry->d_name.name;
	int namelen = dentry->d_name.len;
	struct btrfs_dir_item *di;
	struct btrfs_path *path;
	struct btrfs_root *root = BTRFS_I(dir)->root;
Y
Yan 已提交
5665
	int ret = 0;
C
Chris Mason 已提交
5666 5667

	path = btrfs_alloc_path();
5668 5669
	if (!path)
		return -ENOMEM;
5670

5671 5672
	di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
			name, namelen, 0);
5673 5674 5675 5676 5677
	if (!di) {
		ret = -ENOENT;
		goto out;
	}
	if (IS_ERR(di)) {
Y
Yan 已提交
5678
		ret = PTR_ERR(di);
5679 5680
		goto out;
	}
C
Chris Mason 已提交
5681

5682
	btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5683 5684
	if (location->type != BTRFS_INODE_ITEM_KEY &&
	    location->type != BTRFS_ROOT_ITEM_KEY) {
5685
		ret = -EUCLEAN;
5686 5687 5688 5689 5690
		btrfs_warn(root->fs_info,
"%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
			   __func__, name, btrfs_ino(BTRFS_I(dir)),
			   location->objectid, location->type, location->offset);
	}
C
Chris Mason 已提交
5691 5692 5693 5694 5695 5696 5697 5698 5699 5700
out:
	btrfs_free_path(path);
	return ret;
}

/*
 * when we hit a tree root in a directory, the btrfs part of the inode
 * needs to be changed to reflect the root directory of the tree root.  This
 * is kind of like crossing a mount point.
 */
5701
static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5702 5703 5704 5705
				    struct inode *dir,
				    struct dentry *dentry,
				    struct btrfs_key *location,
				    struct btrfs_root **sub_root)
C
Chris Mason 已提交
5706
{
5707 5708 5709 5710
	struct btrfs_path *path;
	struct btrfs_root *new_root;
	struct btrfs_root_ref *ref;
	struct extent_buffer *leaf;
5711
	struct btrfs_key key;
5712 5713
	int ret;
	int err = 0;
C
Chris Mason 已提交
5714

5715 5716 5717 5718 5719
	path = btrfs_alloc_path();
	if (!path) {
		err = -ENOMEM;
		goto out;
	}
C
Chris Mason 已提交
5720

5721
	err = -ENOENT;
5722 5723 5724 5725
	key.objectid = BTRFS_I(dir)->root->root_key.objectid;
	key.type = BTRFS_ROOT_REF_KEY;
	key.offset = location->objectid;

5726
	ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5727 5728 5729 5730 5731
	if (ret) {
		if (ret < 0)
			err = ret;
		goto out;
	}
C
Chris Mason 已提交
5732

5733 5734
	leaf = path->nodes[0];
	ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5735
	if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
5736 5737
	    btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
		goto out;
C
Chris Mason 已提交
5738

5739 5740 5741 5742 5743 5744
	ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
				   (unsigned long)(ref + 1),
				   dentry->d_name.len);
	if (ret)
		goto out;

5745
	btrfs_release_path(path);
5746

5747
	new_root = btrfs_read_fs_root_no_name(fs_info, location);
5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760
	if (IS_ERR(new_root)) {
		err = PTR_ERR(new_root);
		goto out;
	}

	*sub_root = new_root;
	location->objectid = btrfs_root_dirid(&new_root->root_item);
	location->type = BTRFS_INODE_ITEM_KEY;
	location->offset = 0;
	err = 0;
out:
	btrfs_free_path(path);
	return err;
C
Chris Mason 已提交
5761 5762
}

5763 5764 5765 5766
static void inode_tree_add(struct inode *inode)
{
	struct btrfs_root *root = BTRFS_I(inode)->root;
	struct btrfs_inode *entry;
5767 5768
	struct rb_node **p;
	struct rb_node *parent;
5769
	struct rb_node *new = &BTRFS_I(inode)->rb_node;
5770
	u64 ino = btrfs_ino(BTRFS_I(inode));
5771

A
Al Viro 已提交
5772
	if (inode_unhashed(inode))
5773
		return;
5774
	parent = NULL;
5775
	spin_lock(&root->inode_lock);
5776
	p = &root->inode_tree.rb_node;
5777 5778 5779 5780
	while (*p) {
		parent = *p;
		entry = rb_entry(parent, struct btrfs_inode, rb_node);

5781
		if (ino < btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5782
			p = &parent->rb_left;
5783
		else if (ino > btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5784
			p = &parent->rb_right;
5785 5786
		else {
			WARN_ON(!(entry->vfs_inode.i_state &
A
Al Viro 已提交
5787
				  (I_WILL_FREE | I_FREEING)));
5788
			rb_replace_node(parent, new, &root->inode_tree);
5789 5790
			RB_CLEAR_NODE(parent);
			spin_unlock(&root->inode_lock);
5791
			return;
5792 5793
		}
	}
5794 5795
	rb_link_node(new, parent, p);
	rb_insert_color(new, &root->inode_tree);
5796 5797 5798 5799 5800
	spin_unlock(&root->inode_lock);
}

static void inode_tree_del(struct inode *inode)
{
5801
	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5802
	struct btrfs_root *root = BTRFS_I(inode)->root;
5803
	int empty = 0;
5804

5805
	spin_lock(&root->inode_lock);
5806 5807 5808
	if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
		rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
		RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
5809
		empty = RB_EMPTY_ROOT(&root->inode_tree);
5810
	}
5811
	spin_unlock(&root->inode_lock);
5812

5813
	if (empty && btrfs_root_refs(&root->root_item) == 0) {
5814
		synchronize_srcu(&fs_info->subvol_srcu);
5815 5816 5817 5818 5819 5820 5821 5822
		spin_lock(&root->inode_lock);
		empty = RB_EMPTY_ROOT(&root->inode_tree);
		spin_unlock(&root->inode_lock);
		if (empty)
			btrfs_add_dead_root(root);
	}
}

5823
void btrfs_invalidate_inodes(struct btrfs_root *root)
5824
{
5825
	struct btrfs_fs_info *fs_info = root->fs_info;
5826 5827 5828 5829 5830 5831
	struct rb_node *node;
	struct rb_node *prev;
	struct btrfs_inode *entry;
	struct inode *inode;
	u64 objectid = 0;

5832
	if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
5833
		WARN_ON(btrfs_root_refs(&root->root_item) != 0);
5834 5835 5836 5837 5838 5839 5840 5841 5842

	spin_lock(&root->inode_lock);
again:
	node = root->inode_tree.rb_node;
	prev = NULL;
	while (node) {
		prev = node;
		entry = rb_entry(node, struct btrfs_inode, rb_node);

5843
		if (objectid < btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5844
			node = node->rb_left;
5845
		else if (objectid > btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5846 5847 5848 5849 5850 5851 5852
			node = node->rb_right;
		else
			break;
	}
	if (!node) {
		while (prev) {
			entry = rb_entry(prev, struct btrfs_inode, rb_node);
5853
			if (objectid <= btrfs_ino(BTRFS_I(&entry->vfs_inode))) {
5854 5855 5856 5857 5858 5859 5860 5861
				node = prev;
				break;
			}
			prev = rb_next(prev);
		}
	}
	while (node) {
		entry = rb_entry(node, struct btrfs_inode, rb_node);
5862
		objectid = btrfs_ino(BTRFS_I(&entry->vfs_inode)) + 1;
5863 5864 5865 5866 5867 5868
		inode = igrab(&entry->vfs_inode);
		if (inode) {
			spin_unlock(&root->inode_lock);
			if (atomic_read(&inode->i_count) > 1)
				d_prune_aliases(inode);
			/*
5869
			 * btrfs_drop_inode will have it removed from
5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884
			 * the inode cache when its usage count
			 * hits zero.
			 */
			iput(inode);
			cond_resched();
			spin_lock(&root->inode_lock);
			goto again;
		}

		if (cond_resched_lock(&root->inode_lock))
			goto again;

		node = rb_next(node);
	}
	spin_unlock(&root->inode_lock);
5885 5886
}

5887 5888 5889
static int btrfs_init_locked_inode(struct inode *inode, void *p)
{
	struct btrfs_iget_args *args = p;
5890 5891 5892
	inode->i_ino = args->location->objectid;
	memcpy(&BTRFS_I(inode)->location, args->location,
	       sizeof(*args->location));
5893
	BTRFS_I(inode)->root = args->root;
C
Chris Mason 已提交
5894 5895 5896 5897 5898 5899
	return 0;
}

static int btrfs_find_actor(struct inode *inode, void *opaque)
{
	struct btrfs_iget_args *args = opaque;
5900
	return args->location->objectid == BTRFS_I(inode)->location.objectid &&
C
Chris Mason 已提交
5901
		args->root == BTRFS_I(inode)->root;
C
Chris Mason 已提交
5902 5903
}

5904
static struct inode *btrfs_iget_locked(struct super_block *s,
5905
				       struct btrfs_key *location,
5906
				       struct btrfs_root *root)
C
Chris Mason 已提交
5907 5908 5909
{
	struct inode *inode;
	struct btrfs_iget_args args;
5910
	unsigned long hashval = btrfs_inode_hash(location->objectid, root);
5911

5912
	args.location = location;
C
Chris Mason 已提交
5913 5914
	args.root = root;

5915
	inode = iget5_locked(s, hashval, btrfs_find_actor,
C
Chris Mason 已提交
5916 5917 5918 5919 5920
			     btrfs_init_locked_inode,
			     (void *)&args);
	return inode;
}

B
Balaji Rao 已提交
5921 5922 5923 5924
/* Get an inode object given its location and corresponding root.
 * Returns in *is_new if the inode was read from disk
 */
struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
5925
			 struct btrfs_root *root, int *new)
B
Balaji Rao 已提交
5926 5927 5928
{
	struct inode *inode;

5929
	inode = btrfs_iget_locked(s, location, root);
B
Balaji Rao 已提交
5930
	if (!inode)
5931
		return ERR_PTR(-ENOMEM);
B
Balaji Rao 已提交
5932 5933

	if (inode->i_state & I_NEW) {
5934 5935 5936
		int ret;

		ret = btrfs_read_locked_inode(inode);
5937 5938 5939 5940 5941 5942
		if (!is_bad_inode(inode)) {
			inode_tree_add(inode);
			unlock_new_inode(inode);
			if (new)
				*new = 1;
		} else {
5943 5944
			unlock_new_inode(inode);
			iput(inode);
5945 5946
			ASSERT(ret < 0);
			inode = ERR_PTR(ret < 0 ? ret : -ESTALE);
5947 5948 5949
		}
	}

B
Balaji Rao 已提交
5950 5951 5952
	return inode;
}

5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963
static struct inode *new_simple_dir(struct super_block *s,
				    struct btrfs_key *key,
				    struct btrfs_root *root)
{
	struct inode *inode = new_inode(s);

	if (!inode)
		return ERR_PTR(-ENOMEM);

	BTRFS_I(inode)->root = root;
	memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5964
	set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5965 5966

	inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
L
Li Zefan 已提交
5967
	inode->i_op = &btrfs_dir_ro_inode_operations;
5968
	inode->i_opflags &= ~IOP_XATTR;
5969 5970
	inode->i_fop = &simple_dir_operations;
	inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5971
	inode->i_mtime = current_time(inode);
5972 5973 5974
	inode->i_atime = inode->i_mtime;
	inode->i_ctime = inode->i_mtime;
	BTRFS_I(inode)->i_otime = inode->i_mtime;
5975 5976 5977 5978

	return inode;
}

5979
struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
C
Chris Mason 已提交
5980
{
5981
	struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
C
Chris Mason 已提交
5982
	struct inode *inode;
5983
	struct btrfs_root *root = BTRFS_I(dir)->root;
C
Chris Mason 已提交
5984 5985
	struct btrfs_root *sub_root = root;
	struct btrfs_key location;
5986
	int index;
5987
	int ret = 0;
C
Chris Mason 已提交
5988 5989 5990

	if (dentry->d_name.len > BTRFS_NAME_LEN)
		return ERR_PTR(-ENAMETOOLONG);
5991

J
Jeff Layton 已提交
5992
	ret = btrfs_inode_by_name(dir, dentry, &location);
C
Chris Mason 已提交
5993 5994
	if (ret < 0)
		return ERR_PTR(ret);
5995

5996
	if (location.type == BTRFS_INODE_ITEM_KEY) {
5997
		inode = btrfs_iget(dir->i_sb, &location, root, NULL);
5998 5999 6000
		return inode;
	}

6001
	index = srcu_read_lock(&fs_info->subvol_srcu);
6002
	ret = fixup_tree_root_location(fs_info, dir, dentry,
6003 6004 6005 6006 6007 6008 6009
				       &location, &sub_root);
	if (ret < 0) {
		if (ret != -ENOENT)
			inode = ERR_PTR(ret);
		else
			inode = new_simple_dir(dir->i_sb, &location, sub_root);
	} else {
6010
		inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
C
Chris Mason 已提交
6011
	}
6012
	srcu_read_unlock(&fs_info->subvol_srcu, index);
6013

6014
	if (!IS_ERR(inode) && root != sub_root) {
6015
		down_read(&fs_info->cleanup_work_sem);
6016
		if (!sb_rdonly(inode->i_sb))
6017
			ret = btrfs_orphan_cleanup(sub_root);
6018
		up_read(&fs_info->cleanup_work_sem);
6019 6020
		if (ret) {
			iput(inode);
6021
			inode = ERR_PTR(ret);
6022
		}
6023 6024
	}

6025 6026 6027
	return inode;
}

N
Nick Piggin 已提交
6028
static int btrfs_dentry_delete(const struct dentry *dentry)
6029 6030
{
	struct btrfs_root *root;
6031
	struct inode *inode = d_inode(dentry);
6032

L
Li Zefan 已提交
6033
	if (!inode && !IS_ROOT(dentry))
6034
		inode = d_inode(dentry->d_parent);
6035

L
Li Zefan 已提交
6036 6037
	if (inode) {
		root = BTRFS_I(inode)->root;
6038 6039
		if (btrfs_root_refs(&root->root_item) == 0)
			return 1;
L
Li Zefan 已提交
6040

6041
		if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
L
Li Zefan 已提交
6042
			return 1;
6043
	}
6044 6045 6046
	return 0;
}

6047 6048
static void btrfs_dentry_release(struct dentry *dentry)
{
6049
	kfree(dentry->d_fsdata);
6050 6051
}

6052
static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
A
Al Viro 已提交
6053
				   unsigned int flags)
6054
{
6055
	struct inode *inode;
6056

6057 6058 6059 6060 6061 6062 6063 6064
	inode = btrfs_lookup_dentry(dir, dentry);
	if (IS_ERR(inode)) {
		if (PTR_ERR(inode) == -ENOENT)
			inode = NULL;
		else
			return ERR_CAST(inode);
	}

6065
	return d_splice_alias(inode, dentry);
C
Chris Mason 已提交
6066 6067
}

6068
unsigned char btrfs_filetype_table[] = {
C
Chris Mason 已提交
6069 6070 6071
	DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
};

6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109
/*
 * All this infrastructure exists because dir_emit can fault, and we are holding
 * the tree lock when doing readdir.  For now just allocate a buffer and copy
 * our information into that, and then dir_emit from the buffer.  This is
 * similar to what NFS does, only we don't keep the buffer around in pagecache
 * because I'm afraid I'll mess that up.  Long term we need to make filldir do
 * copy_to_user_inatomic so we don't have to worry about page faulting under the
 * tree lock.
 */
static int btrfs_opendir(struct inode *inode, struct file *file)
{
	struct btrfs_file_private *private;

	private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
	if (!private)
		return -ENOMEM;
	private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
	if (!private->filldir_buf) {
		kfree(private);
		return -ENOMEM;
	}
	file->private_data = private;
	return 0;
}

struct dir_entry {
	u64 ino;
	u64 offset;
	unsigned type;
	int name_len;
};

static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
{
	while (entries--) {
		struct dir_entry *entry = addr;
		char *name = (char *)(entry + 1);

6110 6111 6112 6113
		ctx->pos = get_unaligned(&entry->offset);
		if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
					 get_unaligned(&entry->ino),
					 get_unaligned(&entry->type)))
6114
			return 1;
6115 6116
		addr += sizeof(struct dir_entry) +
			get_unaligned(&entry->name_len);
6117 6118 6119 6120 6121
		ctx->pos++;
	}
	return 0;
}

A
Al Viro 已提交
6122
static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
C
Chris Mason 已提交
6123
{
A
Al Viro 已提交
6124
	struct inode *inode = file_inode(file);
C
Chris Mason 已提交
6125
	struct btrfs_root *root = BTRFS_I(inode)->root;
6126
	struct btrfs_file_private *private = file->private_data;
C
Chris Mason 已提交
6127 6128
	struct btrfs_dir_item *di;
	struct btrfs_key key;
6129
	struct btrfs_key found_key;
C
Chris Mason 已提交
6130
	struct btrfs_path *path;
6131
	void *addr;
6132 6133
	struct list_head ins_list;
	struct list_head del_list;
C
Chris Mason 已提交
6134
	int ret;
6135
	struct extent_buffer *leaf;
C
Chris Mason 已提交
6136
	int slot;
6137 6138
	char *name_ptr;
	int name_len;
6139 6140
	int entries = 0;
	int total_len = 0;
6141
	bool put = false;
6142
	struct btrfs_key location;
6143

A
Al Viro 已提交
6144 6145 6146
	if (!dir_emit_dots(file, ctx))
		return 0;

6147
	path = btrfs_alloc_path();
6148 6149
	if (!path)
		return -ENOMEM;
C
Chris Mason 已提交
6150

6151
	addr = private->filldir_buf;
6152
	path->reada = READA_FORWARD;
6153

6154 6155 6156
	INIT_LIST_HEAD(&ins_list);
	INIT_LIST_HEAD(&del_list);
	put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
6157

6158
again:
6159
	key.type = BTRFS_DIR_INDEX_KEY;
A
Al Viro 已提交
6160
	key.offset = ctx->pos;
6161
	key.objectid = btrfs_ino(BTRFS_I(inode));
6162

C
Chris Mason 已提交
6163 6164 6165
	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
	if (ret < 0)
		goto err;
6166 6167

	while (1) {
6168 6169
		struct dir_entry *entry;

6170
		leaf = path->nodes[0];
C
Chris Mason 已提交
6171
		slot = path->slots[0];
6172 6173 6174 6175 6176 6177 6178
		if (slot >= btrfs_header_nritems(leaf)) {
			ret = btrfs_next_leaf(root, path);
			if (ret < 0)
				goto err;
			else if (ret > 0)
				break;
			continue;
C
Chris Mason 已提交
6179
		}
6180

6181 6182 6183
		btrfs_item_key_to_cpu(leaf, &found_key, slot);

		if (found_key.objectid != key.objectid)
C
Chris Mason 已提交
6184
			break;
6185
		if (found_key.type != BTRFS_DIR_INDEX_KEY)
C
Chris Mason 已提交
6186
			break;
A
Al Viro 已提交
6187
		if (found_key.offset < ctx->pos)
6188
			goto next;
6189
		if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
6190
			goto next;
C
Chris Mason 已提交
6191
		di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
6192
		name_len = btrfs_dir_name_len(leaf, di);
6193 6194 6195 6196 6197 6198 6199 6200 6201 6202
		if ((total_len + sizeof(struct dir_entry) + name_len) >=
		    PAGE_SIZE) {
			btrfs_release_path(path);
			ret = btrfs_filldir(private->filldir_buf, entries, ctx);
			if (ret)
				goto nopos;
			addr = private->filldir_buf;
			entries = 0;
			total_len = 0;
			goto again;
6203
		}
6204 6205

		entry = addr;
6206
		put_unaligned(name_len, &entry->name_len);
6207
		name_ptr = (char *)(entry + 1);
6208 6209
		read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
				   name_len);
6210 6211
		put_unaligned(btrfs_filetype_table[btrfs_dir_type(leaf, di)],
				&entry->type);
6212
		btrfs_dir_item_key_to_cpu(leaf, di, &location);
6213 6214
		put_unaligned(location.objectid, &entry->ino);
		put_unaligned(found_key.offset, &entry->offset);
6215 6216 6217
		entries++;
		addr += sizeof(struct dir_entry) + name_len;
		total_len += sizeof(struct dir_entry) + name_len;
6218 6219
next:
		path->slots[0]++;
C
Chris Mason 已提交
6220
	}
6221 6222 6223 6224 6225
	btrfs_release_path(path);

	ret = btrfs_filldir(private->filldir_buf, entries, ctx);
	if (ret)
		goto nopos;
6226

6227
	ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
6228
	if (ret)
6229 6230
		goto nopos;

6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247
	/*
	 * Stop new entries from being returned after we return the last
	 * entry.
	 *
	 * New directory entries are assigned a strictly increasing
	 * offset.  This means that new entries created during readdir
	 * are *guaranteed* to be seen in the future by that readdir.
	 * This has broken buggy programs which operate on names as
	 * they're returned by readdir.  Until we re-use freed offsets
	 * we have this hack to stop new entries from being returned
	 * under the assumption that they'll never reach this huge
	 * offset.
	 *
	 * This is being careful not to overflow 32bit loff_t unless the
	 * last entry requires it because doing so has broken 32bit apps
	 * in the past.
	 */
6248 6249 6250 6251
	if (ctx->pos >= INT_MAX)
		ctx->pos = LLONG_MAX;
	else
		ctx->pos = INT_MAX;
C
Chris Mason 已提交
6252 6253 6254
nopos:
	ret = 0;
err:
6255 6256
	if (put)
		btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
C
Chris Mason 已提交
6257 6258 6259 6260
	btrfs_free_path(path);
	return ret;
}

6261
int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
C
Chris Mason 已提交
6262 6263 6264 6265
{
	struct btrfs_root *root = BTRFS_I(inode)->root;
	struct btrfs_trans_handle *trans;
	int ret = 0;
6266
	bool nolock = false;
C
Chris Mason 已提交
6267

6268
	if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6269 6270
		return 0;

6271 6272
	if (btrfs_fs_closing(root->fs_info) &&
			btrfs_is_free_space_inode(BTRFS_I(inode)))
6273
		nolock = true;
6274

6275
	if (wbc->sync_mode == WB_SYNC_ALL) {
6276
		if (nolock)
6277
			trans = btrfs_join_transaction_nolock(root);
6278
		else
6279
			trans = btrfs_join_transaction(root);
6280 6281
		if (IS_ERR(trans))
			return PTR_ERR(trans);
6282
		ret = btrfs_commit_transaction(trans);
C
Chris Mason 已提交
6283 6284 6285 6286 6287
	}
	return ret;
}

/*
6288
 * This is somewhat expensive, updating the tree every time the
C
Chris Mason 已提交
6289 6290 6291 6292
 * inode changes.  But, it is most likely to find the inode in cache.
 * FIXME, needs more benchmarking...there are no reasons other than performance
 * to keep or drop this code.
 */
6293
static int btrfs_dirty_inode(struct inode *inode)
C
Chris Mason 已提交
6294
{
6295
	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
C
Chris Mason 已提交
6296 6297
	struct btrfs_root *root = BTRFS_I(inode)->root;
	struct btrfs_trans_handle *trans;
6298 6299
	int ret;

6300
	if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6301
		return 0;
C
Chris Mason 已提交
6302

6303
	trans = btrfs_join_transaction(root);
6304 6305
	if (IS_ERR(trans))
		return PTR_ERR(trans);
6306 6307

	ret = btrfs_update_inode(trans, root, inode);
6308 6309
	if (ret && ret == -ENOSPC) {
		/* whoops, lets try again with the full transaction */
6310
		btrfs_end_transaction(trans);
6311
		trans = btrfs_start_transaction(root, 1);
6312 6313
		if (IS_ERR(trans))
			return PTR_ERR(trans);
6314

6315 6316
		ret = btrfs_update_inode(trans, root, inode);
	}
6317
	btrfs_end_transaction(trans);
6318
	if (BTRFS_I(inode)->delayed_node)
6319
		btrfs_balance_delayed_items(fs_info);
6320 6321 6322 6323 6324 6325 6326 6327

	return ret;
}

/*
 * This is a copy of file_update_time.  We need this so we can return error on
 * ENOSPC for updating the inode in the case of file write and mmap writes.
 */
6328 6329
static int btrfs_update_time(struct inode *inode, struct timespec *now,
			     int flags)
6330
{
6331
	struct btrfs_root *root = BTRFS_I(inode)->root;
6332
	bool dirty = flags & ~S_VERSION;
6333 6334 6335 6336

	if (btrfs_root_readonly(root))
		return -EROFS;

6337
	if (flags & S_VERSION)
6338
		dirty |= inode_maybe_inc_iversion(inode, dirty);
6339 6340 6341 6342 6343 6344
	if (flags & S_CTIME)
		inode->i_ctime = *now;
	if (flags & S_MTIME)
		inode->i_mtime = *now;
	if (flags & S_ATIME)
		inode->i_atime = *now;
6345
	return dirty ? btrfs_dirty_inode(inode) : 0;
C
Chris Mason 已提交
6346 6347
}

C
Chris Mason 已提交
6348 6349 6350 6351 6352
/*
 * find the highest existing sequence number in a directory
 * and then set the in-memory index_cnt variable to reflect
 * free sequence numbers
 */
6353
static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
6354
{
6355
	struct btrfs_root *root = inode->root;
6356 6357 6358 6359 6360
	struct btrfs_key key, found_key;
	struct btrfs_path *path;
	struct extent_buffer *leaf;
	int ret;

6361
	key.objectid = btrfs_ino(inode);
6362
	key.type = BTRFS_DIR_INDEX_KEY;
6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383
	key.offset = (u64)-1;

	path = btrfs_alloc_path();
	if (!path)
		return -ENOMEM;

	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
	if (ret < 0)
		goto out;
	/* FIXME: we should be able to handle this */
	if (ret == 0)
		goto out;
	ret = 0;

	/*
	 * MAGIC NUMBER EXPLANATION:
	 * since we search a directory based on f_pos we have to start at 2
	 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
	 * else has to start at 2
	 */
	if (path->slots[0] == 0) {
6384
		inode->index_cnt = 2;
6385 6386 6387 6388 6389 6390 6391 6392
		goto out;
	}

	path->slots[0]--;

	leaf = path->nodes[0];
	btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);

6393
	if (found_key.objectid != btrfs_ino(inode) ||
6394
	    found_key.type != BTRFS_DIR_INDEX_KEY) {
6395
		inode->index_cnt = 2;
6396 6397 6398
		goto out;
	}

6399
	inode->index_cnt = found_key.offset + 1;
6400 6401 6402 6403 6404
out:
	btrfs_free_path(path);
	return ret;
}

C
Chris Mason 已提交
6405 6406 6407 6408
/*
 * helper to find a free sequence number in a given directory.  This current
 * code is very simple, later versions will do smarter things in the btree
 */
6409
int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
6410 6411 6412
{
	int ret = 0;

6413 6414
	if (dir->index_cnt == (u64)-1) {
		ret = btrfs_inode_delayed_dir_index_count(dir);
6415 6416 6417 6418 6419
		if (ret) {
			ret = btrfs_set_inode_index_count(dir);
			if (ret)
				return ret;
		}
6420 6421
	}

6422 6423
	*index = dir->index_cnt;
	dir->index_cnt++;
6424 6425 6426 6427

	return ret;
}

6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438
static int btrfs_insert_inode_locked(struct inode *inode)
{
	struct btrfs_iget_args args;
	args.location = &BTRFS_I(inode)->location;
	args.root = BTRFS_I(inode)->root;

	return insert_inode_locked4(inode,
		   btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
		   btrfs_find_actor, &args);
}

6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469
/*
 * Inherit flags from the parent inode.
 *
 * Currently only the compression flags and the cow flags are inherited.
 */
static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
{
	unsigned int flags;

	if (!dir)
		return;

	flags = BTRFS_I(dir)->flags;

	if (flags & BTRFS_INODE_NOCOMPRESS) {
		BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
		BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
	} else if (flags & BTRFS_INODE_COMPRESS) {
		BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
		BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
	}

	if (flags & BTRFS_INODE_NODATACOW) {
		BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
		if (S_ISREG(inode->i_mode))
			BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
	}

	btrfs_update_iflags(inode);
}

C
Chris Mason 已提交
6470 6471
static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
				     struct btrfs_root *root,
6472
				     struct inode *dir,
6473
				     const char *name, int name_len,
A
Al Viro 已提交
6474 6475
				     u64 ref_objectid, u64 objectid,
				     umode_t mode, u64 *index)
C
Chris Mason 已提交
6476
{
6477
	struct btrfs_fs_info *fs_info = root->fs_info;
C
Chris Mason 已提交
6478
	struct inode *inode;
6479
	struct btrfs_inode_item *inode_item;
C
Chris Mason 已提交
6480
	struct btrfs_key *location;
6481
	struct btrfs_path *path;
6482 6483 6484
	struct btrfs_inode_ref *ref;
	struct btrfs_key key[2];
	u32 sizes[2];
6485
	int nitems = name ? 2 : 1;
6486
	unsigned long ptr;
C
Chris Mason 已提交
6487 6488
	int ret;

6489
	path = btrfs_alloc_path();
6490 6491
	if (!path)
		return ERR_PTR(-ENOMEM);
6492

6493
	inode = new_inode(fs_info->sb);
6494 6495
	if (!inode) {
		btrfs_free_path(path);
C
Chris Mason 已提交
6496
		return ERR_PTR(-ENOMEM);
6497
	}
C
Chris Mason 已提交
6498

6499 6500 6501 6502 6503 6504 6505
	/*
	 * O_TMPFILE, set link count to 0, so that after this point,
	 * we fill in an inode item with the correct link count.
	 */
	if (!name)
		set_nlink(inode, 0);

6506 6507 6508 6509 6510 6511
	/*
	 * we have to initialize this early, so we can reclaim the inode
	 * number if we fail afterwards in this function.
	 */
	inode->i_ino = objectid;

6512
	if (dir && name) {
6513 6514
		trace_btrfs_inode_request(dir);

6515
		ret = btrfs_set_inode_index(BTRFS_I(dir), index);
6516
		if (ret) {
6517
			btrfs_free_path(path);
6518
			iput(inode);
6519
			return ERR_PTR(ret);
6520
		}
6521 6522
	} else if (dir) {
		*index = 0;
6523 6524 6525
	}
	/*
	 * index_cnt is ignored for everything but a dir,
6526
	 * btrfs_set_inode_index_count has an explanation for the magic
6527 6528 6529
	 * number
	 */
	BTRFS_I(inode)->index_cnt = 2;
6530
	BTRFS_I(inode)->dir_index = *index;
C
Chris Mason 已提交
6531
	BTRFS_I(inode)->root = root;
6532
	BTRFS_I(inode)->generation = trans->transid;
6533
	inode->i_generation = BTRFS_I(inode)->generation;
6534

J
Josef Bacik 已提交
6535 6536 6537 6538 6539 6540 6541 6542
	/*
	 * We could have gotten an inode number from somebody who was fsynced
	 * and then removed in this same transaction, so let's just set full
	 * sync since it will be a full sync anyway and this will blow away the
	 * old info in the log.
	 */
	set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);

6543
	key[0].objectid = objectid;
6544
	key[0].type = BTRFS_INODE_ITEM_KEY;
6545 6546 6547
	key[0].offset = 0;

	sizes[0] = sizeof(struct btrfs_inode_item);
6548 6549 6550 6551 6552 6553 6554 6555 6556

	if (name) {
		/*
		 * Start new inodes with an inode_ref. This is slightly more
		 * efficient for small numbers of hard links since they will
		 * be packed into one item. Extended refs will kick in if we
		 * add more hard links than can fit in the ref item.
		 */
		key[1].objectid = objectid;
6557
		key[1].type = BTRFS_INODE_REF_KEY;
6558 6559 6560 6561
		key[1].offset = ref_objectid;

		sizes[1] = name_len + sizeof(*ref);
	}
6562

6563 6564 6565
	location = &BTRFS_I(inode)->location;
	location->objectid = objectid;
	location->offset = 0;
6566
	location->type = BTRFS_INODE_ITEM_KEY;
6567 6568 6569 6570 6571

	ret = btrfs_insert_inode_locked(inode);
	if (ret < 0)
		goto fail;

6572
	path->leave_spinning = 1;
6573
	ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
6574
	if (ret != 0)
6575
		goto fail_unlock;
6576

6577
	inode_init_owner(inode, dir, mode);
6578
	inode_set_bytes(inode, 0);
6579

6580
	inode->i_mtime = current_time(inode);
6581 6582 6583 6584
	inode->i_atime = inode->i_mtime;
	inode->i_ctime = inode->i_mtime;
	BTRFS_I(inode)->i_otime = inode->i_mtime;

6585 6586
	inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
				  struct btrfs_inode_item);
6587
	memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
6588
			     sizeof(*inode_item));
6589
	fill_inode_item(trans, path->nodes[0], inode_item, inode);
6590

6591 6592 6593 6594 6595 6596 6597 6598
	if (name) {
		ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
				     struct btrfs_inode_ref);
		btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
		btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
		ptr = (unsigned long)(ref + 1);
		write_extent_buffer(path->nodes[0], name, ptr, name_len);
	}
6599

6600 6601 6602
	btrfs_mark_buffer_dirty(path->nodes[0]);
	btrfs_free_path(path);

6603 6604
	btrfs_inherit_iflags(inode, dir);

6605
	if (S_ISREG(mode)) {
6606
		if (btrfs_test_opt(fs_info, NODATASUM))
6607
			BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6608
		if (btrfs_test_opt(fs_info, NODATACOW))
6609 6610
			BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
				BTRFS_INODE_NODATASUM;
6611 6612
	}

6613
	inode_tree_add(inode);
6614 6615

	trace_btrfs_inode_new(inode);
6616
	btrfs_set_inode_last_trans(trans, inode);
6617

6618 6619
	btrfs_update_root_times(trans, root);

6620 6621
	ret = btrfs_inode_inherit_props(trans, inode, dir);
	if (ret)
6622
		btrfs_err(fs_info,
6623
			  "error inheriting props for ino %llu (root %llu): %d",
6624
			btrfs_ino(BTRFS_I(inode)), root->root_key.objectid, ret);
6625

C
Chris Mason 已提交
6626
	return inode;
6627 6628 6629

fail_unlock:
	unlock_new_inode(inode);
6630
fail:
6631
	if (dir && name)
6632
		BTRFS_I(dir)->index_cnt--;
6633
	btrfs_free_path(path);
6634
	iput(inode);
6635
	return ERR_PTR(ret);
C
Chris Mason 已提交
6636 6637 6638 6639 6640 6641 6642
}

static inline u8 btrfs_inode_type(struct inode *inode)
{
	return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
}

C
Chris Mason 已提交
6643 6644 6645 6646 6647 6648
/*
 * utility function to add 'inode' into 'parent_inode' with
 * a give name and a given sequence number.
 * if 'add_backref' is true, also insert a backref from the
 * inode to the parent directory.
 */
6649
int btrfs_add_link(struct btrfs_trans_handle *trans,
6650
		   struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6651
		   const char *name, int name_len, int add_backref, u64 index)
C
Chris Mason 已提交
6652
{
6653
	struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
6654
	int ret = 0;
C
Chris Mason 已提交
6655
	struct btrfs_key key;
6656 6657 6658
	struct btrfs_root *root = parent_inode->root;
	u64 ino = btrfs_ino(inode);
	u64 parent_ino = btrfs_ino(parent_inode);
6659

L
Li Zefan 已提交
6660
	if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6661
		memcpy(&key, &inode->root->root_key, sizeof(key));
6662
	} else {
L
Li Zefan 已提交
6663
		key.objectid = ino;
6664
		key.type = BTRFS_INODE_ITEM_KEY;
6665 6666 6667
		key.offset = 0;
	}

L
Li Zefan 已提交
6668
	if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6669 6670 6671
		ret = btrfs_add_root_ref(trans, fs_info, key.objectid,
					 root->root_key.objectid, parent_ino,
					 index, name, name_len);
6672
	} else if (add_backref) {
L
Li Zefan 已提交
6673 6674
		ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
					     parent_ino, index);
6675
	}
C
Chris Mason 已提交
6676

6677 6678 6679
	/* Nothing to clean up yet */
	if (ret)
		return ret;
6680

6681 6682
	ret = btrfs_insert_dir_item(trans, root, name, name_len,
				    parent_inode, &key,
6683
				    btrfs_inode_type(&inode->vfs_inode), index);
C
Chris Mason 已提交
6684
	if (ret == -EEXIST || ret == -EOVERFLOW)
6685 6686
		goto fail_dir_item;
	else if (ret) {
6687
		btrfs_abort_transaction(trans, ret);
6688
		return ret;
C
Chris Mason 已提交
6689
	}
6690

6691
	btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6692
			   name_len * 2);
6693 6694 6695 6696
	inode_inc_iversion(&parent_inode->vfs_inode);
	parent_inode->vfs_inode.i_mtime = parent_inode->vfs_inode.i_ctime =
		current_time(&parent_inode->vfs_inode);
	ret = btrfs_update_inode(trans, root, &parent_inode->vfs_inode);
6697
	if (ret)
6698
		btrfs_abort_transaction(trans, ret);
C
Chris Mason 已提交
6699
	return ret;
6700 6701 6702 6703 6704

fail_dir_item:
	if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
		u64 local_index;
		int err;
6705 6706 6707
		err = btrfs_del_root_ref(trans, fs_info, key.objectid,
					 root->root_key.objectid, parent_ino,
					 &local_index, name, name_len);
6708 6709 6710 6711 6712 6713 6714 6715 6716

	} else if (add_backref) {
		u64 local_index;
		int err;

		err = btrfs_del_inode_ref(trans, root, name, name_len,
					  ino, parent_ino, &local_index);
	}
	return ret;
C
Chris Mason 已提交
6717 6718 6719
}

static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6720 6721
			    struct btrfs_inode *dir, struct dentry *dentry,
			    struct btrfs_inode *inode, int backref, u64 index)
C
Chris Mason 已提交
6722
{
6723 6724 6725
	int err = btrfs_add_link(trans, dir, inode,
				 dentry->d_name.name, dentry->d_name.len,
				 backref, index);
C
Chris Mason 已提交
6726 6727 6728 6729 6730
	if (err > 0)
		err = -EEXIST;
	return err;
}

J
Josef Bacik 已提交
6731
static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
A
Al Viro 已提交
6732
			umode_t mode, dev_t rdev)
J
Josef Bacik 已提交
6733
{
6734
	struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
J
Josef Bacik 已提交
6735 6736
	struct btrfs_trans_handle *trans;
	struct btrfs_root *root = BTRFS_I(dir)->root;
6737
	struct inode *inode = NULL;
J
Josef Bacik 已提交
6738 6739 6740
	int err;
	int drop_inode = 0;
	u64 objectid;
6741
	u64 index = 0;
J
Josef Bacik 已提交
6742

J
Josef Bacik 已提交
6743 6744 6745 6746 6747
	/*
	 * 2 for inode item and ref
	 * 2 for dir items
	 * 1 for xattr if selinux is on
	 */
6748 6749 6750
	trans = btrfs_start_transaction(root, 5);
	if (IS_ERR(trans))
		return PTR_ERR(trans);
6751

6752 6753 6754 6755
	err = btrfs_find_free_ino(root, &objectid);
	if (err)
		goto out_unlock;

6756
	inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6757 6758
			dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
			mode, &index);
6759 6760
	if (IS_ERR(inode)) {
		err = PTR_ERR(inode);
J
Josef Bacik 已提交
6761
		goto out_unlock;
6762
	}
J
Josef Bacik 已提交
6763

6764 6765 6766 6767 6768 6769 6770
	/*
	* If the active LSM wants to access the inode during
	* d_instantiate it needs these. Smack checks to see
	* if the filesystem supports xattrs by looking at the
	* ops vector.
	*/
	inode->i_op = &btrfs_special_inode_operations;
6771 6772 6773
	init_special_inode(inode, inode->i_mode, rdev);

	err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
J
Josef Bacik 已提交
6774
	if (err)
6775 6776
		goto out_unlock_inode;

6777 6778
	err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
			0, index);
6779 6780 6781
	if (err) {
		goto out_unlock_inode;
	} else {
6782
		btrfs_update_inode(trans, root, inode);
6783
		d_instantiate_new(dentry, inode);
J
Josef Bacik 已提交
6784
	}
6785

J
Josef Bacik 已提交
6786
out_unlock:
6787
	btrfs_end_transaction(trans);
6788
	btrfs_btree_balance_dirty(fs_info);
J
Josef Bacik 已提交
6789 6790 6791 6792 6793
	if (drop_inode) {
		inode_dec_link_count(inode);
		iput(inode);
	}
	return err;
6794 6795 6796 6797 6798 6799

out_unlock_inode:
	drop_inode = 1;
	unlock_new_inode(inode);
	goto out_unlock;

J
Josef Bacik 已提交
6800 6801
}

C
Chris Mason 已提交
6802
static int btrfs_create(struct inode *dir, struct dentry *dentry,
A
Al Viro 已提交
6803
			umode_t mode, bool excl)
C
Chris Mason 已提交
6804
{
6805
	struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
C
Chris Mason 已提交
6806 6807
	struct btrfs_trans_handle *trans;
	struct btrfs_root *root = BTRFS_I(dir)->root;
6808
	struct inode *inode = NULL;
6809
	int drop_inode_on_err = 0;
6810
	int err;
C
Chris Mason 已提交
6811
	u64 objectid;
6812
	u64 index = 0;
C
Chris Mason 已提交
6813

J
Josef Bacik 已提交
6814 6815 6816 6817 6818
	/*
	 * 2 for inode item and ref
	 * 2 for dir items
	 * 1 for xattr if selinux is on
	 */
6819 6820 6821
	trans = btrfs_start_transaction(root, 5);
	if (IS_ERR(trans))
		return PTR_ERR(trans);
J
Josef Bacik 已提交
6822

6823 6824 6825 6826
	err = btrfs_find_free_ino(root, &objectid);
	if (err)
		goto out_unlock;

6827
	inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6828 6829
			dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
			mode, &index);
6830 6831
	if (IS_ERR(inode)) {
		err = PTR_ERR(inode);
C
Chris Mason 已提交
6832
		goto out_unlock;
6833
	}
6834
	drop_inode_on_err = 1;
6835 6836 6837 6838 6839 6840 6841 6842
	/*
	* If the active LSM wants to access the inode during
	* d_instantiate it needs these. Smack checks to see
	* if the filesystem supports xattrs by looking at the
	* ops vector.
	*/
	inode->i_fop = &btrfs_file_operations;
	inode->i_op = &btrfs_file_inode_operations;
6843 6844 6845 6846 6847 6848 6849 6850 6851
	inode->i_mapping->a_ops = &btrfs_aops;

	err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
	if (err)
		goto out_unlock_inode;

	err = btrfs_update_inode(trans, root, inode);
	if (err)
		goto out_unlock_inode;
6852

6853 6854
	err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
			0, index);
C
Chris Mason 已提交
6855
	if (err)
6856
		goto out_unlock_inode;
6857 6858

	BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
6859
	d_instantiate_new(dentry, inode);
6860

C
Chris Mason 已提交
6861
out_unlock:
6862
	btrfs_end_transaction(trans);
6863
	if (err && drop_inode_on_err) {
C
Chris Mason 已提交
6864 6865 6866
		inode_dec_link_count(inode);
		iput(inode);
	}
6867
	btrfs_btree_balance_dirty(fs_info);
C
Chris Mason 已提交
6868
	return err;
6869 6870 6871 6872 6873

out_unlock_inode:
	unlock_new_inode(inode);
	goto out_unlock;

C
Chris Mason 已提交
6874 6875 6876 6877 6878
}

static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
		      struct dentry *dentry)
{
6879
	struct btrfs_trans_handle *trans = NULL;
C
Chris Mason 已提交
6880
	struct btrfs_root *root = BTRFS_I(dir)->root;
6881
	struct inode *inode = d_inode(old_dentry);
6882
	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6883
	u64 index;
C
Chris Mason 已提交
6884 6885 6886
	int err;
	int drop_inode = 0;

6887 6888
	/* do not allow sys_link's with other subvols of the same device */
	if (root->objectid != BTRFS_I(inode)->root->objectid)
6889
		return -EXDEV;
6890

M
Mark Fasheh 已提交
6891
	if (inode->i_nlink >= BTRFS_LINK_MAX)
6892
		return -EMLINK;
6893

6894
	err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6895 6896 6897
	if (err)
		goto fail;

6898
	/*
M
Miao Xie 已提交
6899
	 * 2 items for inode and inode ref
6900
	 * 2 items for dir items
M
Miao Xie 已提交
6901
	 * 1 item for parent inode
6902
	 */
M
Miao Xie 已提交
6903
	trans = btrfs_start_transaction(root, 5);
6904 6905
	if (IS_ERR(trans)) {
		err = PTR_ERR(trans);
6906
		trans = NULL;
6907 6908
		goto fail;
	}
6909

6910 6911
	/* There are several dir indexes for this inode, clear the cache. */
	BTRFS_I(inode)->dir_index = 0ULL;
Z
Zach Brown 已提交
6912
	inc_nlink(inode);
6913
	inode_inc_iversion(inode);
6914
	inode->i_ctime = current_time(inode);
A
Al Viro 已提交
6915
	ihold(inode);
6916
	set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6917

6918 6919
	err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
			1, index);
6920

6921
	if (err) {
6922
		drop_inode = 1;
6923
	} else {
6924
		struct dentry *parent = dentry->d_parent;
6925
		err = btrfs_update_inode(trans, root, inode);
6926 6927
		if (err)
			goto fail;
6928 6929 6930 6931 6932
		if (inode->i_nlink == 1) {
			/*
			 * If new hard link count is 1, it's a file created
			 * with open(2) O_TMPFILE flag.
			 */
6933
			err = btrfs_orphan_del(trans, BTRFS_I(inode));
6934 6935 6936
			if (err)
				goto fail;
		}
6937
		d_instantiate(dentry, inode);
6938
		btrfs_log_new_name(trans, BTRFS_I(inode), NULL, parent);
6939
	}
C
Chris Mason 已提交
6940

6941
fail:
6942
	if (trans)
6943
		btrfs_end_transaction(trans);
C
Chris Mason 已提交
6944 6945 6946 6947
	if (drop_inode) {
		inode_dec_link_count(inode);
		iput(inode);
	}
6948
	btrfs_btree_balance_dirty(fs_info);
C
Chris Mason 已提交
6949 6950 6951
	return err;
}

6952
static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
C
Chris Mason 已提交
6953
{
6954
	struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6955
	struct inode *inode = NULL;
C
Chris Mason 已提交
6956 6957 6958 6959
	struct btrfs_trans_handle *trans;
	struct btrfs_root *root = BTRFS_I(dir)->root;
	int err = 0;
	int drop_on_err = 0;
6960
	u64 objectid = 0;
6961
	u64 index = 0;
C
Chris Mason 已提交
6962

J
Josef Bacik 已提交
6963 6964 6965 6966 6967
	/*
	 * 2 items for inode and ref
	 * 2 items for dir items
	 * 1 for xattr if selinux is on
	 */
6968 6969 6970
	trans = btrfs_start_transaction(root, 5);
	if (IS_ERR(trans))
		return PTR_ERR(trans);
C
Chris Mason 已提交
6971

6972 6973 6974 6975
	err = btrfs_find_free_ino(root, &objectid);
	if (err)
		goto out_fail;

6976
	inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6977 6978
			dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
			S_IFDIR | mode, &index);
C
Chris Mason 已提交
6979 6980 6981 6982
	if (IS_ERR(inode)) {
		err = PTR_ERR(inode);
		goto out_fail;
	}
6983

C
Chris Mason 已提交
6984
	drop_on_err = 1;
6985 6986 6987
	/* these must be set before we unlock the inode */
	inode->i_op = &btrfs_dir_inode_operations;
	inode->i_fop = &btrfs_dir_file_operations;
J
Josef Bacik 已提交
6988

6989
	err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
J
Josef Bacik 已提交
6990
	if (err)
6991
		goto out_fail_inode;
C
Chris Mason 已提交
6992

6993
	btrfs_i_size_write(BTRFS_I(inode), 0);
C
Chris Mason 已提交
6994 6995
	err = btrfs_update_inode(trans, root, inode);
	if (err)
6996
		goto out_fail_inode;
6997

6998 6999 7000
	err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
			dentry->d_name.name,
			dentry->d_name.len, 0, index);
C
Chris Mason 已提交
7001
	if (err)
7002
		goto out_fail_inode;
7003

7004
	d_instantiate_new(dentry, inode);
C
Chris Mason 已提交
7005 7006 7007
	drop_on_err = 0;

out_fail:
7008
	btrfs_end_transaction(trans);
7009 7010
	if (drop_on_err) {
		inode_dec_link_count(inode);
C
Chris Mason 已提交
7011
		iput(inode);
7012
	}
7013
	btrfs_btree_balance_dirty(fs_info);
C
Chris Mason 已提交
7014
	return err;
7015 7016 7017 7018

out_fail_inode:
	unlock_new_inode(inode);
	goto out_fail;
C
Chris Mason 已提交
7019 7020
}

C
Chris Mason 已提交
7021
static noinline int uncompress_inline(struct btrfs_path *path,
7022
				      struct page *page,
C
Chris Mason 已提交
7023 7024 7025 7026 7027 7028 7029 7030 7031
				      size_t pg_offset, u64 extent_offset,
				      struct btrfs_file_extent_item *item)
{
	int ret;
	struct extent_buffer *leaf = path->nodes[0];
	char *tmp;
	size_t max_size;
	unsigned long inline_size;
	unsigned long ptr;
7032
	int compress_type;
C
Chris Mason 已提交
7033 7034

	WARN_ON(pg_offset != 0);
7035
	compress_type = btrfs_file_extent_compression(leaf, item);
C
Chris Mason 已提交
7036 7037
	max_size = btrfs_file_extent_ram_bytes(leaf, item);
	inline_size = btrfs_file_extent_inline_item_len(leaf,
7038
					btrfs_item_nr(path->slots[0]));
C
Chris Mason 已提交
7039
	tmp = kmalloc(inline_size, GFP_NOFS);
7040 7041
	if (!tmp)
		return -ENOMEM;
C
Chris Mason 已提交
7042 7043 7044 7045
	ptr = btrfs_file_extent_inline_start(item);

	read_extent_buffer(leaf, tmp, ptr, inline_size);

7046
	max_size = min_t(unsigned long, PAGE_SIZE, max_size);
7047 7048
	ret = btrfs_decompress(compress_type, tmp, page,
			       extent_offset, inline_size, max_size);
7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062

	/*
	 * decompression code contains a memset to fill in any space between the end
	 * of the uncompressed data and the end of max_size in case the decompressed
	 * data ends up shorter than ram_bytes.  That doesn't cover the hole between
	 * the end of an inline extent and the beginning of the next block, so we
	 * cover that region here.
	 */

	if (max_size + pg_offset < PAGE_SIZE) {
		char *map = kmap(page);
		memset(map + pg_offset + max_size, 0, PAGE_SIZE - max_size - pg_offset);
		kunmap(page);
	}
C
Chris Mason 已提交
7063
	kfree(tmp);
7064
	return ret;
C
Chris Mason 已提交
7065 7066
}

C
Chris Mason 已提交
7067 7068
/*
 * a bit scary, this does extent mapping from logical file offset to the disk.
C
Chris Mason 已提交
7069 7070
 * the ugly parts come from merging extents from the disk with the in-ram
 * representation.  This gets more complex because of the data=ordered code,
C
Chris Mason 已提交
7071 7072 7073 7074
 * where the in-ram extents might be locked pending data=ordered completion.
 *
 * This also copies inline extents directly into the page.
 */
7075 7076 7077 7078
struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
		struct page *page,
	    size_t pg_offset, u64 start, u64 len,
		int create)
7079
{
7080
	struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
7081 7082 7083 7084
	int ret;
	int err = 0;
	u64 extent_start = 0;
	u64 extent_end = 0;
7085
	u64 objectid = btrfs_ino(inode);
7086
	u32 found_type;
7087
	struct btrfs_path *path = NULL;
7088
	struct btrfs_root *root = inode->root;
7089
	struct btrfs_file_extent_item *item;
7090 7091
	struct extent_buffer *leaf;
	struct btrfs_key found_key;
7092
	struct extent_map *em = NULL;
7093 7094
	struct extent_map_tree *em_tree = &inode->extent_tree;
	struct extent_io_tree *io_tree = &inode->io_tree;
7095
	const bool new_inline = !page || create;
7096

7097
	read_lock(&em_tree->lock);
7098
	em = lookup_extent_mapping(em_tree, start, len);
7099
	if (em)
7100
		em->bdev = fs_info->fs_devices->latest_bdev;
7101
	read_unlock(&em_tree->lock);
7102

7103
	if (em) {
7104 7105 7106
		if (em->start > start || em->start + em->len <= start)
			free_extent_map(em);
		else if (em->block_start == EXTENT_MAP_INLINE && page)
7107 7108 7109
			free_extent_map(em);
		else
			goto out;
7110
	}
7111
	em = alloc_extent_map();
7112
	if (!em) {
7113 7114
		err = -ENOMEM;
		goto out;
7115
	}
7116
	em->bdev = fs_info->fs_devices->latest_bdev;
7117
	em->start = EXTENT_MAP_HOLE;
7118
	em->orig_start = EXTENT_MAP_HOLE;
7119
	em->len = (u64)-1;
C
Chris Mason 已提交
7120
	em->block_len = (u64)-1;
7121 7122 7123

	if (!path) {
		path = btrfs_alloc_path();
J
Josef Bacik 已提交
7124 7125 7126 7127 7128 7129 7130 7131
		if (!path) {
			err = -ENOMEM;
			goto out;
		}
		/*
		 * Chances are we'll be called again, so go ahead and do
		 * readahead
		 */
7132
		path->reada = READA_FORWARD;
7133 7134
	}

7135
	ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146
	if (ret < 0) {
		err = ret;
		goto out;
	}

	if (ret != 0) {
		if (path->slots[0] == 0)
			goto not_found;
		path->slots[0]--;
	}

7147 7148
	leaf = path->nodes[0];
	item = btrfs_item_ptr(leaf, path->slots[0],
7149 7150
			      struct btrfs_file_extent_item);
	/* are we inside the extent that was found? */
7151
	btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
7152
	found_type = found_key.type;
7153
	if (found_key.objectid != objectid ||
7154
	    found_type != BTRFS_EXTENT_DATA_KEY) {
7155 7156 7157 7158 7159 7160 7161 7162
		/*
		 * If we backup past the first extent we want to move forward
		 * and see if there is an extent in front of us, otherwise we'll
		 * say there is a hole for our whole search range which can
		 * cause problems.
		 */
		extent_end = start;
		goto next;
7163 7164
	}

7165 7166
	found_type = btrfs_file_extent_type(leaf, item);
	extent_start = found_key.offset;
Y
Yan Zheng 已提交
7167 7168
	if (found_type == BTRFS_FILE_EXTENT_REG ||
	    found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7169
		extent_end = extent_start +
7170
		       btrfs_file_extent_num_bytes(leaf, item);
L
Liu Bo 已提交
7171 7172 7173

		trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
						       extent_start);
Y
Yan Zheng 已提交
7174 7175
	} else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
		size_t size;
7176
		size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
7177
		extent_end = ALIGN(extent_start + size,
7178
				   fs_info->sectorsize);
L
Liu Bo 已提交
7179 7180 7181 7182

		trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
						      path->slots[0],
						      extent_start);
Y
Yan Zheng 已提交
7183
	}
7184
next:
Y
Yan Zheng 已提交
7185 7186 7187 7188 7189 7190 7191
	if (start >= extent_end) {
		path->slots[0]++;
		if (path->slots[0] >= btrfs_header_nritems(leaf)) {
			ret = btrfs_next_leaf(root, path);
			if (ret < 0) {
				err = ret;
				goto out;
7192
			}
Y
Yan Zheng 已提交
7193 7194 7195
			if (ret > 0)
				goto not_found;
			leaf = path->nodes[0];
7196
		}
Y
Yan Zheng 已提交
7197 7198 7199 7200 7201 7202
		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
		if (found_key.objectid != objectid ||
		    found_key.type != BTRFS_EXTENT_DATA_KEY)
			goto not_found;
		if (start + len <= found_key.offset)
			goto not_found;
7203 7204
		if (start > found_key.offset)
			goto next;
Y
Yan Zheng 已提交
7205
		em->start = start;
7206
		em->orig_start = start;
Y
Yan Zheng 已提交
7207 7208 7209 7210
		em->len = found_key.offset - start;
		goto not_found_em;
	}

7211
	btrfs_extent_item_to_extent_map(inode, path, item,
7212
			new_inline, em);
7213

Y
Yan Zheng 已提交
7214 7215
	if (found_type == BTRFS_FILE_EXTENT_REG ||
	    found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7216 7217
		goto insert;
	} else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
7218
		unsigned long ptr;
7219
		char *map;
7220 7221 7222
		size_t size;
		size_t extent_offset;
		size_t copy_size;
7223

7224
		if (new_inline)
7225
			goto out;
7226

7227
		size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
Y
Yan Zheng 已提交
7228
		extent_offset = page_offset(page) + pg_offset - extent_start;
7229 7230
		copy_size = min_t(u64, PAGE_SIZE - pg_offset,
				  size - extent_offset);
7231
		em->start = extent_start + extent_offset;
7232
		em->len = ALIGN(copy_size, fs_info->sectorsize);
7233
		em->orig_block_len = em->len;
7234
		em->orig_start = em->start;
7235
		ptr = btrfs_file_extent_inline_start(item) + extent_offset;
7236
		if (!PageUptodate(page)) {
7237 7238
			if (btrfs_file_extent_compression(leaf, item) !=
			    BTRFS_COMPRESS_NONE) {
7239
				ret = uncompress_inline(path, page, pg_offset,
C
Chris Mason 已提交
7240
							extent_offset, item);
7241 7242 7243 7244
				if (ret) {
					err = ret;
					goto out;
				}
C
Chris Mason 已提交
7245 7246 7247 7248
			} else {
				map = kmap(page);
				read_extent_buffer(leaf, map + pg_offset, ptr,
						   copy_size);
7249
				if (pg_offset + copy_size < PAGE_SIZE) {
7250
					memset(map + pg_offset + copy_size, 0,
7251
					       PAGE_SIZE - pg_offset -
7252 7253
					       copy_size);
				}
C
Chris Mason 已提交
7254 7255
				kunmap(page);
			}
7256
			flush_dcache_page(page);
7257
		}
7258
		set_extent_uptodate(io_tree, em->start,
7259
				    extent_map_end(em) - 1, NULL, GFP_NOFS);
7260 7261 7262 7263
		goto insert;
	}
not_found:
	em->start = start;
7264
	em->orig_start = start;
7265
	em->len = len;
7266
not_found_em:
7267
	em->block_start = EXTENT_MAP_HOLE;
7268
insert:
7269
	btrfs_release_path(path);
7270
	if (em->start > start || extent_map_end(em) <= start) {
7271
		btrfs_err(fs_info,
J
Jeff Mahoney 已提交
7272 7273
			  "bad extent! em: [%llu %llu] passed [%llu %llu]",
			  em->start, em->len, start, len);
7274 7275 7276
		err = -EIO;
		goto out;
	}
7277 7278

	err = 0;
7279
	write_lock(&em_tree->lock);
7280
	err = btrfs_add_extent_mapping(fs_info, em_tree, &em, start, len);
7281
	write_unlock(&em_tree->lock);
7282
out:
7283

7284
	trace_btrfs_get_extent(root, inode, em);
7285

7286
	btrfs_free_path(path);
7287 7288 7289 7290
	if (err) {
		free_extent_map(em);
		return ERR_PTR(err);
	}
7291
	BUG_ON(!em); /* Error is always set */
7292 7293 7294
	return em;
}

7295 7296 7297 7298
struct extent_map *btrfs_get_extent_fiemap(struct btrfs_inode *inode,
		struct page *page,
		size_t pg_offset, u64 start, u64 len,
		int create)
7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310
{
	struct extent_map *em;
	struct extent_map *hole_em = NULL;
	u64 range_start = start;
	u64 end;
	u64 found;
	u64 found_end;
	int err = 0;

	em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
	if (IS_ERR(em))
		return em;
7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321
	/*
	 * If our em maps to:
	 * - a hole or
	 * - a pre-alloc extent,
	 * there might actually be delalloc bytes behind it.
	 */
	if (em->block_start != EXTENT_MAP_HOLE &&
	    !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
		return em;
	else
		hole_em = em;
7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332

	/* check to see if we've wrapped (len == -1 or similar) */
	end = start + len;
	if (end < start)
		end = (u64)-1;
	else
		end -= 1;

	em = NULL;

	/* ok, we didn't find anything, lets look for delalloc */
7333
	found = count_range_bits(&inode->io_tree, &range_start,
7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351
				 end, len, EXTENT_DELALLOC, 1);
	found_end = range_start + found;
	if (found_end < range_start)
		found_end = (u64)-1;

	/*
	 * we didn't find anything useful, return
	 * the original results from get_extent()
	 */
	if (range_start > end || found_end <= start) {
		em = hole_em;
		hole_em = NULL;
		goto out;
	}

	/* adjust the range_start to make sure it doesn't
	 * go backwards from the start they passed in
	 */
7352
	range_start = max(start, range_start);
7353 7354 7355 7356 7357 7358
	found = found_end - range_start;

	if (found > 0) {
		u64 hole_start = start;
		u64 hole_len = len;

7359
		em = alloc_extent_map();
7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398
		if (!em) {
			err = -ENOMEM;
			goto out;
		}
		/*
		 * when btrfs_get_extent can't find anything it
		 * returns one huge hole
		 *
		 * make sure what it found really fits our range, and
		 * adjust to make sure it is based on the start from
		 * the caller
		 */
		if (hole_em) {
			u64 calc_end = extent_map_end(hole_em);

			if (calc_end <= start || (hole_em->start > end)) {
				free_extent_map(hole_em);
				hole_em = NULL;
			} else {
				hole_start = max(hole_em->start, start);
				hole_len = calc_end - hole_start;
			}
		}
		em->bdev = NULL;
		if (hole_em && range_start > hole_start) {
			/* our hole starts before our delalloc, so we
			 * have to return just the parts of the hole
			 * that go until  the delalloc starts
			 */
			em->len = min(hole_len,
				      range_start - hole_start);
			em->start = hole_start;
			em->orig_start = hole_start;
			/*
			 * don't adjust block start at all,
			 * it is fixed at EXTENT_MAP_HOLE
			 */
			em->block_start = hole_em->block_start;
			em->block_len = hole_len;
7399 7400
			if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
				set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
7401 7402 7403 7404 7405 7406 7407
		} else {
			em->start = range_start;
			em->len = found;
			em->orig_start = range_start;
			em->block_start = EXTENT_MAP_DELALLOC;
			em->block_len = found;
		}
7408
	} else {
7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420
		return hole_em;
	}
out:

	free_extent_map(hole_em);
	if (err) {
		free_extent_map(em);
		return ERR_PTR(err);
	}
	return em;
}

7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434
static struct extent_map *btrfs_create_dio_extent(struct inode *inode,
						  const u64 start,
						  const u64 len,
						  const u64 orig_start,
						  const u64 block_start,
						  const u64 block_len,
						  const u64 orig_block_len,
						  const u64 ram_bytes,
						  const int type)
{
	struct extent_map *em = NULL;
	int ret;

	if (type != BTRFS_ORDERED_NOCOW) {
7435 7436 7437 7438 7439
		em = create_io_em(inode, start, len, orig_start,
				  block_start, block_len, orig_block_len,
				  ram_bytes,
				  BTRFS_COMPRESS_NONE, /* compress_type */
				  type);
7440 7441 7442 7443 7444 7445 7446 7447
		if (IS_ERR(em))
			goto out;
	}
	ret = btrfs_add_ordered_extent_dio(inode, start, block_start,
					   len, block_len, type);
	if (ret) {
		if (em) {
			free_extent_map(em);
7448
			btrfs_drop_extent_cache(BTRFS_I(inode), start,
7449 7450 7451 7452 7453 7454 7455 7456 7457
						start + len - 1, 0);
		}
		em = ERR_PTR(ret);
	}
 out:

	return em;
}

7458 7459 7460
static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
						  u64 start, u64 len)
{
7461
	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7462
	struct btrfs_root *root = BTRFS_I(inode)->root;
7463
	struct extent_map *em;
7464 7465 7466 7467 7468
	struct btrfs_key ins;
	u64 alloc_hint;
	int ret;

	alloc_hint = get_extent_allocation_hint(inode, start, len);
7469
	ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
7470
				   0, alloc_hint, &ins, 1, 1);
7471 7472
	if (ret)
		return ERR_PTR(ret);
7473

7474 7475
	em = btrfs_create_dio_extent(inode, start, ins.offset, start,
				     ins.objectid, ins.offset, ins.offset,
7476
				     ins.offset, BTRFS_ORDERED_REGULAR);
7477
	btrfs_dec_block_group_reservations(fs_info, ins.objectid);
7478
	if (IS_ERR(em))
7479 7480
		btrfs_free_reserved_extent(fs_info, ins.objectid,
					   ins.offset, 1);
7481

7482 7483 7484
	return em;
}

7485 7486 7487 7488
/*
 * returns 1 when the nocow is safe, < 1 on error, 0 if the
 * block must be cow'd
 */
7489
noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7490 7491
			      u64 *orig_start, u64 *orig_block_len,
			      u64 *ram_bytes)
7492
{
7493
	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7494 7495 7496 7497
	struct btrfs_path *path;
	int ret;
	struct extent_buffer *leaf;
	struct btrfs_root *root = BTRFS_I(inode)->root;
7498
	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7499 7500 7501 7502 7503 7504 7505 7506
	struct btrfs_file_extent_item *fi;
	struct btrfs_key key;
	u64 disk_bytenr;
	u64 backref_offset;
	u64 extent_end;
	u64 num_bytes;
	int slot;
	int found_type;
7507
	bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
7508

7509 7510 7511 7512
	path = btrfs_alloc_path();
	if (!path)
		return -ENOMEM;

7513 7514
	ret = btrfs_lookup_file_extent(NULL, root, path,
			btrfs_ino(BTRFS_I(inode)), offset, 0);
7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529
	if (ret < 0)
		goto out;

	slot = path->slots[0];
	if (ret == 1) {
		if (slot == 0) {
			/* can't find the item, must cow */
			ret = 0;
			goto out;
		}
		slot--;
	}
	ret = 0;
	leaf = path->nodes[0];
	btrfs_item_key_to_cpu(leaf, &key, slot);
7530
	if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547
	    key.type != BTRFS_EXTENT_DATA_KEY) {
		/* not our file or wrong item type, must cow */
		goto out;
	}

	if (key.offset > offset) {
		/* Wrong offset, must cow */
		goto out;
	}

	fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
	found_type = btrfs_file_extent_type(leaf, fi);
	if (found_type != BTRFS_FILE_EXTENT_REG &&
	    found_type != BTRFS_FILE_EXTENT_PREALLOC) {
		/* not a regular extent, must cow */
		goto out;
	}
7548 7549 7550 7551

	if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
		goto out;

7552 7553 7554 7555
	extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
	if (extent_end <= offset)
		goto out;

7556
	disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
7557 7558 7559 7560 7561 7562 7563 7564
	if (disk_bytenr == 0)
		goto out;

	if (btrfs_file_extent_compression(leaf, fi) ||
	    btrfs_file_extent_encryption(leaf, fi) ||
	    btrfs_file_extent_other_encoding(leaf, fi))
		goto out;

7565 7566
	backref_offset = btrfs_file_extent_offset(leaf, fi);

7567 7568 7569 7570 7571
	if (orig_start) {
		*orig_start = key.offset - backref_offset;
		*orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
		*ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
	}
7572

7573
	if (btrfs_extent_readonly(fs_info, disk_bytenr))
7574
		goto out;
7575 7576 7577 7578 7579

	num_bytes = min(offset + *len, extent_end) - offset;
	if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
		u64 range_end;

7580 7581
		range_end = round_up(offset + num_bytes,
				     root->fs_info->sectorsize) - 1;
7582 7583 7584 7585 7586 7587 7588 7589
		ret = test_range_bit(io_tree, offset, range_end,
				     EXTENT_DELALLOC, 0, NULL);
		if (ret) {
			ret = -EAGAIN;
			goto out;
		}
	}

7590
	btrfs_release_path(path);
7591 7592 7593 7594 7595

	/*
	 * look for other files referencing this extent, if we
	 * find any we must cow
	 */
7596

7597
	ret = btrfs_cross_ref_exist(root, btrfs_ino(BTRFS_I(inode)),
7598 7599 7600 7601 7602
				    key.offset - backref_offset, disk_bytenr);
	if (ret) {
		ret = 0;
		goto out;
	}
7603 7604 7605 7606 7607 7608 7609 7610 7611

	/*
	 * adjust disk_bytenr and num_bytes to cover just the bytes
	 * in this extent we are about to write.  If there
	 * are any csums in that range we have to cow in order
	 * to keep the csums correct
	 */
	disk_bytenr += backref_offset;
	disk_bytenr += offset - key.offset;
7612 7613
	if (csum_exist_in_range(fs_info, disk_bytenr, num_bytes))
		goto out;
7614 7615 7616 7617
	/*
	 * all of the above have passed, it is safe to overwrite this extent
	 * without cow
	 */
7618
	*len = num_bytes;
7619 7620 7621 7622 7623 7624
	ret = 1;
out:
	btrfs_free_path(path);
	return ret;
}

7625 7626 7627 7628 7629 7630 7631 7632
static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
			      struct extent_state **cached_state, int writing)
{
	struct btrfs_ordered_extent *ordered;
	int ret = 0;

	while (1) {
		lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7633
				 cached_state);
7634 7635
		/*
		 * We're concerned with the entire range that we're going to be
7636
		 * doing DIO to, so we need to make sure there's no ordered
7637 7638
		 * extents in this range.
		 */
7639
		ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
7640 7641 7642 7643 7644 7645 7646 7647 7648
						     lockend - lockstart + 1);

		/*
		 * We need to make sure there are no buffered pages in this
		 * range either, we could have raced between the invalidate in
		 * generic_file_direct_write and locking the extent.  The
		 * invalidate needs to happen so that reads after a write do not
		 * get stale data.
		 */
7649
		if (!ordered &&
7650 7651
		    (!writing || !filemap_range_has_page(inode->i_mapping,
							 lockstart, lockend)))
7652 7653 7654
			break;

		unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7655
				     cached_state);
7656 7657

		if (ordered) {
7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677
			/*
			 * If we are doing a DIO read and the ordered extent we
			 * found is for a buffered write, we can not wait for it
			 * to complete and retry, because if we do so we can
			 * deadlock with concurrent buffered writes on page
			 * locks. This happens only if our DIO read covers more
			 * than one extent map, if at this point has already
			 * created an ordered extent for a previous extent map
			 * and locked its range in the inode's io tree, and a
			 * concurrent write against that previous extent map's
			 * range and this range started (we unlock the ranges
			 * in the io tree only when the bios complete and
			 * buffered writes always lock pages before attempting
			 * to lock range in the io tree).
			 */
			if (writing ||
			    test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
				btrfs_start_ordered_extent(inode, ordered, 1);
			else
				ret = -ENOTBLK;
7678 7679 7680
			btrfs_put_ordered_extent(ordered);
		} else {
			/*
7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691
			 * We could trigger writeback for this range (and wait
			 * for it to complete) and then invalidate the pages for
			 * this range (through invalidate_inode_pages2_range()),
			 * but that can lead us to a deadlock with a concurrent
			 * call to readpages() (a buffered read or a defrag call
			 * triggered a readahead) on a page lock due to an
			 * ordered dio extent we created before but did not have
			 * yet a corresponding bio submitted (whence it can not
			 * complete), which makes readpages() wait for that
			 * ordered extent to complete while holding a lock on
			 * that page.
7692
			 */
7693
			ret = -ENOTBLK;
7694 7695
		}

7696 7697 7698
		if (ret)
			break;

7699 7700 7701 7702 7703 7704
		cond_resched();
	}

	return ret;
}

7705 7706 7707 7708 7709 7710
/* The callers of this must take lock_extent() */
static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
				       u64 orig_start, u64 block_start,
				       u64 block_len, u64 orig_block_len,
				       u64 ram_bytes, int compress_type,
				       int type)
7711 7712 7713 7714 7715 7716
{
	struct extent_map_tree *em_tree;
	struct extent_map *em;
	struct btrfs_root *root = BTRFS_I(inode)->root;
	int ret;

7717 7718 7719
	ASSERT(type == BTRFS_ORDERED_PREALLOC ||
	       type == BTRFS_ORDERED_COMPRESSED ||
	       type == BTRFS_ORDERED_NOCOW ||
7720
	       type == BTRFS_ORDERED_REGULAR);
7721

7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732
	em_tree = &BTRFS_I(inode)->extent_tree;
	em = alloc_extent_map();
	if (!em)
		return ERR_PTR(-ENOMEM);

	em->start = start;
	em->orig_start = orig_start;
	em->len = len;
	em->block_len = block_len;
	em->block_start = block_start;
	em->bdev = root->fs_info->fs_devices->latest_bdev;
7733
	em->orig_block_len = orig_block_len;
J
Josef Bacik 已提交
7734
	em->ram_bytes = ram_bytes;
7735
	em->generation = -1;
7736
	set_bit(EXTENT_FLAG_PINNED, &em->flags);
7737
	if (type == BTRFS_ORDERED_PREALLOC) {
7738
		set_bit(EXTENT_FLAG_FILLING, &em->flags);
7739
	} else if (type == BTRFS_ORDERED_COMPRESSED) {
7740 7741 7742
		set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
		em->compress_type = compress_type;
	}
7743 7744

	do {
7745
		btrfs_drop_extent_cache(BTRFS_I(inode), em->start,
7746 7747
				em->start + em->len - 1, 0);
		write_lock(&em_tree->lock);
J
Josef Bacik 已提交
7748
		ret = add_extent_mapping(em_tree, em, 1);
7749
		write_unlock(&em_tree->lock);
7750 7751 7752 7753
		/*
		 * The caller has taken lock_extent(), who could race with us
		 * to add em?
		 */
7754 7755 7756 7757 7758 7759 7760
	} while (ret == -EEXIST);

	if (ret) {
		free_extent_map(em);
		return ERR_PTR(ret);
	}

7761
	/* em got 2 refs now, callers needs to do free_extent_map once. */
7762 7763 7764
	return em;
}

7765 7766 7767
static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
				   struct buffer_head *bh_result, int create)
{
7768
	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7769
	struct extent_map *em;
7770
	struct extent_state *cached_state = NULL;
7771
	struct btrfs_dio_data *dio_data = NULL;
7772
	u64 start = iblock << inode->i_blkbits;
7773
	u64 lockstart, lockend;
7774
	u64 len = bh_result->b_size;
7775
	int unlock_bits = EXTENT_LOCKED;
7776
	int ret = 0;
7777

7778
	if (create)
7779
		unlock_bits |= EXTENT_DIRTY;
7780
	else
7781
		len = min_t(u64, len, fs_info->sectorsize);
7782

7783 7784 7785
	lockstart = start;
	lockend = start + len - 1;

7786 7787 7788
	if (current->journal_info) {
		/*
		 * Need to pull our outstanding extents and set journal_info to NULL so
7789
		 * that anything that needs to check if there's a transaction doesn't get
7790 7791
		 * confused.
		 */
7792
		dio_data = current->journal_info;
7793 7794 7795
		current->journal_info = NULL;
	}

7796 7797 7798 7799
	/*
	 * If this errors out it's because we couldn't invalidate pagecache for
	 * this range and we need to fallback to buffered.
	 */
7800 7801 7802 7803 7804
	if (lock_extent_direct(inode, lockstart, lockend, &cached_state,
			       create)) {
		ret = -ENOTBLK;
		goto err;
	}
7805

7806
	em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
7807 7808 7809 7810
	if (IS_ERR(em)) {
		ret = PTR_ERR(em);
		goto unlock_err;
	}
7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821

	/*
	 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
	 * io.  INLINE is special, and we could probably kludge it in here, but
	 * it's still buffered so for safety lets just fall back to the generic
	 * buffered path.
	 *
	 * For COMPRESSED we _have_ to read the entire extent in so we can
	 * decompress it, so there will be buffering required no matter what we
	 * do, so go ahead and fallback to buffered.
	 *
7822
	 * We return -ENOTBLK because that's what makes DIO go ahead and go back
7823 7824 7825 7826 7827 7828
	 * to buffered IO.  Don't blame me, this is the price we pay for using
	 * the generic code.
	 */
	if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
	    em->block_start == EXTENT_MAP_INLINE) {
		free_extent_map(em);
7829 7830
		ret = -ENOTBLK;
		goto unlock_err;
7831 7832 7833 7834 7835 7836
	}

	/* Just a good old fashioned hole, return */
	if (!create && (em->block_start == EXTENT_MAP_HOLE ||
			test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
		free_extent_map(em);
7837
		goto unlock_err;
7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848
	}

	/*
	 * We don't allocate a new extent in the following cases
	 *
	 * 1) The inode is marked as NODATACOW.  In this case we'll just use the
	 * existing extent.
	 * 2) The extent is marked as PREALLOC.  We're good to go here and can
	 * just use the extent.
	 *
	 */
7849
	if (!create) {
7850 7851 7852
		len = min(len, em->len - (start - em->start));
		lockstart = start + len;
		goto unlock;
7853
	}
7854 7855 7856 7857 7858

	if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
	    ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
	     em->block_start != EXTENT_MAP_HOLE)) {
		int type;
7859
		u64 block_start, orig_start, orig_block_len, ram_bytes;
7860 7861 7862 7863 7864

		if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
			type = BTRFS_ORDERED_PREALLOC;
		else
			type = BTRFS_ORDERED_NOCOW;
7865
		len = min(len, em->len - (start - em->start));
7866
		block_start = em->block_start + (start - em->start);
7867

7868
		if (can_nocow_extent(inode, start, &len, &orig_start,
7869
				     &orig_block_len, &ram_bytes) == 1 &&
7870
		    btrfs_inc_nocow_writers(fs_info, block_start)) {
7871
			struct extent_map *em2;
7872

7873 7874 7875 7876
			em2 = btrfs_create_dio_extent(inode, start, len,
						      orig_start, block_start,
						      len, orig_block_len,
						      ram_bytes, type);
7877
			btrfs_dec_nocow_writers(fs_info, block_start);
7878 7879
			if (type == BTRFS_ORDERED_PREALLOC) {
				free_extent_map(em);
7880
				em = em2;
7881
			}
7882 7883
			if (em2 && IS_ERR(em2)) {
				ret = PTR_ERR(em2);
7884
				goto unlock_err;
7885
			}
7886 7887 7888 7889 7890 7891 7892
			/*
			 * For inode marked NODATACOW or extent marked PREALLOC,
			 * use the existing or preallocated extent, so does not
			 * need to adjust btrfs_space_info's bytes_may_use.
			 */
			btrfs_free_reserved_data_space_noquota(inode,
					start, len);
7893
			goto unlock;
7894 7895
		}
	}
7896

7897 7898 7899 7900 7901
	/*
	 * this will cow the extent, reset the len in case we changed
	 * it above
	 */
	len = bh_result->b_size;
7902 7903
	free_extent_map(em);
	em = btrfs_new_extent_direct(inode, start, len);
7904 7905 7906 7907
	if (IS_ERR(em)) {
		ret = PTR_ERR(em);
		goto unlock_err;
	}
7908 7909
	len = min(len, em->len - (start - em->start));
unlock:
7910 7911
	bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
		inode->i_blkbits;
7912
	bh_result->b_size = len;
7913 7914
	bh_result->b_bdev = em->bdev;
	set_buffer_mapped(bh_result);
7915 7916 7917 7918 7919 7920 7921 7922
	if (create) {
		if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
			set_buffer_new(bh_result);

		/*
		 * Need to update the i_size under the extent lock so buffered
		 * readers will get the updated i_size when we unlock.
		 */
7923
		if (!dio_data->overwrite && start + len > i_size_read(inode))
7924
			i_size_write(inode, start + len);
7925

7926 7927
		WARN_ON(dio_data->reserve < len);
		dio_data->reserve -= len;
7928
		dio_data->unsubmitted_oe_range_end = start + len;
7929
		current->journal_info = dio_data;
7930
	}
7931

7932 7933 7934 7935 7936
	/*
	 * In the case of write we need to clear and unlock the entire range,
	 * in the case of read we need to unlock only the end area that we
	 * aren't using if there is any left over space.
	 */
L
Liu Bo 已提交
7937
	if (lockstart < lockend) {
7938 7939
		clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
				 lockend, unlock_bits, 1, 0,
7940
				 &cached_state);
L
Liu Bo 已提交
7941
	} else {
7942
		free_extent_state(cached_state);
L
Liu Bo 已提交
7943
	}
7944

7945 7946 7947
	free_extent_map(em);

	return 0;
7948 7949 7950

unlock_err:
	clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7951
			 unlock_bits, 1, 0, &cached_state);
7952
err:
7953 7954
	if (dio_data)
		current->journal_info = dio_data;
7955
	return ret;
7956 7957
}

7958 7959 7960
static inline blk_status_t submit_dio_repair_bio(struct inode *inode,
						 struct bio *bio,
						 int mirror_num)
7961
{
7962
	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7963
	blk_status_t ret;
7964

M
Mike Christie 已提交
7965
	BUG_ON(bio_op(bio) == REQ_OP_WRITE);
7966

7967
	ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DIO_REPAIR);
7968
	if (ret)
7969
		return ret;
7970

7971
	ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
7972

7973 7974 7975 7976 7977 7978 7979 7980
	return ret;
}

static int btrfs_check_dio_repairable(struct inode *inode,
				      struct bio *failed_bio,
				      struct io_failure_record *failrec,
				      int failed_mirror)
{
7981
	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7982 7983
	int num_copies;

7984
	num_copies = btrfs_num_copies(fs_info, failrec->logical, failrec->len);
7985 7986 7987 7988 7989 7990
	if (num_copies == 1) {
		/*
		 * we only have a single copy of the data, so don't bother with
		 * all the retry and error correction code that follows. no
		 * matter what the error is, it is very likely to persist.
		 */
7991 7992 7993
		btrfs_debug(fs_info,
			"Check DIO Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d",
			num_copies, failrec->this_mirror, failed_mirror);
7994 7995 7996 7997 7998 7999 8000 8001 8002
		return 0;
	}

	failrec->failed_mirror = failed_mirror;
	failrec->this_mirror++;
	if (failrec->this_mirror == failed_mirror)
		failrec->this_mirror++;

	if (failrec->this_mirror > num_copies) {
8003 8004 8005
		btrfs_debug(fs_info,
			"Check DIO Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d",
			num_copies, failrec->this_mirror, failed_mirror);
8006 8007 8008 8009 8010 8011
		return 0;
	}

	return 1;
}

8012 8013 8014 8015
static blk_status_t dio_read_error(struct inode *inode, struct bio *failed_bio,
				   struct page *page, unsigned int pgoff,
				   u64 start, u64 end, int failed_mirror,
				   bio_end_io_t *repair_endio, void *repair_arg)
8016 8017
{
	struct io_failure_record *failrec;
8018 8019
	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
	struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
8020 8021
	struct bio *bio;
	int isector;
8022
	unsigned int read_mode = 0;
8023
	int segs;
8024
	int ret;
8025
	blk_status_t status;
8026
	struct bio_vec bvec;
8027

M
Mike Christie 已提交
8028
	BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
8029 8030 8031

	ret = btrfs_get_io_failure_record(inode, start, end, &failrec);
	if (ret)
8032
		return errno_to_blk_status(ret);
8033 8034 8035 8036

	ret = btrfs_check_dio_repairable(inode, failed_bio, failrec,
					 failed_mirror);
	if (!ret) {
8037
		free_io_failure(failure_tree, io_tree, failrec);
8038
		return BLK_STS_IOERR;
8039 8040
	}

8041
	segs = bio_segments(failed_bio);
8042
	bio_get_first_bvec(failed_bio, &bvec);
8043
	if (segs > 1 ||
8044
	    (bvec.bv_len > btrfs_inode_sectorsize(inode)))
8045
		read_mode |= REQ_FAILFAST_DEV;
8046 8047 8048 8049

	isector = start - btrfs_io_bio(failed_bio)->logical;
	isector >>= inode->i_sb->s_blocksize_bits;
	bio = btrfs_create_repair_bio(inode, failed_bio, failrec, page,
8050
				pgoff, isector, repair_endio, repair_arg);
M
Mike Christie 已提交
8051
	bio_set_op_attrs(bio, REQ_OP_READ, read_mode);
8052 8053

	btrfs_debug(BTRFS_I(inode)->root->fs_info,
8054
		    "repair DIO read error: submitting new dio read[%#x] to this_mirror=%d, in_validation=%d",
8055 8056
		    read_mode, failrec->this_mirror, failrec->in_validation);

8057 8058
	status = submit_dio_repair_bio(inode, bio, failrec->this_mirror);
	if (status) {
8059
		free_io_failure(failure_tree, io_tree, failrec);
8060 8061 8062
		bio_put(bio);
	}

8063
	return status;
8064 8065 8066 8067 8068 8069 8070 8071 8072
}

struct btrfs_retry_complete {
	struct completion done;
	struct inode *inode;
	u64 start;
	int uptodate;
};

8073
static void btrfs_retry_endio_nocsum(struct bio *bio)
8074 8075
{
	struct btrfs_retry_complete *done = bio->bi_private;
8076
	struct inode *inode = done->inode;
8077
	struct bio_vec *bvec;
8078
	struct extent_io_tree *io_tree, *failure_tree;
8079 8080
	int i;

8081
	if (bio->bi_status)
8082 8083
		goto end;

8084
	ASSERT(bio->bi_vcnt == 1);
8085 8086
	io_tree = &BTRFS_I(inode)->io_tree;
	failure_tree = &BTRFS_I(inode)->io_failure_tree;
8087
	ASSERT(bio_first_bvec_all(bio)->bv_len == btrfs_inode_sectorsize(inode));
8088

8089
	done->uptodate = 1;
8090
	ASSERT(!bio_flagged(bio, BIO_CLONED));
8091
	bio_for_each_segment_all(bvec, bio, i)
8092 8093 8094
		clean_io_failure(BTRFS_I(inode)->root->fs_info, failure_tree,
				 io_tree, done->start, bvec->bv_page,
				 btrfs_ino(BTRFS_I(inode)), 0);
8095 8096 8097 8098 8099
end:
	complete(&done->done);
	bio_put(bio);
}

8100 8101
static blk_status_t __btrfs_correct_data_nocsum(struct inode *inode,
						struct btrfs_io_bio *io_bio)
8102
{
8103
	struct btrfs_fs_info *fs_info;
8104 8105
	struct bio_vec bvec;
	struct bvec_iter iter;
8106
	struct btrfs_retry_complete done;
8107
	u64 start;
8108 8109 8110
	unsigned int pgoff;
	u32 sectorsize;
	int nr_sectors;
8111 8112
	blk_status_t ret;
	blk_status_t err = BLK_STS_OK;
8113

8114
	fs_info = BTRFS_I(inode)->root->fs_info;
8115
	sectorsize = fs_info->sectorsize;
8116

8117 8118
	start = io_bio->logical;
	done.inode = inode;
8119
	io_bio->bio.bi_iter = io_bio->iter;
8120

8121 8122 8123
	bio_for_each_segment(bvec, &io_bio->bio, iter) {
		nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
		pgoff = bvec.bv_offset;
8124 8125

next_block_or_try_again:
8126 8127 8128 8129
		done.uptodate = 0;
		done.start = start;
		init_completion(&done.done);

8130
		ret = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
8131 8132 8133
				pgoff, start, start + sectorsize - 1,
				io_bio->mirror_num,
				btrfs_retry_endio_nocsum, &done);
8134 8135 8136 8137
		if (ret) {
			err = ret;
			goto next;
		}
8138

8139
		wait_for_completion_io(&done.done);
8140 8141 8142

		if (!done.uptodate) {
			/* We might have another mirror, so try again */
8143
			goto next_block_or_try_again;
8144 8145
		}

8146
next:
8147 8148
		start += sectorsize;

8149 8150
		nr_sectors--;
		if (nr_sectors) {
8151
			pgoff += sectorsize;
8152
			ASSERT(pgoff < PAGE_SIZE);
8153 8154
			goto next_block_or_try_again;
		}
8155 8156
	}

8157
	return err;
8158 8159
}

8160
static void btrfs_retry_endio(struct bio *bio)
8161 8162 8163
{
	struct btrfs_retry_complete *done = bio->bi_private;
	struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8164 8165
	struct extent_io_tree *io_tree, *failure_tree;
	struct inode *inode = done->inode;
8166 8167 8168 8169 8170
	struct bio_vec *bvec;
	int uptodate;
	int ret;
	int i;

8171
	if (bio->bi_status)
8172 8173 8174
		goto end;

	uptodate = 1;
8175 8176

	ASSERT(bio->bi_vcnt == 1);
8177
	ASSERT(bio_first_bvec_all(bio)->bv_len == btrfs_inode_sectorsize(done->inode));
8178

8179 8180 8181
	io_tree = &BTRFS_I(inode)->io_tree;
	failure_tree = &BTRFS_I(inode)->io_failure_tree;

8182
	ASSERT(!bio_flagged(bio, BIO_CLONED));
8183
	bio_for_each_segment_all(bvec, bio, i) {
8184 8185 8186
		ret = __readpage_endio_check(inode, io_bio, i, bvec->bv_page,
					     bvec->bv_offset, done->start,
					     bvec->bv_len);
8187
		if (!ret)
8188 8189 8190 8191 8192
			clean_io_failure(BTRFS_I(inode)->root->fs_info,
					 failure_tree, io_tree, done->start,
					 bvec->bv_page,
					 btrfs_ino(BTRFS_I(inode)),
					 bvec->bv_offset);
8193 8194 8195 8196 8197 8198 8199 8200 8201 8202
		else
			uptodate = 0;
	}

	done->uptodate = uptodate;
end:
	complete(&done->done);
	bio_put(bio);
}

8203 8204
static blk_status_t __btrfs_subio_endio_read(struct inode *inode,
		struct btrfs_io_bio *io_bio, blk_status_t err)
8205
{
8206
	struct btrfs_fs_info *fs_info;
8207 8208
	struct bio_vec bvec;
	struct bvec_iter iter;
8209 8210 8211
	struct btrfs_retry_complete done;
	u64 start;
	u64 offset = 0;
8212 8213 8214 8215
	u32 sectorsize;
	int nr_sectors;
	unsigned int pgoff;
	int csum_pos;
8216
	bool uptodate = (err == 0);
8217
	int ret;
8218
	blk_status_t status;
8219

8220
	fs_info = BTRFS_I(inode)->root->fs_info;
8221
	sectorsize = fs_info->sectorsize;
8222

8223
	err = BLK_STS_OK;
8224
	start = io_bio->logical;
8225
	done.inode = inode;
8226
	io_bio->bio.bi_iter = io_bio->iter;
8227

8228 8229
	bio_for_each_segment(bvec, &io_bio->bio, iter) {
		nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
8230

8231
		pgoff = bvec.bv_offset;
8232
next_block:
8233 8234 8235 8236 8237 8238 8239
		if (uptodate) {
			csum_pos = BTRFS_BYTES_TO_BLKS(fs_info, offset);
			ret = __readpage_endio_check(inode, io_bio, csum_pos,
					bvec.bv_page, pgoff, start, sectorsize);
			if (likely(!ret))
				goto next;
		}
8240 8241 8242 8243 8244
try_again:
		done.uptodate = 0;
		done.start = start;
		init_completion(&done.done);

8245 8246 8247 8248 8249 8250
		status = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
					pgoff, start, start + sectorsize - 1,
					io_bio->mirror_num, btrfs_retry_endio,
					&done);
		if (status) {
			err = status;
8251 8252 8253
			goto next;
		}

8254
		wait_for_completion_io(&done.done);
8255 8256 8257 8258 8259 8260

		if (!done.uptodate) {
			/* We might have another mirror, so try again */
			goto try_again;
		}
next:
8261 8262 8263 8264 8265
		offset += sectorsize;
		start += sectorsize;

		ASSERT(nr_sectors);

8266 8267
		nr_sectors--;
		if (nr_sectors) {
8268
			pgoff += sectorsize;
8269
			ASSERT(pgoff < PAGE_SIZE);
8270 8271
			goto next_block;
		}
8272
	}
8273 8274 8275 8276

	return err;
}

8277 8278
static blk_status_t btrfs_subio_endio_read(struct inode *inode,
		struct btrfs_io_bio *io_bio, blk_status_t err)
8279 8280 8281 8282 8283 8284 8285
{
	bool skip_csum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;

	if (skip_csum) {
		if (unlikely(err))
			return __btrfs_correct_data_nocsum(inode, io_bio);
		else
8286
			return BLK_STS_OK;
8287 8288 8289 8290 8291
	} else {
		return __btrfs_subio_endio_read(inode, io_bio, err);
	}
}

8292
static void btrfs_endio_direct_read(struct bio *bio)
8293 8294 8295 8296 8297
{
	struct btrfs_dio_private *dip = bio->bi_private;
	struct inode *inode = dip->inode;
	struct bio *dio_bio;
	struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8298
	blk_status_t err = bio->bi_status;
8299

8300
	if (dip->flags & BTRFS_DIO_ORIG_BIO_SUBMITTED)
8301
		err = btrfs_subio_endio_read(inode, io_bio, err);
8302

8303
	unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
8304
		      dip->logical_offset + dip->bytes - 1);
8305
	dio_bio = dip->dio_bio;
8306 8307

	kfree(dip);
8308

8309
	dio_bio->bi_status = err;
8310
	dio_end_io(dio_bio);
8311 8312

	if (io_bio->end_io)
8313
		io_bio->end_io(io_bio, blk_status_to_errno(err));
8314
	bio_put(bio);
8315 8316
}

8317 8318 8319
static void __endio_write_update_ordered(struct inode *inode,
					 const u64 offset, const u64 bytes,
					 const bool uptodate)
8320
{
8321
	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8322
	struct btrfs_ordered_extent *ordered = NULL;
8323 8324
	struct btrfs_workqueue *wq;
	btrfs_work_func_t func;
8325 8326
	u64 ordered_offset = offset;
	u64 ordered_bytes = bytes;
8327
	u64 last_offset;
8328

8329 8330 8331 8332 8333 8334 8335 8336
	if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
		wq = fs_info->endio_freespace_worker;
		func = btrfs_freespace_write_helper;
	} else {
		wq = fs_info->endio_write_workers;
		func = btrfs_endio_write_helper;
	}

8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361
	while (ordered_offset < offset + bytes) {
		last_offset = ordered_offset;
		if (btrfs_dec_test_first_ordered_pending(inode, &ordered,
							   &ordered_offset,
							   ordered_bytes,
							   uptodate)) {
			btrfs_init_work(&ordered->work, func,
					finish_ordered_fn,
					NULL, NULL);
			btrfs_queue_work(wq, &ordered->work);
		}
		/*
		 * If btrfs_dec_test_ordered_pending does not find any ordered
		 * extent in the range, we can exit.
		 */
		if (ordered_offset == last_offset)
			return;
		/*
		 * Our bio might span multiple ordered extents. In this case
		 * we keep goin until we have accounted the whole dio.
		 */
		if (ordered_offset < offset + bytes) {
			ordered_bytes = offset + bytes - ordered_offset;
			ordered = NULL;
		}
8362
	}
8363 8364 8365 8366 8367 8368 8369
}

static void btrfs_endio_direct_write(struct bio *bio)
{
	struct btrfs_dio_private *dip = bio->bi_private;
	struct bio *dio_bio = dip->dio_bio;

8370
	__endio_write_update_ordered(dip->inode, dip->logical_offset,
8371
				     dip->bytes, !bio->bi_status);
8372 8373

	kfree(dip);
8374

8375
	dio_bio->bi_status = bio->bi_status;
8376
	dio_end_io(dio_bio);
8377
	bio_put(bio);
8378 8379
}

8380
static blk_status_t btrfs_submit_bio_start_direct_io(void *private_data,
8381
				    struct bio *bio, u64 offset)
8382
{
8383
	struct inode *inode = private_data;
8384
	blk_status_t ret;
8385
	ret = btrfs_csum_one_bio(inode, bio, offset, 1);
8386
	BUG_ON(ret); /* -ENOMEM */
8387 8388 8389
	return 0;
}

8390
static void btrfs_end_dio_bio(struct bio *bio)
M
Miao Xie 已提交
8391 8392
{
	struct btrfs_dio_private *dip = bio->bi_private;
8393
	blk_status_t err = bio->bi_status;
M
Miao Xie 已提交
8394

8395 8396
	if (err)
		btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
8397
			   "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
8398 8399
			   btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
			   bio->bi_opf,
8400 8401 8402 8403 8404
			   (unsigned long long)bio->bi_iter.bi_sector,
			   bio->bi_iter.bi_size, err);

	if (dip->subio_endio)
		err = dip->subio_endio(dip->inode, btrfs_io_bio(bio), err);
8405 8406

	if (err) {
M
Miao Xie 已提交
8407
		/*
8408 8409 8410 8411
		 * We want to perceive the errors flag being set before
		 * decrementing the reference count. We don't need a barrier
		 * since atomic operations with a return value are fully
		 * ordered as per atomic_t.txt
M
Miao Xie 已提交
8412
		 */
8413
		dip->errors = 1;
M
Miao Xie 已提交
8414 8415 8416 8417 8418 8419
	}

	/* if there are more bios still pending for this dio, just exit */
	if (!atomic_dec_and_test(&dip->pending_bios))
		goto out;

8420
	if (dip->errors) {
M
Miao Xie 已提交
8421
		bio_io_error(dip->orig_bio);
8422
	} else {
8423
		dip->dio_bio->bi_status = BLK_STS_OK;
8424
		bio_endio(dip->orig_bio);
M
Miao Xie 已提交
8425 8426 8427 8428 8429
	}
out:
	bio_put(bio);
}

8430
static inline blk_status_t btrfs_lookup_and_bind_dio_csum(struct inode *inode,
8431 8432 8433 8434 8435 8436
						 struct btrfs_dio_private *dip,
						 struct bio *bio,
						 u64 file_offset)
{
	struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
	struct btrfs_io_bio *orig_io_bio = btrfs_io_bio(dip->orig_bio);
8437
	blk_status_t ret;
8438 8439 8440 8441 8442 8443 8444

	/*
	 * We load all the csum data we need when we submit
	 * the first bio to reduce the csum tree search and
	 * contention.
	 */
	if (dip->logical_offset == file_offset) {
8445
		ret = btrfs_lookup_bio_sums_dio(inode, dip->orig_bio,
8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460
						file_offset);
		if (ret)
			return ret;
	}

	if (bio == dip->orig_bio)
		return 0;

	file_offset -= dip->logical_offset;
	file_offset >>= inode->i_sb->s_blocksize_bits;
	io_bio->csum = (u8 *)(((u32 *)orig_io_bio->csum) + file_offset);

	return 0;
}

8461 8462
static inline blk_status_t btrfs_submit_dio_bio(struct bio *bio,
		struct inode *inode, u64 file_offset, int async_submit)
M
Miao Xie 已提交
8463
{
8464
	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8465
	struct btrfs_dio_private *dip = bio->bi_private;
M
Mike Christie 已提交
8466
	bool write = bio_op(bio) == REQ_OP_WRITE;
8467
	blk_status_t ret;
M
Miao Xie 已提交
8468

8469
	/* Check btrfs_submit_bio_hook() for rules about async submit. */
8470 8471 8472
	if (async_submit)
		async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);

8473
	if (!write) {
8474
		ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
8475 8476 8477
		if (ret)
			goto err;
	}
M
Miao Xie 已提交
8478

8479
	if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
8480 8481 8482
		goto map;

	if (write && async_submit) {
8483 8484
		ret = btrfs_wq_submit_bio(fs_info, bio, 0, 0,
					  file_offset, inode,
8485 8486
					  btrfs_submit_bio_start_direct_io,
					  btrfs_submit_bio_done);
M
Miao Xie 已提交
8487
		goto err;
8488 8489 8490 8491 8492
	} else if (write) {
		/*
		 * If we aren't doing async submit, calculate the csum of the
		 * bio now.
		 */
8493
		ret = btrfs_csum_one_bio(inode, bio, file_offset, 1);
8494 8495
		if (ret)
			goto err;
8496
	} else {
8497
		ret = btrfs_lookup_and_bind_dio_csum(inode, dip, bio,
8498
						     file_offset);
8499 8500 8501
		if (ret)
			goto err;
	}
8502
map:
8503
	ret = btrfs_map_bio(fs_info, bio, 0, 0);
M
Miao Xie 已提交
8504 8505 8506 8507
err:
	return ret;
}

8508
static int btrfs_submit_direct_hook(struct btrfs_dio_private *dip)
M
Miao Xie 已提交
8509 8510
{
	struct inode *inode = dip->inode;
8511
	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
M
Miao Xie 已提交
8512 8513
	struct bio *bio;
	struct bio *orig_bio = dip->orig_bio;
8514
	u64 start_sector = orig_bio->bi_iter.bi_sector;
M
Miao Xie 已提交
8515 8516
	u64 file_offset = dip->logical_offset;
	u64 map_length;
8517
	int async_submit = 0;
8518 8519 8520
	u64 submit_len;
	int clone_offset = 0;
	int clone_len;
8521
	int ret;
8522
	blk_status_t status;
M
Miao Xie 已提交
8523

8524
	map_length = orig_bio->bi_iter.bi_size;
8525
	submit_len = map_length;
8526 8527
	ret = btrfs_map_block(fs_info, btrfs_op(orig_bio), start_sector << 9,
			      &map_length, NULL, 0);
8528
	if (ret)
M
Miao Xie 已提交
8529
		return -EIO;
8530

8531
	if (map_length >= submit_len) {
8532
		bio = orig_bio;
8533
		dip->flags |= BTRFS_DIO_ORIG_BIO_SUBMITTED;
8534 8535 8536
		goto submit;
	}

D
David Woodhouse 已提交
8537
	/* async crcs make it difficult to collect full stripe writes. */
8538
	if (btrfs_data_alloc_profile(fs_info) & BTRFS_BLOCK_GROUP_RAID56_MASK)
D
David Woodhouse 已提交
8539 8540 8541 8542
		async_submit = 0;
	else
		async_submit = 1;

8543 8544
	/* bio split */
	ASSERT(map_length <= INT_MAX);
8545
	atomic_inc(&dip->pending_bios);
8546
	do {
8547
		clone_len = min_t(int, submit_len, map_length);
8548

8549 8550 8551 8552
		/*
		 * This will never fail as it's passing GPF_NOFS and
		 * the allocation is backed by btrfs_bioset.
		 */
8553
		bio = btrfs_bio_clone_partial(orig_bio, clone_offset,
8554 8555 8556 8557 8558 8559 8560 8561 8562
					      clone_len);
		bio->bi_private = dip;
		bio->bi_end_io = btrfs_end_dio_bio;
		btrfs_io_bio(bio)->logical = file_offset;

		ASSERT(submit_len >= clone_len);
		submit_len -= clone_len;
		if (submit_len == 0)
			break;
M
Miao Xie 已提交
8563

8564 8565 8566 8567 8568 8569 8570
		/*
		 * Increase the count before we submit the bio so we know
		 * the end IO handler won't happen before we increase the
		 * count. Otherwise, the dip might get freed before we're
		 * done setting it up.
		 */
		atomic_inc(&dip->pending_bios);
M
Miao Xie 已提交
8571

8572
		status = btrfs_submit_dio_bio(bio, inode, file_offset,
8573 8574
						async_submit);
		if (status) {
8575 8576 8577 8578
			bio_put(bio);
			atomic_dec(&dip->pending_bios);
			goto out_err;
		}
M
Miao Xie 已提交
8579

8580 8581 8582
		clone_offset += clone_len;
		start_sector += clone_len >> 9;
		file_offset += clone_len;
8583

8584 8585 8586 8587 8588
		map_length = submit_len;
		ret = btrfs_map_block(fs_info, btrfs_op(orig_bio),
				      start_sector << 9, &map_length, NULL, 0);
		if (ret)
			goto out_err;
8589
	} while (submit_len > 0);
M
Miao Xie 已提交
8590

8591
submit:
8592
	status = btrfs_submit_dio_bio(bio, inode, file_offset, async_submit);
8593
	if (!status)
M
Miao Xie 已提交
8594 8595 8596 8597 8598 8599
		return 0;

	bio_put(bio);
out_err:
	dip->errors = 1;
	/*
8600 8601 8602 8603
	 * Before atomic variable goto zero, we must  make sure dip->errors is
	 * perceived to be set. This ordering is ensured by the fact that an
	 * atomic operations with a return value are fully ordered as per
	 * atomic_t.txt
M
Miao Xie 已提交
8604 8605 8606 8607 8608 8609 8610 8611
	 */
	if (atomic_dec_and_test(&dip->pending_bios))
		bio_io_error(dip->orig_bio);

	/* bio_end_io() will handle error, so we needn't return it */
	return 0;
}

8612 8613
static void btrfs_submit_direct(struct bio *dio_bio, struct inode *inode,
				loff_t file_offset)
8614
{
8615
	struct btrfs_dio_private *dip = NULL;
L
Liu Bo 已提交
8616 8617
	struct bio *bio = NULL;
	struct btrfs_io_bio *io_bio;
8618
	bool write = (bio_op(dio_bio) == REQ_OP_WRITE);
8619 8620
	int ret = 0;

8621
	bio = btrfs_bio_clone(dio_bio);
8622

8623
	dip = kzalloc(sizeof(*dip), GFP_NOFS);
8624 8625
	if (!dip) {
		ret = -ENOMEM;
8626
		goto free_ordered;
8627 8628
	}

8629
	dip->private = dio_bio->bi_private;
8630 8631
	dip->inode = inode;
	dip->logical_offset = file_offset;
8632 8633
	dip->bytes = dio_bio->bi_iter.bi_size;
	dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
L
Liu Bo 已提交
8634 8635
	bio->bi_private = dip;
	dip->orig_bio = bio;
8636
	dip->dio_bio = dio_bio;
M
Miao Xie 已提交
8637
	atomic_set(&dip->pending_bios, 0);
L
Liu Bo 已提交
8638 8639
	io_bio = btrfs_io_bio(bio);
	io_bio->logical = file_offset;
8640

8641
	if (write) {
L
Liu Bo 已提交
8642
		bio->bi_end_io = btrfs_endio_direct_write;
8643
	} else {
L
Liu Bo 已提交
8644
		bio->bi_end_io = btrfs_endio_direct_read;
8645 8646
		dip->subio_endio = btrfs_subio_endio_read;
	}
8647

8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662
	/*
	 * Reset the range for unsubmitted ordered extents (to a 0 length range)
	 * even if we fail to submit a bio, because in such case we do the
	 * corresponding error handling below and it must not be done a second
	 * time by btrfs_direct_IO().
	 */
	if (write) {
		struct btrfs_dio_data *dio_data = current->journal_info;

		dio_data->unsubmitted_oe_range_end = dip->logical_offset +
			dip->bytes;
		dio_data->unsubmitted_oe_range_start =
			dio_data->unsubmitted_oe_range_end;
	}

8663
	ret = btrfs_submit_direct_hook(dip);
M
Miao Xie 已提交
8664
	if (!ret)
8665
		return;
8666

L
Liu Bo 已提交
8667 8668
	if (io_bio->end_io)
		io_bio->end_io(io_bio, ret);
8669

8670 8671
free_ordered:
	/*
8672 8673 8674 8675 8676 8677 8678
	 * If we arrived here it means either we failed to submit the dip
	 * or we either failed to clone the dio_bio or failed to allocate the
	 * dip. If we cloned the dio_bio and allocated the dip, we can just
	 * call bio_endio against our io_bio so that we get proper resource
	 * cleanup if we fail to submit the dip, otherwise, we must do the
	 * same as btrfs_endio_direct_[write|read] because we can't call these
	 * callbacks - they require an allocated dip and a clone of dio_bio.
8679
	 */
L
Liu Bo 已提交
8680
	if (bio && dip) {
8681
		bio_io_error(bio);
8682
		/*
L
Liu Bo 已提交
8683
		 * The end io callbacks free our dip, do the final put on bio
8684 8685 8686 8687
		 * and all the cleanup and final put for dio_bio (through
		 * dio_end_io()).
		 */
		dip = NULL;
L
Liu Bo 已提交
8688
		bio = NULL;
8689
	} else {
8690
		if (write)
8691
			__endio_write_update_ordered(inode,
8692 8693
						file_offset,
						dio_bio->bi_iter.bi_size,
8694
						false);
8695
		else
8696 8697
			unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
			      file_offset + dio_bio->bi_iter.bi_size - 1);
8698

8699
		dio_bio->bi_status = BLK_STS_IOERR;
8700 8701 8702 8703
		/*
		 * Releases and cleans up our dio_bio, no need to bio_put()
		 * nor bio_endio()/bio_io_error() against dio_bio.
		 */
8704
		dio_end_io(dio_bio);
8705
	}
L
Liu Bo 已提交
8706 8707
	if (bio)
		bio_put(bio);
8708
	kfree(dip);
8709 8710
}

8711 8712
static ssize_t check_direct_IO(struct btrfs_fs_info *fs_info,
			       const struct iov_iter *iter, loff_t offset)
C
Chris Mason 已提交
8713 8714
{
	int seg;
8715
	int i;
8716
	unsigned int blocksize_mask = fs_info->sectorsize - 1;
C
Chris Mason 已提交
8717 8718 8719 8720 8721
	ssize_t retval = -EINVAL;

	if (offset & blocksize_mask)
		goto out;

8722 8723
	if (iov_iter_alignment(iter) & blocksize_mask)
		goto out;
8724

8725
	/* If this is a write we don't need to check anymore */
8726
	if (iov_iter_rw(iter) != READ || !iter_is_iovec(iter))
8727 8728 8729 8730 8731 8732 8733 8734 8735
		return 0;
	/*
	 * Check to make sure we don't have duplicate iov_base's in this
	 * iovec, if so return EINVAL, otherwise we'll get csum errors
	 * when reading back.
	 */
	for (seg = 0; seg < iter->nr_segs; seg++) {
		for (i = seg + 1; i < iter->nr_segs; i++) {
			if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
8736 8737
				goto out;
		}
C
Chris Mason 已提交
8738 8739 8740 8741 8742
	}
	retval = 0;
out:
	return retval;
}
8743

8744
static ssize_t btrfs_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
8745
{
8746 8747
	struct file *file = iocb->ki_filp;
	struct inode *inode = file->f_mapping->host;
8748
	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8749
	struct btrfs_dio_data dio_data = { 0 };
8750
	struct extent_changeset *data_reserved = NULL;
8751
	loff_t offset = iocb->ki_pos;
8752
	size_t count = 0;
8753
	int flags = 0;
M
Miao Xie 已提交
8754 8755
	bool wakeup = true;
	bool relock = false;
8756
	ssize_t ret;
8757

8758
	if (check_direct_IO(fs_info, iter, offset))
C
Chris Mason 已提交
8759
		return 0;
8760

8761
	inode_dio_begin(inode);
M
Miao Xie 已提交
8762

8763
	/*
8764 8765 8766 8767
	 * The generic stuff only does filemap_write_and_wait_range, which
	 * isn't enough if we've written compressed pages to this area, so
	 * we need to flush the dirty pages again to make absolutely sure
	 * that any outstanding dirty pages are on disk.
8768
	 */
8769
	count = iov_iter_count(iter);
8770 8771
	if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
		     &BTRFS_I(inode)->runtime_flags))
8772 8773
		filemap_fdatawrite_range(inode->i_mapping, offset,
					 offset + count - 1);
8774

8775
	if (iov_iter_rw(iter) == WRITE) {
M
Miao Xie 已提交
8776 8777 8778 8779 8780 8781
		/*
		 * If the write DIO is beyond the EOF, we need update
		 * the isize, but it is protected by i_mutex. So we can
		 * not unlock the i_mutex at this case.
		 */
		if (offset + count <= inode->i_size) {
8782
			dio_data.overwrite = 1;
A
Al Viro 已提交
8783
			inode_unlock(inode);
M
Miao Xie 已提交
8784
			relock = true;
G
Goldwyn Rodrigues 已提交
8785 8786 8787
		} else if (iocb->ki_flags & IOCB_NOWAIT) {
			ret = -EAGAIN;
			goto out;
M
Miao Xie 已提交
8788
		}
8789 8790
		ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
						   offset, count);
8791
		if (ret)
M
Miao Xie 已提交
8792
			goto out;
8793 8794 8795 8796 8797 8798

		/*
		 * We need to know how many extents we reserved so that we can
		 * do the accounting properly if we go over the number we
		 * originally calculated.  Abuse current->journal_info for this.
		 */
8799
		dio_data.reserve = round_up(count,
8800
					    fs_info->sectorsize);
8801 8802
		dio_data.unsubmitted_oe_range_start = (u64)offset;
		dio_data.unsubmitted_oe_range_end = (u64)offset;
8803
		current->journal_info = &dio_data;
8804
		down_read(&BTRFS_I(inode)->dio_sem);
8805 8806
	} else if (test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
				     &BTRFS_I(inode)->runtime_flags)) {
8807
		inode_dio_end(inode);
M
Miao Xie 已提交
8808 8809
		flags = DIO_LOCKING | DIO_SKIP_HOLES;
		wakeup = false;
8810 8811
	}

8812
	ret = __blockdev_direct_IO(iocb, inode,
8813
				   fs_info->fs_devices->latest_bdev,
8814
				   iter, btrfs_get_blocks_direct, NULL,
8815
				   btrfs_submit_direct, flags);
8816
	if (iov_iter_rw(iter) == WRITE) {
8817
		up_read(&BTRFS_I(inode)->dio_sem);
8818
		current->journal_info = NULL;
L
Liu Bo 已提交
8819
		if (ret < 0 && ret != -EIOCBQUEUED) {
8820
			if (dio_data.reserve)
8821
				btrfs_delalloc_release_space(inode, data_reserved,
8822
					offset, dio_data.reserve, true);
8823 8824 8825 8826 8827 8828 8829 8830
			/*
			 * On error we might have left some ordered extents
			 * without submitting corresponding bios for them, so
			 * cleanup them up to avoid other tasks getting them
			 * and waiting for them to complete forever.
			 */
			if (dio_data.unsubmitted_oe_range_start <
			    dio_data.unsubmitted_oe_range_end)
8831
				__endio_write_update_ordered(inode,
8832 8833 8834
					dio_data.unsubmitted_oe_range_start,
					dio_data.unsubmitted_oe_range_end -
					dio_data.unsubmitted_oe_range_start,
8835
					false);
L
Liu Bo 已提交
8836
		} else if (ret >= 0 && (size_t)ret < count)
8837
			btrfs_delalloc_release_space(inode, data_reserved,
8838 8839
					offset, count - (size_t)ret, true);
		btrfs_delalloc_release_extents(BTRFS_I(inode), count, false);
8840
	}
M
Miao Xie 已提交
8841
out:
8842
	if (wakeup)
8843
		inode_dio_end(inode);
M
Miao Xie 已提交
8844
	if (relock)
A
Al Viro 已提交
8845
		inode_lock(inode);
8846

8847
	extent_changeset_free(data_reserved);
8848
	return ret;
8849 8850
}

T
Tsutomu Itoh 已提交
8851 8852
#define BTRFS_FIEMAP_FLAGS	(FIEMAP_FLAG_SYNC)

Y
Yehuda Sadeh 已提交
8853 8854 8855
static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
		__u64 start, __u64 len)
{
T
Tsutomu Itoh 已提交
8856 8857 8858 8859 8860 8861
	int	ret;

	ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
	if (ret)
		return ret;

8862
	return extent_fiemap(inode, fieinfo, start, len);
Y
Yehuda Sadeh 已提交
8863 8864
}

8865
int btrfs_readpage(struct file *file, struct page *page)
C
Chris Mason 已提交
8866
{
8867 8868
	struct extent_io_tree *tree;
	tree = &BTRFS_I(page->mapping->host)->io_tree;
8869
	return extent_read_full_page(tree, page, btrfs_get_extent, 0);
C
Chris Mason 已提交
8870
}
8871

8872
static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
C
Chris Mason 已提交
8873
{
J
Josef Bacik 已提交
8874 8875
	struct inode *inode = page->mapping->host;
	int ret;
8876 8877 8878 8879 8880 8881

	if (current->flags & PF_MEMALLOC) {
		redirty_page_for_writepage(wbc, page);
		unlock_page(page);
		return 0;
	}
J
Josef Bacik 已提交
8882 8883 8884 8885 8886 8887 8888 8889 8890 8891

	/*
	 * If we are under memory pressure we will call this directly from the
	 * VM, we need to make sure we have the inode referenced for the ordered
	 * extent.  If not just return like we didn't do anything.
	 */
	if (!igrab(inode)) {
		redirty_page_for_writepage(wbc, page);
		return AOP_WRITEPAGE_ACTIVATE;
	}
8892
	ret = extent_write_full_page(page, wbc);
J
Josef Bacik 已提交
8893 8894
	btrfs_add_delayed_iput(inode);
	return ret;
C
Chris Mason 已提交
8895 8896
}

8897 8898
static int btrfs_writepages(struct address_space *mapping,
			    struct writeback_control *wbc)
C
Chris Mason 已提交
8899
{
8900
	struct extent_io_tree *tree;
8901

8902
	tree = &BTRFS_I(mapping->host)->io_tree;
8903
	return extent_writepages(tree, mapping, wbc);
C
Chris Mason 已提交
8904 8905
}

C
Chris Mason 已提交
8906 8907 8908 8909
static int
btrfs_readpages(struct file *file, struct address_space *mapping,
		struct list_head *pages, unsigned nr_pages)
{
8910 8911
	struct extent_io_tree *tree;
	tree = &BTRFS_I(mapping->host)->io_tree;
8912
	return extent_readpages(tree, mapping, pages, nr_pages);
C
Chris Mason 已提交
8913
}
8914
static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
C
Chris Mason 已提交
8915
{
8916 8917
	struct extent_io_tree *tree;
	struct extent_map_tree *map;
8918
	int ret;
8919

8920 8921
	tree = &BTRFS_I(page->mapping->host)->io_tree;
	map = &BTRFS_I(page->mapping->host)->extent_tree;
8922
	ret = try_release_extent_mapping(map, tree, page, gfp_flags);
8923 8924 8925
	if (ret == 1) {
		ClearPagePrivate(page);
		set_page_private(page, 0);
8926
		put_page(page);
C
Chris Mason 已提交
8927
	}
8928
	return ret;
C
Chris Mason 已提交
8929 8930
}

8931 8932
static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
{
8933 8934
	if (PageWriteback(page) || PageDirty(page))
		return 0;
8935
	return __btrfs_releasepage(page, gfp_flags);
8936 8937
}

8938 8939
static void btrfs_invalidatepage(struct page *page, unsigned int offset,
				 unsigned int length)
C
Chris Mason 已提交
8940
{
8941
	struct inode *inode = page->mapping->host;
8942
	struct extent_io_tree *tree;
8943
	struct btrfs_ordered_extent *ordered;
8944
	struct extent_state *cached_state = NULL;
8945
	u64 page_start = page_offset(page);
8946
	u64 page_end = page_start + PAGE_SIZE - 1;
8947 8948
	u64 start;
	u64 end;
8949
	int inode_evicting = inode->i_state & I_FREEING;
C
Chris Mason 已提交
8950

8951 8952 8953 8954 8955 8956 8957
	/*
	 * we have the page locked, so new writeback can't start,
	 * and the dirty bit won't be cleared while we are here.
	 *
	 * Wait for IO on this page so that we can safely clear
	 * the PagePrivate2 bit and do ordered accounting
	 */
8958
	wait_on_page_writeback(page);
8959

8960
	tree = &BTRFS_I(inode)->io_tree;
8961 8962 8963 8964
	if (offset) {
		btrfs_releasepage(page, GFP_NOFS);
		return;
	}
8965 8966

	if (!inode_evicting)
8967
		lock_extent_bits(tree, page_start, page_end, &cached_state);
8968 8969
again:
	start = page_start;
8970
	ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), start,
8971
					page_end - start + 1);
8972
	if (ordered) {
8973
		end = min(page_end, ordered->file_offset + ordered->len - 1);
8974 8975 8976 8977
		/*
		 * IO on this page will never be started, so we need
		 * to account for any ordered extents now
		 */
8978
		if (!inode_evicting)
8979
			clear_extent_bit(tree, start, end,
8980
					 EXTENT_DIRTY | EXTENT_DELALLOC |
8981
					 EXTENT_DELALLOC_NEW |
8982
					 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8983
					 EXTENT_DEFRAG, 1, 0, &cached_state);
8984 8985 8986 8987
		/*
		 * whoever cleared the private bit is responsible
		 * for the finish_ordered_io
		 */
8988 8989 8990 8991 8992 8993 8994 8995
		if (TestClearPagePrivate2(page)) {
			struct btrfs_ordered_inode_tree *tree;
			u64 new_len;

			tree = &BTRFS_I(inode)->ordered_tree;

			spin_lock_irq(&tree->lock);
			set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8996
			new_len = start - ordered->file_offset;
8997 8998 8999 9000 9001
			if (new_len < ordered->truncated_len)
				ordered->truncated_len = new_len;
			spin_unlock_irq(&tree->lock);

			if (btrfs_dec_test_ordered_pending(inode, &ordered,
9002 9003
							   start,
							   end - start + 1, 1))
9004
				btrfs_finish_ordered_io(ordered);
9005
		}
9006
		btrfs_put_ordered_extent(ordered);
9007 9008
		if (!inode_evicting) {
			cached_state = NULL;
9009
			lock_extent_bits(tree, start, end,
9010 9011
					 &cached_state);
		}
9012 9013 9014 9015

		start = end + 1;
		if (start < page_end)
			goto again;
9016 9017
	}

Q
Qu Wenruo 已提交
9018 9019 9020 9021 9022 9023 9024 9025 9026
	/*
	 * Qgroup reserved space handler
	 * Page here will be either
	 * 1) Already written to disk
	 *    In this case, its reserved space is released from data rsv map
	 *    and will be freed by delayed_ref handler finally.
	 *    So even we call qgroup_free_data(), it won't decrease reserved
	 *    space.
	 * 2) Not written to disk
9027 9028 9029 9030 9031
	 *    This means the reserved space should be freed here. However,
	 *    if a truncate invalidates the page (by clearing PageDirty)
	 *    and the page is accounted for while allocating extent
	 *    in btrfs_check_data_free_space() we let delayed_ref to
	 *    free the entire extent.
Q
Qu Wenruo 已提交
9032
	 */
9033
	if (PageDirty(page))
9034
		btrfs_qgroup_free_data(inode, NULL, page_start, PAGE_SIZE);
9035 9036 9037
	if (!inode_evicting) {
		clear_extent_bit(tree, page_start, page_end,
				 EXTENT_LOCKED | EXTENT_DIRTY |
9038 9039
				 EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
				 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
9040
				 &cached_state);
9041 9042

		__btrfs_releasepage(page, GFP_NOFS);
9043 9044
	}

C
Chris Mason 已提交
9045
	ClearPageChecked(page);
9046 9047 9048
	if (PagePrivate(page)) {
		ClearPagePrivate(page);
		set_page_private(page, 0);
9049
		put_page(page);
9050
	}
C
Chris Mason 已提交
9051 9052
}

C
Chris Mason 已提交
9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067
/*
 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
 * called from a page fault handler when a page is first dirtied. Hence we must
 * be careful to check for EOF conditions here. We set the page up correctly
 * for a written page which means we get ENOSPC checking when writing into
 * holes and correct delalloc and unwritten extent mapping on filesystems that
 * support these features.
 *
 * We are not allowed to take the i_mutex here so we have to play games to
 * protect against truncate races as the page could now be beyond EOF.  Because
 * vmtruncate() writes the inode size before removing pages, once we have the
 * page lock we can determine safely if the page is beyond EOF. If it is not
 * beyond EOF, then the page is guaranteed safe against truncation until we
 * unlock the page.
 */
9068
int btrfs_page_mkwrite(struct vm_fault *vmf)
C
Chris Mason 已提交
9069
{
9070
	struct page *page = vmf->page;
9071
	struct inode *inode = file_inode(vmf->vma->vm_file);
9072
	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9073 9074
	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
	struct btrfs_ordered_extent *ordered;
9075
	struct extent_state *cached_state = NULL;
9076
	struct extent_changeset *data_reserved = NULL;
9077 9078
	char *kaddr;
	unsigned long zero_start;
C
Chris Mason 已提交
9079
	loff_t size;
9080
	int ret;
9081
	int reserved = 0;
9082
	u64 reserved_space;
9083
	u64 page_start;
9084
	u64 page_end;
9085 9086
	u64 end;

9087
	reserved_space = PAGE_SIZE;
C
Chris Mason 已提交
9088

9089
	sb_start_pagefault(inode->i_sb);
9090
	page_start = page_offset(page);
9091
	page_end = page_start + PAGE_SIZE - 1;
9092
	end = page_end;
9093

9094 9095 9096 9097 9098 9099 9100 9101
	/*
	 * Reserving delalloc space after obtaining the page lock can lead to
	 * deadlock. For example, if a dirty page is locked by this function
	 * and the call to btrfs_delalloc_reserve_space() ends up triggering
	 * dirty page write out, then the btrfs_writepage() function could
	 * end up waiting indefinitely to get a lock on the page currently
	 * being processed by btrfs_page_mkwrite() function.
	 */
9102
	ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
9103
					   reserved_space);
9104
	if (!ret) {
9105
		ret = file_update_time(vmf->vma->vm_file);
9106 9107
		reserved = 1;
	}
9108 9109 9110 9111 9112
	if (ret) {
		if (ret == -ENOMEM)
			ret = VM_FAULT_OOM;
		else /* -ENOSPC, -EIO, etc */
			ret = VM_FAULT_SIGBUS;
9113 9114 9115
		if (reserved)
			goto out;
		goto out_noreserve;
9116
	}
9117

9118
	ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
9119
again:
C
Chris Mason 已提交
9120 9121
	lock_page(page);
	size = i_size_read(inode);
9122

C
Chris Mason 已提交
9123
	if ((page->mapping != inode->i_mapping) ||
9124
	    (page_start >= size)) {
C
Chris Mason 已提交
9125 9126 9127
		/* page got truncated out from underneath us */
		goto out_unlock;
	}
9128 9129
	wait_on_page_writeback(page);

9130
	lock_extent_bits(io_tree, page_start, page_end, &cached_state);
9131 9132
	set_page_extent_mapped(page);

9133 9134 9135 9136
	/*
	 * we can't set the delalloc bits if there are pending ordered
	 * extents.  Drop our locks and wait for them to finish
	 */
9137 9138
	ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
			PAGE_SIZE);
9139
	if (ordered) {
9140
		unlock_extent_cached(io_tree, page_start, page_end,
9141
				     &cached_state);
9142
		unlock_page(page);
9143
		btrfs_start_ordered_extent(inode, ordered, 1);
9144 9145 9146 9147
		btrfs_put_ordered_extent(ordered);
		goto again;
	}

9148
	if (page->index == ((size - 1) >> PAGE_SHIFT)) {
9149
		reserved_space = round_up(size - page_start,
9150
					  fs_info->sectorsize);
9151
		if (reserved_space < PAGE_SIZE) {
9152
			end = page_start + reserved_space - 1;
9153
			btrfs_delalloc_release_space(inode, data_reserved,
9154 9155
					page_start, PAGE_SIZE - reserved_space,
					true);
9156 9157 9158
		}
	}

J
Josef Bacik 已提交
9159
	/*
9160 9161 9162 9163 9164
	 * page_mkwrite gets called when the page is firstly dirtied after it's
	 * faulted in, but write(2) could also dirty a page and set delalloc
	 * bits, thus in this case for space account reason, we still need to
	 * clear any delalloc bits within this page range since we have to
	 * reserve data&meta space before lock_page() (see above comments).
J
Josef Bacik 已提交
9165
	 */
9166
	clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
9167 9168
			  EXTENT_DIRTY | EXTENT_DELALLOC |
			  EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
9169
			  0, 0, &cached_state);
J
Josef Bacik 已提交
9170

9171
	ret = btrfs_set_extent_delalloc(inode, page_start, end, 0,
9172
					&cached_state, 0);
J
Josef Bacik 已提交
9173
	if (ret) {
9174
		unlock_extent_cached(io_tree, page_start, page_end,
9175
				     &cached_state);
J
Josef Bacik 已提交
9176 9177 9178
		ret = VM_FAULT_SIGBUS;
		goto out_unlock;
	}
9179
	ret = 0;
C
Chris Mason 已提交
9180 9181

	/* page is wholly or partially inside EOF */
9182 9183
	if (page_start + PAGE_SIZE > size)
		zero_start = size & ~PAGE_MASK;
C
Chris Mason 已提交
9184
	else
9185
		zero_start = PAGE_SIZE;
C
Chris Mason 已提交
9186

9187
	if (zero_start != PAGE_SIZE) {
9188
		kaddr = kmap(page);
9189
		memset(kaddr + zero_start, 0, PAGE_SIZE - zero_start);
9190 9191 9192
		flush_dcache_page(page);
		kunmap(page);
	}
9193
	ClearPageChecked(page);
9194
	set_page_dirty(page);
9195
	SetPageUptodate(page);
9196

9197
	BTRFS_I(inode)->last_trans = fs_info->generation;
9198
	BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
9199
	BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
9200

9201
	unlock_extent_cached(io_tree, page_start, page_end, &cached_state);
C
Chris Mason 已提交
9202 9203

out_unlock:
9204
	if (!ret) {
9205
		btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, true);
9206
		sb_end_pagefault(inode->i_sb);
9207
		extent_changeset_free(data_reserved);
9208
		return VM_FAULT_LOCKED;
9209
	}
C
Chris Mason 已提交
9210
	unlock_page(page);
9211
out:
9212
	btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, (ret != 0));
9213
	btrfs_delalloc_release_space(inode, data_reserved, page_start,
9214
				     reserved_space, (ret != 0));
9215
out_noreserve:
9216
	sb_end_pagefault(inode->i_sb);
9217
	extent_changeset_free(data_reserved);
C
Chris Mason 已提交
9218 9219 9220
	return ret;
}

9221
static int btrfs_truncate(struct inode *inode, bool skip_writeback)
C
Chris Mason 已提交
9222
{
9223
	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
C
Chris Mason 已提交
9224
	struct btrfs_root *root = BTRFS_I(inode)->root;
9225
	struct btrfs_block_rsv *rsv;
9226
	int ret = 0;
9227
	int err = 0;
C
Chris Mason 已提交
9228
	struct btrfs_trans_handle *trans;
9229 9230
	u64 mask = fs_info->sectorsize - 1;
	u64 min_size = btrfs_calc_trunc_metadata_size(fs_info, 1);
C
Chris Mason 已提交
9231

9232 9233 9234 9235 9236 9237
	if (!skip_writeback) {
		ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
					       (u64)-1);
		if (ret)
			return ret;
	}
C
Chris Mason 已提交
9238

9239
	/*
9240
	 * Yes ladies and gentlemen, this is indeed ugly.  The fact is we have
9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253
	 * 3 things going on here
	 *
	 * 1) We need to reserve space for our orphan item and the space to
	 * delete our orphan item.  Lord knows we don't want to have a dangling
	 * orphan item because we didn't reserve space to remove it.
	 *
	 * 2) We need to reserve space to update our inode.
	 *
	 * 3) We need to have something to cache all the space that is going to
	 * be free'd up by the truncate operation, but also have some slack
	 * space reserved in case it uses space during the truncate (thank you
	 * very much snapshotting).
	 *
9254
	 * And we need these to all be separate.  The fact is we can use a lot of
9255
	 * space doing the truncate, and we have no earthly idea how much space
9256
	 * we will use, so we need the truncate reservation to be separate so it
9257 9258 9259 9260 9261
	 * doesn't end up using space reserved for updating the inode or
	 * removing the orphan item.  We also need to be able to stop the
	 * transaction and start a new one, which means we need to be able to
	 * update the inode several times, and we have no idea of knowing how
	 * many times that will be, so we can't just reserve 1 item for the
9262
	 * entirety of the operation, so that has to be done separately as well.
9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274
	 * Then there is the orphan item, which does indeed need to be held on
	 * to for the whole operation, and we need nobody to touch this reserved
	 * space except the orphan code.
	 *
	 * So that leaves us with
	 *
	 * 1) root->orphan_block_rsv - for the orphan deletion.
	 * 2) rsv - for the truncate reservation, which we will steal from the
	 * transaction reservation.
	 * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
	 * updating the inode.
	 */
9275
	rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
9276 9277
	if (!rsv)
		return -ENOMEM;
J
Josef Bacik 已提交
9278
	rsv->size = min_size;
9279
	rsv->failfast = 1;
9280

9281
	/*
9282
	 * 1 for the truncate slack space
9283 9284
	 * 1 for updating the inode.
	 */
9285
	trans = btrfs_start_transaction(root, 2);
9286 9287 9288 9289
	if (IS_ERR(trans)) {
		err = PTR_ERR(trans);
		goto out;
	}
9290

9291
	/* Migrate the slack space for the truncate to our reserve */
9292
	ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
9293
				      min_size, 0);
9294
	BUG_ON(ret);
9295

J
Josef Bacik 已提交
9296 9297 9298 9299 9300 9301 9302 9303
	/*
	 * So if we truncate and then write and fsync we normally would just
	 * write the extents that changed, which is a problem if we need to
	 * first truncate that entire inode.  So set this flag so we write out
	 * all of the extents in the inode to the sync log so we're completely
	 * safe.
	 */
	set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
9304
	trans->block_rsv = rsv;
9305

9306 9307 9308 9309
	while (1) {
		ret = btrfs_truncate_inode_items(trans, root, inode,
						 inode->i_size,
						 BTRFS_EXTENT_DATA_KEY);
9310
		trans->block_rsv = &fs_info->trans_block_rsv;
9311
		if (ret != -ENOSPC && ret != -EAGAIN) {
9312 9313
			if (ret < 0)
				err = ret;
9314
			break;
9315
		}
C
Chris Mason 已提交
9316

9317
		ret = btrfs_update_inode(trans, root, inode);
9318 9319 9320 9321
		if (ret) {
			err = ret;
			break;
		}
9322

9323
		btrfs_end_transaction(trans);
9324
		btrfs_btree_balance_dirty(fs_info);
9325 9326 9327 9328 9329 9330 9331 9332

		trans = btrfs_start_transaction(root, 2);
		if (IS_ERR(trans)) {
			ret = err = PTR_ERR(trans);
			trans = NULL;
			break;
		}

9333
		btrfs_block_rsv_release(fs_info, rsv, -1);
9334
		ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
9335
					      rsv, min_size, 0);
9336 9337
		BUG_ON(ret);	/* shouldn't happen */
		trans->block_rsv = rsv;
9338 9339
	}

9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360
	/*
	 * We can't call btrfs_truncate_block inside a trans handle as we could
	 * deadlock with freeze, if we got NEED_TRUNCATE_BLOCK then we know
	 * we've truncated everything except the last little bit, and can do
	 * btrfs_truncate_block and then update the disk_i_size.
	 */
	if (ret == NEED_TRUNCATE_BLOCK) {
		btrfs_end_transaction(trans);
		btrfs_btree_balance_dirty(fs_info);

		ret = btrfs_truncate_block(inode, inode->i_size, 0, 0);
		if (ret)
			goto out;
		trans = btrfs_start_transaction(root, 1);
		if (IS_ERR(trans)) {
			ret = PTR_ERR(trans);
			goto out;
		}
		btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
	}

9361
	if (ret == 0 && inode->i_nlink > 0) {
9362
		trans->block_rsv = root->orphan_block_rsv;
9363
		ret = btrfs_orphan_del(trans, BTRFS_I(inode));
9364 9365
		if (ret)
			err = ret;
9366 9367
	}

9368
	if (trans) {
9369
		trans->block_rsv = &fs_info->trans_block_rsv;
9370 9371 9372
		ret = btrfs_update_inode(trans, root, inode);
		if (ret && !err)
			err = ret;
9373

9374
		ret = btrfs_end_transaction(trans);
9375
		btrfs_btree_balance_dirty(fs_info);
9376
	}
9377
out:
9378
	btrfs_free_block_rsv(fs_info, rsv);
9379

9380 9381
	if (ret && !err)
		err = ret;
9382

9383
	return err;
C
Chris Mason 已提交
9384 9385
}

C
Chris Mason 已提交
9386 9387 9388
/*
 * create a new subvolume directory/inode (helper for the ioctl).
 */
9389
int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
9390 9391 9392
			     struct btrfs_root *new_root,
			     struct btrfs_root *parent_root,
			     u64 new_dirid)
C
Chris Mason 已提交
9393 9394
{
	struct inode *inode;
9395
	int err;
9396
	u64 index = 0;
C
Chris Mason 已提交
9397

9398 9399 9400 9401
	inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
				new_dirid, new_dirid,
				S_IFDIR | (~current_umask() & S_IRWXUGO),
				&index);
9402
	if (IS_ERR(inode))
C
Christoph Hellwig 已提交
9403
		return PTR_ERR(inode);
C
Chris Mason 已提交
9404 9405 9406
	inode->i_op = &btrfs_dir_inode_operations;
	inode->i_fop = &btrfs_dir_file_operations;

M
Miklos Szeredi 已提交
9407
	set_nlink(inode, 1);
9408
	btrfs_i_size_write(BTRFS_I(inode), 0);
9409
	unlock_new_inode(inode);
9410

9411 9412 9413
	err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
	if (err)
		btrfs_err(new_root->fs_info,
9414
			  "error inheriting subvolume %llu properties: %d",
9415 9416
			  new_root->root_key.objectid, err);

9417
	err = btrfs_update_inode(trans, new_root, inode);
9418

9419
	iput(inode);
9420
	return err;
C
Chris Mason 已提交
9421 9422 9423 9424
}

struct inode *btrfs_alloc_inode(struct super_block *sb)
{
9425
	struct btrfs_fs_info *fs_info = btrfs_sb(sb);
C
Chris Mason 已提交
9426
	struct btrfs_inode *ei;
Y
Yan, Zheng 已提交
9427
	struct inode *inode;
C
Chris Mason 已提交
9428

9429
	ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_KERNEL);
C
Chris Mason 已提交
9430 9431
	if (!ei)
		return NULL;
Y
Yan, Zheng 已提交
9432 9433 9434

	ei->root = NULL;
	ei->generation = 0;
9435
	ei->last_trans = 0;
9436
	ei->last_sub_trans = 0;
9437
	ei->logged_trans = 0;
Y
Yan, Zheng 已提交
9438
	ei->delalloc_bytes = 0;
9439
	ei->new_delalloc_bytes = 0;
9440
	ei->defrag_bytes = 0;
Y
Yan, Zheng 已提交
9441 9442
	ei->disk_i_size = 0;
	ei->flags = 0;
9443
	ei->csum_bytes = 0;
Y
Yan, Zheng 已提交
9444
	ei->index_cnt = (u64)-1;
9445
	ei->dir_index = 0;
Y
Yan, Zheng 已提交
9446
	ei->last_unlink_trans = 0;
9447
	ei->last_log_commit = 0;
Y
Yan, Zheng 已提交
9448

9449 9450
	spin_lock_init(&ei->lock);
	ei->outstanding_extents = 0;
9451 9452 9453
	if (sb->s_magic != BTRFS_TEST_MAGIC)
		btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
					      BTRFS_BLOCK_RSV_DELALLOC);
9454
	ei->runtime_flags = 0;
9455
	ei->prop_compress = BTRFS_COMPRESS_NONE;
9456
	ei->defrag_compress = BTRFS_COMPRESS_NONE;
Y
Yan, Zheng 已提交
9457

9458 9459
	ei->delayed_node = NULL;

9460 9461 9462
	ei->i_otime.tv_sec = 0;
	ei->i_otime.tv_nsec = 0;

Y
Yan, Zheng 已提交
9463
	inode = &ei->vfs_inode;
9464
	extent_map_tree_init(&ei->extent_tree);
9465 9466
	extent_io_tree_init(&ei->io_tree, inode);
	extent_io_tree_init(&ei->io_failure_tree, inode);
9467 9468
	ei->io_tree.track_uptodate = 1;
	ei->io_failure_tree.track_uptodate = 1;
9469
	atomic_set(&ei->sync_writers, 0);
Y
Yan, Zheng 已提交
9470
	mutex_init(&ei->log_mutex);
9471
	mutex_init(&ei->delalloc_mutex);
9472
	btrfs_ordered_inode_tree_init(&ei->ordered_tree);
Y
Yan, Zheng 已提交
9473
	INIT_LIST_HEAD(&ei->delalloc_inodes);
9474
	INIT_LIST_HEAD(&ei->delayed_iput);
Y
Yan, Zheng 已提交
9475
	RB_CLEAR_NODE(&ei->rb_node);
9476
	init_rwsem(&ei->dio_sem);
Y
Yan, Zheng 已提交
9477 9478

	return inode;
C
Chris Mason 已提交
9479 9480
}

9481 9482 9483
#ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
void btrfs_test_destroy_inode(struct inode *inode)
{
9484
	btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9485 9486 9487 9488
	kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
}
#endif

N
Nick Piggin 已提交
9489 9490 9491 9492 9493 9494
static void btrfs_i_callback(struct rcu_head *head)
{
	struct inode *inode = container_of(head, struct inode, i_rcu);
	kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
}

C
Chris Mason 已提交
9495 9496
void btrfs_destroy_inode(struct inode *inode)
{
9497
	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9498
	struct btrfs_ordered_extent *ordered;
9499 9500
	struct btrfs_root *root = BTRFS_I(inode)->root;

A
Al Viro 已提交
9501
	WARN_ON(!hlist_empty(&inode->i_dentry));
C
Chris Mason 已提交
9502
	WARN_ON(inode->i_data.nrpages);
9503 9504
	WARN_ON(BTRFS_I(inode)->block_rsv.reserved);
	WARN_ON(BTRFS_I(inode)->block_rsv.size);
9505
	WARN_ON(BTRFS_I(inode)->outstanding_extents);
9506
	WARN_ON(BTRFS_I(inode)->delalloc_bytes);
9507
	WARN_ON(BTRFS_I(inode)->new_delalloc_bytes);
9508
	WARN_ON(BTRFS_I(inode)->csum_bytes);
9509
	WARN_ON(BTRFS_I(inode)->defrag_bytes);
C
Chris Mason 已提交
9510

9511 9512 9513 9514 9515 9516 9517 9518
	/*
	 * This can happen where we create an inode, but somebody else also
	 * created the same inode and we need to destroy the one we already
	 * created.
	 */
	if (!root)
		goto free;

9519 9520
	if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
		     &BTRFS_I(inode)->runtime_flags)) {
9521
		btrfs_info(fs_info, "inode %llu still on the orphan list",
9522
			   btrfs_ino(BTRFS_I(inode)));
9523
		atomic_dec(&root->orphan_inodes);
9524 9525
	}

C
Chris Mason 已提交
9526
	while (1) {
9527 9528 9529 9530
		ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
		if (!ordered)
			break;
		else {
9531
			btrfs_err(fs_info,
J
Jeff Mahoney 已提交
9532 9533
				  "found ordered extent %llu %llu on inode cleanup",
				  ordered->file_offset, ordered->len);
9534 9535 9536 9537 9538
			btrfs_remove_ordered_extent(inode, ordered);
			btrfs_put_ordered_extent(ordered);
			btrfs_put_ordered_extent(ordered);
		}
	}
9539
	btrfs_qgroup_check_reserved_leak(inode);
9540
	inode_tree_del(inode);
9541
	btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9542
free:
N
Nick Piggin 已提交
9543
	call_rcu(&inode->i_rcu, btrfs_i_callback);
C
Chris Mason 已提交
9544 9545
}

9546
int btrfs_drop_inode(struct inode *inode)
9547 9548
{
	struct btrfs_root *root = BTRFS_I(inode)->root;
9549

9550 9551 9552
	if (root == NULL)
		return 1;

9553
	/* the snap/subvol tree is on deleting */
9554
	if (btrfs_root_refs(&root->root_item) == 0)
9555
		return 1;
9556
	else
9557
		return generic_drop_inode(inode);
9558 9559
}

9560
static void init_once(void *foo)
C
Chris Mason 已提交
9561 9562 9563 9564 9565 9566
{
	struct btrfs_inode *ei = (struct btrfs_inode *) foo;

	inode_init_once(&ei->vfs_inode);
}

9567
void __cold btrfs_destroy_cachep(void)
C
Chris Mason 已提交
9568
{
9569 9570 9571 9572 9573
	/*
	 * Make sure all delayed rcu free inodes are flushed before we
	 * destroy cache.
	 */
	rcu_barrier();
9574 9575 9576 9577
	kmem_cache_destroy(btrfs_inode_cachep);
	kmem_cache_destroy(btrfs_trans_handle_cachep);
	kmem_cache_destroy(btrfs_path_cachep);
	kmem_cache_destroy(btrfs_free_space_cachep);
C
Chris Mason 已提交
9578 9579
}

9580
int __init btrfs_init_cachep(void)
C
Chris Mason 已提交
9581
{
D
David Sterba 已提交
9582
	btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
9583
			sizeof(struct btrfs_inode), 0,
9584 9585
			SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
			init_once);
C
Chris Mason 已提交
9586 9587
	if (!btrfs_inode_cachep)
		goto fail;
9588

D
David Sterba 已提交
9589
	btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
9590
			sizeof(struct btrfs_trans_handle), 0,
9591
			SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
C
Chris Mason 已提交
9592 9593
	if (!btrfs_trans_handle_cachep)
		goto fail;
9594

D
David Sterba 已提交
9595
	btrfs_path_cachep = kmem_cache_create("btrfs_path",
9596
			sizeof(struct btrfs_path), 0,
9597
			SLAB_MEM_SPREAD, NULL);
C
Chris Mason 已提交
9598 9599
	if (!btrfs_path_cachep)
		goto fail;
9600

D
David Sterba 已提交
9601
	btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
9602
			sizeof(struct btrfs_free_space), 0,
9603
			SLAB_MEM_SPREAD, NULL);
9604 9605 9606
	if (!btrfs_free_space_cachep)
		goto fail;

C
Chris Mason 已提交
9607 9608 9609 9610 9611 9612
	return 0;
fail:
	btrfs_destroy_cachep();
	return -ENOMEM;
}

9613 9614
static int btrfs_getattr(const struct path *path, struct kstat *stat,
			 u32 request_mask, unsigned int flags)
C
Chris Mason 已提交
9615
{
9616
	u64 delalloc_bytes;
9617
	struct inode *inode = d_inode(path->dentry);
D
David Sterba 已提交
9618
	u32 blocksize = inode->i_sb->s_blocksize;
Y
Yonghong Song 已提交
9619 9620 9621 9622 9623 9624 9625 9626 9627 9628 9629 9630 9631 9632 9633 9634 9635 9636
	u32 bi_flags = BTRFS_I(inode)->flags;

	stat->result_mask |= STATX_BTIME;
	stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
	stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
	if (bi_flags & BTRFS_INODE_APPEND)
		stat->attributes |= STATX_ATTR_APPEND;
	if (bi_flags & BTRFS_INODE_COMPRESS)
		stat->attributes |= STATX_ATTR_COMPRESSED;
	if (bi_flags & BTRFS_INODE_IMMUTABLE)
		stat->attributes |= STATX_ATTR_IMMUTABLE;
	if (bi_flags & BTRFS_INODE_NODUMP)
		stat->attributes |= STATX_ATTR_NODUMP;

	stat->attributes_mask |= (STATX_ATTR_APPEND |
				  STATX_ATTR_COMPRESSED |
				  STATX_ATTR_IMMUTABLE |
				  STATX_ATTR_NODUMP);
D
David Sterba 已提交
9637

C
Chris Mason 已提交
9638
	generic_fillattr(inode, stat);
9639
	stat->dev = BTRFS_I(inode)->root->anon_dev;
9640 9641

	spin_lock(&BTRFS_I(inode)->lock);
9642
	delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
9643
	spin_unlock(&BTRFS_I(inode)->lock);
D
David Sterba 已提交
9644
	stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
9645
			ALIGN(delalloc_bytes, blocksize)) >> 9;
C
Chris Mason 已提交
9646 9647 9648
	return 0;
}

9649 9650 9651 9652 9653
static int btrfs_rename_exchange(struct inode *old_dir,
			      struct dentry *old_dentry,
			      struct inode *new_dir,
			      struct dentry *new_dentry)
{
9654
	struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9655 9656 9657 9658 9659
	struct btrfs_trans_handle *trans;
	struct btrfs_root *root = BTRFS_I(old_dir)->root;
	struct btrfs_root *dest = BTRFS_I(new_dir)->root;
	struct inode *new_inode = new_dentry->d_inode;
	struct inode *old_inode = old_dentry->d_inode;
9660
	struct timespec ctime = current_time(old_inode);
9661
	struct dentry *parent;
9662 9663
	u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
	u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
9664 9665 9666 9667
	u64 old_idx = 0;
	u64 new_idx = 0;
	u64 root_objectid;
	int ret;
9668 9669
	bool root_log_pinned = false;
	bool dest_log_pinned = false;
9670 9671 9672 9673 9674 9675 9676

	/* we only allow rename subvolume link between subvolumes */
	if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
		return -EXDEV;

	/* close the race window with snapshot create/destroy ioctl */
	if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9677
		down_read(&fs_info->subvol_sem);
9678
	if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9679
		down_read(&fs_info->subvol_sem);
9680 9681 9682 9683 9684 9685 9686 9687 9688 9689 9690 9691 9692 9693 9694 9695 9696 9697 9698

	/*
	 * We want to reserve the absolute worst case amount of items.  So if
	 * both inodes are subvols and we need to unlink them then that would
	 * require 4 item modifications, but if they are both normal inodes it
	 * would require 5 item modifications, so we'll assume their normal
	 * inodes.  So 5 * 2 is 10, plus 2 for the new links, so 12 total items
	 * should cover the worst case number of items we'll modify.
	 */
	trans = btrfs_start_transaction(root, 12);
	if (IS_ERR(trans)) {
		ret = PTR_ERR(trans);
		goto out_notrans;
	}

	/*
	 * We need to find a free sequence number both in the source and
	 * in the destination directory for the exchange.
	 */
9699
	ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
9700 9701
	if (ret)
		goto out_fail;
9702
	ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
9703 9704 9705 9706 9707 9708 9709 9710 9711
	if (ret)
		goto out_fail;

	BTRFS_I(old_inode)->dir_index = 0ULL;
	BTRFS_I(new_inode)->dir_index = 0ULL;

	/* Reference for the source. */
	if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
		/* force full log commit if subvolume involved. */
9712
		btrfs_set_log_full_commit(fs_info, trans);
9713
	} else {
9714 9715
		btrfs_pin_log_trans(root);
		root_log_pinned = true;
9716 9717 9718 9719
		ret = btrfs_insert_inode_ref(trans, dest,
					     new_dentry->d_name.name,
					     new_dentry->d_name.len,
					     old_ino,
9720 9721
					     btrfs_ino(BTRFS_I(new_dir)),
					     old_idx);
9722 9723 9724 9725 9726 9727 9728
		if (ret)
			goto out_fail;
	}

	/* And now for the dest. */
	if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
		/* force full log commit if subvolume involved. */
9729
		btrfs_set_log_full_commit(fs_info, trans);
9730
	} else {
9731 9732
		btrfs_pin_log_trans(dest);
		dest_log_pinned = true;
9733 9734 9735 9736
		ret = btrfs_insert_inode_ref(trans, root,
					     old_dentry->d_name.name,
					     old_dentry->d_name.len,
					     new_ino,
9737 9738
					     btrfs_ino(BTRFS_I(old_dir)),
					     new_idx);
9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752 9753
		if (ret)
			goto out_fail;
	}

	/* Update inode version and ctime/mtime. */
	inode_inc_iversion(old_dir);
	inode_inc_iversion(new_dir);
	inode_inc_iversion(old_inode);
	inode_inc_iversion(new_inode);
	old_dir->i_ctime = old_dir->i_mtime = ctime;
	new_dir->i_ctime = new_dir->i_mtime = ctime;
	old_inode->i_ctime = ctime;
	new_inode->i_ctime = ctime;

	if (old_dentry->d_parent != new_dentry->d_parent) {
9754 9755 9756 9757
		btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
				BTRFS_I(old_inode), 1);
		btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
				BTRFS_I(new_inode), 1);
9758 9759 9760 9761 9762 9763 9764 9765 9766 9767
	}

	/* src is a subvolume */
	if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
		root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
		ret = btrfs_unlink_subvol(trans, root, old_dir,
					  root_objectid,
					  old_dentry->d_name.name,
					  old_dentry->d_name.len);
	} else { /* src is an inode */
9768 9769
		ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
					   BTRFS_I(old_dentry->d_inode),
9770 9771 9772 9773 9774 9775
					   old_dentry->d_name.name,
					   old_dentry->d_name.len);
		if (!ret)
			ret = btrfs_update_inode(trans, root, old_inode);
	}
	if (ret) {
9776
		btrfs_abort_transaction(trans, ret);
9777 9778 9779 9780 9781 9782 9783 9784 9785 9786 9787
		goto out_fail;
	}

	/* dest is a subvolume */
	if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
		root_objectid = BTRFS_I(new_inode)->root->root_key.objectid;
		ret = btrfs_unlink_subvol(trans, dest, new_dir,
					  root_objectid,
					  new_dentry->d_name.name,
					  new_dentry->d_name.len);
	} else { /* dest is an inode */
9788 9789
		ret = __btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
					   BTRFS_I(new_dentry->d_inode),
9790 9791 9792 9793 9794 9795
					   new_dentry->d_name.name,
					   new_dentry->d_name.len);
		if (!ret)
			ret = btrfs_update_inode(trans, dest, new_inode);
	}
	if (ret) {
9796
		btrfs_abort_transaction(trans, ret);
9797 9798 9799
		goto out_fail;
	}

9800
	ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9801 9802 9803
			     new_dentry->d_name.name,
			     new_dentry->d_name.len, 0, old_idx);
	if (ret) {
9804
		btrfs_abort_transaction(trans, ret);
9805 9806 9807
		goto out_fail;
	}

9808
	ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
9809 9810 9811
			     old_dentry->d_name.name,
			     old_dentry->d_name.len, 0, new_idx);
	if (ret) {
9812
		btrfs_abort_transaction(trans, ret);
9813 9814 9815 9816 9817 9818 9819 9820
		goto out_fail;
	}

	if (old_inode->i_nlink == 1)
		BTRFS_I(old_inode)->dir_index = old_idx;
	if (new_inode->i_nlink == 1)
		BTRFS_I(new_inode)->dir_index = new_idx;

9821
	if (root_log_pinned) {
9822
		parent = new_dentry->d_parent;
9823 9824
		btrfs_log_new_name(trans, BTRFS_I(old_inode), BTRFS_I(old_dir),
				parent);
9825
		btrfs_end_log_trans(root);
9826
		root_log_pinned = false;
9827
	}
9828
	if (dest_log_pinned) {
9829
		parent = old_dentry->d_parent;
9830 9831
		btrfs_log_new_name(trans, BTRFS_I(new_inode), BTRFS_I(new_dir),
				parent);
9832
		btrfs_end_log_trans(dest);
9833
		dest_log_pinned = false;
9834 9835
	}
out_fail:
9836 9837 9838 9839 9840 9841 9842 9843 9844 9845 9846 9847
	/*
	 * If we have pinned a log and an error happened, we unpin tasks
	 * trying to sync the log and force them to fallback to a transaction
	 * commit if the log currently contains any of the inodes involved in
	 * this rename operation (to ensure we do not persist a log with an
	 * inconsistent state for any of these inodes or leading to any
	 * inconsistencies when replayed). If the transaction was aborted, the
	 * abortion reason is propagated to userspace when attempting to commit
	 * the transaction. If the log does not contain any of these inodes, we
	 * allow the tasks to sync it.
	 */
	if (ret && (root_log_pinned || dest_log_pinned)) {
9848 9849 9850
		if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
		    btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
		    btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9851
		    (new_inode &&
9852
		     btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9853
			btrfs_set_log_full_commit(fs_info, trans);
9854 9855 9856 9857 9858 9859 9860 9861 9862 9863

		if (root_log_pinned) {
			btrfs_end_log_trans(root);
			root_log_pinned = false;
		}
		if (dest_log_pinned) {
			btrfs_end_log_trans(dest);
			dest_log_pinned = false;
		}
	}
9864
	ret = btrfs_end_transaction(trans);
9865 9866
out_notrans:
	if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9867
		up_read(&fs_info->subvol_sem);
9868
	if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9869
		up_read(&fs_info->subvol_sem);
9870 9871 9872 9873 9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9885 9886 9887 9888 9889 9890

	return ret;
}

static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans,
				     struct btrfs_root *root,
				     struct inode *dir,
				     struct dentry *dentry)
{
	int ret;
	struct inode *inode;
	u64 objectid;
	u64 index;

	ret = btrfs_find_free_ino(root, &objectid);
	if (ret)
		return ret;

	inode = btrfs_new_inode(trans, root, dir,
				dentry->d_name.name,
				dentry->d_name.len,
9891
				btrfs_ino(BTRFS_I(dir)),
9892 9893 9894 9895 9896 9897 9898 9899 9900 9901 9902 9903 9904 9905 9906 9907
				objectid,
				S_IFCHR | WHITEOUT_MODE,
				&index);

	if (IS_ERR(inode)) {
		ret = PTR_ERR(inode);
		return ret;
	}

	inode->i_op = &btrfs_special_inode_operations;
	init_special_inode(inode, inode->i_mode,
		WHITEOUT_DEV);

	ret = btrfs_init_inode_security(trans, inode, dir,
				&dentry->d_name);
	if (ret)
9908
		goto out;
9909

9910 9911
	ret = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
				BTRFS_I(inode), 0, index);
9912
	if (ret)
9913
		goto out;
9914 9915

	ret = btrfs_update_inode(trans, root, inode);
9916
out:
9917
	unlock_new_inode(inode);
9918 9919
	if (ret)
		inode_dec_link_count(inode);
9920 9921
	iput(inode);

9922
	return ret;
9923 9924
}

C
Chris Mason 已提交
9925
static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
9926 9927
			   struct inode *new_dir, struct dentry *new_dentry,
			   unsigned int flags)
C
Chris Mason 已提交
9928
{
9929
	struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
C
Chris Mason 已提交
9930
	struct btrfs_trans_handle *trans;
9931
	unsigned int trans_num_items;
C
Chris Mason 已提交
9932
	struct btrfs_root *root = BTRFS_I(old_dir)->root;
9933
	struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9934 9935
	struct inode *new_inode = d_inode(new_dentry);
	struct inode *old_inode = d_inode(old_dentry);
9936
	u64 index = 0;
9937
	u64 root_objectid;
C
Chris Mason 已提交
9938
	int ret;
9939
	u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9940
	bool log_pinned = false;
C
Chris Mason 已提交
9941

9942
	if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9943 9944
		return -EPERM;

9945
	/* we only allow rename subvolume link between subvolumes */
L
Li Zefan 已提交
9946
	if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9947 9948
		return -EXDEV;

L
Li Zefan 已提交
9949
	if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9950
	    (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
C
Chris Mason 已提交
9951
		return -ENOTEMPTY;
9952

9953 9954 9955
	if (S_ISDIR(old_inode->i_mode) && new_inode &&
	    new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
		return -ENOTEMPTY;
C
Chris Mason 已提交
9956 9957 9958


	/* check for collisions, even if the  name isn't there */
9959
	ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
C
Chris Mason 已提交
9960 9961 9962 9963 9964 9965 9966
			     new_dentry->d_name.name,
			     new_dentry->d_name.len);

	if (ret) {
		if (ret == -EEXIST) {
			/* we shouldn't get
			 * eexist without a new_inode */
9967
			if (WARN_ON(!new_inode)) {
C
Chris Mason 已提交
9968 9969 9970 9971 9972 9973 9974 9975 9976
				return ret;
			}
		} else {
			/* maybe -EOVERFLOW */
			return ret;
		}
	}
	ret = 0;

9977
	/*
9978 9979
	 * we're using rename to replace one file with another.  Start IO on it
	 * now so  we don't add too much work to the end of the transaction
9980
	 */
9981
	if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9982 9983
		filemap_flush(old_inode->i_mapping);

9984
	/* close the racy window with snapshot create/destroy ioctl */
L
Li Zefan 已提交
9985
	if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9986
		down_read(&fs_info->subvol_sem);
9987 9988 9989 9990
	/*
	 * We want to reserve the absolute worst case amount of items.  So if
	 * both inodes are subvols and we need to unlink them then that would
	 * require 4 item modifications, but if they are both normal inodes it
9991
	 * would require 5 item modifications, so we'll assume they are normal
9992 9993
	 * inodes.  So 5 * 2 is 10, plus 1 for the new link, so 11 total items
	 * should cover the worst case number of items we'll modify.
9994 9995 9996
	 * If our rename has the whiteout flag, we need more 5 units for the
	 * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
	 * when selinux is enabled).
9997
	 */
9998 9999 10000 10001
	trans_num_items = 11;
	if (flags & RENAME_WHITEOUT)
		trans_num_items += 5;
	trans = btrfs_start_transaction(root, trans_num_items);
10002
	if (IS_ERR(trans)) {
10003 10004 10005
		ret = PTR_ERR(trans);
		goto out_notrans;
	}
10006

10007 10008
	if (dest != root)
		btrfs_record_root_in_trans(trans, dest);
10009

10010
	ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
10011 10012
	if (ret)
		goto out_fail;
10013

10014
	BTRFS_I(old_inode)->dir_index = 0ULL;
L
Li Zefan 已提交
10015
	if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
10016
		/* force full log commit if subvolume involved. */
10017
		btrfs_set_log_full_commit(fs_info, trans);
10018
	} else {
10019 10020
		btrfs_pin_log_trans(root);
		log_pinned = true;
10021 10022 10023
		ret = btrfs_insert_inode_ref(trans, dest,
					     new_dentry->d_name.name,
					     new_dentry->d_name.len,
L
Li Zefan 已提交
10024
					     old_ino,
10025
					     btrfs_ino(BTRFS_I(new_dir)), index);
10026 10027
		if (ret)
			goto out_fail;
10028
	}
10029

10030 10031 10032
	inode_inc_iversion(old_dir);
	inode_inc_iversion(new_dir);
	inode_inc_iversion(old_inode);
10033 10034
	old_dir->i_ctime = old_dir->i_mtime =
	new_dir->i_ctime = new_dir->i_mtime =
10035
	old_inode->i_ctime = current_time(old_dir);
10036

10037
	if (old_dentry->d_parent != new_dentry->d_parent)
10038 10039
		btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
				BTRFS_I(old_inode), 1);
10040

L
Li Zefan 已提交
10041
	if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
10042 10043 10044 10045 10046
		root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
		ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
					old_dentry->d_name.name,
					old_dentry->d_name.len);
	} else {
10047 10048
		ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
					BTRFS_I(d_inode(old_dentry)),
10049 10050 10051 10052
					old_dentry->d_name.name,
					old_dentry->d_name.len);
		if (!ret)
			ret = btrfs_update_inode(trans, root, old_inode);
10053
	}
10054
	if (ret) {
10055
		btrfs_abort_transaction(trans, ret);
10056 10057
		goto out_fail;
	}
C
Chris Mason 已提交
10058 10059

	if (new_inode) {
10060
		inode_inc_iversion(new_inode);
10061
		new_inode->i_ctime = current_time(new_inode);
10062
		if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
10063 10064 10065 10066 10067 10068 10069 10070
			     BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
			root_objectid = BTRFS_I(new_inode)->location.objectid;
			ret = btrfs_unlink_subvol(trans, dest, new_dir,
						root_objectid,
						new_dentry->d_name.name,
						new_dentry->d_name.len);
			BUG_ON(new_inode->i_nlink == 0);
		} else {
10071 10072
			ret = btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
						 BTRFS_I(d_inode(new_dentry)),
10073 10074 10075
						 new_dentry->d_name.name,
						 new_dentry->d_name.len);
		}
10076
		if (!ret && new_inode->i_nlink == 0)
10077 10078
			ret = btrfs_orphan_add(trans,
					BTRFS_I(d_inode(new_dentry)));
10079
		if (ret) {
10080
			btrfs_abort_transaction(trans, ret);
10081 10082
			goto out_fail;
		}
C
Chris Mason 已提交
10083
	}
10084

10085
	ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
10086
			     new_dentry->d_name.name,
10087
			     new_dentry->d_name.len, 0, index);
10088
	if (ret) {
10089
		btrfs_abort_transaction(trans, ret);
10090 10091
		goto out_fail;
	}
C
Chris Mason 已提交
10092

10093 10094 10095
	if (old_inode->i_nlink == 1)
		BTRFS_I(old_inode)->dir_index = index;

10096
	if (log_pinned) {
10097
		struct dentry *parent = new_dentry->d_parent;
10098

10099 10100
		btrfs_log_new_name(trans, BTRFS_I(old_inode), BTRFS_I(old_dir),
				parent);
10101
		btrfs_end_log_trans(root);
10102
		log_pinned = false;
10103
	}
10104 10105 10106 10107 10108 10109

	if (flags & RENAME_WHITEOUT) {
		ret = btrfs_whiteout_for_rename(trans, root, old_dir,
						old_dentry);

		if (ret) {
10110
			btrfs_abort_transaction(trans, ret);
10111 10112
			goto out_fail;
		}
10113
	}
C
Chris Mason 已提交
10114
out_fail:
10115 10116 10117 10118 10119 10120 10121 10122 10123 10124 10125 10126
	/*
	 * If we have pinned the log and an error happened, we unpin tasks
	 * trying to sync the log and force them to fallback to a transaction
	 * commit if the log currently contains any of the inodes involved in
	 * this rename operation (to ensure we do not persist a log with an
	 * inconsistent state for any of these inodes or leading to any
	 * inconsistencies when replayed). If the transaction was aborted, the
	 * abortion reason is propagated to userspace when attempting to commit
	 * the transaction. If the log does not contain any of these inodes, we
	 * allow the tasks to sync it.
	 */
	if (ret && log_pinned) {
10127 10128 10129
		if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
		    btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
		    btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
10130
		    (new_inode &&
10131
		     btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
10132
			btrfs_set_log_full_commit(fs_info, trans);
10133 10134 10135 10136

		btrfs_end_log_trans(root);
		log_pinned = false;
	}
10137
	btrfs_end_transaction(trans);
10138
out_notrans:
L
Li Zefan 已提交
10139
	if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
10140
		up_read(&fs_info->subvol_sem);
J
Josef Bacik 已提交
10141

C
Chris Mason 已提交
10142 10143 10144
	return ret;
}

M
Miklos Szeredi 已提交
10145 10146 10147 10148
static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
			 struct inode *new_dir, struct dentry *new_dentry,
			 unsigned int flags)
{
10149
	if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
M
Miklos Szeredi 已提交
10150 10151
		return -EINVAL;

10152 10153 10154 10155 10156
	if (flags & RENAME_EXCHANGE)
		return btrfs_rename_exchange(old_dir, old_dentry, new_dir,
					  new_dentry);

	return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
M
Miklos Szeredi 已提交
10157 10158
}

10159 10160 10161
static void btrfs_run_delalloc_work(struct btrfs_work *work)
{
	struct btrfs_delalloc_work *delalloc_work;
10162
	struct inode *inode;
10163 10164 10165

	delalloc_work = container_of(work, struct btrfs_delalloc_work,
				     work);
10166
	inode = delalloc_work->inode;
10167 10168 10169
	filemap_flush(inode->i_mapping);
	if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
				&BTRFS_I(inode)->runtime_flags))
10170
		filemap_flush(inode->i_mapping);
10171 10172

	if (delalloc_work->delay_iput)
10173
		btrfs_add_delayed_iput(inode);
10174
	else
10175
		iput(inode);
10176 10177 10178 10179
	complete(&delalloc_work->completion);
}

struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode,
10180
						    int delay_iput)
10181 10182 10183
{
	struct btrfs_delalloc_work *work;

10184
	work = kmalloc(sizeof(*work), GFP_NOFS);
10185 10186 10187 10188 10189 10190 10191
	if (!work)
		return NULL;

	init_completion(&work->completion);
	INIT_LIST_HEAD(&work->list);
	work->inode = inode;
	work->delay_iput = delay_iput;
10192 10193 10194
	WARN_ON_ONCE(!inode);
	btrfs_init_work(&work->work, btrfs_flush_delalloc_helper,
			btrfs_run_delalloc_work, NULL, NULL);
10195 10196 10197 10198 10199 10200 10201

	return work;
}

void btrfs_wait_and_free_delalloc_work(struct btrfs_delalloc_work *work)
{
	wait_for_completion(&work->completion);
10202
	kfree(work);
10203 10204
}

C
Chris Mason 已提交
10205 10206 10207 10208
/*
 * some fairly slow code that needs optimization. This walks the list
 * of all the inodes with pending delalloc and forces them to disk.
 */
10209 10210
static int __start_delalloc_inodes(struct btrfs_root *root, int delay_iput,
				   int nr)
10211 10212
{
	struct btrfs_inode *binode;
10213
	struct inode *inode;
10214 10215
	struct btrfs_delalloc_work *work, *next;
	struct list_head works;
10216
	struct list_head splice;
10217
	int ret = 0;
10218

10219
	INIT_LIST_HEAD(&works);
10220
	INIT_LIST_HEAD(&splice);
10221

10222
	mutex_lock(&root->delalloc_mutex);
10223 10224
	spin_lock(&root->delalloc_lock);
	list_splice_init(&root->delalloc_inodes, &splice);
10225 10226
	while (!list_empty(&splice)) {
		binode = list_entry(splice.next, struct btrfs_inode,
10227
				    delalloc_inodes);
10228

10229 10230
		list_move_tail(&binode->delalloc_inodes,
			       &root->delalloc_inodes);
10231
		inode = igrab(&binode->vfs_inode);
10232
		if (!inode) {
10233
			cond_resched_lock(&root->delalloc_lock);
10234
			continue;
10235
		}
10236
		spin_unlock(&root->delalloc_lock);
10237

10238
		work = btrfs_alloc_delalloc_work(inode, delay_iput);
10239
		if (!work) {
10240 10241 10242 10243
			if (delay_iput)
				btrfs_add_delayed_iput(inode);
			else
				iput(inode);
10244
			ret = -ENOMEM;
10245
			goto out;
10246
		}
10247
		list_add_tail(&work->list, &works);
10248 10249
		btrfs_queue_work(root->fs_info->flush_workers,
				 &work->work);
10250 10251
		ret++;
		if (nr != -1 && ret >= nr)
10252
			goto out;
10253
		cond_resched();
10254
		spin_lock(&root->delalloc_lock);
10255
	}
10256
	spin_unlock(&root->delalloc_lock);
10257

10258
out:
10259 10260 10261 10262 10263 10264 10265 10266 10267 10268
	list_for_each_entry_safe(work, next, &works, list) {
		list_del_init(&work->list);
		btrfs_wait_and_free_delalloc_work(work);
	}

	if (!list_empty_careful(&splice)) {
		spin_lock(&root->delalloc_lock);
		list_splice_tail(&splice, &root->delalloc_inodes);
		spin_unlock(&root->delalloc_lock);
	}
10269
	mutex_unlock(&root->delalloc_mutex);
10270 10271
	return ret;
}
10272

10273 10274
int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
{
10275
	struct btrfs_fs_info *fs_info = root->fs_info;
10276
	int ret;
10277

10278
	if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10279 10280
		return -EROFS;

10281 10282 10283
	ret = __start_delalloc_inodes(root, delay_iput, -1);
	if (ret > 0)
		ret = 0;
10284 10285 10286
	return ret;
}

10287 10288
int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int delay_iput,
			       int nr)
10289 10290 10291 10292 10293
{
	struct btrfs_root *root;
	struct list_head splice;
	int ret;

10294
	if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10295 10296 10297 10298
		return -EROFS;

	INIT_LIST_HEAD(&splice);

10299
	mutex_lock(&fs_info->delalloc_root_mutex);
10300 10301
	spin_lock(&fs_info->delalloc_root_lock);
	list_splice_init(&fs_info->delalloc_roots, &splice);
10302
	while (!list_empty(&splice) && nr) {
10303 10304 10305 10306 10307 10308 10309 10310
		root = list_first_entry(&splice, struct btrfs_root,
					delalloc_root);
		root = btrfs_grab_fs_root(root);
		BUG_ON(!root);
		list_move_tail(&root->delalloc_root,
			       &fs_info->delalloc_roots);
		spin_unlock(&fs_info->delalloc_root_lock);

10311
		ret = __start_delalloc_inodes(root, delay_iput, nr);
10312
		btrfs_put_fs_root(root);
10313
		if (ret < 0)
10314 10315
			goto out;

10316 10317 10318 10319
		if (nr != -1) {
			nr -= ret;
			WARN_ON(nr < 0);
		}
10320
		spin_lock(&fs_info->delalloc_root_lock);
10321
	}
10322
	spin_unlock(&fs_info->delalloc_root_lock);
10323

10324
	ret = 0;
10325
out:
10326
	if (!list_empty_careful(&splice)) {
10327 10328 10329
		spin_lock(&fs_info->delalloc_root_lock);
		list_splice_tail(&splice, &fs_info->delalloc_roots);
		spin_unlock(&fs_info->delalloc_root_lock);
10330
	}
10331
	mutex_unlock(&fs_info->delalloc_root_mutex);
10332
	return ret;
10333 10334
}

C
Chris Mason 已提交
10335 10336 10337
static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
			 const char *symname)
{
10338
	struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
C
Chris Mason 已提交
10339 10340 10341 10342
	struct btrfs_trans_handle *trans;
	struct btrfs_root *root = BTRFS_I(dir)->root;
	struct btrfs_path *path;
	struct btrfs_key key;
10343
	struct inode *inode = NULL;
C
Chris Mason 已提交
10344 10345 10346
	int err;
	int drop_inode = 0;
	u64 objectid;
10347
	u64 index = 0;
C
Chris Mason 已提交
10348 10349
	int name_len;
	int datasize;
10350
	unsigned long ptr;
C
Chris Mason 已提交
10351
	struct btrfs_file_extent_item *ei;
10352
	struct extent_buffer *leaf;
C
Chris Mason 已提交
10353

10354
	name_len = strlen(symname);
10355
	if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
C
Chris Mason 已提交
10356
		return -ENAMETOOLONG;
10357

J
Josef Bacik 已提交
10358 10359 10360
	/*
	 * 2 items for inode item and ref
	 * 2 items for dir items
10361 10362
	 * 1 item for updating parent inode item
	 * 1 item for the inline extent item
J
Josef Bacik 已提交
10363 10364
	 * 1 item for xattr if selinux is on
	 */
10365
	trans = btrfs_start_transaction(root, 7);
10366 10367
	if (IS_ERR(trans))
		return PTR_ERR(trans);
10368

10369 10370 10371 10372
	err = btrfs_find_free_ino(root, &objectid);
	if (err)
		goto out_unlock;

10373
	inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
10374 10375
				dentry->d_name.len, btrfs_ino(BTRFS_I(dir)),
				objectid, S_IFLNK|S_IRWXUGO, &index);
10376 10377
	if (IS_ERR(inode)) {
		err = PTR_ERR(inode);
C
Chris Mason 已提交
10378
		goto out_unlock;
10379
	}
C
Chris Mason 已提交
10380

10381 10382 10383 10384 10385 10386 10387 10388
	/*
	* If the active LSM wants to access the inode during
	* d_instantiate it needs these. Smack checks to see
	* if the filesystem supports xattrs by looking at the
	* ops vector.
	*/
	inode->i_fop = &btrfs_file_operations;
	inode->i_op = &btrfs_file_inode_operations;
10389 10390 10391 10392 10393 10394
	inode->i_mapping->a_ops = &btrfs_aops;
	BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;

	err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
	if (err)
		goto out_unlock_inode;
10395

C
Chris Mason 已提交
10396
	path = btrfs_alloc_path();
10397 10398
	if (!path) {
		err = -ENOMEM;
10399
		goto out_unlock_inode;
10400
	}
10401
	key.objectid = btrfs_ino(BTRFS_I(inode));
C
Chris Mason 已提交
10402
	key.offset = 0;
10403
	key.type = BTRFS_EXTENT_DATA_KEY;
C
Chris Mason 已提交
10404 10405 10406
	datasize = btrfs_file_extent_calc_inline_size(name_len);
	err = btrfs_insert_empty_item(trans, root, path, &key,
				      datasize);
10407
	if (err) {
10408
		btrfs_free_path(path);
10409
		goto out_unlock_inode;
10410
	}
10411 10412 10413 10414 10415
	leaf = path->nodes[0];
	ei = btrfs_item_ptr(leaf, path->slots[0],
			    struct btrfs_file_extent_item);
	btrfs_set_file_extent_generation(leaf, ei, trans->transid);
	btrfs_set_file_extent_type(leaf, ei,
C
Chris Mason 已提交
10416
				   BTRFS_FILE_EXTENT_INLINE);
C
Chris Mason 已提交
10417 10418 10419 10420 10421
	btrfs_set_file_extent_encryption(leaf, ei, 0);
	btrfs_set_file_extent_compression(leaf, ei, 0);
	btrfs_set_file_extent_other_encoding(leaf, ei, 0);
	btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);

C
Chris Mason 已提交
10422
	ptr = btrfs_file_extent_inline_start(ei);
10423 10424
	write_extent_buffer(leaf, symname, ptr, name_len);
	btrfs_mark_buffer_dirty(leaf);
C
Chris Mason 已提交
10425
	btrfs_free_path(path);
10426

C
Chris Mason 已提交
10427
	inode->i_op = &btrfs_symlink_inode_operations;
10428
	inode_nohighmem(inode);
C
Chris Mason 已提交
10429
	inode->i_mapping->a_ops = &btrfs_symlink_aops;
Y
Yan Zheng 已提交
10430
	inode_set_bytes(inode, name_len);
10431
	btrfs_i_size_write(BTRFS_I(inode), name_len);
10432
	err = btrfs_update_inode(trans, root, inode);
10433 10434 10435 10436 10437 10438
	/*
	 * Last step, add directory indexes for our symlink inode. This is the
	 * last step to avoid extra cleanup of these indexes if an error happens
	 * elsewhere above.
	 */
	if (!err)
10439 10440
		err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
				BTRFS_I(inode), 0, index);
10441
	if (err) {
10442
		drop_inode = 1;
10443 10444 10445
		goto out_unlock_inode;
	}

10446
	d_instantiate_new(dentry, inode);
C
Chris Mason 已提交
10447 10448

out_unlock:
10449
	btrfs_end_transaction(trans);
C
Chris Mason 已提交
10450 10451 10452 10453
	if (drop_inode) {
		inode_dec_link_count(inode);
		iput(inode);
	}
10454
	btrfs_btree_balance_dirty(fs_info);
C
Chris Mason 已提交
10455
	return err;
10456 10457 10458 10459 10460

out_unlock_inode:
	drop_inode = 1;
	unlock_new_inode(inode);
	goto out_unlock;
C
Chris Mason 已提交
10461
}
10462

10463 10464 10465 10466
static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
				       u64 start, u64 num_bytes, u64 min_size,
				       loff_t actual_len, u64 *alloc_hint,
				       struct btrfs_trans_handle *trans)
Y
Yan Zheng 已提交
10467
{
10468
	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
J
Josef Bacik 已提交
10469 10470
	struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
	struct extent_map *em;
Y
Yan Zheng 已提交
10471 10472 10473
	struct btrfs_root *root = BTRFS_I(inode)->root;
	struct btrfs_key ins;
	u64 cur_offset = start;
10474
	u64 i_size;
10475
	u64 cur_bytes;
10476
	u64 last_alloc = (u64)-1;
Y
Yan Zheng 已提交
10477
	int ret = 0;
10478
	bool own_trans = true;
10479
	u64 end = start + num_bytes - 1;
Y
Yan Zheng 已提交
10480

10481 10482
	if (trans)
		own_trans = false;
Y
Yan Zheng 已提交
10483
	while (num_bytes > 0) {
10484 10485 10486 10487 10488 10489
		if (own_trans) {
			trans = btrfs_start_transaction(root, 3);
			if (IS_ERR(trans)) {
				ret = PTR_ERR(trans);
				break;
			}
10490 10491
		}

10492
		cur_bytes = min_t(u64, num_bytes, SZ_256M);
10493
		cur_bytes = max(cur_bytes, min_size);
10494 10495 10496 10497 10498 10499 10500
		/*
		 * If we are severely fragmented we could end up with really
		 * small allocations, so if the allocator is returning small
		 * chunks lets make its job easier by only searching for those
		 * sized chunks.
		 */
		cur_bytes = min(cur_bytes, last_alloc);
10501 10502
		ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
				min_size, 0, *alloc_hint, &ins, 1, 0);
10503
		if (ret) {
10504
			if (own_trans)
10505
				btrfs_end_transaction(trans);
10506
			break;
Y
Yan Zheng 已提交
10507
		}
10508
		btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10509

10510
		last_alloc = ins.offset;
Y
Yan Zheng 已提交
10511 10512 10513
		ret = insert_reserved_file_extent(trans, inode,
						  cur_offset, ins.objectid,
						  ins.offset, ins.offset,
Y
Yan, Zheng 已提交
10514
						  ins.offset, 0, 0, 0,
Y
Yan Zheng 已提交
10515
						  BTRFS_FILE_EXTENT_PREALLOC);
10516
		if (ret) {
10517
			btrfs_free_reserved_extent(fs_info, ins.objectid,
10518
						   ins.offset, 0);
10519
			btrfs_abort_transaction(trans, ret);
10520
			if (own_trans)
10521
				btrfs_end_transaction(trans);
10522 10523
			break;
		}
10524

10525
		btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
C
Chris Mason 已提交
10526
					cur_offset + ins.offset -1, 0);
10527

J
Josef Bacik 已提交
10528 10529 10530 10531 10532 10533 10534 10535 10536 10537 10538 10539
		em = alloc_extent_map();
		if (!em) {
			set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
				&BTRFS_I(inode)->runtime_flags);
			goto next;
		}

		em->start = cur_offset;
		em->orig_start = cur_offset;
		em->len = ins.offset;
		em->block_start = ins.objectid;
		em->block_len = ins.offset;
10540
		em->orig_block_len = ins.offset;
J
Josef Bacik 已提交
10541
		em->ram_bytes = ins.offset;
10542
		em->bdev = fs_info->fs_devices->latest_bdev;
J
Josef Bacik 已提交
10543 10544 10545 10546 10547
		set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
		em->generation = trans->transid;

		while (1) {
			write_lock(&em_tree->lock);
J
Josef Bacik 已提交
10548
			ret = add_extent_mapping(em_tree, em, 1);
J
Josef Bacik 已提交
10549 10550 10551
			write_unlock(&em_tree->lock);
			if (ret != -EEXIST)
				break;
10552
			btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
J
Josef Bacik 已提交
10553 10554 10555 10556 10557
						cur_offset + ins.offset - 1,
						0);
		}
		free_extent_map(em);
next:
Y
Yan Zheng 已提交
10558 10559
		num_bytes -= ins.offset;
		cur_offset += ins.offset;
10560
		*alloc_hint = ins.objectid + ins.offset;
10561

10562
		inode_inc_iversion(inode);
10563
		inode->i_ctime = current_time(inode);
10564
		BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
Y
Yan Zheng 已提交
10565
		if (!(mode & FALLOC_FL_KEEP_SIZE) &&
10566 10567
		    (actual_len > inode->i_size) &&
		    (cur_offset > inode->i_size)) {
10568
			if (cur_offset > actual_len)
10569
				i_size = actual_len;
10570
			else
10571 10572 10573
				i_size = cur_offset;
			i_size_write(inode, i_size);
			btrfs_ordered_update_i_size(inode, i_size, NULL);
10574 10575
		}

Y
Yan Zheng 已提交
10576
		ret = btrfs_update_inode(trans, root, inode);
10577 10578

		if (ret) {
10579
			btrfs_abort_transaction(trans, ret);
10580
			if (own_trans)
10581
				btrfs_end_transaction(trans);
10582 10583
			break;
		}
Y
Yan Zheng 已提交
10584

10585
		if (own_trans)
10586
			btrfs_end_transaction(trans);
10587
	}
10588
	if (cur_offset < end)
10589
		btrfs_free_reserved_data_space(inode, NULL, cur_offset,
10590
			end - cur_offset + 1);
Y
Yan Zheng 已提交
10591 10592 10593
	return ret;
}

10594 10595 10596 10597 10598 10599 10600 10601 10602 10603 10604 10605 10606 10607 10608 10609 10610 10611
int btrfs_prealloc_file_range(struct inode *inode, int mode,
			      u64 start, u64 num_bytes, u64 min_size,
			      loff_t actual_len, u64 *alloc_hint)
{
	return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
					   min_size, actual_len, alloc_hint,
					   NULL);
}

int btrfs_prealloc_file_range_trans(struct inode *inode,
				    struct btrfs_trans_handle *trans, int mode,
				    u64 start, u64 num_bytes, u64 min_size,
				    loff_t actual_len, u64 *alloc_hint)
{
	return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
					   min_size, actual_len, alloc_hint, trans);
}

10612 10613 10614 10615 10616
static int btrfs_set_page_dirty(struct page *page)
{
	return __set_page_dirty_nobuffers(page);
}

10617
static int btrfs_permission(struct inode *inode, int mask)
Y
Yan 已提交
10618
{
L
Li Zefan 已提交
10619
	struct btrfs_root *root = BTRFS_I(inode)->root;
10620
	umode_t mode = inode->i_mode;
L
Li Zefan 已提交
10621

10622 10623 10624 10625 10626 10627 10628
	if (mask & MAY_WRITE &&
	    (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
		if (btrfs_root_readonly(root))
			return -EROFS;
		if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
			return -EACCES;
	}
10629
	return generic_permission(inode, mask);
Y
Yan 已提交
10630
}
C
Chris Mason 已提交
10631

10632 10633
static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
{
10634
	struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10635 10636 10637 10638 10639 10640 10641 10642 10643 10644 10645 10646 10647 10648 10649 10650 10651 10652 10653
	struct btrfs_trans_handle *trans;
	struct btrfs_root *root = BTRFS_I(dir)->root;
	struct inode *inode = NULL;
	u64 objectid;
	u64 index;
	int ret = 0;

	/*
	 * 5 units required for adding orphan entry
	 */
	trans = btrfs_start_transaction(root, 5);
	if (IS_ERR(trans))
		return PTR_ERR(trans);

	ret = btrfs_find_free_ino(root, &objectid);
	if (ret)
		goto out;

	inode = btrfs_new_inode(trans, root, dir, NULL, 0,
10654
			btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
10655 10656 10657 10658 10659 10660 10661 10662 10663 10664 10665 10666
	if (IS_ERR(inode)) {
		ret = PTR_ERR(inode);
		inode = NULL;
		goto out;
	}

	inode->i_fop = &btrfs_file_operations;
	inode->i_op = &btrfs_file_inode_operations;

	inode->i_mapping->a_ops = &btrfs_aops;
	BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;

10667 10668 10669 10670 10671 10672 10673
	ret = btrfs_init_inode_security(trans, inode, dir, NULL);
	if (ret)
		goto out_inode;

	ret = btrfs_update_inode(trans, root, inode);
	if (ret)
		goto out_inode;
10674
	ret = btrfs_orphan_add(trans, BTRFS_I(inode));
10675
	if (ret)
10676
		goto out_inode;
10677

10678 10679 10680 10681 10682 10683 10684 10685
	/*
	 * We set number of links to 0 in btrfs_new_inode(), and here we set
	 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
	 * through:
	 *
	 *    d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
	 */
	set_nlink(inode, 1);
10686
	unlock_new_inode(inode);
10687 10688 10689 10690
	d_tmpfile(dentry, inode);
	mark_inode_dirty(inode);

out:
10691
	btrfs_end_transaction(trans);
10692 10693
	if (ret)
		iput(inode);
10694
	btrfs_btree_balance_dirty(fs_info);
10695
	return ret;
10696 10697 10698 10699 10700

out_inode:
	unlock_new_inode(inode);
	goto out;

10701 10702
}

10703
__attribute__((const))
L
Liu Bo 已提交
10704
static int btrfs_readpage_io_failed_hook(struct page *page, int failed_mirror)
10705
{
L
Liu Bo 已提交
10706
	return -EAGAIN;
10707 10708
}

10709 10710 10711 10712 10713 10714 10715 10716 10717 10718 10719 10720 10721 10722 10723 10724 10725 10726 10727 10728 10729 10730 10731 10732 10733 10734 10735 10736 10737 10738 10739 10740 10741 10742 10743 10744
static struct btrfs_fs_info *iotree_fs_info(void *private_data)
{
	struct inode *inode = private_data;
	return btrfs_sb(inode->i_sb);
}

static void btrfs_check_extent_io_range(void *private_data, const char *caller,
					u64 start, u64 end)
{
	struct inode *inode = private_data;
	u64 isize;

	isize = i_size_read(inode);
	if (end >= PAGE_SIZE && (end % 2) == 0 && end != isize - 1) {
		btrfs_debug_rl(BTRFS_I(inode)->root->fs_info,
		    "%s: ino %llu isize %llu odd range [%llu,%llu]",
			caller, btrfs_ino(BTRFS_I(inode)), isize, start, end);
	}
}

void btrfs_set_range_writeback(void *private_data, u64 start, u64 end)
{
	struct inode *inode = private_data;
	unsigned long index = start >> PAGE_SHIFT;
	unsigned long end_index = end >> PAGE_SHIFT;
	struct page *page;

	while (index <= end_index) {
		page = find_get_page(inode->i_mapping, index);
		ASSERT(page); /* Pages should be in the extent_io_tree */
		set_page_writeback(page);
		put_page(page);
		index++;
	}
}

10745
static const struct inode_operations btrfs_dir_inode_operations = {
10746
	.getattr	= btrfs_getattr,
C
Chris Mason 已提交
10747 10748 10749 10750 10751 10752
	.lookup		= btrfs_lookup,
	.create		= btrfs_create,
	.unlink		= btrfs_unlink,
	.link		= btrfs_link,
	.mkdir		= btrfs_mkdir,
	.rmdir		= btrfs_rmdir,
10753
	.rename		= btrfs_rename2,
C
Chris Mason 已提交
10754 10755
	.symlink	= btrfs_symlink,
	.setattr	= btrfs_setattr,
J
Josef Bacik 已提交
10756
	.mknod		= btrfs_mknod,
J
Josef Bacik 已提交
10757
	.listxattr	= btrfs_listxattr,
Y
Yan 已提交
10758
	.permission	= btrfs_permission,
10759
	.get_acl	= btrfs_get_acl,
10760
	.set_acl	= btrfs_set_acl,
10761
	.update_time	= btrfs_update_time,
10762
	.tmpfile        = btrfs_tmpfile,
C
Chris Mason 已提交
10763
};
10764
static const struct inode_operations btrfs_dir_ro_inode_operations = {
C
Chris Mason 已提交
10765
	.lookup		= btrfs_lookup,
Y
Yan 已提交
10766
	.permission	= btrfs_permission,
10767
	.update_time	= btrfs_update_time,
C
Chris Mason 已提交
10768
};
10769

10770
static const struct file_operations btrfs_dir_file_operations = {
C
Chris Mason 已提交
10771 10772
	.llseek		= generic_file_llseek,
	.read		= generic_read_dir,
10773
	.iterate_shared	= btrfs_real_readdir,
10774
	.open		= btrfs_opendir,
C
Christoph Hellwig 已提交
10775
	.unlocked_ioctl	= btrfs_ioctl,
C
Chris Mason 已提交
10776
#ifdef CONFIG_COMPAT
10777
	.compat_ioctl	= btrfs_compat_ioctl,
C
Chris Mason 已提交
10778
#endif
S
Sage Weil 已提交
10779
	.release        = btrfs_release_file,
10780
	.fsync		= btrfs_sync_file,
C
Chris Mason 已提交
10781 10782
};

10783
static const struct extent_io_ops btrfs_extent_io_ops = {
10784
	/* mandatory callbacks */
10785
	.submit_bio_hook = btrfs_submit_bio_hook,
10786
	.readpage_end_io_hook = btrfs_readpage_end_io_hook,
10787
	.merge_bio_hook = btrfs_merge_bio_hook,
L
Liu Bo 已提交
10788
	.readpage_io_failed_hook = btrfs_readpage_io_failed_hook,
10789 10790
	.tree_fs_info = iotree_fs_info,
	.set_range_writeback = btrfs_set_range_writeback,
10791 10792 10793

	/* optional callbacks */
	.fill_delalloc = run_delalloc_range,
10794
	.writepage_end_io_hook = btrfs_writepage_end_io_hook,
10795
	.writepage_start_hook = btrfs_writepage_start_hook,
C
Chris Mason 已提交
10796 10797
	.set_bit_hook = btrfs_set_bit_hook,
	.clear_bit_hook = btrfs_clear_bit_hook,
J
Josef Bacik 已提交
10798 10799
	.merge_extent_hook = btrfs_merge_extent_hook,
	.split_extent_hook = btrfs_split_extent_hook,
10800
	.check_extent_io_range = btrfs_check_extent_io_range,
10801 10802
};

10803 10804 10805 10806 10807 10808 10809 10810 10811 10812 10813 10814
/*
 * btrfs doesn't support the bmap operation because swapfiles
 * use bmap to make a mapping of extents in the file.  They assume
 * these extents won't change over the life of the file and they
 * use the bmap result to do IO directly to the drive.
 *
 * the btrfs bmap call would return logical addresses that aren't
 * suitable for IO and they also will change frequently as COW
 * operations happen.  So, swapfile + btrfs == corruption.
 *
 * For now we're avoiding this by dropping bmap.
 */
10815
static const struct address_space_operations btrfs_aops = {
C
Chris Mason 已提交
10816 10817
	.readpage	= btrfs_readpage,
	.writepage	= btrfs_writepage,
C
Chris Mason 已提交
10818
	.writepages	= btrfs_writepages,
C
Chris Mason 已提交
10819
	.readpages	= btrfs_readpages,
10820
	.direct_IO	= btrfs_direct_IO,
10821 10822
	.invalidatepage = btrfs_invalidatepage,
	.releasepage	= btrfs_releasepage,
10823
	.set_page_dirty	= btrfs_set_page_dirty,
10824
	.error_remove_page = generic_error_remove_page,
C
Chris Mason 已提交
10825 10826
};

10827
static const struct address_space_operations btrfs_symlink_aops = {
C
Chris Mason 已提交
10828 10829
	.readpage	= btrfs_readpage,
	.writepage	= btrfs_writepage,
C
Chris Mason 已提交
10830 10831
	.invalidatepage = btrfs_invalidatepage,
	.releasepage	= btrfs_releasepage,
C
Chris Mason 已提交
10832 10833
};

10834
static const struct inode_operations btrfs_file_inode_operations = {
C
Chris Mason 已提交
10835 10836
	.getattr	= btrfs_getattr,
	.setattr	= btrfs_setattr,
J
Josef Bacik 已提交
10837
	.listxattr      = btrfs_listxattr,
Y
Yan 已提交
10838
	.permission	= btrfs_permission,
Y
Yehuda Sadeh 已提交
10839
	.fiemap		= btrfs_fiemap,
10840
	.get_acl	= btrfs_get_acl,
10841
	.set_acl	= btrfs_set_acl,
10842
	.update_time	= btrfs_update_time,
C
Chris Mason 已提交
10843
};
10844
static const struct inode_operations btrfs_special_inode_operations = {
J
Josef Bacik 已提交
10845 10846
	.getattr	= btrfs_getattr,
	.setattr	= btrfs_setattr,
Y
Yan 已提交
10847
	.permission	= btrfs_permission,
J
Josef Bacik 已提交
10848
	.listxattr	= btrfs_listxattr,
10849
	.get_acl	= btrfs_get_acl,
10850
	.set_acl	= btrfs_set_acl,
10851
	.update_time	= btrfs_update_time,
J
Josef Bacik 已提交
10852
};
10853
static const struct inode_operations btrfs_symlink_inode_operations = {
10854
	.get_link	= page_get_link,
10855
	.getattr	= btrfs_getattr,
10856
	.setattr	= btrfs_setattr,
Y
Yan 已提交
10857
	.permission	= btrfs_permission,
J
Jim Owens 已提交
10858
	.listxattr	= btrfs_listxattr,
10859
	.update_time	= btrfs_update_time,
C
Chris Mason 已提交
10860
};
10861

10862
const struct dentry_operations btrfs_dentry_operations = {
10863
	.d_delete	= btrfs_dentry_delete,
10864
	.d_release	= btrfs_dentry_release,
10865
};