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