inode.c 162 KB
Newer Older
Chris Mason's avatar
Chris Mason committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/*
 * Copyright (C) 2007 Oracle.  All rights reserved.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public
 * License v2 as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this program; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 021110-1307, USA.
 */

19
#include <linux/kernel.h>
20
#include <linux/bio.h>
Chris Mason's avatar
Chris Mason committed
21
#include <linux/buffer_head.h>
Sage Weil's avatar
Sage Weil committed
22
#include <linux/file.h>
Chris Mason's avatar
Chris Mason committed
23
24
25
26
27
28
29
30
31
32
33
34
#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/statfs.h>
#include <linux/compat.h>
Chris Mason's avatar
Chris Mason committed
35
#include <linux/bit_spinlock.h>
Josef Bacik's avatar
Josef Bacik committed
36
#include <linux/xattr.h>
Josef Bacik's avatar
Josef Bacik committed
37
#include <linux/posix_acl.h>
Yan Zheng's avatar
Yan Zheng committed
38
#include <linux/falloc.h>
Chris Mason's avatar
Chris Mason committed
39
#include "compat.h"
Chris Mason's avatar
Chris Mason committed
40
41
42
43
44
45
#include "ctree.h"
#include "disk-io.h"
#include "transaction.h"
#include "btrfs_inode.h"
#include "ioctl.h"
#include "print-tree.h"
46
#include "volumes.h"
47
#include "ordered-data.h"
48
#include "xattr.h"
49
#include "tree-log.h"
50
#include "compression.h"
51
#include "locking.h"
Chris Mason's avatar
Chris Mason committed
52
53
54
55
56
57

struct btrfs_iget_args {
	u64 ino;
	struct btrfs_root *root;
};

58
59
60
61
62
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;
63
64
static const struct address_space_operations btrfs_aops;
static const struct address_space_operations btrfs_symlink_aops;
65
static const struct file_operations btrfs_dir_file_operations;
66
static struct extent_io_ops btrfs_extent_io_ops;
Chris Mason's avatar
Chris Mason committed
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83

static struct kmem_cache *btrfs_inode_cachep;
struct kmem_cache *btrfs_trans_handle_cachep;
struct kmem_cache *btrfs_transaction_cachep;
struct kmem_cache *btrfs_path_cachep;

#define S_SHIFT 12
static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
	[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,
};

84
static void btrfs_truncate(struct inode *inode);
85
static int btrfs_finish_ordered_io(struct inode *inode, u64 start, u64 end);
86
87
88
89
static noinline int cow_file_range(struct inode *inode,
				   struct page *locked_page,
				   u64 start, u64 end, int *page_started,
				   unsigned long *nr_written, int unlock);
90

91
92
static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
				     struct inode *inode,  struct inode *dir)
Jim Owens's avatar
Jim Owens committed
93
94
95
{
	int err;

96
	err = btrfs_init_acl(trans, inode, dir);
Jim Owens's avatar
Jim Owens committed
97
	if (!err)
98
		err = btrfs_xattr_security_init(trans, inode, dir);
Jim Owens's avatar
Jim Owens committed
99
100
101
	return err;
}

102
103
104
105
106
/*
 * 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
 */
107
static noinline int insert_inline_extent(struct btrfs_trans_handle *trans,
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
				struct btrfs_root *root, struct inode *inode,
				u64 start, size_t size, size_t compressed_size,
				struct page **compressed_pages)
{
	struct btrfs_key key;
	struct btrfs_path *path;
	struct extent_buffer *leaf;
	struct page *page = NULL;
	char *kaddr;
	unsigned long ptr;
	struct btrfs_file_extent_item *ei;
	int err = 0;
	int ret;
	size_t cur_size = size;
	size_t datasize;
	unsigned long offset;
	int use_compress = 0;

	if (compressed_size && compressed_pages) {
		use_compress = 1;
		cur_size = compressed_size;
	}

131
132
	path = btrfs_alloc_path();
	if (!path)
133
134
		return -ENOMEM;

135
	path->leave_spinning = 1;
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
	btrfs_set_trans_block_group(trans, inode);

	key.objectid = inode->i_ino;
	key.offset = start;
	btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
	datasize = btrfs_file_extent_calc_inline_size(cur_size);

	inode_add_bytes(inode, size);
	ret = btrfs_insert_empty_item(trans, root, path, &key,
				      datasize);
	BUG_ON(ret);
	if (ret) {
		err = ret;
		goto fail;
	}
	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);

	if (use_compress) {
		struct page *cpage;
		int i = 0;
164
		while (compressed_size > 0) {
165
			cpage = compressed_pages[i];
166
			cur_size = min_t(unsigned long, compressed_size,
167
168
				       PAGE_CACHE_SIZE);

169
			kaddr = kmap_atomic(cpage, KM_USER0);
170
			write_extent_buffer(leaf, kaddr, ptr, cur_size);
171
			kunmap_atomic(kaddr, KM_USER0);
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191

			i++;
			ptr += cur_size;
			compressed_size -= cur_size;
		}
		btrfs_set_file_extent_compression(leaf, ei,
						  BTRFS_COMPRESS_ZLIB);
	} else {
		page = find_get_page(inode->i_mapping,
				     start >> PAGE_CACHE_SHIFT);
		btrfs_set_file_extent_compression(leaf, ei, 0);
		kaddr = kmap_atomic(page, KM_USER0);
		offset = start & (PAGE_CACHE_SIZE - 1);
		write_extent_buffer(leaf, kaddr + offset, ptr, size);
		kunmap_atomic(kaddr, KM_USER0);
		page_cache_release(page);
	}
	btrfs_mark_buffer_dirty(leaf);
	btrfs_free_path(path);

192
193
194
195
196
197
198
199
200
	/*
	 * 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.
	 */
201
202
	BTRFS_I(inode)->disk_i_size = inode->i_size;
	btrfs_update_inode(trans, root, inode);
203

204
205
206
207
208
209
210
211
212
213
214
215
	return 0;
fail:
	btrfs_free_path(path);
	return err;
}


/*
 * 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.
 */
216
static noinline int cow_file_range_inline(struct btrfs_trans_handle *trans,
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
				 struct btrfs_root *root,
				 struct inode *inode, u64 start, u64 end,
				 size_t compressed_size,
				 struct page **compressed_pages)
{
	u64 isize = i_size_read(inode);
	u64 actual_end = min(end + 1, isize);
	u64 inline_len = actual_end - start;
	u64 aligned_end = (end + root->sectorsize - 1) &
			~((u64)root->sectorsize - 1);
	u64 hint_byte;
	u64 data_len = inline_len;
	int ret;

	if (compressed_size)
		data_len = compressed_size;

	if (start > 0 ||
Chris Mason's avatar
Chris Mason committed
235
	    actual_end >= PAGE_CACHE_SIZE ||
236
237
238
239
240
241
242
243
	    data_len >= BTRFS_MAX_INLINE_DATA_SIZE(root) ||
	    (!compressed_size &&
	    (actual_end & (root->sectorsize - 1)) == 0) ||
	    end + 1 < isize ||
	    data_len > root->fs_info->max_inline) {
		return 1;
	}

Yan, Zheng's avatar
Yan, Zheng committed
244
	ret = btrfs_drop_extents(trans, inode, start, aligned_end,
245
				 &hint_byte, 1);
246
247
248
249
250
251
252
253
	BUG_ON(ret);

	if (isize > actual_end)
		inline_len = min_t(u64, isize, actual_end);
	ret = insert_inline_extent(trans, root, inode, start,
				   inline_len, compressed_size,
				   compressed_pages);
	BUG_ON(ret);
254
	btrfs_drop_extent_cache(inode, start, aligned_end - 1, 0);
255
256
257
	return 0;
}

258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
struct async_extent {
	u64 start;
	u64 ram_size;
	u64 compressed_size;
	struct page **pages;
	unsigned long nr_pages;
	struct list_head list;
};

struct async_cow {
	struct inode *inode;
	struct btrfs_root *root;
	struct page *locked_page;
	u64 start;
	u64 end;
	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,
				     unsigned long nr_pages)
{
	struct async_extent *async_extent;

	async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
	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;
	list_add_tail(&async_extent->list, &cow->extents);
	return 0;
}

Chris Mason's avatar
Chris Mason committed
295
/*
296
297
298
 * 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).
299
 *
300
301
302
303
304
 * 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.
305
 *
306
307
308
309
 * 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
 * are written in the same order that pdflush sent them down.
Chris Mason's avatar
Chris Mason committed
310
 */
311
312
313
314
315
static noinline int compress_file_range(struct inode *inode,
					struct page *locked_page,
					u64 start, u64 end,
					struct async_cow *async_cow,
					int *num_added)
316
317
318
{
	struct btrfs_root *root = BTRFS_I(inode)->root;
	struct btrfs_trans_handle *trans;
319
	u64 num_bytes;
320
321
	u64 orig_start;
	u64 disk_num_bytes;
322
	u64 blocksize = root->sectorsize;
323
	u64 actual_end;
324
	u64 isize = i_size_read(inode);
325
	int ret = 0;
326
327
328
329
330
331
	struct page **pages = NULL;
	unsigned long nr_pages;
	unsigned long nr_pages_ret = 0;
	unsigned long total_compressed = 0;
	unsigned long total_in = 0;
	unsigned long max_compressed = 128 * 1024;
332
	unsigned long max_uncompressed = 128 * 1024;
333
334
	int i;
	int will_compress;
335

336
337
	orig_start = start;

338
	actual_end = min_t(u64, isize, end + 1);
339
340
341
342
again:
	will_compress = 0;
	nr_pages = (end >> PAGE_CACHE_SHIFT) - (start >> PAGE_CACHE_SHIFT) + 1;
	nr_pages = min(nr_pages, (128 * 1024UL) / PAGE_CACHE_SIZE);
343

344
345
346
347
348
349
350
351
352
353
354
355
356
	/*
	 * 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;

357
358
359
360
	total_compressed = actual_end - start;

	/* we want to make sure that amount of ram required to uncompress
	 * an extent is reasonable, so we limit the total size in ram
361
362
363
364
365
366
367
	 * of a compressed extent to 128k.  This is a crucial number
	 * because it also controls how easily we can spread reads across
	 * cpus for decompression.
	 *
	 * We also want to make sure the amount of IO required to do
	 * a random read is reasonably small, so we limit the size of
	 * a compressed extent to 128k.
368
369
	 */
	total_compressed = min(total_compressed, max_uncompressed);
370
	num_bytes = (end - start + blocksize) & ~(blocksize - 1);
371
	num_bytes = max(blocksize,  num_bytes);
372
373
374
	disk_num_bytes = num_bytes;
	total_in = 0;
	ret = 0;
375

376
377
378
379
	/*
	 * 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.
380
	 */
381
	if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS) &&
382
383
	    (btrfs_test_opt(root, COMPRESS) ||
	     (BTRFS_I(inode)->force_compress))) {
384
		WARN_ON(pages);
385
		pages = kzalloc(sizeof(struct page *) * nr_pages, GFP_NOFS);
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412

		ret = btrfs_zlib_compress_pages(inode->i_mapping, start,
						total_compressed, pages,
						nr_pages, &nr_pages_ret,
						&total_in,
						&total_compressed,
						max_compressed);

		if (!ret) {
			unsigned long offset = total_compressed &
				(PAGE_CACHE_SIZE - 1);
			struct page *page = pages[nr_pages_ret - 1];
			char *kaddr;

			/* zero the tail end of the last page, we might be
			 * sending it down to disk
			 */
			if (offset) {
				kaddr = kmap_atomic(page, KM_USER0);
				memset(kaddr + offset, 0,
				       PAGE_CACHE_SIZE - offset);
				kunmap_atomic(kaddr, KM_USER0);
			}
			will_compress = 1;
		}
	}
	if (start == 0) {
413
414
415
416
		trans = btrfs_join_transaction(root, 1);
		BUG_ON(!trans);
		btrfs_set_trans_block_group(trans, inode);

417
		/* lets try to make an inline extent */
418
		if (ret || total_in < (actual_end - start)) {
419
			/* we didn't compress the entire range, try
420
			 * to make an uncompressed inline extent.
421
422
423
424
			 */
			ret = cow_file_range_inline(trans, root, inode,
						    start, end, 0, NULL);
		} else {
425
			/* try making a compressed inline extent */
426
427
428
429
430
			ret = cow_file_range_inline(trans, root, inode,
						    start, end,
						    total_compressed, pages);
		}
		if (ret == 0) {
431
432
433
434
435
			/*
			 * inline extent creation worked, we don't need
			 * to create any more async work items.  Unlock
			 * and free up our temp pages.
			 */
436
			extent_clear_unlock_delalloc(inode,
437
438
439
			     &BTRFS_I(inode)->io_tree,
			     start, end, NULL,
			     EXTENT_CLEAR_UNLOCK_PAGE | EXTENT_CLEAR_DIRTY |
440
			     EXTENT_CLEAR_DELALLOC |
441
			     EXTENT_CLEAR_ACCOUNTING |
442
			     EXTENT_SET_WRITEBACK | EXTENT_END_WRITEBACK);
443
444

			btrfs_end_transaction(trans, root);
445
446
			goto free_pages_out;
		}
447
		btrfs_end_transaction(trans, root);
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
	}

	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
		 */
		total_compressed = (total_compressed + blocksize - 1) &
			~(blocksize - 1);

		/*
		 * one last check to make sure the compression is really a
		 * win, compare the page count read with the blocks on disk
		 */
		total_in = (total_in + PAGE_CACHE_SIZE - 1) &
			~(PAGE_CACHE_SIZE - 1);
		if (total_compressed >= total_in) {
			will_compress = 0;
		} else {
			disk_num_bytes = total_compressed;
			num_bytes = total_in;
		}
	}
	if (!will_compress && pages) {
		/*
		 * the compression code ran but failed to make things smaller,
		 * free any pages it allocated and our page pointer array
		 */
		for (i = 0; i < nr_pages_ret; i++) {
Chris Mason's avatar
Chris Mason committed
478
			WARN_ON(pages[i]->mapping);
479
480
481
482
483
484
485
486
			page_cache_release(pages[i]);
		}
		kfree(pages);
		pages = NULL;
		total_compressed = 0;
		nr_pages_ret = 0;

		/* flag the file so we don't compress in the future */
487
488
		if (!btrfs_test_opt(root, FORCE_COMPRESS) &&
		    !(BTRFS_I(inode)->force_compress)) {
489
			BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
490
		}
491
	}
492
493
	if (will_compress) {
		*num_added += 1;
494

495
496
497
498
499
500
		/* the async work queues will take care of doing actual
		 * allocation on disk for these compressed pages,
		 * and will submit them to the elevator.
		 */
		add_async_extent(async_cow, start, num_bytes,
				 total_compressed, pages, nr_pages_ret);
501

502
		if (start + num_bytes < end && start + num_bytes < actual_end) {
503
504
505
506
507
508
			start += num_bytes;
			pages = NULL;
			cond_resched();
			goto again;
		}
	} else {
509
cleanup_and_bail_uncompressed:
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
		/*
		 * 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 */
		}
		add_async_extent(async_cow, start, end - start + 1, 0, NULL, 0);
		*num_added += 1;
	}
525

526
527
528
529
530
531
532
533
out:
	return 0;

free_pages_out:
	for (i = 0; i < nr_pages_ret; i++) {
		WARN_ON(pages[i]->mapping);
		page_cache_release(pages[i]);
	}
534
	kfree(pages);
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555

	goto out;
}

/*
 * 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.
 */
static noinline int submit_compressed_extents(struct inode *inode,
					      struct async_cow *async_cow)
{
	struct async_extent *async_extent;
	u64 alloc_hint = 0;
	struct btrfs_trans_handle *trans;
	struct btrfs_key ins;
	struct extent_map *em;
	struct btrfs_root *root = BTRFS_I(inode)->root;
	struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
	struct extent_io_tree *io_tree;
556
	int ret = 0;
557
558
559
560
561

	if (list_empty(&async_cow->extents))
		return 0;


562
	while (!list_empty(&async_cow->extents)) {
563
564
565
		async_extent = list_entry(async_cow->extents.next,
					  struct async_extent, list);
		list_del(&async_extent->list);
566

567
568
		io_tree = &BTRFS_I(inode)->io_tree;

569
retry:
570
571
572
573
574
575
		/* 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,
576
577
				    async_extent->start +
				    async_extent->ram_size - 1, GFP_NOFS);
578
579

			/* allocate blocks */
580
581
582
583
584
			ret = cow_file_range(inode, async_cow->locked_page,
					     async_extent->start,
					     async_extent->start +
					     async_extent->ram_size - 1,
					     &page_started, &nr_written, 0);
585
586
587
588
589
590
591

			/*
			 * 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.
			 */
592
			if (!page_started && !ret)
593
594
				extent_write_locked_range(io_tree,
						  inode, async_extent->start,
595
						  async_extent->start +
596
597
598
599
600
601
602
603
604
605
606
607
						  async_extent->ram_size - 1,
						  btrfs_get_extent,
						  WB_SYNC_ALL);
			kfree(async_extent);
			cond_resched();
			continue;
		}

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

608
		trans = btrfs_join_transaction(root, 1);
609
610
611
612
613
		ret = btrfs_reserve_extent(trans, root,
					   async_extent->compressed_size,
					   async_extent->compressed_size,
					   0, alloc_hint,
					   (u64)-1, &ins, 1);
614
615
		btrfs_end_transaction(trans, root);

616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
		if (ret) {
			int i;
			for (i = 0; i < async_extent->nr_pages; i++) {
				WARN_ON(async_extent->pages[i]->mapping);
				page_cache_release(async_extent->pages[i]);
			}
			kfree(async_extent->pages);
			async_extent->nr_pages = 0;
			async_extent->pages = NULL;
			unlock_extent(io_tree, async_extent->start,
				      async_extent->start +
				      async_extent->ram_size - 1, GFP_NOFS);
			goto retry;
		}

631
632
633
634
635
636
637
638
		/*
		 * here we're doing allocation and writeback of the
		 * compressed pages
		 */
		btrfs_drop_extent_cache(inode, async_extent->start,
					async_extent->start +
					async_extent->ram_size - 1, 0);

639
640
641
		em = alloc_extent_map(GFP_NOFS);
		em->start = async_extent->start;
		em->len = async_extent->ram_size;
642
		em->orig_start = em->start;
643

644
645
646
647
648
649
		em->block_start = ins.objectid;
		em->block_len = ins.offset;
		em->bdev = root->fs_info->fs_devices->latest_bdev;
		set_bit(EXTENT_FLAG_PINNED, &em->flags);
		set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);

650
		while (1) {
651
			write_lock(&em_tree->lock);
652
			ret = add_extent_mapping(em_tree, em);
653
			write_unlock(&em_tree->lock);
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
			if (ret != -EEXIST) {
				free_extent_map(em);
				break;
			}
			btrfs_drop_extent_cache(inode, async_extent->start,
						async_extent->start +
						async_extent->ram_size - 1, 0);
		}

		ret = btrfs_add_ordered_extent(inode, async_extent->start,
					       ins.objectid,
					       async_extent->ram_size,
					       ins.offset,
					       BTRFS_ORDERED_COMPRESSED);
		BUG_ON(ret);

		/*
		 * clear dirty, set writeback and unlock the pages.
		 */
		extent_clear_unlock_delalloc(inode,
674
675
676
677
678
679
				&BTRFS_I(inode)->io_tree,
				async_extent->start,
				async_extent->start +
				async_extent->ram_size - 1,
				NULL, EXTENT_CLEAR_UNLOCK_PAGE |
				EXTENT_CLEAR_UNLOCK |
680
				EXTENT_CLEAR_DELALLOC |
681
				EXTENT_CLEAR_DIRTY | EXTENT_SET_WRITEBACK);
682
683

		ret = btrfs_submit_compressed_write(inode,
684
685
686
687
688
				    async_extent->start,
				    async_extent->ram_size,
				    ins.objectid,
				    ins.offset, async_extent->pages,
				    async_extent->nr_pages);
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726

		BUG_ON(ret);
		alloc_hint = ins.objectid + ins.offset;
		kfree(async_extent);
		cond_resched();
	}

	return 0;
}

/*
 * 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.
 */
static noinline int cow_file_range(struct inode *inode,
				   struct page *locked_page,
				   u64 start, u64 end, int *page_started,
				   unsigned long *nr_written,
				   int unlock)
{
	struct btrfs_root *root = BTRFS_I(inode)->root;
	struct btrfs_trans_handle *trans;
	u64 alloc_hint = 0;
	u64 num_bytes;
	unsigned long ram_size;
	u64 disk_num_bytes;
	u64 cur_alloc_size;
	u64 blocksize = root->sectorsize;
	u64 actual_end;
727
	u64 isize = i_size_read(inode);
728
729
730
731
732
733
734
735
736
	struct btrfs_key ins;
	struct extent_map *em;
	struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
	int ret = 0;

	trans = btrfs_join_transaction(root, 1);
	BUG_ON(!trans);
	btrfs_set_trans_block_group(trans, inode);

737
	actual_end = min_t(u64, isize, end + 1);
738
739
740
741
742
743
744
745
746
747
748
749

	num_bytes = (end - start + blocksize) & ~(blocksize - 1);
	num_bytes = max(blocksize,  num_bytes);
	disk_num_bytes = num_bytes;
	ret = 0;

	if (start == 0) {
		/* lets try to make an inline extent */
		ret = cow_file_range_inline(trans, root, inode,
					    start, end, 0, NULL);
		if (ret == 0) {
			extent_clear_unlock_delalloc(inode,
750
751
752
753
754
				     &BTRFS_I(inode)->io_tree,
				     start, end, NULL,
				     EXTENT_CLEAR_UNLOCK_PAGE |
				     EXTENT_CLEAR_UNLOCK |
				     EXTENT_CLEAR_DELALLOC |
755
				     EXTENT_CLEAR_ACCOUNTING |
756
757
758
				     EXTENT_CLEAR_DIRTY |
				     EXTENT_SET_WRITEBACK |
				     EXTENT_END_WRITEBACK);
759

760
761
762
763
764
765
766
767
768
769
770
			*nr_written = *nr_written +
			     (end - start + PAGE_CACHE_SIZE) / PAGE_CACHE_SIZE;
			*page_started = 1;
			ret = 0;
			goto out;
		}
	}

	BUG_ON(disk_num_bytes >
	       btrfs_super_total_bytes(&root->fs_info->super_copy));

771
772
773
774
775

	read_lock(&BTRFS_I(inode)->extent_tree.lock);
	em = search_extent_mapping(&BTRFS_I(inode)->extent_tree,
				   start, num_bytes);
	if (em) {
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
		/*
		 * 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);
		}
792
793
	}
	read_unlock(&BTRFS_I(inode)->extent_tree.lock);
794
795
	btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);

796
	while (disk_num_bytes > 0) {
797
798
		unsigned long op;

799
		cur_alloc_size = min(disk_num_bytes, root->fs_info->max_extent);
800
		ret = btrfs_reserve_extent(trans, root, cur_alloc_size,
801
					   root->sectorsize, 0, alloc_hint,
802
					   (u64)-1, &ins, 1);
803
804
		BUG_ON(ret);

805
806
		em = alloc_extent_map(GFP_NOFS);
		em->start = start;
807
		em->orig_start = em->start;
808
809
		ram_size = ins.offset;
		em->len = ins.offset;
810

811
		em->block_start = ins.objectid;
812
		em->block_len = ins.offset;
813
		em->bdev = root->fs_info->fs_devices->latest_bdev;
814
		set_bit(EXTENT_FLAG_PINNED, &em->flags);
815

816
		while (1) {
817
			write_lock(&em_tree->lock);
818
			ret = add_extent_mapping(em_tree, em);
819
			write_unlock(&em_tree->lock);
820
821
822
823
824
			if (ret != -EEXIST) {
				free_extent_map(em);
				break;
			}
			btrfs_drop_extent_cache(inode, start,
825
						start + ram_size - 1, 0);
826
827
		}

828
		cur_alloc_size = ins.offset;
829
		ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
830
					       ram_size, cur_alloc_size, 0);
831
		BUG_ON(ret);
832

833
834
835
836
837
838
839
		if (root->root_key.objectid ==
		    BTRFS_DATA_RELOC_TREE_OBJECTID) {
			ret = btrfs_reloc_clone_csums(inode, start,
						      cur_alloc_size);
			BUG_ON(ret);
		}

840
		if (disk_num_bytes < cur_alloc_size)
841
			break;
842

843
844
845
		/* 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
846
847
848
		 *
		 * Do set the Private2 bit so we know this page was properly
		 * setup for writepage
849
		 */
850
851
852
853
		op = unlock ? EXTENT_CLEAR_UNLOCK_PAGE : 0;
		op |= EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
			EXTENT_SET_PRIVATE2;

854
855
		extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
					     start, start + ram_size - 1,
856
					     locked_page, op);
857
		disk_num_bytes -= cur_alloc_size;
858
859
860
		num_bytes -= cur_alloc_size;
		alloc_hint = ins.objectid + ins.offset;
		start += cur_alloc_size;
861
862
	}
out:
863
	ret = 0;
864
	btrfs_end_transaction(trans, root);
865

866
	return ret;
867
}
868

869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
/*
 * 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);
	if (num_added == 0)
		async_cow->inode = NULL;
}

/*
 * work queue call back to submit previously compressed pages
 */
static noinline void async_cow_submit(struct btrfs_work *work)
{
	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;
	nr_pages = (async_cow->end - async_cow->start + PAGE_CACHE_SIZE) >>
		PAGE_CACHE_SHIFT;

	atomic_sub(nr_pages, &root->fs_info->async_delalloc_pages);

	if (atomic_read(&root->fs_info->async_delalloc_pages) <
	    5 * 1042 * 1024 &&
	    waitqueue_active(&root->fs_info->async_submit_wait))
		wake_up(&root->fs_info->async_submit_wait);

907
	if (async_cow->inode)
908
909
		submit_compressed_extents(async_cow->inode, async_cow);
}
910

911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
static noinline void async_cow_free(struct btrfs_work *work)
{
	struct async_cow *async_cow;
	async_cow = container_of(work, struct async_cow, work);
	kfree(async_cow);
}

static int cow_file_range_async(struct inode *inode, struct page *locked_page,
				u64 start, u64 end, int *page_started,
				unsigned long *nr_written)
{
	struct async_cow *async_cow;
	struct btrfs_root *root = BTRFS_I(inode)->root;
	unsigned long nr_pages;
	u64 cur_end;
	int limit = 10 * 1024 * 1042;

928
929
	clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
			 1, 0, NULL, GFP_NOFS);
930
	while (start < end) {
931
932
933
934
935
936
		async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
		async_cow->inode = inode;
		async_cow->root = root;
		async_cow->locked_page = locked_page;
		async_cow->start = start;

937
		if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
			cur_end = end;
		else
			cur_end = min(end, start + 512 * 1024 - 1);

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

		async_cow->work.func = async_cow_start;
		async_cow->work.ordered_func = async_cow_submit;
		async_cow->work.ordered_free = async_cow_free;
		async_cow->work.flags = 0;

		nr_pages = (cur_end - start + PAGE_CACHE_SIZE) >>
			PAGE_CACHE_SHIFT;
		atomic_add(nr_pages, &root->fs_info->async_delalloc_pages);

		btrfs_queue_worker(&root->fs_info->delalloc_workers,
				   &async_cow->work);

		if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) {
			wait_event(root->fs_info->async_submit_wait,
			   (atomic_read(&root->fs_info->async_delalloc_pages) <
			    limit));
		}

963
		while (atomic_read(&root->fs_info->async_submit_draining) &&
964
965
966
967
968
969
970
971
972
973
974
		      atomic_read(&root->fs_info->async_delalloc_pages)) {
			wait_event(root->fs_info->async_submit_wait,
			  (atomic_read(&root->fs_info->async_delalloc_pages) ==
			   0));
		}

		*nr_written += nr_pages;
		start = cur_end + 1;
	}
	*page_started = 1;
	return 0;
975
976
}

977
static noinline int csum_exist_in_range(struct btrfs_root *root,
978
979
980
981
982
983
					u64 bytenr, u64 num_bytes)
{
	int ret;
	struct btrfs_ordered_sum *sums;
	LIST_HEAD(list);

Yan Zheng's avatar
Yan Zheng committed
984
985
	ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr,
				       bytenr + num_bytes - 1, &list);
986
987
988
989
990
991
992
993
994
995
996
	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);
	}
	return 1;
}

Chris Mason's avatar
Chris Mason committed
997
998
999
1000
1001
1002
1003
/*
 * 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
 */
1004
1005
static noinline int run_delalloc_nocow(struct inode *inode,
				       struct page *locked_page,
1006
1007
			      u64 start, u64 end, int *page_started, int force,
			      unsigned long *nr_written)
1008
1009
{
	struct btrfs_root *root = BTRFS_I(inode)->root;
1010
	struct btrfs_trans_handle *trans;
1011
1012
	struct extent_buffer *leaf;
	struct btrfs_path *path;
Yan Zheng's avatar
Yan Zheng committed
1013
	struct btrfs_file_extent_item *fi;
1014
	struct btrfs_key found_key;
Yan Zheng's avatar
Yan Zheng committed
1015
1016
1017
	u64 cow_start;
	u64 cur_offset;
	u64 extent_end;
1018
	u64 extent_offset;
Yan Zheng's avatar
Yan Zheng committed
1019
1020
1021
1022
	u64 disk_bytenr;
	u64 num_bytes;
	int extent_type;
	int ret;
Yan Zheng's avatar
Yan Zheng committed
1023
	int type;
Yan Zheng's avatar
Yan Zheng committed
1024
1025
	int nocow;
	int check_prev = 1;
1026
1027
1028

	path = btrfs_alloc_path();
	BUG_ON(!path);
1029
1030
	trans = btrfs_join_transaction(root, 1);
	BUG_ON(!trans);
1031

Yan Zheng's avatar
Yan Zheng committed
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
	cow_start = (u64)-1;
	cur_offset = start;
	while (1) {
		ret = btrfs_lookup_file_extent(trans, root, path, inode->i_ino,
					       cur_offset, 0);
		BUG_ON(ret < 0);
		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);
			if (found_key.objectid == inode->i_ino &&
			    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);
			if (ret < 0)
				BUG_ON(1);
			if (ret > 0)
				break;
			leaf = path->nodes[0];
		}
1057

Yan Zheng's avatar
Yan Zheng committed
1058
1059
		nocow = 0;
		disk_bytenr = 0;
1060
		num_bytes = 0;
Yan Zheng's avatar
Yan Zheng committed
1061
1062
1063
1064
1065
1066
1067
1068
1069
		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);

		if (found_key.objectid > inode->i_ino ||
		    found_key.type > BTRFS_EXTENT_DATA_KEY ||
		    found_key.offset > end)
			break;

		if (found_key.offset > cur_offset) {
			extent_end = found_key.offset;
1070
			extent_type = 0;
Yan Zheng's avatar
Yan Zheng committed
1071
1072
1073
1074
1075
1076
1077
			goto out_check;
		}

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

Yan Zheng's avatar
Yan Zheng committed
1078
1079
		if (extent_type == BTRFS_FILE_EXTENT_REG ||
		    extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
Yan Zheng's avatar
Yan Zheng committed
1080
			disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1081
			extent_offset = btrfs_file_extent_offset(leaf, fi);
Yan Zheng's avatar
Yan Zheng committed
1082
1083
1084
1085
1086
1087
			extent_end = found_key.offset +
				btrfs_file_extent_num_bytes(leaf, fi);
			if (extent_end <= start) {
				path->slots[0]++;
				goto next_slot;
			}
1088
1089
			if (disk_bytenr == 0)
				goto out_check;
Yan Zheng's avatar
Yan Zheng committed
1090
1091
1092
1093
			if (btrfs_file_extent_compression(leaf, fi) ||
			    btrfs_file_extent_encryption(leaf, fi) ||
			    btrfs_file_extent_other_encoding(leaf, fi))
				goto out_check;
Yan Zheng's avatar
Yan Zheng committed
1094
1095
			if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
				goto out_check;
1096
			if (btrfs_extent_readonly(root, disk_bytenr))
Yan Zheng's avatar
Yan Zheng committed
1097
				goto out_check;
1098
			if (btrfs_cross_ref_exist(trans, root, inode->i_ino,
1099
1100
						  found_key.offset -
						  extent_offset, disk_bytenr))
1101
				goto out_check;
1102
			disk_bytenr += extent_offset;
1103
1104
1105
1106
1107
1108
1109
1110
1111
			disk_bytenr += cur_offset - found_key.offset;
			num_bytes = min(end + 1, extent_end) - cur_offset;
			/*
			 * force cow if csum exists in the range.
			 * this ensure that csum for a given extent are
			 * either valid or do not exist.
			 */
			if (csum_exist_in_range(root, disk_bytenr, num_bytes))
				goto out_check;
Yan Zheng's avatar
Yan Zheng committed
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
			nocow = 1;
		} else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
			extent_end = found_key.offset +
				btrfs_file_extent_inline_len(leaf, fi);
			extent_end = ALIGN(extent_end, root->sectorsize);
		} else {
			BUG_ON(1);
		}
out_check:
		if (extent_end <= start) {
			path->slots[0]++;
			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;
1133
1134
1135
		}

		btrfs_release_path(root, path);
Yan Zheng's avatar
Yan Zheng committed
1136
1137
		if (cow_start != (u64)-1) {
			ret = cow_file_range(inode, locked_page, cow_start,
1138
1139
					found_key.offset - 1, page_started,
					nr_written, 1);
Yan Zheng's avatar
Yan Zheng committed
1140
1141
			BUG_ON(ret);
			cow_start = (u64)-1;
1142
		}
Yan Zheng's avatar
Yan Zheng committed
1143

Yan Zheng's avatar
Yan Zheng committed
1144
1145
1146
1147
1148
1149
		if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
			struct extent_map *em;
			struct extent_map_tree *em_tree;
			em_tree = &BTRFS_I(inode)->extent_tree;
			em = alloc_extent_map(GFP_NOFS);
			em->start = cur_offset;
1150
			em->orig_start = em->start;
Yan Zheng's avatar
Yan Zheng committed
1151
1152
1153
1154
1155
1156
			em->len = num_bytes;
			em->block_len = num_bytes;
			em->block_start = disk_bytenr;
			em->bdev = root->fs_info->fs_devices->latest_bdev;
			set_bit(EXTENT_FLAG_PINNED, &em->flags);
			while (1) {
1157
				write_lock(&em_tree->lock);
Yan Zheng's avatar
Yan Zheng committed
1158
				ret = add_extent_mapping(em_tree, em);
1159
				write_unlock(&em_tree->lock);
Yan Zheng's avatar
Yan Zheng committed
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
				if (ret != -EEXIST) {
					free_extent_map(em);
					break;
				}
				btrfs_drop_extent_cache(inode, em->start,
						em->start + em->len - 1, 0);
			}
			type = BTRFS_ORDERED_PREALLOC;
		} else {
			type = BTRFS_ORDERED_NOCOW;
		}
Yan Zheng's avatar
Yan Zheng committed
1171
1172

		ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
Yan Zheng's avatar
Yan Zheng committed
1173
1174
					       num_bytes, num_bytes, type);
		BUG_ON(ret);
1175

Yan Zheng's avatar
Yan Zheng committed
1176
		extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
1177
1178
1179
1180
				cur_offset, cur_offset + num_bytes - 1,
				locked_page, EXTENT_CLEAR_UNLOCK_PAGE |
				EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
				EXTENT_SET_PRIVATE2);
Yan Zheng's avatar
Yan Zheng committed
1181
1182
1183
		cur_offset = extent_end;
		if (cur_offset > end)
			break;
1184
	}
Yan Zheng's avatar
Yan Zheng committed
1185
1186
1187
1188
1189
1190
	btrfs_release_path(root, path);

	if (cur_offset <= end && cow_start == (u64)-1)
		cow_start = cur_offset;
	if (cow_start != (u64)-1) {
		ret = cow_file_range(inode, locked_page, cow_start, end,
1191
				     page_started, nr_written, 1);
Yan Zheng's avatar
Yan Zheng committed
1192
1193
1194
1195
1196
		BUG_ON(ret);
	}

	ret = btrfs_end_transaction(trans, root);
	BUG_ON(ret);
1197
	btrfs_free_path(path);
Yan Zheng's avatar
Yan Zheng committed
1198
	return 0;
1199
1200
}

Chris Mason's avatar
Chris Mason committed
1201
1202
1203
/*
 * extent_io.c call back to do delayed allocation processing
 */
1204
static int run_delalloc_range(struct inode *inode, struct page *locked_page,
1205
1206
			      u64 start, u64 end, int *page_started,
			      unsigned long *nr_written)
1207
1208
{
	int ret;
1209
	struct btrfs_root *root = BTRFS_I(inode)->root;
1210

1211
	if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)
1212
		ret = run_delalloc_nocow(inode, locked_page, start, end,
1213
					 page_started, 1, nr_written);
1214
	else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC)
Yan Zheng's avatar
Yan Zheng committed
1215
		ret = run_delalloc_nocow(inode, locked_page, start, end,
1216
					 page_started, 0, nr_written);
1217
1218
	else if (!btrfs_test_opt(root, COMPRESS) &&
		 !(BTRFS_I(inode)->force_compress))
1219
1220
		ret = cow_file_range(inode, locked_page, start, end,
				      page_started, nr_written, 1);
1221
	else
1222
		ret = cow_file_range_async(inode, locked_page, start, end,
1223
					   page_started, nr_written);
1224
1225
1226
	return ret;
}

Josef Bacik's avatar
Josef Bacik committed
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
static int btrfs_split_extent_hook(struct inode *inode,
				    struct extent_state *orig, u64 split)
{
	struct btrfs_root *root = BTRFS_I(inode)->root;
	u64 size;

	if (!(orig->state & EXTENT_DELALLOC))
		return 0;

	size = orig->end - orig->start + 1;
	if (size > root->fs_info->max_extent) {
		u64 num_extents;
		u64 new_size;

		new_size = orig->end - split + 1;
		num_extents = div64_u64(size + root->fs_info->max_extent - 1,
					root->fs_info->max_extent);

		/*
1246
1247
		 * if we break a large extent up then leave oustanding_extents
		 * be, since we've already accounted for the large extent.
Josef Bacik's avatar
Josef Bacik committed
1248
1249
1250
1251
1252
1253
		 */
		if (div64_u64(new_size + root->fs_info->max_extent - 1,
			      root->fs_info->max_extent) < num_extents)
			return 0;
	}

1254
1255
1256
	spin_lock(&BTRFS_I(inode)->accounting_lock);
	BTRFS_I(inode)->outstanding_extents++;
	spin_unlock(&BTRFS_I(inode)->accounting_lock);
Josef Bacik's avatar
Josef Bacik committed
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286

	return 0;
}

/*
 * 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.
 */
static int btrfs_merge_extent_hook(struct inode *inode,
				   struct extent_state *new,
				   struct extent_state *other)
{
	struct btrfs_root *root = BTRFS_I(inode)->root;
	u64 new_size, old_size;
	u64 num_extents;

	/* not delalloc, ignore it */
	if (!(other->state & EXTENT_DELALLOC))
		return 0;

	old_size = other->end - other->start + 1;
	if (new->start < other->start)
		new_size = other->end - new->start + 1;
	else
		new_size = new->end - other->start + 1;

	/* we're not bigger than the max, unreserve the space and go */
	if (new_size <= root->fs_info->max_extent) {
1287
1288
1289
		spin_lock(&BTRFS_I(inode)->accounting_lock);
		BTRFS_I(inode)->outstanding_extents--;
		spin_unlock(&BTRFS_I(inode)->accounting_lock);
Josef Bacik's avatar
Josef Bacik committed
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
		return 0;
	}

	/*
	 * If we grew by another max_extent, just return, we want to keep that
	 * reserved amount.
	 */
	num_extents = div64_u64(old_size + root->fs_info->max_extent - 1,
				root->fs_info->max_extent);
	if (div64_u64(new_size + root->fs_info->max_extent - 1,
		      root->fs_info->max_extent) > num_extents)
		return 0;

1303
1304
1305
	spin_lock(&BTRFS_I(inode)->accounting_lock);
	BTRFS_I(inode)->outstanding_extents--;
	spin_unlock(&BTRFS_I(inode)->accounting_lock);
Josef Bacik's avatar
Josef Bacik committed
1306
1307
1308
1309

	return 0;
}

Chris Mason's avatar
Chris Mason committed
1310
1311
1312
1313
1314
/*
 * 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.
 */
1315
static int btrfs_set_bit_hook(struct inode *inode, u64 start, u64 end,
1316
		       unsigned long old, unsigned long bits)
1317
{
Josef Bacik's avatar
Josef Bacik committed
1318

1319
1320
1321
1322
1323
	/*
	 * set_bit and clear bit hooks normally require _irqsave/restore
	 * but in this case, we are only testeing for the DELALLOC
	 * bit, which is only set or cleared with irqs on
	 */
1324
	if (!(old & EXTENT_DELALLOC) && (bits & EXTENT_DELALLOC)) {
1325
		struct btrfs_root *root = BTRFS_I(inode)->root;
Josef Bacik's avatar
Josef Bacik committed
1326

1327
1328
1329
		spin_lock(&BTRFS_I(inode)->accounting_lock);
		BTRFS_I(inode)->outstanding_extents++;
		spin_unlock(&BTRFS_I(inode)->accounting_lock);
1330
		btrfs_delalloc_reserve_space(root, inode, end - start + 1);
1331
		spin_lock(&root->fs_info->