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