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