fs: btrfs: Add missing include file
[deliverable/linux.git] / fs / btrfs / inode.c
CommitLineData
6cbd5570
CM
1/*
2 * Copyright (C) 2007 Oracle. All rights reserved.
3 *
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public
6 * License v2 as published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public
14 * License along with this program; if not, write to the
15 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16 * Boston, MA 021110-1307, USA.
17 */
18
8f18cf13 19#include <linux/kernel.h>
065631f6 20#include <linux/bio.h>
39279cc3 21#include <linux/buffer_head.h>
f2eb0a24 22#include <linux/file.h>
39279cc3
CM
23#include <linux/fs.h>
24#include <linux/pagemap.h>
25#include <linux/highmem.h>
26#include <linux/time.h>
27#include <linux/init.h>
28#include <linux/string.h>
39279cc3
CM
29#include <linux/backing-dev.h>
30#include <linux/mpage.h>
31#include <linux/swap.h>
32#include <linux/writeback.h>
33#include <linux/statfs.h>
34#include <linux/compat.h>
a27bb332 35#include <linux/aio.h>
9ebefb18 36#include <linux/bit_spinlock.h>
5103e947 37#include <linux/xattr.h>
33268eaf 38#include <linux/posix_acl.h>
d899e052 39#include <linux/falloc.h>
5a0e3ad6 40#include <linux/slab.h>
7a36ddec 41#include <linux/ratelimit.h>
22c44fe6 42#include <linux/mount.h>
55e301fd 43#include <linux/btrfs.h>
53b381b3 44#include <linux/blkdev.h>
f23b5a59 45#include <linux/posix_acl_xattr.h>
4a3d1caf 46#include <linux/uio.h>
39279cc3
CM
47#include "ctree.h"
48#include "disk-io.h"
49#include "transaction.h"
50#include "btrfs_inode.h"
39279cc3 51#include "print-tree.h"
e6dcd2dc 52#include "ordered-data.h"
95819c05 53#include "xattr.h"
e02119d5 54#include "tree-log.h"
4a54c8c1 55#include "volumes.h"
c8b97818 56#include "compression.h"
b4ce94de 57#include "locking.h"
dc89e982 58#include "free-space-cache.h"
581bb050 59#include "inode-map.h"
38c227d8 60#include "backref.h"
f23b5a59 61#include "hash.h"
63541927 62#include "props.h"
39279cc3
CM
63
64struct btrfs_iget_args {
90d3e592 65 struct btrfs_key *location;
39279cc3
CM
66 struct btrfs_root *root;
67};
68
6e1d5dcc
AD
69static const struct inode_operations btrfs_dir_inode_operations;
70static const struct inode_operations btrfs_symlink_inode_operations;
71static const struct inode_operations btrfs_dir_ro_inode_operations;
72static const struct inode_operations btrfs_special_inode_operations;
73static const struct inode_operations btrfs_file_inode_operations;
7f09410b
AD
74static const struct address_space_operations btrfs_aops;
75static const struct address_space_operations btrfs_symlink_aops;
828c0950 76static const struct file_operations btrfs_dir_file_operations;
d1310b2e 77static struct extent_io_ops btrfs_extent_io_ops;
39279cc3
CM
78
79static struct kmem_cache *btrfs_inode_cachep;
8ccf6f19 80static struct kmem_cache *btrfs_delalloc_work_cachep;
39279cc3
CM
81struct kmem_cache *btrfs_trans_handle_cachep;
82struct kmem_cache *btrfs_transaction_cachep;
39279cc3 83struct kmem_cache *btrfs_path_cachep;
dc89e982 84struct kmem_cache *btrfs_free_space_cachep;
39279cc3
CM
85
86#define S_SHIFT 12
87static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
88 [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
89 [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
90 [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
91 [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
92 [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
93 [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
94 [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
95};
96
3972f260 97static int btrfs_setsize(struct inode *inode, struct iattr *attr);
a41ad394 98static int btrfs_truncate(struct inode *inode);
5fd02043 99static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
771ed689
CM
100static noinline int cow_file_range(struct inode *inode,
101 struct page *locked_page,
102 u64 start, u64 end, int *page_started,
103 unsigned long *nr_written, int unlock);
70c8a91c
JB
104static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
105 u64 len, u64 orig_start,
106 u64 block_start, u64 block_len,
cc95bef6
JB
107 u64 orig_block_len, u64 ram_bytes,
108 int type);
7b128766 109
48a3b636 110static int btrfs_dirty_inode(struct inode *inode);
7b128766 111
6a3891c5
JB
112#ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
113void btrfs_test_inode_set_ops(struct inode *inode)
114{
115 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
116}
117#endif
118
f34f57a3 119static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
2a7dba39
EP
120 struct inode *inode, struct inode *dir,
121 const struct qstr *qstr)
0279b4cd
JO
122{
123 int err;
124
f34f57a3 125 err = btrfs_init_acl(trans, inode, dir);
0279b4cd 126 if (!err)
2a7dba39 127 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
0279b4cd
JO
128 return err;
129}
130
c8b97818
CM
131/*
132 * this does all the hard work for inserting an inline extent into
133 * the btree. The caller should have done a btrfs_drop_extents so that
134 * no overlapping inline items exist in the btree
135 */
40f76580 136static int insert_inline_extent(struct btrfs_trans_handle *trans,
1acae57b 137 struct btrfs_path *path, int extent_inserted,
c8b97818
CM
138 struct btrfs_root *root, struct inode *inode,
139 u64 start, size_t size, size_t compressed_size,
fe3f566c 140 int compress_type,
c8b97818
CM
141 struct page **compressed_pages)
142{
c8b97818
CM
143 struct extent_buffer *leaf;
144 struct page *page = NULL;
145 char *kaddr;
146 unsigned long ptr;
147 struct btrfs_file_extent_item *ei;
148 int err = 0;
149 int ret;
150 size_t cur_size = size;
c8b97818 151 unsigned long offset;
c8b97818 152
fe3f566c 153 if (compressed_size && compressed_pages)
c8b97818 154 cur_size = compressed_size;
c8b97818 155
1acae57b 156 inode_add_bytes(inode, size);
c8b97818 157
1acae57b
FDBM
158 if (!extent_inserted) {
159 struct btrfs_key key;
160 size_t datasize;
c8b97818 161
1acae57b
FDBM
162 key.objectid = btrfs_ino(inode);
163 key.offset = start;
962a298f 164 key.type = BTRFS_EXTENT_DATA_KEY;
c8b97818 165
1acae57b
FDBM
166 datasize = btrfs_file_extent_calc_inline_size(cur_size);
167 path->leave_spinning = 1;
168 ret = btrfs_insert_empty_item(trans, root, path, &key,
169 datasize);
170 if (ret) {
171 err = ret;
172 goto fail;
173 }
c8b97818
CM
174 }
175 leaf = path->nodes[0];
176 ei = btrfs_item_ptr(leaf, path->slots[0],
177 struct btrfs_file_extent_item);
178 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
179 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
180 btrfs_set_file_extent_encryption(leaf, ei, 0);
181 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
182 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
183 ptr = btrfs_file_extent_inline_start(ei);
184
261507a0 185 if (compress_type != BTRFS_COMPRESS_NONE) {
c8b97818
CM
186 struct page *cpage;
187 int i = 0;
d397712b 188 while (compressed_size > 0) {
c8b97818 189 cpage = compressed_pages[i];
5b050f04 190 cur_size = min_t(unsigned long, compressed_size,
c8b97818
CM
191 PAGE_CACHE_SIZE);
192
7ac687d9 193 kaddr = kmap_atomic(cpage);
c8b97818 194 write_extent_buffer(leaf, kaddr, ptr, cur_size);
7ac687d9 195 kunmap_atomic(kaddr);
c8b97818
CM
196
197 i++;
198 ptr += cur_size;
199 compressed_size -= cur_size;
200 }
201 btrfs_set_file_extent_compression(leaf, ei,
261507a0 202 compress_type);
c8b97818
CM
203 } else {
204 page = find_get_page(inode->i_mapping,
205 start >> PAGE_CACHE_SHIFT);
206 btrfs_set_file_extent_compression(leaf, ei, 0);
7ac687d9 207 kaddr = kmap_atomic(page);
c8b97818
CM
208 offset = start & (PAGE_CACHE_SIZE - 1);
209 write_extent_buffer(leaf, kaddr + offset, ptr, size);
7ac687d9 210 kunmap_atomic(kaddr);
c8b97818
CM
211 page_cache_release(page);
212 }
213 btrfs_mark_buffer_dirty(leaf);
1acae57b 214 btrfs_release_path(path);
c8b97818 215
c2167754
YZ
216 /*
217 * we're an inline extent, so nobody can
218 * extend the file past i_size without locking
219 * a page we already have locked.
220 *
221 * We must do any isize and inode updates
222 * before we unlock the pages. Otherwise we
223 * could end up racing with unlink.
224 */
c8b97818 225 BTRFS_I(inode)->disk_i_size = inode->i_size;
79787eaa 226 ret = btrfs_update_inode(trans, root, inode);
c2167754 227
79787eaa 228 return ret;
c8b97818 229fail:
c8b97818
CM
230 return err;
231}
232
233
234/*
235 * conditionally insert an inline extent into the file. This
236 * does the checks required to make sure the data is small enough
237 * to fit as an inline extent.
238 */
00361589
JB
239static noinline int cow_file_range_inline(struct btrfs_root *root,
240 struct inode *inode, u64 start,
241 u64 end, size_t compressed_size,
242 int compress_type,
243 struct page **compressed_pages)
c8b97818 244{
00361589 245 struct btrfs_trans_handle *trans;
c8b97818
CM
246 u64 isize = i_size_read(inode);
247 u64 actual_end = min(end + 1, isize);
248 u64 inline_len = actual_end - start;
fda2832f 249 u64 aligned_end = ALIGN(end, root->sectorsize);
c8b97818
CM
250 u64 data_len = inline_len;
251 int ret;
1acae57b
FDBM
252 struct btrfs_path *path;
253 int extent_inserted = 0;
254 u32 extent_item_size;
c8b97818
CM
255
256 if (compressed_size)
257 data_len = compressed_size;
258
259 if (start > 0 ||
354877be
WS
260 actual_end > PAGE_CACHE_SIZE ||
261 data_len > BTRFS_MAX_INLINE_DATA_SIZE(root) ||
c8b97818
CM
262 (!compressed_size &&
263 (actual_end & (root->sectorsize - 1)) == 0) ||
264 end + 1 < isize ||
265 data_len > root->fs_info->max_inline) {
266 return 1;
267 }
268
1acae57b
FDBM
269 path = btrfs_alloc_path();
270 if (!path)
271 return -ENOMEM;
272
00361589 273 trans = btrfs_join_transaction(root);
1acae57b
FDBM
274 if (IS_ERR(trans)) {
275 btrfs_free_path(path);
00361589 276 return PTR_ERR(trans);
1acae57b 277 }
00361589
JB
278 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
279
1acae57b
FDBM
280 if (compressed_size && compressed_pages)
281 extent_item_size = btrfs_file_extent_calc_inline_size(
282 compressed_size);
283 else
284 extent_item_size = btrfs_file_extent_calc_inline_size(
285 inline_len);
286
287 ret = __btrfs_drop_extents(trans, root, inode, path,
288 start, aligned_end, NULL,
289 1, 1, extent_item_size, &extent_inserted);
00361589
JB
290 if (ret) {
291 btrfs_abort_transaction(trans, root, ret);
292 goto out;
293 }
c8b97818
CM
294
295 if (isize > actual_end)
296 inline_len = min_t(u64, isize, actual_end);
1acae57b
FDBM
297 ret = insert_inline_extent(trans, path, extent_inserted,
298 root, inode, start,
c8b97818 299 inline_len, compressed_size,
fe3f566c 300 compress_type, compressed_pages);
2adcac1a 301 if (ret && ret != -ENOSPC) {
79787eaa 302 btrfs_abort_transaction(trans, root, ret);
00361589 303 goto out;
2adcac1a 304 } else if (ret == -ENOSPC) {
00361589
JB
305 ret = 1;
306 goto out;
79787eaa 307 }
2adcac1a 308
bdc20e67 309 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
0ca1f7ce 310 btrfs_delalloc_release_metadata(inode, end + 1 - start);
a1ed835e 311 btrfs_drop_extent_cache(inode, start, aligned_end - 1, 0);
00361589 312out:
1acae57b 313 btrfs_free_path(path);
00361589
JB
314 btrfs_end_transaction(trans, root);
315 return ret;
c8b97818
CM
316}
317
771ed689
CM
318struct async_extent {
319 u64 start;
320 u64 ram_size;
321 u64 compressed_size;
322 struct page **pages;
323 unsigned long nr_pages;
261507a0 324 int compress_type;
771ed689
CM
325 struct list_head list;
326};
327
328struct async_cow {
329 struct inode *inode;
330 struct btrfs_root *root;
331 struct page *locked_page;
332 u64 start;
333 u64 end;
334 struct list_head extents;
335 struct btrfs_work work;
336};
337
338static noinline int add_async_extent(struct async_cow *cow,
339 u64 start, u64 ram_size,
340 u64 compressed_size,
341 struct page **pages,
261507a0
LZ
342 unsigned long nr_pages,
343 int compress_type)
771ed689
CM
344{
345 struct async_extent *async_extent;
346
347 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
79787eaa 348 BUG_ON(!async_extent); /* -ENOMEM */
771ed689
CM
349 async_extent->start = start;
350 async_extent->ram_size = ram_size;
351 async_extent->compressed_size = compressed_size;
352 async_extent->pages = pages;
353 async_extent->nr_pages = nr_pages;
261507a0 354 async_extent->compress_type = compress_type;
771ed689
CM
355 list_add_tail(&async_extent->list, &cow->extents);
356 return 0;
357}
358
f79707b0
WS
359static inline int inode_need_compress(struct inode *inode)
360{
361 struct btrfs_root *root = BTRFS_I(inode)->root;
362
363 /* force compress */
364 if (btrfs_test_opt(root, FORCE_COMPRESS))
365 return 1;
366 /* bad compression ratios */
367 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
368 return 0;
369 if (btrfs_test_opt(root, COMPRESS) ||
370 BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS ||
371 BTRFS_I(inode)->force_compress)
372 return 1;
373 return 0;
374}
375
d352ac68 376/*
771ed689
CM
377 * we create compressed extents in two phases. The first
378 * phase compresses a range of pages that have already been
379 * locked (both pages and state bits are locked).
c8b97818 380 *
771ed689
CM
381 * This is done inside an ordered work queue, and the compression
382 * is spread across many cpus. The actual IO submission is step
383 * two, and the ordered work queue takes care of making sure that
384 * happens in the same order things were put onto the queue by
385 * writepages and friends.
c8b97818 386 *
771ed689
CM
387 * If this code finds it can't get good compression, it puts an
388 * entry onto the work queue to write the uncompressed bytes. This
389 * makes sure that both compressed inodes and uncompressed inodes
b2570314
AB
390 * are written in the same order that the flusher thread sent them
391 * down.
d352ac68 392 */
c44f649e 393static noinline void compress_file_range(struct inode *inode,
771ed689
CM
394 struct page *locked_page,
395 u64 start, u64 end,
396 struct async_cow *async_cow,
397 int *num_added)
b888db2b
CM
398{
399 struct btrfs_root *root = BTRFS_I(inode)->root;
db94535d 400 u64 num_bytes;
db94535d 401 u64 blocksize = root->sectorsize;
c8b97818 402 u64 actual_end;
42dc7bab 403 u64 isize = i_size_read(inode);
e6dcd2dc 404 int ret = 0;
c8b97818
CM
405 struct page **pages = NULL;
406 unsigned long nr_pages;
407 unsigned long nr_pages_ret = 0;
408 unsigned long total_compressed = 0;
409 unsigned long total_in = 0;
410 unsigned long max_compressed = 128 * 1024;
771ed689 411 unsigned long max_uncompressed = 128 * 1024;
c8b97818
CM
412 int i;
413 int will_compress;
261507a0 414 int compress_type = root->fs_info->compress_type;
4adaa611 415 int redirty = 0;
b888db2b 416
4cb13e5d
LB
417 /* if this is a small write inside eof, kick off a defrag */
418 if ((end - start + 1) < 16 * 1024 &&
419 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
4cb5300b
CM
420 btrfs_add_inode_defrag(NULL, inode);
421
42dc7bab 422 actual_end = min_t(u64, isize, end + 1);
c8b97818
CM
423again:
424 will_compress = 0;
425 nr_pages = (end >> PAGE_CACHE_SHIFT) - (start >> PAGE_CACHE_SHIFT) + 1;
426 nr_pages = min(nr_pages, (128 * 1024UL) / PAGE_CACHE_SIZE);
be20aa9d 427
f03d9301
CM
428 /*
429 * we don't want to send crud past the end of i_size through
430 * compression, that's just a waste of CPU time. So, if the
431 * end of the file is before the start of our current
432 * requested range of bytes, we bail out to the uncompressed
433 * cleanup code that can deal with all of this.
434 *
435 * It isn't really the fastest way to fix things, but this is a
436 * very uncommon corner.
437 */
438 if (actual_end <= start)
439 goto cleanup_and_bail_uncompressed;
440
c8b97818
CM
441 total_compressed = actual_end - start;
442
4bcbb332
SW
443 /*
444 * skip compression for a small file range(<=blocksize) that
445 * isn't an inline extent, since it dosen't save disk space at all.
446 */
447 if (total_compressed <= blocksize &&
448 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
449 goto cleanup_and_bail_uncompressed;
450
c8b97818
CM
451 /* we want to make sure that amount of ram required to uncompress
452 * an extent is reasonable, so we limit the total size in ram
771ed689
CM
453 * of a compressed extent to 128k. This is a crucial number
454 * because it also controls how easily we can spread reads across
455 * cpus for decompression.
456 *
457 * We also want to make sure the amount of IO required to do
458 * a random read is reasonably small, so we limit the size of
459 * a compressed extent to 128k.
c8b97818
CM
460 */
461 total_compressed = min(total_compressed, max_uncompressed);
fda2832f 462 num_bytes = ALIGN(end - start + 1, blocksize);
be20aa9d 463 num_bytes = max(blocksize, num_bytes);
c8b97818
CM
464 total_in = 0;
465 ret = 0;
db94535d 466
771ed689
CM
467 /*
468 * we do compression for mount -o compress and when the
469 * inode has not been flagged as nocompress. This flag can
470 * change at any time if we discover bad compression ratios.
c8b97818 471 */
f79707b0 472 if (inode_need_compress(inode)) {
c8b97818 473 WARN_ON(pages);
31e818fe 474 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
560f7d75
LZ
475 if (!pages) {
476 /* just bail out to the uncompressed code */
477 goto cont;
478 }
c8b97818 479
261507a0
LZ
480 if (BTRFS_I(inode)->force_compress)
481 compress_type = BTRFS_I(inode)->force_compress;
482
4adaa611
CM
483 /*
484 * we need to call clear_page_dirty_for_io on each
485 * page in the range. Otherwise applications with the file
486 * mmap'd can wander in and change the page contents while
487 * we are compressing them.
488 *
489 * If the compression fails for any reason, we set the pages
490 * dirty again later on.
491 */
492 extent_range_clear_dirty_for_io(inode, start, end);
493 redirty = 1;
261507a0
LZ
494 ret = btrfs_compress_pages(compress_type,
495 inode->i_mapping, start,
496 total_compressed, pages,
497 nr_pages, &nr_pages_ret,
498 &total_in,
499 &total_compressed,
500 max_compressed);
c8b97818
CM
501
502 if (!ret) {
503 unsigned long offset = total_compressed &
504 (PAGE_CACHE_SIZE - 1);
505 struct page *page = pages[nr_pages_ret - 1];
506 char *kaddr;
507
508 /* zero the tail end of the last page, we might be
509 * sending it down to disk
510 */
511 if (offset) {
7ac687d9 512 kaddr = kmap_atomic(page);
c8b97818
CM
513 memset(kaddr + offset, 0,
514 PAGE_CACHE_SIZE - offset);
7ac687d9 515 kunmap_atomic(kaddr);
c8b97818
CM
516 }
517 will_compress = 1;
518 }
519 }
560f7d75 520cont:
c8b97818
CM
521 if (start == 0) {
522 /* lets try to make an inline extent */
771ed689 523 if (ret || total_in < (actual_end - start)) {
c8b97818 524 /* we didn't compress the entire range, try
771ed689 525 * to make an uncompressed inline extent.
c8b97818 526 */
00361589
JB
527 ret = cow_file_range_inline(root, inode, start, end,
528 0, 0, NULL);
c8b97818 529 } else {
771ed689 530 /* try making a compressed inline extent */
00361589 531 ret = cow_file_range_inline(root, inode, start, end,
fe3f566c
LZ
532 total_compressed,
533 compress_type, pages);
c8b97818 534 }
79787eaa 535 if (ret <= 0) {
151a41bc
JB
536 unsigned long clear_flags = EXTENT_DELALLOC |
537 EXTENT_DEFRAG;
e6eb4314
FM
538 unsigned long page_error_op;
539
151a41bc 540 clear_flags |= (ret < 0) ? EXTENT_DO_ACCOUNTING : 0;
e6eb4314 541 page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
151a41bc 542
771ed689 543 /*
79787eaa
JM
544 * inline extent creation worked or returned error,
545 * we don't need to create any more async work items.
546 * Unlock and free up our temp pages.
771ed689 547 */
c2790a2e 548 extent_clear_unlock_delalloc(inode, start, end, NULL,
151a41bc 549 clear_flags, PAGE_UNLOCK |
c2790a2e
JB
550 PAGE_CLEAR_DIRTY |
551 PAGE_SET_WRITEBACK |
e6eb4314 552 page_error_op |
c2790a2e 553 PAGE_END_WRITEBACK);
c8b97818
CM
554 goto free_pages_out;
555 }
556 }
557
558 if (will_compress) {
559 /*
560 * we aren't doing an inline extent round the compressed size
561 * up to a block size boundary so the allocator does sane
562 * things
563 */
fda2832f 564 total_compressed = ALIGN(total_compressed, blocksize);
c8b97818
CM
565
566 /*
567 * one last check to make sure the compression is really a
568 * win, compare the page count read with the blocks on disk
569 */
fda2832f 570 total_in = ALIGN(total_in, PAGE_CACHE_SIZE);
c8b97818
CM
571 if (total_compressed >= total_in) {
572 will_compress = 0;
573 } else {
c8b97818
CM
574 num_bytes = total_in;
575 }
576 }
577 if (!will_compress && pages) {
578 /*
579 * the compression code ran but failed to make things smaller,
580 * free any pages it allocated and our page pointer array
581 */
582 for (i = 0; i < nr_pages_ret; i++) {
70b99e69 583 WARN_ON(pages[i]->mapping);
c8b97818
CM
584 page_cache_release(pages[i]);
585 }
586 kfree(pages);
587 pages = NULL;
588 total_compressed = 0;
589 nr_pages_ret = 0;
590
591 /* flag the file so we don't compress in the future */
1e701a32
CM
592 if (!btrfs_test_opt(root, FORCE_COMPRESS) &&
593 !(BTRFS_I(inode)->force_compress)) {
a555f810 594 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
1e701a32 595 }
c8b97818 596 }
771ed689
CM
597 if (will_compress) {
598 *num_added += 1;
c8b97818 599
771ed689
CM
600 /* the async work queues will take care of doing actual
601 * allocation on disk for these compressed pages,
602 * and will submit them to the elevator.
603 */
604 add_async_extent(async_cow, start, num_bytes,
261507a0
LZ
605 total_compressed, pages, nr_pages_ret,
606 compress_type);
179e29e4 607
24ae6365 608 if (start + num_bytes < end) {
771ed689
CM
609 start += num_bytes;
610 pages = NULL;
611 cond_resched();
612 goto again;
613 }
614 } else {
f03d9301 615cleanup_and_bail_uncompressed:
771ed689
CM
616 /*
617 * No compression, but we still need to write the pages in
618 * the file we've been given so far. redirty the locked
619 * page if it corresponds to our extent and set things up
620 * for the async work queue to run cow_file_range to do
621 * the normal delalloc dance
622 */
623 if (page_offset(locked_page) >= start &&
624 page_offset(locked_page) <= end) {
625 __set_page_dirty_nobuffers(locked_page);
626 /* unlocked later on in the async handlers */
627 }
4adaa611
CM
628 if (redirty)
629 extent_range_redirty_for_io(inode, start, end);
261507a0
LZ
630 add_async_extent(async_cow, start, end - start + 1,
631 0, NULL, 0, BTRFS_COMPRESS_NONE);
771ed689
CM
632 *num_added += 1;
633 }
3b951516 634
c44f649e 635 return;
771ed689
CM
636
637free_pages_out:
638 for (i = 0; i < nr_pages_ret; i++) {
639 WARN_ON(pages[i]->mapping);
640 page_cache_release(pages[i]);
641 }
d397712b 642 kfree(pages);
771ed689 643}
771ed689 644
40ae837b
FM
645static void free_async_extent_pages(struct async_extent *async_extent)
646{
647 int i;
648
649 if (!async_extent->pages)
650 return;
651
652 for (i = 0; i < async_extent->nr_pages; i++) {
653 WARN_ON(async_extent->pages[i]->mapping);
654 page_cache_release(async_extent->pages[i]);
655 }
656 kfree(async_extent->pages);
657 async_extent->nr_pages = 0;
658 async_extent->pages = NULL;
771ed689
CM
659}
660
661/*
662 * phase two of compressed writeback. This is the ordered portion
663 * of the code, which only gets called in the order the work was
664 * queued. We walk all the async extents created by compress_file_range
665 * and send them down to the disk.
666 */
dec8f175 667static noinline void submit_compressed_extents(struct inode *inode,
771ed689
CM
668 struct async_cow *async_cow)
669{
670 struct async_extent *async_extent;
671 u64 alloc_hint = 0;
771ed689
CM
672 struct btrfs_key ins;
673 struct extent_map *em;
674 struct btrfs_root *root = BTRFS_I(inode)->root;
675 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
676 struct extent_io_tree *io_tree;
f5a84ee3 677 int ret = 0;
771ed689 678
3e04e7f1 679again:
d397712b 680 while (!list_empty(&async_cow->extents)) {
771ed689
CM
681 async_extent = list_entry(async_cow->extents.next,
682 struct async_extent, list);
683 list_del(&async_extent->list);
c8b97818 684
771ed689
CM
685 io_tree = &BTRFS_I(inode)->io_tree;
686
f5a84ee3 687retry:
771ed689
CM
688 /* did the compression code fall back to uncompressed IO? */
689 if (!async_extent->pages) {
690 int page_started = 0;
691 unsigned long nr_written = 0;
692
693 lock_extent(io_tree, async_extent->start,
2ac55d41 694 async_extent->start +
d0082371 695 async_extent->ram_size - 1);
771ed689
CM
696
697 /* allocate blocks */
f5a84ee3
JB
698 ret = cow_file_range(inode, async_cow->locked_page,
699 async_extent->start,
700 async_extent->start +
701 async_extent->ram_size - 1,
702 &page_started, &nr_written, 0);
771ed689 703
79787eaa
JM
704 /* JDM XXX */
705
771ed689
CM
706 /*
707 * if page_started, cow_file_range inserted an
708 * inline extent and took care of all the unlocking
709 * and IO for us. Otherwise, we need to submit
710 * all those pages down to the drive.
711 */
f5a84ee3 712 if (!page_started && !ret)
771ed689
CM
713 extent_write_locked_range(io_tree,
714 inode, async_extent->start,
d397712b 715 async_extent->start +
771ed689
CM
716 async_extent->ram_size - 1,
717 btrfs_get_extent,
718 WB_SYNC_ALL);
3e04e7f1
JB
719 else if (ret)
720 unlock_page(async_cow->locked_page);
771ed689
CM
721 kfree(async_extent);
722 cond_resched();
723 continue;
724 }
725
726 lock_extent(io_tree, async_extent->start,
d0082371 727 async_extent->start + async_extent->ram_size - 1);
771ed689 728
00361589 729 ret = btrfs_reserve_extent(root,
771ed689
CM
730 async_extent->compressed_size,
731 async_extent->compressed_size,
e570fd27 732 0, alloc_hint, &ins, 1, 1);
f5a84ee3 733 if (ret) {
40ae837b 734 free_async_extent_pages(async_extent);
3e04e7f1 735
fdf8e2ea
JB
736 if (ret == -ENOSPC) {
737 unlock_extent(io_tree, async_extent->start,
738 async_extent->start +
739 async_extent->ram_size - 1);
ce62003f
LB
740
741 /*
742 * we need to redirty the pages if we decide to
743 * fallback to uncompressed IO, otherwise we
744 * will not submit these pages down to lower
745 * layers.
746 */
747 extent_range_redirty_for_io(inode,
748 async_extent->start,
749 async_extent->start +
750 async_extent->ram_size - 1);
751
79787eaa 752 goto retry;
fdf8e2ea 753 }
3e04e7f1 754 goto out_free;
f5a84ee3
JB
755 }
756
c2167754
YZ
757 /*
758 * here we're doing allocation and writeback of the
759 * compressed pages
760 */
761 btrfs_drop_extent_cache(inode, async_extent->start,
762 async_extent->start +
763 async_extent->ram_size - 1, 0);
764
172ddd60 765 em = alloc_extent_map();
b9aa55be
LB
766 if (!em) {
767 ret = -ENOMEM;
3e04e7f1 768 goto out_free_reserve;
b9aa55be 769 }
771ed689
CM
770 em->start = async_extent->start;
771 em->len = async_extent->ram_size;
445a6944 772 em->orig_start = em->start;
2ab28f32
JB
773 em->mod_start = em->start;
774 em->mod_len = em->len;
c8b97818 775
771ed689
CM
776 em->block_start = ins.objectid;
777 em->block_len = ins.offset;
b4939680 778 em->orig_block_len = ins.offset;
cc95bef6 779 em->ram_bytes = async_extent->ram_size;
771ed689 780 em->bdev = root->fs_info->fs_devices->latest_bdev;
261507a0 781 em->compress_type = async_extent->compress_type;
771ed689
CM
782 set_bit(EXTENT_FLAG_PINNED, &em->flags);
783 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
70c8a91c 784 em->generation = -1;
771ed689 785
d397712b 786 while (1) {
890871be 787 write_lock(&em_tree->lock);
09a2a8f9 788 ret = add_extent_mapping(em_tree, em, 1);
890871be 789 write_unlock(&em_tree->lock);
771ed689
CM
790 if (ret != -EEXIST) {
791 free_extent_map(em);
792 break;
793 }
794 btrfs_drop_extent_cache(inode, async_extent->start,
795 async_extent->start +
796 async_extent->ram_size - 1, 0);
797 }
798
3e04e7f1
JB
799 if (ret)
800 goto out_free_reserve;
801
261507a0
LZ
802 ret = btrfs_add_ordered_extent_compress(inode,
803 async_extent->start,
804 ins.objectid,
805 async_extent->ram_size,
806 ins.offset,
807 BTRFS_ORDERED_COMPRESSED,
808 async_extent->compress_type);
d9f85963
FM
809 if (ret) {
810 btrfs_drop_extent_cache(inode, async_extent->start,
811 async_extent->start +
812 async_extent->ram_size - 1, 0);
3e04e7f1 813 goto out_free_reserve;
d9f85963 814 }
771ed689 815
771ed689
CM
816 /*
817 * clear dirty, set writeback and unlock the pages.
818 */
c2790a2e 819 extent_clear_unlock_delalloc(inode, async_extent->start,
a791e35e
CM
820 async_extent->start +
821 async_extent->ram_size - 1,
151a41bc
JB
822 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
823 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
c2790a2e 824 PAGE_SET_WRITEBACK);
771ed689 825 ret = btrfs_submit_compressed_write(inode,
d397712b
CM
826 async_extent->start,
827 async_extent->ram_size,
828 ins.objectid,
829 ins.offset, async_extent->pages,
830 async_extent->nr_pages);
fce2a4e6
FM
831 if (ret) {
832 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
833 struct page *p = async_extent->pages[0];
834 const u64 start = async_extent->start;
835 const u64 end = start + async_extent->ram_size - 1;
836
837 p->mapping = inode->i_mapping;
838 tree->ops->writepage_end_io_hook(p, start, end,
839 NULL, 0);
840 p->mapping = NULL;
841 extent_clear_unlock_delalloc(inode, start, end, NULL, 0,
842 PAGE_END_WRITEBACK |
843 PAGE_SET_ERROR);
40ae837b 844 free_async_extent_pages(async_extent);
fce2a4e6 845 }
771ed689
CM
846 alloc_hint = ins.objectid + ins.offset;
847 kfree(async_extent);
848 cond_resched();
849 }
dec8f175 850 return;
3e04e7f1 851out_free_reserve:
e570fd27 852 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
79787eaa 853out_free:
c2790a2e 854 extent_clear_unlock_delalloc(inode, async_extent->start,
3e04e7f1
JB
855 async_extent->start +
856 async_extent->ram_size - 1,
c2790a2e 857 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
151a41bc
JB
858 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
859 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
704de49d
FM
860 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
861 PAGE_SET_ERROR);
40ae837b 862 free_async_extent_pages(async_extent);
79787eaa 863 kfree(async_extent);
3e04e7f1 864 goto again;
771ed689
CM
865}
866
4b46fce2
JB
867static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
868 u64 num_bytes)
869{
870 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
871 struct extent_map *em;
872 u64 alloc_hint = 0;
873
874 read_lock(&em_tree->lock);
875 em = search_extent_mapping(em_tree, start, num_bytes);
876 if (em) {
877 /*
878 * if block start isn't an actual block number then find the
879 * first block in this inode and use that as a hint. If that
880 * block is also bogus then just don't worry about it.
881 */
882 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
883 free_extent_map(em);
884 em = search_extent_mapping(em_tree, 0, 0);
885 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
886 alloc_hint = em->block_start;
887 if (em)
888 free_extent_map(em);
889 } else {
890 alloc_hint = em->block_start;
891 free_extent_map(em);
892 }
893 }
894 read_unlock(&em_tree->lock);
895
896 return alloc_hint;
897}
898
771ed689
CM
899/*
900 * when extent_io.c finds a delayed allocation range in the file,
901 * the call backs end up in this code. The basic idea is to
902 * allocate extents on disk for the range, and create ordered data structs
903 * in ram to track those extents.
904 *
905 * locked_page is the page that writepage had locked already. We use
906 * it to make sure we don't do extra locks or unlocks.
907 *
908 * *page_started is set to one if we unlock locked_page and do everything
909 * required to start IO on it. It may be clean and already done with
910 * IO when we return.
911 */
00361589
JB
912static noinline int cow_file_range(struct inode *inode,
913 struct page *locked_page,
914 u64 start, u64 end, int *page_started,
915 unsigned long *nr_written,
916 int unlock)
771ed689 917{
00361589 918 struct btrfs_root *root = BTRFS_I(inode)->root;
771ed689
CM
919 u64 alloc_hint = 0;
920 u64 num_bytes;
921 unsigned long ram_size;
922 u64 disk_num_bytes;
923 u64 cur_alloc_size;
924 u64 blocksize = root->sectorsize;
771ed689
CM
925 struct btrfs_key ins;
926 struct extent_map *em;
927 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
928 int ret = 0;
929
02ecd2c2
JB
930 if (btrfs_is_free_space_inode(inode)) {
931 WARN_ON_ONCE(1);
29bce2f3
JB
932 ret = -EINVAL;
933 goto out_unlock;
02ecd2c2 934 }
771ed689 935
fda2832f 936 num_bytes = ALIGN(end - start + 1, blocksize);
771ed689
CM
937 num_bytes = max(blocksize, num_bytes);
938 disk_num_bytes = num_bytes;
771ed689 939
4cb5300b 940 /* if this is a small write inside eof, kick off defrag */
4cb13e5d
LB
941 if (num_bytes < 64 * 1024 &&
942 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
00361589 943 btrfs_add_inode_defrag(NULL, inode);
4cb5300b 944
771ed689
CM
945 if (start == 0) {
946 /* lets try to make an inline extent */
00361589
JB
947 ret = cow_file_range_inline(root, inode, start, end, 0, 0,
948 NULL);
771ed689 949 if (ret == 0) {
c2790a2e
JB
950 extent_clear_unlock_delalloc(inode, start, end, NULL,
951 EXTENT_LOCKED | EXTENT_DELALLOC |
151a41bc 952 EXTENT_DEFRAG, PAGE_UNLOCK |
c2790a2e
JB
953 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
954 PAGE_END_WRITEBACK);
c2167754 955
771ed689
CM
956 *nr_written = *nr_written +
957 (end - start + PAGE_CACHE_SIZE) / PAGE_CACHE_SIZE;
958 *page_started = 1;
771ed689 959 goto out;
79787eaa 960 } else if (ret < 0) {
79787eaa 961 goto out_unlock;
771ed689
CM
962 }
963 }
964
965 BUG_ON(disk_num_bytes >
6c41761f 966 btrfs_super_total_bytes(root->fs_info->super_copy));
771ed689 967
4b46fce2 968 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
771ed689
CM
969 btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
970
d397712b 971 while (disk_num_bytes > 0) {
a791e35e
CM
972 unsigned long op;
973
287a0ab9 974 cur_alloc_size = disk_num_bytes;
00361589 975 ret = btrfs_reserve_extent(root, cur_alloc_size,
771ed689 976 root->sectorsize, 0, alloc_hint,
e570fd27 977 &ins, 1, 1);
00361589 978 if (ret < 0)
79787eaa 979 goto out_unlock;
d397712b 980
172ddd60 981 em = alloc_extent_map();
b9aa55be
LB
982 if (!em) {
983 ret = -ENOMEM;
ace68bac 984 goto out_reserve;
b9aa55be 985 }
e6dcd2dc 986 em->start = start;
445a6944 987 em->orig_start = em->start;
771ed689
CM
988 ram_size = ins.offset;
989 em->len = ins.offset;
2ab28f32
JB
990 em->mod_start = em->start;
991 em->mod_len = em->len;
c8b97818 992
e6dcd2dc 993 em->block_start = ins.objectid;
c8b97818 994 em->block_len = ins.offset;
b4939680 995 em->orig_block_len = ins.offset;
cc95bef6 996 em->ram_bytes = ram_size;
e6dcd2dc 997 em->bdev = root->fs_info->fs_devices->latest_bdev;
7f3c74fb 998 set_bit(EXTENT_FLAG_PINNED, &em->flags);
70c8a91c 999 em->generation = -1;
c8b97818 1000
d397712b 1001 while (1) {
890871be 1002 write_lock(&em_tree->lock);
09a2a8f9 1003 ret = add_extent_mapping(em_tree, em, 1);
890871be 1004 write_unlock(&em_tree->lock);
e6dcd2dc
CM
1005 if (ret != -EEXIST) {
1006 free_extent_map(em);
1007 break;
1008 }
1009 btrfs_drop_extent_cache(inode, start,
c8b97818 1010 start + ram_size - 1, 0);
e6dcd2dc 1011 }
ace68bac
LB
1012 if (ret)
1013 goto out_reserve;
e6dcd2dc 1014
98d20f67 1015 cur_alloc_size = ins.offset;
e6dcd2dc 1016 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
771ed689 1017 ram_size, cur_alloc_size, 0);
ace68bac 1018 if (ret)
d9f85963 1019 goto out_drop_extent_cache;
c8b97818 1020
17d217fe
YZ
1021 if (root->root_key.objectid ==
1022 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1023 ret = btrfs_reloc_clone_csums(inode, start,
1024 cur_alloc_size);
00361589 1025 if (ret)
d9f85963 1026 goto out_drop_extent_cache;
17d217fe
YZ
1027 }
1028
d397712b 1029 if (disk_num_bytes < cur_alloc_size)
3b951516 1030 break;
d397712b 1031
c8b97818
CM
1032 /* we're not doing compressed IO, don't unlock the first
1033 * page (which the caller expects to stay locked), don't
1034 * clear any dirty bits and don't set any writeback bits
8b62b72b
CM
1035 *
1036 * Do set the Private2 bit so we know this page was properly
1037 * setup for writepage
c8b97818 1038 */
c2790a2e
JB
1039 op = unlock ? PAGE_UNLOCK : 0;
1040 op |= PAGE_SET_PRIVATE2;
a791e35e 1041
c2790a2e
JB
1042 extent_clear_unlock_delalloc(inode, start,
1043 start + ram_size - 1, locked_page,
1044 EXTENT_LOCKED | EXTENT_DELALLOC,
1045 op);
c8b97818 1046 disk_num_bytes -= cur_alloc_size;
c59f8951
CM
1047 num_bytes -= cur_alloc_size;
1048 alloc_hint = ins.objectid + ins.offset;
1049 start += cur_alloc_size;
b888db2b 1050 }
79787eaa 1051out:
be20aa9d 1052 return ret;
b7d5b0a8 1053
d9f85963
FM
1054out_drop_extent_cache:
1055 btrfs_drop_extent_cache(inode, start, start + ram_size - 1, 0);
ace68bac 1056out_reserve:
e570fd27 1057 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
79787eaa 1058out_unlock:
c2790a2e 1059 extent_clear_unlock_delalloc(inode, start, end, locked_page,
151a41bc
JB
1060 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
1061 EXTENT_DELALLOC | EXTENT_DEFRAG,
1062 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
1063 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK);
79787eaa 1064 goto out;
771ed689 1065}
c8b97818 1066
771ed689
CM
1067/*
1068 * work queue call back to started compression on a file and pages
1069 */
1070static noinline void async_cow_start(struct btrfs_work *work)
1071{
1072 struct async_cow *async_cow;
1073 int num_added = 0;
1074 async_cow = container_of(work, struct async_cow, work);
1075
1076 compress_file_range(async_cow->inode, async_cow->locked_page,
1077 async_cow->start, async_cow->end, async_cow,
1078 &num_added);
8180ef88 1079 if (num_added == 0) {
cb77fcd8 1080 btrfs_add_delayed_iput(async_cow->inode);
771ed689 1081 async_cow->inode = NULL;
8180ef88 1082 }
771ed689
CM
1083}
1084
1085/*
1086 * work queue call back to submit previously compressed pages
1087 */
1088static noinline void async_cow_submit(struct btrfs_work *work)
1089{
1090 struct async_cow *async_cow;
1091 struct btrfs_root *root;
1092 unsigned long nr_pages;
1093
1094 async_cow = container_of(work, struct async_cow, work);
1095
1096 root = async_cow->root;
1097 nr_pages = (async_cow->end - async_cow->start + PAGE_CACHE_SIZE) >>
1098 PAGE_CACHE_SHIFT;
1099
66657b31 1100 if (atomic_sub_return(nr_pages, &root->fs_info->async_delalloc_pages) <
287082b0 1101 5 * 1024 * 1024 &&
771ed689
CM
1102 waitqueue_active(&root->fs_info->async_submit_wait))
1103 wake_up(&root->fs_info->async_submit_wait);
1104
d397712b 1105 if (async_cow->inode)
771ed689 1106 submit_compressed_extents(async_cow->inode, async_cow);
771ed689 1107}
c8b97818 1108
771ed689
CM
1109static noinline void async_cow_free(struct btrfs_work *work)
1110{
1111 struct async_cow *async_cow;
1112 async_cow = container_of(work, struct async_cow, work);
8180ef88 1113 if (async_cow->inode)
cb77fcd8 1114 btrfs_add_delayed_iput(async_cow->inode);
771ed689
CM
1115 kfree(async_cow);
1116}
1117
1118static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1119 u64 start, u64 end, int *page_started,
1120 unsigned long *nr_written)
1121{
1122 struct async_cow *async_cow;
1123 struct btrfs_root *root = BTRFS_I(inode)->root;
1124 unsigned long nr_pages;
1125 u64 cur_end;
287082b0 1126 int limit = 10 * 1024 * 1024;
771ed689 1127
a3429ab7
CM
1128 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1129 1, 0, NULL, GFP_NOFS);
d397712b 1130 while (start < end) {
771ed689 1131 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
79787eaa 1132 BUG_ON(!async_cow); /* -ENOMEM */
8180ef88 1133 async_cow->inode = igrab(inode);
771ed689
CM
1134 async_cow->root = root;
1135 async_cow->locked_page = locked_page;
1136 async_cow->start = start;
1137
f79707b0
WS
1138 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
1139 !btrfs_test_opt(root, FORCE_COMPRESS))
771ed689
CM
1140 cur_end = end;
1141 else
1142 cur_end = min(end, start + 512 * 1024 - 1);
1143
1144 async_cow->end = cur_end;
1145 INIT_LIST_HEAD(&async_cow->extents);
1146
9e0af237
LB
1147 btrfs_init_work(&async_cow->work,
1148 btrfs_delalloc_helper,
1149 async_cow_start, async_cow_submit,
1150 async_cow_free);
771ed689 1151
771ed689
CM
1152 nr_pages = (cur_end - start + PAGE_CACHE_SIZE) >>
1153 PAGE_CACHE_SHIFT;
1154 atomic_add(nr_pages, &root->fs_info->async_delalloc_pages);
1155
afe3d242
QW
1156 btrfs_queue_work(root->fs_info->delalloc_workers,
1157 &async_cow->work);
771ed689
CM
1158
1159 if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) {
1160 wait_event(root->fs_info->async_submit_wait,
1161 (atomic_read(&root->fs_info->async_delalloc_pages) <
1162 limit));
1163 }
1164
d397712b 1165 while (atomic_read(&root->fs_info->async_submit_draining) &&
771ed689
CM
1166 atomic_read(&root->fs_info->async_delalloc_pages)) {
1167 wait_event(root->fs_info->async_submit_wait,
1168 (atomic_read(&root->fs_info->async_delalloc_pages) ==
1169 0));
1170 }
1171
1172 *nr_written += nr_pages;
1173 start = cur_end + 1;
1174 }
1175 *page_started = 1;
1176 return 0;
be20aa9d
CM
1177}
1178
d397712b 1179static noinline int csum_exist_in_range(struct btrfs_root *root,
17d217fe
YZ
1180 u64 bytenr, u64 num_bytes)
1181{
1182 int ret;
1183 struct btrfs_ordered_sum *sums;
1184 LIST_HEAD(list);
1185
07d400a6 1186 ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr,
a2de733c 1187 bytenr + num_bytes - 1, &list, 0);
17d217fe
YZ
1188 if (ret == 0 && list_empty(&list))
1189 return 0;
1190
1191 while (!list_empty(&list)) {
1192 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1193 list_del(&sums->list);
1194 kfree(sums);
1195 }
1196 return 1;
1197}
1198
d352ac68
CM
1199/*
1200 * when nowcow writeback call back. This checks for snapshots or COW copies
1201 * of the extents that exist in the file, and COWs the file as required.
1202 *
1203 * If no cow copies or snapshots exist, we write directly to the existing
1204 * blocks on disk
1205 */
7f366cfe
CM
1206static noinline int run_delalloc_nocow(struct inode *inode,
1207 struct page *locked_page,
771ed689
CM
1208 u64 start, u64 end, int *page_started, int force,
1209 unsigned long *nr_written)
be20aa9d 1210{
be20aa9d 1211 struct btrfs_root *root = BTRFS_I(inode)->root;
7ea394f1 1212 struct btrfs_trans_handle *trans;
be20aa9d 1213 struct extent_buffer *leaf;
be20aa9d 1214 struct btrfs_path *path;
80ff3856 1215 struct btrfs_file_extent_item *fi;
be20aa9d 1216 struct btrfs_key found_key;
80ff3856
YZ
1217 u64 cow_start;
1218 u64 cur_offset;
1219 u64 extent_end;
5d4f98a2 1220 u64 extent_offset;
80ff3856
YZ
1221 u64 disk_bytenr;
1222 u64 num_bytes;
b4939680 1223 u64 disk_num_bytes;
cc95bef6 1224 u64 ram_bytes;
80ff3856 1225 int extent_type;
79787eaa 1226 int ret, err;
d899e052 1227 int type;
80ff3856
YZ
1228 int nocow;
1229 int check_prev = 1;
82d5902d 1230 bool nolock;
33345d01 1231 u64 ino = btrfs_ino(inode);
be20aa9d
CM
1232
1233 path = btrfs_alloc_path();
17ca04af 1234 if (!path) {
c2790a2e
JB
1235 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1236 EXTENT_LOCKED | EXTENT_DELALLOC |
151a41bc
JB
1237 EXTENT_DO_ACCOUNTING |
1238 EXTENT_DEFRAG, PAGE_UNLOCK |
c2790a2e
JB
1239 PAGE_CLEAR_DIRTY |
1240 PAGE_SET_WRITEBACK |
1241 PAGE_END_WRITEBACK);
d8926bb3 1242 return -ENOMEM;
17ca04af 1243 }
82d5902d 1244
83eea1f1 1245 nolock = btrfs_is_free_space_inode(inode);
82d5902d
LZ
1246
1247 if (nolock)
7a7eaa40 1248 trans = btrfs_join_transaction_nolock(root);
82d5902d 1249 else
7a7eaa40 1250 trans = btrfs_join_transaction(root);
ff5714cc 1251
79787eaa 1252 if (IS_ERR(trans)) {
c2790a2e
JB
1253 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1254 EXTENT_LOCKED | EXTENT_DELALLOC |
151a41bc
JB
1255 EXTENT_DO_ACCOUNTING |
1256 EXTENT_DEFRAG, PAGE_UNLOCK |
c2790a2e
JB
1257 PAGE_CLEAR_DIRTY |
1258 PAGE_SET_WRITEBACK |
1259 PAGE_END_WRITEBACK);
79787eaa
JM
1260 btrfs_free_path(path);
1261 return PTR_ERR(trans);
1262 }
1263
74b21075 1264 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
be20aa9d 1265
80ff3856
YZ
1266 cow_start = (u64)-1;
1267 cur_offset = start;
1268 while (1) {
33345d01 1269 ret = btrfs_lookup_file_extent(trans, root, path, ino,
80ff3856 1270 cur_offset, 0);
d788a349 1271 if (ret < 0)
79787eaa 1272 goto error;
80ff3856
YZ
1273 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1274 leaf = path->nodes[0];
1275 btrfs_item_key_to_cpu(leaf, &found_key,
1276 path->slots[0] - 1);
33345d01 1277 if (found_key.objectid == ino &&
80ff3856
YZ
1278 found_key.type == BTRFS_EXTENT_DATA_KEY)
1279 path->slots[0]--;
1280 }
1281 check_prev = 0;
1282next_slot:
1283 leaf = path->nodes[0];
1284 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1285 ret = btrfs_next_leaf(root, path);
d788a349 1286 if (ret < 0)
79787eaa 1287 goto error;
80ff3856
YZ
1288 if (ret > 0)
1289 break;
1290 leaf = path->nodes[0];
1291 }
be20aa9d 1292
80ff3856
YZ
1293 nocow = 0;
1294 disk_bytenr = 0;
17d217fe 1295 num_bytes = 0;
80ff3856
YZ
1296 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1297
33345d01 1298 if (found_key.objectid > ino ||
80ff3856
YZ
1299 found_key.type > BTRFS_EXTENT_DATA_KEY ||
1300 found_key.offset > end)
1301 break;
1302
1303 if (found_key.offset > cur_offset) {
1304 extent_end = found_key.offset;
e9061e21 1305 extent_type = 0;
80ff3856
YZ
1306 goto out_check;
1307 }
1308
1309 fi = btrfs_item_ptr(leaf, path->slots[0],
1310 struct btrfs_file_extent_item);
1311 extent_type = btrfs_file_extent_type(leaf, fi);
1312
cc95bef6 1313 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
d899e052
YZ
1314 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1315 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
80ff3856 1316 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
5d4f98a2 1317 extent_offset = btrfs_file_extent_offset(leaf, fi);
80ff3856
YZ
1318 extent_end = found_key.offset +
1319 btrfs_file_extent_num_bytes(leaf, fi);
b4939680
JB
1320 disk_num_bytes =
1321 btrfs_file_extent_disk_num_bytes(leaf, fi);
80ff3856
YZ
1322 if (extent_end <= start) {
1323 path->slots[0]++;
1324 goto next_slot;
1325 }
17d217fe
YZ
1326 if (disk_bytenr == 0)
1327 goto out_check;
80ff3856
YZ
1328 if (btrfs_file_extent_compression(leaf, fi) ||
1329 btrfs_file_extent_encryption(leaf, fi) ||
1330 btrfs_file_extent_other_encoding(leaf, fi))
1331 goto out_check;
d899e052
YZ
1332 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1333 goto out_check;
d2fb3437 1334 if (btrfs_extent_readonly(root, disk_bytenr))
80ff3856 1335 goto out_check;
33345d01 1336 if (btrfs_cross_ref_exist(trans, root, ino,
5d4f98a2
YZ
1337 found_key.offset -
1338 extent_offset, disk_bytenr))
17d217fe 1339 goto out_check;
5d4f98a2 1340 disk_bytenr += extent_offset;
17d217fe
YZ
1341 disk_bytenr += cur_offset - found_key.offset;
1342 num_bytes = min(end + 1, extent_end) - cur_offset;
e9894fd3
WS
1343 /*
1344 * if there are pending snapshots for this root,
1345 * we fall into common COW way.
1346 */
1347 if (!nolock) {
9ea24bbe 1348 err = btrfs_start_write_no_snapshoting(root);
e9894fd3
WS
1349 if (!err)
1350 goto out_check;
1351 }
17d217fe
YZ
1352 /*
1353 * force cow if csum exists in the range.
1354 * this ensure that csum for a given extent are
1355 * either valid or do not exist.
1356 */
1357 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
1358 goto out_check;
80ff3856
YZ
1359 nocow = 1;
1360 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1361 extent_end = found_key.offset +
514ac8ad
CM
1362 btrfs_file_extent_inline_len(leaf,
1363 path->slots[0], fi);
80ff3856
YZ
1364 extent_end = ALIGN(extent_end, root->sectorsize);
1365 } else {
1366 BUG_ON(1);
1367 }
1368out_check:
1369 if (extent_end <= start) {
1370 path->slots[0]++;
e9894fd3 1371 if (!nolock && nocow)
9ea24bbe 1372 btrfs_end_write_no_snapshoting(root);
80ff3856
YZ
1373 goto next_slot;
1374 }
1375 if (!nocow) {
1376 if (cow_start == (u64)-1)
1377 cow_start = cur_offset;
1378 cur_offset = extent_end;
1379 if (cur_offset > end)
1380 break;
1381 path->slots[0]++;
1382 goto next_slot;
7ea394f1
YZ
1383 }
1384
b3b4aa74 1385 btrfs_release_path(path);
80ff3856 1386 if (cow_start != (u64)-1) {
00361589
JB
1387 ret = cow_file_range(inode, locked_page,
1388 cow_start, found_key.offset - 1,
1389 page_started, nr_written, 1);
e9894fd3
WS
1390 if (ret) {
1391 if (!nolock && nocow)
9ea24bbe 1392 btrfs_end_write_no_snapshoting(root);
79787eaa 1393 goto error;
e9894fd3 1394 }
80ff3856 1395 cow_start = (u64)-1;
7ea394f1 1396 }
80ff3856 1397
d899e052
YZ
1398 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1399 struct extent_map *em;
1400 struct extent_map_tree *em_tree;
1401 em_tree = &BTRFS_I(inode)->extent_tree;
172ddd60 1402 em = alloc_extent_map();
79787eaa 1403 BUG_ON(!em); /* -ENOMEM */
d899e052 1404 em->start = cur_offset;
70c8a91c 1405 em->orig_start = found_key.offset - extent_offset;
d899e052
YZ
1406 em->len = num_bytes;
1407 em->block_len = num_bytes;
1408 em->block_start = disk_bytenr;
b4939680 1409 em->orig_block_len = disk_num_bytes;
cc95bef6 1410 em->ram_bytes = ram_bytes;
d899e052 1411 em->bdev = root->fs_info->fs_devices->latest_bdev;
2ab28f32
JB
1412 em->mod_start = em->start;
1413 em->mod_len = em->len;
d899e052 1414 set_bit(EXTENT_FLAG_PINNED, &em->flags);
b11e234d 1415 set_bit(EXTENT_FLAG_FILLING, &em->flags);
70c8a91c 1416 em->generation = -1;
d899e052 1417 while (1) {
890871be 1418 write_lock(&em_tree->lock);
09a2a8f9 1419 ret = add_extent_mapping(em_tree, em, 1);
890871be 1420 write_unlock(&em_tree->lock);
d899e052
YZ
1421 if (ret != -EEXIST) {
1422 free_extent_map(em);
1423 break;
1424 }
1425 btrfs_drop_extent_cache(inode, em->start,
1426 em->start + em->len - 1, 0);
1427 }
1428 type = BTRFS_ORDERED_PREALLOC;
1429 } else {
1430 type = BTRFS_ORDERED_NOCOW;
1431 }
80ff3856
YZ
1432
1433 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
d899e052 1434 num_bytes, num_bytes, type);
79787eaa 1435 BUG_ON(ret); /* -ENOMEM */
771ed689 1436
efa56464
YZ
1437 if (root->root_key.objectid ==
1438 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1439 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1440 num_bytes);
e9894fd3
WS
1441 if (ret) {
1442 if (!nolock && nocow)
9ea24bbe 1443 btrfs_end_write_no_snapshoting(root);
79787eaa 1444 goto error;
e9894fd3 1445 }
efa56464
YZ
1446 }
1447
c2790a2e
JB
1448 extent_clear_unlock_delalloc(inode, cur_offset,
1449 cur_offset + num_bytes - 1,
1450 locked_page, EXTENT_LOCKED |
1451 EXTENT_DELALLOC, PAGE_UNLOCK |
1452 PAGE_SET_PRIVATE2);
e9894fd3 1453 if (!nolock && nocow)
9ea24bbe 1454 btrfs_end_write_no_snapshoting(root);
80ff3856
YZ
1455 cur_offset = extent_end;
1456 if (cur_offset > end)
1457 break;
be20aa9d 1458 }
b3b4aa74 1459 btrfs_release_path(path);
80ff3856 1460
17ca04af 1461 if (cur_offset <= end && cow_start == (u64)-1) {
80ff3856 1462 cow_start = cur_offset;
17ca04af
JB
1463 cur_offset = end;
1464 }
1465
80ff3856 1466 if (cow_start != (u64)-1) {
00361589
JB
1467 ret = cow_file_range(inode, locked_page, cow_start, end,
1468 page_started, nr_written, 1);
d788a349 1469 if (ret)
79787eaa 1470 goto error;
80ff3856
YZ
1471 }
1472
79787eaa 1473error:
a698d075 1474 err = btrfs_end_transaction(trans, root);
79787eaa
JM
1475 if (!ret)
1476 ret = err;
1477
17ca04af 1478 if (ret && cur_offset < end)
c2790a2e
JB
1479 extent_clear_unlock_delalloc(inode, cur_offset, end,
1480 locked_page, EXTENT_LOCKED |
151a41bc
JB
1481 EXTENT_DELALLOC | EXTENT_DEFRAG |
1482 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1483 PAGE_CLEAR_DIRTY |
c2790a2e
JB
1484 PAGE_SET_WRITEBACK |
1485 PAGE_END_WRITEBACK);
7ea394f1 1486 btrfs_free_path(path);
79787eaa 1487 return ret;
be20aa9d
CM
1488}
1489
47059d93
WS
1490static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1491{
1492
1493 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1494 !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1495 return 0;
1496
1497 /*
1498 * @defrag_bytes is a hint value, no spinlock held here,
1499 * if is not zero, it means the file is defragging.
1500 * Force cow if given extent needs to be defragged.
1501 */
1502 if (BTRFS_I(inode)->defrag_bytes &&
1503 test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1504 EXTENT_DEFRAG, 0, NULL))
1505 return 1;
1506
1507 return 0;
1508}
1509
d352ac68
CM
1510/*
1511 * extent_io.c call back to do delayed allocation processing
1512 */
c8b97818 1513static int run_delalloc_range(struct inode *inode, struct page *locked_page,
771ed689
CM
1514 u64 start, u64 end, int *page_started,
1515 unsigned long *nr_written)
be20aa9d 1516{
be20aa9d 1517 int ret;
47059d93 1518 int force_cow = need_force_cow(inode, start, end);
a2135011 1519
47059d93 1520 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
c8b97818 1521 ret = run_delalloc_nocow(inode, locked_page, start, end,
d397712b 1522 page_started, 1, nr_written);
47059d93 1523 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
d899e052 1524 ret = run_delalloc_nocow(inode, locked_page, start, end,
d397712b 1525 page_started, 0, nr_written);
7816030e 1526 } else if (!inode_need_compress(inode)) {
7f366cfe
CM
1527 ret = cow_file_range(inode, locked_page, start, end,
1528 page_started, nr_written, 1);
7ddf5a42
JB
1529 } else {
1530 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1531 &BTRFS_I(inode)->runtime_flags);
771ed689 1532 ret = cow_file_range_async(inode, locked_page, start, end,
d397712b 1533 page_started, nr_written);
7ddf5a42 1534 }
b888db2b
CM
1535 return ret;
1536}
1537
1bf85046
JM
1538static void btrfs_split_extent_hook(struct inode *inode,
1539 struct extent_state *orig, u64 split)
9ed74f2d 1540{
dcab6a3b
JB
1541 u64 size;
1542
0ca1f7ce 1543 /* not delalloc, ignore it */
9ed74f2d 1544 if (!(orig->state & EXTENT_DELALLOC))
1bf85046 1545 return;
9ed74f2d 1546
dcab6a3b
JB
1547 size = orig->end - orig->start + 1;
1548 if (size > BTRFS_MAX_EXTENT_SIZE) {
1549 u64 num_extents;
1550 u64 new_size;
1551
1552 /*
ba117213
JB
1553 * See the explanation in btrfs_merge_extent_hook, the same
1554 * applies here, just in reverse.
dcab6a3b
JB
1555 */
1556 new_size = orig->end - split + 1;
ba117213 1557 num_extents = div64_u64(new_size + BTRFS_MAX_EXTENT_SIZE - 1,
dcab6a3b 1558 BTRFS_MAX_EXTENT_SIZE);
ba117213
JB
1559 new_size = split - orig->start;
1560 num_extents += div64_u64(new_size + BTRFS_MAX_EXTENT_SIZE - 1,
1561 BTRFS_MAX_EXTENT_SIZE);
1562 if (div64_u64(size + BTRFS_MAX_EXTENT_SIZE - 1,
1563 BTRFS_MAX_EXTENT_SIZE) >= num_extents)
dcab6a3b
JB
1564 return;
1565 }
1566
9e0baf60
JB
1567 spin_lock(&BTRFS_I(inode)->lock);
1568 BTRFS_I(inode)->outstanding_extents++;
1569 spin_unlock(&BTRFS_I(inode)->lock);
9ed74f2d
JB
1570}
1571
1572/*
1573 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1574 * extents so we can keep track of new extents that are just merged onto old
1575 * extents, such as when we are doing sequential writes, so we can properly
1576 * account for the metadata space we'll need.
1577 */
1bf85046
JM
1578static void btrfs_merge_extent_hook(struct inode *inode,
1579 struct extent_state *new,
1580 struct extent_state *other)
9ed74f2d 1581{
dcab6a3b
JB
1582 u64 new_size, old_size;
1583 u64 num_extents;
1584
9ed74f2d
JB
1585 /* not delalloc, ignore it */
1586 if (!(other->state & EXTENT_DELALLOC))
1bf85046 1587 return;
9ed74f2d 1588
8461a3de
JB
1589 if (new->start > other->start)
1590 new_size = new->end - other->start + 1;
1591 else
1592 new_size = other->end - new->start + 1;
dcab6a3b
JB
1593
1594 /* we're not bigger than the max, unreserve the space and go */
1595 if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1596 spin_lock(&BTRFS_I(inode)->lock);
1597 BTRFS_I(inode)->outstanding_extents--;
1598 spin_unlock(&BTRFS_I(inode)->lock);
1599 return;
1600 }
1601
1602 /*
ba117213
JB
1603 * We have to add up either side to figure out how many extents were
1604 * accounted for before we merged into one big extent. If the number of
1605 * extents we accounted for is <= the amount we need for the new range
1606 * then we can return, otherwise drop. Think of it like this
1607 *
1608 * [ 4k][MAX_SIZE]
1609 *
1610 * So we've grown the extent by a MAX_SIZE extent, this would mean we
1611 * need 2 outstanding extents, on one side we have 1 and the other side
1612 * we have 1 so they are == and we can return. But in this case
1613 *
1614 * [MAX_SIZE+4k][MAX_SIZE+4k]
1615 *
1616 * Each range on their own accounts for 2 extents, but merged together
1617 * they are only 3 extents worth of accounting, so we need to drop in
1618 * this case.
dcab6a3b 1619 */
ba117213 1620 old_size = other->end - other->start + 1;
dcab6a3b
JB
1621 num_extents = div64_u64(old_size + BTRFS_MAX_EXTENT_SIZE - 1,
1622 BTRFS_MAX_EXTENT_SIZE);
ba117213
JB
1623 old_size = new->end - new->start + 1;
1624 num_extents += div64_u64(old_size + BTRFS_MAX_EXTENT_SIZE - 1,
1625 BTRFS_MAX_EXTENT_SIZE);
1626
dcab6a3b 1627 if (div64_u64(new_size + BTRFS_MAX_EXTENT_SIZE - 1,
ba117213 1628 BTRFS_MAX_EXTENT_SIZE) >= num_extents)
dcab6a3b
JB
1629 return;
1630
9e0baf60
JB
1631 spin_lock(&BTRFS_I(inode)->lock);
1632 BTRFS_I(inode)->outstanding_extents--;
1633 spin_unlock(&BTRFS_I(inode)->lock);
9ed74f2d
JB
1634}
1635
eb73c1b7
MX
1636static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1637 struct inode *inode)
1638{
1639 spin_lock(&root->delalloc_lock);
1640 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1641 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1642 &root->delalloc_inodes);
1643 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1644 &BTRFS_I(inode)->runtime_flags);
1645 root->nr_delalloc_inodes++;
1646 if (root->nr_delalloc_inodes == 1) {
1647 spin_lock(&root->fs_info->delalloc_root_lock);
1648 BUG_ON(!list_empty(&root->delalloc_root));
1649 list_add_tail(&root->delalloc_root,
1650 &root->fs_info->delalloc_roots);
1651 spin_unlock(&root->fs_info->delalloc_root_lock);
1652 }
1653 }
1654 spin_unlock(&root->delalloc_lock);
1655}
1656
1657static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1658 struct inode *inode)
1659{
1660 spin_lock(&root->delalloc_lock);
1661 if (!list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1662 list_del_init(&BTRFS_I(inode)->delalloc_inodes);
1663 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1664 &BTRFS_I(inode)->runtime_flags);
1665 root->nr_delalloc_inodes--;
1666 if (!root->nr_delalloc_inodes) {
1667 spin_lock(&root->fs_info->delalloc_root_lock);
1668 BUG_ON(list_empty(&root->delalloc_root));
1669 list_del_init(&root->delalloc_root);
1670 spin_unlock(&root->fs_info->delalloc_root_lock);
1671 }
1672 }
1673 spin_unlock(&root->delalloc_lock);
1674}
1675
d352ac68
CM
1676/*
1677 * extent_io.c set_bit_hook, used to track delayed allocation
1678 * bytes in this file, and to maintain the list of inodes that
1679 * have pending delalloc work to be done.
1680 */
1bf85046 1681static void btrfs_set_bit_hook(struct inode *inode,
9ee49a04 1682 struct extent_state *state, unsigned *bits)
291d673e 1683{
9ed74f2d 1684
47059d93
WS
1685 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1686 WARN_ON(1);
75eff68e
CM
1687 /*
1688 * set_bit and clear bit hooks normally require _irqsave/restore
27160b6b 1689 * but in this case, we are only testing for the DELALLOC
75eff68e
CM
1690 * bit, which is only set or cleared with irqs on
1691 */
0ca1f7ce 1692 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
291d673e 1693 struct btrfs_root *root = BTRFS_I(inode)->root;
0ca1f7ce 1694 u64 len = state->end + 1 - state->start;
83eea1f1 1695 bool do_list = !btrfs_is_free_space_inode(inode);
9ed74f2d 1696
9e0baf60 1697 if (*bits & EXTENT_FIRST_DELALLOC) {
0ca1f7ce 1698 *bits &= ~EXTENT_FIRST_DELALLOC;
9e0baf60
JB
1699 } else {
1700 spin_lock(&BTRFS_I(inode)->lock);
1701 BTRFS_I(inode)->outstanding_extents++;
1702 spin_unlock(&BTRFS_I(inode)->lock);
1703 }
287a0ab9 1704
6a3891c5
JB
1705 /* For sanity tests */
1706 if (btrfs_test_is_dummy_root(root))
1707 return;
1708
963d678b
MX
1709 __percpu_counter_add(&root->fs_info->delalloc_bytes, len,
1710 root->fs_info->delalloc_batch);
df0af1a5 1711 spin_lock(&BTRFS_I(inode)->lock);
0ca1f7ce 1712 BTRFS_I(inode)->delalloc_bytes += len;
47059d93
WS
1713 if (*bits & EXTENT_DEFRAG)
1714 BTRFS_I(inode)->defrag_bytes += len;
df0af1a5 1715 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
eb73c1b7
MX
1716 &BTRFS_I(inode)->runtime_flags))
1717 btrfs_add_delalloc_inodes(root, inode);
df0af1a5 1718 spin_unlock(&BTRFS_I(inode)->lock);
291d673e 1719 }
291d673e
CM
1720}
1721
d352ac68
CM
1722/*
1723 * extent_io.c clear_bit_hook, see set_bit_hook for why
1724 */
1bf85046 1725static void btrfs_clear_bit_hook(struct inode *inode,
41074888 1726 struct extent_state *state,
9ee49a04 1727 unsigned *bits)
291d673e 1728{
47059d93 1729 u64 len = state->end + 1 - state->start;
dcab6a3b
JB
1730 u64 num_extents = div64_u64(len + BTRFS_MAX_EXTENT_SIZE -1,
1731 BTRFS_MAX_EXTENT_SIZE);
47059d93
WS
1732
1733 spin_lock(&BTRFS_I(inode)->lock);
1734 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG))
1735 BTRFS_I(inode)->defrag_bytes -= len;
1736 spin_unlock(&BTRFS_I(inode)->lock);
1737
75eff68e
CM
1738 /*
1739 * set_bit and clear bit hooks normally require _irqsave/restore
27160b6b 1740 * but in this case, we are only testing for the DELALLOC
75eff68e
CM
1741 * bit, which is only set or cleared with irqs on
1742 */
0ca1f7ce 1743 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
291d673e 1744 struct btrfs_root *root = BTRFS_I(inode)->root;
83eea1f1 1745 bool do_list = !btrfs_is_free_space_inode(inode);
bcbfce8a 1746
9e0baf60 1747 if (*bits & EXTENT_FIRST_DELALLOC) {
0ca1f7ce 1748 *bits &= ~EXTENT_FIRST_DELALLOC;
9e0baf60
JB
1749 } else if (!(*bits & EXTENT_DO_ACCOUNTING)) {
1750 spin_lock(&BTRFS_I(inode)->lock);
dcab6a3b 1751 BTRFS_I(inode)->outstanding_extents -= num_extents;
9e0baf60
JB
1752 spin_unlock(&BTRFS_I(inode)->lock);
1753 }
0ca1f7ce 1754
b6d08f06
JB
1755 /*
1756 * We don't reserve metadata space for space cache inodes so we
1757 * don't need to call dellalloc_release_metadata if there is an
1758 * error.
1759 */
1760 if (*bits & EXTENT_DO_ACCOUNTING &&
1761 root != root->fs_info->tree_root)
0ca1f7ce
YZ
1762 btrfs_delalloc_release_metadata(inode, len);
1763
6a3891c5
JB
1764 /* For sanity tests. */
1765 if (btrfs_test_is_dummy_root(root))
1766 return;
1767
0cb59c99 1768 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
7ee9e440 1769 && do_list && !(state->state & EXTENT_NORESERVE))
0ca1f7ce 1770 btrfs_free_reserved_data_space(inode, len);
9ed74f2d 1771
963d678b
MX
1772 __percpu_counter_add(&root->fs_info->delalloc_bytes, -len,
1773 root->fs_info->delalloc_batch);
df0af1a5 1774 spin_lock(&BTRFS_I(inode)->lock);
0ca1f7ce 1775 BTRFS_I(inode)->delalloc_bytes -= len;
0cb59c99 1776 if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 &&
df0af1a5 1777 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
eb73c1b7
MX
1778 &BTRFS_I(inode)->runtime_flags))
1779 btrfs_del_delalloc_inode(root, inode);
df0af1a5 1780 spin_unlock(&BTRFS_I(inode)->lock);
291d673e 1781 }
291d673e
CM
1782}
1783
d352ac68
CM
1784/*
1785 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1786 * we don't create bios that span stripes or chunks
1787 */
64a16701 1788int btrfs_merge_bio_hook(int rw, struct page *page, unsigned long offset,
c8b97818
CM
1789 size_t size, struct bio *bio,
1790 unsigned long bio_flags)
239b14b3
CM
1791{
1792 struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
4f024f37 1793 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
239b14b3
CM
1794 u64 length = 0;
1795 u64 map_length;
239b14b3
CM
1796 int ret;
1797
771ed689
CM
1798 if (bio_flags & EXTENT_BIO_COMPRESSED)
1799 return 0;
1800
4f024f37 1801 length = bio->bi_iter.bi_size;
239b14b3 1802 map_length = length;
64a16701 1803 ret = btrfs_map_block(root->fs_info, rw, logical,
f188591e 1804 &map_length, NULL, 0);
3ec706c8 1805 /* Will always return 0 with map_multi == NULL */
3444a972 1806 BUG_ON(ret < 0);
d397712b 1807 if (map_length < length + size)
239b14b3 1808 return 1;
3444a972 1809 return 0;
239b14b3
CM
1810}
1811
d352ac68
CM
1812/*
1813 * in order to insert checksums into the metadata in large chunks,
1814 * we wait until bio submission time. All the pages in the bio are
1815 * checksummed and sums are attached onto the ordered extent record.
1816 *
1817 * At IO completion time the cums attached on the ordered extent record
1818 * are inserted into the btree
1819 */
d397712b
CM
1820static int __btrfs_submit_bio_start(struct inode *inode, int rw,
1821 struct bio *bio, int mirror_num,
eaf25d93
CM
1822 unsigned long bio_flags,
1823 u64 bio_offset)
065631f6 1824{
065631f6 1825 struct btrfs_root *root = BTRFS_I(inode)->root;
065631f6 1826 int ret = 0;
e015640f 1827
d20f7043 1828 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
79787eaa 1829 BUG_ON(ret); /* -ENOMEM */
4a69a410
CM
1830 return 0;
1831}
e015640f 1832
4a69a410
CM
1833/*
1834 * in order to insert checksums into the metadata in large chunks,
1835 * we wait until bio submission time. All the pages in the bio are
1836 * checksummed and sums are attached onto the ordered extent record.
1837 *
1838 * At IO completion time the cums attached on the ordered extent record
1839 * are inserted into the btree
1840 */
b2950863 1841static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
eaf25d93
CM
1842 int mirror_num, unsigned long bio_flags,
1843 u64 bio_offset)
4a69a410
CM
1844{
1845 struct btrfs_root *root = BTRFS_I(inode)->root;
61891923
SB
1846 int ret;
1847
1848 ret = btrfs_map_bio(root, rw, bio, mirror_num, 1);
1849 if (ret)
1850 bio_endio(bio, ret);
1851 return ret;
44b8bd7e
CM
1852}
1853
d352ac68 1854/*
cad321ad
CM
1855 * extent_io.c submission hook. This does the right thing for csum calculation
1856 * on write, or reading the csums from the tree before a read
d352ac68 1857 */
b2950863 1858static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
eaf25d93
CM
1859 int mirror_num, unsigned long bio_flags,
1860 u64 bio_offset)
44b8bd7e
CM
1861{
1862 struct btrfs_root *root = BTRFS_I(inode)->root;
1863 int ret = 0;
19b9bdb0 1864 int skip_sum;
0417341e 1865 int metadata = 0;
b812ce28 1866 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
44b8bd7e 1867
6cbff00f 1868 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
cad321ad 1869
83eea1f1 1870 if (btrfs_is_free_space_inode(inode))
0417341e
JM
1871 metadata = 2;
1872
7b6d91da 1873 if (!(rw & REQ_WRITE)) {
5fd02043
JB
1874 ret = btrfs_bio_wq_end_io(root->fs_info, bio, metadata);
1875 if (ret)
61891923 1876 goto out;
5fd02043 1877
d20f7043 1878 if (bio_flags & EXTENT_BIO_COMPRESSED) {
61891923
SB
1879 ret = btrfs_submit_compressed_read(inode, bio,
1880 mirror_num,
1881 bio_flags);
1882 goto out;
c2db1073
TI
1883 } else if (!skip_sum) {
1884 ret = btrfs_lookup_bio_sums(root, inode, bio, NULL);
1885 if (ret)
61891923 1886 goto out;
c2db1073 1887 }
4d1b5fb4 1888 goto mapit;
b812ce28 1889 } else if (async && !skip_sum) {
17d217fe
YZ
1890 /* csum items have already been cloned */
1891 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1892 goto mapit;
19b9bdb0 1893 /* we're doing a write, do the async checksumming */
61891923 1894 ret = btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
44b8bd7e 1895 inode, rw, bio, mirror_num,
eaf25d93
CM
1896 bio_flags, bio_offset,
1897 __btrfs_submit_bio_start,
4a69a410 1898 __btrfs_submit_bio_done);
61891923 1899 goto out;
b812ce28
JB
1900 } else if (!skip_sum) {
1901 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1902 if (ret)
1903 goto out;
19b9bdb0
CM
1904 }
1905
0b86a832 1906mapit:
61891923
SB
1907 ret = btrfs_map_bio(root, rw, bio, mirror_num, 0);
1908
1909out:
1910 if (ret < 0)
1911 bio_endio(bio, ret);
1912 return ret;
065631f6 1913}
6885f308 1914
d352ac68
CM
1915/*
1916 * given a list of ordered sums record them in the inode. This happens
1917 * at IO completion time based on sums calculated at bio submission time.
1918 */
ba1da2f4 1919static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
e6dcd2dc
CM
1920 struct inode *inode, u64 file_offset,
1921 struct list_head *list)
1922{
e6dcd2dc
CM
1923 struct btrfs_ordered_sum *sum;
1924
c6e30871 1925 list_for_each_entry(sum, list, list) {
39847c4d 1926 trans->adding_csums = 1;
d20f7043
CM
1927 btrfs_csum_file_blocks(trans,
1928 BTRFS_I(inode)->root->fs_info->csum_root, sum);
39847c4d 1929 trans->adding_csums = 0;
e6dcd2dc
CM
1930 }
1931 return 0;
1932}
1933
2ac55d41
JB
1934int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
1935 struct extent_state **cached_state)
ea8c2819 1936{
6c1500f2 1937 WARN_ON((end & (PAGE_CACHE_SIZE - 1)) == 0);
ea8c2819 1938 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
2ac55d41 1939 cached_state, GFP_NOFS);
ea8c2819
CM
1940}
1941
d352ac68 1942/* see btrfs_writepage_start_hook for details on why this is required */
247e743c
CM
1943struct btrfs_writepage_fixup {
1944 struct page *page;
1945 struct btrfs_work work;
1946};
1947
b2950863 1948static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
247e743c
CM
1949{
1950 struct btrfs_writepage_fixup *fixup;
1951 struct btrfs_ordered_extent *ordered;
2ac55d41 1952 struct extent_state *cached_state = NULL;
247e743c
CM
1953 struct page *page;
1954 struct inode *inode;
1955 u64 page_start;
1956 u64 page_end;
87826df0 1957 int ret;
247e743c
CM
1958
1959 fixup = container_of(work, struct btrfs_writepage_fixup, work);
1960 page = fixup->page;
4a096752 1961again:
247e743c
CM
1962 lock_page(page);
1963 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
1964 ClearPageChecked(page);
1965 goto out_page;
1966 }
1967
1968 inode = page->mapping->host;
1969 page_start = page_offset(page);
1970 page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
1971
2ac55d41 1972 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end, 0,
d0082371 1973 &cached_state);
4a096752
CM
1974
1975 /* already ordered? We're done */
8b62b72b 1976 if (PagePrivate2(page))
247e743c 1977 goto out;
4a096752
CM
1978
1979 ordered = btrfs_lookup_ordered_extent(inode, page_start);
1980 if (ordered) {
2ac55d41
JB
1981 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
1982 page_end, &cached_state, GFP_NOFS);
4a096752
CM
1983 unlock_page(page);
1984 btrfs_start_ordered_extent(inode, ordered, 1);
87826df0 1985 btrfs_put_ordered_extent(ordered);
4a096752
CM
1986 goto again;
1987 }
247e743c 1988
87826df0
JM
1989 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
1990 if (ret) {
1991 mapping_set_error(page->mapping, ret);
1992 end_extent_writepage(page, ret, page_start, page_end);
1993 ClearPageChecked(page);
1994 goto out;
1995 }
1996
2ac55d41 1997 btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state);
247e743c 1998 ClearPageChecked(page);
87826df0 1999 set_page_dirty(page);
247e743c 2000out:
2ac55d41
JB
2001 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
2002 &cached_state, GFP_NOFS);
247e743c
CM
2003out_page:
2004 unlock_page(page);
2005 page_cache_release(page);
b897abec 2006 kfree(fixup);
247e743c
CM
2007}
2008
2009/*
2010 * There are a few paths in the higher layers of the kernel that directly
2011 * set the page dirty bit without asking the filesystem if it is a
2012 * good idea. This causes problems because we want to make sure COW
2013 * properly happens and the data=ordered rules are followed.
2014 *
c8b97818 2015 * In our case any range that doesn't have the ORDERED bit set
247e743c
CM
2016 * hasn't been properly setup for IO. We kick off an async process
2017 * to fix it up. The async helper will wait for ordered extents, set
2018 * the delalloc bit and make it safe to write the page.
2019 */
b2950863 2020static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
247e743c
CM
2021{
2022 struct inode *inode = page->mapping->host;
2023 struct btrfs_writepage_fixup *fixup;
2024 struct btrfs_root *root = BTRFS_I(inode)->root;
247e743c 2025
8b62b72b
CM
2026 /* this page is properly in the ordered list */
2027 if (TestClearPagePrivate2(page))
247e743c
CM
2028 return 0;
2029
2030 if (PageChecked(page))
2031 return -EAGAIN;
2032
2033 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2034 if (!fixup)
2035 return -EAGAIN;
f421950f 2036
247e743c
CM
2037 SetPageChecked(page);
2038 page_cache_get(page);
9e0af237
LB
2039 btrfs_init_work(&fixup->work, btrfs_fixup_helper,
2040 btrfs_writepage_fixup_worker, NULL, NULL);
247e743c 2041 fixup->page = page;
dc6e3209 2042 btrfs_queue_work(root->fs_info->fixup_workers, &fixup->work);
87826df0 2043 return -EBUSY;
247e743c
CM
2044}
2045
d899e052
YZ
2046static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2047 struct inode *inode, u64 file_pos,
2048 u64 disk_bytenr, u64 disk_num_bytes,
2049 u64 num_bytes, u64 ram_bytes,
2050 u8 compression, u8 encryption,
2051 u16 other_encoding, int extent_type)
2052{
2053 struct btrfs_root *root = BTRFS_I(inode)->root;
2054 struct btrfs_file_extent_item *fi;
2055 struct btrfs_path *path;
2056 struct extent_buffer *leaf;
2057 struct btrfs_key ins;
1acae57b 2058 int extent_inserted = 0;
d899e052
YZ
2059 int ret;
2060
2061 path = btrfs_alloc_path();
d8926bb3
MF
2062 if (!path)
2063 return -ENOMEM;
d899e052 2064
a1ed835e
CM
2065 /*
2066 * we may be replacing one extent in the tree with another.
2067 * The new extent is pinned in the extent map, and we don't want
2068 * to drop it from the cache until it is completely in the btree.
2069 *
2070 * So, tell btrfs_drop_extents to leave this extent in the cache.
2071 * the caller is expected to unpin it and allow it to be merged
2072 * with the others.
2073 */
1acae57b
FDBM
2074 ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2075 file_pos + num_bytes, NULL, 0,
2076 1, sizeof(*fi), &extent_inserted);
79787eaa
JM
2077 if (ret)
2078 goto out;
d899e052 2079
1acae57b
FDBM
2080 if (!extent_inserted) {
2081 ins.objectid = btrfs_ino(inode);
2082 ins.offset = file_pos;
2083 ins.type = BTRFS_EXTENT_DATA_KEY;
2084
2085 path->leave_spinning = 1;
2086 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2087 sizeof(*fi));
2088 if (ret)
2089 goto out;
2090 }
d899e052
YZ
2091 leaf = path->nodes[0];
2092 fi = btrfs_item_ptr(leaf, path->slots[0],
2093 struct btrfs_file_extent_item);
2094 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2095 btrfs_set_file_extent_type(leaf, fi, extent_type);
2096 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2097 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2098 btrfs_set_file_extent_offset(leaf, fi, 0);
2099 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2100 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2101 btrfs_set_file_extent_compression(leaf, fi, compression);
2102 btrfs_set_file_extent_encryption(leaf, fi, encryption);
2103 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
b9473439 2104
d899e052 2105 btrfs_mark_buffer_dirty(leaf);
ce195332 2106 btrfs_release_path(path);
d899e052
YZ
2107
2108 inode_add_bytes(inode, num_bytes);
d899e052
YZ
2109
2110 ins.objectid = disk_bytenr;
2111 ins.offset = disk_num_bytes;
2112 ins.type = BTRFS_EXTENT_ITEM_KEY;
5d4f98a2
YZ
2113 ret = btrfs_alloc_reserved_file_extent(trans, root,
2114 root->root_key.objectid,
33345d01 2115 btrfs_ino(inode), file_pos, &ins);
79787eaa 2116out:
d899e052 2117 btrfs_free_path(path);
b9473439 2118
79787eaa 2119 return ret;
d899e052
YZ
2120}
2121
38c227d8
LB
2122/* snapshot-aware defrag */
2123struct sa_defrag_extent_backref {
2124 struct rb_node node;
2125 struct old_sa_defrag_extent *old;
2126 u64 root_id;
2127 u64 inum;
2128 u64 file_pos;
2129 u64 extent_offset;
2130 u64 num_bytes;
2131 u64 generation;
2132};
2133
2134struct old_sa_defrag_extent {
2135 struct list_head list;
2136 struct new_sa_defrag_extent *new;
2137
2138 u64 extent_offset;
2139 u64 bytenr;
2140 u64 offset;
2141 u64 len;
2142 int count;
2143};
2144
2145struct new_sa_defrag_extent {
2146 struct rb_root root;
2147 struct list_head head;
2148 struct btrfs_path *path;
2149 struct inode *inode;
2150 u64 file_pos;
2151 u64 len;
2152 u64 bytenr;
2153 u64 disk_len;
2154 u8 compress_type;
2155};
2156
2157static int backref_comp(struct sa_defrag_extent_backref *b1,
2158 struct sa_defrag_extent_backref *b2)
2159{
2160 if (b1->root_id < b2->root_id)
2161 return -1;
2162 else if (b1->root_id > b2->root_id)
2163 return 1;
2164
2165 if (b1->inum < b2->inum)
2166 return -1;
2167 else if (b1->inum > b2->inum)
2168 return 1;
2169
2170 if (b1->file_pos < b2->file_pos)
2171 return -1;
2172 else if (b1->file_pos > b2->file_pos)
2173 return 1;
2174
2175 /*
2176 * [------------------------------] ===> (a range of space)
2177 * |<--->| |<---->| =============> (fs/file tree A)
2178 * |<---------------------------->| ===> (fs/file tree B)
2179 *
2180 * A range of space can refer to two file extents in one tree while
2181 * refer to only one file extent in another tree.
2182 *
2183 * So we may process a disk offset more than one time(two extents in A)
2184 * and locate at the same extent(one extent in B), then insert two same
2185 * backrefs(both refer to the extent in B).
2186 */
2187 return 0;
2188}
2189
2190static void backref_insert(struct rb_root *root,
2191 struct sa_defrag_extent_backref *backref)
2192{
2193 struct rb_node **p = &root->rb_node;
2194 struct rb_node *parent = NULL;
2195 struct sa_defrag_extent_backref *entry;
2196 int ret;
2197
2198 while (*p) {
2199 parent = *p;
2200 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2201
2202 ret = backref_comp(backref, entry);
2203 if (ret < 0)
2204 p = &(*p)->rb_left;
2205 else
2206 p = &(*p)->rb_right;
2207 }
2208
2209 rb_link_node(&backref->node, parent, p);
2210 rb_insert_color(&backref->node, root);
2211}
2212
2213/*
2214 * Note the backref might has changed, and in this case we just return 0.
2215 */
2216static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2217 void *ctx)
2218{
2219 struct btrfs_file_extent_item *extent;
2220 struct btrfs_fs_info *fs_info;
2221 struct old_sa_defrag_extent *old = ctx;
2222 struct new_sa_defrag_extent *new = old->new;
2223 struct btrfs_path *path = new->path;
2224 struct btrfs_key key;
2225 struct btrfs_root *root;
2226 struct sa_defrag_extent_backref *backref;
2227 struct extent_buffer *leaf;
2228 struct inode *inode = new->inode;
2229 int slot;
2230 int ret;
2231 u64 extent_offset;
2232 u64 num_bytes;
2233
2234 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2235 inum == btrfs_ino(inode))
2236 return 0;
2237
2238 key.objectid = root_id;
2239 key.type = BTRFS_ROOT_ITEM_KEY;
2240 key.offset = (u64)-1;
2241
2242 fs_info = BTRFS_I(inode)->root->fs_info;
2243 root = btrfs_read_fs_root_no_name(fs_info, &key);
2244 if (IS_ERR(root)) {
2245 if (PTR_ERR(root) == -ENOENT)
2246 return 0;
2247 WARN_ON(1);
2248 pr_debug("inum=%llu, offset=%llu, root_id=%llu\n",
2249 inum, offset, root_id);
2250 return PTR_ERR(root);
2251 }
2252
2253 key.objectid = inum;
2254 key.type = BTRFS_EXTENT_DATA_KEY;
2255 if (offset > (u64)-1 << 32)
2256 key.offset = 0;
2257 else
2258 key.offset = offset;
2259
2260 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
fae7f21c 2261 if (WARN_ON(ret < 0))
38c227d8 2262 return ret;
50f1319c 2263 ret = 0;
38c227d8
LB
2264
2265 while (1) {
2266 cond_resched();
2267
2268 leaf = path->nodes[0];
2269 slot = path->slots[0];
2270
2271 if (slot >= btrfs_header_nritems(leaf)) {
2272 ret = btrfs_next_leaf(root, path);
2273 if (ret < 0) {
2274 goto out;
2275 } else if (ret > 0) {
2276 ret = 0;
2277 goto out;
2278 }
2279 continue;
2280 }
2281
2282 path->slots[0]++;
2283
2284 btrfs_item_key_to_cpu(leaf, &key, slot);
2285
2286 if (key.objectid > inum)
2287 goto out;
2288
2289 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2290 continue;
2291
2292 extent = btrfs_item_ptr(leaf, slot,
2293 struct btrfs_file_extent_item);
2294
2295 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2296 continue;
2297
e68afa49
LB
2298 /*
2299 * 'offset' refers to the exact key.offset,
2300 * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2301 * (key.offset - extent_offset).
2302 */
2303 if (key.offset != offset)
38c227d8
LB
2304 continue;
2305
e68afa49 2306 extent_offset = btrfs_file_extent_offset(leaf, extent);
38c227d8 2307 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
e68afa49 2308
38c227d8
LB
2309 if (extent_offset >= old->extent_offset + old->offset +
2310 old->len || extent_offset + num_bytes <=
2311 old->extent_offset + old->offset)
2312 continue;
38c227d8
LB
2313 break;
2314 }
2315
2316 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2317 if (!backref) {
2318 ret = -ENOENT;
2319 goto out;
2320 }
2321
2322 backref->root_id = root_id;
2323 backref->inum = inum;
e68afa49 2324 backref->file_pos = offset;
38c227d8
LB
2325 backref->num_bytes = num_bytes;
2326 backref->extent_offset = extent_offset;
2327 backref->generation = btrfs_file_extent_generation(leaf, extent);
2328 backref->old = old;
2329 backref_insert(&new->root, backref);
2330 old->count++;
2331out:
2332 btrfs_release_path(path);
2333 WARN_ON(ret);
2334 return ret;
2335}
2336
2337static noinline bool record_extent_backrefs(struct btrfs_path *path,
2338 struct new_sa_defrag_extent *new)
2339{
2340 struct btrfs_fs_info *fs_info = BTRFS_I(new->inode)->root->fs_info;
2341 struct old_sa_defrag_extent *old, *tmp;
2342 int ret;
2343
2344 new->path = path;
2345
2346 list_for_each_entry_safe(old, tmp, &new->head, list) {
e68afa49
LB
2347 ret = iterate_inodes_from_logical(old->bytenr +
2348 old->extent_offset, fs_info,
38c227d8
LB
2349 path, record_one_backref,
2350 old);
4724b106
JB
2351 if (ret < 0 && ret != -ENOENT)
2352 return false;
38c227d8
LB
2353
2354 /* no backref to be processed for this extent */
2355 if (!old->count) {
2356 list_del(&old->list);
2357 kfree(old);
2358 }
2359 }
2360
2361 if (list_empty(&new->head))
2362 return false;
2363
2364 return true;
2365}
2366
2367static int relink_is_mergable(struct extent_buffer *leaf,
2368 struct btrfs_file_extent_item *fi,
116e0024 2369 struct new_sa_defrag_extent *new)
38c227d8 2370{
116e0024 2371 if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
38c227d8
LB
2372 return 0;
2373
2374 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2375 return 0;
2376
116e0024
LB
2377 if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2378 return 0;
2379
2380 if (btrfs_file_extent_encryption(leaf, fi) ||
38c227d8
LB
2381 btrfs_file_extent_other_encoding(leaf, fi))
2382 return 0;
2383
2384 return 1;
2385}
2386
2387/*
2388 * Note the backref might has changed, and in this case we just return 0.
2389 */
2390static noinline int relink_extent_backref(struct btrfs_path *path,
2391 struct sa_defrag_extent_backref *prev,
2392 struct sa_defrag_extent_backref *backref)
2393{
2394 struct btrfs_file_extent_item *extent;
2395 struct btrfs_file_extent_item *item;
2396 struct btrfs_ordered_extent *ordered;
2397 struct btrfs_trans_handle *trans;
2398 struct btrfs_fs_info *fs_info;
2399 struct btrfs_root *root;
2400 struct btrfs_key key;
2401 struct extent_buffer *leaf;
2402 struct old_sa_defrag_extent *old = backref->old;
2403 struct new_sa_defrag_extent *new = old->new;
2404 struct inode *src_inode = new->inode;
2405 struct inode *inode;
2406 struct extent_state *cached = NULL;
2407 int ret = 0;
2408 u64 start;
2409 u64 len;
2410 u64 lock_start;
2411 u64 lock_end;
2412 bool merge = false;
2413 int index;
2414
2415 if (prev && prev->root_id == backref->root_id &&
2416 prev->inum == backref->inum &&
2417 prev->file_pos + prev->num_bytes == backref->file_pos)
2418 merge = true;
2419
2420 /* step 1: get root */
2421 key.objectid = backref->root_id;
2422 key.type = BTRFS_ROOT_ITEM_KEY;
2423 key.offset = (u64)-1;
2424
2425 fs_info = BTRFS_I(src_inode)->root->fs_info;
2426 index = srcu_read_lock(&fs_info->subvol_srcu);
2427
2428 root = btrfs_read_fs_root_no_name(fs_info, &key);
2429 if (IS_ERR(root)) {
2430 srcu_read_unlock(&fs_info->subvol_srcu, index);
2431 if (PTR_ERR(root) == -ENOENT)
2432 return 0;
2433 return PTR_ERR(root);
2434 }
38c227d8 2435
bcbba5e6
WS
2436 if (btrfs_root_readonly(root)) {
2437 srcu_read_unlock(&fs_info->subvol_srcu, index);
2438 return 0;
2439 }
2440
38c227d8
LB
2441 /* step 2: get inode */
2442 key.objectid = backref->inum;
2443 key.type = BTRFS_INODE_ITEM_KEY;
2444 key.offset = 0;
2445
2446 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2447 if (IS_ERR(inode)) {
2448 srcu_read_unlock(&fs_info->subvol_srcu, index);
2449 return 0;
2450 }
2451
2452 srcu_read_unlock(&fs_info->subvol_srcu, index);
2453
2454 /* step 3: relink backref */
2455 lock_start = backref->file_pos;
2456 lock_end = backref->file_pos + backref->num_bytes - 1;
2457 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2458 0, &cached);
2459
2460 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2461 if (ordered) {
2462 btrfs_put_ordered_extent(ordered);
2463 goto out_unlock;
2464 }
2465
2466 trans = btrfs_join_transaction(root);
2467 if (IS_ERR(trans)) {
2468 ret = PTR_ERR(trans);
2469 goto out_unlock;
2470 }
2471
2472 key.objectid = backref->inum;
2473 key.type = BTRFS_EXTENT_DATA_KEY;
2474 key.offset = backref->file_pos;
2475
2476 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2477 if (ret < 0) {
2478 goto out_free_path;
2479 } else if (ret > 0) {
2480 ret = 0;
2481 goto out_free_path;
2482 }
2483
2484 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2485 struct btrfs_file_extent_item);
2486
2487 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2488 backref->generation)
2489 goto out_free_path;
2490
2491 btrfs_release_path(path);
2492
2493 start = backref->file_pos;
2494 if (backref->extent_offset < old->extent_offset + old->offset)
2495 start += old->extent_offset + old->offset -
2496 backref->extent_offset;
2497
2498 len = min(backref->extent_offset + backref->num_bytes,
2499 old->extent_offset + old->offset + old->len);
2500 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2501
2502 ret = btrfs_drop_extents(trans, root, inode, start,
2503 start + len, 1);
2504 if (ret)
2505 goto out_free_path;
2506again:
2507 key.objectid = btrfs_ino(inode);
2508 key.type = BTRFS_EXTENT_DATA_KEY;
2509 key.offset = start;
2510
a09a0a70 2511 path->leave_spinning = 1;
38c227d8
LB
2512 if (merge) {
2513 struct btrfs_file_extent_item *fi;
2514 u64 extent_len;
2515 struct btrfs_key found_key;
2516
3c9665df 2517 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
38c227d8
LB
2518 if (ret < 0)
2519 goto out_free_path;
2520
2521 path->slots[0]--;
2522 leaf = path->nodes[0];
2523 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2524
2525 fi = btrfs_item_ptr(leaf, path->slots[0],
2526 struct btrfs_file_extent_item);
2527 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2528
116e0024
LB
2529 if (extent_len + found_key.offset == start &&
2530 relink_is_mergable(leaf, fi, new)) {
38c227d8
LB
2531 btrfs_set_file_extent_num_bytes(leaf, fi,
2532 extent_len + len);
2533 btrfs_mark_buffer_dirty(leaf);
2534 inode_add_bytes(inode, len);
2535
2536 ret = 1;
2537 goto out_free_path;
2538 } else {
2539 merge = false;
2540 btrfs_release_path(path);
2541 goto again;
2542 }
2543 }
2544
2545 ret = btrfs_insert_empty_item(trans, root, path, &key,
2546 sizeof(*extent));
2547 if (ret) {
2548 btrfs_abort_transaction(trans, root, ret);
2549 goto out_free_path;
2550 }
2551
2552 leaf = path->nodes[0];
2553 item = btrfs_item_ptr(leaf, path->slots[0],
2554 struct btrfs_file_extent_item);
2555 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2556 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2557 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2558 btrfs_set_file_extent_num_bytes(leaf, item, len);
2559 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2560 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2561 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2562 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2563 btrfs_set_file_extent_encryption(leaf, item, 0);
2564 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2565
2566 btrfs_mark_buffer_dirty(leaf);
2567 inode_add_bytes(inode, len);
a09a0a70 2568 btrfs_release_path(path);
38c227d8
LB
2569
2570 ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2571 new->disk_len, 0,
2572 backref->root_id, backref->inum,
2573 new->file_pos, 0); /* start - extent_offset */
2574 if (ret) {
2575 btrfs_abort_transaction(trans, root, ret);
2576 goto out_free_path;
2577 }
2578
2579 ret = 1;
2580out_free_path:
2581 btrfs_release_path(path);
a09a0a70 2582 path->leave_spinning = 0;
38c227d8
LB
2583 btrfs_end_transaction(trans, root);
2584out_unlock:
2585 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2586 &cached, GFP_NOFS);
2587 iput(inode);
2588 return ret;
2589}
2590
6f519564
LB
2591static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2592{
2593 struct old_sa_defrag_extent *old, *tmp;
2594
2595 if (!new)
2596 return;
2597
2598 list_for_each_entry_safe(old, tmp, &new->head, list) {
2599 list_del(&old->list);
2600 kfree(old);
2601 }
2602 kfree(new);
2603}
2604
38c227d8
LB
2605static void relink_file_extents(struct new_sa_defrag_extent *new)
2606{
2607 struct btrfs_path *path;
38c227d8
LB
2608 struct sa_defrag_extent_backref *backref;
2609 struct sa_defrag_extent_backref *prev = NULL;
2610 struct inode *inode;
2611 struct btrfs_root *root;
2612 struct rb_node *node;
2613 int ret;
2614
2615 inode = new->inode;
2616 root = BTRFS_I(inode)->root;
2617
2618 path = btrfs_alloc_path();
2619 if (!path)
2620 return;
2621
2622 if (!record_extent_backrefs(path, new)) {
2623 btrfs_free_path(path);
2624 goto out;
2625 }
2626 btrfs_release_path(path);
2627
2628 while (1) {
2629 node = rb_first(&new->root);
2630 if (!node)
2631 break;
2632 rb_erase(node, &new->root);
2633
2634 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2635
2636 ret = relink_extent_backref(path, prev, backref);
2637 WARN_ON(ret < 0);
2638
2639 kfree(prev);
2640
2641 if (ret == 1)
2642 prev = backref;
2643 else
2644 prev = NULL;
2645 cond_resched();
2646 }
2647 kfree(prev);
2648
2649 btrfs_free_path(path);
38c227d8 2650out:
6f519564
LB
2651 free_sa_defrag_extent(new);
2652
38c227d8
LB
2653 atomic_dec(&root->fs_info->defrag_running);
2654 wake_up(&root->fs_info->transaction_wait);
38c227d8
LB
2655}
2656
2657static struct new_sa_defrag_extent *
2658record_old_file_extents(struct inode *inode,
2659 struct btrfs_ordered_extent *ordered)
2660{
2661 struct btrfs_root *root = BTRFS_I(inode)->root;
2662 struct btrfs_path *path;
2663 struct btrfs_key key;
6f519564 2664 struct old_sa_defrag_extent *old;
38c227d8
LB
2665 struct new_sa_defrag_extent *new;
2666 int ret;
2667
2668 new = kmalloc(sizeof(*new), GFP_NOFS);
2669 if (!new)
2670 return NULL;
2671
2672 new->inode = inode;
2673 new->file_pos = ordered->file_offset;
2674 new->len = ordered->len;
2675 new->bytenr = ordered->start;
2676 new->disk_len = ordered->disk_len;
2677 new->compress_type = ordered->compress_type;
2678 new->root = RB_ROOT;
2679 INIT_LIST_HEAD(&new->head);
2680
2681 path = btrfs_alloc_path();
2682 if (!path)
2683 goto out_kfree;
2684
2685 key.objectid = btrfs_ino(inode);
2686 key.type = BTRFS_EXTENT_DATA_KEY;
2687 key.offset = new->file_pos;
2688
2689 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2690 if (ret < 0)
2691 goto out_free_path;
2692 if (ret > 0 && path->slots[0] > 0)
2693 path->slots[0]--;
2694
2695 /* find out all the old extents for the file range */
2696 while (1) {
2697 struct btrfs_file_extent_item *extent;
2698 struct extent_buffer *l;
2699 int slot;
2700 u64 num_bytes;
2701 u64 offset;
2702 u64 end;
2703 u64 disk_bytenr;
2704 u64 extent_offset;
2705
2706 l = path->nodes[0];
2707 slot = path->slots[0];
2708
2709 if (slot >= btrfs_header_nritems(l)) {
2710 ret = btrfs_next_leaf(root, path);
2711 if (ret < 0)
6f519564 2712 goto out_free_path;
38c227d8
LB
2713 else if (ret > 0)
2714 break;
2715 continue;
2716 }
2717
2718 btrfs_item_key_to_cpu(l, &key, slot);
2719
2720 if (key.objectid != btrfs_ino(inode))
2721 break;
2722 if (key.type != BTRFS_EXTENT_DATA_KEY)
2723 break;
2724 if (key.offset >= new->file_pos + new->len)
2725 break;
2726
2727 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2728
2729 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2730 if (key.offset + num_bytes < new->file_pos)
2731 goto next;
2732
2733 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2734 if (!disk_bytenr)
2735 goto next;
2736
2737 extent_offset = btrfs_file_extent_offset(l, extent);
2738
2739 old = kmalloc(sizeof(*old), GFP_NOFS);
2740 if (!old)
6f519564 2741 goto out_free_path;
38c227d8
LB
2742
2743 offset = max(new->file_pos, key.offset);
2744 end = min(new->file_pos + new->len, key.offset + num_bytes);
2745
2746 old->bytenr = disk_bytenr;
2747 old->extent_offset = extent_offset;
2748 old->offset = offset - key.offset;
2749 old->len = end - offset;
2750 old->new = new;
2751 old->count = 0;
2752 list_add_tail(&old->list, &new->head);
2753next:
2754 path->slots[0]++;
2755 cond_resched();
2756 }
2757
2758 btrfs_free_path(path);
2759 atomic_inc(&root->fs_info->defrag_running);
2760
2761 return new;
2762
38c227d8
LB
2763out_free_path:
2764 btrfs_free_path(path);
2765out_kfree:
6f519564 2766 free_sa_defrag_extent(new);
38c227d8
LB
2767 return NULL;
2768}
2769
e570fd27
MX
2770static void btrfs_release_delalloc_bytes(struct btrfs_root *root,
2771 u64 start, u64 len)
2772{
2773 struct btrfs_block_group_cache *cache;
2774
2775 cache = btrfs_lookup_block_group(root->fs_info, start);
2776 ASSERT(cache);
2777
2778 spin_lock(&cache->lock);
2779 cache->delalloc_bytes -= len;
2780 spin_unlock(&cache->lock);
2781
2782 btrfs_put_block_group(cache);
2783}
2784
d352ac68
CM
2785/* as ordered data IO finishes, this gets called so we can finish
2786 * an ordered extent if the range of bytes in the file it covers are
2787 * fully written.
2788 */
5fd02043 2789static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
e6dcd2dc 2790{
5fd02043 2791 struct inode *inode = ordered_extent->inode;
e6dcd2dc 2792 struct btrfs_root *root = BTRFS_I(inode)->root;
0ca1f7ce 2793 struct btrfs_trans_handle *trans = NULL;
e6dcd2dc 2794 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2ac55d41 2795 struct extent_state *cached_state = NULL;
38c227d8 2796 struct new_sa_defrag_extent *new = NULL;
261507a0 2797 int compress_type = 0;
77cef2ec
JB
2798 int ret = 0;
2799 u64 logical_len = ordered_extent->len;
82d5902d 2800 bool nolock;
77cef2ec 2801 bool truncated = false;
e6dcd2dc 2802
83eea1f1 2803 nolock = btrfs_is_free_space_inode(inode);
0cb59c99 2804
5fd02043
JB
2805 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2806 ret = -EIO;
2807 goto out;
2808 }
2809
f612496b
MX
2810 btrfs_free_io_failure_record(inode, ordered_extent->file_offset,
2811 ordered_extent->file_offset +
2812 ordered_extent->len - 1);
2813
77cef2ec
JB
2814 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2815 truncated = true;
2816 logical_len = ordered_extent->truncated_len;
2817 /* Truncated the entire extent, don't bother adding */
2818 if (!logical_len)
2819 goto out;
2820 }
2821
c2167754 2822 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
79787eaa 2823 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
6c760c07
JB
2824 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2825 if (nolock)
2826 trans = btrfs_join_transaction_nolock(root);
2827 else
2828 trans = btrfs_join_transaction(root);
2829 if (IS_ERR(trans)) {
2830 ret = PTR_ERR(trans);
2831 trans = NULL;
2832 goto out;
c2167754 2833 }
6c760c07
JB
2834 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2835 ret = btrfs_update_inode_fallback(trans, root, inode);
2836 if (ret) /* -ENOMEM or corruption */
2837 btrfs_abort_transaction(trans, root, ret);
c2167754
YZ
2838 goto out;
2839 }
e6dcd2dc 2840
2ac55d41
JB
2841 lock_extent_bits(io_tree, ordered_extent->file_offset,
2842 ordered_extent->file_offset + ordered_extent->len - 1,
d0082371 2843 0, &cached_state);
e6dcd2dc 2844
38c227d8
LB
2845 ret = test_range_bit(io_tree, ordered_extent->file_offset,
2846 ordered_extent->file_offset + ordered_extent->len - 1,
2847 EXTENT_DEFRAG, 1, cached_state);
2848 if (ret) {
2849 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
8101c8db 2850 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
38c227d8
LB
2851 /* the inode is shared */
2852 new = record_old_file_extents(inode, ordered_extent);
2853
2854 clear_extent_bit(io_tree, ordered_extent->file_offset,
2855 ordered_extent->file_offset + ordered_extent->len - 1,
2856 EXTENT_DEFRAG, 0, 0, &cached_state, GFP_NOFS);
2857 }
2858
0cb59c99 2859 if (nolock)
7a7eaa40 2860 trans = btrfs_join_transaction_nolock(root);
0cb59c99 2861 else
7a7eaa40 2862 trans = btrfs_join_transaction(root);
79787eaa
JM
2863 if (IS_ERR(trans)) {
2864 ret = PTR_ERR(trans);
2865 trans = NULL;
2866 goto out_unlock;
2867 }
a79b7d4b 2868
0ca1f7ce 2869 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
c2167754 2870
c8b97818 2871 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
261507a0 2872 compress_type = ordered_extent->compress_type;
d899e052 2873 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
261507a0 2874 BUG_ON(compress_type);
920bbbfb 2875 ret = btrfs_mark_extent_written(trans, inode,
d899e052
YZ
2876 ordered_extent->file_offset,
2877 ordered_extent->file_offset +
77cef2ec 2878 logical_len);
d899e052 2879 } else {
0af3d00b 2880 BUG_ON(root == root->fs_info->tree_root);
d899e052
YZ
2881 ret = insert_reserved_file_extent(trans, inode,
2882 ordered_extent->file_offset,
2883 ordered_extent->start,
2884 ordered_extent->disk_len,
77cef2ec 2885 logical_len, logical_len,
261507a0 2886 compress_type, 0, 0,
d899e052 2887 BTRFS_FILE_EXTENT_REG);
e570fd27
MX
2888 if (!ret)
2889 btrfs_release_delalloc_bytes(root,
2890 ordered_extent->start,
2891 ordered_extent->disk_len);
d899e052 2892 }
5dc562c5
JB
2893 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
2894 ordered_extent->file_offset, ordered_extent->len,
2895 trans->transid);
79787eaa
JM
2896 if (ret < 0) {
2897 btrfs_abort_transaction(trans, root, ret);
5fd02043 2898 goto out_unlock;
79787eaa 2899 }
2ac55d41 2900
e6dcd2dc
CM
2901 add_pending_csums(trans, inode, ordered_extent->file_offset,
2902 &ordered_extent->list);
2903
6c760c07
JB
2904 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2905 ret = btrfs_update_inode_fallback(trans, root, inode);
2906 if (ret) { /* -ENOMEM or corruption */
2907 btrfs_abort_transaction(trans, root, ret);
2908 goto out_unlock;
1ef30be1
JB
2909 }
2910 ret = 0;
5fd02043
JB
2911out_unlock:
2912 unlock_extent_cached(io_tree, ordered_extent->file_offset,
2913 ordered_extent->file_offset +
2914 ordered_extent->len - 1, &cached_state, GFP_NOFS);
c2167754 2915out:
5b0e95bf 2916 if (root != root->fs_info->tree_root)
0cb59c99 2917 btrfs_delalloc_release_metadata(inode, ordered_extent->len);
a698d075
MX
2918 if (trans)
2919 btrfs_end_transaction(trans, root);
0cb59c99 2920
77cef2ec
JB
2921 if (ret || truncated) {
2922 u64 start, end;
2923
2924 if (truncated)
2925 start = ordered_extent->file_offset + logical_len;
2926 else
2927 start = ordered_extent->file_offset;
2928 end = ordered_extent->file_offset + ordered_extent->len - 1;
2929 clear_extent_uptodate(io_tree, start, end, NULL, GFP_NOFS);
2930
2931 /* Drop the cache for the part of the extent we didn't write. */
2932 btrfs_drop_extent_cache(inode, start, end, 0);
5fd02043 2933
0bec9ef5
JB
2934 /*
2935 * If the ordered extent had an IOERR or something else went
2936 * wrong we need to return the space for this ordered extent
77cef2ec
JB
2937 * back to the allocator. We only free the extent in the
2938 * truncated case if we didn't write out the extent at all.
0bec9ef5 2939 */
77cef2ec
JB
2940 if ((ret || !logical_len) &&
2941 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
0bec9ef5
JB
2942 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
2943 btrfs_free_reserved_extent(root, ordered_extent->start,
e570fd27 2944 ordered_extent->disk_len, 1);
0bec9ef5
JB
2945 }
2946
2947
5fd02043 2948 /*
8bad3c02
LB
2949 * This needs to be done to make sure anybody waiting knows we are done
2950 * updating everything for this ordered extent.
5fd02043
JB
2951 */
2952 btrfs_remove_ordered_extent(inode, ordered_extent);
2953
38c227d8 2954 /* for snapshot-aware defrag */
6f519564
LB
2955 if (new) {
2956 if (ret) {
2957 free_sa_defrag_extent(new);
2958 atomic_dec(&root->fs_info->defrag_running);
2959 } else {
2960 relink_file_extents(new);
2961 }
2962 }
38c227d8 2963
e6dcd2dc
CM
2964 /* once for us */
2965 btrfs_put_ordered_extent(ordered_extent);
2966 /* once for the tree */
2967 btrfs_put_ordered_extent(ordered_extent);
2968
5fd02043
JB
2969 return ret;
2970}
2971
2972static void finish_ordered_fn(struct btrfs_work *work)
2973{
2974 struct btrfs_ordered_extent *ordered_extent;
2975 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
2976 btrfs_finish_ordered_io(ordered_extent);
e6dcd2dc
CM
2977}
2978
b2950863 2979static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
211f90e6
CM
2980 struct extent_state *state, int uptodate)
2981{
5fd02043
JB
2982 struct inode *inode = page->mapping->host;
2983 struct btrfs_root *root = BTRFS_I(inode)->root;
2984 struct btrfs_ordered_extent *ordered_extent = NULL;
9e0af237
LB
2985 struct btrfs_workqueue *wq;
2986 btrfs_work_func_t func;
5fd02043 2987
1abe9b8a 2988 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
2989
8b62b72b 2990 ClearPagePrivate2(page);
5fd02043
JB
2991 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
2992 end - start + 1, uptodate))
2993 return 0;
2994
9e0af237
LB
2995 if (btrfs_is_free_space_inode(inode)) {
2996 wq = root->fs_info->endio_freespace_worker;
2997 func = btrfs_freespace_write_helper;
2998 } else {
2999 wq = root->fs_info->endio_write_workers;
3000 func = btrfs_endio_write_helper;
3001 }
5fd02043 3002
9e0af237
LB
3003 btrfs_init_work(&ordered_extent->work, func, finish_ordered_fn, NULL,
3004 NULL);
3005 btrfs_queue_work(wq, &ordered_extent->work);
5fd02043
JB
3006
3007 return 0;
211f90e6
CM
3008}
3009
dc380aea
MX
3010static int __readpage_endio_check(struct inode *inode,
3011 struct btrfs_io_bio *io_bio,
3012 int icsum, struct page *page,
3013 int pgoff, u64 start, size_t len)
3014{
3015 char *kaddr;
3016 u32 csum_expected;
3017 u32 csum = ~(u32)0;
3018 static DEFINE_RATELIMIT_STATE(_rs, DEFAULT_RATELIMIT_INTERVAL,
3019 DEFAULT_RATELIMIT_BURST);
3020
3021 csum_expected = *(((u32 *)io_bio->csum) + icsum);
3022
3023 kaddr = kmap_atomic(page);
3024 csum = btrfs_csum_data(kaddr + pgoff, csum, len);
3025 btrfs_csum_final(csum, (char *)&csum);
3026 if (csum != csum_expected)
3027 goto zeroit;
3028
3029 kunmap_atomic(kaddr);
3030 return 0;
3031zeroit:
3032 if (__ratelimit(&_rs))
f0954c66 3033 btrfs_warn(BTRFS_I(inode)->root->fs_info,
dc380aea
MX
3034 "csum failed ino %llu off %llu csum %u expected csum %u",
3035 btrfs_ino(inode), start, csum, csum_expected);
3036 memset(kaddr + pgoff, 1, len);
3037 flush_dcache_page(page);
3038 kunmap_atomic(kaddr);
3039 if (csum_expected == 0)
3040 return 0;
3041 return -EIO;
3042}
3043
d352ac68
CM
3044/*
3045 * when reads are done, we need to check csums to verify the data is correct
4a54c8c1
JS
3046 * if there's a match, we allow the bio to finish. If not, the code in
3047 * extent_io.c will try to find good copies for us.
d352ac68 3048 */
facc8a22
MX
3049static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
3050 u64 phy_offset, struct page *page,
3051 u64 start, u64 end, int mirror)
07157aac 3052{
4eee4fa4 3053 size_t offset = start - page_offset(page);
07157aac 3054 struct inode *inode = page->mapping->host;
d1310b2e 3055 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
ff79f819 3056 struct btrfs_root *root = BTRFS_I(inode)->root;
d1310b2e 3057
d20f7043
CM
3058 if (PageChecked(page)) {
3059 ClearPageChecked(page);
dc380aea 3060 return 0;
d20f7043 3061 }
6cbff00f
CH
3062
3063 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
dc380aea 3064 return 0;
17d217fe
YZ
3065
3066 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
9655d298 3067 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
17d217fe
YZ
3068 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM,
3069 GFP_NOFS);
b6cda9bc 3070 return 0;
17d217fe 3071 }
d20f7043 3072
facc8a22 3073 phy_offset >>= inode->i_sb->s_blocksize_bits;
dc380aea
MX
3074 return __readpage_endio_check(inode, io_bio, phy_offset, page, offset,
3075 start, (size_t)(end - start + 1));
07157aac 3076}
b888db2b 3077
24bbcf04
YZ
3078struct delayed_iput {
3079 struct list_head list;
3080 struct inode *inode;
3081};
3082
79787eaa
JM
3083/* JDM: If this is fs-wide, why can't we add a pointer to
3084 * btrfs_inode instead and avoid the allocation? */
24bbcf04
YZ
3085void btrfs_add_delayed_iput(struct inode *inode)
3086{
3087 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
3088 struct delayed_iput *delayed;
3089
3090 if (atomic_add_unless(&inode->i_count, -1, 1))
3091 return;
3092
3093 delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL);
3094 delayed->inode = inode;
3095
3096 spin_lock(&fs_info->delayed_iput_lock);
3097 list_add_tail(&delayed->list, &fs_info->delayed_iputs);
3098 spin_unlock(&fs_info->delayed_iput_lock);
3099}
3100
3101void btrfs_run_delayed_iputs(struct btrfs_root *root)
3102{
3103 LIST_HEAD(list);
3104 struct btrfs_fs_info *fs_info = root->fs_info;
3105 struct delayed_iput *delayed;
3106 int empty;
3107
3108 spin_lock(&fs_info->delayed_iput_lock);
3109 empty = list_empty(&fs_info->delayed_iputs);
3110 spin_unlock(&fs_info->delayed_iput_lock);
3111 if (empty)
3112 return;
3113
24bbcf04
YZ
3114 spin_lock(&fs_info->delayed_iput_lock);
3115 list_splice_init(&fs_info->delayed_iputs, &list);
3116 spin_unlock(&fs_info->delayed_iput_lock);
3117
3118 while (!list_empty(&list)) {
3119 delayed = list_entry(list.next, struct delayed_iput, list);
3120 list_del(&delayed->list);
3121 iput(delayed->inode);
3122 kfree(delayed);
3123 }
24bbcf04
YZ
3124}
3125
d68fc57b 3126/*
42b2aa86 3127 * This is called in transaction commit time. If there are no orphan
d68fc57b
YZ
3128 * files in the subvolume, it removes orphan item and frees block_rsv
3129 * structure.
3130 */
3131void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
3132 struct btrfs_root *root)
3133{
90290e19 3134 struct btrfs_block_rsv *block_rsv;
d68fc57b
YZ
3135 int ret;
3136
8a35d95f 3137 if (atomic_read(&root->orphan_inodes) ||
d68fc57b
YZ
3138 root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
3139 return;
3140
90290e19 3141 spin_lock(&root->orphan_lock);
8a35d95f 3142 if (atomic_read(&root->orphan_inodes)) {
90290e19
JB
3143 spin_unlock(&root->orphan_lock);
3144 return;
3145 }
3146
3147 if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
3148 spin_unlock(&root->orphan_lock);
3149 return;
3150 }
3151
3152 block_rsv = root->orphan_block_rsv;
3153 root->orphan_block_rsv = NULL;
3154 spin_unlock(&root->orphan_lock);
3155
27cdeb70 3156 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state) &&
d68fc57b
YZ
3157 btrfs_root_refs(&root->root_item) > 0) {
3158 ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root,
3159 root->root_key.objectid);
4ef31a45
JB
3160 if (ret)
3161 btrfs_abort_transaction(trans, root, ret);
3162 else
27cdeb70
MX
3163 clear_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED,
3164 &root->state);
d68fc57b
YZ
3165 }
3166
90290e19
JB
3167 if (block_rsv) {
3168 WARN_ON(block_rsv->size > 0);
3169 btrfs_free_block_rsv(root, block_rsv);
d68fc57b
YZ
3170 }
3171}
3172
7b128766
JB
3173/*
3174 * This creates an orphan entry for the given inode in case something goes
3175 * wrong in the middle of an unlink/truncate.
d68fc57b
YZ
3176 *
3177 * NOTE: caller of this function should reserve 5 units of metadata for
3178 * this function.
7b128766
JB
3179 */
3180int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
3181{
3182 struct btrfs_root *root = BTRFS_I(inode)->root;
d68fc57b
YZ
3183 struct btrfs_block_rsv *block_rsv = NULL;
3184 int reserve = 0;
3185 int insert = 0;
3186 int ret;
7b128766 3187
d68fc57b 3188 if (!root->orphan_block_rsv) {
66d8f3dd 3189 block_rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
b532402e
TI
3190 if (!block_rsv)
3191 return -ENOMEM;
d68fc57b 3192 }
7b128766 3193
d68fc57b
YZ
3194 spin_lock(&root->orphan_lock);
3195 if (!root->orphan_block_rsv) {
3196 root->orphan_block_rsv = block_rsv;
3197 } else if (block_rsv) {
3198 btrfs_free_block_rsv(root, block_rsv);
3199 block_rsv = NULL;
7b128766 3200 }
7b128766 3201
8a35d95f
JB
3202 if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3203 &BTRFS_I(inode)->runtime_flags)) {
d68fc57b
YZ
3204#if 0
3205 /*
3206 * For proper ENOSPC handling, we should do orphan
3207 * cleanup when mounting. But this introduces backward
3208 * compatibility issue.
3209 */
3210 if (!xchg(&root->orphan_item_inserted, 1))
3211 insert = 2;
3212 else
3213 insert = 1;
3214#endif
3215 insert = 1;
321f0e70 3216 atomic_inc(&root->orphan_inodes);
7b128766
JB
3217 }
3218
72ac3c0d
JB
3219 if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3220 &BTRFS_I(inode)->runtime_flags))
d68fc57b 3221 reserve = 1;
d68fc57b 3222 spin_unlock(&root->orphan_lock);
7b128766 3223
d68fc57b
YZ
3224 /* grab metadata reservation from transaction handle */
3225 if (reserve) {
3226 ret = btrfs_orphan_reserve_metadata(trans, inode);
79787eaa 3227 BUG_ON(ret); /* -ENOSPC in reservation; Logic error? JDM */
d68fc57b 3228 }
7b128766 3229
d68fc57b
YZ
3230 /* insert an orphan item to track this unlinked/truncated file */
3231 if (insert >= 1) {
33345d01 3232 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
4ef31a45 3233 if (ret) {
703c88e0 3234 atomic_dec(&root->orphan_inodes);
4ef31a45
JB
3235 if (reserve) {
3236 clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3237 &BTRFS_I(inode)->runtime_flags);
3238 btrfs_orphan_release_metadata(inode);
3239 }
3240 if (ret != -EEXIST) {
e8e7cff6
JB
3241 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3242 &BTRFS_I(inode)->runtime_flags);
4ef31a45
JB
3243 btrfs_abort_transaction(trans, root, ret);
3244 return ret;
3245 }
79787eaa
JM
3246 }
3247 ret = 0;
d68fc57b
YZ
3248 }
3249
3250 /* insert an orphan item to track subvolume contains orphan files */
3251 if (insert >= 2) {
3252 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
3253 root->root_key.objectid);
79787eaa
JM
3254 if (ret && ret != -EEXIST) {
3255 btrfs_abort_transaction(trans, root, ret);
3256 return ret;
3257 }
d68fc57b
YZ
3258 }
3259 return 0;
7b128766
JB
3260}
3261
3262/*
3263 * We have done the truncate/delete so we can go ahead and remove the orphan
3264 * item for this particular inode.
3265 */
48a3b636
ES
3266static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3267 struct inode *inode)
7b128766
JB
3268{
3269 struct btrfs_root *root = BTRFS_I(inode)->root;
d68fc57b
YZ
3270 int delete_item = 0;
3271 int release_rsv = 0;
7b128766
JB
3272 int ret = 0;
3273
d68fc57b 3274 spin_lock(&root->orphan_lock);
8a35d95f
JB
3275 if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3276 &BTRFS_I(inode)->runtime_flags))
d68fc57b 3277 delete_item = 1;
7b128766 3278
72ac3c0d
JB
3279 if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3280 &BTRFS_I(inode)->runtime_flags))
d68fc57b 3281 release_rsv = 1;
d68fc57b 3282 spin_unlock(&root->orphan_lock);
7b128766 3283
703c88e0 3284 if (delete_item) {
8a35d95f 3285 atomic_dec(&root->orphan_inodes);
703c88e0
FDBM
3286 if (trans)
3287 ret = btrfs_del_orphan_item(trans, root,
3288 btrfs_ino(inode));
8a35d95f 3289 }
7b128766 3290
703c88e0
FDBM
3291 if (release_rsv)
3292 btrfs_orphan_release_metadata(inode);
3293
4ef31a45 3294 return ret;
7b128766
JB
3295}
3296
3297/*
3298 * this cleans up any orphans that may be left on the list from the last use
3299 * of this root.
3300 */
66b4ffd1 3301int btrfs_orphan_cleanup(struct btrfs_root *root)
7b128766
JB
3302{
3303 struct btrfs_path *path;
3304 struct extent_buffer *leaf;
7b128766
JB
3305 struct btrfs_key key, found_key;
3306 struct btrfs_trans_handle *trans;
3307 struct inode *inode;
8f6d7f4f 3308 u64 last_objectid = 0;
7b128766
JB
3309 int ret = 0, nr_unlink = 0, nr_truncate = 0;
3310
d68fc57b 3311 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
66b4ffd1 3312 return 0;
c71bf099
YZ
3313
3314 path = btrfs_alloc_path();
66b4ffd1
JB
3315 if (!path) {
3316 ret = -ENOMEM;
3317 goto out;
3318 }
7b128766
JB
3319 path->reada = -1;
3320
3321 key.objectid = BTRFS_ORPHAN_OBJECTID;
962a298f 3322 key.type = BTRFS_ORPHAN_ITEM_KEY;
7b128766
JB
3323 key.offset = (u64)-1;
3324
7b128766
JB
3325 while (1) {
3326 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
66b4ffd1
JB
3327 if (ret < 0)
3328 goto out;
7b128766
JB
3329
3330 /*
3331 * if ret == 0 means we found what we were searching for, which
25985edc 3332 * is weird, but possible, so only screw with path if we didn't
7b128766
JB
3333 * find the key and see if we have stuff that matches
3334 */
3335 if (ret > 0) {
66b4ffd1 3336 ret = 0;
7b128766
JB
3337 if (path->slots[0] == 0)
3338 break;
3339 path->slots[0]--;
3340 }
3341
3342 /* pull out the item */
3343 leaf = path->nodes[0];
7b128766
JB
3344 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3345
3346 /* make sure the item matches what we want */
3347 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3348 break;
962a298f 3349 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
7b128766
JB
3350 break;
3351
3352 /* release the path since we're done with it */
b3b4aa74 3353 btrfs_release_path(path);
7b128766
JB
3354
3355 /*
3356 * this is where we are basically btrfs_lookup, without the
3357 * crossing root thing. we store the inode number in the
3358 * offset of the orphan item.
3359 */
8f6d7f4f
JB
3360
3361 if (found_key.offset == last_objectid) {
c2cf52eb
SK
3362 btrfs_err(root->fs_info,
3363 "Error removing orphan entry, stopping orphan cleanup");
8f6d7f4f
JB
3364 ret = -EINVAL;
3365 goto out;
3366 }
3367
3368 last_objectid = found_key.offset;
3369
5d4f98a2
YZ
3370 found_key.objectid = found_key.offset;
3371 found_key.type = BTRFS_INODE_ITEM_KEY;
3372 found_key.offset = 0;
73f73415 3373 inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
8c6ffba0 3374 ret = PTR_ERR_OR_ZERO(inode);
a8c9e576 3375 if (ret && ret != -ESTALE)
66b4ffd1 3376 goto out;
7b128766 3377
f8e9e0b0
AJ
3378 if (ret == -ESTALE && root == root->fs_info->tree_root) {
3379 struct btrfs_root *dead_root;
3380 struct btrfs_fs_info *fs_info = root->fs_info;
3381 int is_dead_root = 0;
3382
3383 /*
3384 * this is an orphan in the tree root. Currently these
3385 * could come from 2 sources:
3386 * a) a snapshot deletion in progress
3387 * b) a free space cache inode
3388 * We need to distinguish those two, as the snapshot
3389 * orphan must not get deleted.
3390 * find_dead_roots already ran before us, so if this
3391 * is a snapshot deletion, we should find the root
3392 * in the dead_roots list
3393 */
3394 spin_lock(&fs_info->trans_lock);
3395 list_for_each_entry(dead_root, &fs_info->dead_roots,
3396 root_list) {
3397 if (dead_root->root_key.objectid ==
3398 found_key.objectid) {
3399 is_dead_root = 1;
3400 break;
3401 }
3402 }
3403 spin_unlock(&fs_info->trans_lock);
3404 if (is_dead_root) {
3405 /* prevent this orphan from being found again */
3406 key.offset = found_key.objectid - 1;
3407 continue;
3408 }
3409 }
7b128766 3410 /*
a8c9e576
JB
3411 * Inode is already gone but the orphan item is still there,
3412 * kill the orphan item.
7b128766 3413 */
a8c9e576
JB
3414 if (ret == -ESTALE) {
3415 trans = btrfs_start_transaction(root, 1);
66b4ffd1
JB
3416 if (IS_ERR(trans)) {
3417 ret = PTR_ERR(trans);
3418 goto out;
3419 }
c2cf52eb
SK
3420 btrfs_debug(root->fs_info, "auto deleting %Lu",
3421 found_key.objectid);
a8c9e576
JB
3422 ret = btrfs_del_orphan_item(trans, root,
3423 found_key.objectid);
5b21f2ed 3424 btrfs_end_transaction(trans, root);
4ef31a45
JB
3425 if (ret)
3426 goto out;
7b128766
JB
3427 continue;
3428 }
3429
a8c9e576
JB
3430 /*
3431 * add this inode to the orphan list so btrfs_orphan_del does
3432 * the proper thing when we hit it
3433 */
8a35d95f
JB
3434 set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3435 &BTRFS_I(inode)->runtime_flags);
925396ec 3436 atomic_inc(&root->orphan_inodes);
a8c9e576 3437
7b128766
JB
3438 /* if we have links, this was a truncate, lets do that */
3439 if (inode->i_nlink) {
fae7f21c 3440 if (WARN_ON(!S_ISREG(inode->i_mode))) {
a41ad394
JB
3441 iput(inode);
3442 continue;
3443 }
7b128766 3444 nr_truncate++;
f3fe820c
JB
3445
3446 /* 1 for the orphan item deletion. */
3447 trans = btrfs_start_transaction(root, 1);
3448 if (IS_ERR(trans)) {
c69b26b0 3449 iput(inode);
f3fe820c
JB
3450 ret = PTR_ERR(trans);
3451 goto out;
3452 }
3453 ret = btrfs_orphan_add(trans, inode);
3454 btrfs_end_transaction(trans, root);
c69b26b0
JB
3455 if (ret) {
3456 iput(inode);
f3fe820c 3457 goto out;
c69b26b0 3458 }
f3fe820c 3459
66b4ffd1 3460 ret = btrfs_truncate(inode);
4a7d0f68
JB
3461 if (ret)
3462 btrfs_orphan_del(NULL, inode);
7b128766
JB
3463 } else {
3464 nr_unlink++;
3465 }
3466
3467 /* this will do delete_inode and everything for us */
3468 iput(inode);
66b4ffd1
JB
3469 if (ret)
3470 goto out;
7b128766 3471 }
3254c876
MX
3472 /* release the path since we're done with it */
3473 btrfs_release_path(path);
3474
d68fc57b
YZ
3475 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3476
3477 if (root->orphan_block_rsv)
3478 btrfs_block_rsv_release(root, root->orphan_block_rsv,
3479 (u64)-1);
3480
27cdeb70
MX
3481 if (root->orphan_block_rsv ||
3482 test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
7a7eaa40 3483 trans = btrfs_join_transaction(root);
66b4ffd1
JB
3484 if (!IS_ERR(trans))
3485 btrfs_end_transaction(trans, root);
d68fc57b 3486 }
7b128766
JB
3487
3488 if (nr_unlink)
4884b476 3489 btrfs_debug(root->fs_info, "unlinked %d orphans", nr_unlink);
7b128766 3490 if (nr_truncate)
4884b476 3491 btrfs_debug(root->fs_info, "truncated %d orphans", nr_truncate);
66b4ffd1
JB
3492
3493out:
3494 if (ret)
68b663d1 3495 btrfs_err(root->fs_info,
c2cf52eb 3496 "could not do orphan cleanup %d", ret);
66b4ffd1
JB
3497 btrfs_free_path(path);
3498 return ret;
7b128766
JB
3499}
3500
46a53cca
CM
3501/*
3502 * very simple check to peek ahead in the leaf looking for xattrs. If we
3503 * don't find any xattrs, we know there can't be any acls.
3504 *
3505 * slot is the slot the inode is in, objectid is the objectid of the inode
3506 */
3507static noinline int acls_after_inode_item(struct extent_buffer *leaf,
63541927
FDBM
3508 int slot, u64 objectid,
3509 int *first_xattr_slot)
46a53cca
CM
3510{
3511 u32 nritems = btrfs_header_nritems(leaf);
3512 struct btrfs_key found_key;
f23b5a59
JB
3513 static u64 xattr_access = 0;
3514 static u64 xattr_default = 0;
46a53cca
CM
3515 int scanned = 0;
3516
f23b5a59
JB
3517 if (!xattr_access) {
3518 xattr_access = btrfs_name_hash(POSIX_ACL_XATTR_ACCESS,
3519 strlen(POSIX_ACL_XATTR_ACCESS));
3520 xattr_default = btrfs_name_hash(POSIX_ACL_XATTR_DEFAULT,
3521 strlen(POSIX_ACL_XATTR_DEFAULT));
3522 }
3523
46a53cca 3524 slot++;
63541927 3525 *first_xattr_slot = -1;
46a53cca
CM
3526 while (slot < nritems) {
3527 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3528
3529 /* we found a different objectid, there must not be acls */
3530 if (found_key.objectid != objectid)
3531 return 0;
3532
3533 /* we found an xattr, assume we've got an acl */
f23b5a59 3534 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
63541927
FDBM
3535 if (*first_xattr_slot == -1)
3536 *first_xattr_slot = slot;
f23b5a59
JB
3537 if (found_key.offset == xattr_access ||
3538 found_key.offset == xattr_default)
3539 return 1;
3540 }
46a53cca
CM
3541
3542 /*
3543 * we found a key greater than an xattr key, there can't
3544 * be any acls later on
3545 */
3546 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3547 return 0;
3548
3549 slot++;
3550 scanned++;
3551
3552 /*
3553 * it goes inode, inode backrefs, xattrs, extents,
3554 * so if there are a ton of hard links to an inode there can
3555 * be a lot of backrefs. Don't waste time searching too hard,
3556 * this is just an optimization
3557 */
3558 if (scanned >= 8)
3559 break;
3560 }
3561 /* we hit the end of the leaf before we found an xattr or
3562 * something larger than an xattr. We have to assume the inode
3563 * has acls
3564 */
63541927
FDBM
3565 if (*first_xattr_slot == -1)
3566 *first_xattr_slot = slot;
46a53cca
CM
3567 return 1;
3568}
3569
d352ac68
CM
3570/*
3571 * read an inode from the btree into the in-memory inode
3572 */
5d4f98a2 3573static void btrfs_read_locked_inode(struct inode *inode)
39279cc3
CM
3574{
3575 struct btrfs_path *path;
5f39d397 3576 struct extent_buffer *leaf;
39279cc3
CM
3577 struct btrfs_inode_item *inode_item;
3578 struct btrfs_root *root = BTRFS_I(inode)->root;
3579 struct btrfs_key location;
67de1176 3580 unsigned long ptr;
46a53cca 3581 int maybe_acls;
618e21d5 3582 u32 rdev;
39279cc3 3583 int ret;
2f7e33d4 3584 bool filled = false;
63541927 3585 int first_xattr_slot;
2f7e33d4
MX
3586
3587 ret = btrfs_fill_inode(inode, &rdev);
3588 if (!ret)
3589 filled = true;
39279cc3
CM
3590
3591 path = btrfs_alloc_path();
1748f843
MF
3592 if (!path)
3593 goto make_bad;
3594
39279cc3 3595 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
dc17ff8f 3596
39279cc3 3597 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
5f39d397 3598 if (ret)
39279cc3 3599 goto make_bad;
39279cc3 3600
5f39d397 3601 leaf = path->nodes[0];
2f7e33d4
MX
3602
3603 if (filled)
67de1176 3604 goto cache_index;
2f7e33d4 3605
5f39d397
CM
3606 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3607 struct btrfs_inode_item);
5f39d397 3608 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
bfe86848 3609 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
2f2f43d3
EB
3610 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3611 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
dbe674a9 3612 btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
5f39d397 3613
a937b979
DS
3614 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3615 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
5f39d397 3616
a937b979
DS
3617 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3618 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
5f39d397 3619
a937b979
DS
3620 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3621 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
5f39d397 3622
9cc97d64 3623 BTRFS_I(inode)->i_otime.tv_sec =
3624 btrfs_timespec_sec(leaf, &inode_item->otime);
3625 BTRFS_I(inode)->i_otime.tv_nsec =
3626 btrfs_timespec_nsec(leaf, &inode_item->otime);
5f39d397 3627
a76a3cd4 3628 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
e02119d5 3629 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
5dc562c5
JB
3630 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3631
3632 /*
3633 * If we were modified in the current generation and evicted from memory
3634 * and then re-read we need to do a full sync since we don't have any
3635 * idea about which extents were modified before we were evicted from
3636 * cache.
3637 */
3638 if (BTRFS_I(inode)->last_trans == root->fs_info->generation)
3639 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3640 &BTRFS_I(inode)->runtime_flags);
3641
0c4d2d95 3642 inode->i_version = btrfs_inode_sequence(leaf, inode_item);
e02119d5 3643 inode->i_generation = BTRFS_I(inode)->generation;
618e21d5 3644 inode->i_rdev = 0;
5f39d397
CM
3645 rdev = btrfs_inode_rdev(leaf, inode_item);
3646
aec7477b 3647 BTRFS_I(inode)->index_cnt = (u64)-1;
d2fb3437 3648 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
67de1176
MX
3649
3650cache_index:
3651 path->slots[0]++;
3652 if (inode->i_nlink != 1 ||
3653 path->slots[0] >= btrfs_header_nritems(leaf))
3654 goto cache_acl;
3655
3656 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3657 if (location.objectid != btrfs_ino(inode))
3658 goto cache_acl;
3659
3660 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3661 if (location.type == BTRFS_INODE_REF_KEY) {
3662 struct btrfs_inode_ref *ref;
3663
3664 ref = (struct btrfs_inode_ref *)ptr;
3665 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3666 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3667 struct btrfs_inode_extref *extref;
3668
3669 extref = (struct btrfs_inode_extref *)ptr;
3670 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3671 extref);
3672 }
2f7e33d4 3673cache_acl:
46a53cca
CM
3674 /*
3675 * try to precache a NULL acl entry for files that don't have
3676 * any xattrs or acls
3677 */
33345d01 3678 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
63541927
FDBM
3679 btrfs_ino(inode), &first_xattr_slot);
3680 if (first_xattr_slot != -1) {
3681 path->slots[0] = first_xattr_slot;
3682 ret = btrfs_load_inode_props(inode, path);
3683 if (ret)
3684 btrfs_err(root->fs_info,
351fd353 3685 "error loading props for ino %llu (root %llu): %d",
63541927
FDBM
3686 btrfs_ino(inode),
3687 root->root_key.objectid, ret);
3688 }
3689 btrfs_free_path(path);
3690
72c04902
AV
3691 if (!maybe_acls)
3692 cache_no_acl(inode);
46a53cca 3693
39279cc3 3694 switch (inode->i_mode & S_IFMT) {
39279cc3
CM
3695 case S_IFREG:
3696 inode->i_mapping->a_ops = &btrfs_aops;
d1310b2e 3697 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
39279cc3
CM
3698 inode->i_fop = &btrfs_file_operations;
3699 inode->i_op = &btrfs_file_inode_operations;
3700 break;
3701 case S_IFDIR:
3702 inode->i_fop = &btrfs_dir_file_operations;
3703 if (root == root->fs_info->tree_root)
3704 inode->i_op = &btrfs_dir_ro_inode_operations;
3705 else
3706 inode->i_op = &btrfs_dir_inode_operations;
3707 break;
3708 case S_IFLNK:
3709 inode->i_op = &btrfs_symlink_inode_operations;
3710 inode->i_mapping->a_ops = &btrfs_symlink_aops;
3711 break;
618e21d5 3712 default:
0279b4cd 3713 inode->i_op = &btrfs_special_inode_operations;
618e21d5
JB
3714 init_special_inode(inode, inode->i_mode, rdev);
3715 break;
39279cc3 3716 }
6cbff00f
CH
3717
3718 btrfs_update_iflags(inode);
39279cc3
CM
3719 return;
3720
3721make_bad:
39279cc3 3722 btrfs_free_path(path);
39279cc3
CM
3723 make_bad_inode(inode);
3724}
3725
d352ac68
CM
3726/*
3727 * given a leaf and an inode, copy the inode fields into the leaf
3728 */
e02119d5
CM
3729static void fill_inode_item(struct btrfs_trans_handle *trans,
3730 struct extent_buffer *leaf,
5f39d397 3731 struct btrfs_inode_item *item,
39279cc3
CM
3732 struct inode *inode)
3733{
51fab693
LB
3734 struct btrfs_map_token token;
3735
3736 btrfs_init_map_token(&token);
5f39d397 3737
51fab693
LB
3738 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3739 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3740 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3741 &token);
3742 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3743 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
5f39d397 3744
a937b979 3745 btrfs_set_token_timespec_sec(leaf, &item->atime,
51fab693 3746 inode->i_atime.tv_sec, &token);
a937b979 3747 btrfs_set_token_timespec_nsec(leaf, &item->atime,
51fab693 3748 inode->i_atime.tv_nsec, &token);
5f39d397 3749
a937b979 3750 btrfs_set_token_timespec_sec(leaf, &item->mtime,
51fab693 3751 inode->i_mtime.tv_sec, &token);
a937b979 3752 btrfs_set_token_timespec_nsec(leaf, &item->mtime,
51fab693 3753 inode->i_mtime.tv_nsec, &token);
5f39d397 3754
a937b979 3755 btrfs_set_token_timespec_sec(leaf, &item->ctime,
51fab693 3756 inode->i_ctime.tv_sec, &token);
a937b979 3757 btrfs_set_token_timespec_nsec(leaf, &item->ctime,
51fab693 3758 inode->i_ctime.tv_nsec, &token);
5f39d397 3759
9cc97d64 3760 btrfs_set_token_timespec_sec(leaf, &item->otime,
3761 BTRFS_I(inode)->i_otime.tv_sec, &token);
3762 btrfs_set_token_timespec_nsec(leaf, &item->otime,
3763 BTRFS_I(inode)->i_otime.tv_nsec, &token);
3764
51fab693
LB
3765 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3766 &token);
3767 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3768 &token);
3769 btrfs_set_token_inode_sequence(leaf, item, inode->i_version, &token);
3770 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3771 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3772 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3773 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
39279cc3
CM
3774}
3775
d352ac68
CM
3776/*
3777 * copy everything in the in-memory inode into the btree.
3778 */
2115133f 3779static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
d397712b 3780 struct btrfs_root *root, struct inode *inode)
39279cc3
CM
3781{
3782 struct btrfs_inode_item *inode_item;
3783 struct btrfs_path *path;
5f39d397 3784 struct extent_buffer *leaf;
39279cc3
CM
3785 int ret;
3786
3787 path = btrfs_alloc_path();
16cdcec7
MX
3788 if (!path)
3789 return -ENOMEM;
3790
b9473439 3791 path->leave_spinning = 1;
16cdcec7
MX
3792 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3793 1);
39279cc3
CM
3794 if (ret) {
3795 if (ret > 0)
3796 ret = -ENOENT;
3797 goto failed;
3798 }
3799
5f39d397
CM
3800 leaf = path->nodes[0];
3801 inode_item = btrfs_item_ptr(leaf, path->slots[0],
16cdcec7 3802 struct btrfs_inode_item);
39279cc3 3803
e02119d5 3804 fill_inode_item(trans, leaf, inode_item, inode);
5f39d397 3805 btrfs_mark_buffer_dirty(leaf);
15ee9bc7 3806 btrfs_set_inode_last_trans(trans, inode);
39279cc3
CM
3807 ret = 0;
3808failed:
39279cc3
CM
3809 btrfs_free_path(path);
3810 return ret;
3811}
3812
2115133f
CM
3813/*
3814 * copy everything in the in-memory inode into the btree.
3815 */
3816noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3817 struct btrfs_root *root, struct inode *inode)
3818{
3819 int ret;
3820
3821 /*
3822 * If the inode is a free space inode, we can deadlock during commit
3823 * if we put it into the delayed code.
3824 *
3825 * The data relocation inode should also be directly updated
3826 * without delay
3827 */
83eea1f1 3828 if (!btrfs_is_free_space_inode(inode)
1d52c78a
JB
3829 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
3830 && !root->fs_info->log_root_recovering) {
8ea05e3a
AB
3831 btrfs_update_root_times(trans, root);
3832
2115133f
CM
3833 ret = btrfs_delayed_update_inode(trans, root, inode);
3834 if (!ret)
3835 btrfs_set_inode_last_trans(trans, inode);
3836 return ret;
3837 }
3838
3839 return btrfs_update_inode_item(trans, root, inode);
3840}
3841
be6aef60
JB
3842noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3843 struct btrfs_root *root,
3844 struct inode *inode)
2115133f
CM
3845{
3846 int ret;
3847
3848 ret = btrfs_update_inode(trans, root, inode);
3849 if (ret == -ENOSPC)
3850 return btrfs_update_inode_item(trans, root, inode);
3851 return ret;
3852}
3853
d352ac68
CM
3854/*
3855 * unlink helper that gets used here in inode.c and in the tree logging
3856 * recovery code. It remove a link in a directory with a given name, and
3857 * also drops the back refs in the inode to the directory
3858 */
92986796
AV
3859static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3860 struct btrfs_root *root,
3861 struct inode *dir, struct inode *inode,
3862 const char *name, int name_len)
39279cc3
CM
3863{
3864 struct btrfs_path *path;
39279cc3 3865 int ret = 0;
5f39d397 3866 struct extent_buffer *leaf;
39279cc3 3867 struct btrfs_dir_item *di;
5f39d397 3868 struct btrfs_key key;
aec7477b 3869 u64 index;
33345d01
LZ
3870 u64 ino = btrfs_ino(inode);
3871 u64 dir_ino = btrfs_ino(dir);
39279cc3
CM
3872
3873 path = btrfs_alloc_path();
54aa1f4d
CM
3874 if (!path) {
3875 ret = -ENOMEM;
554233a6 3876 goto out;
54aa1f4d
CM
3877 }
3878
b9473439 3879 path->leave_spinning = 1;
33345d01 3880 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
39279cc3
CM
3881 name, name_len, -1);
3882 if (IS_ERR(di)) {
3883 ret = PTR_ERR(di);
3884 goto err;
3885 }
3886 if (!di) {
3887 ret = -ENOENT;
3888 goto err;
3889 }
5f39d397
CM
3890 leaf = path->nodes[0];
3891 btrfs_dir_item_key_to_cpu(leaf, di, &key);
39279cc3 3892 ret = btrfs_delete_one_dir_name(trans, root, path, di);
54aa1f4d
CM
3893 if (ret)
3894 goto err;
b3b4aa74 3895 btrfs_release_path(path);
39279cc3 3896
67de1176
MX
3897 /*
3898 * If we don't have dir index, we have to get it by looking up
3899 * the inode ref, since we get the inode ref, remove it directly,
3900 * it is unnecessary to do delayed deletion.
3901 *
3902 * But if we have dir index, needn't search inode ref to get it.
3903 * Since the inode ref is close to the inode item, it is better
3904 * that we delay to delete it, and just do this deletion when
3905 * we update the inode item.
3906 */
3907 if (BTRFS_I(inode)->dir_index) {
3908 ret = btrfs_delayed_delete_inode_ref(inode);
3909 if (!ret) {
3910 index = BTRFS_I(inode)->dir_index;
3911 goto skip_backref;
3912 }
3913 }
3914
33345d01
LZ
3915 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
3916 dir_ino, &index);
aec7477b 3917 if (ret) {
c2cf52eb
SK
3918 btrfs_info(root->fs_info,
3919 "failed to delete reference to %.*s, inode %llu parent %llu",
c1c9ff7c 3920 name_len, name, ino, dir_ino);
79787eaa 3921 btrfs_abort_transaction(trans, root, ret);
aec7477b
JB
3922 goto err;
3923 }
67de1176 3924skip_backref:
16cdcec7 3925 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
79787eaa
JM
3926 if (ret) {
3927 btrfs_abort_transaction(trans, root, ret);
39279cc3 3928 goto err;
79787eaa 3929 }
39279cc3 3930
e02119d5 3931 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
33345d01 3932 inode, dir_ino);
79787eaa
JM
3933 if (ret != 0 && ret != -ENOENT) {
3934 btrfs_abort_transaction(trans, root, ret);
3935 goto err;
3936 }
e02119d5
CM
3937
3938 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
3939 dir, index);
6418c961
CM
3940 if (ret == -ENOENT)
3941 ret = 0;
d4e3991b
ZB
3942 else if (ret)
3943 btrfs_abort_transaction(trans, root, ret);
39279cc3
CM
3944err:
3945 btrfs_free_path(path);
e02119d5
CM
3946 if (ret)
3947 goto out;
3948
3949 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
0c4d2d95
JB
3950 inode_inc_iversion(inode);
3951 inode_inc_iversion(dir);
e02119d5 3952 inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME;
b9959295 3953 ret = btrfs_update_inode(trans, root, dir);
e02119d5 3954out:
39279cc3
CM
3955 return ret;
3956}
3957
92986796
AV
3958int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3959 struct btrfs_root *root,
3960 struct inode *dir, struct inode *inode,
3961 const char *name, int name_len)
3962{
3963 int ret;
3964 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
3965 if (!ret) {
8b558c5f 3966 drop_nlink(inode);
92986796
AV
3967 ret = btrfs_update_inode(trans, root, inode);
3968 }
3969 return ret;
3970}
39279cc3 3971
a22285a6
YZ
3972/*
3973 * helper to start transaction for unlink and rmdir.
3974 *
d52be818
JB
3975 * unlink and rmdir are special in btrfs, they do not always free space, so
3976 * if we cannot make our reservations the normal way try and see if there is
3977 * plenty of slack room in the global reserve to migrate, otherwise we cannot
3978 * allow the unlink to occur.
a22285a6 3979 */
d52be818 3980static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
4df27c4d 3981{
39279cc3 3982 struct btrfs_trans_handle *trans;
a22285a6 3983 struct btrfs_root *root = BTRFS_I(dir)->root;
4df27c4d
YZ
3984 int ret;
3985
e70bea5f
JB
3986 /*
3987 * 1 for the possible orphan item
3988 * 1 for the dir item
3989 * 1 for the dir index
3990 * 1 for the inode ref
e70bea5f
JB
3991 * 1 for the inode
3992 */
6e137ed3 3993 trans = btrfs_start_transaction(root, 5);
a22285a6
YZ
3994 if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
3995 return trans;
4df27c4d 3996
d52be818
JB
3997 if (PTR_ERR(trans) == -ENOSPC) {
3998 u64 num_bytes = btrfs_calc_trans_metadata_size(root, 5);
4df27c4d 3999
d52be818
JB
4000 trans = btrfs_start_transaction(root, 0);
4001 if (IS_ERR(trans))
4002 return trans;
4003 ret = btrfs_cond_migrate_bytes(root->fs_info,
4004 &root->fs_info->trans_block_rsv,
4005 num_bytes, 5);
4006 if (ret) {
4007 btrfs_end_transaction(trans, root);
4008 return ERR_PTR(ret);
a22285a6 4009 }
5a77d76c 4010 trans->block_rsv = &root->fs_info->trans_block_rsv;
d52be818 4011 trans->bytes_reserved = num_bytes;
a22285a6 4012 }
d52be818 4013 return trans;
a22285a6
YZ
4014}
4015
4016static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4017{
4018 struct btrfs_root *root = BTRFS_I(dir)->root;
4019 struct btrfs_trans_handle *trans;
4020 struct inode *inode = dentry->d_inode;
4021 int ret;
a22285a6 4022
d52be818 4023 trans = __unlink_start_trans(dir);
a22285a6
YZ
4024 if (IS_ERR(trans))
4025 return PTR_ERR(trans);
5f39d397 4026
12fcfd22
CM
4027 btrfs_record_unlink_dir(trans, dir, dentry->d_inode, 0);
4028
e02119d5
CM
4029 ret = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
4030 dentry->d_name.name, dentry->d_name.len);
b532402e
TI
4031 if (ret)
4032 goto out;
7b128766 4033
a22285a6 4034 if (inode->i_nlink == 0) {
7b128766 4035 ret = btrfs_orphan_add(trans, inode);
b532402e
TI
4036 if (ret)
4037 goto out;
a22285a6 4038 }
7b128766 4039
b532402e 4040out:
d52be818 4041 btrfs_end_transaction(trans, root);
b53d3f5d 4042 btrfs_btree_balance_dirty(root);
39279cc3
CM
4043 return ret;
4044}
4045
4df27c4d
YZ
4046int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4047 struct btrfs_root *root,
4048 struct inode *dir, u64 objectid,
4049 const char *name, int name_len)
4050{
4051 struct btrfs_path *path;
4052 struct extent_buffer *leaf;
4053 struct btrfs_dir_item *di;
4054 struct btrfs_key key;
4055 u64 index;
4056 int ret;
33345d01 4057 u64 dir_ino = btrfs_ino(dir);
4df27c4d
YZ
4058
4059 path = btrfs_alloc_path();
4060 if (!path)
4061 return -ENOMEM;
4062
33345d01 4063 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4df27c4d 4064 name, name_len, -1);
79787eaa
JM
4065 if (IS_ERR_OR_NULL(di)) {
4066 if (!di)
4067 ret = -ENOENT;
4068 else
4069 ret = PTR_ERR(di);
4070 goto out;
4071 }
4df27c4d
YZ
4072
4073 leaf = path->nodes[0];
4074 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4075 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4076 ret = btrfs_delete_one_dir_name(trans, root, path, di);
79787eaa
JM
4077 if (ret) {
4078 btrfs_abort_transaction(trans, root, ret);
4079 goto out;
4080 }
b3b4aa74 4081 btrfs_release_path(path);
4df27c4d
YZ
4082
4083 ret = btrfs_del_root_ref(trans, root->fs_info->tree_root,
4084 objectid, root->root_key.objectid,
33345d01 4085 dir_ino, &index, name, name_len);
4df27c4d 4086 if (ret < 0) {
79787eaa
JM
4087 if (ret != -ENOENT) {
4088 btrfs_abort_transaction(trans, root, ret);
4089 goto out;
4090 }
33345d01 4091 di = btrfs_search_dir_index_item(root, path, dir_ino,
4df27c4d 4092 name, name_len);
79787eaa
JM
4093 if (IS_ERR_OR_NULL(di)) {
4094 if (!di)
4095 ret = -ENOENT;
4096 else
4097 ret = PTR_ERR(di);
4098 btrfs_abort_transaction(trans, root, ret);
4099 goto out;
4100 }
4df27c4d
YZ
4101
4102 leaf = path->nodes[0];
4103 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
b3b4aa74 4104 btrfs_release_path(path);
4df27c4d
YZ
4105 index = key.offset;
4106 }
945d8962 4107 btrfs_release_path(path);
4df27c4d 4108
16cdcec7 4109 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
79787eaa
JM
4110 if (ret) {
4111 btrfs_abort_transaction(trans, root, ret);
4112 goto out;
4113 }
4df27c4d
YZ
4114
4115 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
0c4d2d95 4116 inode_inc_iversion(dir);
4df27c4d 4117 dir->i_mtime = dir->i_ctime = CURRENT_TIME;
5a24e84c 4118 ret = btrfs_update_inode_fallback(trans, root, dir);
79787eaa
JM
4119 if (ret)
4120 btrfs_abort_transaction(trans, root, ret);
4121out:
71d7aed0 4122 btrfs_free_path(path);
79787eaa 4123 return ret;
4df27c4d
YZ
4124}
4125
39279cc3
CM
4126static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4127{
4128 struct inode *inode = dentry->d_inode;
1832a6d5 4129 int err = 0;
39279cc3 4130 struct btrfs_root *root = BTRFS_I(dir)->root;
39279cc3 4131 struct btrfs_trans_handle *trans;
39279cc3 4132
b3ae244e 4133 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
134d4512 4134 return -ENOTEMPTY;
b3ae244e
DS
4135 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID)
4136 return -EPERM;
134d4512 4137
d52be818 4138 trans = __unlink_start_trans(dir);
a22285a6 4139 if (IS_ERR(trans))
5df6a9f6 4140 return PTR_ERR(trans);
5df6a9f6 4141
33345d01 4142 if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4df27c4d
YZ
4143 err = btrfs_unlink_subvol(trans, root, dir,
4144 BTRFS_I(inode)->location.objectid,
4145 dentry->d_name.name,
4146 dentry->d_name.len);
4147 goto out;
4148 }
4149
7b128766
JB
4150 err = btrfs_orphan_add(trans, inode);
4151 if (err)
4df27c4d 4152 goto out;
7b128766 4153
39279cc3 4154 /* now the directory is empty */
e02119d5
CM
4155 err = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
4156 dentry->d_name.name, dentry->d_name.len);
d397712b 4157 if (!err)
dbe674a9 4158 btrfs_i_size_write(inode, 0);
4df27c4d 4159out:
d52be818 4160 btrfs_end_transaction(trans, root);
b53d3f5d 4161 btrfs_btree_balance_dirty(root);
3954401f 4162
39279cc3
CM
4163 return err;
4164}
4165
39279cc3
CM
4166/*
4167 * this can truncate away extent items, csum items and directory items.
4168 * It starts at a high offset and removes keys until it can't find
d352ac68 4169 * any higher than new_size
39279cc3
CM
4170 *
4171 * csum items that cross the new i_size are truncated to the new size
4172 * as well.
7b128766
JB
4173 *
4174 * min_type is the minimum key type to truncate down to. If set to 0, this
4175 * will kill all the items on this inode, including the INODE_ITEM_KEY.
39279cc3 4176 */
8082510e
YZ
4177int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4178 struct btrfs_root *root,
4179 struct inode *inode,
4180 u64 new_size, u32 min_type)
39279cc3 4181{
39279cc3 4182 struct btrfs_path *path;
5f39d397 4183 struct extent_buffer *leaf;
39279cc3 4184 struct btrfs_file_extent_item *fi;
8082510e
YZ
4185 struct btrfs_key key;
4186 struct btrfs_key found_key;
39279cc3 4187 u64 extent_start = 0;
db94535d 4188 u64 extent_num_bytes = 0;
5d4f98a2 4189 u64 extent_offset = 0;
39279cc3 4190 u64 item_end = 0;
7f4f6e0a 4191 u64 last_size = (u64)-1;
8082510e 4192 u32 found_type = (u8)-1;
39279cc3
CM
4193 int found_extent;
4194 int del_item;
85e21bac
CM
4195 int pending_del_nr = 0;
4196 int pending_del_slot = 0;
179e29e4 4197 int extent_type = -1;
8082510e
YZ
4198 int ret;
4199 int err = 0;
33345d01 4200 u64 ino = btrfs_ino(inode);
8082510e
YZ
4201
4202 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
39279cc3 4203
0eb0e19c
MF
4204 path = btrfs_alloc_path();
4205 if (!path)
4206 return -ENOMEM;
4207 path->reada = -1;
4208
5dc562c5
JB
4209 /*
4210 * We want to drop from the next block forward in case this new size is
4211 * not block aligned since we will be keeping the last block of the
4212 * extent just the way it is.
4213 */
27cdeb70
MX
4214 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4215 root == root->fs_info->tree_root)
fda2832f
QW
4216 btrfs_drop_extent_cache(inode, ALIGN(new_size,
4217 root->sectorsize), (u64)-1, 0);
8082510e 4218
16cdcec7
MX
4219 /*
4220 * This function is also used to drop the items in the log tree before
4221 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4222 * it is used to drop the loged items. So we shouldn't kill the delayed
4223 * items.
4224 */
4225 if (min_type == 0 && root == BTRFS_I(inode)->root)
4226 btrfs_kill_delayed_inode_items(inode);
4227
33345d01 4228 key.objectid = ino;
39279cc3 4229 key.offset = (u64)-1;
5f39d397
CM
4230 key.type = (u8)-1;
4231
85e21bac 4232search_again:
b9473439 4233 path->leave_spinning = 1;
85e21bac 4234 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
8082510e
YZ
4235 if (ret < 0) {
4236 err = ret;
4237 goto out;
4238 }
d397712b 4239
85e21bac 4240 if (ret > 0) {
e02119d5
CM
4241 /* there are no items in the tree for us to truncate, we're
4242 * done
4243 */
8082510e
YZ
4244 if (path->slots[0] == 0)
4245 goto out;
85e21bac
CM
4246 path->slots[0]--;
4247 }
4248
d397712b 4249 while (1) {
39279cc3 4250 fi = NULL;
5f39d397
CM
4251 leaf = path->nodes[0];
4252 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
962a298f 4253 found_type = found_key.type;
39279cc3 4254
33345d01 4255 if (found_key.objectid != ino)
39279cc3 4256 break;
5f39d397 4257
85e21bac 4258 if (found_type < min_type)
39279cc3
CM
4259 break;
4260
5f39d397 4261 item_end = found_key.offset;
39279cc3 4262 if (found_type == BTRFS_EXTENT_DATA_KEY) {
5f39d397 4263 fi = btrfs_item_ptr(leaf, path->slots[0],
39279cc3 4264 struct btrfs_file_extent_item);
179e29e4
CM
4265 extent_type = btrfs_file_extent_type(leaf, fi);
4266 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
5f39d397 4267 item_end +=
db94535d 4268 btrfs_file_extent_num_bytes(leaf, fi);
179e29e4 4269 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
179e29e4 4270 item_end += btrfs_file_extent_inline_len(leaf,
514ac8ad 4271 path->slots[0], fi);
39279cc3 4272 }
008630c1 4273 item_end--;
39279cc3 4274 }
8082510e
YZ
4275 if (found_type > min_type) {
4276 del_item = 1;
4277 } else {
4278 if (item_end < new_size)
b888db2b 4279 break;
8082510e
YZ
4280 if (found_key.offset >= new_size)
4281 del_item = 1;
4282 else
4283 del_item = 0;
39279cc3 4284 }
39279cc3 4285 found_extent = 0;
39279cc3 4286 /* FIXME, shrink the extent if the ref count is only 1 */
179e29e4
CM
4287 if (found_type != BTRFS_EXTENT_DATA_KEY)
4288 goto delete;
4289
7f4f6e0a
JB
4290 if (del_item)
4291 last_size = found_key.offset;
4292 else
4293 last_size = new_size;
4294
179e29e4 4295 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
39279cc3 4296 u64 num_dec;
db94535d 4297 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
f70a9a6b 4298 if (!del_item) {
db94535d
CM
4299 u64 orig_num_bytes =
4300 btrfs_file_extent_num_bytes(leaf, fi);
fda2832f
QW
4301 extent_num_bytes = ALIGN(new_size -
4302 found_key.offset,
4303 root->sectorsize);
db94535d
CM
4304 btrfs_set_file_extent_num_bytes(leaf, fi,
4305 extent_num_bytes);
4306 num_dec = (orig_num_bytes -
9069218d 4307 extent_num_bytes);
27cdeb70
MX
4308 if (test_bit(BTRFS_ROOT_REF_COWS,
4309 &root->state) &&
4310 extent_start != 0)
a76a3cd4 4311 inode_sub_bytes(inode, num_dec);
5f39d397 4312 btrfs_mark_buffer_dirty(leaf);
39279cc3 4313 } else {
db94535d
CM
4314 extent_num_bytes =
4315 btrfs_file_extent_disk_num_bytes(leaf,
4316 fi);
5d4f98a2
YZ
4317 extent_offset = found_key.offset -
4318 btrfs_file_extent_offset(leaf, fi);
4319
39279cc3 4320 /* FIXME blocksize != 4096 */
9069218d 4321 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
39279cc3
CM
4322 if (extent_start != 0) {
4323 found_extent = 1;
27cdeb70
MX
4324 if (test_bit(BTRFS_ROOT_REF_COWS,
4325 &root->state))
a76a3cd4 4326 inode_sub_bytes(inode, num_dec);
e02119d5 4327 }
39279cc3 4328 }
9069218d 4329 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
c8b97818
CM
4330 /*
4331 * we can't truncate inline items that have had
4332 * special encodings
4333 */
4334 if (!del_item &&
4335 btrfs_file_extent_compression(leaf, fi) == 0 &&
4336 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4337 btrfs_file_extent_other_encoding(leaf, fi) == 0) {
e02119d5
CM
4338 u32 size = new_size - found_key.offset;
4339
27cdeb70 4340 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
a76a3cd4
YZ
4341 inode_sub_bytes(inode, item_end + 1 -
4342 new_size);
514ac8ad
CM
4343
4344 /*
4345 * update the ram bytes to properly reflect
4346 * the new size of our item
4347 */
4348 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
e02119d5
CM
4349 size =
4350 btrfs_file_extent_calc_inline_size(size);
afe5fea7 4351 btrfs_truncate_item(root, path, size, 1);
27cdeb70
MX
4352 } else if (test_bit(BTRFS_ROOT_REF_COWS,
4353 &root->state)) {
a76a3cd4
YZ
4354 inode_sub_bytes(inode, item_end + 1 -
4355 found_key.offset);
9069218d 4356 }
39279cc3 4357 }
179e29e4 4358delete:
39279cc3 4359 if (del_item) {
85e21bac
CM
4360 if (!pending_del_nr) {
4361 /* no pending yet, add ourselves */
4362 pending_del_slot = path->slots[0];
4363 pending_del_nr = 1;
4364 } else if (pending_del_nr &&
4365 path->slots[0] + 1 == pending_del_slot) {
4366 /* hop on the pending chunk */
4367 pending_del_nr++;
4368 pending_del_slot = path->slots[0];
4369 } else {
d397712b 4370 BUG();
85e21bac 4371 }
39279cc3
CM
4372 } else {
4373 break;
4374 }
27cdeb70
MX
4375 if (found_extent &&
4376 (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4377 root == root->fs_info->tree_root)) {
b9473439 4378 btrfs_set_path_blocking(path);
39279cc3 4379 ret = btrfs_free_extent(trans, root, extent_start,
5d4f98a2
YZ
4380 extent_num_bytes, 0,
4381 btrfs_header_owner(leaf),
66d7e7f0 4382 ino, extent_offset, 0);
39279cc3
CM
4383 BUG_ON(ret);
4384 }
85e21bac 4385
8082510e
YZ
4386 if (found_type == BTRFS_INODE_ITEM_KEY)
4387 break;
4388
4389 if (path->slots[0] == 0 ||
4390 path->slots[0] != pending_del_slot) {
8082510e
YZ
4391 if (pending_del_nr) {
4392 ret = btrfs_del_items(trans, root, path,
4393 pending_del_slot,
4394 pending_del_nr);
79787eaa
JM
4395 if (ret) {
4396 btrfs_abort_transaction(trans,
4397 root, ret);
4398 goto error;
4399 }
8082510e
YZ
4400 pending_del_nr = 0;
4401 }
b3b4aa74 4402 btrfs_release_path(path);
85e21bac 4403 goto search_again;
8082510e
YZ
4404 } else {
4405 path->slots[0]--;
85e21bac 4406 }
39279cc3 4407 }
8082510e 4408out:
85e21bac
CM
4409 if (pending_del_nr) {
4410 ret = btrfs_del_items(trans, root, path, pending_del_slot,
4411 pending_del_nr);
79787eaa
JM
4412 if (ret)
4413 btrfs_abort_transaction(trans, root, ret);
85e21bac 4414 }
79787eaa 4415error:
dac5705c
FM
4416 if (last_size != (u64)-1 &&
4417 root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID)
7f4f6e0a 4418 btrfs_ordered_update_i_size(inode, last_size, NULL);
39279cc3 4419 btrfs_free_path(path);
8082510e 4420 return err;
39279cc3
CM
4421}
4422
4423/*
2aaa6655
JB
4424 * btrfs_truncate_page - read, zero a chunk and write a page
4425 * @inode - inode that we're zeroing
4426 * @from - the offset to start zeroing
4427 * @len - the length to zero, 0 to zero the entire range respective to the
4428 * offset
4429 * @front - zero up to the offset instead of from the offset on
4430 *
4431 * This will find the page for the "from" offset and cow the page and zero the
4432 * part we want to zero. This is used with truncate and hole punching.
39279cc3 4433 */
2aaa6655
JB
4434int btrfs_truncate_page(struct inode *inode, loff_t from, loff_t len,
4435 int front)
39279cc3 4436{
2aaa6655 4437 struct address_space *mapping = inode->i_mapping;
db94535d 4438 struct btrfs_root *root = BTRFS_I(inode)->root;
e6dcd2dc
CM
4439 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4440 struct btrfs_ordered_extent *ordered;
2ac55d41 4441 struct extent_state *cached_state = NULL;
e6dcd2dc 4442 char *kaddr;
db94535d 4443 u32 blocksize = root->sectorsize;
39279cc3
CM
4444 pgoff_t index = from >> PAGE_CACHE_SHIFT;
4445 unsigned offset = from & (PAGE_CACHE_SIZE-1);
4446 struct page *page;
3b16a4e3 4447 gfp_t mask = btrfs_alloc_write_mask(mapping);
39279cc3 4448 int ret = 0;
a52d9a80 4449 u64 page_start;
e6dcd2dc 4450 u64 page_end;
39279cc3 4451
2aaa6655
JB
4452 if ((offset & (blocksize - 1)) == 0 &&
4453 (!len || ((len & (blocksize - 1)) == 0)))
39279cc3 4454 goto out;
0ca1f7ce 4455 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
5d5e103a
JB
4456 if (ret)
4457 goto out;
39279cc3 4458
211c17f5 4459again:
3b16a4e3 4460 page = find_or_create_page(mapping, index, mask);
5d5e103a 4461 if (!page) {
0ca1f7ce 4462 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
ac6a2b36 4463 ret = -ENOMEM;
39279cc3 4464 goto out;
5d5e103a 4465 }
e6dcd2dc
CM
4466
4467 page_start = page_offset(page);
4468 page_end = page_start + PAGE_CACHE_SIZE - 1;
4469
39279cc3 4470 if (!PageUptodate(page)) {
9ebefb18 4471 ret = btrfs_readpage(NULL, page);
39279cc3 4472 lock_page(page);
211c17f5
CM
4473 if (page->mapping != mapping) {
4474 unlock_page(page);
4475 page_cache_release(page);
4476 goto again;
4477 }
39279cc3
CM
4478 if (!PageUptodate(page)) {
4479 ret = -EIO;
89642229 4480 goto out_unlock;
39279cc3
CM
4481 }
4482 }
211c17f5 4483 wait_on_page_writeback(page);
e6dcd2dc 4484
d0082371 4485 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
e6dcd2dc
CM
4486 set_page_extent_mapped(page);
4487
4488 ordered = btrfs_lookup_ordered_extent(inode, page_start);
4489 if (ordered) {
2ac55d41
JB
4490 unlock_extent_cached(io_tree, page_start, page_end,
4491 &cached_state, GFP_NOFS);
e6dcd2dc
CM
4492 unlock_page(page);
4493 page_cache_release(page);
eb84ae03 4494 btrfs_start_ordered_extent(inode, ordered, 1);
e6dcd2dc
CM
4495 btrfs_put_ordered_extent(ordered);
4496 goto again;
4497 }
4498
2ac55d41 4499 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
9e8a4a8b
LB
4500 EXTENT_DIRTY | EXTENT_DELALLOC |
4501 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
2ac55d41 4502 0, 0, &cached_state, GFP_NOFS);
5d5e103a 4503
2ac55d41
JB
4504 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
4505 &cached_state);
9ed74f2d 4506 if (ret) {
2ac55d41
JB
4507 unlock_extent_cached(io_tree, page_start, page_end,
4508 &cached_state, GFP_NOFS);
9ed74f2d
JB
4509 goto out_unlock;
4510 }
4511
e6dcd2dc 4512 if (offset != PAGE_CACHE_SIZE) {
2aaa6655
JB
4513 if (!len)
4514 len = PAGE_CACHE_SIZE - offset;
e6dcd2dc 4515 kaddr = kmap(page);
2aaa6655
JB
4516 if (front)
4517 memset(kaddr, 0, offset);
4518 else
4519 memset(kaddr + offset, 0, len);
e6dcd2dc
CM
4520 flush_dcache_page(page);
4521 kunmap(page);
4522 }
247e743c 4523 ClearPageChecked(page);
e6dcd2dc 4524 set_page_dirty(page);
2ac55d41
JB
4525 unlock_extent_cached(io_tree, page_start, page_end, &cached_state,
4526 GFP_NOFS);
39279cc3 4527
89642229 4528out_unlock:
5d5e103a 4529 if (ret)
0ca1f7ce 4530 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
39279cc3
CM
4531 unlock_page(page);
4532 page_cache_release(page);
4533out:
4534 return ret;
4535}
4536
16e7549f
JB
4537static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4538 u64 offset, u64 len)
4539{
4540 struct btrfs_trans_handle *trans;
4541 int ret;
4542
4543 /*
4544 * Still need to make sure the inode looks like it's been updated so
4545 * that any holes get logged if we fsync.
4546 */
4547 if (btrfs_fs_incompat(root->fs_info, NO_HOLES)) {
4548 BTRFS_I(inode)->last_trans = root->fs_info->generation;
4549 BTRFS_I(inode)->last_sub_trans = root->log_transid;
4550 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4551 return 0;
4552 }
4553
4554 /*
4555 * 1 - for the one we're dropping
4556 * 1 - for the one we're adding
4557 * 1 - for updating the inode.
4558 */
4559 trans = btrfs_start_transaction(root, 3);
4560 if (IS_ERR(trans))
4561 return PTR_ERR(trans);
4562
4563 ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
4564 if (ret) {
4565 btrfs_abort_transaction(trans, root, ret);
4566 btrfs_end_transaction(trans, root);
4567 return ret;
4568 }
4569
4570 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(inode), offset,
4571 0, 0, len, 0, len, 0, 0, 0);
4572 if (ret)
4573 btrfs_abort_transaction(trans, root, ret);
4574 else
4575 btrfs_update_inode(trans, root, inode);
4576 btrfs_end_transaction(trans, root);
4577 return ret;
4578}
4579
695a0d0d
JB
4580/*
4581 * This function puts in dummy file extents for the area we're creating a hole
4582 * for. So if we are truncating this file to a larger size we need to insert
4583 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4584 * the range between oldsize and size
4585 */
a41ad394 4586int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
39279cc3 4587{
9036c102
YZ
4588 struct btrfs_root *root = BTRFS_I(inode)->root;
4589 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
a22285a6 4590 struct extent_map *em = NULL;
2ac55d41 4591 struct extent_state *cached_state = NULL;
5dc562c5 4592 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
fda2832f
QW
4593 u64 hole_start = ALIGN(oldsize, root->sectorsize);
4594 u64 block_end = ALIGN(size, root->sectorsize);
9036c102
YZ
4595 u64 last_byte;
4596 u64 cur_offset;
4597 u64 hole_size;
9ed74f2d 4598 int err = 0;
39279cc3 4599
a71754fc
JB
4600 /*
4601 * If our size started in the middle of a page we need to zero out the
4602 * rest of the page before we expand the i_size, otherwise we could
4603 * expose stale data.
4604 */
4605 err = btrfs_truncate_page(inode, oldsize, 0, 0);
4606 if (err)
4607 return err;
4608
9036c102
YZ
4609 if (size <= hole_start)
4610 return 0;
4611
9036c102
YZ
4612 while (1) {
4613 struct btrfs_ordered_extent *ordered;
fa7c1494 4614
2ac55d41 4615 lock_extent_bits(io_tree, hole_start, block_end - 1, 0,
d0082371 4616 &cached_state);
fa7c1494
MX
4617 ordered = btrfs_lookup_ordered_range(inode, hole_start,
4618 block_end - hole_start);
9036c102
YZ
4619 if (!ordered)
4620 break;
2ac55d41
JB
4621 unlock_extent_cached(io_tree, hole_start, block_end - 1,
4622 &cached_state, GFP_NOFS);
fa7c1494 4623 btrfs_start_ordered_extent(inode, ordered, 1);
9036c102
YZ
4624 btrfs_put_ordered_extent(ordered);
4625 }
39279cc3 4626
9036c102
YZ
4627 cur_offset = hole_start;
4628 while (1) {
4629 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
4630 block_end - cur_offset, 0);
79787eaa
JM
4631 if (IS_ERR(em)) {
4632 err = PTR_ERR(em);
f2767956 4633 em = NULL;
79787eaa
JM
4634 break;
4635 }
9036c102 4636 last_byte = min(extent_map_end(em), block_end);
fda2832f 4637 last_byte = ALIGN(last_byte , root->sectorsize);
8082510e 4638 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
5dc562c5 4639 struct extent_map *hole_em;
9036c102 4640 hole_size = last_byte - cur_offset;
9ed74f2d 4641
16e7549f
JB
4642 err = maybe_insert_hole(root, inode, cur_offset,
4643 hole_size);
4644 if (err)
3893e33b 4645 break;
5dc562c5
JB
4646 btrfs_drop_extent_cache(inode, cur_offset,
4647 cur_offset + hole_size - 1, 0);
4648 hole_em = alloc_extent_map();
4649 if (!hole_em) {
4650 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4651 &BTRFS_I(inode)->runtime_flags);
4652 goto next;
4653 }
4654 hole_em->start = cur_offset;
4655 hole_em->len = hole_size;
4656 hole_em->orig_start = cur_offset;
8082510e 4657
5dc562c5
JB
4658 hole_em->block_start = EXTENT_MAP_HOLE;
4659 hole_em->block_len = 0;
b4939680 4660 hole_em->orig_block_len = 0;
cc95bef6 4661 hole_em->ram_bytes = hole_size;
5dc562c5
JB
4662 hole_em->bdev = root->fs_info->fs_devices->latest_bdev;
4663 hole_em->compress_type = BTRFS_COMPRESS_NONE;
16e7549f 4664 hole_em->generation = root->fs_info->generation;
8082510e 4665
5dc562c5
JB
4666 while (1) {
4667 write_lock(&em_tree->lock);
09a2a8f9 4668 err = add_extent_mapping(em_tree, hole_em, 1);
5dc562c5
JB
4669 write_unlock(&em_tree->lock);
4670 if (err != -EEXIST)
4671 break;
4672 btrfs_drop_extent_cache(inode, cur_offset,
4673 cur_offset +
4674 hole_size - 1, 0);
4675 }
4676 free_extent_map(hole_em);
9036c102 4677 }
16e7549f 4678next:
9036c102 4679 free_extent_map(em);
a22285a6 4680 em = NULL;
9036c102 4681 cur_offset = last_byte;
8082510e 4682 if (cur_offset >= block_end)
9036c102
YZ
4683 break;
4684 }
a22285a6 4685 free_extent_map(em);
2ac55d41
JB
4686 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
4687 GFP_NOFS);
9036c102
YZ
4688 return err;
4689}
39279cc3 4690
9ea24bbe
FM
4691static int wait_snapshoting_atomic_t(atomic_t *a)
4692{
4693 schedule();
4694 return 0;
4695}
4696
4697static void wait_for_snapshot_creation(struct btrfs_root *root)
4698{
4699 while (true) {
4700 int ret;
4701
4702 ret = btrfs_start_write_no_snapshoting(root);
4703 if (ret)
4704 break;
4705 wait_on_atomic_t(&root->will_be_snapshoted,
4706 wait_snapshoting_atomic_t,
4707 TASK_UNINTERRUPTIBLE);
4708 }
4709}
4710
3972f260 4711static int btrfs_setsize(struct inode *inode, struct iattr *attr)
8082510e 4712{
f4a2f4c5
MX
4713 struct btrfs_root *root = BTRFS_I(inode)->root;
4714 struct btrfs_trans_handle *trans;
a41ad394 4715 loff_t oldsize = i_size_read(inode);
3972f260
ES
4716 loff_t newsize = attr->ia_size;
4717 int mask = attr->ia_valid;
8082510e
YZ
4718 int ret;
4719
3972f260
ES
4720 /*
4721 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
4722 * special case where we need to update the times despite not having
4723 * these flags set. For all other operations the VFS set these flags
4724 * explicitly if it wants a timestamp update.
4725 */
dff6efc3
CH
4726 if (newsize != oldsize) {
4727 inode_inc_iversion(inode);
4728 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
4729 inode->i_ctime = inode->i_mtime =
4730 current_fs_time(inode->i_sb);
4731 }
3972f260 4732
a41ad394 4733 if (newsize > oldsize) {
7caef267 4734 truncate_pagecache(inode, newsize);
9ea24bbe
FM
4735 /*
4736 * Don't do an expanding truncate while snapshoting is ongoing.
4737 * This is to ensure the snapshot captures a fully consistent
4738 * state of this file - if the snapshot captures this expanding
4739 * truncation, it must capture all writes that happened before
4740 * this truncation.
4741 */
4742 wait_for_snapshot_creation(root);
a41ad394 4743 ret = btrfs_cont_expand(inode, oldsize, newsize);
9ea24bbe
FM
4744 if (ret) {
4745 btrfs_end_write_no_snapshoting(root);
8082510e 4746 return ret;
9ea24bbe 4747 }
8082510e 4748
f4a2f4c5 4749 trans = btrfs_start_transaction(root, 1);
9ea24bbe
FM
4750 if (IS_ERR(trans)) {
4751 btrfs_end_write_no_snapshoting(root);
f4a2f4c5 4752 return PTR_ERR(trans);
9ea24bbe 4753 }
f4a2f4c5
MX
4754
4755 i_size_write(inode, newsize);
4756 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
4757 ret = btrfs_update_inode(trans, root, inode);
9ea24bbe 4758 btrfs_end_write_no_snapshoting(root);
7ad85bb7 4759 btrfs_end_transaction(trans, root);
a41ad394 4760 } else {
8082510e 4761
a41ad394
JB
4762 /*
4763 * We're truncating a file that used to have good data down to
4764 * zero. Make sure it gets into the ordered flush list so that
4765 * any new writes get down to disk quickly.
4766 */
4767 if (newsize == 0)
72ac3c0d
JB
4768 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
4769 &BTRFS_I(inode)->runtime_flags);
8082510e 4770
f3fe820c
JB
4771 /*
4772 * 1 for the orphan item we're going to add
4773 * 1 for the orphan item deletion.
4774 */
4775 trans = btrfs_start_transaction(root, 2);
4776 if (IS_ERR(trans))
4777 return PTR_ERR(trans);
4778
4779 /*
4780 * We need to do this in case we fail at _any_ point during the
4781 * actual truncate. Once we do the truncate_setsize we could
4782 * invalidate pages which forces any outstanding ordered io to
4783 * be instantly completed which will give us extents that need
4784 * to be truncated. If we fail to get an orphan inode down we
4785 * could have left over extents that were never meant to live,
4786 * so we need to garuntee from this point on that everything
4787 * will be consistent.
4788 */
4789 ret = btrfs_orphan_add(trans, inode);
4790 btrfs_end_transaction(trans, root);
4791 if (ret)
4792 return ret;
4793
a41ad394
JB
4794 /* we don't support swapfiles, so vmtruncate shouldn't fail */
4795 truncate_setsize(inode, newsize);
2e60a51e
MX
4796
4797 /* Disable nonlocked read DIO to avoid the end less truncate */
4798 btrfs_inode_block_unlocked_dio(inode);
4799 inode_dio_wait(inode);
4800 btrfs_inode_resume_unlocked_dio(inode);
4801
a41ad394 4802 ret = btrfs_truncate(inode);
7f4f6e0a
JB
4803 if (ret && inode->i_nlink) {
4804 int err;
4805
4806 /*
4807 * failed to truncate, disk_i_size is only adjusted down
4808 * as we remove extents, so it should represent the true
4809 * size of the inode, so reset the in memory size and
4810 * delete our orphan entry.
4811 */
4812 trans = btrfs_join_transaction(root);
4813 if (IS_ERR(trans)) {
4814 btrfs_orphan_del(NULL, inode);
4815 return ret;
4816 }
4817 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
4818 err = btrfs_orphan_del(trans, inode);
4819 if (err)
4820 btrfs_abort_transaction(trans, root, err);
4821 btrfs_end_transaction(trans, root);
4822 }
8082510e
YZ
4823 }
4824
a41ad394 4825 return ret;
8082510e
YZ
4826}
4827
9036c102
YZ
4828static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
4829{
4830 struct inode *inode = dentry->d_inode;
b83cc969 4831 struct btrfs_root *root = BTRFS_I(inode)->root;
9036c102 4832 int err;
39279cc3 4833
b83cc969
LZ
4834 if (btrfs_root_readonly(root))
4835 return -EROFS;
4836
9036c102
YZ
4837 err = inode_change_ok(inode, attr);
4838 if (err)
4839 return err;
2bf5a725 4840
5a3f23d5 4841 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
3972f260 4842 err = btrfs_setsize(inode, attr);
8082510e
YZ
4843 if (err)
4844 return err;
39279cc3 4845 }
9036c102 4846
1025774c
CH
4847 if (attr->ia_valid) {
4848 setattr_copy(inode, attr);
0c4d2d95 4849 inode_inc_iversion(inode);
22c44fe6 4850 err = btrfs_dirty_inode(inode);
1025774c 4851
22c44fe6 4852 if (!err && attr->ia_valid & ATTR_MODE)
996a710d 4853 err = posix_acl_chmod(inode, inode->i_mode);
1025774c 4854 }
33268eaf 4855
39279cc3
CM
4856 return err;
4857}
61295eb8 4858
131e404a
FDBM
4859/*
4860 * While truncating the inode pages during eviction, we get the VFS calling
4861 * btrfs_invalidatepage() against each page of the inode. This is slow because
4862 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
4863 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
4864 * extent_state structures over and over, wasting lots of time.
4865 *
4866 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
4867 * those expensive operations on a per page basis and do only the ordered io
4868 * finishing, while we release here the extent_map and extent_state structures,
4869 * without the excessive merging and splitting.
4870 */
4871static void evict_inode_truncate_pages(struct inode *inode)
4872{
4873 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4874 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
4875 struct rb_node *node;
4876
4877 ASSERT(inode->i_state & I_FREEING);
91b0abe3 4878 truncate_inode_pages_final(&inode->i_data);
131e404a
FDBM
4879
4880 write_lock(&map_tree->lock);
4881 while (!RB_EMPTY_ROOT(&map_tree->map)) {
4882 struct extent_map *em;
4883
4884 node = rb_first(&map_tree->map);
4885 em = rb_entry(node, struct extent_map, rb_node);
180589ef
WS
4886 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
4887 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
131e404a
FDBM
4888 remove_extent_mapping(map_tree, em);
4889 free_extent_map(em);
7064dd5c
FM
4890 if (need_resched()) {
4891 write_unlock(&map_tree->lock);
4892 cond_resched();
4893 write_lock(&map_tree->lock);
4894 }
131e404a
FDBM
4895 }
4896 write_unlock(&map_tree->lock);
4897
4898 spin_lock(&io_tree->lock);
4899 while (!RB_EMPTY_ROOT(&io_tree->state)) {
4900 struct extent_state *state;
4901 struct extent_state *cached_state = NULL;
4902
4903 node = rb_first(&io_tree->state);
4904 state = rb_entry(node, struct extent_state, rb_node);
4905 atomic_inc(&state->refs);
4906 spin_unlock(&io_tree->lock);
4907
4908 lock_extent_bits(io_tree, state->start, state->end,
4909 0, &cached_state);
4910 clear_extent_bit(io_tree, state->start, state->end,
4911 EXTENT_LOCKED | EXTENT_DIRTY |
4912 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
4913 EXTENT_DEFRAG, 1, 1,
4914 &cached_state, GFP_NOFS);
4915 free_extent_state(state);
4916
7064dd5c 4917 cond_resched();
131e404a
FDBM
4918 spin_lock(&io_tree->lock);
4919 }
4920 spin_unlock(&io_tree->lock);
4921}
4922
bd555975 4923void btrfs_evict_inode(struct inode *inode)
39279cc3
CM
4924{
4925 struct btrfs_trans_handle *trans;
4926 struct btrfs_root *root = BTRFS_I(inode)->root;
726c35fa 4927 struct btrfs_block_rsv *rsv, *global_rsv;
07127184 4928 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
39279cc3
CM
4929 int ret;
4930
1abe9b8a 4931 trace_btrfs_inode_evict(inode);
4932
131e404a
FDBM
4933 evict_inode_truncate_pages(inode);
4934
69e9c6c6
SB
4935 if (inode->i_nlink &&
4936 ((btrfs_root_refs(&root->root_item) != 0 &&
4937 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
4938 btrfs_is_free_space_inode(inode)))
bd555975
AV
4939 goto no_delete;
4940
39279cc3 4941 if (is_bad_inode(inode)) {
7b128766 4942 btrfs_orphan_del(NULL, inode);
39279cc3
CM
4943 goto no_delete;
4944 }
bd555975 4945 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
4a096752 4946 btrfs_wait_ordered_range(inode, 0, (u64)-1);
5f39d397 4947
f612496b
MX
4948 btrfs_free_io_failure_record(inode, 0, (u64)-1);
4949
c71bf099 4950 if (root->fs_info->log_root_recovering) {
6bf02314 4951 BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
8a35d95f 4952 &BTRFS_I(inode)->runtime_flags));
c71bf099
YZ
4953 goto no_delete;
4954 }
4955
76dda93c 4956 if (inode->i_nlink > 0) {
69e9c6c6
SB
4957 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
4958 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
76dda93c
YZ
4959 goto no_delete;
4960 }
4961
0e8c36a9
MX
4962 ret = btrfs_commit_inode_delayed_inode(inode);
4963 if (ret) {
4964 btrfs_orphan_del(NULL, inode);
4965 goto no_delete;
4966 }
4967
66d8f3dd 4968 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
4289a667
JB
4969 if (!rsv) {
4970 btrfs_orphan_del(NULL, inode);
4971 goto no_delete;
4972 }
4a338542 4973 rsv->size = min_size;
ca7e70f5 4974 rsv->failfast = 1;
726c35fa 4975 global_rsv = &root->fs_info->global_block_rsv;
4289a667 4976
dbe674a9 4977 btrfs_i_size_write(inode, 0);
5f39d397 4978
4289a667 4979 /*
8407aa46
MX
4980 * This is a bit simpler than btrfs_truncate since we've already
4981 * reserved our space for our orphan item in the unlink, so we just
4982 * need to reserve some slack space in case we add bytes and update
4983 * inode item when doing the truncate.
4289a667 4984 */
8082510e 4985 while (1) {
08e007d2
MX
4986 ret = btrfs_block_rsv_refill(root, rsv, min_size,
4987 BTRFS_RESERVE_FLUSH_LIMIT);
726c35fa
JB
4988
4989 /*
4990 * Try and steal from the global reserve since we will
4991 * likely not use this space anyway, we want to try as
4992 * hard as possible to get this to work.
4993 */
4994 if (ret)
4995 ret = btrfs_block_rsv_migrate(global_rsv, rsv, min_size);
d68fc57b 4996
d68fc57b 4997 if (ret) {
c2cf52eb
SK
4998 btrfs_warn(root->fs_info,
4999 "Could not get space for a delete, will truncate on mount %d",
5000 ret);
4289a667
JB
5001 btrfs_orphan_del(NULL, inode);
5002 btrfs_free_block_rsv(root, rsv);
5003 goto no_delete;
d68fc57b 5004 }
7b128766 5005
0e8c36a9 5006 trans = btrfs_join_transaction(root);
4289a667
JB
5007 if (IS_ERR(trans)) {
5008 btrfs_orphan_del(NULL, inode);
5009 btrfs_free_block_rsv(root, rsv);
5010 goto no_delete;
d68fc57b 5011 }
7b128766 5012
4289a667
JB
5013 trans->block_rsv = rsv;
5014
d68fc57b 5015 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
ca7e70f5 5016 if (ret != -ENOSPC)
8082510e 5017 break;
85e21bac 5018
8407aa46 5019 trans->block_rsv = &root->fs_info->trans_block_rsv;
8082510e
YZ
5020 btrfs_end_transaction(trans, root);
5021 trans = NULL;
b53d3f5d 5022 btrfs_btree_balance_dirty(root);
8082510e 5023 }
5f39d397 5024
4289a667
JB
5025 btrfs_free_block_rsv(root, rsv);
5026
4ef31a45
JB
5027 /*
5028 * Errors here aren't a big deal, it just means we leave orphan items
5029 * in the tree. They will be cleaned up on the next mount.
5030 */
8082510e 5031 if (ret == 0) {
4289a667 5032 trans->block_rsv = root->orphan_block_rsv;
4ef31a45
JB
5033 btrfs_orphan_del(trans, inode);
5034 } else {
5035 btrfs_orphan_del(NULL, inode);
8082510e 5036 }
54aa1f4d 5037
4289a667 5038 trans->block_rsv = &root->fs_info->trans_block_rsv;
581bb050
LZ
5039 if (!(root == root->fs_info->tree_root ||
5040 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
33345d01 5041 btrfs_return_ino(root, btrfs_ino(inode));
581bb050 5042
54aa1f4d 5043 btrfs_end_transaction(trans, root);
b53d3f5d 5044 btrfs_btree_balance_dirty(root);
39279cc3 5045no_delete:
89042e5a 5046 btrfs_remove_delayed_node(inode);
dbd5768f 5047 clear_inode(inode);
8082510e 5048 return;
39279cc3
CM
5049}
5050
5051/*
5052 * this returns the key found in the dir entry in the location pointer.
5053 * If no dir entries were found, location->objectid is 0.
5054 */
5055static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5056 struct btrfs_key *location)
5057{
5058 const char *name = dentry->d_name.name;
5059 int namelen = dentry->d_name.len;
5060 struct btrfs_dir_item *di;
5061 struct btrfs_path *path;
5062 struct btrfs_root *root = BTRFS_I(dir)->root;
0d9f7f3e 5063 int ret = 0;
39279cc3
CM
5064
5065 path = btrfs_alloc_path();
d8926bb3
MF
5066 if (!path)
5067 return -ENOMEM;
3954401f 5068
33345d01 5069 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir), name,
39279cc3 5070 namelen, 0);
0d9f7f3e
Y
5071 if (IS_ERR(di))
5072 ret = PTR_ERR(di);
d397712b 5073
c704005d 5074 if (IS_ERR_OR_NULL(di))
3954401f 5075 goto out_err;
d397712b 5076
5f39d397 5077 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
39279cc3 5078out:
39279cc3
CM
5079 btrfs_free_path(path);
5080 return ret;
3954401f
CM
5081out_err:
5082 location->objectid = 0;
5083 goto out;
39279cc3
CM
5084}
5085
5086/*
5087 * when we hit a tree root in a directory, the btrfs part of the inode
5088 * needs to be changed to reflect the root directory of the tree root. This
5089 * is kind of like crossing a mount point.
5090 */
5091static int fixup_tree_root_location(struct btrfs_root *root,
4df27c4d
YZ
5092 struct inode *dir,
5093 struct dentry *dentry,
5094 struct btrfs_key *location,
5095 struct btrfs_root **sub_root)
39279cc3 5096{
4df27c4d
YZ
5097 struct btrfs_path *path;
5098 struct btrfs_root *new_root;
5099 struct btrfs_root_ref *ref;
5100 struct extent_buffer *leaf;
1d4c08e0 5101 struct btrfs_key key;
4df27c4d
YZ
5102 int ret;
5103 int err = 0;
39279cc3 5104
4df27c4d
YZ
5105 path = btrfs_alloc_path();
5106 if (!path) {
5107 err = -ENOMEM;
5108 goto out;
5109 }
39279cc3 5110
4df27c4d 5111 err = -ENOENT;
1d4c08e0
DS
5112 key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5113 key.type = BTRFS_ROOT_REF_KEY;
5114 key.offset = location->objectid;
5115
5116 ret = btrfs_search_slot(NULL, root->fs_info->tree_root, &key, path,
5117 0, 0);
4df27c4d
YZ
5118 if (ret) {
5119 if (ret < 0)
5120 err = ret;
5121 goto out;
5122 }
39279cc3 5123
4df27c4d
YZ
5124 leaf = path->nodes[0];
5125 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
33345d01 5126 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
4df27c4d
YZ
5127 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5128 goto out;
39279cc3 5129
4df27c4d
YZ
5130 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5131 (unsigned long)(ref + 1),
5132 dentry->d_name.len);
5133 if (ret)
5134 goto out;
5135
b3b4aa74 5136 btrfs_release_path(path);
4df27c4d
YZ
5137
5138 new_root = btrfs_read_fs_root_no_name(root->fs_info, location);
5139 if (IS_ERR(new_root)) {
5140 err = PTR_ERR(new_root);
5141 goto out;
5142 }
5143
4df27c4d
YZ
5144 *sub_root = new_root;
5145 location->objectid = btrfs_root_dirid(&new_root->root_item);
5146 location->type = BTRFS_INODE_ITEM_KEY;
5147 location->offset = 0;
5148 err = 0;
5149out:
5150 btrfs_free_path(path);
5151 return err;
39279cc3
CM
5152}
5153
5d4f98a2
YZ
5154static void inode_tree_add(struct inode *inode)
5155{
5156 struct btrfs_root *root = BTRFS_I(inode)->root;
5157 struct btrfs_inode *entry;
03e860bd
FNP
5158 struct rb_node **p;
5159 struct rb_node *parent;
cef21937 5160 struct rb_node *new = &BTRFS_I(inode)->rb_node;
33345d01 5161 u64 ino = btrfs_ino(inode);
5d4f98a2 5162
1d3382cb 5163 if (inode_unhashed(inode))
76dda93c 5164 return;
e1409cef 5165 parent = NULL;
5d4f98a2 5166 spin_lock(&root->inode_lock);
e1409cef 5167 p = &root->inode_tree.rb_node;
5d4f98a2
YZ
5168 while (*p) {
5169 parent = *p;
5170 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5171
33345d01 5172 if (ino < btrfs_ino(&entry->vfs_inode))
03e860bd 5173 p = &parent->rb_left;
33345d01 5174 else if (ino > btrfs_ino(&entry->vfs_inode))
03e860bd 5175 p = &parent->rb_right;
5d4f98a2
YZ
5176 else {
5177 WARN_ON(!(entry->vfs_inode.i_state &
a4ffdde6 5178 (I_WILL_FREE | I_FREEING)));
cef21937 5179 rb_replace_node(parent, new, &root->inode_tree);
03e860bd
FNP
5180 RB_CLEAR_NODE(parent);
5181 spin_unlock(&root->inode_lock);
cef21937 5182 return;
5d4f98a2
YZ
5183 }
5184 }
cef21937
FDBM
5185 rb_link_node(new, parent, p);
5186 rb_insert_color(new, &root->inode_tree);
5d4f98a2
YZ
5187 spin_unlock(&root->inode_lock);
5188}
5189
5190static void inode_tree_del(struct inode *inode)
5191{
5192 struct btrfs_root *root = BTRFS_I(inode)->root;
76dda93c 5193 int empty = 0;
5d4f98a2 5194
03e860bd 5195 spin_lock(&root->inode_lock);
5d4f98a2 5196 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5d4f98a2 5197 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5d4f98a2 5198 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
76dda93c 5199 empty = RB_EMPTY_ROOT(&root->inode_tree);
5d4f98a2 5200 }
03e860bd 5201 spin_unlock(&root->inode_lock);
76dda93c 5202
69e9c6c6 5203 if (empty && btrfs_root_refs(&root->root_item) == 0) {
76dda93c
YZ
5204 synchronize_srcu(&root->fs_info->subvol_srcu);
5205 spin_lock(&root->inode_lock);
5206 empty = RB_EMPTY_ROOT(&root->inode_tree);
5207 spin_unlock(&root->inode_lock);
5208 if (empty)
5209 btrfs_add_dead_root(root);
5210 }
5211}
5212
143bede5 5213void btrfs_invalidate_inodes(struct btrfs_root *root)
76dda93c
YZ
5214{
5215 struct rb_node *node;
5216 struct rb_node *prev;
5217 struct btrfs_inode *entry;
5218 struct inode *inode;
5219 u64 objectid = 0;
5220
7813b3db
LB
5221 if (!test_bit(BTRFS_FS_STATE_ERROR, &root->fs_info->fs_state))
5222 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
76dda93c
YZ
5223
5224 spin_lock(&root->inode_lock);
5225again:
5226 node = root->inode_tree.rb_node;
5227 prev = NULL;
5228 while (node) {
5229 prev = node;
5230 entry = rb_entry(node, struct btrfs_inode, rb_node);
5231
33345d01 5232 if (objectid < btrfs_ino(&entry->vfs_inode))
76dda93c 5233 node = node->rb_left;
33345d01 5234 else if (objectid > btrfs_ino(&entry->vfs_inode))
76dda93c
YZ
5235 node = node->rb_right;
5236 else
5237 break;
5238 }
5239 if (!node) {
5240 while (prev) {
5241 entry = rb_entry(prev, struct btrfs_inode, rb_node);
33345d01 5242 if (objectid <= btrfs_ino(&entry->vfs_inode)) {
76dda93c
YZ
5243 node = prev;
5244 break;
5245 }
5246 prev = rb_next(prev);
5247 }
5248 }
5249 while (node) {
5250 entry = rb_entry(node, struct btrfs_inode, rb_node);
33345d01 5251 objectid = btrfs_ino(&entry->vfs_inode) + 1;
76dda93c
YZ
5252 inode = igrab(&entry->vfs_inode);
5253 if (inode) {
5254 spin_unlock(&root->inode_lock);
5255 if (atomic_read(&inode->i_count) > 1)
5256 d_prune_aliases(inode);
5257 /*
45321ac5 5258 * btrfs_drop_inode will have it removed from
76dda93c
YZ
5259 * the inode cache when its usage count
5260 * hits zero.
5261 */
5262 iput(inode);
5263 cond_resched();
5264 spin_lock(&root->inode_lock);
5265 goto again;
5266 }
5267
5268 if (cond_resched_lock(&root->inode_lock))
5269 goto again;
5270
5271 node = rb_next(node);
5272 }
5273 spin_unlock(&root->inode_lock);
5d4f98a2
YZ
5274}
5275
e02119d5
CM
5276static int btrfs_init_locked_inode(struct inode *inode, void *p)
5277{
5278 struct btrfs_iget_args *args = p;
90d3e592
CM
5279 inode->i_ino = args->location->objectid;
5280 memcpy(&BTRFS_I(inode)->location, args->location,
5281 sizeof(*args->location));
e02119d5 5282 BTRFS_I(inode)->root = args->root;
39279cc3
CM
5283 return 0;
5284}
5285
5286static int btrfs_find_actor(struct inode *inode, void *opaque)
5287{
5288 struct btrfs_iget_args *args = opaque;
90d3e592 5289 return args->location->objectid == BTRFS_I(inode)->location.objectid &&
d397712b 5290 args->root == BTRFS_I(inode)->root;
39279cc3
CM
5291}
5292
5d4f98a2 5293static struct inode *btrfs_iget_locked(struct super_block *s,
90d3e592 5294 struct btrfs_key *location,
5d4f98a2 5295 struct btrfs_root *root)
39279cc3
CM
5296{
5297 struct inode *inode;
5298 struct btrfs_iget_args args;
90d3e592 5299 unsigned long hashval = btrfs_inode_hash(location->objectid, root);
778ba82b 5300
90d3e592 5301 args.location = location;
39279cc3
CM
5302 args.root = root;
5303
778ba82b 5304 inode = iget5_locked(s, hashval, btrfs_find_actor,
39279cc3
CM
5305 btrfs_init_locked_inode,
5306 (void *)&args);
5307 return inode;
5308}
5309
1a54ef8c
BR
5310/* Get an inode object given its location and corresponding root.
5311 * Returns in *is_new if the inode was read from disk
5312 */
5313struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
73f73415 5314 struct btrfs_root *root, int *new)
1a54ef8c
BR
5315{
5316 struct inode *inode;
5317
90d3e592 5318 inode = btrfs_iget_locked(s, location, root);
1a54ef8c 5319 if (!inode)
5d4f98a2 5320 return ERR_PTR(-ENOMEM);
1a54ef8c
BR
5321
5322 if (inode->i_state & I_NEW) {
1a54ef8c 5323 btrfs_read_locked_inode(inode);
1748f843
MF
5324 if (!is_bad_inode(inode)) {
5325 inode_tree_add(inode);
5326 unlock_new_inode(inode);
5327 if (new)
5328 *new = 1;
5329 } else {
e0b6d65b
ST
5330 unlock_new_inode(inode);
5331 iput(inode);
5332 inode = ERR_PTR(-ESTALE);
1748f843
MF
5333 }
5334 }
5335
1a54ef8c
BR
5336 return inode;
5337}
5338
4df27c4d
YZ
5339static struct inode *new_simple_dir(struct super_block *s,
5340 struct btrfs_key *key,
5341 struct btrfs_root *root)
5342{
5343 struct inode *inode = new_inode(s);
5344
5345 if (!inode)
5346 return ERR_PTR(-ENOMEM);
5347
4df27c4d
YZ
5348 BTRFS_I(inode)->root = root;
5349 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
72ac3c0d 5350 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
4df27c4d
YZ
5351
5352 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
848cce0d 5353 inode->i_op = &btrfs_dir_ro_inode_operations;
4df27c4d
YZ
5354 inode->i_fop = &simple_dir_operations;
5355 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
9cc97d64 5356 inode->i_mtime = CURRENT_TIME;
5357 inode->i_atime = inode->i_mtime;
5358 inode->i_ctime = inode->i_mtime;
5359 BTRFS_I(inode)->i_otime = inode->i_mtime;
4df27c4d
YZ
5360
5361 return inode;
5362}
5363
3de4586c 5364struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
39279cc3 5365{
d397712b 5366 struct inode *inode;
4df27c4d 5367 struct btrfs_root *root = BTRFS_I(dir)->root;
39279cc3
CM
5368 struct btrfs_root *sub_root = root;
5369 struct btrfs_key location;
76dda93c 5370 int index;
b4aff1f8 5371 int ret = 0;
39279cc3
CM
5372
5373 if (dentry->d_name.len > BTRFS_NAME_LEN)
5374 return ERR_PTR(-ENAMETOOLONG);
5f39d397 5375
39e3c955 5376 ret = btrfs_inode_by_name(dir, dentry, &location);
39279cc3
CM
5377 if (ret < 0)
5378 return ERR_PTR(ret);
5f39d397 5379
4df27c4d 5380 if (location.objectid == 0)
5662344b 5381 return ERR_PTR(-ENOENT);
4df27c4d
YZ
5382
5383 if (location.type == BTRFS_INODE_ITEM_KEY) {
73f73415 5384 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
4df27c4d
YZ
5385 return inode;
5386 }
5387
5388 BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
5389
76dda93c 5390 index = srcu_read_lock(&root->fs_info->subvol_srcu);
4df27c4d
YZ
5391 ret = fixup_tree_root_location(root, dir, dentry,
5392 &location, &sub_root);
5393 if (ret < 0) {
5394 if (ret != -ENOENT)
5395 inode = ERR_PTR(ret);
5396 else
5397 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5398 } else {
73f73415 5399 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
39279cc3 5400 }
76dda93c
YZ
5401 srcu_read_unlock(&root->fs_info->subvol_srcu, index);
5402
34d19bad 5403 if (!IS_ERR(inode) && root != sub_root) {
c71bf099
YZ
5404 down_read(&root->fs_info->cleanup_work_sem);
5405 if (!(inode->i_sb->s_flags & MS_RDONLY))
66b4ffd1 5406 ret = btrfs_orphan_cleanup(sub_root);
c71bf099 5407 up_read(&root->fs_info->cleanup_work_sem);
01cd3367
JB
5408 if (ret) {
5409 iput(inode);
66b4ffd1 5410 inode = ERR_PTR(ret);
01cd3367 5411 }
c71bf099
YZ
5412 }
5413
3de4586c
CM
5414 return inode;
5415}
5416
fe15ce44 5417static int btrfs_dentry_delete(const struct dentry *dentry)
76dda93c
YZ
5418{
5419 struct btrfs_root *root;
848cce0d 5420 struct inode *inode = dentry->d_inode;
76dda93c 5421
848cce0d
LZ
5422 if (!inode && !IS_ROOT(dentry))
5423 inode = dentry->d_parent->d_inode;
76dda93c 5424
848cce0d
LZ
5425 if (inode) {
5426 root = BTRFS_I(inode)->root;
efefb143
YZ
5427 if (btrfs_root_refs(&root->root_item) == 0)
5428 return 1;
848cce0d
LZ
5429
5430 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5431 return 1;
efefb143 5432 }
76dda93c
YZ
5433 return 0;
5434}
5435
b4aff1f8
JB
5436static void btrfs_dentry_release(struct dentry *dentry)
5437{
944a4515 5438 kfree(dentry->d_fsdata);
b4aff1f8
JB
5439}
5440
3de4586c 5441static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
00cd8dd3 5442 unsigned int flags)
3de4586c 5443{
5662344b 5444 struct inode *inode;
a66e7cc6 5445
5662344b
TI
5446 inode = btrfs_lookup_dentry(dir, dentry);
5447 if (IS_ERR(inode)) {
5448 if (PTR_ERR(inode) == -ENOENT)
5449 inode = NULL;
5450 else
5451 return ERR_CAST(inode);
5452 }
5453
41d28bca 5454 return d_splice_alias(inode, dentry);
39279cc3
CM
5455}
5456
16cdcec7 5457unsigned char btrfs_filetype_table[] = {
39279cc3
CM
5458 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
5459};
5460
9cdda8d3 5461static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
39279cc3 5462{
9cdda8d3 5463 struct inode *inode = file_inode(file);
39279cc3
CM
5464 struct btrfs_root *root = BTRFS_I(inode)->root;
5465 struct btrfs_item *item;
5466 struct btrfs_dir_item *di;
5467 struct btrfs_key key;
5f39d397 5468 struct btrfs_key found_key;
39279cc3 5469 struct btrfs_path *path;
16cdcec7
MX
5470 struct list_head ins_list;
5471 struct list_head del_list;
39279cc3 5472 int ret;
5f39d397 5473 struct extent_buffer *leaf;
39279cc3 5474 int slot;
39279cc3
CM
5475 unsigned char d_type;
5476 int over = 0;
5477 u32 di_cur;
5478 u32 di_total;
5479 u32 di_len;
5480 int key_type = BTRFS_DIR_INDEX_KEY;
5f39d397
CM
5481 char tmp_name[32];
5482 char *name_ptr;
5483 int name_len;
9cdda8d3 5484 int is_curr = 0; /* ctx->pos points to the current index? */
39279cc3
CM
5485
5486 /* FIXME, use a real flag for deciding about the key type */
5487 if (root->fs_info->tree_root == root)
5488 key_type = BTRFS_DIR_ITEM_KEY;
5f39d397 5489
9cdda8d3
AV
5490 if (!dir_emit_dots(file, ctx))
5491 return 0;
5492
49593bfa 5493 path = btrfs_alloc_path();
16cdcec7
MX
5494 if (!path)
5495 return -ENOMEM;
ff5714cc 5496
026fd317 5497 path->reada = 1;
49593bfa 5498
16cdcec7
MX
5499 if (key_type == BTRFS_DIR_INDEX_KEY) {
5500 INIT_LIST_HEAD(&ins_list);
5501 INIT_LIST_HEAD(&del_list);
5502 btrfs_get_delayed_items(inode, &ins_list, &del_list);
5503 }
5504
962a298f 5505 key.type = key_type;
9cdda8d3 5506 key.offset = ctx->pos;
33345d01 5507 key.objectid = btrfs_ino(inode);
5f39d397 5508
39279cc3
CM
5509 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5510 if (ret < 0)
5511 goto err;
49593bfa
DW
5512
5513 while (1) {
5f39d397 5514 leaf = path->nodes[0];
39279cc3 5515 slot = path->slots[0];
b9e03af0
LZ
5516 if (slot >= btrfs_header_nritems(leaf)) {
5517 ret = btrfs_next_leaf(root, path);
5518 if (ret < 0)
5519 goto err;
5520 else if (ret > 0)
5521 break;
5522 continue;
39279cc3 5523 }
3de4586c 5524
dd3cc16b 5525 item = btrfs_item_nr(slot);
5f39d397
CM
5526 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5527
5528 if (found_key.objectid != key.objectid)
39279cc3 5529 break;
962a298f 5530 if (found_key.type != key_type)
39279cc3 5531 break;
9cdda8d3 5532 if (found_key.offset < ctx->pos)
b9e03af0 5533 goto next;
16cdcec7
MX
5534 if (key_type == BTRFS_DIR_INDEX_KEY &&
5535 btrfs_should_delete_dir_index(&del_list,
5536 found_key.offset))
5537 goto next;
5f39d397 5538
9cdda8d3 5539 ctx->pos = found_key.offset;
16cdcec7 5540 is_curr = 1;
49593bfa 5541
39279cc3
CM
5542 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5543 di_cur = 0;
5f39d397 5544 di_total = btrfs_item_size(leaf, item);
49593bfa
DW
5545
5546 while (di_cur < di_total) {
5f39d397
CM
5547 struct btrfs_key location;
5548
22a94d44
JB
5549 if (verify_dir_item(root, leaf, di))
5550 break;
5551
5f39d397 5552 name_len = btrfs_dir_name_len(leaf, di);
49593bfa 5553 if (name_len <= sizeof(tmp_name)) {
5f39d397
CM
5554 name_ptr = tmp_name;
5555 } else {
5556 name_ptr = kmalloc(name_len, GFP_NOFS);
49593bfa
DW
5557 if (!name_ptr) {
5558 ret = -ENOMEM;
5559 goto err;
5560 }
5f39d397
CM
5561 }
5562 read_extent_buffer(leaf, name_ptr,
5563 (unsigned long)(di + 1), name_len);
5564
5565 d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
5566 btrfs_dir_item_key_to_cpu(leaf, di, &location);
3de4586c 5567
fede766f 5568
3de4586c 5569 /* is this a reference to our own snapshot? If so
8c9c2bf7
AJ
5570 * skip it.
5571 *
5572 * In contrast to old kernels, we insert the snapshot's
5573 * dir item and dir index after it has been created, so
5574 * we won't find a reference to our own snapshot. We
5575 * still keep the following code for backward
5576 * compatibility.
3de4586c
CM
5577 */
5578 if (location.type == BTRFS_ROOT_ITEM_KEY &&
5579 location.objectid == root->root_key.objectid) {
5580 over = 0;
5581 goto skip;
5582 }
9cdda8d3
AV
5583 over = !dir_emit(ctx, name_ptr, name_len,
5584 location.objectid, d_type);
5f39d397 5585
3de4586c 5586skip:
5f39d397
CM
5587 if (name_ptr != tmp_name)
5588 kfree(name_ptr);
5589
39279cc3
CM
5590 if (over)
5591 goto nopos;
5103e947 5592 di_len = btrfs_dir_name_len(leaf, di) +
49593bfa 5593 btrfs_dir_data_len(leaf, di) + sizeof(*di);
39279cc3
CM
5594 di_cur += di_len;
5595 di = (struct btrfs_dir_item *)((char *)di + di_len);
5596 }
b9e03af0
LZ
5597next:
5598 path->slots[0]++;
39279cc3 5599 }
49593bfa 5600
16cdcec7
MX
5601 if (key_type == BTRFS_DIR_INDEX_KEY) {
5602 if (is_curr)
9cdda8d3
AV
5603 ctx->pos++;
5604 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
16cdcec7
MX
5605 if (ret)
5606 goto nopos;
5607 }
5608
49593bfa 5609 /* Reached end of directory/root. Bump pos past the last item. */
db62efbb
ZB
5610 ctx->pos++;
5611
5612 /*
5613 * Stop new entries from being returned after we return the last
5614 * entry.
5615 *
5616 * New directory entries are assigned a strictly increasing
5617 * offset. This means that new entries created during readdir
5618 * are *guaranteed* to be seen in the future by that readdir.
5619 * This has broken buggy programs which operate on names as
5620 * they're returned by readdir. Until we re-use freed offsets
5621 * we have this hack to stop new entries from being returned
5622 * under the assumption that they'll never reach this huge
5623 * offset.
5624 *
5625 * This is being careful not to overflow 32bit loff_t unless the
5626 * last entry requires it because doing so has broken 32bit apps
5627 * in the past.
5628 */
5629 if (key_type == BTRFS_DIR_INDEX_KEY) {
5630 if (ctx->pos >= INT_MAX)
5631 ctx->pos = LLONG_MAX;
5632 else
5633 ctx->pos = INT_MAX;
5634 }
39279cc3
CM
5635nopos:
5636 ret = 0;
5637err:
16cdcec7
MX
5638 if (key_type == BTRFS_DIR_INDEX_KEY)
5639 btrfs_put_delayed_items(&ins_list, &del_list);
39279cc3 5640 btrfs_free_path(path);
39279cc3
CM
5641 return ret;
5642}
5643
a9185b41 5644int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
39279cc3
CM
5645{
5646 struct btrfs_root *root = BTRFS_I(inode)->root;
5647 struct btrfs_trans_handle *trans;
5648 int ret = 0;
0af3d00b 5649 bool nolock = false;
39279cc3 5650
72ac3c0d 5651 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
4ca8b41e
CM
5652 return 0;
5653
83eea1f1 5654 if (btrfs_fs_closing(root->fs_info) && btrfs_is_free_space_inode(inode))
82d5902d 5655 nolock = true;
0af3d00b 5656
a9185b41 5657 if (wbc->sync_mode == WB_SYNC_ALL) {
0af3d00b 5658 if (nolock)
7a7eaa40 5659 trans = btrfs_join_transaction_nolock(root);
0af3d00b 5660 else
7a7eaa40 5661 trans = btrfs_join_transaction(root);
3612b495
TI
5662 if (IS_ERR(trans))
5663 return PTR_ERR(trans);
a698d075 5664 ret = btrfs_commit_transaction(trans, root);
39279cc3
CM
5665 }
5666 return ret;
5667}
5668
5669/*
54aa1f4d 5670 * This is somewhat expensive, updating the tree every time the
39279cc3
CM
5671 * inode changes. But, it is most likely to find the inode in cache.
5672 * FIXME, needs more benchmarking...there are no reasons other than performance
5673 * to keep or drop this code.
5674 */
48a3b636 5675static int btrfs_dirty_inode(struct inode *inode)
39279cc3
CM
5676{
5677 struct btrfs_root *root = BTRFS_I(inode)->root;
5678 struct btrfs_trans_handle *trans;
8929ecfa
YZ
5679 int ret;
5680
72ac3c0d 5681 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
22c44fe6 5682 return 0;
39279cc3 5683
7a7eaa40 5684 trans = btrfs_join_transaction(root);
22c44fe6
JB
5685 if (IS_ERR(trans))
5686 return PTR_ERR(trans);
8929ecfa
YZ
5687
5688 ret = btrfs_update_inode(trans, root, inode);
94b60442
CM
5689 if (ret && ret == -ENOSPC) {
5690 /* whoops, lets try again with the full transaction */
5691 btrfs_end_transaction(trans, root);
5692 trans = btrfs_start_transaction(root, 1);
22c44fe6
JB
5693 if (IS_ERR(trans))
5694 return PTR_ERR(trans);
8929ecfa 5695
94b60442 5696 ret = btrfs_update_inode(trans, root, inode);
94b60442 5697 }
39279cc3 5698 btrfs_end_transaction(trans, root);
16cdcec7
MX
5699 if (BTRFS_I(inode)->delayed_node)
5700 btrfs_balance_delayed_items(root);
22c44fe6
JB
5701
5702 return ret;
5703}
5704
5705/*
5706 * This is a copy of file_update_time. We need this so we can return error on
5707 * ENOSPC for updating the inode in the case of file write and mmap writes.
5708 */
e41f941a
JB
5709static int btrfs_update_time(struct inode *inode, struct timespec *now,
5710 int flags)
22c44fe6 5711{
2bc55652
AB
5712 struct btrfs_root *root = BTRFS_I(inode)->root;
5713
5714 if (btrfs_root_readonly(root))
5715 return -EROFS;
5716
e41f941a 5717 if (flags & S_VERSION)
22c44fe6 5718 inode_inc_iversion(inode);
e41f941a
JB
5719 if (flags & S_CTIME)
5720 inode->i_ctime = *now;
5721 if (flags & S_MTIME)
5722 inode->i_mtime = *now;
5723 if (flags & S_ATIME)
5724 inode->i_atime = *now;
5725 return btrfs_dirty_inode(inode);
39279cc3
CM
5726}
5727
d352ac68
CM
5728/*
5729 * find the highest existing sequence number in a directory
5730 * and then set the in-memory index_cnt variable to reflect
5731 * free sequence numbers
5732 */
aec7477b
JB
5733static int btrfs_set_inode_index_count(struct inode *inode)
5734{
5735 struct btrfs_root *root = BTRFS_I(inode)->root;
5736 struct btrfs_key key, found_key;
5737 struct btrfs_path *path;
5738 struct extent_buffer *leaf;
5739 int ret;
5740
33345d01 5741 key.objectid = btrfs_ino(inode);
962a298f 5742 key.type = BTRFS_DIR_INDEX_KEY;
aec7477b
JB
5743 key.offset = (u64)-1;
5744
5745 path = btrfs_alloc_path();
5746 if (!path)
5747 return -ENOMEM;
5748
5749 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5750 if (ret < 0)
5751 goto out;
5752 /* FIXME: we should be able to handle this */
5753 if (ret == 0)
5754 goto out;
5755 ret = 0;
5756
5757 /*
5758 * MAGIC NUMBER EXPLANATION:
5759 * since we search a directory based on f_pos we have to start at 2
5760 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
5761 * else has to start at 2
5762 */
5763 if (path->slots[0] == 0) {
5764 BTRFS_I(inode)->index_cnt = 2;
5765 goto out;
5766 }
5767
5768 path->slots[0]--;
5769
5770 leaf = path->nodes[0];
5771 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5772
33345d01 5773 if (found_key.objectid != btrfs_ino(inode) ||
962a298f 5774 found_key.type != BTRFS_DIR_INDEX_KEY) {
aec7477b
JB
5775 BTRFS_I(inode)->index_cnt = 2;
5776 goto out;
5777 }
5778
5779 BTRFS_I(inode)->index_cnt = found_key.offset + 1;
5780out:
5781 btrfs_free_path(path);
5782 return ret;
5783}
5784
d352ac68
CM
5785/*
5786 * helper to find a free sequence number in a given directory. This current
5787 * code is very simple, later versions will do smarter things in the btree
5788 */
3de4586c 5789int btrfs_set_inode_index(struct inode *dir, u64 *index)
aec7477b
JB
5790{
5791 int ret = 0;
5792
5793 if (BTRFS_I(dir)->index_cnt == (u64)-1) {
16cdcec7
MX
5794 ret = btrfs_inode_delayed_dir_index_count(dir);
5795 if (ret) {
5796 ret = btrfs_set_inode_index_count(dir);
5797 if (ret)
5798 return ret;
5799 }
aec7477b
JB
5800 }
5801
00e4e6b3 5802 *index = BTRFS_I(dir)->index_cnt;
aec7477b
JB
5803 BTRFS_I(dir)->index_cnt++;
5804
5805 return ret;
5806}
5807
b0d5d10f
CM
5808static int btrfs_insert_inode_locked(struct inode *inode)
5809{
5810 struct btrfs_iget_args args;
5811 args.location = &BTRFS_I(inode)->location;
5812 args.root = BTRFS_I(inode)->root;
5813
5814 return insert_inode_locked4(inode,
5815 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
5816 btrfs_find_actor, &args);
5817}
5818
39279cc3
CM
5819static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
5820 struct btrfs_root *root,
aec7477b 5821 struct inode *dir,
9c58309d 5822 const char *name, int name_len,
175a4eb7
AV
5823 u64 ref_objectid, u64 objectid,
5824 umode_t mode, u64 *index)
39279cc3
CM
5825{
5826 struct inode *inode;
5f39d397 5827 struct btrfs_inode_item *inode_item;
39279cc3 5828 struct btrfs_key *location;
5f39d397 5829 struct btrfs_path *path;
9c58309d
CM
5830 struct btrfs_inode_ref *ref;
5831 struct btrfs_key key[2];
5832 u32 sizes[2];
ef3b9af5 5833 int nitems = name ? 2 : 1;
9c58309d 5834 unsigned long ptr;
39279cc3 5835 int ret;
39279cc3 5836
5f39d397 5837 path = btrfs_alloc_path();
d8926bb3
MF
5838 if (!path)
5839 return ERR_PTR(-ENOMEM);
5f39d397 5840
39279cc3 5841 inode = new_inode(root->fs_info->sb);
8fb27640
YS
5842 if (!inode) {
5843 btrfs_free_path(path);
39279cc3 5844 return ERR_PTR(-ENOMEM);
8fb27640 5845 }
39279cc3 5846
5762b5c9
FM
5847 /*
5848 * O_TMPFILE, set link count to 0, so that after this point,
5849 * we fill in an inode item with the correct link count.
5850 */
5851 if (!name)
5852 set_nlink(inode, 0);
5853
581bb050
LZ
5854 /*
5855 * we have to initialize this early, so we can reclaim the inode
5856 * number if we fail afterwards in this function.
5857 */
5858 inode->i_ino = objectid;
5859
ef3b9af5 5860 if (dir && name) {
1abe9b8a 5861 trace_btrfs_inode_request(dir);
5862
3de4586c 5863 ret = btrfs_set_inode_index(dir, index);
09771430 5864 if (ret) {
8fb27640 5865 btrfs_free_path(path);
09771430 5866 iput(inode);
aec7477b 5867 return ERR_PTR(ret);
09771430 5868 }
ef3b9af5
FM
5869 } else if (dir) {
5870 *index = 0;
aec7477b
JB
5871 }
5872 /*
5873 * index_cnt is ignored for everything but a dir,
5874 * btrfs_get_inode_index_count has an explanation for the magic
5875 * number
5876 */
5877 BTRFS_I(inode)->index_cnt = 2;
67de1176 5878 BTRFS_I(inode)->dir_index = *index;
39279cc3 5879 BTRFS_I(inode)->root = root;
e02119d5 5880 BTRFS_I(inode)->generation = trans->transid;
76195853 5881 inode->i_generation = BTRFS_I(inode)->generation;
b888db2b 5882
5dc562c5
JB
5883 /*
5884 * We could have gotten an inode number from somebody who was fsynced
5885 * and then removed in this same transaction, so let's just set full
5886 * sync since it will be a full sync anyway and this will blow away the
5887 * old info in the log.
5888 */
5889 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
5890
9c58309d 5891 key[0].objectid = objectid;
962a298f 5892 key[0].type = BTRFS_INODE_ITEM_KEY;
9c58309d
CM
5893 key[0].offset = 0;
5894
9c58309d 5895 sizes[0] = sizeof(struct btrfs_inode_item);
ef3b9af5
FM
5896
5897 if (name) {
5898 /*
5899 * Start new inodes with an inode_ref. This is slightly more
5900 * efficient for small numbers of hard links since they will
5901 * be packed into one item. Extended refs will kick in if we
5902 * add more hard links than can fit in the ref item.
5903 */
5904 key[1].objectid = objectid;
962a298f 5905 key[1].type = BTRFS_INODE_REF_KEY;
ef3b9af5
FM
5906 key[1].offset = ref_objectid;
5907
5908 sizes[1] = name_len + sizeof(*ref);
5909 }
9c58309d 5910
b0d5d10f
CM
5911 location = &BTRFS_I(inode)->location;
5912 location->objectid = objectid;
5913 location->offset = 0;
962a298f 5914 location->type = BTRFS_INODE_ITEM_KEY;
b0d5d10f
CM
5915
5916 ret = btrfs_insert_inode_locked(inode);
5917 if (ret < 0)
5918 goto fail;
5919
b9473439 5920 path->leave_spinning = 1;
ef3b9af5 5921 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
9c58309d 5922 if (ret != 0)
b0d5d10f 5923 goto fail_unlock;
5f39d397 5924
ecc11fab 5925 inode_init_owner(inode, dir, mode);
a76a3cd4 5926 inode_set_bytes(inode, 0);
9cc97d64 5927
5928 inode->i_mtime = CURRENT_TIME;
5929 inode->i_atime = inode->i_mtime;
5930 inode->i_ctime = inode->i_mtime;
5931 BTRFS_I(inode)->i_otime = inode->i_mtime;
5932
5f39d397
CM
5933 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
5934 struct btrfs_inode_item);
293f7e07
LZ
5935 memset_extent_buffer(path->nodes[0], 0, (unsigned long)inode_item,
5936 sizeof(*inode_item));
e02119d5 5937 fill_inode_item(trans, path->nodes[0], inode_item, inode);
9c58309d 5938
ef3b9af5
FM
5939 if (name) {
5940 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
5941 struct btrfs_inode_ref);
5942 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
5943 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
5944 ptr = (unsigned long)(ref + 1);
5945 write_extent_buffer(path->nodes[0], name, ptr, name_len);
5946 }
9c58309d 5947
5f39d397
CM
5948 btrfs_mark_buffer_dirty(path->nodes[0]);
5949 btrfs_free_path(path);
5950
6cbff00f
CH
5951 btrfs_inherit_iflags(inode, dir);
5952
569254b0 5953 if (S_ISREG(mode)) {
94272164
CM
5954 if (btrfs_test_opt(root, NODATASUM))
5955 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
213490b3 5956 if (btrfs_test_opt(root, NODATACOW))
f2bdf9a8
JB
5957 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
5958 BTRFS_INODE_NODATASUM;
94272164
CM
5959 }
5960
5d4f98a2 5961 inode_tree_add(inode);
1abe9b8a 5962
5963 trace_btrfs_inode_new(inode);
1973f0fa 5964 btrfs_set_inode_last_trans(trans, inode);
1abe9b8a 5965
8ea05e3a
AB
5966 btrfs_update_root_times(trans, root);
5967
63541927
FDBM
5968 ret = btrfs_inode_inherit_props(trans, inode, dir);
5969 if (ret)
5970 btrfs_err(root->fs_info,
5971 "error inheriting props for ino %llu (root %llu): %d",
5972 btrfs_ino(inode), root->root_key.objectid, ret);
5973
39279cc3 5974 return inode;
b0d5d10f
CM
5975
5976fail_unlock:
5977 unlock_new_inode(inode);
5f39d397 5978fail:
ef3b9af5 5979 if (dir && name)
aec7477b 5980 BTRFS_I(dir)->index_cnt--;
5f39d397 5981 btrfs_free_path(path);
09771430 5982 iput(inode);
5f39d397 5983 return ERR_PTR(ret);
39279cc3
CM
5984}
5985
5986static inline u8 btrfs_inode_type(struct inode *inode)
5987{
5988 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
5989}
5990
d352ac68
CM
5991/*
5992 * utility function to add 'inode' into 'parent_inode' with
5993 * a give name and a given sequence number.
5994 * if 'add_backref' is true, also insert a backref from the
5995 * inode to the parent directory.
5996 */
e02119d5
CM
5997int btrfs_add_link(struct btrfs_trans_handle *trans,
5998 struct inode *parent_inode, struct inode *inode,
5999 const char *name, int name_len, int add_backref, u64 index)
39279cc3 6000{
4df27c4d 6001 int ret = 0;
39279cc3 6002 struct btrfs_key key;
e02119d5 6003 struct btrfs_root *root = BTRFS_I(parent_inode)->root;
33345d01
LZ
6004 u64 ino = btrfs_ino(inode);
6005 u64 parent_ino = btrfs_ino(parent_inode);
5f39d397 6006
33345d01 6007 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
4df27c4d
YZ
6008 memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
6009 } else {
33345d01 6010 key.objectid = ino;
962a298f 6011 key.type = BTRFS_INODE_ITEM_KEY;
4df27c4d
YZ
6012 key.offset = 0;
6013 }
6014
33345d01 6015 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
4df27c4d
YZ
6016 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
6017 key.objectid, root->root_key.objectid,
33345d01 6018 parent_ino, index, name, name_len);
4df27c4d 6019 } else if (add_backref) {
33345d01
LZ
6020 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6021 parent_ino, index);
4df27c4d 6022 }
39279cc3 6023
79787eaa
JM
6024 /* Nothing to clean up yet */
6025 if (ret)
6026 return ret;
4df27c4d 6027
79787eaa
JM
6028 ret = btrfs_insert_dir_item(trans, root, name, name_len,
6029 parent_inode, &key,
6030 btrfs_inode_type(inode), index);
9c52057c 6031 if (ret == -EEXIST || ret == -EOVERFLOW)
79787eaa
JM
6032 goto fail_dir_item;
6033 else if (ret) {
6034 btrfs_abort_transaction(trans, root, ret);
6035 return ret;
39279cc3 6036 }
79787eaa
JM
6037
6038 btrfs_i_size_write(parent_inode, parent_inode->i_size +
6039 name_len * 2);
0c4d2d95 6040 inode_inc_iversion(parent_inode);
79787eaa
JM
6041 parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
6042 ret = btrfs_update_inode(trans, root, parent_inode);
6043 if (ret)
6044 btrfs_abort_transaction(trans, root, ret);
39279cc3 6045 return ret;
fe66a05a
CM
6046
6047fail_dir_item:
6048 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6049 u64 local_index;
6050 int err;
6051 err = btrfs_del_root_ref(trans, root->fs_info->tree_root,
6052 key.objectid, root->root_key.objectid,
6053 parent_ino, &local_index, name, name_len);
6054
6055 } else if (add_backref) {
6056 u64 local_index;
6057 int err;
6058
6059 err = btrfs_del_inode_ref(trans, root, name, name_len,
6060 ino, parent_ino, &local_index);
6061 }
6062 return ret;
39279cc3
CM
6063}
6064
6065static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
a1b075d2
JB
6066 struct inode *dir, struct dentry *dentry,
6067 struct inode *inode, int backref, u64 index)
39279cc3 6068{
a1b075d2
JB
6069 int err = btrfs_add_link(trans, dir, inode,
6070 dentry->d_name.name, dentry->d_name.len,
6071 backref, index);
39279cc3
CM
6072 if (err > 0)
6073 err = -EEXIST;
6074 return err;
6075}
6076
618e21d5 6077static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
1a67aafb 6078 umode_t mode, dev_t rdev)
618e21d5
JB
6079{
6080 struct btrfs_trans_handle *trans;
6081 struct btrfs_root *root = BTRFS_I(dir)->root;
1832a6d5 6082 struct inode *inode = NULL;
618e21d5
JB
6083 int err;
6084 int drop_inode = 0;
6085 u64 objectid;
00e4e6b3 6086 u64 index = 0;
618e21d5
JB
6087
6088 if (!new_valid_dev(rdev))
6089 return -EINVAL;
6090
9ed74f2d
JB
6091 /*
6092 * 2 for inode item and ref
6093 * 2 for dir items
6094 * 1 for xattr if selinux is on
6095 */
a22285a6
YZ
6096 trans = btrfs_start_transaction(root, 5);
6097 if (IS_ERR(trans))
6098 return PTR_ERR(trans);
1832a6d5 6099
581bb050
LZ
6100 err = btrfs_find_free_ino(root, &objectid);
6101 if (err)
6102 goto out_unlock;
6103
aec7477b 6104 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
33345d01 6105 dentry->d_name.len, btrfs_ino(dir), objectid,
d82a6f1d 6106 mode, &index);
7cf96da3
TI
6107 if (IS_ERR(inode)) {
6108 err = PTR_ERR(inode);
618e21d5 6109 goto out_unlock;
7cf96da3 6110 }
618e21d5 6111
ad19db71
CS
6112 /*
6113 * If the active LSM wants to access the inode during
6114 * d_instantiate it needs these. Smack checks to see
6115 * if the filesystem supports xattrs by looking at the
6116 * ops vector.
6117 */
ad19db71 6118 inode->i_op = &btrfs_special_inode_operations;
b0d5d10f
CM
6119 init_special_inode(inode, inode->i_mode, rdev);
6120
6121 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
618e21d5 6122 if (err)
b0d5d10f
CM
6123 goto out_unlock_inode;
6124
6125 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
6126 if (err) {
6127 goto out_unlock_inode;
6128 } else {
1b4ab1bb 6129 btrfs_update_inode(trans, root, inode);
b0d5d10f 6130 unlock_new_inode(inode);
08c422c2 6131 d_instantiate(dentry, inode);
618e21d5 6132 }
b0d5d10f 6133
618e21d5 6134out_unlock:
7ad85bb7 6135 btrfs_end_transaction(trans, root);
c581afc8 6136 btrfs_balance_delayed_items(root);
b53d3f5d 6137 btrfs_btree_balance_dirty(root);
618e21d5
JB
6138 if (drop_inode) {
6139 inode_dec_link_count(inode);
6140 iput(inode);
6141 }
618e21d5 6142 return err;
b0d5d10f
CM
6143
6144out_unlock_inode:
6145 drop_inode = 1;
6146 unlock_new_inode(inode);
6147 goto out_unlock;
6148
618e21d5
JB
6149}
6150
39279cc3 6151static int btrfs_create(struct inode *dir, struct dentry *dentry,
ebfc3b49 6152 umode_t mode, bool excl)
39279cc3
CM
6153{
6154 struct btrfs_trans_handle *trans;
6155 struct btrfs_root *root = BTRFS_I(dir)->root;
1832a6d5 6156 struct inode *inode = NULL;
43baa579 6157 int drop_inode_on_err = 0;
a22285a6 6158 int err;
39279cc3 6159 u64 objectid;
00e4e6b3 6160 u64 index = 0;
39279cc3 6161
9ed74f2d
JB
6162 /*
6163 * 2 for inode item and ref
6164 * 2 for dir items
6165 * 1 for xattr if selinux is on
6166 */
a22285a6
YZ
6167 trans = btrfs_start_transaction(root, 5);
6168 if (IS_ERR(trans))
6169 return PTR_ERR(trans);
9ed74f2d 6170
581bb050
LZ
6171 err = btrfs_find_free_ino(root, &objectid);
6172 if (err)
6173 goto out_unlock;
6174
aec7477b 6175 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
33345d01 6176 dentry->d_name.len, btrfs_ino(dir), objectid,
d82a6f1d 6177 mode, &index);
7cf96da3
TI
6178 if (IS_ERR(inode)) {
6179 err = PTR_ERR(inode);
39279cc3 6180 goto out_unlock;
7cf96da3 6181 }
43baa579 6182 drop_inode_on_err = 1;
ad19db71
CS
6183 /*
6184 * If the active LSM wants to access the inode during
6185 * d_instantiate it needs these. Smack checks to see
6186 * if the filesystem supports xattrs by looking at the
6187 * ops vector.
6188 */
6189 inode->i_fop = &btrfs_file_operations;
6190 inode->i_op = &btrfs_file_inode_operations;
b0d5d10f 6191 inode->i_mapping->a_ops = &btrfs_aops;
b0d5d10f
CM
6192
6193 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6194 if (err)
6195 goto out_unlock_inode;
6196
6197 err = btrfs_update_inode(trans, root, inode);
6198 if (err)
6199 goto out_unlock_inode;
ad19db71 6200
a1b075d2 6201 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
39279cc3 6202 if (err)
b0d5d10f 6203 goto out_unlock_inode;
43baa579 6204
43baa579 6205 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
b0d5d10f 6206 unlock_new_inode(inode);
43baa579
FB
6207 d_instantiate(dentry, inode);
6208
39279cc3 6209out_unlock:
7ad85bb7 6210 btrfs_end_transaction(trans, root);
43baa579 6211 if (err && drop_inode_on_err) {
39279cc3
CM
6212 inode_dec_link_count(inode);
6213 iput(inode);
6214 }
c581afc8 6215 btrfs_balance_delayed_items(root);
b53d3f5d 6216 btrfs_btree_balance_dirty(root);
39279cc3 6217 return err;
b0d5d10f
CM
6218
6219out_unlock_inode:
6220 unlock_new_inode(inode);
6221 goto out_unlock;
6222
39279cc3
CM
6223}
6224
6225static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6226 struct dentry *dentry)
6227{
6228 struct btrfs_trans_handle *trans;
6229 struct btrfs_root *root = BTRFS_I(dir)->root;
6230 struct inode *inode = old_dentry->d_inode;
00e4e6b3 6231 u64 index;
39279cc3
CM
6232 int err;
6233 int drop_inode = 0;
6234
4a8be425
TH
6235 /* do not allow sys_link's with other subvols of the same device */
6236 if (root->objectid != BTRFS_I(inode)->root->objectid)
3ab3564f 6237 return -EXDEV;
4a8be425 6238
f186373f 6239 if (inode->i_nlink >= BTRFS_LINK_MAX)
c055e99e 6240 return -EMLINK;
4a8be425 6241
3de4586c 6242 err = btrfs_set_inode_index(dir, &index);
aec7477b
JB
6243 if (err)
6244 goto fail;
6245
a22285a6 6246 /*
7e6b6465 6247 * 2 items for inode and inode ref
a22285a6 6248 * 2 items for dir items
7e6b6465 6249 * 1 item for parent inode
a22285a6 6250 */
7e6b6465 6251 trans = btrfs_start_transaction(root, 5);
a22285a6
YZ
6252 if (IS_ERR(trans)) {
6253 err = PTR_ERR(trans);
6254 goto fail;
6255 }
5f39d397 6256
67de1176
MX
6257 /* There are several dir indexes for this inode, clear the cache. */
6258 BTRFS_I(inode)->dir_index = 0ULL;
8b558c5f 6259 inc_nlink(inode);
0c4d2d95 6260 inode_inc_iversion(inode);
3153495d 6261 inode->i_ctime = CURRENT_TIME;
7de9c6ee 6262 ihold(inode);
e9976151 6263 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
aec7477b 6264
a1b075d2 6265 err = btrfs_add_nondir(trans, dir, dentry, inode, 1, index);
5f39d397 6266
a5719521 6267 if (err) {
54aa1f4d 6268 drop_inode = 1;
a5719521 6269 } else {
10d9f309 6270 struct dentry *parent = dentry->d_parent;
a5719521 6271 err = btrfs_update_inode(trans, root, inode);
79787eaa
JM
6272 if (err)
6273 goto fail;
ef3b9af5
FM
6274 if (inode->i_nlink == 1) {
6275 /*
6276 * If new hard link count is 1, it's a file created
6277 * with open(2) O_TMPFILE flag.
6278 */
6279 err = btrfs_orphan_del(trans, inode);
6280 if (err)
6281 goto fail;
6282 }
08c422c2 6283 d_instantiate(dentry, inode);
6a912213 6284 btrfs_log_new_name(trans, inode, NULL, parent);
a5719521 6285 }
39279cc3 6286
7ad85bb7 6287 btrfs_end_transaction(trans, root);
c581afc8 6288 btrfs_balance_delayed_items(root);
1832a6d5 6289fail:
39279cc3
CM
6290 if (drop_inode) {
6291 inode_dec_link_count(inode);
6292 iput(inode);
6293 }
b53d3f5d 6294 btrfs_btree_balance_dirty(root);
39279cc3
CM
6295 return err;
6296}
6297
18bb1db3 6298static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
39279cc3 6299{
b9d86667 6300 struct inode *inode = NULL;
39279cc3
CM
6301 struct btrfs_trans_handle *trans;
6302 struct btrfs_root *root = BTRFS_I(dir)->root;
6303 int err = 0;
6304 int drop_on_err = 0;
b9d86667 6305 u64 objectid = 0;
00e4e6b3 6306 u64 index = 0;
39279cc3 6307
9ed74f2d
JB
6308 /*
6309 * 2 items for inode and ref
6310 * 2 items for dir items
6311 * 1 for xattr if selinux is on
6312 */
a22285a6
YZ
6313 trans = btrfs_start_transaction(root, 5);
6314 if (IS_ERR(trans))
6315 return PTR_ERR(trans);
39279cc3 6316
581bb050
LZ
6317 err = btrfs_find_free_ino(root, &objectid);
6318 if (err)
6319 goto out_fail;
6320
aec7477b 6321 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
33345d01 6322 dentry->d_name.len, btrfs_ino(dir), objectid,
d82a6f1d 6323 S_IFDIR | mode, &index);
39279cc3
CM
6324 if (IS_ERR(inode)) {
6325 err = PTR_ERR(inode);
6326 goto out_fail;
6327 }
5f39d397 6328
39279cc3 6329 drop_on_err = 1;
b0d5d10f
CM
6330 /* these must be set before we unlock the inode */
6331 inode->i_op = &btrfs_dir_inode_operations;
6332 inode->i_fop = &btrfs_dir_file_operations;
33268eaf 6333
2a7dba39 6334 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
33268eaf 6335 if (err)
b0d5d10f 6336 goto out_fail_inode;
39279cc3 6337
dbe674a9 6338 btrfs_i_size_write(inode, 0);
39279cc3
CM
6339 err = btrfs_update_inode(trans, root, inode);
6340 if (err)
b0d5d10f 6341 goto out_fail_inode;
5f39d397 6342
a1b075d2
JB
6343 err = btrfs_add_link(trans, dir, inode, dentry->d_name.name,
6344 dentry->d_name.len, 0, index);
39279cc3 6345 if (err)
b0d5d10f 6346 goto out_fail_inode;
5f39d397 6347
39279cc3 6348 d_instantiate(dentry, inode);
b0d5d10f
CM
6349 /*
6350 * mkdir is special. We're unlocking after we call d_instantiate
6351 * to avoid a race with nfsd calling d_instantiate.
6352 */
6353 unlock_new_inode(inode);
39279cc3 6354 drop_on_err = 0;
39279cc3
CM
6355
6356out_fail:
7ad85bb7 6357 btrfs_end_transaction(trans, root);
c7cfb8a5
WS
6358 if (drop_on_err) {
6359 inode_dec_link_count(inode);
39279cc3 6360 iput(inode);
c7cfb8a5 6361 }
c581afc8 6362 btrfs_balance_delayed_items(root);
b53d3f5d 6363 btrfs_btree_balance_dirty(root);
39279cc3 6364 return err;
b0d5d10f
CM
6365
6366out_fail_inode:
6367 unlock_new_inode(inode);
6368 goto out_fail;
39279cc3
CM
6369}
6370
e6c4efd8
QW
6371/* Find next extent map of a given extent map, caller needs to ensure locks */
6372static struct extent_map *next_extent_map(struct extent_map *em)
6373{
6374 struct rb_node *next;
6375
6376 next = rb_next(&em->rb_node);
6377 if (!next)
6378 return NULL;
6379 return container_of(next, struct extent_map, rb_node);
6380}
6381
6382static struct extent_map *prev_extent_map(struct extent_map *em)
6383{
6384 struct rb_node *prev;
6385
6386 prev = rb_prev(&em->rb_node);
6387 if (!prev)
6388 return NULL;
6389 return container_of(prev, struct extent_map, rb_node);
6390}
6391
d352ac68 6392/* helper for btfs_get_extent. Given an existing extent in the tree,
e6c4efd8 6393 * the existing extent is the nearest extent to map_start,
d352ac68 6394 * and an extent that you want to insert, deal with overlap and insert
e6c4efd8 6395 * the best fitted new extent into the tree.
d352ac68 6396 */
3b951516
CM
6397static int merge_extent_mapping(struct extent_map_tree *em_tree,
6398 struct extent_map *existing,
e6dcd2dc 6399 struct extent_map *em,
51f395ad 6400 u64 map_start)
3b951516 6401{
e6c4efd8
QW
6402 struct extent_map *prev;
6403 struct extent_map *next;
6404 u64 start;
6405 u64 end;
3b951516 6406 u64 start_diff;
3b951516 6407
e6dcd2dc 6408 BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
e6c4efd8
QW
6409
6410 if (existing->start > map_start) {
6411 next = existing;
6412 prev = prev_extent_map(next);
6413 } else {
6414 prev = existing;
6415 next = next_extent_map(prev);
6416 }
6417
6418 start = prev ? extent_map_end(prev) : em->start;
6419 start = max_t(u64, start, em->start);
6420 end = next ? next->start : extent_map_end(em);
6421 end = min_t(u64, end, extent_map_end(em));
6422 start_diff = start - em->start;
6423 em->start = start;
6424 em->len = end - start;
c8b97818
CM
6425 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
6426 !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
e6dcd2dc 6427 em->block_start += start_diff;
c8b97818
CM
6428 em->block_len -= start_diff;
6429 }
09a2a8f9 6430 return add_extent_mapping(em_tree, em, 0);
3b951516
CM
6431}
6432
c8b97818
CM
6433static noinline int uncompress_inline(struct btrfs_path *path,
6434 struct inode *inode, struct page *page,
6435 size_t pg_offset, u64 extent_offset,
6436 struct btrfs_file_extent_item *item)
6437{
6438 int ret;
6439 struct extent_buffer *leaf = path->nodes[0];
6440 char *tmp;
6441 size_t max_size;
6442 unsigned long inline_size;
6443 unsigned long ptr;
261507a0 6444 int compress_type;
c8b97818
CM
6445
6446 WARN_ON(pg_offset != 0);
261507a0 6447 compress_type = btrfs_file_extent_compression(leaf, item);
c8b97818
CM
6448 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6449 inline_size = btrfs_file_extent_inline_item_len(leaf,
dd3cc16b 6450 btrfs_item_nr(path->slots[0]));
c8b97818 6451 tmp = kmalloc(inline_size, GFP_NOFS);
8d413713
TI
6452 if (!tmp)
6453 return -ENOMEM;
c8b97818
CM
6454 ptr = btrfs_file_extent_inline_start(item);
6455
6456 read_extent_buffer(leaf, tmp, ptr, inline_size);
6457
5b050f04 6458 max_size = min_t(unsigned long, PAGE_CACHE_SIZE, max_size);
261507a0
LZ
6459 ret = btrfs_decompress(compress_type, tmp, page,
6460 extent_offset, inline_size, max_size);
c8b97818 6461 kfree(tmp);
166ae5a4 6462 return ret;
c8b97818
CM
6463}
6464
d352ac68
CM
6465/*
6466 * a bit scary, this does extent mapping from logical file offset to the disk.
d397712b
CM
6467 * the ugly parts come from merging extents from the disk with the in-ram
6468 * representation. This gets more complex because of the data=ordered code,
d352ac68
CM
6469 * where the in-ram extents might be locked pending data=ordered completion.
6470 *
6471 * This also copies inline extents directly into the page.
6472 */
d397712b 6473
a52d9a80 6474struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
70dec807 6475 size_t pg_offset, u64 start, u64 len,
a52d9a80
CM
6476 int create)
6477{
6478 int ret;
6479 int err = 0;
a52d9a80
CM
6480 u64 extent_start = 0;
6481 u64 extent_end = 0;
33345d01 6482 u64 objectid = btrfs_ino(inode);
a52d9a80 6483 u32 found_type;
f421950f 6484 struct btrfs_path *path = NULL;
a52d9a80
CM
6485 struct btrfs_root *root = BTRFS_I(inode)->root;
6486 struct btrfs_file_extent_item *item;
5f39d397
CM
6487 struct extent_buffer *leaf;
6488 struct btrfs_key found_key;
a52d9a80
CM
6489 struct extent_map *em = NULL;
6490 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
d1310b2e 6491 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
a52d9a80 6492 struct btrfs_trans_handle *trans = NULL;
7ffbb598 6493 const bool new_inline = !page || create;
a52d9a80 6494
a52d9a80 6495again:
890871be 6496 read_lock(&em_tree->lock);
d1310b2e 6497 em = lookup_extent_mapping(em_tree, start, len);
a061fc8d
CM
6498 if (em)
6499 em->bdev = root->fs_info->fs_devices->latest_bdev;
890871be 6500 read_unlock(&em_tree->lock);
d1310b2e 6501
a52d9a80 6502 if (em) {
e1c4b745
CM
6503 if (em->start > start || em->start + em->len <= start)
6504 free_extent_map(em);
6505 else if (em->block_start == EXTENT_MAP_INLINE && page)
70dec807
CM
6506 free_extent_map(em);
6507 else
6508 goto out;
a52d9a80 6509 }
172ddd60 6510 em = alloc_extent_map();
a52d9a80 6511 if (!em) {
d1310b2e
CM
6512 err = -ENOMEM;
6513 goto out;
a52d9a80 6514 }
e6dcd2dc 6515 em->bdev = root->fs_info->fs_devices->latest_bdev;
d1310b2e 6516 em->start = EXTENT_MAP_HOLE;
445a6944 6517 em->orig_start = EXTENT_MAP_HOLE;
d1310b2e 6518 em->len = (u64)-1;
c8b97818 6519 em->block_len = (u64)-1;
f421950f
CM
6520
6521 if (!path) {
6522 path = btrfs_alloc_path();
026fd317
JB
6523 if (!path) {
6524 err = -ENOMEM;
6525 goto out;
6526 }
6527 /*
6528 * Chances are we'll be called again, so go ahead and do
6529 * readahead
6530 */
6531 path->reada = 1;
f421950f
CM
6532 }
6533
179e29e4
CM
6534 ret = btrfs_lookup_file_extent(trans, root, path,
6535 objectid, start, trans != NULL);
a52d9a80
CM
6536 if (ret < 0) {
6537 err = ret;
6538 goto out;
6539 }
6540
6541 if (ret != 0) {
6542 if (path->slots[0] == 0)
6543 goto not_found;
6544 path->slots[0]--;
6545 }
6546
5f39d397
CM
6547 leaf = path->nodes[0];
6548 item = btrfs_item_ptr(leaf, path->slots[0],
a52d9a80 6549 struct btrfs_file_extent_item);
a52d9a80 6550 /* are we inside the extent that was found? */
5f39d397 6551 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
962a298f 6552 found_type = found_key.type;
5f39d397 6553 if (found_key.objectid != objectid ||
a52d9a80 6554 found_type != BTRFS_EXTENT_DATA_KEY) {
25a50341
JB
6555 /*
6556 * If we backup past the first extent we want to move forward
6557 * and see if there is an extent in front of us, otherwise we'll
6558 * say there is a hole for our whole search range which can
6559 * cause problems.
6560 */
6561 extent_end = start;
6562 goto next;
a52d9a80
CM
6563 }
6564
5f39d397
CM
6565 found_type = btrfs_file_extent_type(leaf, item);
6566 extent_start = found_key.offset;
d899e052
YZ
6567 if (found_type == BTRFS_FILE_EXTENT_REG ||
6568 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
a52d9a80 6569 extent_end = extent_start +
db94535d 6570 btrfs_file_extent_num_bytes(leaf, item);
9036c102
YZ
6571 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6572 size_t size;
514ac8ad 6573 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
fda2832f 6574 extent_end = ALIGN(extent_start + size, root->sectorsize);
9036c102 6575 }
25a50341 6576next:
9036c102
YZ
6577 if (start >= extent_end) {
6578 path->slots[0]++;
6579 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6580 ret = btrfs_next_leaf(root, path);
6581 if (ret < 0) {
6582 err = ret;
6583 goto out;
a52d9a80 6584 }
9036c102
YZ
6585 if (ret > 0)
6586 goto not_found;
6587 leaf = path->nodes[0];
a52d9a80 6588 }
9036c102
YZ
6589 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6590 if (found_key.objectid != objectid ||
6591 found_key.type != BTRFS_EXTENT_DATA_KEY)
6592 goto not_found;
6593 if (start + len <= found_key.offset)
6594 goto not_found;
e2eca69d
WS
6595 if (start > found_key.offset)
6596 goto next;
9036c102 6597 em->start = start;
70c8a91c 6598 em->orig_start = start;
9036c102
YZ
6599 em->len = found_key.offset - start;
6600 goto not_found_em;
6601 }
6602
7ffbb598
FM
6603 btrfs_extent_item_to_extent_map(inode, path, item, new_inline, em);
6604
d899e052
YZ
6605 if (found_type == BTRFS_FILE_EXTENT_REG ||
6606 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
a52d9a80
CM
6607 goto insert;
6608 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
5f39d397 6609 unsigned long ptr;
a52d9a80 6610 char *map;
3326d1b0
CM
6611 size_t size;
6612 size_t extent_offset;
6613 size_t copy_size;
a52d9a80 6614
7ffbb598 6615 if (new_inline)
689f9346 6616 goto out;
5f39d397 6617
514ac8ad 6618 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
9036c102 6619 extent_offset = page_offset(page) + pg_offset - extent_start;
70dec807 6620 copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
3326d1b0 6621 size - extent_offset);
3326d1b0 6622 em->start = extent_start + extent_offset;
fda2832f 6623 em->len = ALIGN(copy_size, root->sectorsize);
b4939680 6624 em->orig_block_len = em->len;
70c8a91c 6625 em->orig_start = em->start;
689f9346 6626 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
179e29e4 6627 if (create == 0 && !PageUptodate(page)) {
261507a0
LZ
6628 if (btrfs_file_extent_compression(leaf, item) !=
6629 BTRFS_COMPRESS_NONE) {
c8b97818
CM
6630 ret = uncompress_inline(path, inode, page,
6631 pg_offset,
6632 extent_offset, item);
166ae5a4
ZB
6633 if (ret) {
6634 err = ret;
6635 goto out;
6636 }
c8b97818
CM
6637 } else {
6638 map = kmap(page);
6639 read_extent_buffer(leaf, map + pg_offset, ptr,
6640 copy_size);
93c82d57
CM
6641 if (pg_offset + copy_size < PAGE_CACHE_SIZE) {
6642 memset(map + pg_offset + copy_size, 0,
6643 PAGE_CACHE_SIZE - pg_offset -
6644 copy_size);
6645 }
c8b97818
CM
6646 kunmap(page);
6647 }
179e29e4
CM
6648 flush_dcache_page(page);
6649 } else if (create && PageUptodate(page)) {
6bf7e080 6650 BUG();
179e29e4
CM
6651 if (!trans) {
6652 kunmap(page);
6653 free_extent_map(em);
6654 em = NULL;
ff5714cc 6655
b3b4aa74 6656 btrfs_release_path(path);
7a7eaa40 6657 trans = btrfs_join_transaction(root);
ff5714cc 6658
3612b495
TI
6659 if (IS_ERR(trans))
6660 return ERR_CAST(trans);
179e29e4
CM
6661 goto again;
6662 }
c8b97818 6663 map = kmap(page);
70dec807 6664 write_extent_buffer(leaf, map + pg_offset, ptr,
179e29e4 6665 copy_size);
c8b97818 6666 kunmap(page);
179e29e4 6667 btrfs_mark_buffer_dirty(leaf);
a52d9a80 6668 }
d1310b2e 6669 set_extent_uptodate(io_tree, em->start,
507903b8 6670 extent_map_end(em) - 1, NULL, GFP_NOFS);
a52d9a80 6671 goto insert;
a52d9a80
CM
6672 }
6673not_found:
6674 em->start = start;
70c8a91c 6675 em->orig_start = start;
d1310b2e 6676 em->len = len;
a52d9a80 6677not_found_em:
5f39d397 6678 em->block_start = EXTENT_MAP_HOLE;
9036c102 6679 set_bit(EXTENT_FLAG_VACANCY, &em->flags);
a52d9a80 6680insert:
b3b4aa74 6681 btrfs_release_path(path);
d1310b2e 6682 if (em->start > start || extent_map_end(em) <= start) {
c2cf52eb 6683 btrfs_err(root->fs_info, "bad extent! em: [%llu %llu] passed [%llu %llu]",
c1c9ff7c 6684 em->start, em->len, start, len);
a52d9a80
CM
6685 err = -EIO;
6686 goto out;
6687 }
d1310b2e
CM
6688
6689 err = 0;
890871be 6690 write_lock(&em_tree->lock);
09a2a8f9 6691 ret = add_extent_mapping(em_tree, em, 0);
3b951516
CM
6692 /* it is possible that someone inserted the extent into the tree
6693 * while we had the lock dropped. It is also possible that
6694 * an overlapping map exists in the tree
6695 */
a52d9a80 6696 if (ret == -EEXIST) {
3b951516 6697 struct extent_map *existing;
e6dcd2dc
CM
6698
6699 ret = 0;
6700
e6c4efd8
QW
6701 existing = search_extent_mapping(em_tree, start, len);
6702 /*
6703 * existing will always be non-NULL, since there must be
6704 * extent causing the -EEXIST.
6705 */
6706 if (start >= extent_map_end(existing) ||
32be3a1a 6707 start <= existing->start) {
e6c4efd8
QW
6708 /*
6709 * The existing extent map is the one nearest to
6710 * the [start, start + len) range which overlaps
6711 */
6712 err = merge_extent_mapping(em_tree, existing,
6713 em, start);
e1c4b745 6714 free_extent_map(existing);
e6c4efd8 6715 if (err) {
3b951516
CM
6716 free_extent_map(em);
6717 em = NULL;
6718 }
6719 } else {
6720 free_extent_map(em);
6721 em = existing;
e6dcd2dc 6722 err = 0;
a52d9a80 6723 }
a52d9a80 6724 }
890871be 6725 write_unlock(&em_tree->lock);
a52d9a80 6726out:
1abe9b8a 6727
4cd8587c 6728 trace_btrfs_get_extent(root, em);
1abe9b8a 6729
f421950f
CM
6730 if (path)
6731 btrfs_free_path(path);
a52d9a80
CM
6732 if (trans) {
6733 ret = btrfs_end_transaction(trans, root);
d397712b 6734 if (!err)
a52d9a80
CM
6735 err = ret;
6736 }
a52d9a80
CM
6737 if (err) {
6738 free_extent_map(em);
a52d9a80
CM
6739 return ERR_PTR(err);
6740 }
79787eaa 6741 BUG_ON(!em); /* Error is always set */
a52d9a80
CM
6742 return em;
6743}
6744
ec29ed5b
CM
6745struct extent_map *btrfs_get_extent_fiemap(struct inode *inode, struct page *page,
6746 size_t pg_offset, u64 start, u64 len,
6747 int create)
6748{
6749 struct extent_map *em;
6750 struct extent_map *hole_em = NULL;
6751 u64 range_start = start;
6752 u64 end;
6753 u64 found;
6754 u64 found_end;
6755 int err = 0;
6756
6757 em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
6758 if (IS_ERR(em))
6759 return em;
6760 if (em) {
6761 /*
f9e4fb53
LB
6762 * if our em maps to
6763 * - a hole or
6764 * - a pre-alloc extent,
6765 * there might actually be delalloc bytes behind it.
ec29ed5b 6766 */
f9e4fb53
LB
6767 if (em->block_start != EXTENT_MAP_HOLE &&
6768 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
ec29ed5b
CM
6769 return em;
6770 else
6771 hole_em = em;
6772 }
6773
6774 /* check to see if we've wrapped (len == -1 or similar) */
6775 end = start + len;
6776 if (end < start)
6777 end = (u64)-1;
6778 else
6779 end -= 1;
6780
6781 em = NULL;
6782
6783 /* ok, we didn't find anything, lets look for delalloc */
6784 found = count_range_bits(&BTRFS_I(inode)->io_tree, &range_start,
6785 end, len, EXTENT_DELALLOC, 1);
6786 found_end = range_start + found;
6787 if (found_end < range_start)
6788 found_end = (u64)-1;
6789
6790 /*
6791 * we didn't find anything useful, return
6792 * the original results from get_extent()
6793 */
6794 if (range_start > end || found_end <= start) {
6795 em = hole_em;
6796 hole_em = NULL;
6797 goto out;
6798 }
6799
6800 /* adjust the range_start to make sure it doesn't
6801 * go backwards from the start they passed in
6802 */
67871254 6803 range_start = max(start, range_start);
ec29ed5b
CM
6804 found = found_end - range_start;
6805
6806 if (found > 0) {
6807 u64 hole_start = start;
6808 u64 hole_len = len;
6809
172ddd60 6810 em = alloc_extent_map();
ec29ed5b
CM
6811 if (!em) {
6812 err = -ENOMEM;
6813 goto out;
6814 }
6815 /*
6816 * when btrfs_get_extent can't find anything it
6817 * returns one huge hole
6818 *
6819 * make sure what it found really fits our range, and
6820 * adjust to make sure it is based on the start from
6821 * the caller
6822 */
6823 if (hole_em) {
6824 u64 calc_end = extent_map_end(hole_em);
6825
6826 if (calc_end <= start || (hole_em->start > end)) {
6827 free_extent_map(hole_em);
6828 hole_em = NULL;
6829 } else {
6830 hole_start = max(hole_em->start, start);
6831 hole_len = calc_end - hole_start;
6832 }
6833 }
6834 em->bdev = NULL;
6835 if (hole_em && range_start > hole_start) {
6836 /* our hole starts before our delalloc, so we
6837 * have to return just the parts of the hole
6838 * that go until the delalloc starts
6839 */
6840 em->len = min(hole_len,
6841 range_start - hole_start);
6842 em->start = hole_start;
6843 em->orig_start = hole_start;
6844 /*
6845 * don't adjust block start at all,
6846 * it is fixed at EXTENT_MAP_HOLE
6847 */
6848 em->block_start = hole_em->block_start;
6849 em->block_len = hole_len;
f9e4fb53
LB
6850 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
6851 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
ec29ed5b
CM
6852 } else {
6853 em->start = range_start;
6854 em->len = found;
6855 em->orig_start = range_start;
6856 em->block_start = EXTENT_MAP_DELALLOC;
6857 em->block_len = found;
6858 }
6859 } else if (hole_em) {
6860 return hole_em;
6861 }
6862out:
6863
6864 free_extent_map(hole_em);
6865 if (err) {
6866 free_extent_map(em);
6867 return ERR_PTR(err);
6868 }
6869 return em;
6870}
6871
4b46fce2
JB
6872static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
6873 u64 start, u64 len)
6874{
6875 struct btrfs_root *root = BTRFS_I(inode)->root;
70c8a91c 6876 struct extent_map *em;
4b46fce2
JB
6877 struct btrfs_key ins;
6878 u64 alloc_hint;
6879 int ret;
4b46fce2 6880
4b46fce2 6881 alloc_hint = get_extent_allocation_hint(inode, start, len);
00361589 6882 ret = btrfs_reserve_extent(root, len, root->sectorsize, 0,
e570fd27 6883 alloc_hint, &ins, 1, 1);
00361589
JB
6884 if (ret)
6885 return ERR_PTR(ret);
4b46fce2 6886
70c8a91c 6887 em = create_pinned_em(inode, start, ins.offset, start, ins.objectid,
cc95bef6 6888 ins.offset, ins.offset, ins.offset, 0);
00361589 6889 if (IS_ERR(em)) {
e570fd27 6890 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
00361589
JB
6891 return em;
6892 }
4b46fce2
JB
6893
6894 ret = btrfs_add_ordered_extent_dio(inode, start, ins.objectid,
6895 ins.offset, ins.offset, 0);
6896 if (ret) {
e570fd27 6897 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
00361589
JB
6898 free_extent_map(em);
6899 return ERR_PTR(ret);
4b46fce2 6900 }
00361589 6901
4b46fce2
JB
6902 return em;
6903}
6904
46bfbb5c
CM
6905/*
6906 * returns 1 when the nocow is safe, < 1 on error, 0 if the
6907 * block must be cow'd
6908 */
00361589 6909noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7ee9e440
JB
6910 u64 *orig_start, u64 *orig_block_len,
6911 u64 *ram_bytes)
46bfbb5c 6912{
00361589 6913 struct btrfs_trans_handle *trans;
46bfbb5c
CM
6914 struct btrfs_path *path;
6915 int ret;
6916 struct extent_buffer *leaf;
6917 struct btrfs_root *root = BTRFS_I(inode)->root;
7b2b7085 6918 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
46bfbb5c
CM
6919 struct btrfs_file_extent_item *fi;
6920 struct btrfs_key key;
6921 u64 disk_bytenr;
6922 u64 backref_offset;
6923 u64 extent_end;
6924 u64 num_bytes;
6925 int slot;
6926 int found_type;
7ee9e440 6927 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
e77751aa 6928
46bfbb5c
CM
6929 path = btrfs_alloc_path();
6930 if (!path)
6931 return -ENOMEM;
6932
00361589 6933 ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode),
46bfbb5c
CM
6934 offset, 0);
6935 if (ret < 0)
6936 goto out;
6937
6938 slot = path->slots[0];
6939 if (ret == 1) {
6940 if (slot == 0) {
6941 /* can't find the item, must cow */
6942 ret = 0;
6943 goto out;
6944 }
6945 slot--;
6946 }
6947 ret = 0;
6948 leaf = path->nodes[0];
6949 btrfs_item_key_to_cpu(leaf, &key, slot);
33345d01 6950 if (key.objectid != btrfs_ino(inode) ||
46bfbb5c
CM
6951 key.type != BTRFS_EXTENT_DATA_KEY) {
6952 /* not our file or wrong item type, must cow */
6953 goto out;
6954 }
6955
6956 if (key.offset > offset) {
6957 /* Wrong offset, must cow */
6958 goto out;
6959 }
6960
6961 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
6962 found_type = btrfs_file_extent_type(leaf, fi);
6963 if (found_type != BTRFS_FILE_EXTENT_REG &&
6964 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
6965 /* not a regular extent, must cow */
6966 goto out;
6967 }
7ee9e440
JB
6968
6969 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
6970 goto out;
6971
e77751aa
MX
6972 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
6973 if (extent_end <= offset)
6974 goto out;
6975
46bfbb5c 6976 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
7ee9e440
JB
6977 if (disk_bytenr == 0)
6978 goto out;
6979
6980 if (btrfs_file_extent_compression(leaf, fi) ||
6981 btrfs_file_extent_encryption(leaf, fi) ||
6982 btrfs_file_extent_other_encoding(leaf, fi))
6983 goto out;
6984
46bfbb5c
CM
6985 backref_offset = btrfs_file_extent_offset(leaf, fi);
6986
7ee9e440
JB
6987 if (orig_start) {
6988 *orig_start = key.offset - backref_offset;
6989 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
6990 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
6991 }
eb384b55 6992
46bfbb5c
CM
6993 if (btrfs_extent_readonly(root, disk_bytenr))
6994 goto out;
7b2b7085
MX
6995
6996 num_bytes = min(offset + *len, extent_end) - offset;
6997 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6998 u64 range_end;
6999
7000 range_end = round_up(offset + num_bytes, root->sectorsize) - 1;
7001 ret = test_range_bit(io_tree, offset, range_end,
7002 EXTENT_DELALLOC, 0, NULL);
7003 if (ret) {
7004 ret = -EAGAIN;
7005 goto out;
7006 }
7007 }
7008
1bda19eb 7009 btrfs_release_path(path);
46bfbb5c
CM
7010
7011 /*
7012 * look for other files referencing this extent, if we
7013 * find any we must cow
7014 */
00361589
JB
7015 trans = btrfs_join_transaction(root);
7016 if (IS_ERR(trans)) {
7017 ret = 0;
46bfbb5c 7018 goto out;
00361589
JB
7019 }
7020
7021 ret = btrfs_cross_ref_exist(trans, root, btrfs_ino(inode),
7022 key.offset - backref_offset, disk_bytenr);
7023 btrfs_end_transaction(trans, root);
7024 if (ret) {
7025 ret = 0;
7026 goto out;
7027 }
46bfbb5c
CM
7028
7029 /*
7030 * adjust disk_bytenr and num_bytes to cover just the bytes
7031 * in this extent we are about to write. If there
7032 * are any csums in that range we have to cow in order
7033 * to keep the csums correct
7034 */
7035 disk_bytenr += backref_offset;
7036 disk_bytenr += offset - key.offset;
46bfbb5c
CM
7037 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
7038 goto out;
7039 /*
7040 * all of the above have passed, it is safe to overwrite this extent
7041 * without cow
7042 */
eb384b55 7043 *len = num_bytes;
46bfbb5c
CM
7044 ret = 1;
7045out:
7046 btrfs_free_path(path);
7047 return ret;
7048}
7049
fc4adbff
AG
7050bool btrfs_page_exists_in_range(struct inode *inode, loff_t start, loff_t end)
7051{
7052 struct radix_tree_root *root = &inode->i_mapping->page_tree;
7053 int found = false;
7054 void **pagep = NULL;
7055 struct page *page = NULL;
7056 int start_idx;
7057 int end_idx;
7058
7059 start_idx = start >> PAGE_CACHE_SHIFT;
7060
7061 /*
7062 * end is the last byte in the last page. end == start is legal
7063 */
7064 end_idx = end >> PAGE_CACHE_SHIFT;
7065
7066 rcu_read_lock();
7067
7068 /* Most of the code in this while loop is lifted from
7069 * find_get_page. It's been modified to begin searching from a
7070 * page and return just the first page found in that range. If the
7071 * found idx is less than or equal to the end idx then we know that
7072 * a page exists. If no pages are found or if those pages are
7073 * outside of the range then we're fine (yay!) */
7074 while (page == NULL &&
7075 radix_tree_gang_lookup_slot(root, &pagep, NULL, start_idx, 1)) {
7076 page = radix_tree_deref_slot(pagep);
7077 if (unlikely(!page))
7078 break;
7079
7080 if (radix_tree_exception(page)) {
809f9016
FM
7081 if (radix_tree_deref_retry(page)) {
7082 page = NULL;
fc4adbff 7083 continue;
809f9016 7084 }
fc4adbff
AG
7085 /*
7086 * Otherwise, shmem/tmpfs must be storing a swap entry
7087 * here as an exceptional entry: so return it without
7088 * attempting to raise page count.
7089 */
6fdef6d4 7090 page = NULL;
fc4adbff
AG
7091 break; /* TODO: Is this relevant for this use case? */
7092 }
7093
91405151
FM
7094 if (!page_cache_get_speculative(page)) {
7095 page = NULL;
fc4adbff 7096 continue;
91405151 7097 }
fc4adbff
AG
7098
7099 /*
7100 * Has the page moved?
7101 * This is part of the lockless pagecache protocol. See
7102 * include/linux/pagemap.h for details.
7103 */
7104 if (unlikely(page != *pagep)) {
7105 page_cache_release(page);
7106 page = NULL;
7107 }
7108 }
7109
7110 if (page) {
7111 if (page->index <= end_idx)
7112 found = true;
7113 page_cache_release(page);
7114 }
7115
7116 rcu_read_unlock();
7117 return found;
7118}
7119
eb838e73
JB
7120static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7121 struct extent_state **cached_state, int writing)
7122{
7123 struct btrfs_ordered_extent *ordered;
7124 int ret = 0;
7125
7126 while (1) {
7127 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7128 0, cached_state);
7129 /*
7130 * We're concerned with the entire range that we're going to be
7131 * doing DIO to, so we need to make sure theres no ordered
7132 * extents in this range.
7133 */
7134 ordered = btrfs_lookup_ordered_range(inode, lockstart,
7135 lockend - lockstart + 1);
7136
7137 /*
7138 * We need to make sure there are no buffered pages in this
7139 * range either, we could have raced between the invalidate in
7140 * generic_file_direct_write and locking the extent. The
7141 * invalidate needs to happen so that reads after a write do not
7142 * get stale data.
7143 */
fc4adbff
AG
7144 if (!ordered &&
7145 (!writing ||
7146 !btrfs_page_exists_in_range(inode, lockstart, lockend)))
eb838e73
JB
7147 break;
7148
7149 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7150 cached_state, GFP_NOFS);
7151
7152 if (ordered) {
7153 btrfs_start_ordered_extent(inode, ordered, 1);
7154 btrfs_put_ordered_extent(ordered);
7155 } else {
7156 /* Screw you mmap */
728404da 7157 ret = btrfs_fdatawrite_range(inode, lockstart, lockend);
075bdbdb
FM
7158 if (ret)
7159 break;
7160 ret = filemap_fdatawait_range(inode->i_mapping,
7161 lockstart,
7162 lockend);
eb838e73
JB
7163 if (ret)
7164 break;
7165
7166 /*
7167 * If we found a page that couldn't be invalidated just
7168 * fall back to buffered.
7169 */
7170 ret = invalidate_inode_pages2_range(inode->i_mapping,
7171 lockstart >> PAGE_CACHE_SHIFT,
7172 lockend >> PAGE_CACHE_SHIFT);
7173 if (ret)
7174 break;
7175 }
7176
7177 cond_resched();
7178 }
7179
7180 return ret;
7181}
7182
69ffb543
JB
7183static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
7184 u64 len, u64 orig_start,
7185 u64 block_start, u64 block_len,
cc95bef6
JB
7186 u64 orig_block_len, u64 ram_bytes,
7187 int type)
69ffb543
JB
7188{
7189 struct extent_map_tree *em_tree;
7190 struct extent_map *em;
7191 struct btrfs_root *root = BTRFS_I(inode)->root;
7192 int ret;
7193
7194 em_tree = &BTRFS_I(inode)->extent_tree;
7195 em = alloc_extent_map();
7196 if (!em)
7197 return ERR_PTR(-ENOMEM);
7198
7199 em->start = start;
7200 em->orig_start = orig_start;
2ab28f32
JB
7201 em->mod_start = start;
7202 em->mod_len = len;
69ffb543
JB
7203 em->len = len;
7204 em->block_len = block_len;
7205 em->block_start = block_start;
7206 em->bdev = root->fs_info->fs_devices->latest_bdev;
b4939680 7207 em->orig_block_len = orig_block_len;
cc95bef6 7208 em->ram_bytes = ram_bytes;
70c8a91c 7209 em->generation = -1;
69ffb543
JB
7210 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7211 if (type == BTRFS_ORDERED_PREALLOC)
b11e234d 7212 set_bit(EXTENT_FLAG_FILLING, &em->flags);
69ffb543
JB
7213
7214 do {
7215 btrfs_drop_extent_cache(inode, em->start,
7216 em->start + em->len - 1, 0);
7217 write_lock(&em_tree->lock);
09a2a8f9 7218 ret = add_extent_mapping(em_tree, em, 1);
69ffb543
JB
7219 write_unlock(&em_tree->lock);
7220 } while (ret == -EEXIST);
7221
7222 if (ret) {
7223 free_extent_map(em);
7224 return ERR_PTR(ret);
7225 }
7226
7227 return em;
7228}
7229
7230
4b46fce2
JB
7231static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
7232 struct buffer_head *bh_result, int create)
7233{
7234 struct extent_map *em;
7235 struct btrfs_root *root = BTRFS_I(inode)->root;
eb838e73 7236 struct extent_state *cached_state = NULL;
4b46fce2 7237 u64 start = iblock << inode->i_blkbits;
eb838e73 7238 u64 lockstart, lockend;
4b46fce2 7239 u64 len = bh_result->b_size;
e1cbbfa5 7240 u64 *outstanding_extents = NULL;
eb838e73 7241 int unlock_bits = EXTENT_LOCKED;
0934856d 7242 int ret = 0;
eb838e73 7243
172a5049 7244 if (create)
3266789f 7245 unlock_bits |= EXTENT_DIRTY;
172a5049 7246 else
c329861d 7247 len = min_t(u64, len, root->sectorsize);
eb838e73 7248
c329861d
JB
7249 lockstart = start;
7250 lockend = start + len - 1;
7251
e1cbbfa5
JB
7252 if (current->journal_info) {
7253 /*
7254 * Need to pull our outstanding extents and set journal_info to NULL so
7255 * that anything that needs to check if there's a transction doesn't get
7256 * confused.
7257 */
7258 outstanding_extents = current->journal_info;
7259 current->journal_info = NULL;
7260 }
7261
eb838e73
JB
7262 /*
7263 * If this errors out it's because we couldn't invalidate pagecache for
7264 * this range and we need to fallback to buffered.
7265 */
7266 if (lock_extent_direct(inode, lockstart, lockend, &cached_state, create))
7267 return -ENOTBLK;
7268
4b46fce2 7269 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
eb838e73
JB
7270 if (IS_ERR(em)) {
7271 ret = PTR_ERR(em);
7272 goto unlock_err;
7273 }
4b46fce2
JB
7274
7275 /*
7276 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7277 * io. INLINE is special, and we could probably kludge it in here, but
7278 * it's still buffered so for safety lets just fall back to the generic
7279 * buffered path.
7280 *
7281 * For COMPRESSED we _have_ to read the entire extent in so we can
7282 * decompress it, so there will be buffering required no matter what we
7283 * do, so go ahead and fallback to buffered.
7284 *
7285 * We return -ENOTBLK because thats what makes DIO go ahead and go back
7286 * to buffered IO. Don't blame me, this is the price we pay for using
7287 * the generic code.
7288 */
7289 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7290 em->block_start == EXTENT_MAP_INLINE) {
7291 free_extent_map(em);
eb838e73
JB
7292 ret = -ENOTBLK;
7293 goto unlock_err;
4b46fce2
JB
7294 }
7295
7296 /* Just a good old fashioned hole, return */
7297 if (!create && (em->block_start == EXTENT_MAP_HOLE ||
7298 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
7299 free_extent_map(em);
eb838e73 7300 goto unlock_err;
4b46fce2
JB
7301 }
7302
7303 /*
7304 * We don't allocate a new extent in the following cases
7305 *
7306 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7307 * existing extent.
7308 * 2) The extent is marked as PREALLOC. We're good to go here and can
7309 * just use the extent.
7310 *
7311 */
46bfbb5c 7312 if (!create) {
eb838e73
JB
7313 len = min(len, em->len - (start - em->start));
7314 lockstart = start + len;
7315 goto unlock;
46bfbb5c 7316 }
4b46fce2
JB
7317
7318 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7319 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7320 em->block_start != EXTENT_MAP_HOLE)) {
4b46fce2 7321 int type;
eb384b55 7322 u64 block_start, orig_start, orig_block_len, ram_bytes;
4b46fce2
JB
7323
7324 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7325 type = BTRFS_ORDERED_PREALLOC;
7326 else
7327 type = BTRFS_ORDERED_NOCOW;
46bfbb5c 7328 len = min(len, em->len - (start - em->start));
4b46fce2 7329 block_start = em->block_start + (start - em->start);
46bfbb5c 7330
00361589 7331 if (can_nocow_extent(inode, start, &len, &orig_start,
7ee9e440 7332 &orig_block_len, &ram_bytes) == 1) {
69ffb543
JB
7333 if (type == BTRFS_ORDERED_PREALLOC) {
7334 free_extent_map(em);
7335 em = create_pinned_em(inode, start, len,
7336 orig_start,
b4939680 7337 block_start, len,
cc95bef6
JB
7338 orig_block_len,
7339 ram_bytes, type);
555e1286
FM
7340 if (IS_ERR(em)) {
7341 ret = PTR_ERR(em);
69ffb543 7342 goto unlock_err;
555e1286 7343 }
69ffb543
JB
7344 }
7345
46bfbb5c
CM
7346 ret = btrfs_add_ordered_extent_dio(inode, start,
7347 block_start, len, len, type);
46bfbb5c
CM
7348 if (ret) {
7349 free_extent_map(em);
eb838e73 7350 goto unlock_err;
46bfbb5c
CM
7351 }
7352 goto unlock;
4b46fce2 7353 }
4b46fce2 7354 }
00361589 7355
46bfbb5c
CM
7356 /*
7357 * this will cow the extent, reset the len in case we changed
7358 * it above
7359 */
7360 len = bh_result->b_size;
70c8a91c
JB
7361 free_extent_map(em);
7362 em = btrfs_new_extent_direct(inode, start, len);
eb838e73
JB
7363 if (IS_ERR(em)) {
7364 ret = PTR_ERR(em);
7365 goto unlock_err;
7366 }
46bfbb5c
CM
7367 len = min(len, em->len - (start - em->start));
7368unlock:
4b46fce2
JB
7369 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7370 inode->i_blkbits;
46bfbb5c 7371 bh_result->b_size = len;
4b46fce2
JB
7372 bh_result->b_bdev = em->bdev;
7373 set_buffer_mapped(bh_result);
c3473e83
JB
7374 if (create) {
7375 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7376 set_buffer_new(bh_result);
7377
7378 /*
7379 * Need to update the i_size under the extent lock so buffered
7380 * readers will get the updated i_size when we unlock.
7381 */
7382 if (start + len > i_size_read(inode))
7383 i_size_write(inode, start + len);
0934856d 7384
e1cbbfa5
JB
7385 /*
7386 * If we have an outstanding_extents count still set then we're
7387 * within our reservation, otherwise we need to adjust our inode
7388 * counter appropriately.
7389 */
7390 if (*outstanding_extents) {
7391 (*outstanding_extents)--;
7392 } else {
3e05bde8
JB
7393 spin_lock(&BTRFS_I(inode)->lock);
7394 BTRFS_I(inode)->outstanding_extents++;
7395 spin_unlock(&BTRFS_I(inode)->lock);
7396 }
e1cbbfa5
JB
7397
7398 current->journal_info = outstanding_extents;
3266789f 7399 btrfs_free_reserved_data_space(inode, len);
c3473e83 7400 }
4b46fce2 7401
eb838e73
JB
7402 /*
7403 * In the case of write we need to clear and unlock the entire range,
7404 * in the case of read we need to unlock only the end area that we
7405 * aren't using if there is any left over space.
7406 */
24c03fa5 7407 if (lockstart < lockend) {
0934856d
MX
7408 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
7409 lockend, unlock_bits, 1, 0,
7410 &cached_state, GFP_NOFS);
24c03fa5 7411 } else {
eb838e73 7412 free_extent_state(cached_state);
24c03fa5 7413 }
eb838e73 7414
4b46fce2
JB
7415 free_extent_map(em);
7416
7417 return 0;
eb838e73
JB
7418
7419unlock_err:
eb838e73
JB
7420 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7421 unlock_bits, 1, 0, &cached_state, GFP_NOFS);
e1cbbfa5
JB
7422 if (outstanding_extents)
7423 current->journal_info = outstanding_extents;
eb838e73 7424 return ret;
4b46fce2
JB
7425}
7426
8b110e39
MX
7427static inline int submit_dio_repair_bio(struct inode *inode, struct bio *bio,
7428 int rw, int mirror_num)
7429{
7430 struct btrfs_root *root = BTRFS_I(inode)->root;
7431 int ret;
7432
7433 BUG_ON(rw & REQ_WRITE);
7434
7435 bio_get(bio);
7436
7437 ret = btrfs_bio_wq_end_io(root->fs_info, bio,
7438 BTRFS_WQ_ENDIO_DIO_REPAIR);
7439 if (ret)
7440 goto err;
7441
7442 ret = btrfs_map_bio(root, rw, bio, mirror_num, 0);
7443err:
7444 bio_put(bio);
7445 return ret;
7446}
7447
7448static int btrfs_check_dio_repairable(struct inode *inode,
7449 struct bio *failed_bio,
7450 struct io_failure_record *failrec,
7451 int failed_mirror)
7452{
7453 int num_copies;
7454
7455 num_copies = btrfs_num_copies(BTRFS_I(inode)->root->fs_info,
7456 failrec->logical, failrec->len);
7457 if (num_copies == 1) {
7458 /*
7459 * we only have a single copy of the data, so don't bother with
7460 * all the retry and error correction code that follows. no
7461 * matter what the error is, it is very likely to persist.
7462 */
7463 pr_debug("Check DIO Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d\n",
7464 num_copies, failrec->this_mirror, failed_mirror);
7465 return 0;
7466 }
7467
7468 failrec->failed_mirror = failed_mirror;
7469 failrec->this_mirror++;
7470 if (failrec->this_mirror == failed_mirror)
7471 failrec->this_mirror++;
7472
7473 if (failrec->this_mirror > num_copies) {
7474 pr_debug("Check DIO Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d\n",
7475 num_copies, failrec->this_mirror, failed_mirror);
7476 return 0;
7477 }
7478
7479 return 1;
7480}
7481
7482static int dio_read_error(struct inode *inode, struct bio *failed_bio,
7483 struct page *page, u64 start, u64 end,
7484 int failed_mirror, bio_end_io_t *repair_endio,
7485 void *repair_arg)
7486{
7487 struct io_failure_record *failrec;
7488 struct bio *bio;
7489 int isector;
7490 int read_mode;
7491 int ret;
7492
7493 BUG_ON(failed_bio->bi_rw & REQ_WRITE);
7494
7495 ret = btrfs_get_io_failure_record(inode, start, end, &failrec);
7496 if (ret)
7497 return ret;
7498
7499 ret = btrfs_check_dio_repairable(inode, failed_bio, failrec,
7500 failed_mirror);
7501 if (!ret) {
7502 free_io_failure(inode, failrec);
7503 return -EIO;
7504 }
7505
7506 if (failed_bio->bi_vcnt > 1)
7507 read_mode = READ_SYNC | REQ_FAILFAST_DEV;
7508 else
7509 read_mode = READ_SYNC;
7510
7511 isector = start - btrfs_io_bio(failed_bio)->logical;
7512 isector >>= inode->i_sb->s_blocksize_bits;
7513 bio = btrfs_create_repair_bio(inode, failed_bio, failrec, page,
7514 0, isector, repair_endio, repair_arg);
7515 if (!bio) {
7516 free_io_failure(inode, failrec);
7517 return -EIO;
7518 }
7519
7520 btrfs_debug(BTRFS_I(inode)->root->fs_info,
7521 "Repair DIO Read Error: submitting new dio read[%#x] to this_mirror=%d, in_validation=%d\n",
7522 read_mode, failrec->this_mirror, failrec->in_validation);
7523
7524 ret = submit_dio_repair_bio(inode, bio, read_mode,
7525 failrec->this_mirror);
7526 if (ret) {
7527 free_io_failure(inode, failrec);
7528 bio_put(bio);
7529 }
7530
7531 return ret;
7532}
7533
7534struct btrfs_retry_complete {
7535 struct completion done;
7536 struct inode *inode;
7537 u64 start;
7538 int uptodate;
7539};
7540
7541static void btrfs_retry_endio_nocsum(struct bio *bio, int err)
7542{
7543 struct btrfs_retry_complete *done = bio->bi_private;
7544 struct bio_vec *bvec;
7545 int i;
7546
7547 if (err)
7548 goto end;
7549
7550 done->uptodate = 1;
7551 bio_for_each_segment_all(bvec, bio, i)
7552 clean_io_failure(done->inode, done->start, bvec->bv_page, 0);
7553end:
7554 complete(&done->done);
7555 bio_put(bio);
7556}
7557
7558static int __btrfs_correct_data_nocsum(struct inode *inode,
7559 struct btrfs_io_bio *io_bio)
4b46fce2 7560{
2c30c71b 7561 struct bio_vec *bvec;
8b110e39 7562 struct btrfs_retry_complete done;
4b46fce2 7563 u64 start;
2c30c71b 7564 int i;
c1dc0896 7565 int ret;
4b46fce2 7566
8b110e39
MX
7567 start = io_bio->logical;
7568 done.inode = inode;
7569
7570 bio_for_each_segment_all(bvec, &io_bio->bio, i) {
7571try_again:
7572 done.uptodate = 0;
7573 done.start = start;
7574 init_completion(&done.done);
7575
7576 ret = dio_read_error(inode, &io_bio->bio, bvec->bv_page, start,
7577 start + bvec->bv_len - 1,
7578 io_bio->mirror_num,
7579 btrfs_retry_endio_nocsum, &done);
7580 if (ret)
7581 return ret;
7582
7583 wait_for_completion(&done.done);
7584
7585 if (!done.uptodate) {
7586 /* We might have another mirror, so try again */
7587 goto try_again;
7588 }
7589
7590 start += bvec->bv_len;
7591 }
7592
7593 return 0;
7594}
7595
7596static void btrfs_retry_endio(struct bio *bio, int err)
7597{
7598 struct btrfs_retry_complete *done = bio->bi_private;
7599 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
7600 struct bio_vec *bvec;
7601 int uptodate;
7602 int ret;
7603 int i;
7604
7605 if (err)
7606 goto end;
7607
7608 uptodate = 1;
7609 bio_for_each_segment_all(bvec, bio, i) {
7610 ret = __readpage_endio_check(done->inode, io_bio, i,
7611 bvec->bv_page, 0,
7612 done->start, bvec->bv_len);
7613 if (!ret)
7614 clean_io_failure(done->inode, done->start,
7615 bvec->bv_page, 0);
7616 else
7617 uptodate = 0;
7618 }
7619
7620 done->uptodate = uptodate;
7621end:
7622 complete(&done->done);
7623 bio_put(bio);
7624}
7625
7626static int __btrfs_subio_endio_read(struct inode *inode,
7627 struct btrfs_io_bio *io_bio, int err)
7628{
7629 struct bio_vec *bvec;
7630 struct btrfs_retry_complete done;
7631 u64 start;
7632 u64 offset = 0;
7633 int i;
7634 int ret;
dc380aea 7635
8b110e39 7636 err = 0;
c1dc0896 7637 start = io_bio->logical;
8b110e39
MX
7638 done.inode = inode;
7639
c1dc0896 7640 bio_for_each_segment_all(bvec, &io_bio->bio, i) {
dc380aea
MX
7641 ret = __readpage_endio_check(inode, io_bio, i, bvec->bv_page,
7642 0, start, bvec->bv_len);
8b110e39
MX
7643 if (likely(!ret))
7644 goto next;
7645try_again:
7646 done.uptodate = 0;
7647 done.start = start;
7648 init_completion(&done.done);
7649
7650 ret = dio_read_error(inode, &io_bio->bio, bvec->bv_page, start,
7651 start + bvec->bv_len - 1,
7652 io_bio->mirror_num,
7653 btrfs_retry_endio, &done);
7654 if (ret) {
7655 err = ret;
7656 goto next;
7657 }
7658
7659 wait_for_completion(&done.done);
7660
7661 if (!done.uptodate) {
7662 /* We might have another mirror, so try again */
7663 goto try_again;
7664 }
7665next:
7666 offset += bvec->bv_len;
4b46fce2 7667 start += bvec->bv_len;
2c30c71b 7668 }
c1dc0896
MX
7669
7670 return err;
7671}
7672
8b110e39
MX
7673static int btrfs_subio_endio_read(struct inode *inode,
7674 struct btrfs_io_bio *io_bio, int err)
7675{
7676 bool skip_csum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
7677
7678 if (skip_csum) {
7679 if (unlikely(err))
7680 return __btrfs_correct_data_nocsum(inode, io_bio);
7681 else
7682 return 0;
7683 } else {
7684 return __btrfs_subio_endio_read(inode, io_bio, err);
7685 }
7686}
7687
c1dc0896
MX
7688static void btrfs_endio_direct_read(struct bio *bio, int err)
7689{
7690 struct btrfs_dio_private *dip = bio->bi_private;
7691 struct inode *inode = dip->inode;
7692 struct bio *dio_bio;
7693 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
7694
8b110e39
MX
7695 if (dip->flags & BTRFS_DIO_ORIG_BIO_SUBMITTED)
7696 err = btrfs_subio_endio_read(inode, io_bio, err);
c1dc0896 7697
4b46fce2 7698 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
d0082371 7699 dip->logical_offset + dip->bytes - 1);
9be3395b 7700 dio_bio = dip->dio_bio;
4b46fce2 7701
4b46fce2 7702 kfree(dip);
c0da7aa1
JB
7703
7704 /* If we had a csum failure make sure to clear the uptodate flag */
7705 if (err)
9be3395b
CM
7706 clear_bit(BIO_UPTODATE, &dio_bio->bi_flags);
7707 dio_end_io(dio_bio, err);
23ea8e5a
MX
7708
7709 if (io_bio->end_io)
7710 io_bio->end_io(io_bio, err);
9be3395b 7711 bio_put(bio);
4b46fce2
JB
7712}
7713
7714static void btrfs_endio_direct_write(struct bio *bio, int err)
7715{
7716 struct btrfs_dio_private *dip = bio->bi_private;
7717 struct inode *inode = dip->inode;
7718 struct btrfs_root *root = BTRFS_I(inode)->root;
4b46fce2 7719 struct btrfs_ordered_extent *ordered = NULL;
163cf09c
CM
7720 u64 ordered_offset = dip->logical_offset;
7721 u64 ordered_bytes = dip->bytes;
9be3395b 7722 struct bio *dio_bio;
4b46fce2
JB
7723 int ret;
7724
7725 if (err)
7726 goto out_done;
163cf09c
CM
7727again:
7728 ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
7729 &ordered_offset,
5fd02043 7730 ordered_bytes, !err);
4b46fce2 7731 if (!ret)
163cf09c 7732 goto out_test;
4b46fce2 7733
9e0af237
LB
7734 btrfs_init_work(&ordered->work, btrfs_endio_write_helper,
7735 finish_ordered_fn, NULL, NULL);
fccb5d86
QW
7736 btrfs_queue_work(root->fs_info->endio_write_workers,
7737 &ordered->work);
163cf09c
CM
7738out_test:
7739 /*
7740 * our bio might span multiple ordered extents. If we haven't
7741 * completed the accounting for the whole dio, go back and try again
7742 */
7743 if (ordered_offset < dip->logical_offset + dip->bytes) {
7744 ordered_bytes = dip->logical_offset + dip->bytes -
7745 ordered_offset;
5fd02043 7746 ordered = NULL;
163cf09c
CM
7747 goto again;
7748 }
4b46fce2 7749out_done:
9be3395b 7750 dio_bio = dip->dio_bio;
4b46fce2 7751
4b46fce2 7752 kfree(dip);
c0da7aa1
JB
7753
7754 /* If we had an error make sure to clear the uptodate flag */
7755 if (err)
9be3395b
CM
7756 clear_bit(BIO_UPTODATE, &dio_bio->bi_flags);
7757 dio_end_io(dio_bio, err);
7758 bio_put(bio);
4b46fce2
JB
7759}
7760
eaf25d93
CM
7761static int __btrfs_submit_bio_start_direct_io(struct inode *inode, int rw,
7762 struct bio *bio, int mirror_num,
7763 unsigned long bio_flags, u64 offset)
7764{
7765 int ret;
7766 struct btrfs_root *root = BTRFS_I(inode)->root;
7767 ret = btrfs_csum_one_bio(root, inode, bio, offset, 1);
79787eaa 7768 BUG_ON(ret); /* -ENOMEM */
eaf25d93
CM
7769 return 0;
7770}
7771
e65e1535
MX
7772static void btrfs_end_dio_bio(struct bio *bio, int err)
7773{
7774 struct btrfs_dio_private *dip = bio->bi_private;
7775
8b110e39
MX
7776 if (err)
7777 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
7778 "direct IO failed ino %llu rw %lu sector %#Lx len %u err no %d",
7779 btrfs_ino(dip->inode), bio->bi_rw,
7780 (unsigned long long)bio->bi_iter.bi_sector,
7781 bio->bi_iter.bi_size, err);
7782
7783 if (dip->subio_endio)
7784 err = dip->subio_endio(dip->inode, btrfs_io_bio(bio), err);
c1dc0896
MX
7785
7786 if (err) {
e65e1535
MX
7787 dip->errors = 1;
7788
7789 /*
7790 * before atomic variable goto zero, we must make sure
7791 * dip->errors is perceived to be set.
7792 */
4e857c58 7793 smp_mb__before_atomic();
e65e1535
MX
7794 }
7795
7796 /* if there are more bios still pending for this dio, just exit */
7797 if (!atomic_dec_and_test(&dip->pending_bios))
7798 goto out;
7799
9be3395b 7800 if (dip->errors) {
e65e1535 7801 bio_io_error(dip->orig_bio);
9be3395b
CM
7802 } else {
7803 set_bit(BIO_UPTODATE, &dip->dio_bio->bi_flags);
e65e1535
MX
7804 bio_endio(dip->orig_bio, 0);
7805 }
7806out:
7807 bio_put(bio);
7808}
7809
7810static struct bio *btrfs_dio_bio_alloc(struct block_device *bdev,
7811 u64 first_sector, gfp_t gfp_flags)
7812{
7813 int nr_vecs = bio_get_nr_vecs(bdev);
7814 return btrfs_bio_alloc(bdev, first_sector, nr_vecs, gfp_flags);
7815}
7816
c1dc0896
MX
7817static inline int btrfs_lookup_and_bind_dio_csum(struct btrfs_root *root,
7818 struct inode *inode,
7819 struct btrfs_dio_private *dip,
7820 struct bio *bio,
7821 u64 file_offset)
7822{
7823 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
7824 struct btrfs_io_bio *orig_io_bio = btrfs_io_bio(dip->orig_bio);
7825 int ret;
7826
7827 /*
7828 * We load all the csum data we need when we submit
7829 * the first bio to reduce the csum tree search and
7830 * contention.
7831 */
7832 if (dip->logical_offset == file_offset) {
7833 ret = btrfs_lookup_bio_sums_dio(root, inode, dip->orig_bio,
7834 file_offset);
7835 if (ret)
7836 return ret;
7837 }
7838
7839 if (bio == dip->orig_bio)
7840 return 0;
7841
7842 file_offset -= dip->logical_offset;
7843 file_offset >>= inode->i_sb->s_blocksize_bits;
7844 io_bio->csum = (u8 *)(((u32 *)orig_io_bio->csum) + file_offset);
7845
7846 return 0;
7847}
7848
e65e1535
MX
7849static inline int __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode,
7850 int rw, u64 file_offset, int skip_sum,
c329861d 7851 int async_submit)
e65e1535 7852{
facc8a22 7853 struct btrfs_dio_private *dip = bio->bi_private;
e65e1535
MX
7854 int write = rw & REQ_WRITE;
7855 struct btrfs_root *root = BTRFS_I(inode)->root;
7856 int ret;
7857
b812ce28
JB
7858 if (async_submit)
7859 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
7860
e65e1535 7861 bio_get(bio);
5fd02043
JB
7862
7863 if (!write) {
bfebd8b5
DS
7864 ret = btrfs_bio_wq_end_io(root->fs_info, bio,
7865 BTRFS_WQ_ENDIO_DATA);
5fd02043
JB
7866 if (ret)
7867 goto err;
7868 }
e65e1535 7869
1ae39938
JB
7870 if (skip_sum)
7871 goto map;
7872
7873 if (write && async_submit) {
e65e1535
MX
7874 ret = btrfs_wq_submit_bio(root->fs_info,
7875 inode, rw, bio, 0, 0,
7876 file_offset,
7877 __btrfs_submit_bio_start_direct_io,
7878 __btrfs_submit_bio_done);
7879 goto err;
1ae39938
JB
7880 } else if (write) {
7881 /*
7882 * If we aren't doing async submit, calculate the csum of the
7883 * bio now.
7884 */
7885 ret = btrfs_csum_one_bio(root, inode, bio, file_offset, 1);
7886 if (ret)
7887 goto err;
23ea8e5a 7888 } else {
c1dc0896
MX
7889 ret = btrfs_lookup_and_bind_dio_csum(root, inode, dip, bio,
7890 file_offset);
c2db1073
TI
7891 if (ret)
7892 goto err;
7893 }
1ae39938
JB
7894map:
7895 ret = btrfs_map_bio(root, rw, bio, 0, async_submit);
e65e1535
MX
7896err:
7897 bio_put(bio);
7898 return ret;
7899}
7900
7901static int btrfs_submit_direct_hook(int rw, struct btrfs_dio_private *dip,
7902 int skip_sum)
7903{
7904 struct inode *inode = dip->inode;
7905 struct btrfs_root *root = BTRFS_I(inode)->root;
e65e1535
MX
7906 struct bio *bio;
7907 struct bio *orig_bio = dip->orig_bio;
7908 struct bio_vec *bvec = orig_bio->bi_io_vec;
4f024f37 7909 u64 start_sector = orig_bio->bi_iter.bi_sector;
e65e1535
MX
7910 u64 file_offset = dip->logical_offset;
7911 u64 submit_len = 0;
7912 u64 map_length;
7913 int nr_pages = 0;
23ea8e5a 7914 int ret;
1ae39938 7915 int async_submit = 0;
e65e1535 7916
4f024f37 7917 map_length = orig_bio->bi_iter.bi_size;
53b381b3 7918 ret = btrfs_map_block(root->fs_info, rw, start_sector << 9,
e65e1535 7919 &map_length, NULL, 0);
7a5c3c9b 7920 if (ret)
e65e1535 7921 return -EIO;
facc8a22 7922
4f024f37 7923 if (map_length >= orig_bio->bi_iter.bi_size) {
02f57c7a 7924 bio = orig_bio;
c1dc0896 7925 dip->flags |= BTRFS_DIO_ORIG_BIO_SUBMITTED;
02f57c7a
JB
7926 goto submit;
7927 }
7928
53b381b3 7929 /* async crcs make it difficult to collect full stripe writes. */
ffe2d203 7930 if (btrfs_get_alloc_profile(root, 1) & BTRFS_BLOCK_GROUP_RAID56_MASK)
53b381b3
DW
7931 async_submit = 0;
7932 else
7933 async_submit = 1;
7934
02f57c7a
JB
7935 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS);
7936 if (!bio)
7937 return -ENOMEM;
7a5c3c9b 7938
02f57c7a
JB
7939 bio->bi_private = dip;
7940 bio->bi_end_io = btrfs_end_dio_bio;
c1dc0896 7941 btrfs_io_bio(bio)->logical = file_offset;
02f57c7a
JB
7942 atomic_inc(&dip->pending_bios);
7943
e65e1535 7944 while (bvec <= (orig_bio->bi_io_vec + orig_bio->bi_vcnt - 1)) {
ee39b432 7945 if (map_length < submit_len + bvec->bv_len ||
e65e1535 7946 bio_add_page(bio, bvec->bv_page, bvec->bv_len,
ee39b432 7947 bvec->bv_offset) < bvec->bv_len) {
e65e1535
MX
7948 /*
7949 * inc the count before we submit the bio so
7950 * we know the end IO handler won't happen before
7951 * we inc the count. Otherwise, the dip might get freed
7952 * before we're done setting it up
7953 */
7954 atomic_inc(&dip->pending_bios);
7955 ret = __btrfs_submit_dio_bio(bio, inode, rw,
7956 file_offset, skip_sum,
c329861d 7957 async_submit);
e65e1535
MX
7958 if (ret) {
7959 bio_put(bio);
7960 atomic_dec(&dip->pending_bios);
7961 goto out_err;
7962 }
7963
e65e1535
MX
7964 start_sector += submit_len >> 9;
7965 file_offset += submit_len;
7966
7967 submit_len = 0;
7968 nr_pages = 0;
7969
7970 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev,
7971 start_sector, GFP_NOFS);
7972 if (!bio)
7973 goto out_err;
7974 bio->bi_private = dip;
7975 bio->bi_end_io = btrfs_end_dio_bio;
c1dc0896 7976 btrfs_io_bio(bio)->logical = file_offset;
e65e1535 7977
4f024f37 7978 map_length = orig_bio->bi_iter.bi_size;
53b381b3 7979 ret = btrfs_map_block(root->fs_info, rw,
3ec706c8 7980 start_sector << 9,
e65e1535
MX
7981 &map_length, NULL, 0);
7982 if (ret) {
7983 bio_put(bio);
7984 goto out_err;
7985 }
7986 } else {
7987 submit_len += bvec->bv_len;
67871254 7988 nr_pages++;
e65e1535
MX
7989 bvec++;
7990 }
7991 }
7992
02f57c7a 7993submit:
e65e1535 7994 ret = __btrfs_submit_dio_bio(bio, inode, rw, file_offset, skip_sum,
c329861d 7995 async_submit);
e65e1535
MX
7996 if (!ret)
7997 return 0;
7998
7999 bio_put(bio);
8000out_err:
8001 dip->errors = 1;
8002 /*
8003 * before atomic variable goto zero, we must
8004 * make sure dip->errors is perceived to be set.
8005 */
4e857c58 8006 smp_mb__before_atomic();
e65e1535
MX
8007 if (atomic_dec_and_test(&dip->pending_bios))
8008 bio_io_error(dip->orig_bio);
8009
8010 /* bio_end_io() will handle error, so we needn't return it */
8011 return 0;
8012}
8013
9be3395b
CM
8014static void btrfs_submit_direct(int rw, struct bio *dio_bio,
8015 struct inode *inode, loff_t file_offset)
4b46fce2
JB
8016{
8017 struct btrfs_root *root = BTRFS_I(inode)->root;
8018 struct btrfs_dio_private *dip;
9be3395b 8019 struct bio *io_bio;
23ea8e5a 8020 struct btrfs_io_bio *btrfs_bio;
4b46fce2 8021 int skip_sum;
7b6d91da 8022 int write = rw & REQ_WRITE;
4b46fce2
JB
8023 int ret = 0;
8024
8025 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
8026
9be3395b 8027 io_bio = btrfs_bio_clone(dio_bio, GFP_NOFS);
9be3395b
CM
8028 if (!io_bio) {
8029 ret = -ENOMEM;
8030 goto free_ordered;
8031 }
8032
c1dc0896 8033 dip = kzalloc(sizeof(*dip), GFP_NOFS);
4b46fce2
JB
8034 if (!dip) {
8035 ret = -ENOMEM;
9be3395b 8036 goto free_io_bio;
4b46fce2 8037 }
4b46fce2 8038
9be3395b 8039 dip->private = dio_bio->bi_private;
4b46fce2
JB
8040 dip->inode = inode;
8041 dip->logical_offset = file_offset;
4f024f37
KO
8042 dip->bytes = dio_bio->bi_iter.bi_size;
8043 dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
9be3395b 8044 io_bio->bi_private = dip;
9be3395b
CM
8045 dip->orig_bio = io_bio;
8046 dip->dio_bio = dio_bio;
e65e1535 8047 atomic_set(&dip->pending_bios, 0);
c1dc0896
MX
8048 btrfs_bio = btrfs_io_bio(io_bio);
8049 btrfs_bio->logical = file_offset;
4b46fce2 8050
c1dc0896 8051 if (write) {
9be3395b 8052 io_bio->bi_end_io = btrfs_endio_direct_write;
c1dc0896 8053 } else {
9be3395b 8054 io_bio->bi_end_io = btrfs_endio_direct_read;
c1dc0896
MX
8055 dip->subio_endio = btrfs_subio_endio_read;
8056 }
4b46fce2 8057
e65e1535
MX
8058 ret = btrfs_submit_direct_hook(rw, dip, skip_sum);
8059 if (!ret)
eaf25d93 8060 return;
9be3395b 8061
23ea8e5a
MX
8062 if (btrfs_bio->end_io)
8063 btrfs_bio->end_io(btrfs_bio, ret);
9be3395b
CM
8064free_io_bio:
8065 bio_put(io_bio);
8066
4b46fce2
JB
8067free_ordered:
8068 /*
8069 * If this is a write, we need to clean up the reserved space and kill
8070 * the ordered extent.
8071 */
8072 if (write) {
8073 struct btrfs_ordered_extent *ordered;
955256f2 8074 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
4b46fce2
JB
8075 if (!test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags) &&
8076 !test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags))
8077 btrfs_free_reserved_extent(root, ordered->start,
e570fd27 8078 ordered->disk_len, 1);
4b46fce2
JB
8079 btrfs_put_ordered_extent(ordered);
8080 btrfs_put_ordered_extent(ordered);
8081 }
9be3395b 8082 bio_endio(dio_bio, ret);
4b46fce2
JB
8083}
8084
5a5f79b5 8085static ssize_t check_direct_IO(struct btrfs_root *root, int rw, struct kiocb *iocb,
28060d5d 8086 const struct iov_iter *iter, loff_t offset)
5a5f79b5
CM
8087{
8088 int seg;
a1b75f7d 8089 int i;
5a5f79b5
CM
8090 unsigned blocksize_mask = root->sectorsize - 1;
8091 ssize_t retval = -EINVAL;
5a5f79b5
CM
8092
8093 if (offset & blocksize_mask)
8094 goto out;
8095
28060d5d
AV
8096 if (iov_iter_alignment(iter) & blocksize_mask)
8097 goto out;
a1b75f7d 8098
28060d5d
AV
8099 /* If this is a write we don't need to check anymore */
8100 if (rw & WRITE)
8101 return 0;
8102 /*
8103 * Check to make sure we don't have duplicate iov_base's in this
8104 * iovec, if so return EINVAL, otherwise we'll get csum errors
8105 * when reading back.
8106 */
8107 for (seg = 0; seg < iter->nr_segs; seg++) {
8108 for (i = seg + 1; i < iter->nr_segs; i++) {
8109 if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
a1b75f7d
JB
8110 goto out;
8111 }
5a5f79b5
CM
8112 }
8113 retval = 0;
8114out:
8115 return retval;
8116}
eb838e73 8117
16432985 8118static ssize_t btrfs_direct_IO(int rw, struct kiocb *iocb,
d8d3d94b 8119 struct iov_iter *iter, loff_t offset)
16432985 8120{
4b46fce2
JB
8121 struct file *file = iocb->ki_filp;
8122 struct inode *inode = file->f_mapping->host;
e1cbbfa5 8123 u64 outstanding_extents = 0;
0934856d 8124 size_t count = 0;
2e60a51e 8125 int flags = 0;
38851cc1
MX
8126 bool wakeup = true;
8127 bool relock = false;
0934856d 8128 ssize_t ret;
4b46fce2 8129
28060d5d 8130 if (check_direct_IO(BTRFS_I(inode)->root, rw, iocb, iter, offset))
5a5f79b5 8131 return 0;
3f7c579c 8132
38851cc1 8133 atomic_inc(&inode->i_dio_count);
4e857c58 8134 smp_mb__after_atomic();
38851cc1 8135
0e267c44 8136 /*
41bd9ca4
MX
8137 * The generic stuff only does filemap_write_and_wait_range, which
8138 * isn't enough if we've written compressed pages to this area, so
8139 * we need to flush the dirty pages again to make absolutely sure
8140 * that any outstanding dirty pages are on disk.
0e267c44 8141 */
a6cbcd4a 8142 count = iov_iter_count(iter);
41bd9ca4
MX
8143 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8144 &BTRFS_I(inode)->runtime_flags))
9a025a08
WS
8145 filemap_fdatawrite_range(inode->i_mapping, offset,
8146 offset + count - 1);
0e267c44 8147
0934856d 8148 if (rw & WRITE) {
38851cc1
MX
8149 /*
8150 * If the write DIO is beyond the EOF, we need update
8151 * the isize, but it is protected by i_mutex. So we can
8152 * not unlock the i_mutex at this case.
8153 */
8154 if (offset + count <= inode->i_size) {
8155 mutex_unlock(&inode->i_mutex);
8156 relock = true;
8157 }
0934856d
MX
8158 ret = btrfs_delalloc_reserve_space(inode, count);
8159 if (ret)
38851cc1 8160 goto out;
e1cbbfa5
JB
8161 outstanding_extents = div64_u64(count +
8162 BTRFS_MAX_EXTENT_SIZE - 1,
8163 BTRFS_MAX_EXTENT_SIZE);
8164
8165 /*
8166 * We need to know how many extents we reserved so that we can
8167 * do the accounting properly if we go over the number we
8168 * originally calculated. Abuse current->journal_info for this.
8169 */
8170 current->journal_info = &outstanding_extents;
ee39b432
DS
8171 } else if (test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
8172 &BTRFS_I(inode)->runtime_flags)) {
38851cc1
MX
8173 inode_dio_done(inode);
8174 flags = DIO_LOCKING | DIO_SKIP_HOLES;
8175 wakeup = false;
0934856d
MX
8176 }
8177
8178 ret = __blockdev_direct_IO(rw, iocb, inode,
8179 BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev,
31b14039 8180 iter, offset, btrfs_get_blocks_direct, NULL,
2e60a51e 8181 btrfs_submit_direct, flags);
0934856d 8182 if (rw & WRITE) {
e1cbbfa5 8183 current->journal_info = NULL;
0934856d
MX
8184 if (ret < 0 && ret != -EIOCBQUEUED)
8185 btrfs_delalloc_release_space(inode, count);
172a5049 8186 else if (ret >= 0 && (size_t)ret < count)
0934856d
MX
8187 btrfs_delalloc_release_space(inode,
8188 count - (size_t)ret);
0934856d 8189 }
38851cc1 8190out:
2e60a51e
MX
8191 if (wakeup)
8192 inode_dio_done(inode);
38851cc1
MX
8193 if (relock)
8194 mutex_lock(&inode->i_mutex);
0934856d
MX
8195
8196 return ret;
16432985
CM
8197}
8198
05dadc09
TI
8199#define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
8200
1506fcc8
YS
8201static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8202 __u64 start, __u64 len)
8203{
05dadc09
TI
8204 int ret;
8205
8206 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
8207 if (ret)
8208 return ret;
8209
ec29ed5b 8210 return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap);
1506fcc8
YS
8211}
8212
a52d9a80 8213int btrfs_readpage(struct file *file, struct page *page)
9ebefb18 8214{
d1310b2e
CM
8215 struct extent_io_tree *tree;
8216 tree = &BTRFS_I(page->mapping->host)->io_tree;
8ddc7d9c 8217 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
9ebefb18 8218}
1832a6d5 8219
a52d9a80 8220static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
39279cc3 8221{
d1310b2e 8222 struct extent_io_tree *tree;
b888db2b
CM
8223
8224
8225 if (current->flags & PF_MEMALLOC) {
8226 redirty_page_for_writepage(wbc, page);
8227 unlock_page(page);
8228 return 0;
8229 }
d1310b2e 8230 tree = &BTRFS_I(page->mapping->host)->io_tree;
a52d9a80 8231 return extent_write_full_page(tree, page, btrfs_get_extent, wbc);
9ebefb18
CM
8232}
8233
48a3b636
ES
8234static int btrfs_writepages(struct address_space *mapping,
8235 struct writeback_control *wbc)
b293f02e 8236{
d1310b2e 8237 struct extent_io_tree *tree;
771ed689 8238
d1310b2e 8239 tree = &BTRFS_I(mapping->host)->io_tree;
b293f02e
CM
8240 return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
8241}
8242
3ab2fb5a
CM
8243static int
8244btrfs_readpages(struct file *file, struct address_space *mapping,
8245 struct list_head *pages, unsigned nr_pages)
8246{
d1310b2e
CM
8247 struct extent_io_tree *tree;
8248 tree = &BTRFS_I(mapping->host)->io_tree;
3ab2fb5a
CM
8249 return extent_readpages(tree, mapping, pages, nr_pages,
8250 btrfs_get_extent);
8251}
e6dcd2dc 8252static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
9ebefb18 8253{
d1310b2e
CM
8254 struct extent_io_tree *tree;
8255 struct extent_map_tree *map;
a52d9a80 8256 int ret;
8c2383c3 8257
d1310b2e
CM
8258 tree = &BTRFS_I(page->mapping->host)->io_tree;
8259 map = &BTRFS_I(page->mapping->host)->extent_tree;
70dec807 8260 ret = try_release_extent_mapping(map, tree, page, gfp_flags);
a52d9a80
CM
8261 if (ret == 1) {
8262 ClearPagePrivate(page);
8263 set_page_private(page, 0);
8264 page_cache_release(page);
39279cc3 8265 }
a52d9a80 8266 return ret;
39279cc3
CM
8267}
8268
e6dcd2dc
CM
8269static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8270{
98509cfc
CM
8271 if (PageWriteback(page) || PageDirty(page))
8272 return 0;
b335b003 8273 return __btrfs_releasepage(page, gfp_flags & GFP_NOFS);
e6dcd2dc
CM
8274}
8275
d47992f8
LC
8276static void btrfs_invalidatepage(struct page *page, unsigned int offset,
8277 unsigned int length)
39279cc3 8278{
5fd02043 8279 struct inode *inode = page->mapping->host;
d1310b2e 8280 struct extent_io_tree *tree;
e6dcd2dc 8281 struct btrfs_ordered_extent *ordered;
2ac55d41 8282 struct extent_state *cached_state = NULL;
e6dcd2dc
CM
8283 u64 page_start = page_offset(page);
8284 u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
131e404a 8285 int inode_evicting = inode->i_state & I_FREEING;
39279cc3 8286
8b62b72b
CM
8287 /*
8288 * we have the page locked, so new writeback can't start,
8289 * and the dirty bit won't be cleared while we are here.
8290 *
8291 * Wait for IO on this page so that we can safely clear
8292 * the PagePrivate2 bit and do ordered accounting
8293 */
e6dcd2dc 8294 wait_on_page_writeback(page);
8b62b72b 8295
5fd02043 8296 tree = &BTRFS_I(inode)->io_tree;
e6dcd2dc
CM
8297 if (offset) {
8298 btrfs_releasepage(page, GFP_NOFS);
8299 return;
8300 }
131e404a
FDBM
8301
8302 if (!inode_evicting)
8303 lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
8304 ordered = btrfs_lookup_ordered_extent(inode, page_start);
e6dcd2dc 8305 if (ordered) {
eb84ae03
CM
8306 /*
8307 * IO on this page will never be started, so we need
8308 * to account for any ordered extents now
8309 */
131e404a
FDBM
8310 if (!inode_evicting)
8311 clear_extent_bit(tree, page_start, page_end,
8312 EXTENT_DIRTY | EXTENT_DELALLOC |
8313 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8314 EXTENT_DEFRAG, 1, 0, &cached_state,
8315 GFP_NOFS);
8b62b72b
CM
8316 /*
8317 * whoever cleared the private bit is responsible
8318 * for the finish_ordered_io
8319 */
77cef2ec
JB
8320 if (TestClearPagePrivate2(page)) {
8321 struct btrfs_ordered_inode_tree *tree;
8322 u64 new_len;
8323
8324 tree = &BTRFS_I(inode)->ordered_tree;
8325
8326 spin_lock_irq(&tree->lock);
8327 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8328 new_len = page_start - ordered->file_offset;
8329 if (new_len < ordered->truncated_len)
8330 ordered->truncated_len = new_len;
8331 spin_unlock_irq(&tree->lock);
8332
8333 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8334 page_start,
8335 PAGE_CACHE_SIZE, 1))
8336 btrfs_finish_ordered_io(ordered);
8b62b72b 8337 }
e6dcd2dc 8338 btrfs_put_ordered_extent(ordered);
131e404a
FDBM
8339 if (!inode_evicting) {
8340 cached_state = NULL;
8341 lock_extent_bits(tree, page_start, page_end, 0,
8342 &cached_state);
8343 }
8344 }
8345
8346 if (!inode_evicting) {
8347 clear_extent_bit(tree, page_start, page_end,
8348 EXTENT_LOCKED | EXTENT_DIRTY |
8349 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
8350 EXTENT_DEFRAG, 1, 1,
8351 &cached_state, GFP_NOFS);
8352
8353 __btrfs_releasepage(page, GFP_NOFS);
e6dcd2dc 8354 }
e6dcd2dc 8355
4a096752 8356 ClearPageChecked(page);
9ad6b7bc 8357 if (PagePrivate(page)) {
9ad6b7bc
CM
8358 ClearPagePrivate(page);
8359 set_page_private(page, 0);
8360 page_cache_release(page);
8361 }
39279cc3
CM
8362}
8363
9ebefb18
CM
8364/*
8365 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8366 * called from a page fault handler when a page is first dirtied. Hence we must
8367 * be careful to check for EOF conditions here. We set the page up correctly
8368 * for a written page which means we get ENOSPC checking when writing into
8369 * holes and correct delalloc and unwritten extent mapping on filesystems that
8370 * support these features.
8371 *
8372 * We are not allowed to take the i_mutex here so we have to play games to
8373 * protect against truncate races as the page could now be beyond EOF. Because
8374 * vmtruncate() writes the inode size before removing pages, once we have the
8375 * page lock we can determine safely if the page is beyond EOF. If it is not
8376 * beyond EOF, then the page is guaranteed safe against truncation until we
8377 * unlock the page.
8378 */
c2ec175c 8379int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
9ebefb18 8380{
c2ec175c 8381 struct page *page = vmf->page;
496ad9aa 8382 struct inode *inode = file_inode(vma->vm_file);
1832a6d5 8383 struct btrfs_root *root = BTRFS_I(inode)->root;
e6dcd2dc
CM
8384 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8385 struct btrfs_ordered_extent *ordered;
2ac55d41 8386 struct extent_state *cached_state = NULL;
e6dcd2dc
CM
8387 char *kaddr;
8388 unsigned long zero_start;
9ebefb18 8389 loff_t size;
1832a6d5 8390 int ret;
9998eb70 8391 int reserved = 0;
a52d9a80 8392 u64 page_start;
e6dcd2dc 8393 u64 page_end;
9ebefb18 8394
b2b5ef5c 8395 sb_start_pagefault(inode->i_sb);
0ca1f7ce 8396 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
9998eb70 8397 if (!ret) {
e41f941a 8398 ret = file_update_time(vma->vm_file);
9998eb70
CM
8399 reserved = 1;
8400 }
56a76f82
NP
8401 if (ret) {
8402 if (ret == -ENOMEM)
8403 ret = VM_FAULT_OOM;
8404 else /* -ENOSPC, -EIO, etc */
8405 ret = VM_FAULT_SIGBUS;
9998eb70
CM
8406 if (reserved)
8407 goto out;
8408 goto out_noreserve;
56a76f82 8409 }
1832a6d5 8410
56a76f82 8411 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
e6dcd2dc 8412again:
9ebefb18 8413 lock_page(page);
9ebefb18 8414 size = i_size_read(inode);
e6dcd2dc
CM
8415 page_start = page_offset(page);
8416 page_end = page_start + PAGE_CACHE_SIZE - 1;
a52d9a80 8417
9ebefb18 8418 if ((page->mapping != inode->i_mapping) ||
e6dcd2dc 8419 (page_start >= size)) {
9ebefb18
CM
8420 /* page got truncated out from underneath us */
8421 goto out_unlock;
8422 }
e6dcd2dc
CM
8423 wait_on_page_writeback(page);
8424
d0082371 8425 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
e6dcd2dc
CM
8426 set_page_extent_mapped(page);
8427
eb84ae03
CM
8428 /*
8429 * we can't set the delalloc bits if there are pending ordered
8430 * extents. Drop our locks and wait for them to finish
8431 */
e6dcd2dc
CM
8432 ordered = btrfs_lookup_ordered_extent(inode, page_start);
8433 if (ordered) {
2ac55d41
JB
8434 unlock_extent_cached(io_tree, page_start, page_end,
8435 &cached_state, GFP_NOFS);
e6dcd2dc 8436 unlock_page(page);
eb84ae03 8437 btrfs_start_ordered_extent(inode, ordered, 1);
e6dcd2dc
CM
8438 btrfs_put_ordered_extent(ordered);
8439 goto again;
8440 }
8441
fbf19087
JB
8442 /*
8443 * XXX - page_mkwrite gets called every time the page is dirtied, even
8444 * if it was already dirty, so for space accounting reasons we need to
8445 * clear any delalloc bits for the range we are fixing to save. There
8446 * is probably a better way to do this, but for now keep consistent with
8447 * prepare_pages in the normal write path.
8448 */
2ac55d41 8449 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
9e8a4a8b
LB
8450 EXTENT_DIRTY | EXTENT_DELALLOC |
8451 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
2ac55d41 8452 0, 0, &cached_state, GFP_NOFS);
fbf19087 8453
2ac55d41
JB
8454 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
8455 &cached_state);
9ed74f2d 8456 if (ret) {
2ac55d41
JB
8457 unlock_extent_cached(io_tree, page_start, page_end,
8458 &cached_state, GFP_NOFS);
9ed74f2d
JB
8459 ret = VM_FAULT_SIGBUS;
8460 goto out_unlock;
8461 }
e6dcd2dc 8462 ret = 0;
9ebefb18
CM
8463
8464 /* page is wholly or partially inside EOF */
a52d9a80 8465 if (page_start + PAGE_CACHE_SIZE > size)
e6dcd2dc 8466 zero_start = size & ~PAGE_CACHE_MASK;
9ebefb18 8467 else
e6dcd2dc 8468 zero_start = PAGE_CACHE_SIZE;
9ebefb18 8469
e6dcd2dc
CM
8470 if (zero_start != PAGE_CACHE_SIZE) {
8471 kaddr = kmap(page);
8472 memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
8473 flush_dcache_page(page);
8474 kunmap(page);
8475 }
247e743c 8476 ClearPageChecked(page);
e6dcd2dc 8477 set_page_dirty(page);
50a9b214 8478 SetPageUptodate(page);
5a3f23d5 8479
257c62e1
CM
8480 BTRFS_I(inode)->last_trans = root->fs_info->generation;
8481 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
46d8bc34 8482 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
257c62e1 8483
2ac55d41 8484 unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
9ebefb18
CM
8485
8486out_unlock:
b2b5ef5c
JK
8487 if (!ret) {
8488 sb_end_pagefault(inode->i_sb);
50a9b214 8489 return VM_FAULT_LOCKED;
b2b5ef5c 8490 }
9ebefb18 8491 unlock_page(page);
1832a6d5 8492out:
ec39e180 8493 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
9998eb70 8494out_noreserve:
b2b5ef5c 8495 sb_end_pagefault(inode->i_sb);
9ebefb18
CM
8496 return ret;
8497}
8498
a41ad394 8499static int btrfs_truncate(struct inode *inode)
39279cc3
CM
8500{
8501 struct btrfs_root *root = BTRFS_I(inode)->root;
fcb80c2a 8502 struct btrfs_block_rsv *rsv;
a71754fc 8503 int ret = 0;
3893e33b 8504 int err = 0;
39279cc3 8505 struct btrfs_trans_handle *trans;
dbe674a9 8506 u64 mask = root->sectorsize - 1;
07127184 8507 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
39279cc3 8508
0ef8b726
JB
8509 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
8510 (u64)-1);
8511 if (ret)
8512 return ret;
39279cc3 8513
fcb80c2a
JB
8514 /*
8515 * Yes ladies and gentelment, this is indeed ugly. The fact is we have
8516 * 3 things going on here
8517 *
8518 * 1) We need to reserve space for our orphan item and the space to
8519 * delete our orphan item. Lord knows we don't want to have a dangling
8520 * orphan item because we didn't reserve space to remove it.
8521 *
8522 * 2) We need to reserve space to update our inode.
8523 *
8524 * 3) We need to have something to cache all the space that is going to
8525 * be free'd up by the truncate operation, but also have some slack
8526 * space reserved in case it uses space during the truncate (thank you
8527 * very much snapshotting).
8528 *
8529 * And we need these to all be seperate. The fact is we can use alot of
8530 * space doing the truncate, and we have no earthly idea how much space
8531 * we will use, so we need the truncate reservation to be seperate so it
8532 * doesn't end up using space reserved for updating the inode or
8533 * removing the orphan item. We also need to be able to stop the
8534 * transaction and start a new one, which means we need to be able to
8535 * update the inode several times, and we have no idea of knowing how
8536 * many times that will be, so we can't just reserve 1 item for the
8537 * entirety of the opration, so that has to be done seperately as well.
8538 * Then there is the orphan item, which does indeed need to be held on
8539 * to for the whole operation, and we need nobody to touch this reserved
8540 * space except the orphan code.
8541 *
8542 * So that leaves us with
8543 *
8544 * 1) root->orphan_block_rsv - for the orphan deletion.
8545 * 2) rsv - for the truncate reservation, which we will steal from the
8546 * transaction reservation.
8547 * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
8548 * updating the inode.
8549 */
66d8f3dd 8550 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
fcb80c2a
JB
8551 if (!rsv)
8552 return -ENOMEM;
4a338542 8553 rsv->size = min_size;
ca7e70f5 8554 rsv->failfast = 1;
f0cd846e 8555
907cbceb 8556 /*
07127184 8557 * 1 for the truncate slack space
907cbceb
JB
8558 * 1 for updating the inode.
8559 */
f3fe820c 8560 trans = btrfs_start_transaction(root, 2);
fcb80c2a
JB
8561 if (IS_ERR(trans)) {
8562 err = PTR_ERR(trans);
8563 goto out;
8564 }
f0cd846e 8565
907cbceb
JB
8566 /* Migrate the slack space for the truncate to our reserve */
8567 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv,
8568 min_size);
fcb80c2a 8569 BUG_ON(ret);
f0cd846e 8570
5dc562c5
JB
8571 /*
8572 * So if we truncate and then write and fsync we normally would just
8573 * write the extents that changed, which is a problem if we need to
8574 * first truncate that entire inode. So set this flag so we write out
8575 * all of the extents in the inode to the sync log so we're completely
8576 * safe.
8577 */
8578 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
ca7e70f5 8579 trans->block_rsv = rsv;
907cbceb 8580
8082510e
YZ
8581 while (1) {
8582 ret = btrfs_truncate_inode_items(trans, root, inode,
8583 inode->i_size,
8584 BTRFS_EXTENT_DATA_KEY);
ca7e70f5 8585 if (ret != -ENOSPC) {
3893e33b 8586 err = ret;
8082510e 8587 break;
3893e33b 8588 }
39279cc3 8589
fcb80c2a 8590 trans->block_rsv = &root->fs_info->trans_block_rsv;
8082510e 8591 ret = btrfs_update_inode(trans, root, inode);
3893e33b
JB
8592 if (ret) {
8593 err = ret;
8594 break;
8595 }
ca7e70f5 8596
8082510e 8597 btrfs_end_transaction(trans, root);
b53d3f5d 8598 btrfs_btree_balance_dirty(root);
ca7e70f5
JB
8599
8600 trans = btrfs_start_transaction(root, 2);
8601 if (IS_ERR(trans)) {
8602 ret = err = PTR_ERR(trans);
8603 trans = NULL;
8604 break;
8605 }
8606
8607 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv,
8608 rsv, min_size);
8609 BUG_ON(ret); /* shouldn't happen */
8610 trans->block_rsv = rsv;
8082510e
YZ
8611 }
8612
8613 if (ret == 0 && inode->i_nlink > 0) {
fcb80c2a 8614 trans->block_rsv = root->orphan_block_rsv;
8082510e 8615 ret = btrfs_orphan_del(trans, inode);
3893e33b
JB
8616 if (ret)
8617 err = ret;
8082510e
YZ
8618 }
8619
917c16b2
CM
8620 if (trans) {
8621 trans->block_rsv = &root->fs_info->trans_block_rsv;
8622 ret = btrfs_update_inode(trans, root, inode);
8623 if (ret && !err)
8624 err = ret;
7b128766 8625
7ad85bb7 8626 ret = btrfs_end_transaction(trans, root);
b53d3f5d 8627 btrfs_btree_balance_dirty(root);
917c16b2 8628 }
fcb80c2a
JB
8629
8630out:
8631 btrfs_free_block_rsv(root, rsv);
8632
3893e33b
JB
8633 if (ret && !err)
8634 err = ret;
a41ad394 8635
3893e33b 8636 return err;
39279cc3
CM
8637}
8638
d352ac68
CM
8639/*
8640 * create a new subvolume directory/inode (helper for the ioctl).
8641 */
d2fb3437 8642int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
63541927
FDBM
8643 struct btrfs_root *new_root,
8644 struct btrfs_root *parent_root,
8645 u64 new_dirid)
39279cc3 8646{
39279cc3 8647 struct inode *inode;
76dda93c 8648 int err;
00e4e6b3 8649 u64 index = 0;
39279cc3 8650
12fc9d09
FA
8651 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
8652 new_dirid, new_dirid,
8653 S_IFDIR | (~current_umask() & S_IRWXUGO),
8654 &index);
54aa1f4d 8655 if (IS_ERR(inode))
f46b5a66 8656 return PTR_ERR(inode);
39279cc3
CM
8657 inode->i_op = &btrfs_dir_inode_operations;
8658 inode->i_fop = &btrfs_dir_file_operations;
8659
bfe86848 8660 set_nlink(inode, 1);
dbe674a9 8661 btrfs_i_size_write(inode, 0);
b0d5d10f 8662 unlock_new_inode(inode);
3b96362c 8663
63541927
FDBM
8664 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
8665 if (err)
8666 btrfs_err(new_root->fs_info,
351fd353 8667 "error inheriting subvolume %llu properties: %d",
63541927
FDBM
8668 new_root->root_key.objectid, err);
8669
76dda93c 8670 err = btrfs_update_inode(trans, new_root, inode);
cb8e7090 8671
76dda93c 8672 iput(inode);
ce598979 8673 return err;
39279cc3
CM
8674}
8675
39279cc3
CM
8676struct inode *btrfs_alloc_inode(struct super_block *sb)
8677{
8678 struct btrfs_inode *ei;
2ead6ae7 8679 struct inode *inode;
39279cc3
CM
8680
8681 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
8682 if (!ei)
8683 return NULL;
2ead6ae7
YZ
8684
8685 ei->root = NULL;
2ead6ae7 8686 ei->generation = 0;
15ee9bc7 8687 ei->last_trans = 0;
257c62e1 8688 ei->last_sub_trans = 0;
e02119d5 8689 ei->logged_trans = 0;
2ead6ae7 8690 ei->delalloc_bytes = 0;
47059d93 8691 ei->defrag_bytes = 0;
2ead6ae7
YZ
8692 ei->disk_i_size = 0;
8693 ei->flags = 0;
7709cde3 8694 ei->csum_bytes = 0;
2ead6ae7 8695 ei->index_cnt = (u64)-1;
67de1176 8696 ei->dir_index = 0;
2ead6ae7 8697 ei->last_unlink_trans = 0;
46d8bc34 8698 ei->last_log_commit = 0;
2ead6ae7 8699
9e0baf60
JB
8700 spin_lock_init(&ei->lock);
8701 ei->outstanding_extents = 0;
8702 ei->reserved_extents = 0;
2ead6ae7 8703
72ac3c0d 8704 ei->runtime_flags = 0;
261507a0 8705 ei->force_compress = BTRFS_COMPRESS_NONE;
2ead6ae7 8706
16cdcec7
MX
8707 ei->delayed_node = NULL;
8708
9cc97d64 8709 ei->i_otime.tv_sec = 0;
8710 ei->i_otime.tv_nsec = 0;
8711
2ead6ae7 8712 inode = &ei->vfs_inode;
a8067e02 8713 extent_map_tree_init(&ei->extent_tree);
f993c883
DS
8714 extent_io_tree_init(&ei->io_tree, &inode->i_data);
8715 extent_io_tree_init(&ei->io_failure_tree, &inode->i_data);
0b32f4bb
JB
8716 ei->io_tree.track_uptodate = 1;
8717 ei->io_failure_tree.track_uptodate = 1;
b812ce28 8718 atomic_set(&ei->sync_writers, 0);
2ead6ae7 8719 mutex_init(&ei->log_mutex);
f248679e 8720 mutex_init(&ei->delalloc_mutex);
e6dcd2dc 8721 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
2ead6ae7 8722 INIT_LIST_HEAD(&ei->delalloc_inodes);
2ead6ae7
YZ
8723 RB_CLEAR_NODE(&ei->rb_node);
8724
8725 return inode;
39279cc3
CM
8726}
8727
aaedb55b
JB
8728#ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
8729void btrfs_test_destroy_inode(struct inode *inode)
8730{
8731 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
8732 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8733}
8734#endif
8735
fa0d7e3d
NP
8736static void btrfs_i_callback(struct rcu_head *head)
8737{
8738 struct inode *inode = container_of(head, struct inode, i_rcu);
fa0d7e3d
NP
8739 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8740}
8741
39279cc3
CM
8742void btrfs_destroy_inode(struct inode *inode)
8743{
e6dcd2dc 8744 struct btrfs_ordered_extent *ordered;
5a3f23d5
CM
8745 struct btrfs_root *root = BTRFS_I(inode)->root;
8746
b3d9b7a3 8747 WARN_ON(!hlist_empty(&inode->i_dentry));
39279cc3 8748 WARN_ON(inode->i_data.nrpages);
9e0baf60
JB
8749 WARN_ON(BTRFS_I(inode)->outstanding_extents);
8750 WARN_ON(BTRFS_I(inode)->reserved_extents);
7709cde3
JB
8751 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
8752 WARN_ON(BTRFS_I(inode)->csum_bytes);
47059d93 8753 WARN_ON(BTRFS_I(inode)->defrag_bytes);
39279cc3 8754
a6dbd429
JB
8755 /*
8756 * This can happen where we create an inode, but somebody else also
8757 * created the same inode and we need to destroy the one we already
8758 * created.
8759 */
8760 if (!root)
8761 goto free;
8762
8a35d95f
JB
8763 if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
8764 &BTRFS_I(inode)->runtime_flags)) {
c2cf52eb 8765 btrfs_info(root->fs_info, "inode %llu still on the orphan list",
c1c9ff7c 8766 btrfs_ino(inode));
8a35d95f 8767 atomic_dec(&root->orphan_inodes);
7b128766 8768 }
7b128766 8769
d397712b 8770 while (1) {
e6dcd2dc
CM
8771 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
8772 if (!ordered)
8773 break;
8774 else {
c2cf52eb 8775 btrfs_err(root->fs_info, "found ordered extent %llu %llu on inode cleanup",
c1c9ff7c 8776 ordered->file_offset, ordered->len);
e6dcd2dc
CM
8777 btrfs_remove_ordered_extent(inode, ordered);
8778 btrfs_put_ordered_extent(ordered);
8779 btrfs_put_ordered_extent(ordered);
8780 }
8781 }
5d4f98a2 8782 inode_tree_del(inode);
5b21f2ed 8783 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
a6dbd429 8784free:
fa0d7e3d 8785 call_rcu(&inode->i_rcu, btrfs_i_callback);
39279cc3
CM
8786}
8787
45321ac5 8788int btrfs_drop_inode(struct inode *inode)
76dda93c
YZ
8789{
8790 struct btrfs_root *root = BTRFS_I(inode)->root;
45321ac5 8791
6379ef9f
NA
8792 if (root == NULL)
8793 return 1;
8794
fa6ac876 8795 /* the snap/subvol tree is on deleting */
69e9c6c6 8796 if (btrfs_root_refs(&root->root_item) == 0)
45321ac5 8797 return 1;
76dda93c 8798 else
45321ac5 8799 return generic_drop_inode(inode);
76dda93c
YZ
8800}
8801
0ee0fda0 8802static void init_once(void *foo)
39279cc3
CM
8803{
8804 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
8805
8806 inode_init_once(&ei->vfs_inode);
8807}
8808
8809void btrfs_destroy_cachep(void)
8810{
8c0a8537
KS
8811 /*
8812 * Make sure all delayed rcu free inodes are flushed before we
8813 * destroy cache.
8814 */
8815 rcu_barrier();
39279cc3
CM
8816 if (btrfs_inode_cachep)
8817 kmem_cache_destroy(btrfs_inode_cachep);
8818 if (btrfs_trans_handle_cachep)
8819 kmem_cache_destroy(btrfs_trans_handle_cachep);
8820 if (btrfs_transaction_cachep)
8821 kmem_cache_destroy(btrfs_transaction_cachep);
39279cc3
CM
8822 if (btrfs_path_cachep)
8823 kmem_cache_destroy(btrfs_path_cachep);
dc89e982
JB
8824 if (btrfs_free_space_cachep)
8825 kmem_cache_destroy(btrfs_free_space_cachep);
8ccf6f19
MX
8826 if (btrfs_delalloc_work_cachep)
8827 kmem_cache_destroy(btrfs_delalloc_work_cachep);
39279cc3
CM
8828}
8829
8830int btrfs_init_cachep(void)
8831{
837e1972 8832 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
9601e3f6
CH
8833 sizeof(struct btrfs_inode), 0,
8834 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, init_once);
39279cc3
CM
8835 if (!btrfs_inode_cachep)
8836 goto fail;
9601e3f6 8837
837e1972 8838 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
9601e3f6
CH
8839 sizeof(struct btrfs_trans_handle), 0,
8840 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
39279cc3
CM
8841 if (!btrfs_trans_handle_cachep)
8842 goto fail;
9601e3f6 8843
837e1972 8844 btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction",
9601e3f6
CH
8845 sizeof(struct btrfs_transaction), 0,
8846 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
39279cc3
CM
8847 if (!btrfs_transaction_cachep)
8848 goto fail;
9601e3f6 8849
837e1972 8850 btrfs_path_cachep = kmem_cache_create("btrfs_path",
9601e3f6
CH
8851 sizeof(struct btrfs_path), 0,
8852 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
39279cc3
CM
8853 if (!btrfs_path_cachep)
8854 goto fail;
9601e3f6 8855
837e1972 8856 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
dc89e982
JB
8857 sizeof(struct btrfs_free_space), 0,
8858 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8859 if (!btrfs_free_space_cachep)
8860 goto fail;
8861
8ccf6f19
MX
8862 btrfs_delalloc_work_cachep = kmem_cache_create("btrfs_delalloc_work",
8863 sizeof(struct btrfs_delalloc_work), 0,
8864 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD,
8865 NULL);
8866 if (!btrfs_delalloc_work_cachep)
8867 goto fail;
8868
39279cc3
CM
8869 return 0;
8870fail:
8871 btrfs_destroy_cachep();
8872 return -ENOMEM;
8873}
8874
8875static int btrfs_getattr(struct vfsmount *mnt,
8876 struct dentry *dentry, struct kstat *stat)
8877{
df0af1a5 8878 u64 delalloc_bytes;
39279cc3 8879 struct inode *inode = dentry->d_inode;
fadc0d8b
DS
8880 u32 blocksize = inode->i_sb->s_blocksize;
8881
39279cc3 8882 generic_fillattr(inode, stat);
0ee5dc67 8883 stat->dev = BTRFS_I(inode)->root->anon_dev;
d6667462 8884 stat->blksize = PAGE_CACHE_SIZE;
df0af1a5
MX
8885
8886 spin_lock(&BTRFS_I(inode)->lock);
8887 delalloc_bytes = BTRFS_I(inode)->delalloc_bytes;
8888 spin_unlock(&BTRFS_I(inode)->lock);
fadc0d8b 8889 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
df0af1a5 8890 ALIGN(delalloc_bytes, blocksize)) >> 9;
39279cc3
CM
8891 return 0;
8892}
8893
d397712b
CM
8894static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
8895 struct inode *new_dir, struct dentry *new_dentry)
39279cc3
CM
8896{
8897 struct btrfs_trans_handle *trans;
8898 struct btrfs_root *root = BTRFS_I(old_dir)->root;
4df27c4d 8899 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
39279cc3
CM
8900 struct inode *new_inode = new_dentry->d_inode;
8901 struct inode *old_inode = old_dentry->d_inode;
8902 struct timespec ctime = CURRENT_TIME;
00e4e6b3 8903 u64 index = 0;
4df27c4d 8904 u64 root_objectid;
39279cc3 8905 int ret;
33345d01 8906 u64 old_ino = btrfs_ino(old_inode);
39279cc3 8907
33345d01 8908 if (btrfs_ino(new_dir) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
f679a840
YZ
8909 return -EPERM;
8910
4df27c4d 8911 /* we only allow rename subvolume link between subvolumes */
33345d01 8912 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
3394e160
CM
8913 return -EXDEV;
8914
33345d01
LZ
8915 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
8916 (new_inode && btrfs_ino(new_inode) == BTRFS_FIRST_FREE_OBJECTID))
39279cc3 8917 return -ENOTEMPTY;
5f39d397 8918
4df27c4d
YZ
8919 if (S_ISDIR(old_inode->i_mode) && new_inode &&
8920 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
8921 return -ENOTEMPTY;
9c52057c
CM
8922
8923
8924 /* check for collisions, even if the name isn't there */
4871c158 8925 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9c52057c
CM
8926 new_dentry->d_name.name,
8927 new_dentry->d_name.len);
8928
8929 if (ret) {
8930 if (ret == -EEXIST) {
8931 /* we shouldn't get
8932 * eexist without a new_inode */
fae7f21c 8933 if (WARN_ON(!new_inode)) {
9c52057c
CM
8934 return ret;
8935 }
8936 } else {
8937 /* maybe -EOVERFLOW */
8938 return ret;
8939 }
8940 }
8941 ret = 0;
8942
5a3f23d5 8943 /*
8d875f95
CM
8944 * we're using rename to replace one file with another. Start IO on it
8945 * now so we don't add too much work to the end of the transaction
5a3f23d5 8946 */
8d875f95 8947 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
5a3f23d5
CM
8948 filemap_flush(old_inode->i_mapping);
8949
76dda93c 8950 /* close the racy window with snapshot create/destroy ioctl */
33345d01 8951 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
76dda93c 8952 down_read(&root->fs_info->subvol_sem);
a22285a6
YZ
8953 /*
8954 * We want to reserve the absolute worst case amount of items. So if
8955 * both inodes are subvols and we need to unlink them then that would
8956 * require 4 item modifications, but if they are both normal inodes it
8957 * would require 5 item modifications, so we'll assume their normal
8958 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
8959 * should cover the worst case number of items we'll modify.
8960 */
6e137ed3 8961 trans = btrfs_start_transaction(root, 11);
b44c59a8
JL
8962 if (IS_ERR(trans)) {
8963 ret = PTR_ERR(trans);
8964 goto out_notrans;
8965 }
76dda93c 8966
4df27c4d
YZ
8967 if (dest != root)
8968 btrfs_record_root_in_trans(trans, dest);
5f39d397 8969
a5719521
YZ
8970 ret = btrfs_set_inode_index(new_dir, &index);
8971 if (ret)
8972 goto out_fail;
5a3f23d5 8973
67de1176 8974 BTRFS_I(old_inode)->dir_index = 0ULL;
33345d01 8975 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
4df27c4d 8976 /* force full log commit if subvolume involved. */
995946dd 8977 btrfs_set_log_full_commit(root->fs_info, trans);
4df27c4d 8978 } else {
a5719521
YZ
8979 ret = btrfs_insert_inode_ref(trans, dest,
8980 new_dentry->d_name.name,
8981 new_dentry->d_name.len,
33345d01
LZ
8982 old_ino,
8983 btrfs_ino(new_dir), index);
a5719521
YZ
8984 if (ret)
8985 goto out_fail;
4df27c4d
YZ
8986 /*
8987 * this is an ugly little race, but the rename is required
8988 * to make sure that if we crash, the inode is either at the
8989 * old name or the new one. pinning the log transaction lets
8990 * us make sure we don't allow a log commit to come in after
8991 * we unlink the name but before we add the new name back in.
8992 */
8993 btrfs_pin_log_trans(root);
8994 }
5a3f23d5 8995
0c4d2d95
JB
8996 inode_inc_iversion(old_dir);
8997 inode_inc_iversion(new_dir);
8998 inode_inc_iversion(old_inode);
39279cc3
CM
8999 old_dir->i_ctime = old_dir->i_mtime = ctime;
9000 new_dir->i_ctime = new_dir->i_mtime = ctime;
9001 old_inode->i_ctime = ctime;
5f39d397 9002
12fcfd22
CM
9003 if (old_dentry->d_parent != new_dentry->d_parent)
9004 btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
9005
33345d01 9006 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
4df27c4d
YZ
9007 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9008 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
9009 old_dentry->d_name.name,
9010 old_dentry->d_name.len);
9011 } else {
92986796
AV
9012 ret = __btrfs_unlink_inode(trans, root, old_dir,
9013 old_dentry->d_inode,
9014 old_dentry->d_name.name,
9015 old_dentry->d_name.len);
9016 if (!ret)
9017 ret = btrfs_update_inode(trans, root, old_inode);
4df27c4d 9018 }
79787eaa
JM
9019 if (ret) {
9020 btrfs_abort_transaction(trans, root, ret);
9021 goto out_fail;
9022 }
39279cc3
CM
9023
9024 if (new_inode) {
0c4d2d95 9025 inode_inc_iversion(new_inode);
39279cc3 9026 new_inode->i_ctime = CURRENT_TIME;
33345d01 9027 if (unlikely(btrfs_ino(new_inode) ==
4df27c4d
YZ
9028 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9029 root_objectid = BTRFS_I(new_inode)->location.objectid;
9030 ret = btrfs_unlink_subvol(trans, dest, new_dir,
9031 root_objectid,
9032 new_dentry->d_name.name,
9033 new_dentry->d_name.len);
9034 BUG_ON(new_inode->i_nlink == 0);
9035 } else {
9036 ret = btrfs_unlink_inode(trans, dest, new_dir,
9037 new_dentry->d_inode,
9038 new_dentry->d_name.name,
9039 new_dentry->d_name.len);
9040 }
4ef31a45 9041 if (!ret && new_inode->i_nlink == 0)
e02119d5 9042 ret = btrfs_orphan_add(trans, new_dentry->d_inode);
79787eaa
JM
9043 if (ret) {
9044 btrfs_abort_transaction(trans, root, ret);
9045 goto out_fail;
9046 }
39279cc3 9047 }
aec7477b 9048
4df27c4d
YZ
9049 ret = btrfs_add_link(trans, new_dir, old_inode,
9050 new_dentry->d_name.name,
a5719521 9051 new_dentry->d_name.len, 0, index);
79787eaa
JM
9052 if (ret) {
9053 btrfs_abort_transaction(trans, root, ret);
9054 goto out_fail;
9055 }
39279cc3 9056
67de1176
MX
9057 if (old_inode->i_nlink == 1)
9058 BTRFS_I(old_inode)->dir_index = index;
9059
33345d01 9060 if (old_ino != BTRFS_FIRST_FREE_OBJECTID) {
10d9f309 9061 struct dentry *parent = new_dentry->d_parent;
6a912213 9062 btrfs_log_new_name(trans, old_inode, old_dir, parent);
4df27c4d
YZ
9063 btrfs_end_log_trans(root);
9064 }
39279cc3 9065out_fail:
7ad85bb7 9066 btrfs_end_transaction(trans, root);
b44c59a8 9067out_notrans:
33345d01 9068 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
76dda93c 9069 up_read(&root->fs_info->subvol_sem);
9ed74f2d 9070
39279cc3
CM
9071 return ret;
9072}
9073
80ace85c
MS
9074static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
9075 struct inode *new_dir, struct dentry *new_dentry,
9076 unsigned int flags)
9077{
9078 if (flags & ~RENAME_NOREPLACE)
9079 return -EINVAL;
9080
9081 return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry);
9082}
9083
8ccf6f19
MX
9084static void btrfs_run_delalloc_work(struct btrfs_work *work)
9085{
9086 struct btrfs_delalloc_work *delalloc_work;
9f23e289 9087 struct inode *inode;
8ccf6f19
MX
9088
9089 delalloc_work = container_of(work, struct btrfs_delalloc_work,
9090 work);
9f23e289
JB
9091 inode = delalloc_work->inode;
9092 if (delalloc_work->wait) {
9093 btrfs_wait_ordered_range(inode, 0, (u64)-1);
9094 } else {
9095 filemap_flush(inode->i_mapping);
9096 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
9097 &BTRFS_I(inode)->runtime_flags))
9098 filemap_flush(inode->i_mapping);
9099 }
8ccf6f19
MX
9100
9101 if (delalloc_work->delay_iput)
9f23e289 9102 btrfs_add_delayed_iput(inode);
8ccf6f19 9103 else
9f23e289 9104 iput(inode);
8ccf6f19
MX
9105 complete(&delalloc_work->completion);
9106}
9107
9108struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode,
9109 int wait, int delay_iput)
9110{
9111 struct btrfs_delalloc_work *work;
9112
9113 work = kmem_cache_zalloc(btrfs_delalloc_work_cachep, GFP_NOFS);
9114 if (!work)
9115 return NULL;
9116
9117 init_completion(&work->completion);
9118 INIT_LIST_HEAD(&work->list);
9119 work->inode = inode;
9120 work->wait = wait;
9121 work->delay_iput = delay_iput;
9e0af237
LB
9122 WARN_ON_ONCE(!inode);
9123 btrfs_init_work(&work->work, btrfs_flush_delalloc_helper,
9124 btrfs_run_delalloc_work, NULL, NULL);
8ccf6f19
MX
9125
9126 return work;
9127}
9128
9129void btrfs_wait_and_free_delalloc_work(struct btrfs_delalloc_work *work)
9130{
9131 wait_for_completion(&work->completion);
9132 kmem_cache_free(btrfs_delalloc_work_cachep, work);
9133}
9134
d352ac68
CM
9135/*
9136 * some fairly slow code that needs optimization. This walks the list
9137 * of all the inodes with pending delalloc and forces them to disk.
9138 */
6c255e67
MX
9139static int __start_delalloc_inodes(struct btrfs_root *root, int delay_iput,
9140 int nr)
ea8c2819 9141{
ea8c2819 9142 struct btrfs_inode *binode;
5b21f2ed 9143 struct inode *inode;
8ccf6f19
MX
9144 struct btrfs_delalloc_work *work, *next;
9145 struct list_head works;
1eafa6c7 9146 struct list_head splice;
8ccf6f19 9147 int ret = 0;
ea8c2819 9148
8ccf6f19 9149 INIT_LIST_HEAD(&works);
1eafa6c7 9150 INIT_LIST_HEAD(&splice);
63607cc8 9151
573bfb72 9152 mutex_lock(&root->delalloc_mutex);
eb73c1b7
MX
9153 spin_lock(&root->delalloc_lock);
9154 list_splice_init(&root->delalloc_inodes, &splice);
1eafa6c7
MX
9155 while (!list_empty(&splice)) {
9156 binode = list_entry(splice.next, struct btrfs_inode,
ea8c2819 9157 delalloc_inodes);
1eafa6c7 9158
eb73c1b7
MX
9159 list_move_tail(&binode->delalloc_inodes,
9160 &root->delalloc_inodes);
5b21f2ed 9161 inode = igrab(&binode->vfs_inode);
df0af1a5 9162 if (!inode) {
eb73c1b7 9163 cond_resched_lock(&root->delalloc_lock);
1eafa6c7 9164 continue;
df0af1a5 9165 }
eb73c1b7 9166 spin_unlock(&root->delalloc_lock);
1eafa6c7
MX
9167
9168 work = btrfs_alloc_delalloc_work(inode, 0, delay_iput);
5d99a998 9169 if (!work) {
f4ab9ea7
JB
9170 if (delay_iput)
9171 btrfs_add_delayed_iput(inode);
9172 else
9173 iput(inode);
1eafa6c7 9174 ret = -ENOMEM;
a1ecaabb 9175 goto out;
5b21f2ed 9176 }
1eafa6c7 9177 list_add_tail(&work->list, &works);
a44903ab
QW
9178 btrfs_queue_work(root->fs_info->flush_workers,
9179 &work->work);
6c255e67
MX
9180 ret++;
9181 if (nr != -1 && ret >= nr)
a1ecaabb 9182 goto out;
5b21f2ed 9183 cond_resched();
eb73c1b7 9184 spin_lock(&root->delalloc_lock);
ea8c2819 9185 }
eb73c1b7 9186 spin_unlock(&root->delalloc_lock);
8c8bee1d 9187
a1ecaabb 9188out:
eb73c1b7
MX
9189 list_for_each_entry_safe(work, next, &works, list) {
9190 list_del_init(&work->list);
9191 btrfs_wait_and_free_delalloc_work(work);
9192 }
9193
9194 if (!list_empty_careful(&splice)) {
9195 spin_lock(&root->delalloc_lock);
9196 list_splice_tail(&splice, &root->delalloc_inodes);
9197 spin_unlock(&root->delalloc_lock);
9198 }
573bfb72 9199 mutex_unlock(&root->delalloc_mutex);
eb73c1b7
MX
9200 return ret;
9201}
1eafa6c7 9202
eb73c1b7
MX
9203int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
9204{
9205 int ret;
1eafa6c7 9206
2c21b4d7 9207 if (test_bit(BTRFS_FS_STATE_ERROR, &root->fs_info->fs_state))
eb73c1b7
MX
9208 return -EROFS;
9209
6c255e67
MX
9210 ret = __start_delalloc_inodes(root, delay_iput, -1);
9211 if (ret > 0)
9212 ret = 0;
eb73c1b7
MX
9213 /*
9214 * the filemap_flush will queue IO into the worker threads, but
8c8bee1d
CM
9215 * we have to make sure the IO is actually started and that
9216 * ordered extents get created before we return
9217 */
9218 atomic_inc(&root->fs_info->async_submit_draining);
d397712b 9219 while (atomic_read(&root->fs_info->nr_async_submits) ||
771ed689 9220 atomic_read(&root->fs_info->async_delalloc_pages)) {
8c8bee1d 9221 wait_event(root->fs_info->async_submit_wait,
771ed689
CM
9222 (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
9223 atomic_read(&root->fs_info->async_delalloc_pages) == 0));
8c8bee1d
CM
9224 }
9225 atomic_dec(&root->fs_info->async_submit_draining);
eb73c1b7
MX
9226 return ret;
9227}
9228
6c255e67
MX
9229int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int delay_iput,
9230 int nr)
eb73c1b7
MX
9231{
9232 struct btrfs_root *root;
9233 struct list_head splice;
9234 int ret;
9235
2c21b4d7 9236 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
eb73c1b7
MX
9237 return -EROFS;
9238
9239 INIT_LIST_HEAD(&splice);
9240
573bfb72 9241 mutex_lock(&fs_info->delalloc_root_mutex);
eb73c1b7
MX
9242 spin_lock(&fs_info->delalloc_root_lock);
9243 list_splice_init(&fs_info->delalloc_roots, &splice);
6c255e67 9244 while (!list_empty(&splice) && nr) {
eb73c1b7
MX
9245 root = list_first_entry(&splice, struct btrfs_root,
9246 delalloc_root);
9247 root = btrfs_grab_fs_root(root);
9248 BUG_ON(!root);
9249 list_move_tail(&root->delalloc_root,
9250 &fs_info->delalloc_roots);
9251 spin_unlock(&fs_info->delalloc_root_lock);
9252
6c255e67 9253 ret = __start_delalloc_inodes(root, delay_iput, nr);
eb73c1b7 9254 btrfs_put_fs_root(root);
6c255e67 9255 if (ret < 0)
eb73c1b7
MX
9256 goto out;
9257
6c255e67
MX
9258 if (nr != -1) {
9259 nr -= ret;
9260 WARN_ON(nr < 0);
9261 }
eb73c1b7 9262 spin_lock(&fs_info->delalloc_root_lock);
8ccf6f19 9263 }
eb73c1b7 9264 spin_unlock(&fs_info->delalloc_root_lock);
1eafa6c7 9265
6c255e67 9266 ret = 0;
eb73c1b7
MX
9267 atomic_inc(&fs_info->async_submit_draining);
9268 while (atomic_read(&fs_info->nr_async_submits) ||
9269 atomic_read(&fs_info->async_delalloc_pages)) {
9270 wait_event(fs_info->async_submit_wait,
9271 (atomic_read(&fs_info->nr_async_submits) == 0 &&
9272 atomic_read(&fs_info->async_delalloc_pages) == 0));
9273 }
9274 atomic_dec(&fs_info->async_submit_draining);
eb73c1b7 9275out:
1eafa6c7 9276 if (!list_empty_careful(&splice)) {
eb73c1b7
MX
9277 spin_lock(&fs_info->delalloc_root_lock);
9278 list_splice_tail(&splice, &fs_info->delalloc_roots);
9279 spin_unlock(&fs_info->delalloc_root_lock);
1eafa6c7 9280 }
573bfb72 9281 mutex_unlock(&fs_info->delalloc_root_mutex);
8ccf6f19 9282 return ret;
ea8c2819
CM
9283}
9284
39279cc3
CM
9285static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
9286 const char *symname)
9287{
9288 struct btrfs_trans_handle *trans;
9289 struct btrfs_root *root = BTRFS_I(dir)->root;
9290 struct btrfs_path *path;
9291 struct btrfs_key key;
1832a6d5 9292 struct inode *inode = NULL;
39279cc3
CM
9293 int err;
9294 int drop_inode = 0;
9295 u64 objectid;
67871254 9296 u64 index = 0;
39279cc3
CM
9297 int name_len;
9298 int datasize;
5f39d397 9299 unsigned long ptr;
39279cc3 9300 struct btrfs_file_extent_item *ei;
5f39d397 9301 struct extent_buffer *leaf;
39279cc3 9302
f06becc4 9303 name_len = strlen(symname);
39279cc3
CM
9304 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
9305 return -ENAMETOOLONG;
1832a6d5 9306
9ed74f2d
JB
9307 /*
9308 * 2 items for inode item and ref
9309 * 2 items for dir items
9310 * 1 item for xattr if selinux is on
9311 */
a22285a6
YZ
9312 trans = btrfs_start_transaction(root, 5);
9313 if (IS_ERR(trans))
9314 return PTR_ERR(trans);
1832a6d5 9315
581bb050
LZ
9316 err = btrfs_find_free_ino(root, &objectid);
9317 if (err)
9318 goto out_unlock;
9319
aec7477b 9320 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
33345d01 9321 dentry->d_name.len, btrfs_ino(dir), objectid,
d82a6f1d 9322 S_IFLNK|S_IRWXUGO, &index);
7cf96da3
TI
9323 if (IS_ERR(inode)) {
9324 err = PTR_ERR(inode);
39279cc3 9325 goto out_unlock;
7cf96da3 9326 }
39279cc3 9327
ad19db71
CS
9328 /*
9329 * If the active LSM wants to access the inode during
9330 * d_instantiate it needs these. Smack checks to see
9331 * if the filesystem supports xattrs by looking at the
9332 * ops vector.
9333 */
9334 inode->i_fop = &btrfs_file_operations;
9335 inode->i_op = &btrfs_file_inode_operations;
b0d5d10f 9336 inode->i_mapping->a_ops = &btrfs_aops;
b0d5d10f
CM
9337 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
9338
9339 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
9340 if (err)
9341 goto out_unlock_inode;
ad19db71 9342
a1b075d2 9343 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
39279cc3 9344 if (err)
b0d5d10f 9345 goto out_unlock_inode;
39279cc3
CM
9346
9347 path = btrfs_alloc_path();
d8926bb3
MF
9348 if (!path) {
9349 err = -ENOMEM;
b0d5d10f 9350 goto out_unlock_inode;
d8926bb3 9351 }
33345d01 9352 key.objectid = btrfs_ino(inode);
39279cc3 9353 key.offset = 0;
962a298f 9354 key.type = BTRFS_EXTENT_DATA_KEY;
39279cc3
CM
9355 datasize = btrfs_file_extent_calc_inline_size(name_len);
9356 err = btrfs_insert_empty_item(trans, root, path, &key,
9357 datasize);
54aa1f4d 9358 if (err) {
b0839166 9359 btrfs_free_path(path);
b0d5d10f 9360 goto out_unlock_inode;
54aa1f4d 9361 }
5f39d397
CM
9362 leaf = path->nodes[0];
9363 ei = btrfs_item_ptr(leaf, path->slots[0],
9364 struct btrfs_file_extent_item);
9365 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
9366 btrfs_set_file_extent_type(leaf, ei,
39279cc3 9367 BTRFS_FILE_EXTENT_INLINE);
c8b97818
CM
9368 btrfs_set_file_extent_encryption(leaf, ei, 0);
9369 btrfs_set_file_extent_compression(leaf, ei, 0);
9370 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
9371 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
9372
39279cc3 9373 ptr = btrfs_file_extent_inline_start(ei);
5f39d397
CM
9374 write_extent_buffer(leaf, symname, ptr, name_len);
9375 btrfs_mark_buffer_dirty(leaf);
39279cc3 9376 btrfs_free_path(path);
5f39d397 9377
39279cc3
CM
9378 inode->i_op = &btrfs_symlink_inode_operations;
9379 inode->i_mapping->a_ops = &btrfs_symlink_aops;
d899e052 9380 inode_set_bytes(inode, name_len);
f06becc4 9381 btrfs_i_size_write(inode, name_len);
54aa1f4d 9382 err = btrfs_update_inode(trans, root, inode);
b0d5d10f 9383 if (err) {
54aa1f4d 9384 drop_inode = 1;
b0d5d10f
CM
9385 goto out_unlock_inode;
9386 }
9387
9388 unlock_new_inode(inode);
9389 d_instantiate(dentry, inode);
39279cc3
CM
9390
9391out_unlock:
7ad85bb7 9392 btrfs_end_transaction(trans, root);
39279cc3
CM
9393 if (drop_inode) {
9394 inode_dec_link_count(inode);
9395 iput(inode);
9396 }
b53d3f5d 9397 btrfs_btree_balance_dirty(root);
39279cc3 9398 return err;
b0d5d10f
CM
9399
9400out_unlock_inode:
9401 drop_inode = 1;
9402 unlock_new_inode(inode);
9403 goto out_unlock;
39279cc3 9404}
16432985 9405
0af3d00b
JB
9406static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
9407 u64 start, u64 num_bytes, u64 min_size,
9408 loff_t actual_len, u64 *alloc_hint,
9409 struct btrfs_trans_handle *trans)
d899e052 9410{
5dc562c5
JB
9411 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
9412 struct extent_map *em;
d899e052
YZ
9413 struct btrfs_root *root = BTRFS_I(inode)->root;
9414 struct btrfs_key ins;
d899e052 9415 u64 cur_offset = start;
55a61d1d 9416 u64 i_size;
154ea289 9417 u64 cur_bytes;
d899e052 9418 int ret = 0;
0af3d00b 9419 bool own_trans = true;
d899e052 9420
0af3d00b
JB
9421 if (trans)
9422 own_trans = false;
d899e052 9423 while (num_bytes > 0) {
0af3d00b
JB
9424 if (own_trans) {
9425 trans = btrfs_start_transaction(root, 3);
9426 if (IS_ERR(trans)) {
9427 ret = PTR_ERR(trans);
9428 break;
9429 }
5a303d5d
YZ
9430 }
9431
154ea289
CM
9432 cur_bytes = min(num_bytes, 256ULL * 1024 * 1024);
9433 cur_bytes = max(cur_bytes, min_size);
00361589 9434 ret = btrfs_reserve_extent(root, cur_bytes, min_size, 0,
e570fd27 9435 *alloc_hint, &ins, 1, 0);
5a303d5d 9436 if (ret) {
0af3d00b
JB
9437 if (own_trans)
9438 btrfs_end_transaction(trans, root);
a22285a6 9439 break;
d899e052 9440 }
5a303d5d 9441
d899e052
YZ
9442 ret = insert_reserved_file_extent(trans, inode,
9443 cur_offset, ins.objectid,
9444 ins.offset, ins.offset,
920bbbfb 9445 ins.offset, 0, 0, 0,
d899e052 9446 BTRFS_FILE_EXTENT_PREALLOC);
79787eaa 9447 if (ret) {
857cc2fc 9448 btrfs_free_reserved_extent(root, ins.objectid,
e570fd27 9449 ins.offset, 0);
79787eaa
JM
9450 btrfs_abort_transaction(trans, root, ret);
9451 if (own_trans)
9452 btrfs_end_transaction(trans, root);
9453 break;
9454 }
a1ed835e
CM
9455 btrfs_drop_extent_cache(inode, cur_offset,
9456 cur_offset + ins.offset -1, 0);
5a303d5d 9457
5dc562c5
JB
9458 em = alloc_extent_map();
9459 if (!em) {
9460 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
9461 &BTRFS_I(inode)->runtime_flags);
9462 goto next;
9463 }
9464
9465 em->start = cur_offset;
9466 em->orig_start = cur_offset;
9467 em->len = ins.offset;
9468 em->block_start = ins.objectid;
9469 em->block_len = ins.offset;
b4939680 9470 em->orig_block_len = ins.offset;
cc95bef6 9471 em->ram_bytes = ins.offset;
5dc562c5
JB
9472 em->bdev = root->fs_info->fs_devices->latest_bdev;
9473 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
9474 em->generation = trans->transid;
9475
9476 while (1) {
9477 write_lock(&em_tree->lock);
09a2a8f9 9478 ret = add_extent_mapping(em_tree, em, 1);
5dc562c5
JB
9479 write_unlock(&em_tree->lock);
9480 if (ret != -EEXIST)
9481 break;
9482 btrfs_drop_extent_cache(inode, cur_offset,
9483 cur_offset + ins.offset - 1,
9484 0);
9485 }
9486 free_extent_map(em);
9487next:
d899e052
YZ
9488 num_bytes -= ins.offset;
9489 cur_offset += ins.offset;
efa56464 9490 *alloc_hint = ins.objectid + ins.offset;
5a303d5d 9491
0c4d2d95 9492 inode_inc_iversion(inode);
d899e052 9493 inode->i_ctime = CURRENT_TIME;
6cbff00f 9494 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
d899e052 9495 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
efa56464
YZ
9496 (actual_len > inode->i_size) &&
9497 (cur_offset > inode->i_size)) {
d1ea6a61 9498 if (cur_offset > actual_len)
55a61d1d 9499 i_size = actual_len;
d1ea6a61 9500 else
55a61d1d
JB
9501 i_size = cur_offset;
9502 i_size_write(inode, i_size);
9503 btrfs_ordered_update_i_size(inode, i_size, NULL);
5a303d5d
YZ
9504 }
9505
d899e052 9506 ret = btrfs_update_inode(trans, root, inode);
79787eaa
JM
9507
9508 if (ret) {
9509 btrfs_abort_transaction(trans, root, ret);
9510 if (own_trans)
9511 btrfs_end_transaction(trans, root);
9512 break;
9513 }
d899e052 9514
0af3d00b
JB
9515 if (own_trans)
9516 btrfs_end_transaction(trans, root);
5a303d5d 9517 }
d899e052
YZ
9518 return ret;
9519}
9520
0af3d00b
JB
9521int btrfs_prealloc_file_range(struct inode *inode, int mode,
9522 u64 start, u64 num_bytes, u64 min_size,
9523 loff_t actual_len, u64 *alloc_hint)
9524{
9525 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9526 min_size, actual_len, alloc_hint,
9527 NULL);
9528}
9529
9530int btrfs_prealloc_file_range_trans(struct inode *inode,
9531 struct btrfs_trans_handle *trans, int mode,
9532 u64 start, u64 num_bytes, u64 min_size,
9533 loff_t actual_len, u64 *alloc_hint)
9534{
9535 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9536 min_size, actual_len, alloc_hint, trans);
9537}
9538
e6dcd2dc
CM
9539static int btrfs_set_page_dirty(struct page *page)
9540{
e6dcd2dc
CM
9541 return __set_page_dirty_nobuffers(page);
9542}
9543
10556cb2 9544static int btrfs_permission(struct inode *inode, int mask)
fdebe2bd 9545{
b83cc969 9546 struct btrfs_root *root = BTRFS_I(inode)->root;
cb6db4e5 9547 umode_t mode = inode->i_mode;
b83cc969 9548
cb6db4e5
JM
9549 if (mask & MAY_WRITE &&
9550 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
9551 if (btrfs_root_readonly(root))
9552 return -EROFS;
9553 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
9554 return -EACCES;
9555 }
2830ba7f 9556 return generic_permission(inode, mask);
fdebe2bd 9557}
39279cc3 9558
ef3b9af5
FM
9559static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
9560{
9561 struct btrfs_trans_handle *trans;
9562 struct btrfs_root *root = BTRFS_I(dir)->root;
9563 struct inode *inode = NULL;
9564 u64 objectid;
9565 u64 index;
9566 int ret = 0;
9567
9568 /*
9569 * 5 units required for adding orphan entry
9570 */
9571 trans = btrfs_start_transaction(root, 5);
9572 if (IS_ERR(trans))
9573 return PTR_ERR(trans);
9574
9575 ret = btrfs_find_free_ino(root, &objectid);
9576 if (ret)
9577 goto out;
9578
9579 inode = btrfs_new_inode(trans, root, dir, NULL, 0,
9580 btrfs_ino(dir), objectid, mode, &index);
9581 if (IS_ERR(inode)) {
9582 ret = PTR_ERR(inode);
9583 inode = NULL;
9584 goto out;
9585 }
9586
ef3b9af5
FM
9587 inode->i_fop = &btrfs_file_operations;
9588 inode->i_op = &btrfs_file_inode_operations;
9589
9590 inode->i_mapping->a_ops = &btrfs_aops;
ef3b9af5
FM
9591 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
9592
b0d5d10f
CM
9593 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
9594 if (ret)
9595 goto out_inode;
9596
9597 ret = btrfs_update_inode(trans, root, inode);
9598 if (ret)
9599 goto out_inode;
ef3b9af5
FM
9600 ret = btrfs_orphan_add(trans, inode);
9601 if (ret)
b0d5d10f 9602 goto out_inode;
ef3b9af5 9603
5762b5c9
FM
9604 /*
9605 * We set number of links to 0 in btrfs_new_inode(), and here we set
9606 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
9607 * through:
9608 *
9609 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
9610 */
9611 set_nlink(inode, 1);
b0d5d10f 9612 unlock_new_inode(inode);
ef3b9af5
FM
9613 d_tmpfile(dentry, inode);
9614 mark_inode_dirty(inode);
9615
9616out:
9617 btrfs_end_transaction(trans, root);
9618 if (ret)
9619 iput(inode);
9620 btrfs_balance_delayed_items(root);
9621 btrfs_btree_balance_dirty(root);
ef3b9af5 9622 return ret;
b0d5d10f
CM
9623
9624out_inode:
9625 unlock_new_inode(inode);
9626 goto out;
9627
ef3b9af5
FM
9628}
9629
b38ef71c
FM
9630/* Inspired by filemap_check_errors() */
9631int btrfs_inode_check_errors(struct inode *inode)
9632{
9633 int ret = 0;
9634
9635 if (test_bit(AS_ENOSPC, &inode->i_mapping->flags) &&
9636 test_and_clear_bit(AS_ENOSPC, &inode->i_mapping->flags))
9637 ret = -ENOSPC;
9638 if (test_bit(AS_EIO, &inode->i_mapping->flags) &&
9639 test_and_clear_bit(AS_EIO, &inode->i_mapping->flags))
9640 ret = -EIO;
9641
9642 return ret;
9643}
9644
6e1d5dcc 9645static const struct inode_operations btrfs_dir_inode_operations = {
3394e160 9646 .getattr = btrfs_getattr,
39279cc3
CM
9647 .lookup = btrfs_lookup,
9648 .create = btrfs_create,
9649 .unlink = btrfs_unlink,
9650 .link = btrfs_link,
9651 .mkdir = btrfs_mkdir,
9652 .rmdir = btrfs_rmdir,
80ace85c 9653 .rename2 = btrfs_rename2,
39279cc3
CM
9654 .symlink = btrfs_symlink,
9655 .setattr = btrfs_setattr,
618e21d5 9656 .mknod = btrfs_mknod,
95819c05
CH
9657 .setxattr = btrfs_setxattr,
9658 .getxattr = btrfs_getxattr,
5103e947 9659 .listxattr = btrfs_listxattr,
95819c05 9660 .removexattr = btrfs_removexattr,
fdebe2bd 9661 .permission = btrfs_permission,
4e34e719 9662 .get_acl = btrfs_get_acl,
996a710d 9663 .set_acl = btrfs_set_acl,
93fd63c2 9664 .update_time = btrfs_update_time,
ef3b9af5 9665 .tmpfile = btrfs_tmpfile,
39279cc3 9666};
6e1d5dcc 9667static const struct inode_operations btrfs_dir_ro_inode_operations = {
39279cc3 9668 .lookup = btrfs_lookup,
fdebe2bd 9669 .permission = btrfs_permission,
4e34e719 9670 .get_acl = btrfs_get_acl,
996a710d 9671 .set_acl = btrfs_set_acl,
93fd63c2 9672 .update_time = btrfs_update_time,
39279cc3 9673};
76dda93c 9674
828c0950 9675static const struct file_operations btrfs_dir_file_operations = {
39279cc3
CM
9676 .llseek = generic_file_llseek,
9677 .read = generic_read_dir,
9cdda8d3 9678 .iterate = btrfs_real_readdir,
34287aa3 9679 .unlocked_ioctl = btrfs_ioctl,
39279cc3 9680#ifdef CONFIG_COMPAT
34287aa3 9681 .compat_ioctl = btrfs_ioctl,
39279cc3 9682#endif
6bf13c0c 9683 .release = btrfs_release_file,
e02119d5 9684 .fsync = btrfs_sync_file,
39279cc3
CM
9685};
9686
d1310b2e 9687static struct extent_io_ops btrfs_extent_io_ops = {
07157aac 9688 .fill_delalloc = run_delalloc_range,
065631f6 9689 .submit_bio_hook = btrfs_submit_bio_hook,
239b14b3 9690 .merge_bio_hook = btrfs_merge_bio_hook,
07157aac 9691 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
e6dcd2dc 9692 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
247e743c 9693 .writepage_start_hook = btrfs_writepage_start_hook,
b0c68f8b
CM
9694 .set_bit_hook = btrfs_set_bit_hook,
9695 .clear_bit_hook = btrfs_clear_bit_hook,
9ed74f2d
JB
9696 .merge_extent_hook = btrfs_merge_extent_hook,
9697 .split_extent_hook = btrfs_split_extent_hook,
07157aac
CM
9698};
9699
35054394
CM
9700/*
9701 * btrfs doesn't support the bmap operation because swapfiles
9702 * use bmap to make a mapping of extents in the file. They assume
9703 * these extents won't change over the life of the file and they
9704 * use the bmap result to do IO directly to the drive.
9705 *
9706 * the btrfs bmap call would return logical addresses that aren't
9707 * suitable for IO and they also will change frequently as COW
9708 * operations happen. So, swapfile + btrfs == corruption.
9709 *
9710 * For now we're avoiding this by dropping bmap.
9711 */
7f09410b 9712static const struct address_space_operations btrfs_aops = {
39279cc3
CM
9713 .readpage = btrfs_readpage,
9714 .writepage = btrfs_writepage,
b293f02e 9715 .writepages = btrfs_writepages,
3ab2fb5a 9716 .readpages = btrfs_readpages,
16432985 9717 .direct_IO = btrfs_direct_IO,
a52d9a80
CM
9718 .invalidatepage = btrfs_invalidatepage,
9719 .releasepage = btrfs_releasepage,
e6dcd2dc 9720 .set_page_dirty = btrfs_set_page_dirty,
465fdd97 9721 .error_remove_page = generic_error_remove_page,
39279cc3
CM
9722};
9723
7f09410b 9724static const struct address_space_operations btrfs_symlink_aops = {
39279cc3
CM
9725 .readpage = btrfs_readpage,
9726 .writepage = btrfs_writepage,
2bf5a725
CM
9727 .invalidatepage = btrfs_invalidatepage,
9728 .releasepage = btrfs_releasepage,
39279cc3
CM
9729};
9730
6e1d5dcc 9731static const struct inode_operations btrfs_file_inode_operations = {
39279cc3
CM
9732 .getattr = btrfs_getattr,
9733 .setattr = btrfs_setattr,
95819c05
CH
9734 .setxattr = btrfs_setxattr,
9735 .getxattr = btrfs_getxattr,
5103e947 9736 .listxattr = btrfs_listxattr,
95819c05 9737 .removexattr = btrfs_removexattr,
fdebe2bd 9738 .permission = btrfs_permission,
1506fcc8 9739 .fiemap = btrfs_fiemap,
4e34e719 9740 .get_acl = btrfs_get_acl,
996a710d 9741 .set_acl = btrfs_set_acl,
e41f941a 9742 .update_time = btrfs_update_time,
39279cc3 9743};
6e1d5dcc 9744static const struct inode_operations btrfs_special_inode_operations = {
618e21d5
JB
9745 .getattr = btrfs_getattr,
9746 .setattr = btrfs_setattr,
fdebe2bd 9747 .permission = btrfs_permission,
95819c05
CH
9748 .setxattr = btrfs_setxattr,
9749 .getxattr = btrfs_getxattr,
33268eaf 9750 .listxattr = btrfs_listxattr,
95819c05 9751 .removexattr = btrfs_removexattr,
4e34e719 9752 .get_acl = btrfs_get_acl,
996a710d 9753 .set_acl = btrfs_set_acl,
e41f941a 9754 .update_time = btrfs_update_time,
618e21d5 9755};
6e1d5dcc 9756static const struct inode_operations btrfs_symlink_inode_operations = {
39279cc3
CM
9757 .readlink = generic_readlink,
9758 .follow_link = page_follow_link_light,
9759 .put_link = page_put_link,
f209561a 9760 .getattr = btrfs_getattr,
22c44fe6 9761 .setattr = btrfs_setattr,
fdebe2bd 9762 .permission = btrfs_permission,
0279b4cd
JO
9763 .setxattr = btrfs_setxattr,
9764 .getxattr = btrfs_getxattr,
9765 .listxattr = btrfs_listxattr,
9766 .removexattr = btrfs_removexattr,
e41f941a 9767 .update_time = btrfs_update_time,
39279cc3 9768};
76dda93c 9769
82d339d9 9770const struct dentry_operations btrfs_dentry_operations = {
76dda93c 9771 .d_delete = btrfs_dentry_delete,
b4aff1f8 9772 .d_release = btrfs_dentry_release,
76dda93c 9773};
This page took 2.026395 seconds and 5 git commands to generate.