Btrfs: add a cond_resched() into the worker loop
[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>
9ebefb18 35#include <linux/bit_spinlock.h>
5103e947 36#include <linux/xattr.h>
33268eaf 37#include <linux/posix_acl.h>
d899e052 38#include <linux/falloc.h>
5a0e3ad6 39#include <linux/slab.h>
7a36ddec 40#include <linux/ratelimit.h>
4b4e25f2 41#include "compat.h"
39279cc3
CM
42#include "ctree.h"
43#include "disk-io.h"
44#include "transaction.h"
45#include "btrfs_inode.h"
46#include "ioctl.h"
47#include "print-tree.h"
e6dcd2dc 48#include "ordered-data.h"
95819c05 49#include "xattr.h"
e02119d5 50#include "tree-log.h"
4a54c8c1 51#include "volumes.h"
c8b97818 52#include "compression.h"
b4ce94de 53#include "locking.h"
dc89e982 54#include "free-space-cache.h"
581bb050 55#include "inode-map.h"
39279cc3
CM
56
57struct btrfs_iget_args {
58 u64 ino;
59 struct btrfs_root *root;
60};
61
6e1d5dcc
AD
62static const struct inode_operations btrfs_dir_inode_operations;
63static const struct inode_operations btrfs_symlink_inode_operations;
64static const struct inode_operations btrfs_dir_ro_inode_operations;
65static const struct inode_operations btrfs_special_inode_operations;
66static const struct inode_operations btrfs_file_inode_operations;
7f09410b
AD
67static const struct address_space_operations btrfs_aops;
68static const struct address_space_operations btrfs_symlink_aops;
828c0950 69static const struct file_operations btrfs_dir_file_operations;
d1310b2e 70static struct extent_io_ops btrfs_extent_io_ops;
39279cc3
CM
71
72static struct kmem_cache *btrfs_inode_cachep;
73struct kmem_cache *btrfs_trans_handle_cachep;
74struct kmem_cache *btrfs_transaction_cachep;
39279cc3 75struct kmem_cache *btrfs_path_cachep;
dc89e982 76struct kmem_cache *btrfs_free_space_cachep;
39279cc3
CM
77
78#define S_SHIFT 12
79static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
80 [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
81 [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
82 [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
83 [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
84 [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
85 [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
86 [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
87};
88
a41ad394
JB
89static int btrfs_setsize(struct inode *inode, loff_t newsize);
90static int btrfs_truncate(struct inode *inode);
c8b97818 91static int btrfs_finish_ordered_io(struct inode *inode, u64 start, u64 end);
771ed689
CM
92static noinline int cow_file_range(struct inode *inode,
93 struct page *locked_page,
94 u64 start, u64 end, int *page_started,
95 unsigned long *nr_written, int unlock);
2115133f
CM
96static noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
97 struct btrfs_root *root, struct inode *inode);
7b128766 98
f34f57a3 99static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
2a7dba39
EP
100 struct inode *inode, struct inode *dir,
101 const struct qstr *qstr)
0279b4cd
JO
102{
103 int err;
104
f34f57a3 105 err = btrfs_init_acl(trans, inode, dir);
0279b4cd 106 if (!err)
2a7dba39 107 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
0279b4cd
JO
108 return err;
109}
110
c8b97818
CM
111/*
112 * this does all the hard work for inserting an inline extent into
113 * the btree. The caller should have done a btrfs_drop_extents so that
114 * no overlapping inline items exist in the btree
115 */
d397712b 116static noinline int insert_inline_extent(struct btrfs_trans_handle *trans,
c8b97818
CM
117 struct btrfs_root *root, struct inode *inode,
118 u64 start, size_t size, size_t compressed_size,
fe3f566c 119 int compress_type,
c8b97818
CM
120 struct page **compressed_pages)
121{
122 struct btrfs_key key;
123 struct btrfs_path *path;
124 struct extent_buffer *leaf;
125 struct page *page = NULL;
126 char *kaddr;
127 unsigned long ptr;
128 struct btrfs_file_extent_item *ei;
129 int err = 0;
130 int ret;
131 size_t cur_size = size;
132 size_t datasize;
133 unsigned long offset;
c8b97818 134
fe3f566c 135 if (compressed_size && compressed_pages)
c8b97818 136 cur_size = compressed_size;
c8b97818 137
d397712b
CM
138 path = btrfs_alloc_path();
139 if (!path)
c8b97818
CM
140 return -ENOMEM;
141
b9473439 142 path->leave_spinning = 1;
c8b97818 143
33345d01 144 key.objectid = btrfs_ino(inode);
c8b97818
CM
145 key.offset = start;
146 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
c8b97818
CM
147 datasize = btrfs_file_extent_calc_inline_size(cur_size);
148
149 inode_add_bytes(inode, size);
150 ret = btrfs_insert_empty_item(trans, root, path, &key,
151 datasize);
152 BUG_ON(ret);
153 if (ret) {
154 err = ret;
c8b97818
CM
155 goto fail;
156 }
157 leaf = path->nodes[0];
158 ei = btrfs_item_ptr(leaf, path->slots[0],
159 struct btrfs_file_extent_item);
160 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
161 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
162 btrfs_set_file_extent_encryption(leaf, ei, 0);
163 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
164 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
165 ptr = btrfs_file_extent_inline_start(ei);
166
261507a0 167 if (compress_type != BTRFS_COMPRESS_NONE) {
c8b97818
CM
168 struct page *cpage;
169 int i = 0;
d397712b 170 while (compressed_size > 0) {
c8b97818 171 cpage = compressed_pages[i];
5b050f04 172 cur_size = min_t(unsigned long, compressed_size,
c8b97818
CM
173 PAGE_CACHE_SIZE);
174
b9473439 175 kaddr = kmap_atomic(cpage, KM_USER0);
c8b97818 176 write_extent_buffer(leaf, kaddr, ptr, cur_size);
b9473439 177 kunmap_atomic(kaddr, KM_USER0);
c8b97818
CM
178
179 i++;
180 ptr += cur_size;
181 compressed_size -= cur_size;
182 }
183 btrfs_set_file_extent_compression(leaf, ei,
261507a0 184 compress_type);
c8b97818
CM
185 } else {
186 page = find_get_page(inode->i_mapping,
187 start >> PAGE_CACHE_SHIFT);
188 btrfs_set_file_extent_compression(leaf, ei, 0);
189 kaddr = kmap_atomic(page, KM_USER0);
190 offset = start & (PAGE_CACHE_SIZE - 1);
191 write_extent_buffer(leaf, kaddr + offset, ptr, size);
192 kunmap_atomic(kaddr, KM_USER0);
193 page_cache_release(page);
194 }
195 btrfs_mark_buffer_dirty(leaf);
196 btrfs_free_path(path);
197
c2167754
YZ
198 /*
199 * we're an inline extent, so nobody can
200 * extend the file past i_size without locking
201 * a page we already have locked.
202 *
203 * We must do any isize and inode updates
204 * before we unlock the pages. Otherwise we
205 * could end up racing with unlink.
206 */
c8b97818
CM
207 BTRFS_I(inode)->disk_i_size = inode->i_size;
208 btrfs_update_inode(trans, root, inode);
c2167754 209
c8b97818
CM
210 return 0;
211fail:
212 btrfs_free_path(path);
213 return err;
214}
215
216
217/*
218 * conditionally insert an inline extent into the file. This
219 * does the checks required to make sure the data is small enough
220 * to fit as an inline extent.
221 */
7f366cfe 222static noinline int cow_file_range_inline(struct btrfs_trans_handle *trans,
c8b97818
CM
223 struct btrfs_root *root,
224 struct inode *inode, u64 start, u64 end,
fe3f566c 225 size_t compressed_size, int compress_type,
c8b97818
CM
226 struct page **compressed_pages)
227{
228 u64 isize = i_size_read(inode);
229 u64 actual_end = min(end + 1, isize);
230 u64 inline_len = actual_end - start;
231 u64 aligned_end = (end + root->sectorsize - 1) &
232 ~((u64)root->sectorsize - 1);
233 u64 hint_byte;
234 u64 data_len = inline_len;
235 int ret;
236
237 if (compressed_size)
238 data_len = compressed_size;
239
240 if (start > 0 ||
70b99e69 241 actual_end >= PAGE_CACHE_SIZE ||
c8b97818
CM
242 data_len >= BTRFS_MAX_INLINE_DATA_SIZE(root) ||
243 (!compressed_size &&
244 (actual_end & (root->sectorsize - 1)) == 0) ||
245 end + 1 < isize ||
246 data_len > root->fs_info->max_inline) {
247 return 1;
248 }
249
920bbbfb 250 ret = btrfs_drop_extents(trans, inode, start, aligned_end,
a1ed835e 251 &hint_byte, 1);
c8b97818
CM
252 BUG_ON(ret);
253
254 if (isize > actual_end)
255 inline_len = min_t(u64, isize, actual_end);
256 ret = insert_inline_extent(trans, root, inode, start,
257 inline_len, compressed_size,
fe3f566c 258 compress_type, compressed_pages);
c8b97818 259 BUG_ON(ret);
0ca1f7ce 260 btrfs_delalloc_release_metadata(inode, end + 1 - start);
a1ed835e 261 btrfs_drop_extent_cache(inode, start, aligned_end - 1, 0);
c8b97818
CM
262 return 0;
263}
264
771ed689
CM
265struct async_extent {
266 u64 start;
267 u64 ram_size;
268 u64 compressed_size;
269 struct page **pages;
270 unsigned long nr_pages;
261507a0 271 int compress_type;
771ed689
CM
272 struct list_head list;
273};
274
275struct async_cow {
276 struct inode *inode;
277 struct btrfs_root *root;
278 struct page *locked_page;
279 u64 start;
280 u64 end;
281 struct list_head extents;
282 struct btrfs_work work;
283};
284
285static noinline int add_async_extent(struct async_cow *cow,
286 u64 start, u64 ram_size,
287 u64 compressed_size,
288 struct page **pages,
261507a0
LZ
289 unsigned long nr_pages,
290 int compress_type)
771ed689
CM
291{
292 struct async_extent *async_extent;
293
294 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
dac97e51 295 BUG_ON(!async_extent);
771ed689
CM
296 async_extent->start = start;
297 async_extent->ram_size = ram_size;
298 async_extent->compressed_size = compressed_size;
299 async_extent->pages = pages;
300 async_extent->nr_pages = nr_pages;
261507a0 301 async_extent->compress_type = compress_type;
771ed689
CM
302 list_add_tail(&async_extent->list, &cow->extents);
303 return 0;
304}
305
d352ac68 306/*
771ed689
CM
307 * we create compressed extents in two phases. The first
308 * phase compresses a range of pages that have already been
309 * locked (both pages and state bits are locked).
c8b97818 310 *
771ed689
CM
311 * This is done inside an ordered work queue, and the compression
312 * is spread across many cpus. The actual IO submission is step
313 * two, and the ordered work queue takes care of making sure that
314 * happens in the same order things were put onto the queue by
315 * writepages and friends.
c8b97818 316 *
771ed689
CM
317 * If this code finds it can't get good compression, it puts an
318 * entry onto the work queue to write the uncompressed bytes. This
319 * makes sure that both compressed inodes and uncompressed inodes
320 * are written in the same order that pdflush sent them down.
d352ac68 321 */
771ed689
CM
322static noinline int compress_file_range(struct inode *inode,
323 struct page *locked_page,
324 u64 start, u64 end,
325 struct async_cow *async_cow,
326 int *num_added)
b888db2b
CM
327{
328 struct btrfs_root *root = BTRFS_I(inode)->root;
329 struct btrfs_trans_handle *trans;
db94535d 330 u64 num_bytes;
db94535d 331 u64 blocksize = root->sectorsize;
c8b97818 332 u64 actual_end;
42dc7bab 333 u64 isize = i_size_read(inode);
e6dcd2dc 334 int ret = 0;
c8b97818
CM
335 struct page **pages = NULL;
336 unsigned long nr_pages;
337 unsigned long nr_pages_ret = 0;
338 unsigned long total_compressed = 0;
339 unsigned long total_in = 0;
340 unsigned long max_compressed = 128 * 1024;
771ed689 341 unsigned long max_uncompressed = 128 * 1024;
c8b97818
CM
342 int i;
343 int will_compress;
261507a0 344 int compress_type = root->fs_info->compress_type;
b888db2b 345
4cb5300b
CM
346 /* if this is a small write inside eof, kick off a defragbot */
347 if (end <= BTRFS_I(inode)->disk_i_size && (end - start + 1) < 16 * 1024)
348 btrfs_add_inode_defrag(NULL, inode);
349
42dc7bab 350 actual_end = min_t(u64, isize, end + 1);
c8b97818
CM
351again:
352 will_compress = 0;
353 nr_pages = (end >> PAGE_CACHE_SHIFT) - (start >> PAGE_CACHE_SHIFT) + 1;
354 nr_pages = min(nr_pages, (128 * 1024UL) / PAGE_CACHE_SIZE);
be20aa9d 355
f03d9301
CM
356 /*
357 * we don't want to send crud past the end of i_size through
358 * compression, that's just a waste of CPU time. So, if the
359 * end of the file is before the start of our current
360 * requested range of bytes, we bail out to the uncompressed
361 * cleanup code that can deal with all of this.
362 *
363 * It isn't really the fastest way to fix things, but this is a
364 * very uncommon corner.
365 */
366 if (actual_end <= start)
367 goto cleanup_and_bail_uncompressed;
368
c8b97818
CM
369 total_compressed = actual_end - start;
370
371 /* we want to make sure that amount of ram required to uncompress
372 * an extent is reasonable, so we limit the total size in ram
771ed689
CM
373 * of a compressed extent to 128k. This is a crucial number
374 * because it also controls how easily we can spread reads across
375 * cpus for decompression.
376 *
377 * We also want to make sure the amount of IO required to do
378 * a random read is reasonably small, so we limit the size of
379 * a compressed extent to 128k.
c8b97818
CM
380 */
381 total_compressed = min(total_compressed, max_uncompressed);
db94535d 382 num_bytes = (end - start + blocksize) & ~(blocksize - 1);
be20aa9d 383 num_bytes = max(blocksize, num_bytes);
c8b97818
CM
384 total_in = 0;
385 ret = 0;
db94535d 386
771ed689
CM
387 /*
388 * we do compression for mount -o compress and when the
389 * inode has not been flagged as nocompress. This flag can
390 * change at any time if we discover bad compression ratios.
c8b97818 391 */
6cbff00f 392 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS) &&
1e701a32 393 (btrfs_test_opt(root, COMPRESS) ||
75e7cb7f
LB
394 (BTRFS_I(inode)->force_compress) ||
395 (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS))) {
c8b97818 396 WARN_ON(pages);
cfbc246e 397 pages = kzalloc(sizeof(struct page *) * nr_pages, GFP_NOFS);
560f7d75
LZ
398 if (!pages) {
399 /* just bail out to the uncompressed code */
400 goto cont;
401 }
c8b97818 402
261507a0
LZ
403 if (BTRFS_I(inode)->force_compress)
404 compress_type = BTRFS_I(inode)->force_compress;
405
406 ret = btrfs_compress_pages(compress_type,
407 inode->i_mapping, start,
408 total_compressed, pages,
409 nr_pages, &nr_pages_ret,
410 &total_in,
411 &total_compressed,
412 max_compressed);
c8b97818
CM
413
414 if (!ret) {
415 unsigned long offset = total_compressed &
416 (PAGE_CACHE_SIZE - 1);
417 struct page *page = pages[nr_pages_ret - 1];
418 char *kaddr;
419
420 /* zero the tail end of the last page, we might be
421 * sending it down to disk
422 */
423 if (offset) {
424 kaddr = kmap_atomic(page, KM_USER0);
425 memset(kaddr + offset, 0,
426 PAGE_CACHE_SIZE - offset);
427 kunmap_atomic(kaddr, KM_USER0);
428 }
429 will_compress = 1;
430 }
431 }
560f7d75 432cont:
c8b97818 433 if (start == 0) {
7a7eaa40 434 trans = btrfs_join_transaction(root);
3612b495 435 BUG_ON(IS_ERR(trans));
0ca1f7ce 436 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
771ed689 437
c8b97818 438 /* lets try to make an inline extent */
771ed689 439 if (ret || total_in < (actual_end - start)) {
c8b97818 440 /* we didn't compress the entire range, try
771ed689 441 * to make an uncompressed inline extent.
c8b97818
CM
442 */
443 ret = cow_file_range_inline(trans, root, inode,
fe3f566c 444 start, end, 0, 0, NULL);
c8b97818 445 } else {
771ed689 446 /* try making a compressed inline extent */
c8b97818
CM
447 ret = cow_file_range_inline(trans, root, inode,
448 start, end,
fe3f566c
LZ
449 total_compressed,
450 compress_type, pages);
c8b97818
CM
451 }
452 if (ret == 0) {
771ed689
CM
453 /*
454 * inline extent creation worked, we don't need
455 * to create any more async work items. Unlock
456 * and free up our temp pages.
457 */
c8b97818 458 extent_clear_unlock_delalloc(inode,
a791e35e
CM
459 &BTRFS_I(inode)->io_tree,
460 start, end, NULL,
461 EXTENT_CLEAR_UNLOCK_PAGE | EXTENT_CLEAR_DIRTY |
a3429ab7 462 EXTENT_CLEAR_DELALLOC |
a791e35e 463 EXTENT_SET_WRITEBACK | EXTENT_END_WRITEBACK);
c2167754
YZ
464
465 btrfs_end_transaction(trans, root);
c8b97818
CM
466 goto free_pages_out;
467 }
c2167754 468 btrfs_end_transaction(trans, root);
c8b97818
CM
469 }
470
471 if (will_compress) {
472 /*
473 * we aren't doing an inline extent round the compressed size
474 * up to a block size boundary so the allocator does sane
475 * things
476 */
477 total_compressed = (total_compressed + blocksize - 1) &
478 ~(blocksize - 1);
479
480 /*
481 * one last check to make sure the compression is really a
482 * win, compare the page count read with the blocks on disk
483 */
484 total_in = (total_in + PAGE_CACHE_SIZE - 1) &
485 ~(PAGE_CACHE_SIZE - 1);
486 if (total_compressed >= total_in) {
487 will_compress = 0;
488 } else {
c8b97818
CM
489 num_bytes = total_in;
490 }
491 }
492 if (!will_compress && pages) {
493 /*
494 * the compression code ran but failed to make things smaller,
495 * free any pages it allocated and our page pointer array
496 */
497 for (i = 0; i < nr_pages_ret; i++) {
70b99e69 498 WARN_ON(pages[i]->mapping);
c8b97818
CM
499 page_cache_release(pages[i]);
500 }
501 kfree(pages);
502 pages = NULL;
503 total_compressed = 0;
504 nr_pages_ret = 0;
505
506 /* flag the file so we don't compress in the future */
1e701a32
CM
507 if (!btrfs_test_opt(root, FORCE_COMPRESS) &&
508 !(BTRFS_I(inode)->force_compress)) {
a555f810 509 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
1e701a32 510 }
c8b97818 511 }
771ed689
CM
512 if (will_compress) {
513 *num_added += 1;
c8b97818 514
771ed689
CM
515 /* the async work queues will take care of doing actual
516 * allocation on disk for these compressed pages,
517 * and will submit them to the elevator.
518 */
519 add_async_extent(async_cow, start, num_bytes,
261507a0
LZ
520 total_compressed, pages, nr_pages_ret,
521 compress_type);
179e29e4 522
24ae6365 523 if (start + num_bytes < end) {
771ed689
CM
524 start += num_bytes;
525 pages = NULL;
526 cond_resched();
527 goto again;
528 }
529 } else {
f03d9301 530cleanup_and_bail_uncompressed:
771ed689
CM
531 /*
532 * No compression, but we still need to write the pages in
533 * the file we've been given so far. redirty the locked
534 * page if it corresponds to our extent and set things up
535 * for the async work queue to run cow_file_range to do
536 * the normal delalloc dance
537 */
538 if (page_offset(locked_page) >= start &&
539 page_offset(locked_page) <= end) {
540 __set_page_dirty_nobuffers(locked_page);
541 /* unlocked later on in the async handlers */
542 }
261507a0
LZ
543 add_async_extent(async_cow, start, end - start + 1,
544 0, NULL, 0, BTRFS_COMPRESS_NONE);
771ed689
CM
545 *num_added += 1;
546 }
3b951516 547
771ed689
CM
548out:
549 return 0;
550
551free_pages_out:
552 for (i = 0; i < nr_pages_ret; i++) {
553 WARN_ON(pages[i]->mapping);
554 page_cache_release(pages[i]);
555 }
d397712b 556 kfree(pages);
771ed689
CM
557
558 goto out;
559}
560
561/*
562 * phase two of compressed writeback. This is the ordered portion
563 * of the code, which only gets called in the order the work was
564 * queued. We walk all the async extents created by compress_file_range
565 * and send them down to the disk.
566 */
567static noinline int submit_compressed_extents(struct inode *inode,
568 struct async_cow *async_cow)
569{
570 struct async_extent *async_extent;
571 u64 alloc_hint = 0;
572 struct btrfs_trans_handle *trans;
573 struct btrfs_key ins;
574 struct extent_map *em;
575 struct btrfs_root *root = BTRFS_I(inode)->root;
576 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
577 struct extent_io_tree *io_tree;
f5a84ee3 578 int ret = 0;
771ed689
CM
579
580 if (list_empty(&async_cow->extents))
581 return 0;
582
771ed689 583
d397712b 584 while (!list_empty(&async_cow->extents)) {
771ed689
CM
585 async_extent = list_entry(async_cow->extents.next,
586 struct async_extent, list);
587 list_del(&async_extent->list);
c8b97818 588
771ed689
CM
589 io_tree = &BTRFS_I(inode)->io_tree;
590
f5a84ee3 591retry:
771ed689
CM
592 /* did the compression code fall back to uncompressed IO? */
593 if (!async_extent->pages) {
594 int page_started = 0;
595 unsigned long nr_written = 0;
596
597 lock_extent(io_tree, async_extent->start,
2ac55d41
JB
598 async_extent->start +
599 async_extent->ram_size - 1, GFP_NOFS);
771ed689
CM
600
601 /* allocate blocks */
f5a84ee3
JB
602 ret = cow_file_range(inode, async_cow->locked_page,
603 async_extent->start,
604 async_extent->start +
605 async_extent->ram_size - 1,
606 &page_started, &nr_written, 0);
771ed689
CM
607
608 /*
609 * if page_started, cow_file_range inserted an
610 * inline extent and took care of all the unlocking
611 * and IO for us. Otherwise, we need to submit
612 * all those pages down to the drive.
613 */
f5a84ee3 614 if (!page_started && !ret)
771ed689
CM
615 extent_write_locked_range(io_tree,
616 inode, async_extent->start,
d397712b 617 async_extent->start +
771ed689
CM
618 async_extent->ram_size - 1,
619 btrfs_get_extent,
620 WB_SYNC_ALL);
621 kfree(async_extent);
622 cond_resched();
623 continue;
624 }
625
626 lock_extent(io_tree, async_extent->start,
627 async_extent->start + async_extent->ram_size - 1,
628 GFP_NOFS);
771ed689 629
7a7eaa40 630 trans = btrfs_join_transaction(root);
3612b495 631 BUG_ON(IS_ERR(trans));
74b21075 632 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
771ed689
CM
633 ret = btrfs_reserve_extent(trans, root,
634 async_extent->compressed_size,
635 async_extent->compressed_size,
636 0, alloc_hint,
637 (u64)-1, &ins, 1);
c2167754
YZ
638 btrfs_end_transaction(trans, root);
639
f5a84ee3
JB
640 if (ret) {
641 int i;
642 for (i = 0; i < async_extent->nr_pages; i++) {
643 WARN_ON(async_extent->pages[i]->mapping);
644 page_cache_release(async_extent->pages[i]);
645 }
646 kfree(async_extent->pages);
647 async_extent->nr_pages = 0;
648 async_extent->pages = NULL;
649 unlock_extent(io_tree, async_extent->start,
650 async_extent->start +
651 async_extent->ram_size - 1, GFP_NOFS);
652 goto retry;
653 }
654
c2167754
YZ
655 /*
656 * here we're doing allocation and writeback of the
657 * compressed pages
658 */
659 btrfs_drop_extent_cache(inode, async_extent->start,
660 async_extent->start +
661 async_extent->ram_size - 1, 0);
662
172ddd60 663 em = alloc_extent_map();
c26a9203 664 BUG_ON(!em);
771ed689
CM
665 em->start = async_extent->start;
666 em->len = async_extent->ram_size;
445a6944 667 em->orig_start = em->start;
c8b97818 668
771ed689
CM
669 em->block_start = ins.objectid;
670 em->block_len = ins.offset;
671 em->bdev = root->fs_info->fs_devices->latest_bdev;
261507a0 672 em->compress_type = async_extent->compress_type;
771ed689
CM
673 set_bit(EXTENT_FLAG_PINNED, &em->flags);
674 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
675
d397712b 676 while (1) {
890871be 677 write_lock(&em_tree->lock);
771ed689 678 ret = add_extent_mapping(em_tree, em);
890871be 679 write_unlock(&em_tree->lock);
771ed689
CM
680 if (ret != -EEXIST) {
681 free_extent_map(em);
682 break;
683 }
684 btrfs_drop_extent_cache(inode, async_extent->start,
685 async_extent->start +
686 async_extent->ram_size - 1, 0);
687 }
688
261507a0
LZ
689 ret = btrfs_add_ordered_extent_compress(inode,
690 async_extent->start,
691 ins.objectid,
692 async_extent->ram_size,
693 ins.offset,
694 BTRFS_ORDERED_COMPRESSED,
695 async_extent->compress_type);
771ed689
CM
696 BUG_ON(ret);
697
771ed689
CM
698 /*
699 * clear dirty, set writeback and unlock the pages.
700 */
701 extent_clear_unlock_delalloc(inode,
a791e35e
CM
702 &BTRFS_I(inode)->io_tree,
703 async_extent->start,
704 async_extent->start +
705 async_extent->ram_size - 1,
706 NULL, EXTENT_CLEAR_UNLOCK_PAGE |
707 EXTENT_CLEAR_UNLOCK |
a3429ab7 708 EXTENT_CLEAR_DELALLOC |
a791e35e 709 EXTENT_CLEAR_DIRTY | EXTENT_SET_WRITEBACK);
771ed689
CM
710
711 ret = btrfs_submit_compressed_write(inode,
d397712b
CM
712 async_extent->start,
713 async_extent->ram_size,
714 ins.objectid,
715 ins.offset, async_extent->pages,
716 async_extent->nr_pages);
771ed689
CM
717
718 BUG_ON(ret);
771ed689
CM
719 alloc_hint = ins.objectid + ins.offset;
720 kfree(async_extent);
721 cond_resched();
722 }
723
771ed689
CM
724 return 0;
725}
726
4b46fce2
JB
727static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
728 u64 num_bytes)
729{
730 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
731 struct extent_map *em;
732 u64 alloc_hint = 0;
733
734 read_lock(&em_tree->lock);
735 em = search_extent_mapping(em_tree, start, num_bytes);
736 if (em) {
737 /*
738 * if block start isn't an actual block number then find the
739 * first block in this inode and use that as a hint. If that
740 * block is also bogus then just don't worry about it.
741 */
742 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
743 free_extent_map(em);
744 em = search_extent_mapping(em_tree, 0, 0);
745 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
746 alloc_hint = em->block_start;
747 if (em)
748 free_extent_map(em);
749 } else {
750 alloc_hint = em->block_start;
751 free_extent_map(em);
752 }
753 }
754 read_unlock(&em_tree->lock);
755
756 return alloc_hint;
757}
758
771ed689
CM
759/*
760 * when extent_io.c finds a delayed allocation range in the file,
761 * the call backs end up in this code. The basic idea is to
762 * allocate extents on disk for the range, and create ordered data structs
763 * in ram to track those extents.
764 *
765 * locked_page is the page that writepage had locked already. We use
766 * it to make sure we don't do extra locks or unlocks.
767 *
768 * *page_started is set to one if we unlock locked_page and do everything
769 * required to start IO on it. It may be clean and already done with
770 * IO when we return.
771 */
772static noinline int cow_file_range(struct inode *inode,
773 struct page *locked_page,
774 u64 start, u64 end, int *page_started,
775 unsigned long *nr_written,
776 int unlock)
777{
778 struct btrfs_root *root = BTRFS_I(inode)->root;
779 struct btrfs_trans_handle *trans;
780 u64 alloc_hint = 0;
781 u64 num_bytes;
782 unsigned long ram_size;
783 u64 disk_num_bytes;
784 u64 cur_alloc_size;
785 u64 blocksize = root->sectorsize;
771ed689
CM
786 struct btrfs_key ins;
787 struct extent_map *em;
788 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
789 int ret = 0;
790
2cf8572d 791 BUG_ON(btrfs_is_free_space_inode(root, inode));
7a7eaa40 792 trans = btrfs_join_transaction(root);
3612b495 793 BUG_ON(IS_ERR(trans));
0ca1f7ce 794 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
771ed689 795
771ed689
CM
796 num_bytes = (end - start + blocksize) & ~(blocksize - 1);
797 num_bytes = max(blocksize, num_bytes);
798 disk_num_bytes = num_bytes;
799 ret = 0;
800
4cb5300b
CM
801 /* if this is a small write inside eof, kick off defrag */
802 if (end <= BTRFS_I(inode)->disk_i_size && num_bytes < 64 * 1024)
803 btrfs_add_inode_defrag(trans, inode);
804
771ed689
CM
805 if (start == 0) {
806 /* lets try to make an inline extent */
807 ret = cow_file_range_inline(trans, root, inode,
fe3f566c 808 start, end, 0, 0, NULL);
771ed689
CM
809 if (ret == 0) {
810 extent_clear_unlock_delalloc(inode,
a791e35e
CM
811 &BTRFS_I(inode)->io_tree,
812 start, end, NULL,
813 EXTENT_CLEAR_UNLOCK_PAGE |
814 EXTENT_CLEAR_UNLOCK |
815 EXTENT_CLEAR_DELALLOC |
816 EXTENT_CLEAR_DIRTY |
817 EXTENT_SET_WRITEBACK |
818 EXTENT_END_WRITEBACK);
c2167754 819
771ed689
CM
820 *nr_written = *nr_written +
821 (end - start + PAGE_CACHE_SIZE) / PAGE_CACHE_SIZE;
822 *page_started = 1;
823 ret = 0;
824 goto out;
825 }
826 }
827
828 BUG_ON(disk_num_bytes >
6c41761f 829 btrfs_super_total_bytes(root->fs_info->super_copy));
771ed689 830
4b46fce2 831 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
771ed689
CM
832 btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
833
d397712b 834 while (disk_num_bytes > 0) {
a791e35e
CM
835 unsigned long op;
836
287a0ab9 837 cur_alloc_size = disk_num_bytes;
e6dcd2dc 838 ret = btrfs_reserve_extent(trans, root, cur_alloc_size,
771ed689 839 root->sectorsize, 0, alloc_hint,
e6dcd2dc 840 (u64)-1, &ins, 1);
d397712b
CM
841 BUG_ON(ret);
842
172ddd60 843 em = alloc_extent_map();
c26a9203 844 BUG_ON(!em);
e6dcd2dc 845 em->start = start;
445a6944 846 em->orig_start = em->start;
771ed689
CM
847 ram_size = ins.offset;
848 em->len = ins.offset;
c8b97818 849
e6dcd2dc 850 em->block_start = ins.objectid;
c8b97818 851 em->block_len = ins.offset;
e6dcd2dc 852 em->bdev = root->fs_info->fs_devices->latest_bdev;
7f3c74fb 853 set_bit(EXTENT_FLAG_PINNED, &em->flags);
c8b97818 854
d397712b 855 while (1) {
890871be 856 write_lock(&em_tree->lock);
e6dcd2dc 857 ret = add_extent_mapping(em_tree, em);
890871be 858 write_unlock(&em_tree->lock);
e6dcd2dc
CM
859 if (ret != -EEXIST) {
860 free_extent_map(em);
861 break;
862 }
863 btrfs_drop_extent_cache(inode, start,
c8b97818 864 start + ram_size - 1, 0);
e6dcd2dc
CM
865 }
866
98d20f67 867 cur_alloc_size = ins.offset;
e6dcd2dc 868 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
771ed689 869 ram_size, cur_alloc_size, 0);
e6dcd2dc 870 BUG_ON(ret);
c8b97818 871
17d217fe
YZ
872 if (root->root_key.objectid ==
873 BTRFS_DATA_RELOC_TREE_OBJECTID) {
874 ret = btrfs_reloc_clone_csums(inode, start,
875 cur_alloc_size);
876 BUG_ON(ret);
877 }
878
d397712b 879 if (disk_num_bytes < cur_alloc_size)
3b951516 880 break;
d397712b 881
c8b97818
CM
882 /* we're not doing compressed IO, don't unlock the first
883 * page (which the caller expects to stay locked), don't
884 * clear any dirty bits and don't set any writeback bits
8b62b72b
CM
885 *
886 * Do set the Private2 bit so we know this page was properly
887 * setup for writepage
c8b97818 888 */
a791e35e
CM
889 op = unlock ? EXTENT_CLEAR_UNLOCK_PAGE : 0;
890 op |= EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
891 EXTENT_SET_PRIVATE2;
892
c8b97818
CM
893 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
894 start, start + ram_size - 1,
a791e35e 895 locked_page, op);
c8b97818 896 disk_num_bytes -= cur_alloc_size;
c59f8951
CM
897 num_bytes -= cur_alloc_size;
898 alloc_hint = ins.objectid + ins.offset;
899 start += cur_alloc_size;
b888db2b 900 }
b888db2b 901out:
771ed689 902 ret = 0;
b888db2b 903 btrfs_end_transaction(trans, root);
c8b97818 904
be20aa9d 905 return ret;
771ed689 906}
c8b97818 907
771ed689
CM
908/*
909 * work queue call back to started compression on a file and pages
910 */
911static noinline void async_cow_start(struct btrfs_work *work)
912{
913 struct async_cow *async_cow;
914 int num_added = 0;
915 async_cow = container_of(work, struct async_cow, work);
916
917 compress_file_range(async_cow->inode, async_cow->locked_page,
918 async_cow->start, async_cow->end, async_cow,
919 &num_added);
920 if (num_added == 0)
921 async_cow->inode = NULL;
922}
923
924/*
925 * work queue call back to submit previously compressed pages
926 */
927static noinline void async_cow_submit(struct btrfs_work *work)
928{
929 struct async_cow *async_cow;
930 struct btrfs_root *root;
931 unsigned long nr_pages;
932
933 async_cow = container_of(work, struct async_cow, work);
934
935 root = async_cow->root;
936 nr_pages = (async_cow->end - async_cow->start + PAGE_CACHE_SIZE) >>
937 PAGE_CACHE_SHIFT;
938
939 atomic_sub(nr_pages, &root->fs_info->async_delalloc_pages);
940
941 if (atomic_read(&root->fs_info->async_delalloc_pages) <
942 5 * 1042 * 1024 &&
943 waitqueue_active(&root->fs_info->async_submit_wait))
944 wake_up(&root->fs_info->async_submit_wait);
945
d397712b 946 if (async_cow->inode)
771ed689 947 submit_compressed_extents(async_cow->inode, async_cow);
771ed689 948}
c8b97818 949
771ed689
CM
950static noinline void async_cow_free(struct btrfs_work *work)
951{
952 struct async_cow *async_cow;
953 async_cow = container_of(work, struct async_cow, work);
954 kfree(async_cow);
955}
956
957static int cow_file_range_async(struct inode *inode, struct page *locked_page,
958 u64 start, u64 end, int *page_started,
959 unsigned long *nr_written)
960{
961 struct async_cow *async_cow;
962 struct btrfs_root *root = BTRFS_I(inode)->root;
963 unsigned long nr_pages;
964 u64 cur_end;
965 int limit = 10 * 1024 * 1042;
966
a3429ab7
CM
967 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
968 1, 0, NULL, GFP_NOFS);
d397712b 969 while (start < end) {
771ed689 970 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
8d413713 971 BUG_ON(!async_cow);
771ed689
CM
972 async_cow->inode = inode;
973 async_cow->root = root;
974 async_cow->locked_page = locked_page;
975 async_cow->start = start;
976
6cbff00f 977 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
771ed689
CM
978 cur_end = end;
979 else
980 cur_end = min(end, start + 512 * 1024 - 1);
981
982 async_cow->end = cur_end;
983 INIT_LIST_HEAD(&async_cow->extents);
984
985 async_cow->work.func = async_cow_start;
986 async_cow->work.ordered_func = async_cow_submit;
987 async_cow->work.ordered_free = async_cow_free;
988 async_cow->work.flags = 0;
989
771ed689
CM
990 nr_pages = (cur_end - start + PAGE_CACHE_SIZE) >>
991 PAGE_CACHE_SHIFT;
992 atomic_add(nr_pages, &root->fs_info->async_delalloc_pages);
993
994 btrfs_queue_worker(&root->fs_info->delalloc_workers,
995 &async_cow->work);
996
997 if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) {
998 wait_event(root->fs_info->async_submit_wait,
999 (atomic_read(&root->fs_info->async_delalloc_pages) <
1000 limit));
1001 }
1002
d397712b 1003 while (atomic_read(&root->fs_info->async_submit_draining) &&
771ed689
CM
1004 atomic_read(&root->fs_info->async_delalloc_pages)) {
1005 wait_event(root->fs_info->async_submit_wait,
1006 (atomic_read(&root->fs_info->async_delalloc_pages) ==
1007 0));
1008 }
1009
1010 *nr_written += nr_pages;
1011 start = cur_end + 1;
1012 }
1013 *page_started = 1;
1014 return 0;
be20aa9d
CM
1015}
1016
d397712b 1017static noinline int csum_exist_in_range(struct btrfs_root *root,
17d217fe
YZ
1018 u64 bytenr, u64 num_bytes)
1019{
1020 int ret;
1021 struct btrfs_ordered_sum *sums;
1022 LIST_HEAD(list);
1023
07d400a6 1024 ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr,
a2de733c 1025 bytenr + num_bytes - 1, &list, 0);
17d217fe
YZ
1026 if (ret == 0 && list_empty(&list))
1027 return 0;
1028
1029 while (!list_empty(&list)) {
1030 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1031 list_del(&sums->list);
1032 kfree(sums);
1033 }
1034 return 1;
1035}
1036
d352ac68
CM
1037/*
1038 * when nowcow writeback call back. This checks for snapshots or COW copies
1039 * of the extents that exist in the file, and COWs the file as required.
1040 *
1041 * If no cow copies or snapshots exist, we write directly to the existing
1042 * blocks on disk
1043 */
7f366cfe
CM
1044static noinline int run_delalloc_nocow(struct inode *inode,
1045 struct page *locked_page,
771ed689
CM
1046 u64 start, u64 end, int *page_started, int force,
1047 unsigned long *nr_written)
be20aa9d 1048{
be20aa9d 1049 struct btrfs_root *root = BTRFS_I(inode)->root;
7ea394f1 1050 struct btrfs_trans_handle *trans;
be20aa9d 1051 struct extent_buffer *leaf;
be20aa9d 1052 struct btrfs_path *path;
80ff3856 1053 struct btrfs_file_extent_item *fi;
be20aa9d 1054 struct btrfs_key found_key;
80ff3856
YZ
1055 u64 cow_start;
1056 u64 cur_offset;
1057 u64 extent_end;
5d4f98a2 1058 u64 extent_offset;
80ff3856
YZ
1059 u64 disk_bytenr;
1060 u64 num_bytes;
1061 int extent_type;
1062 int ret;
d899e052 1063 int type;
80ff3856
YZ
1064 int nocow;
1065 int check_prev = 1;
82d5902d 1066 bool nolock;
33345d01 1067 u64 ino = btrfs_ino(inode);
be20aa9d
CM
1068
1069 path = btrfs_alloc_path();
d8926bb3
MF
1070 if (!path)
1071 return -ENOMEM;
82d5902d 1072
2cf8572d 1073 nolock = btrfs_is_free_space_inode(root, inode);
82d5902d
LZ
1074
1075 if (nolock)
7a7eaa40 1076 trans = btrfs_join_transaction_nolock(root);
82d5902d 1077 else
7a7eaa40 1078 trans = btrfs_join_transaction(root);
ff5714cc 1079
3612b495 1080 BUG_ON(IS_ERR(trans));
74b21075 1081 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
be20aa9d 1082
80ff3856
YZ
1083 cow_start = (u64)-1;
1084 cur_offset = start;
1085 while (1) {
33345d01 1086 ret = btrfs_lookup_file_extent(trans, root, path, ino,
80ff3856
YZ
1087 cur_offset, 0);
1088 BUG_ON(ret < 0);
1089 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1090 leaf = path->nodes[0];
1091 btrfs_item_key_to_cpu(leaf, &found_key,
1092 path->slots[0] - 1);
33345d01 1093 if (found_key.objectid == ino &&
80ff3856
YZ
1094 found_key.type == BTRFS_EXTENT_DATA_KEY)
1095 path->slots[0]--;
1096 }
1097 check_prev = 0;
1098next_slot:
1099 leaf = path->nodes[0];
1100 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1101 ret = btrfs_next_leaf(root, path);
1102 if (ret < 0)
1103 BUG_ON(1);
1104 if (ret > 0)
1105 break;
1106 leaf = path->nodes[0];
1107 }
be20aa9d 1108
80ff3856
YZ
1109 nocow = 0;
1110 disk_bytenr = 0;
17d217fe 1111 num_bytes = 0;
80ff3856
YZ
1112 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1113
33345d01 1114 if (found_key.objectid > ino ||
80ff3856
YZ
1115 found_key.type > BTRFS_EXTENT_DATA_KEY ||
1116 found_key.offset > end)
1117 break;
1118
1119 if (found_key.offset > cur_offset) {
1120 extent_end = found_key.offset;
e9061e21 1121 extent_type = 0;
80ff3856
YZ
1122 goto out_check;
1123 }
1124
1125 fi = btrfs_item_ptr(leaf, path->slots[0],
1126 struct btrfs_file_extent_item);
1127 extent_type = btrfs_file_extent_type(leaf, fi);
1128
d899e052
YZ
1129 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1130 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
80ff3856 1131 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
5d4f98a2 1132 extent_offset = btrfs_file_extent_offset(leaf, fi);
80ff3856
YZ
1133 extent_end = found_key.offset +
1134 btrfs_file_extent_num_bytes(leaf, fi);
1135 if (extent_end <= start) {
1136 path->slots[0]++;
1137 goto next_slot;
1138 }
17d217fe
YZ
1139 if (disk_bytenr == 0)
1140 goto out_check;
80ff3856
YZ
1141 if (btrfs_file_extent_compression(leaf, fi) ||
1142 btrfs_file_extent_encryption(leaf, fi) ||
1143 btrfs_file_extent_other_encoding(leaf, fi))
1144 goto out_check;
d899e052
YZ
1145 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1146 goto out_check;
d2fb3437 1147 if (btrfs_extent_readonly(root, disk_bytenr))
80ff3856 1148 goto out_check;
33345d01 1149 if (btrfs_cross_ref_exist(trans, root, ino,
5d4f98a2
YZ
1150 found_key.offset -
1151 extent_offset, disk_bytenr))
17d217fe 1152 goto out_check;
5d4f98a2 1153 disk_bytenr += extent_offset;
17d217fe
YZ
1154 disk_bytenr += cur_offset - found_key.offset;
1155 num_bytes = min(end + 1, extent_end) - cur_offset;
1156 /*
1157 * force cow if csum exists in the range.
1158 * this ensure that csum for a given extent are
1159 * either valid or do not exist.
1160 */
1161 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
1162 goto out_check;
80ff3856
YZ
1163 nocow = 1;
1164 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1165 extent_end = found_key.offset +
1166 btrfs_file_extent_inline_len(leaf, fi);
1167 extent_end = ALIGN(extent_end, root->sectorsize);
1168 } else {
1169 BUG_ON(1);
1170 }
1171out_check:
1172 if (extent_end <= start) {
1173 path->slots[0]++;
1174 goto next_slot;
1175 }
1176 if (!nocow) {
1177 if (cow_start == (u64)-1)
1178 cow_start = cur_offset;
1179 cur_offset = extent_end;
1180 if (cur_offset > end)
1181 break;
1182 path->slots[0]++;
1183 goto next_slot;
7ea394f1
YZ
1184 }
1185
b3b4aa74 1186 btrfs_release_path(path);
80ff3856
YZ
1187 if (cow_start != (u64)-1) {
1188 ret = cow_file_range(inode, locked_page, cow_start,
771ed689
CM
1189 found_key.offset - 1, page_started,
1190 nr_written, 1);
80ff3856
YZ
1191 BUG_ON(ret);
1192 cow_start = (u64)-1;
7ea394f1 1193 }
80ff3856 1194
d899e052
YZ
1195 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1196 struct extent_map *em;
1197 struct extent_map_tree *em_tree;
1198 em_tree = &BTRFS_I(inode)->extent_tree;
172ddd60 1199 em = alloc_extent_map();
c26a9203 1200 BUG_ON(!em);
d899e052 1201 em->start = cur_offset;
445a6944 1202 em->orig_start = em->start;
d899e052
YZ
1203 em->len = num_bytes;
1204 em->block_len = num_bytes;
1205 em->block_start = disk_bytenr;
1206 em->bdev = root->fs_info->fs_devices->latest_bdev;
1207 set_bit(EXTENT_FLAG_PINNED, &em->flags);
1208 while (1) {
890871be 1209 write_lock(&em_tree->lock);
d899e052 1210 ret = add_extent_mapping(em_tree, em);
890871be 1211 write_unlock(&em_tree->lock);
d899e052
YZ
1212 if (ret != -EEXIST) {
1213 free_extent_map(em);
1214 break;
1215 }
1216 btrfs_drop_extent_cache(inode, em->start,
1217 em->start + em->len - 1, 0);
1218 }
1219 type = BTRFS_ORDERED_PREALLOC;
1220 } else {
1221 type = BTRFS_ORDERED_NOCOW;
1222 }
80ff3856
YZ
1223
1224 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
d899e052
YZ
1225 num_bytes, num_bytes, type);
1226 BUG_ON(ret);
771ed689 1227
efa56464
YZ
1228 if (root->root_key.objectid ==
1229 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1230 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1231 num_bytes);
1232 BUG_ON(ret);
1233 }
1234
d899e052 1235 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
a791e35e
CM
1236 cur_offset, cur_offset + num_bytes - 1,
1237 locked_page, EXTENT_CLEAR_UNLOCK_PAGE |
1238 EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
1239 EXTENT_SET_PRIVATE2);
80ff3856
YZ
1240 cur_offset = extent_end;
1241 if (cur_offset > end)
1242 break;
be20aa9d 1243 }
b3b4aa74 1244 btrfs_release_path(path);
80ff3856
YZ
1245
1246 if (cur_offset <= end && cow_start == (u64)-1)
1247 cow_start = cur_offset;
1248 if (cow_start != (u64)-1) {
1249 ret = cow_file_range(inode, locked_page, cow_start, end,
771ed689 1250 page_started, nr_written, 1);
80ff3856
YZ
1251 BUG_ON(ret);
1252 }
1253
0cb59c99
JB
1254 if (nolock) {
1255 ret = btrfs_end_transaction_nolock(trans, root);
1256 BUG_ON(ret);
1257 } else {
1258 ret = btrfs_end_transaction(trans, root);
1259 BUG_ON(ret);
1260 }
7ea394f1 1261 btrfs_free_path(path);
80ff3856 1262 return 0;
be20aa9d
CM
1263}
1264
d352ac68
CM
1265/*
1266 * extent_io.c call back to do delayed allocation processing
1267 */
c8b97818 1268static int run_delalloc_range(struct inode *inode, struct page *locked_page,
771ed689
CM
1269 u64 start, u64 end, int *page_started,
1270 unsigned long *nr_written)
be20aa9d 1271{
be20aa9d 1272 int ret;
7f366cfe 1273 struct btrfs_root *root = BTRFS_I(inode)->root;
a2135011 1274
6cbff00f 1275 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)
c8b97818 1276 ret = run_delalloc_nocow(inode, locked_page, start, end,
d397712b 1277 page_started, 1, nr_written);
6cbff00f 1278 else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC)
d899e052 1279 ret = run_delalloc_nocow(inode, locked_page, start, end,
d397712b 1280 page_started, 0, nr_written);
1e701a32 1281 else if (!btrfs_test_opt(root, COMPRESS) &&
75e7cb7f
LB
1282 !(BTRFS_I(inode)->force_compress) &&
1283 !(BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS))
7f366cfe
CM
1284 ret = cow_file_range(inode, locked_page, start, end,
1285 page_started, nr_written, 1);
be20aa9d 1286 else
771ed689 1287 ret = cow_file_range_async(inode, locked_page, start, end,
d397712b 1288 page_started, nr_written);
b888db2b
CM
1289 return ret;
1290}
1291
1bf85046
JM
1292static void btrfs_split_extent_hook(struct inode *inode,
1293 struct extent_state *orig, u64 split)
9ed74f2d 1294{
0ca1f7ce 1295 /* not delalloc, ignore it */
9ed74f2d 1296 if (!(orig->state & EXTENT_DELALLOC))
1bf85046 1297 return;
9ed74f2d 1298
9e0baf60
JB
1299 spin_lock(&BTRFS_I(inode)->lock);
1300 BTRFS_I(inode)->outstanding_extents++;
1301 spin_unlock(&BTRFS_I(inode)->lock);
9ed74f2d
JB
1302}
1303
1304/*
1305 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1306 * extents so we can keep track of new extents that are just merged onto old
1307 * extents, such as when we are doing sequential writes, so we can properly
1308 * account for the metadata space we'll need.
1309 */
1bf85046
JM
1310static void btrfs_merge_extent_hook(struct inode *inode,
1311 struct extent_state *new,
1312 struct extent_state *other)
9ed74f2d 1313{
9ed74f2d
JB
1314 /* not delalloc, ignore it */
1315 if (!(other->state & EXTENT_DELALLOC))
1bf85046 1316 return;
9ed74f2d 1317
9e0baf60
JB
1318 spin_lock(&BTRFS_I(inode)->lock);
1319 BTRFS_I(inode)->outstanding_extents--;
1320 spin_unlock(&BTRFS_I(inode)->lock);
9ed74f2d
JB
1321}
1322
d352ac68
CM
1323/*
1324 * extent_io.c set_bit_hook, used to track delayed allocation
1325 * bytes in this file, and to maintain the list of inodes that
1326 * have pending delalloc work to be done.
1327 */
1bf85046
JM
1328static void btrfs_set_bit_hook(struct inode *inode,
1329 struct extent_state *state, int *bits)
291d673e 1330{
9ed74f2d 1331
75eff68e
CM
1332 /*
1333 * set_bit and clear bit hooks normally require _irqsave/restore
27160b6b 1334 * but in this case, we are only testing for the DELALLOC
75eff68e
CM
1335 * bit, which is only set or cleared with irqs on
1336 */
0ca1f7ce 1337 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
291d673e 1338 struct btrfs_root *root = BTRFS_I(inode)->root;
0ca1f7ce 1339 u64 len = state->end + 1 - state->start;
2cf8572d 1340 bool do_list = !btrfs_is_free_space_inode(root, inode);
9ed74f2d 1341
9e0baf60 1342 if (*bits & EXTENT_FIRST_DELALLOC) {
0ca1f7ce 1343 *bits &= ~EXTENT_FIRST_DELALLOC;
9e0baf60
JB
1344 } else {
1345 spin_lock(&BTRFS_I(inode)->lock);
1346 BTRFS_I(inode)->outstanding_extents++;
1347 spin_unlock(&BTRFS_I(inode)->lock);
1348 }
287a0ab9 1349
75eff68e 1350 spin_lock(&root->fs_info->delalloc_lock);
0ca1f7ce
YZ
1351 BTRFS_I(inode)->delalloc_bytes += len;
1352 root->fs_info->delalloc_bytes += len;
0cb59c99 1353 if (do_list && list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
ea8c2819
CM
1354 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1355 &root->fs_info->delalloc_inodes);
1356 }
75eff68e 1357 spin_unlock(&root->fs_info->delalloc_lock);
291d673e 1358 }
291d673e
CM
1359}
1360
d352ac68
CM
1361/*
1362 * extent_io.c clear_bit_hook, see set_bit_hook for why
1363 */
1bf85046
JM
1364static void btrfs_clear_bit_hook(struct inode *inode,
1365 struct extent_state *state, int *bits)
291d673e 1366{
75eff68e
CM
1367 /*
1368 * set_bit and clear bit hooks normally require _irqsave/restore
27160b6b 1369 * but in this case, we are only testing for the DELALLOC
75eff68e
CM
1370 * bit, which is only set or cleared with irqs on
1371 */
0ca1f7ce 1372 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
291d673e 1373 struct btrfs_root *root = BTRFS_I(inode)->root;
0ca1f7ce 1374 u64 len = state->end + 1 - state->start;
2cf8572d 1375 bool do_list = !btrfs_is_free_space_inode(root, inode);
bcbfce8a 1376
9e0baf60 1377 if (*bits & EXTENT_FIRST_DELALLOC) {
0ca1f7ce 1378 *bits &= ~EXTENT_FIRST_DELALLOC;
9e0baf60
JB
1379 } else if (!(*bits & EXTENT_DO_ACCOUNTING)) {
1380 spin_lock(&BTRFS_I(inode)->lock);
1381 BTRFS_I(inode)->outstanding_extents--;
1382 spin_unlock(&BTRFS_I(inode)->lock);
1383 }
0ca1f7ce
YZ
1384
1385 if (*bits & EXTENT_DO_ACCOUNTING)
1386 btrfs_delalloc_release_metadata(inode, len);
1387
0cb59c99
JB
1388 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
1389 && do_list)
0ca1f7ce 1390 btrfs_free_reserved_data_space(inode, len);
9ed74f2d 1391
75eff68e 1392 spin_lock(&root->fs_info->delalloc_lock);
0ca1f7ce
YZ
1393 root->fs_info->delalloc_bytes -= len;
1394 BTRFS_I(inode)->delalloc_bytes -= len;
1395
0cb59c99 1396 if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 &&
ea8c2819
CM
1397 !list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1398 list_del_init(&BTRFS_I(inode)->delalloc_inodes);
1399 }
75eff68e 1400 spin_unlock(&root->fs_info->delalloc_lock);
291d673e 1401 }
291d673e
CM
1402}
1403
d352ac68
CM
1404/*
1405 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1406 * we don't create bios that span stripes or chunks
1407 */
239b14b3 1408int btrfs_merge_bio_hook(struct page *page, unsigned long offset,
c8b97818
CM
1409 size_t size, struct bio *bio,
1410 unsigned long bio_flags)
239b14b3
CM
1411{
1412 struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
1413 struct btrfs_mapping_tree *map_tree;
a62b9401 1414 u64 logical = (u64)bio->bi_sector << 9;
239b14b3
CM
1415 u64 length = 0;
1416 u64 map_length;
239b14b3
CM
1417 int ret;
1418
771ed689
CM
1419 if (bio_flags & EXTENT_BIO_COMPRESSED)
1420 return 0;
1421
f2d8d74d 1422 length = bio->bi_size;
239b14b3
CM
1423 map_tree = &root->fs_info->mapping_tree;
1424 map_length = length;
cea9e445 1425 ret = btrfs_map_block(map_tree, READ, logical,
f188591e 1426 &map_length, NULL, 0);
cea9e445 1427
d397712b 1428 if (map_length < length + size)
239b14b3 1429 return 1;
411fc6bc 1430 return ret;
239b14b3
CM
1431}
1432
d352ac68
CM
1433/*
1434 * in order to insert checksums into the metadata in large chunks,
1435 * we wait until bio submission time. All the pages in the bio are
1436 * checksummed and sums are attached onto the ordered extent record.
1437 *
1438 * At IO completion time the cums attached on the ordered extent record
1439 * are inserted into the btree
1440 */
d397712b
CM
1441static int __btrfs_submit_bio_start(struct inode *inode, int rw,
1442 struct bio *bio, int mirror_num,
eaf25d93
CM
1443 unsigned long bio_flags,
1444 u64 bio_offset)
065631f6 1445{
065631f6 1446 struct btrfs_root *root = BTRFS_I(inode)->root;
065631f6 1447 int ret = 0;
e015640f 1448
d20f7043 1449 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
44b8bd7e 1450 BUG_ON(ret);
4a69a410
CM
1451 return 0;
1452}
e015640f 1453
4a69a410
CM
1454/*
1455 * in order to insert checksums into the metadata in large chunks,
1456 * we wait until bio submission time. All the pages in the bio are
1457 * checksummed and sums are attached onto the ordered extent record.
1458 *
1459 * At IO completion time the cums attached on the ordered extent record
1460 * are inserted into the btree
1461 */
b2950863 1462static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
eaf25d93
CM
1463 int mirror_num, unsigned long bio_flags,
1464 u64 bio_offset)
4a69a410
CM
1465{
1466 struct btrfs_root *root = BTRFS_I(inode)->root;
8b712842 1467 return btrfs_map_bio(root, rw, bio, mirror_num, 1);
44b8bd7e
CM
1468}
1469
d352ac68 1470/*
cad321ad
CM
1471 * extent_io.c submission hook. This does the right thing for csum calculation
1472 * on write, or reading the csums from the tree before a read
d352ac68 1473 */
b2950863 1474static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
eaf25d93
CM
1475 int mirror_num, unsigned long bio_flags,
1476 u64 bio_offset)
44b8bd7e
CM
1477{
1478 struct btrfs_root *root = BTRFS_I(inode)->root;
1479 int ret = 0;
19b9bdb0 1480 int skip_sum;
44b8bd7e 1481
6cbff00f 1482 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
cad321ad 1483
2cf8572d 1484 if (btrfs_is_free_space_inode(root, inode))
0cb59c99
JB
1485 ret = btrfs_bio_wq_end_io(root->fs_info, bio, 2);
1486 else
1487 ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
e6dcd2dc 1488 BUG_ON(ret);
065631f6 1489
7b6d91da 1490 if (!(rw & REQ_WRITE)) {
d20f7043 1491 if (bio_flags & EXTENT_BIO_COMPRESSED) {
c8b97818
CM
1492 return btrfs_submit_compressed_read(inode, bio,
1493 mirror_num, bio_flags);
c2db1073
TI
1494 } else if (!skip_sum) {
1495 ret = btrfs_lookup_bio_sums(root, inode, bio, NULL);
1496 if (ret)
1497 return ret;
1498 }
4d1b5fb4 1499 goto mapit;
19b9bdb0 1500 } else if (!skip_sum) {
17d217fe
YZ
1501 /* csum items have already been cloned */
1502 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1503 goto mapit;
19b9bdb0
CM
1504 /* we're doing a write, do the async checksumming */
1505 return btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
44b8bd7e 1506 inode, rw, bio, mirror_num,
eaf25d93
CM
1507 bio_flags, bio_offset,
1508 __btrfs_submit_bio_start,
4a69a410 1509 __btrfs_submit_bio_done);
19b9bdb0
CM
1510 }
1511
0b86a832 1512mapit:
8b712842 1513 return btrfs_map_bio(root, rw, bio, mirror_num, 0);
065631f6 1514}
6885f308 1515
d352ac68
CM
1516/*
1517 * given a list of ordered sums record them in the inode. This happens
1518 * at IO completion time based on sums calculated at bio submission time.
1519 */
ba1da2f4 1520static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
e6dcd2dc
CM
1521 struct inode *inode, u64 file_offset,
1522 struct list_head *list)
1523{
e6dcd2dc
CM
1524 struct btrfs_ordered_sum *sum;
1525
c6e30871 1526 list_for_each_entry(sum, list, list) {
d20f7043
CM
1527 btrfs_csum_file_blocks(trans,
1528 BTRFS_I(inode)->root->fs_info->csum_root, sum);
e6dcd2dc
CM
1529 }
1530 return 0;
1531}
1532
2ac55d41
JB
1533int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
1534 struct extent_state **cached_state)
ea8c2819 1535{
d397712b 1536 if ((end & (PAGE_CACHE_SIZE - 1)) == 0)
771ed689 1537 WARN_ON(1);
ea8c2819 1538 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
2ac55d41 1539 cached_state, GFP_NOFS);
ea8c2819
CM
1540}
1541
d352ac68 1542/* see btrfs_writepage_start_hook for details on why this is required */
247e743c
CM
1543struct btrfs_writepage_fixup {
1544 struct page *page;
1545 struct btrfs_work work;
1546};
1547
b2950863 1548static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
247e743c
CM
1549{
1550 struct btrfs_writepage_fixup *fixup;
1551 struct btrfs_ordered_extent *ordered;
2ac55d41 1552 struct extent_state *cached_state = NULL;
247e743c
CM
1553 struct page *page;
1554 struct inode *inode;
1555 u64 page_start;
1556 u64 page_end;
1557
1558 fixup = container_of(work, struct btrfs_writepage_fixup, work);
1559 page = fixup->page;
4a096752 1560again:
247e743c
CM
1561 lock_page(page);
1562 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
1563 ClearPageChecked(page);
1564 goto out_page;
1565 }
1566
1567 inode = page->mapping->host;
1568 page_start = page_offset(page);
1569 page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
1570
2ac55d41
JB
1571 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end, 0,
1572 &cached_state, GFP_NOFS);
4a096752
CM
1573
1574 /* already ordered? We're done */
8b62b72b 1575 if (PagePrivate2(page))
247e743c 1576 goto out;
4a096752
CM
1577
1578 ordered = btrfs_lookup_ordered_extent(inode, page_start);
1579 if (ordered) {
2ac55d41
JB
1580 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
1581 page_end, &cached_state, GFP_NOFS);
4a096752
CM
1582 unlock_page(page);
1583 btrfs_start_ordered_extent(inode, ordered, 1);
1584 goto again;
1585 }
247e743c 1586
0ca1f7ce 1587 BUG();
2ac55d41 1588 btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state);
247e743c
CM
1589 ClearPageChecked(page);
1590out:
2ac55d41
JB
1591 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
1592 &cached_state, GFP_NOFS);
247e743c
CM
1593out_page:
1594 unlock_page(page);
1595 page_cache_release(page);
b897abec 1596 kfree(fixup);
247e743c
CM
1597}
1598
1599/*
1600 * There are a few paths in the higher layers of the kernel that directly
1601 * set the page dirty bit without asking the filesystem if it is a
1602 * good idea. This causes problems because we want to make sure COW
1603 * properly happens and the data=ordered rules are followed.
1604 *
c8b97818 1605 * In our case any range that doesn't have the ORDERED bit set
247e743c
CM
1606 * hasn't been properly setup for IO. We kick off an async process
1607 * to fix it up. The async helper will wait for ordered extents, set
1608 * the delalloc bit and make it safe to write the page.
1609 */
b2950863 1610static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
247e743c
CM
1611{
1612 struct inode *inode = page->mapping->host;
1613 struct btrfs_writepage_fixup *fixup;
1614 struct btrfs_root *root = BTRFS_I(inode)->root;
247e743c 1615
8b62b72b
CM
1616 /* this page is properly in the ordered list */
1617 if (TestClearPagePrivate2(page))
247e743c
CM
1618 return 0;
1619
1620 if (PageChecked(page))
1621 return -EAGAIN;
1622
1623 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
1624 if (!fixup)
1625 return -EAGAIN;
f421950f 1626
247e743c
CM
1627 SetPageChecked(page);
1628 page_cache_get(page);
1629 fixup->work.func = btrfs_writepage_fixup_worker;
1630 fixup->page = page;
1631 btrfs_queue_worker(&root->fs_info->fixup_workers, &fixup->work);
1632 return -EAGAIN;
1633}
1634
d899e052
YZ
1635static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
1636 struct inode *inode, u64 file_pos,
1637 u64 disk_bytenr, u64 disk_num_bytes,
1638 u64 num_bytes, u64 ram_bytes,
1639 u8 compression, u8 encryption,
1640 u16 other_encoding, int extent_type)
1641{
1642 struct btrfs_root *root = BTRFS_I(inode)->root;
1643 struct btrfs_file_extent_item *fi;
1644 struct btrfs_path *path;
1645 struct extent_buffer *leaf;
1646 struct btrfs_key ins;
1647 u64 hint;
1648 int ret;
1649
1650 path = btrfs_alloc_path();
d8926bb3
MF
1651 if (!path)
1652 return -ENOMEM;
d899e052 1653
b9473439 1654 path->leave_spinning = 1;
a1ed835e
CM
1655
1656 /*
1657 * we may be replacing one extent in the tree with another.
1658 * The new extent is pinned in the extent map, and we don't want
1659 * to drop it from the cache until it is completely in the btree.
1660 *
1661 * So, tell btrfs_drop_extents to leave this extent in the cache.
1662 * the caller is expected to unpin it and allow it to be merged
1663 * with the others.
1664 */
920bbbfb
YZ
1665 ret = btrfs_drop_extents(trans, inode, file_pos, file_pos + num_bytes,
1666 &hint, 0);
d899e052
YZ
1667 BUG_ON(ret);
1668
33345d01 1669 ins.objectid = btrfs_ino(inode);
d899e052
YZ
1670 ins.offset = file_pos;
1671 ins.type = BTRFS_EXTENT_DATA_KEY;
1672 ret = btrfs_insert_empty_item(trans, root, path, &ins, sizeof(*fi));
1673 BUG_ON(ret);
1674 leaf = path->nodes[0];
1675 fi = btrfs_item_ptr(leaf, path->slots[0],
1676 struct btrfs_file_extent_item);
1677 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1678 btrfs_set_file_extent_type(leaf, fi, extent_type);
1679 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
1680 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
1681 btrfs_set_file_extent_offset(leaf, fi, 0);
1682 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
1683 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
1684 btrfs_set_file_extent_compression(leaf, fi, compression);
1685 btrfs_set_file_extent_encryption(leaf, fi, encryption);
1686 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
b9473439
CM
1687
1688 btrfs_unlock_up_safe(path, 1);
1689 btrfs_set_lock_blocking(leaf);
1690
d899e052
YZ
1691 btrfs_mark_buffer_dirty(leaf);
1692
1693 inode_add_bytes(inode, num_bytes);
d899e052
YZ
1694
1695 ins.objectid = disk_bytenr;
1696 ins.offset = disk_num_bytes;
1697 ins.type = BTRFS_EXTENT_ITEM_KEY;
5d4f98a2
YZ
1698 ret = btrfs_alloc_reserved_file_extent(trans, root,
1699 root->root_key.objectid,
33345d01 1700 btrfs_ino(inode), file_pos, &ins);
d899e052 1701 BUG_ON(ret);
d899e052 1702 btrfs_free_path(path);
b9473439 1703
d899e052
YZ
1704 return 0;
1705}
1706
5d13a98f
CM
1707/*
1708 * helper function for btrfs_finish_ordered_io, this
1709 * just reads in some of the csum leaves to prime them into ram
1710 * before we start the transaction. It limits the amount of btree
1711 * reads required while inside the transaction.
1712 */
d352ac68
CM
1713/* as ordered data IO finishes, this gets called so we can finish
1714 * an ordered extent if the range of bytes in the file it covers are
1715 * fully written.
1716 */
211f90e6 1717static int btrfs_finish_ordered_io(struct inode *inode, u64 start, u64 end)
e6dcd2dc 1718{
e6dcd2dc 1719 struct btrfs_root *root = BTRFS_I(inode)->root;
0ca1f7ce 1720 struct btrfs_trans_handle *trans = NULL;
5d13a98f 1721 struct btrfs_ordered_extent *ordered_extent = NULL;
e6dcd2dc 1722 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2ac55d41 1723 struct extent_state *cached_state = NULL;
261507a0 1724 int compress_type = 0;
e6dcd2dc 1725 int ret;
82d5902d 1726 bool nolock;
e6dcd2dc 1727
5a1a3df1
JB
1728 ret = btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
1729 end - start + 1);
ba1da2f4 1730 if (!ret)
e6dcd2dc 1731 return 0;
e6dcd2dc 1732 BUG_ON(!ordered_extent);
efd049fb 1733
2cf8572d 1734 nolock = btrfs_is_free_space_inode(root, inode);
0cb59c99 1735
c2167754
YZ
1736 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
1737 BUG_ON(!list_empty(&ordered_extent->list));
1738 ret = btrfs_ordered_update_i_size(inode, 0, ordered_extent);
1739 if (!ret) {
0cb59c99 1740 if (nolock)
7a7eaa40 1741 trans = btrfs_join_transaction_nolock(root);
0cb59c99 1742 else
7a7eaa40 1743 trans = btrfs_join_transaction(root);
3612b495 1744 BUG_ON(IS_ERR(trans));
0ca1f7ce 1745 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2115133f 1746 ret = btrfs_update_inode_fallback(trans, root, inode);
c2167754 1747 BUG_ON(ret);
c2167754
YZ
1748 }
1749 goto out;
1750 }
e6dcd2dc 1751
2ac55d41
JB
1752 lock_extent_bits(io_tree, ordered_extent->file_offset,
1753 ordered_extent->file_offset + ordered_extent->len - 1,
1754 0, &cached_state, GFP_NOFS);
e6dcd2dc 1755
0cb59c99 1756 if (nolock)
7a7eaa40 1757 trans = btrfs_join_transaction_nolock(root);
0cb59c99 1758 else
7a7eaa40 1759 trans = btrfs_join_transaction(root);
3612b495 1760 BUG_ON(IS_ERR(trans));
0ca1f7ce 1761 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
c2167754 1762
c8b97818 1763 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
261507a0 1764 compress_type = ordered_extent->compress_type;
d899e052 1765 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
261507a0 1766 BUG_ON(compress_type);
920bbbfb 1767 ret = btrfs_mark_extent_written(trans, inode,
d899e052
YZ
1768 ordered_extent->file_offset,
1769 ordered_extent->file_offset +
1770 ordered_extent->len);
1771 BUG_ON(ret);
1772 } else {
0af3d00b 1773 BUG_ON(root == root->fs_info->tree_root);
d899e052
YZ
1774 ret = insert_reserved_file_extent(trans, inode,
1775 ordered_extent->file_offset,
1776 ordered_extent->start,
1777 ordered_extent->disk_len,
1778 ordered_extent->len,
1779 ordered_extent->len,
261507a0 1780 compress_type, 0, 0,
d899e052 1781 BTRFS_FILE_EXTENT_REG);
a1ed835e
CM
1782 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
1783 ordered_extent->file_offset,
1784 ordered_extent->len);
d899e052
YZ
1785 BUG_ON(ret);
1786 }
2ac55d41
JB
1787 unlock_extent_cached(io_tree, ordered_extent->file_offset,
1788 ordered_extent->file_offset +
1789 ordered_extent->len - 1, &cached_state, GFP_NOFS);
1790
e6dcd2dc
CM
1791 add_pending_csums(trans, inode, ordered_extent->file_offset,
1792 &ordered_extent->list);
1793
1ef30be1 1794 ret = btrfs_ordered_update_i_size(inode, 0, ordered_extent);
a39f7521 1795 if (!ret || !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2115133f 1796 ret = btrfs_update_inode_fallback(trans, root, inode);
1ef30be1
JB
1797 BUG_ON(ret);
1798 }
1799 ret = 0;
c2167754 1800out:
5b0e95bf
JB
1801 if (root != root->fs_info->tree_root)
1802 btrfs_delalloc_release_metadata(inode, ordered_extent->len);
1803 if (trans) {
1804 if (nolock)
0cb59c99 1805 btrfs_end_transaction_nolock(trans, root);
5b0e95bf 1806 else
0cb59c99
JB
1807 btrfs_end_transaction(trans, root);
1808 }
1809
e6dcd2dc
CM
1810 /* once for us */
1811 btrfs_put_ordered_extent(ordered_extent);
1812 /* once for the tree */
1813 btrfs_put_ordered_extent(ordered_extent);
1814
e6dcd2dc
CM
1815 return 0;
1816}
1817
b2950863 1818static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
211f90e6
CM
1819 struct extent_state *state, int uptodate)
1820{
1abe9b8a 1821 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
1822
8b62b72b 1823 ClearPagePrivate2(page);
211f90e6
CM
1824 return btrfs_finish_ordered_io(page->mapping->host, start, end);
1825}
1826
d352ac68
CM
1827/*
1828 * when reads are done, we need to check csums to verify the data is correct
4a54c8c1
JS
1829 * if there's a match, we allow the bio to finish. If not, the code in
1830 * extent_io.c will try to find good copies for us.
d352ac68 1831 */
b2950863 1832static int btrfs_readpage_end_io_hook(struct page *page, u64 start, u64 end,
70dec807 1833 struct extent_state *state)
07157aac 1834{
35ebb934 1835 size_t offset = start - ((u64)page->index << PAGE_CACHE_SHIFT);
07157aac 1836 struct inode *inode = page->mapping->host;
d1310b2e 1837 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
07157aac 1838 char *kaddr;
aadfeb6e 1839 u64 private = ~(u32)0;
07157aac 1840 int ret;
ff79f819
CM
1841 struct btrfs_root *root = BTRFS_I(inode)->root;
1842 u32 csum = ~(u32)0;
d1310b2e 1843
d20f7043
CM
1844 if (PageChecked(page)) {
1845 ClearPageChecked(page);
1846 goto good;
1847 }
6cbff00f
CH
1848
1849 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
08d2f347 1850 goto good;
17d217fe
YZ
1851
1852 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
9655d298 1853 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
17d217fe
YZ
1854 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM,
1855 GFP_NOFS);
b6cda9bc 1856 return 0;
17d217fe 1857 }
d20f7043 1858
c2e639f0 1859 if (state && state->start == start) {
70dec807
CM
1860 private = state->private;
1861 ret = 0;
1862 } else {
1863 ret = get_state_private(io_tree, start, &private);
1864 }
9ab86c8e 1865 kaddr = kmap_atomic(page, KM_USER0);
d397712b 1866 if (ret)
07157aac 1867 goto zeroit;
d397712b 1868
ff79f819
CM
1869 csum = btrfs_csum_data(root, kaddr + offset, csum, end - start + 1);
1870 btrfs_csum_final(csum, (char *)&csum);
d397712b 1871 if (csum != private)
07157aac 1872 goto zeroit;
d397712b 1873
9ab86c8e 1874 kunmap_atomic(kaddr, KM_USER0);
d20f7043 1875good:
07157aac
CM
1876 return 0;
1877
1878zeroit:
945d8962 1879 printk_ratelimited(KERN_INFO "btrfs csum failed ino %llu off %llu csum %u "
33345d01
LZ
1880 "private %llu\n",
1881 (unsigned long long)btrfs_ino(page->mapping->host),
193f284d
CM
1882 (unsigned long long)start, csum,
1883 (unsigned long long)private);
db94535d
CM
1884 memset(kaddr + offset, 1, end - start + 1);
1885 flush_dcache_page(page);
9ab86c8e 1886 kunmap_atomic(kaddr, KM_USER0);
3b951516
CM
1887 if (private == 0)
1888 return 0;
7e38326f 1889 return -EIO;
07157aac 1890}
b888db2b 1891
24bbcf04
YZ
1892struct delayed_iput {
1893 struct list_head list;
1894 struct inode *inode;
1895};
1896
1897void btrfs_add_delayed_iput(struct inode *inode)
1898{
1899 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
1900 struct delayed_iput *delayed;
1901
1902 if (atomic_add_unless(&inode->i_count, -1, 1))
1903 return;
1904
1905 delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL);
1906 delayed->inode = inode;
1907
1908 spin_lock(&fs_info->delayed_iput_lock);
1909 list_add_tail(&delayed->list, &fs_info->delayed_iputs);
1910 spin_unlock(&fs_info->delayed_iput_lock);
1911}
1912
1913void btrfs_run_delayed_iputs(struct btrfs_root *root)
1914{
1915 LIST_HEAD(list);
1916 struct btrfs_fs_info *fs_info = root->fs_info;
1917 struct delayed_iput *delayed;
1918 int empty;
1919
1920 spin_lock(&fs_info->delayed_iput_lock);
1921 empty = list_empty(&fs_info->delayed_iputs);
1922 spin_unlock(&fs_info->delayed_iput_lock);
1923 if (empty)
1924 return;
1925
1926 down_read(&root->fs_info->cleanup_work_sem);
1927 spin_lock(&fs_info->delayed_iput_lock);
1928 list_splice_init(&fs_info->delayed_iputs, &list);
1929 spin_unlock(&fs_info->delayed_iput_lock);
1930
1931 while (!list_empty(&list)) {
1932 delayed = list_entry(list.next, struct delayed_iput, list);
1933 list_del(&delayed->list);
1934 iput(delayed->inode);
1935 kfree(delayed);
1936 }
1937 up_read(&root->fs_info->cleanup_work_sem);
1938}
1939
d68fc57b
YZ
1940enum btrfs_orphan_cleanup_state {
1941 ORPHAN_CLEANUP_STARTED = 1,
1942 ORPHAN_CLEANUP_DONE = 2,
1943};
1944
1945/*
1946 * This is called in transaction commmit time. If there are no orphan
1947 * files in the subvolume, it removes orphan item and frees block_rsv
1948 * structure.
1949 */
1950void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
1951 struct btrfs_root *root)
1952{
1953 int ret;
1954
1955 if (!list_empty(&root->orphan_list) ||
1956 root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
1957 return;
1958
1959 if (root->orphan_item_inserted &&
1960 btrfs_root_refs(&root->root_item) > 0) {
1961 ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root,
1962 root->root_key.objectid);
1963 BUG_ON(ret);
1964 root->orphan_item_inserted = 0;
1965 }
1966
1967 if (root->orphan_block_rsv) {
1968 WARN_ON(root->orphan_block_rsv->size > 0);
1969 btrfs_free_block_rsv(root, root->orphan_block_rsv);
1970 root->orphan_block_rsv = NULL;
1971 }
1972}
1973
7b128766
JB
1974/*
1975 * This creates an orphan entry for the given inode in case something goes
1976 * wrong in the middle of an unlink/truncate.
d68fc57b
YZ
1977 *
1978 * NOTE: caller of this function should reserve 5 units of metadata for
1979 * this function.
7b128766
JB
1980 */
1981int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
1982{
1983 struct btrfs_root *root = BTRFS_I(inode)->root;
d68fc57b
YZ
1984 struct btrfs_block_rsv *block_rsv = NULL;
1985 int reserve = 0;
1986 int insert = 0;
1987 int ret;
7b128766 1988
d68fc57b
YZ
1989 if (!root->orphan_block_rsv) {
1990 block_rsv = btrfs_alloc_block_rsv(root);
b532402e
TI
1991 if (!block_rsv)
1992 return -ENOMEM;
d68fc57b 1993 }
7b128766 1994
d68fc57b
YZ
1995 spin_lock(&root->orphan_lock);
1996 if (!root->orphan_block_rsv) {
1997 root->orphan_block_rsv = block_rsv;
1998 } else if (block_rsv) {
1999 btrfs_free_block_rsv(root, block_rsv);
2000 block_rsv = NULL;
7b128766 2001 }
7b128766 2002
d68fc57b
YZ
2003 if (list_empty(&BTRFS_I(inode)->i_orphan)) {
2004 list_add(&BTRFS_I(inode)->i_orphan, &root->orphan_list);
2005#if 0
2006 /*
2007 * For proper ENOSPC handling, we should do orphan
2008 * cleanup when mounting. But this introduces backward
2009 * compatibility issue.
2010 */
2011 if (!xchg(&root->orphan_item_inserted, 1))
2012 insert = 2;
2013 else
2014 insert = 1;
2015#endif
2016 insert = 1;
7b128766
JB
2017 }
2018
d68fc57b
YZ
2019 if (!BTRFS_I(inode)->orphan_meta_reserved) {
2020 BTRFS_I(inode)->orphan_meta_reserved = 1;
2021 reserve = 1;
2022 }
2023 spin_unlock(&root->orphan_lock);
7b128766 2024
d68fc57b
YZ
2025 /* grab metadata reservation from transaction handle */
2026 if (reserve) {
2027 ret = btrfs_orphan_reserve_metadata(trans, inode);
2028 BUG_ON(ret);
2029 }
7b128766 2030
d68fc57b
YZ
2031 /* insert an orphan item to track this unlinked/truncated file */
2032 if (insert >= 1) {
33345d01 2033 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
d68fc57b
YZ
2034 BUG_ON(ret);
2035 }
2036
2037 /* insert an orphan item to track subvolume contains orphan files */
2038 if (insert >= 2) {
2039 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
2040 root->root_key.objectid);
2041 BUG_ON(ret);
2042 }
2043 return 0;
7b128766
JB
2044}
2045
2046/*
2047 * We have done the truncate/delete so we can go ahead and remove the orphan
2048 * item for this particular inode.
2049 */
2050int btrfs_orphan_del(struct btrfs_trans_handle *trans, struct inode *inode)
2051{
2052 struct btrfs_root *root = BTRFS_I(inode)->root;
d68fc57b
YZ
2053 int delete_item = 0;
2054 int release_rsv = 0;
7b128766
JB
2055 int ret = 0;
2056
d68fc57b
YZ
2057 spin_lock(&root->orphan_lock);
2058 if (!list_empty(&BTRFS_I(inode)->i_orphan)) {
2059 list_del_init(&BTRFS_I(inode)->i_orphan);
2060 delete_item = 1;
7b128766
JB
2061 }
2062
d68fc57b
YZ
2063 if (BTRFS_I(inode)->orphan_meta_reserved) {
2064 BTRFS_I(inode)->orphan_meta_reserved = 0;
2065 release_rsv = 1;
7b128766 2066 }
d68fc57b 2067 spin_unlock(&root->orphan_lock);
7b128766 2068
d68fc57b 2069 if (trans && delete_item) {
33345d01 2070 ret = btrfs_del_orphan_item(trans, root, btrfs_ino(inode));
d68fc57b
YZ
2071 BUG_ON(ret);
2072 }
7b128766 2073
d68fc57b
YZ
2074 if (release_rsv)
2075 btrfs_orphan_release_metadata(inode);
7b128766 2076
d68fc57b 2077 return 0;
7b128766
JB
2078}
2079
2080/*
2081 * this cleans up any orphans that may be left on the list from the last use
2082 * of this root.
2083 */
66b4ffd1 2084int btrfs_orphan_cleanup(struct btrfs_root *root)
7b128766
JB
2085{
2086 struct btrfs_path *path;
2087 struct extent_buffer *leaf;
7b128766
JB
2088 struct btrfs_key key, found_key;
2089 struct btrfs_trans_handle *trans;
2090 struct inode *inode;
8f6d7f4f 2091 u64 last_objectid = 0;
7b128766
JB
2092 int ret = 0, nr_unlink = 0, nr_truncate = 0;
2093
d68fc57b 2094 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
66b4ffd1 2095 return 0;
c71bf099
YZ
2096
2097 path = btrfs_alloc_path();
66b4ffd1
JB
2098 if (!path) {
2099 ret = -ENOMEM;
2100 goto out;
2101 }
7b128766
JB
2102 path->reada = -1;
2103
2104 key.objectid = BTRFS_ORPHAN_OBJECTID;
2105 btrfs_set_key_type(&key, BTRFS_ORPHAN_ITEM_KEY);
2106 key.offset = (u64)-1;
2107
7b128766
JB
2108 while (1) {
2109 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
66b4ffd1
JB
2110 if (ret < 0)
2111 goto out;
7b128766
JB
2112
2113 /*
2114 * if ret == 0 means we found what we were searching for, which
25985edc 2115 * is weird, but possible, so only screw with path if we didn't
7b128766
JB
2116 * find the key and see if we have stuff that matches
2117 */
2118 if (ret > 0) {
66b4ffd1 2119 ret = 0;
7b128766
JB
2120 if (path->slots[0] == 0)
2121 break;
2122 path->slots[0]--;
2123 }
2124
2125 /* pull out the item */
2126 leaf = path->nodes[0];
7b128766
JB
2127 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2128
2129 /* make sure the item matches what we want */
2130 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
2131 break;
2132 if (btrfs_key_type(&found_key) != BTRFS_ORPHAN_ITEM_KEY)
2133 break;
2134
2135 /* release the path since we're done with it */
b3b4aa74 2136 btrfs_release_path(path);
7b128766
JB
2137
2138 /*
2139 * this is where we are basically btrfs_lookup, without the
2140 * crossing root thing. we store the inode number in the
2141 * offset of the orphan item.
2142 */
8f6d7f4f
JB
2143
2144 if (found_key.offset == last_objectid) {
2145 printk(KERN_ERR "btrfs: Error removing orphan entry, "
2146 "stopping orphan cleanup\n");
2147 ret = -EINVAL;
2148 goto out;
2149 }
2150
2151 last_objectid = found_key.offset;
2152
5d4f98a2
YZ
2153 found_key.objectid = found_key.offset;
2154 found_key.type = BTRFS_INODE_ITEM_KEY;
2155 found_key.offset = 0;
73f73415 2156 inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
a8c9e576
JB
2157 ret = PTR_RET(inode);
2158 if (ret && ret != -ESTALE)
66b4ffd1 2159 goto out;
7b128766 2160
f8e9e0b0
AJ
2161 if (ret == -ESTALE && root == root->fs_info->tree_root) {
2162 struct btrfs_root *dead_root;
2163 struct btrfs_fs_info *fs_info = root->fs_info;
2164 int is_dead_root = 0;
2165
2166 /*
2167 * this is an orphan in the tree root. Currently these
2168 * could come from 2 sources:
2169 * a) a snapshot deletion in progress
2170 * b) a free space cache inode
2171 * We need to distinguish those two, as the snapshot
2172 * orphan must not get deleted.
2173 * find_dead_roots already ran before us, so if this
2174 * is a snapshot deletion, we should find the root
2175 * in the dead_roots list
2176 */
2177 spin_lock(&fs_info->trans_lock);
2178 list_for_each_entry(dead_root, &fs_info->dead_roots,
2179 root_list) {
2180 if (dead_root->root_key.objectid ==
2181 found_key.objectid) {
2182 is_dead_root = 1;
2183 break;
2184 }
2185 }
2186 spin_unlock(&fs_info->trans_lock);
2187 if (is_dead_root) {
2188 /* prevent this orphan from being found again */
2189 key.offset = found_key.objectid - 1;
2190 continue;
2191 }
2192 }
7b128766 2193 /*
a8c9e576
JB
2194 * Inode is already gone but the orphan item is still there,
2195 * kill the orphan item.
7b128766 2196 */
a8c9e576
JB
2197 if (ret == -ESTALE) {
2198 trans = btrfs_start_transaction(root, 1);
66b4ffd1
JB
2199 if (IS_ERR(trans)) {
2200 ret = PTR_ERR(trans);
2201 goto out;
2202 }
a8c9e576
JB
2203 ret = btrfs_del_orphan_item(trans, root,
2204 found_key.objectid);
2205 BUG_ON(ret);
5b21f2ed 2206 btrfs_end_transaction(trans, root);
7b128766
JB
2207 continue;
2208 }
2209
a8c9e576
JB
2210 /*
2211 * add this inode to the orphan list so btrfs_orphan_del does
2212 * the proper thing when we hit it
2213 */
2214 spin_lock(&root->orphan_lock);
2215 list_add(&BTRFS_I(inode)->i_orphan, &root->orphan_list);
2216 spin_unlock(&root->orphan_lock);
2217
7b128766
JB
2218 /* if we have links, this was a truncate, lets do that */
2219 if (inode->i_nlink) {
a41ad394
JB
2220 if (!S_ISREG(inode->i_mode)) {
2221 WARN_ON(1);
2222 iput(inode);
2223 continue;
2224 }
7b128766 2225 nr_truncate++;
66b4ffd1 2226 ret = btrfs_truncate(inode);
7b128766
JB
2227 } else {
2228 nr_unlink++;
2229 }
2230
2231 /* this will do delete_inode and everything for us */
2232 iput(inode);
66b4ffd1
JB
2233 if (ret)
2234 goto out;
7b128766 2235 }
3254c876
MX
2236 /* release the path since we're done with it */
2237 btrfs_release_path(path);
2238
d68fc57b
YZ
2239 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
2240
2241 if (root->orphan_block_rsv)
2242 btrfs_block_rsv_release(root, root->orphan_block_rsv,
2243 (u64)-1);
2244
2245 if (root->orphan_block_rsv || root->orphan_item_inserted) {
7a7eaa40 2246 trans = btrfs_join_transaction(root);
66b4ffd1
JB
2247 if (!IS_ERR(trans))
2248 btrfs_end_transaction(trans, root);
d68fc57b 2249 }
7b128766
JB
2250
2251 if (nr_unlink)
2252 printk(KERN_INFO "btrfs: unlinked %d orphans\n", nr_unlink);
2253 if (nr_truncate)
2254 printk(KERN_INFO "btrfs: truncated %d orphans\n", nr_truncate);
66b4ffd1
JB
2255
2256out:
2257 if (ret)
2258 printk(KERN_CRIT "btrfs: could not do orphan cleanup %d\n", ret);
2259 btrfs_free_path(path);
2260 return ret;
7b128766
JB
2261}
2262
46a53cca
CM
2263/*
2264 * very simple check to peek ahead in the leaf looking for xattrs. If we
2265 * don't find any xattrs, we know there can't be any acls.
2266 *
2267 * slot is the slot the inode is in, objectid is the objectid of the inode
2268 */
2269static noinline int acls_after_inode_item(struct extent_buffer *leaf,
2270 int slot, u64 objectid)
2271{
2272 u32 nritems = btrfs_header_nritems(leaf);
2273 struct btrfs_key found_key;
2274 int scanned = 0;
2275
2276 slot++;
2277 while (slot < nritems) {
2278 btrfs_item_key_to_cpu(leaf, &found_key, slot);
2279
2280 /* we found a different objectid, there must not be acls */
2281 if (found_key.objectid != objectid)
2282 return 0;
2283
2284 /* we found an xattr, assume we've got an acl */
2285 if (found_key.type == BTRFS_XATTR_ITEM_KEY)
2286 return 1;
2287
2288 /*
2289 * we found a key greater than an xattr key, there can't
2290 * be any acls later on
2291 */
2292 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
2293 return 0;
2294
2295 slot++;
2296 scanned++;
2297
2298 /*
2299 * it goes inode, inode backrefs, xattrs, extents,
2300 * so if there are a ton of hard links to an inode there can
2301 * be a lot of backrefs. Don't waste time searching too hard,
2302 * this is just an optimization
2303 */
2304 if (scanned >= 8)
2305 break;
2306 }
2307 /* we hit the end of the leaf before we found an xattr or
2308 * something larger than an xattr. We have to assume the inode
2309 * has acls
2310 */
2311 return 1;
2312}
2313
d352ac68
CM
2314/*
2315 * read an inode from the btree into the in-memory inode
2316 */
5d4f98a2 2317static void btrfs_read_locked_inode(struct inode *inode)
39279cc3
CM
2318{
2319 struct btrfs_path *path;
5f39d397 2320 struct extent_buffer *leaf;
39279cc3 2321 struct btrfs_inode_item *inode_item;
0b86a832 2322 struct btrfs_timespec *tspec;
39279cc3
CM
2323 struct btrfs_root *root = BTRFS_I(inode)->root;
2324 struct btrfs_key location;
46a53cca 2325 int maybe_acls;
618e21d5 2326 u32 rdev;
39279cc3 2327 int ret;
2f7e33d4
MX
2328 bool filled = false;
2329
2330 ret = btrfs_fill_inode(inode, &rdev);
2331 if (!ret)
2332 filled = true;
39279cc3
CM
2333
2334 path = btrfs_alloc_path();
1748f843
MF
2335 if (!path)
2336 goto make_bad;
2337
d90c7321 2338 path->leave_spinning = 1;
39279cc3 2339 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
dc17ff8f 2340
39279cc3 2341 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
5f39d397 2342 if (ret)
39279cc3 2343 goto make_bad;
39279cc3 2344
5f39d397 2345 leaf = path->nodes[0];
2f7e33d4
MX
2346
2347 if (filled)
2348 goto cache_acl;
2349
5f39d397
CM
2350 inode_item = btrfs_item_ptr(leaf, path->slots[0],
2351 struct btrfs_inode_item);
5f39d397
CM
2352 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
2353 inode->i_nlink = btrfs_inode_nlink(leaf, inode_item);
2354 inode->i_uid = btrfs_inode_uid(leaf, inode_item);
2355 inode->i_gid = btrfs_inode_gid(leaf, inode_item);
dbe674a9 2356 btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
5f39d397
CM
2357
2358 tspec = btrfs_inode_atime(inode_item);
2359 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2360 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2361
2362 tspec = btrfs_inode_mtime(inode_item);
2363 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2364 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2365
2366 tspec = btrfs_inode_ctime(inode_item);
2367 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2368 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2369
a76a3cd4 2370 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
e02119d5 2371 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
c3027eb5 2372 BTRFS_I(inode)->sequence = btrfs_inode_sequence(leaf, inode_item);
e02119d5 2373 inode->i_generation = BTRFS_I(inode)->generation;
618e21d5 2374 inode->i_rdev = 0;
5f39d397
CM
2375 rdev = btrfs_inode_rdev(leaf, inode_item);
2376
aec7477b 2377 BTRFS_I(inode)->index_cnt = (u64)-1;
d2fb3437 2378 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
2f7e33d4 2379cache_acl:
46a53cca
CM
2380 /*
2381 * try to precache a NULL acl entry for files that don't have
2382 * any xattrs or acls
2383 */
33345d01
LZ
2384 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
2385 btrfs_ino(inode));
72c04902
AV
2386 if (!maybe_acls)
2387 cache_no_acl(inode);
46a53cca 2388
39279cc3 2389 btrfs_free_path(path);
39279cc3 2390
39279cc3 2391 switch (inode->i_mode & S_IFMT) {
39279cc3
CM
2392 case S_IFREG:
2393 inode->i_mapping->a_ops = &btrfs_aops;
04160088 2394 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
d1310b2e 2395 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
39279cc3
CM
2396 inode->i_fop = &btrfs_file_operations;
2397 inode->i_op = &btrfs_file_inode_operations;
2398 break;
2399 case S_IFDIR:
2400 inode->i_fop = &btrfs_dir_file_operations;
2401 if (root == root->fs_info->tree_root)
2402 inode->i_op = &btrfs_dir_ro_inode_operations;
2403 else
2404 inode->i_op = &btrfs_dir_inode_operations;
2405 break;
2406 case S_IFLNK:
2407 inode->i_op = &btrfs_symlink_inode_operations;
2408 inode->i_mapping->a_ops = &btrfs_symlink_aops;
04160088 2409 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
39279cc3 2410 break;
618e21d5 2411 default:
0279b4cd 2412 inode->i_op = &btrfs_special_inode_operations;
618e21d5
JB
2413 init_special_inode(inode, inode->i_mode, rdev);
2414 break;
39279cc3 2415 }
6cbff00f
CH
2416
2417 btrfs_update_iflags(inode);
39279cc3
CM
2418 return;
2419
2420make_bad:
39279cc3 2421 btrfs_free_path(path);
39279cc3
CM
2422 make_bad_inode(inode);
2423}
2424
d352ac68
CM
2425/*
2426 * given a leaf and an inode, copy the inode fields into the leaf
2427 */
e02119d5
CM
2428static void fill_inode_item(struct btrfs_trans_handle *trans,
2429 struct extent_buffer *leaf,
5f39d397 2430 struct btrfs_inode_item *item,
39279cc3
CM
2431 struct inode *inode)
2432{
5f39d397
CM
2433 btrfs_set_inode_uid(leaf, item, inode->i_uid);
2434 btrfs_set_inode_gid(leaf, item, inode->i_gid);
dbe674a9 2435 btrfs_set_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size);
5f39d397
CM
2436 btrfs_set_inode_mode(leaf, item, inode->i_mode);
2437 btrfs_set_inode_nlink(leaf, item, inode->i_nlink);
2438
2439 btrfs_set_timespec_sec(leaf, btrfs_inode_atime(item),
2440 inode->i_atime.tv_sec);
2441 btrfs_set_timespec_nsec(leaf, btrfs_inode_atime(item),
2442 inode->i_atime.tv_nsec);
2443
2444 btrfs_set_timespec_sec(leaf, btrfs_inode_mtime(item),
2445 inode->i_mtime.tv_sec);
2446 btrfs_set_timespec_nsec(leaf, btrfs_inode_mtime(item),
2447 inode->i_mtime.tv_nsec);
2448
2449 btrfs_set_timespec_sec(leaf, btrfs_inode_ctime(item),
2450 inode->i_ctime.tv_sec);
2451 btrfs_set_timespec_nsec(leaf, btrfs_inode_ctime(item),
2452 inode->i_ctime.tv_nsec);
2453
a76a3cd4 2454 btrfs_set_inode_nbytes(leaf, item, inode_get_bytes(inode));
e02119d5 2455 btrfs_set_inode_generation(leaf, item, BTRFS_I(inode)->generation);
c3027eb5 2456 btrfs_set_inode_sequence(leaf, item, BTRFS_I(inode)->sequence);
e02119d5 2457 btrfs_set_inode_transid(leaf, item, trans->transid);
5f39d397 2458 btrfs_set_inode_rdev(leaf, item, inode->i_rdev);
b98b6767 2459 btrfs_set_inode_flags(leaf, item, BTRFS_I(inode)->flags);
d82a6f1d 2460 btrfs_set_inode_block_group(leaf, item, 0);
39279cc3
CM
2461}
2462
d352ac68
CM
2463/*
2464 * copy everything in the in-memory inode into the btree.
2465 */
2115133f 2466static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
d397712b 2467 struct btrfs_root *root, struct inode *inode)
39279cc3
CM
2468{
2469 struct btrfs_inode_item *inode_item;
2470 struct btrfs_path *path;
5f39d397 2471 struct extent_buffer *leaf;
39279cc3
CM
2472 int ret;
2473
2474 path = btrfs_alloc_path();
16cdcec7
MX
2475 if (!path)
2476 return -ENOMEM;
2477
b9473439 2478 path->leave_spinning = 1;
16cdcec7
MX
2479 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
2480 1);
39279cc3
CM
2481 if (ret) {
2482 if (ret > 0)
2483 ret = -ENOENT;
2484 goto failed;
2485 }
2486
b4ce94de 2487 btrfs_unlock_up_safe(path, 1);
5f39d397
CM
2488 leaf = path->nodes[0];
2489 inode_item = btrfs_item_ptr(leaf, path->slots[0],
16cdcec7 2490 struct btrfs_inode_item);
39279cc3 2491
e02119d5 2492 fill_inode_item(trans, leaf, inode_item, inode);
5f39d397 2493 btrfs_mark_buffer_dirty(leaf);
15ee9bc7 2494 btrfs_set_inode_last_trans(trans, inode);
39279cc3
CM
2495 ret = 0;
2496failed:
39279cc3
CM
2497 btrfs_free_path(path);
2498 return ret;
2499}
2500
2115133f
CM
2501/*
2502 * copy everything in the in-memory inode into the btree.
2503 */
2504noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
2505 struct btrfs_root *root, struct inode *inode)
2506{
2507 int ret;
2508
2509 /*
2510 * If the inode is a free space inode, we can deadlock during commit
2511 * if we put it into the delayed code.
2512 *
2513 * The data relocation inode should also be directly updated
2514 * without delay
2515 */
2516 if (!btrfs_is_free_space_inode(root, inode)
2517 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID) {
2518 ret = btrfs_delayed_update_inode(trans, root, inode);
2519 if (!ret)
2520 btrfs_set_inode_last_trans(trans, inode);
2521 return ret;
2522 }
2523
2524 return btrfs_update_inode_item(trans, root, inode);
2525}
2526
2527static noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
2528 struct btrfs_root *root, struct inode *inode)
2529{
2530 int ret;
2531
2532 ret = btrfs_update_inode(trans, root, inode);
2533 if (ret == -ENOSPC)
2534 return btrfs_update_inode_item(trans, root, inode);
2535 return ret;
2536}
2537
d352ac68
CM
2538/*
2539 * unlink helper that gets used here in inode.c and in the tree logging
2540 * recovery code. It remove a link in a directory with a given name, and
2541 * also drops the back refs in the inode to the directory
2542 */
92986796
AV
2543static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
2544 struct btrfs_root *root,
2545 struct inode *dir, struct inode *inode,
2546 const char *name, int name_len)
39279cc3
CM
2547{
2548 struct btrfs_path *path;
39279cc3 2549 int ret = 0;
5f39d397 2550 struct extent_buffer *leaf;
39279cc3 2551 struct btrfs_dir_item *di;
5f39d397 2552 struct btrfs_key key;
aec7477b 2553 u64 index;
33345d01
LZ
2554 u64 ino = btrfs_ino(inode);
2555 u64 dir_ino = btrfs_ino(dir);
39279cc3
CM
2556
2557 path = btrfs_alloc_path();
54aa1f4d
CM
2558 if (!path) {
2559 ret = -ENOMEM;
554233a6 2560 goto out;
54aa1f4d
CM
2561 }
2562
b9473439 2563 path->leave_spinning = 1;
33345d01 2564 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
39279cc3
CM
2565 name, name_len, -1);
2566 if (IS_ERR(di)) {
2567 ret = PTR_ERR(di);
2568 goto err;
2569 }
2570 if (!di) {
2571 ret = -ENOENT;
2572 goto err;
2573 }
5f39d397
CM
2574 leaf = path->nodes[0];
2575 btrfs_dir_item_key_to_cpu(leaf, di, &key);
39279cc3 2576 ret = btrfs_delete_one_dir_name(trans, root, path, di);
54aa1f4d
CM
2577 if (ret)
2578 goto err;
b3b4aa74 2579 btrfs_release_path(path);
39279cc3 2580
33345d01
LZ
2581 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
2582 dir_ino, &index);
aec7477b 2583 if (ret) {
d397712b 2584 printk(KERN_INFO "btrfs failed to delete reference to %.*s, "
33345d01
LZ
2585 "inode %llu parent %llu\n", name_len, name,
2586 (unsigned long long)ino, (unsigned long long)dir_ino);
aec7477b
JB
2587 goto err;
2588 }
2589
16cdcec7
MX
2590 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
2591 if (ret)
39279cc3 2592 goto err;
39279cc3 2593
e02119d5 2594 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
33345d01 2595 inode, dir_ino);
49eb7e46 2596 BUG_ON(ret != 0 && ret != -ENOENT);
e02119d5
CM
2597
2598 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
2599 dir, index);
6418c961
CM
2600 if (ret == -ENOENT)
2601 ret = 0;
39279cc3
CM
2602err:
2603 btrfs_free_path(path);
e02119d5
CM
2604 if (ret)
2605 goto out;
2606
2607 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
2608 inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME;
2609 btrfs_update_inode(trans, root, dir);
e02119d5 2610out:
39279cc3
CM
2611 return ret;
2612}
2613
92986796
AV
2614int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
2615 struct btrfs_root *root,
2616 struct inode *dir, struct inode *inode,
2617 const char *name, int name_len)
2618{
2619 int ret;
2620 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
2621 if (!ret) {
2622 btrfs_drop_nlink(inode);
2623 ret = btrfs_update_inode(trans, root, inode);
2624 }
2625 return ret;
2626}
2627
2628
a22285a6
YZ
2629/* helper to check if there is any shared block in the path */
2630static int check_path_shared(struct btrfs_root *root,
2631 struct btrfs_path *path)
39279cc3 2632{
a22285a6
YZ
2633 struct extent_buffer *eb;
2634 int level;
0e4dcbef 2635 u64 refs = 1;
5df6a9f6 2636
a22285a6 2637 for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
dedefd72
JB
2638 int ret;
2639
a22285a6
YZ
2640 if (!path->nodes[level])
2641 break;
2642 eb = path->nodes[level];
2643 if (!btrfs_block_can_be_shared(root, eb))
2644 continue;
2645 ret = btrfs_lookup_extent_info(NULL, root, eb->start, eb->len,
2646 &refs, NULL);
2647 if (refs > 1)
2648 return 1;
5df6a9f6 2649 }
dedefd72 2650 return 0;
39279cc3
CM
2651}
2652
a22285a6
YZ
2653/*
2654 * helper to start transaction for unlink and rmdir.
2655 *
2656 * unlink and rmdir are special in btrfs, they do not always free space.
2657 * so in enospc case, we should make sure they will free space before
2658 * allowing them to use the global metadata reservation.
2659 */
2660static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir,
2661 struct dentry *dentry)
4df27c4d 2662{
39279cc3 2663 struct btrfs_trans_handle *trans;
a22285a6 2664 struct btrfs_root *root = BTRFS_I(dir)->root;
4df27c4d 2665 struct btrfs_path *path;
a22285a6 2666 struct btrfs_inode_ref *ref;
4df27c4d 2667 struct btrfs_dir_item *di;
7b128766 2668 struct inode *inode = dentry->d_inode;
4df27c4d 2669 u64 index;
a22285a6
YZ
2670 int check_link = 1;
2671 int err = -ENOSPC;
4df27c4d 2672 int ret;
33345d01
LZ
2673 u64 ino = btrfs_ino(inode);
2674 u64 dir_ino = btrfs_ino(dir);
4df27c4d 2675
e70bea5f
JB
2676 /*
2677 * 1 for the possible orphan item
2678 * 1 for the dir item
2679 * 1 for the dir index
2680 * 1 for the inode ref
2681 * 1 for the inode ref in the tree log
2682 * 2 for the dir entries in the log
2683 * 1 for the inode
2684 */
2685 trans = btrfs_start_transaction(root, 8);
a22285a6
YZ
2686 if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
2687 return trans;
4df27c4d 2688
33345d01 2689 if (ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
a22285a6 2690 return ERR_PTR(-ENOSPC);
4df27c4d 2691
a22285a6
YZ
2692 /* check if there is someone else holds reference */
2693 if (S_ISDIR(inode->i_mode) && atomic_read(&inode->i_count) > 1)
2694 return ERR_PTR(-ENOSPC);
4df27c4d 2695
a22285a6
YZ
2696 if (atomic_read(&inode->i_count) > 2)
2697 return ERR_PTR(-ENOSPC);
4df27c4d 2698
a22285a6
YZ
2699 if (xchg(&root->fs_info->enospc_unlink, 1))
2700 return ERR_PTR(-ENOSPC);
2701
2702 path = btrfs_alloc_path();
2703 if (!path) {
2704 root->fs_info->enospc_unlink = 0;
2705 return ERR_PTR(-ENOMEM);
4df27c4d
YZ
2706 }
2707
3880a1b4
JB
2708 /* 1 for the orphan item */
2709 trans = btrfs_start_transaction(root, 1);
5df6a9f6 2710 if (IS_ERR(trans)) {
a22285a6
YZ
2711 btrfs_free_path(path);
2712 root->fs_info->enospc_unlink = 0;
2713 return trans;
2714 }
4df27c4d 2715
a22285a6
YZ
2716 path->skip_locking = 1;
2717 path->search_commit_root = 1;
4df27c4d 2718
a22285a6
YZ
2719 ret = btrfs_lookup_inode(trans, root, path,
2720 &BTRFS_I(dir)->location, 0);
2721 if (ret < 0) {
2722 err = ret;
2723 goto out;
2724 }
2725 if (ret == 0) {
2726 if (check_path_shared(root, path))
2727 goto out;
2728 } else {
2729 check_link = 0;
5df6a9f6 2730 }
b3b4aa74 2731 btrfs_release_path(path);
a22285a6
YZ
2732
2733 ret = btrfs_lookup_inode(trans, root, path,
2734 &BTRFS_I(inode)->location, 0);
2735 if (ret < 0) {
2736 err = ret;
2737 goto out;
2738 }
2739 if (ret == 0) {
2740 if (check_path_shared(root, path))
2741 goto out;
2742 } else {
2743 check_link = 0;
2744 }
b3b4aa74 2745 btrfs_release_path(path);
a22285a6
YZ
2746
2747 if (ret == 0 && S_ISREG(inode->i_mode)) {
2748 ret = btrfs_lookup_file_extent(trans, root, path,
33345d01 2749 ino, (u64)-1, 0);
a22285a6
YZ
2750 if (ret < 0) {
2751 err = ret;
2752 goto out;
2753 }
2754 BUG_ON(ret == 0);
2755 if (check_path_shared(root, path))
2756 goto out;
b3b4aa74 2757 btrfs_release_path(path);
a22285a6
YZ
2758 }
2759
2760 if (!check_link) {
2761 err = 0;
2762 goto out;
2763 }
2764
33345d01 2765 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
a22285a6
YZ
2766 dentry->d_name.name, dentry->d_name.len, 0);
2767 if (IS_ERR(di)) {
2768 err = PTR_ERR(di);
2769 goto out;
2770 }
2771 if (di) {
2772 if (check_path_shared(root, path))
2773 goto out;
2774 } else {
2775 err = 0;
2776 goto out;
2777 }
b3b4aa74 2778 btrfs_release_path(path);
a22285a6
YZ
2779
2780 ref = btrfs_lookup_inode_ref(trans, root, path,
2781 dentry->d_name.name, dentry->d_name.len,
33345d01 2782 ino, dir_ino, 0);
a22285a6
YZ
2783 if (IS_ERR(ref)) {
2784 err = PTR_ERR(ref);
2785 goto out;
2786 }
2787 BUG_ON(!ref);
2788 if (check_path_shared(root, path))
2789 goto out;
2790 index = btrfs_inode_ref_index(path->nodes[0], ref);
b3b4aa74 2791 btrfs_release_path(path);
a22285a6 2792
16cdcec7
MX
2793 /*
2794 * This is a commit root search, if we can lookup inode item and other
2795 * relative items in the commit root, it means the transaction of
2796 * dir/file creation has been committed, and the dir index item that we
2797 * delay to insert has also been inserted into the commit root. So
2798 * we needn't worry about the delayed insertion of the dir index item
2799 * here.
2800 */
33345d01 2801 di = btrfs_lookup_dir_index_item(trans, root, path, dir_ino, index,
a22285a6
YZ
2802 dentry->d_name.name, dentry->d_name.len, 0);
2803 if (IS_ERR(di)) {
2804 err = PTR_ERR(di);
2805 goto out;
2806 }
2807 BUG_ON(ret == -ENOENT);
2808 if (check_path_shared(root, path))
2809 goto out;
2810
2811 err = 0;
2812out:
2813 btrfs_free_path(path);
3880a1b4
JB
2814 /* Migrate the orphan reservation over */
2815 if (!err)
2816 err = btrfs_block_rsv_migrate(trans->block_rsv,
2817 &root->fs_info->global_block_rsv,
5a77d76c 2818 trans->bytes_reserved);
3880a1b4 2819
a22285a6
YZ
2820 if (err) {
2821 btrfs_end_transaction(trans, root);
2822 root->fs_info->enospc_unlink = 0;
2823 return ERR_PTR(err);
2824 }
2825
2826 trans->block_rsv = &root->fs_info->global_block_rsv;
2827 return trans;
2828}
2829
2830static void __unlink_end_trans(struct btrfs_trans_handle *trans,
2831 struct btrfs_root *root)
2832{
2833 if (trans->block_rsv == &root->fs_info->global_block_rsv) {
5a77d76c
JB
2834 btrfs_block_rsv_release(root, trans->block_rsv,
2835 trans->bytes_reserved);
2836 trans->block_rsv = &root->fs_info->trans_block_rsv;
a22285a6
YZ
2837 BUG_ON(!root->fs_info->enospc_unlink);
2838 root->fs_info->enospc_unlink = 0;
2839 }
2840 btrfs_end_transaction_throttle(trans, root);
2841}
2842
2843static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
2844{
2845 struct btrfs_root *root = BTRFS_I(dir)->root;
2846 struct btrfs_trans_handle *trans;
2847 struct inode *inode = dentry->d_inode;
2848 int ret;
2849 unsigned long nr = 0;
2850
2851 trans = __unlink_start_trans(dir, dentry);
2852 if (IS_ERR(trans))
2853 return PTR_ERR(trans);
5f39d397 2854
12fcfd22
CM
2855 btrfs_record_unlink_dir(trans, dir, dentry->d_inode, 0);
2856
e02119d5
CM
2857 ret = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
2858 dentry->d_name.name, dentry->d_name.len);
b532402e
TI
2859 if (ret)
2860 goto out;
7b128766 2861
a22285a6 2862 if (inode->i_nlink == 0) {
7b128766 2863 ret = btrfs_orphan_add(trans, inode);
b532402e
TI
2864 if (ret)
2865 goto out;
a22285a6 2866 }
7b128766 2867
b532402e 2868out:
d3c2fdcf 2869 nr = trans->blocks_used;
a22285a6 2870 __unlink_end_trans(trans, root);
d3c2fdcf 2871 btrfs_btree_balance_dirty(root, nr);
39279cc3
CM
2872 return ret;
2873}
2874
4df27c4d
YZ
2875int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
2876 struct btrfs_root *root,
2877 struct inode *dir, u64 objectid,
2878 const char *name, int name_len)
2879{
2880 struct btrfs_path *path;
2881 struct extent_buffer *leaf;
2882 struct btrfs_dir_item *di;
2883 struct btrfs_key key;
2884 u64 index;
2885 int ret;
33345d01 2886 u64 dir_ino = btrfs_ino(dir);
4df27c4d
YZ
2887
2888 path = btrfs_alloc_path();
2889 if (!path)
2890 return -ENOMEM;
2891
33345d01 2892 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4df27c4d 2893 name, name_len, -1);
c704005d 2894 BUG_ON(IS_ERR_OR_NULL(di));
4df27c4d
YZ
2895
2896 leaf = path->nodes[0];
2897 btrfs_dir_item_key_to_cpu(leaf, di, &key);
2898 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
2899 ret = btrfs_delete_one_dir_name(trans, root, path, di);
2900 BUG_ON(ret);
b3b4aa74 2901 btrfs_release_path(path);
4df27c4d
YZ
2902
2903 ret = btrfs_del_root_ref(trans, root->fs_info->tree_root,
2904 objectid, root->root_key.objectid,
33345d01 2905 dir_ino, &index, name, name_len);
4df27c4d
YZ
2906 if (ret < 0) {
2907 BUG_ON(ret != -ENOENT);
33345d01 2908 di = btrfs_search_dir_index_item(root, path, dir_ino,
4df27c4d 2909 name, name_len);
c704005d 2910 BUG_ON(IS_ERR_OR_NULL(di));
4df27c4d
YZ
2911
2912 leaf = path->nodes[0];
2913 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
b3b4aa74 2914 btrfs_release_path(path);
4df27c4d
YZ
2915 index = key.offset;
2916 }
945d8962 2917 btrfs_release_path(path);
4df27c4d 2918
16cdcec7 2919 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
4df27c4d 2920 BUG_ON(ret);
4df27c4d
YZ
2921
2922 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
2923 dir->i_mtime = dir->i_ctime = CURRENT_TIME;
2924 ret = btrfs_update_inode(trans, root, dir);
2925 BUG_ON(ret);
4df27c4d 2926
71d7aed0 2927 btrfs_free_path(path);
4df27c4d
YZ
2928 return 0;
2929}
2930
39279cc3
CM
2931static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
2932{
2933 struct inode *inode = dentry->d_inode;
1832a6d5 2934 int err = 0;
39279cc3 2935 struct btrfs_root *root = BTRFS_I(dir)->root;
39279cc3 2936 struct btrfs_trans_handle *trans;
1832a6d5 2937 unsigned long nr = 0;
39279cc3 2938
3394e160 2939 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE ||
33345d01 2940 btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID)
134d4512
Y
2941 return -ENOTEMPTY;
2942
a22285a6
YZ
2943 trans = __unlink_start_trans(dir, dentry);
2944 if (IS_ERR(trans))
5df6a9f6 2945 return PTR_ERR(trans);
5df6a9f6 2946
33345d01 2947 if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4df27c4d
YZ
2948 err = btrfs_unlink_subvol(trans, root, dir,
2949 BTRFS_I(inode)->location.objectid,
2950 dentry->d_name.name,
2951 dentry->d_name.len);
2952 goto out;
2953 }
2954
7b128766
JB
2955 err = btrfs_orphan_add(trans, inode);
2956 if (err)
4df27c4d 2957 goto out;
7b128766 2958
39279cc3 2959 /* now the directory is empty */
e02119d5
CM
2960 err = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
2961 dentry->d_name.name, dentry->d_name.len);
d397712b 2962 if (!err)
dbe674a9 2963 btrfs_i_size_write(inode, 0);
4df27c4d 2964out:
d3c2fdcf 2965 nr = trans->blocks_used;
a22285a6 2966 __unlink_end_trans(trans, root);
d3c2fdcf 2967 btrfs_btree_balance_dirty(root, nr);
3954401f 2968
39279cc3
CM
2969 return err;
2970}
2971
39279cc3
CM
2972/*
2973 * this can truncate away extent items, csum items and directory items.
2974 * It starts at a high offset and removes keys until it can't find
d352ac68 2975 * any higher than new_size
39279cc3
CM
2976 *
2977 * csum items that cross the new i_size are truncated to the new size
2978 * as well.
7b128766
JB
2979 *
2980 * min_type is the minimum key type to truncate down to. If set to 0, this
2981 * will kill all the items on this inode, including the INODE_ITEM_KEY.
39279cc3 2982 */
8082510e
YZ
2983int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
2984 struct btrfs_root *root,
2985 struct inode *inode,
2986 u64 new_size, u32 min_type)
39279cc3 2987{
39279cc3 2988 struct btrfs_path *path;
5f39d397 2989 struct extent_buffer *leaf;
39279cc3 2990 struct btrfs_file_extent_item *fi;
8082510e
YZ
2991 struct btrfs_key key;
2992 struct btrfs_key found_key;
39279cc3 2993 u64 extent_start = 0;
db94535d 2994 u64 extent_num_bytes = 0;
5d4f98a2 2995 u64 extent_offset = 0;
39279cc3 2996 u64 item_end = 0;
8082510e
YZ
2997 u64 mask = root->sectorsize - 1;
2998 u32 found_type = (u8)-1;
39279cc3
CM
2999 int found_extent;
3000 int del_item;
85e21bac
CM
3001 int pending_del_nr = 0;
3002 int pending_del_slot = 0;
179e29e4 3003 int extent_type = -1;
771ed689 3004 int encoding;
8082510e
YZ
3005 int ret;
3006 int err = 0;
33345d01 3007 u64 ino = btrfs_ino(inode);
8082510e
YZ
3008
3009 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
39279cc3 3010
0eb0e19c
MF
3011 path = btrfs_alloc_path();
3012 if (!path)
3013 return -ENOMEM;
3014 path->reada = -1;
3015
0af3d00b 3016 if (root->ref_cows || root == root->fs_info->tree_root)
5b21f2ed 3017 btrfs_drop_extent_cache(inode, new_size & (~mask), (u64)-1, 0);
8082510e 3018
16cdcec7
MX
3019 /*
3020 * This function is also used to drop the items in the log tree before
3021 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
3022 * it is used to drop the loged items. So we shouldn't kill the delayed
3023 * items.
3024 */
3025 if (min_type == 0 && root == BTRFS_I(inode)->root)
3026 btrfs_kill_delayed_inode_items(inode);
3027
33345d01 3028 key.objectid = ino;
39279cc3 3029 key.offset = (u64)-1;
5f39d397
CM
3030 key.type = (u8)-1;
3031
85e21bac 3032search_again:
b9473439 3033 path->leave_spinning = 1;
85e21bac 3034 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
8082510e
YZ
3035 if (ret < 0) {
3036 err = ret;
3037 goto out;
3038 }
d397712b 3039
85e21bac 3040 if (ret > 0) {
e02119d5
CM
3041 /* there are no items in the tree for us to truncate, we're
3042 * done
3043 */
8082510e
YZ
3044 if (path->slots[0] == 0)
3045 goto out;
85e21bac
CM
3046 path->slots[0]--;
3047 }
3048
d397712b 3049 while (1) {
39279cc3 3050 fi = NULL;
5f39d397
CM
3051 leaf = path->nodes[0];
3052 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3053 found_type = btrfs_key_type(&found_key);
771ed689 3054 encoding = 0;
39279cc3 3055
33345d01 3056 if (found_key.objectid != ino)
39279cc3 3057 break;
5f39d397 3058
85e21bac 3059 if (found_type < min_type)
39279cc3
CM
3060 break;
3061
5f39d397 3062 item_end = found_key.offset;
39279cc3 3063 if (found_type == BTRFS_EXTENT_DATA_KEY) {
5f39d397 3064 fi = btrfs_item_ptr(leaf, path->slots[0],
39279cc3 3065 struct btrfs_file_extent_item);
179e29e4 3066 extent_type = btrfs_file_extent_type(leaf, fi);
771ed689
CM
3067 encoding = btrfs_file_extent_compression(leaf, fi);
3068 encoding |= btrfs_file_extent_encryption(leaf, fi);
3069 encoding |= btrfs_file_extent_other_encoding(leaf, fi);
3070
179e29e4 3071 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
5f39d397 3072 item_end +=
db94535d 3073 btrfs_file_extent_num_bytes(leaf, fi);
179e29e4 3074 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
179e29e4 3075 item_end += btrfs_file_extent_inline_len(leaf,
c8b97818 3076 fi);
39279cc3 3077 }
008630c1 3078 item_end--;
39279cc3 3079 }
8082510e
YZ
3080 if (found_type > min_type) {
3081 del_item = 1;
3082 } else {
3083 if (item_end < new_size)
b888db2b 3084 break;
8082510e
YZ
3085 if (found_key.offset >= new_size)
3086 del_item = 1;
3087 else
3088 del_item = 0;
39279cc3 3089 }
39279cc3 3090 found_extent = 0;
39279cc3 3091 /* FIXME, shrink the extent if the ref count is only 1 */
179e29e4
CM
3092 if (found_type != BTRFS_EXTENT_DATA_KEY)
3093 goto delete;
3094
3095 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
39279cc3 3096 u64 num_dec;
db94535d 3097 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
771ed689 3098 if (!del_item && !encoding) {
db94535d
CM
3099 u64 orig_num_bytes =
3100 btrfs_file_extent_num_bytes(leaf, fi);
e02119d5 3101 extent_num_bytes = new_size -
5f39d397 3102 found_key.offset + root->sectorsize - 1;
b1632b10
Y
3103 extent_num_bytes = extent_num_bytes &
3104 ~((u64)root->sectorsize - 1);
db94535d
CM
3105 btrfs_set_file_extent_num_bytes(leaf, fi,
3106 extent_num_bytes);
3107 num_dec = (orig_num_bytes -
9069218d 3108 extent_num_bytes);
e02119d5 3109 if (root->ref_cows && extent_start != 0)
a76a3cd4 3110 inode_sub_bytes(inode, num_dec);
5f39d397 3111 btrfs_mark_buffer_dirty(leaf);
39279cc3 3112 } else {
db94535d
CM
3113 extent_num_bytes =
3114 btrfs_file_extent_disk_num_bytes(leaf,
3115 fi);
5d4f98a2
YZ
3116 extent_offset = found_key.offset -
3117 btrfs_file_extent_offset(leaf, fi);
3118
39279cc3 3119 /* FIXME blocksize != 4096 */
9069218d 3120 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
39279cc3
CM
3121 if (extent_start != 0) {
3122 found_extent = 1;
e02119d5 3123 if (root->ref_cows)
a76a3cd4 3124 inode_sub_bytes(inode, num_dec);
e02119d5 3125 }
39279cc3 3126 }
9069218d 3127 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
c8b97818
CM
3128 /*
3129 * we can't truncate inline items that have had
3130 * special encodings
3131 */
3132 if (!del_item &&
3133 btrfs_file_extent_compression(leaf, fi) == 0 &&
3134 btrfs_file_extent_encryption(leaf, fi) == 0 &&
3135 btrfs_file_extent_other_encoding(leaf, fi) == 0) {
e02119d5
CM
3136 u32 size = new_size - found_key.offset;
3137
3138 if (root->ref_cows) {
a76a3cd4
YZ
3139 inode_sub_bytes(inode, item_end + 1 -
3140 new_size);
e02119d5
CM
3141 }
3142 size =
3143 btrfs_file_extent_calc_inline_size(size);
9069218d 3144 ret = btrfs_truncate_item(trans, root, path,
e02119d5 3145 size, 1);
e02119d5 3146 } else if (root->ref_cows) {
a76a3cd4
YZ
3147 inode_sub_bytes(inode, item_end + 1 -
3148 found_key.offset);
9069218d 3149 }
39279cc3 3150 }
179e29e4 3151delete:
39279cc3 3152 if (del_item) {
85e21bac
CM
3153 if (!pending_del_nr) {
3154 /* no pending yet, add ourselves */
3155 pending_del_slot = path->slots[0];
3156 pending_del_nr = 1;
3157 } else if (pending_del_nr &&
3158 path->slots[0] + 1 == pending_del_slot) {
3159 /* hop on the pending chunk */
3160 pending_del_nr++;
3161 pending_del_slot = path->slots[0];
3162 } else {
d397712b 3163 BUG();
85e21bac 3164 }
39279cc3
CM
3165 } else {
3166 break;
3167 }
0af3d00b
JB
3168 if (found_extent && (root->ref_cows ||
3169 root == root->fs_info->tree_root)) {
b9473439 3170 btrfs_set_path_blocking(path);
39279cc3 3171 ret = btrfs_free_extent(trans, root, extent_start,
5d4f98a2
YZ
3172 extent_num_bytes, 0,
3173 btrfs_header_owner(leaf),
33345d01 3174 ino, extent_offset);
39279cc3
CM
3175 BUG_ON(ret);
3176 }
85e21bac 3177
8082510e
YZ
3178 if (found_type == BTRFS_INODE_ITEM_KEY)
3179 break;
3180
3181 if (path->slots[0] == 0 ||
3182 path->slots[0] != pending_del_slot) {
82d5902d
LZ
3183 if (root->ref_cows &&
3184 BTRFS_I(inode)->location.objectid !=
3185 BTRFS_FREE_INO_OBJECTID) {
8082510e
YZ
3186 err = -EAGAIN;
3187 goto out;
3188 }
3189 if (pending_del_nr) {
3190 ret = btrfs_del_items(trans, root, path,
3191 pending_del_slot,
3192 pending_del_nr);
3193 BUG_ON(ret);
3194 pending_del_nr = 0;
3195 }
b3b4aa74 3196 btrfs_release_path(path);
85e21bac 3197 goto search_again;
8082510e
YZ
3198 } else {
3199 path->slots[0]--;
85e21bac 3200 }
39279cc3 3201 }
8082510e 3202out:
85e21bac
CM
3203 if (pending_del_nr) {
3204 ret = btrfs_del_items(trans, root, path, pending_del_slot,
3205 pending_del_nr);
d68fc57b 3206 BUG_ON(ret);
85e21bac 3207 }
39279cc3 3208 btrfs_free_path(path);
8082510e 3209 return err;
39279cc3
CM
3210}
3211
3212/*
3213 * taken from block_truncate_page, but does cow as it zeros out
3214 * any bytes left in the last page in the file.
3215 */
3216static int btrfs_truncate_page(struct address_space *mapping, loff_t from)
3217{
3218 struct inode *inode = mapping->host;
db94535d 3219 struct btrfs_root *root = BTRFS_I(inode)->root;
e6dcd2dc
CM
3220 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3221 struct btrfs_ordered_extent *ordered;
2ac55d41 3222 struct extent_state *cached_state = NULL;
e6dcd2dc 3223 char *kaddr;
db94535d 3224 u32 blocksize = root->sectorsize;
39279cc3
CM
3225 pgoff_t index = from >> PAGE_CACHE_SHIFT;
3226 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3227 struct page *page;
3b16a4e3 3228 gfp_t mask = btrfs_alloc_write_mask(mapping);
39279cc3 3229 int ret = 0;
a52d9a80 3230 u64 page_start;
e6dcd2dc 3231 u64 page_end;
39279cc3
CM
3232
3233 if ((offset & (blocksize - 1)) == 0)
3234 goto out;
0ca1f7ce 3235 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
5d5e103a
JB
3236 if (ret)
3237 goto out;
39279cc3
CM
3238
3239 ret = -ENOMEM;
211c17f5 3240again:
3b16a4e3 3241 page = find_or_create_page(mapping, index, mask);
5d5e103a 3242 if (!page) {
0ca1f7ce 3243 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
39279cc3 3244 goto out;
5d5e103a 3245 }
e6dcd2dc
CM
3246
3247 page_start = page_offset(page);
3248 page_end = page_start + PAGE_CACHE_SIZE - 1;
3249
39279cc3 3250 if (!PageUptodate(page)) {
9ebefb18 3251 ret = btrfs_readpage(NULL, page);
39279cc3 3252 lock_page(page);
211c17f5
CM
3253 if (page->mapping != mapping) {
3254 unlock_page(page);
3255 page_cache_release(page);
3256 goto again;
3257 }
39279cc3
CM
3258 if (!PageUptodate(page)) {
3259 ret = -EIO;
89642229 3260 goto out_unlock;
39279cc3
CM
3261 }
3262 }
211c17f5 3263 wait_on_page_writeback(page);
e6dcd2dc 3264
2ac55d41
JB
3265 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state,
3266 GFP_NOFS);
e6dcd2dc
CM
3267 set_page_extent_mapped(page);
3268
3269 ordered = btrfs_lookup_ordered_extent(inode, page_start);
3270 if (ordered) {
2ac55d41
JB
3271 unlock_extent_cached(io_tree, page_start, page_end,
3272 &cached_state, GFP_NOFS);
e6dcd2dc
CM
3273 unlock_page(page);
3274 page_cache_release(page);
eb84ae03 3275 btrfs_start_ordered_extent(inode, ordered, 1);
e6dcd2dc
CM
3276 btrfs_put_ordered_extent(ordered);
3277 goto again;
3278 }
3279
2ac55d41 3280 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
5d5e103a 3281 EXTENT_DIRTY | EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING,
2ac55d41 3282 0, 0, &cached_state, GFP_NOFS);
5d5e103a 3283
2ac55d41
JB
3284 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
3285 &cached_state);
9ed74f2d 3286 if (ret) {
2ac55d41
JB
3287 unlock_extent_cached(io_tree, page_start, page_end,
3288 &cached_state, GFP_NOFS);
9ed74f2d
JB
3289 goto out_unlock;
3290 }
3291
e6dcd2dc
CM
3292 ret = 0;
3293 if (offset != PAGE_CACHE_SIZE) {
3294 kaddr = kmap(page);
3295 memset(kaddr + offset, 0, PAGE_CACHE_SIZE - offset);
3296 flush_dcache_page(page);
3297 kunmap(page);
3298 }
247e743c 3299 ClearPageChecked(page);
e6dcd2dc 3300 set_page_dirty(page);
2ac55d41
JB
3301 unlock_extent_cached(io_tree, page_start, page_end, &cached_state,
3302 GFP_NOFS);
39279cc3 3303
89642229 3304out_unlock:
5d5e103a 3305 if (ret)
0ca1f7ce 3306 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
39279cc3
CM
3307 unlock_page(page);
3308 page_cache_release(page);
3309out:
3310 return ret;
3311}
3312
695a0d0d
JB
3313/*
3314 * This function puts in dummy file extents for the area we're creating a hole
3315 * for. So if we are truncating this file to a larger size we need to insert
3316 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
3317 * the range between oldsize and size
3318 */
a41ad394 3319int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
39279cc3 3320{
9036c102
YZ
3321 struct btrfs_trans_handle *trans;
3322 struct btrfs_root *root = BTRFS_I(inode)->root;
3323 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
a22285a6 3324 struct extent_map *em = NULL;
2ac55d41 3325 struct extent_state *cached_state = NULL;
9036c102 3326 u64 mask = root->sectorsize - 1;
a41ad394 3327 u64 hole_start = (oldsize + mask) & ~mask;
9036c102
YZ
3328 u64 block_end = (size + mask) & ~mask;
3329 u64 last_byte;
3330 u64 cur_offset;
3331 u64 hole_size;
9ed74f2d 3332 int err = 0;
39279cc3 3333
9036c102
YZ
3334 if (size <= hole_start)
3335 return 0;
3336
9036c102
YZ
3337 while (1) {
3338 struct btrfs_ordered_extent *ordered;
3339 btrfs_wait_ordered_range(inode, hole_start,
3340 block_end - hole_start);
2ac55d41
JB
3341 lock_extent_bits(io_tree, hole_start, block_end - 1, 0,
3342 &cached_state, GFP_NOFS);
9036c102
YZ
3343 ordered = btrfs_lookup_ordered_extent(inode, hole_start);
3344 if (!ordered)
3345 break;
2ac55d41
JB
3346 unlock_extent_cached(io_tree, hole_start, block_end - 1,
3347 &cached_state, GFP_NOFS);
9036c102
YZ
3348 btrfs_put_ordered_extent(ordered);
3349 }
39279cc3 3350
9036c102
YZ
3351 cur_offset = hole_start;
3352 while (1) {
3353 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
3354 block_end - cur_offset, 0);
c704005d 3355 BUG_ON(IS_ERR_OR_NULL(em));
9036c102
YZ
3356 last_byte = min(extent_map_end(em), block_end);
3357 last_byte = (last_byte + mask) & ~mask;
8082510e 3358 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
771ed689 3359 u64 hint_byte = 0;
9036c102 3360 hole_size = last_byte - cur_offset;
9ed74f2d 3361
3642320e 3362 trans = btrfs_start_transaction(root, 3);
a22285a6
YZ
3363 if (IS_ERR(trans)) {
3364 err = PTR_ERR(trans);
9ed74f2d 3365 break;
a22285a6 3366 }
8082510e
YZ
3367
3368 err = btrfs_drop_extents(trans, inode, cur_offset,
3369 cur_offset + hole_size,
3370 &hint_byte, 1);
5b397377 3371 if (err) {
3642320e 3372 btrfs_update_inode(trans, root, inode);
5b397377 3373 btrfs_end_transaction(trans, root);
3893e33b 3374 break;
5b397377 3375 }
8082510e 3376
9036c102 3377 err = btrfs_insert_file_extent(trans, root,
33345d01 3378 btrfs_ino(inode), cur_offset, 0,
9036c102
YZ
3379 0, hole_size, 0, hole_size,
3380 0, 0, 0);
5b397377 3381 if (err) {
3642320e 3382 btrfs_update_inode(trans, root, inode);
5b397377 3383 btrfs_end_transaction(trans, root);
3893e33b 3384 break;
5b397377 3385 }
8082510e 3386
9036c102
YZ
3387 btrfs_drop_extent_cache(inode, hole_start,
3388 last_byte - 1, 0);
8082510e 3389
3642320e 3390 btrfs_update_inode(trans, root, inode);
8082510e 3391 btrfs_end_transaction(trans, root);
9036c102
YZ
3392 }
3393 free_extent_map(em);
a22285a6 3394 em = NULL;
9036c102 3395 cur_offset = last_byte;
8082510e 3396 if (cur_offset >= block_end)
9036c102
YZ
3397 break;
3398 }
1832a6d5 3399
a22285a6 3400 free_extent_map(em);
2ac55d41
JB
3401 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
3402 GFP_NOFS);
9036c102
YZ
3403 return err;
3404}
39279cc3 3405
a41ad394 3406static int btrfs_setsize(struct inode *inode, loff_t newsize)
8082510e 3407{
f4a2f4c5
MX
3408 struct btrfs_root *root = BTRFS_I(inode)->root;
3409 struct btrfs_trans_handle *trans;
a41ad394 3410 loff_t oldsize = i_size_read(inode);
8082510e
YZ
3411 int ret;
3412
a41ad394 3413 if (newsize == oldsize)
8082510e
YZ
3414 return 0;
3415
a41ad394 3416 if (newsize > oldsize) {
a41ad394
JB
3417 truncate_pagecache(inode, oldsize, newsize);
3418 ret = btrfs_cont_expand(inode, oldsize, newsize);
f4a2f4c5 3419 if (ret)
8082510e 3420 return ret;
8082510e 3421
f4a2f4c5
MX
3422 trans = btrfs_start_transaction(root, 1);
3423 if (IS_ERR(trans))
3424 return PTR_ERR(trans);
3425
3426 i_size_write(inode, newsize);
3427 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
3428 ret = btrfs_update_inode(trans, root, inode);
3429
3430 btrfs_end_transaction_throttle(trans, root);
a41ad394 3431 } else {
8082510e 3432
a41ad394
JB
3433 /*
3434 * We're truncating a file that used to have good data down to
3435 * zero. Make sure it gets into the ordered flush list so that
3436 * any new writes get down to disk quickly.
3437 */
3438 if (newsize == 0)
3439 BTRFS_I(inode)->ordered_data_close = 1;
8082510e 3440
a41ad394
JB
3441 /* we don't support swapfiles, so vmtruncate shouldn't fail */
3442 truncate_setsize(inode, newsize);
3443 ret = btrfs_truncate(inode);
8082510e
YZ
3444 }
3445
a41ad394 3446 return ret;
8082510e
YZ
3447}
3448
9036c102
YZ
3449static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
3450{
3451 struct inode *inode = dentry->d_inode;
b83cc969 3452 struct btrfs_root *root = BTRFS_I(inode)->root;
9036c102 3453 int err;
39279cc3 3454
b83cc969
LZ
3455 if (btrfs_root_readonly(root))
3456 return -EROFS;
3457
9036c102
YZ
3458 err = inode_change_ok(inode, attr);
3459 if (err)
3460 return err;
2bf5a725 3461
5a3f23d5 3462 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
a41ad394 3463 err = btrfs_setsize(inode, attr->ia_size);
8082510e
YZ
3464 if (err)
3465 return err;
39279cc3 3466 }
9036c102 3467
1025774c
CH
3468 if (attr->ia_valid) {
3469 setattr_copy(inode, attr);
3470 mark_inode_dirty(inode);
3471
3472 if (attr->ia_valid & ATTR_MODE)
3473 err = btrfs_acl_chmod(inode);
3474 }
33268eaf 3475
39279cc3
CM
3476 return err;
3477}
61295eb8 3478
bd555975 3479void btrfs_evict_inode(struct inode *inode)
39279cc3
CM
3480{
3481 struct btrfs_trans_handle *trans;
3482 struct btrfs_root *root = BTRFS_I(inode)->root;
726c35fa 3483 struct btrfs_block_rsv *rsv, *global_rsv;
07127184 3484 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
d3c2fdcf 3485 unsigned long nr;
39279cc3
CM
3486 int ret;
3487
1abe9b8a 3488 trace_btrfs_inode_evict(inode);
3489
39279cc3 3490 truncate_inode_pages(&inode->i_data, 0);
0af3d00b 3491 if (inode->i_nlink && (btrfs_root_refs(&root->root_item) != 0 ||
2cf8572d 3492 btrfs_is_free_space_inode(root, inode)))
bd555975
AV
3493 goto no_delete;
3494
39279cc3 3495 if (is_bad_inode(inode)) {
7b128766 3496 btrfs_orphan_del(NULL, inode);
39279cc3
CM
3497 goto no_delete;
3498 }
bd555975 3499 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
4a096752 3500 btrfs_wait_ordered_range(inode, 0, (u64)-1);
5f39d397 3501
c71bf099
YZ
3502 if (root->fs_info->log_root_recovering) {
3503 BUG_ON(!list_empty(&BTRFS_I(inode)->i_orphan));
3504 goto no_delete;
3505 }
3506
76dda93c
YZ
3507 if (inode->i_nlink > 0) {
3508 BUG_ON(btrfs_root_refs(&root->root_item) != 0);
3509 goto no_delete;
3510 }
3511
4289a667
JB
3512 rsv = btrfs_alloc_block_rsv(root);
3513 if (!rsv) {
3514 btrfs_orphan_del(NULL, inode);
3515 goto no_delete;
3516 }
4a338542 3517 rsv->size = min_size;
726c35fa 3518 global_rsv = &root->fs_info->global_block_rsv;
4289a667 3519
dbe674a9 3520 btrfs_i_size_write(inode, 0);
5f39d397 3521
4289a667
JB
3522 /*
3523 * This is a bit simpler than btrfs_truncate since
3524 *
3525 * 1) We've already reserved our space for our orphan item in the
3526 * unlink.
3527 * 2) We're going to delete the inode item, so we don't need to update
3528 * it at all.
3529 *
3530 * So we just need to reserve some slack space in case we add bytes when
3531 * doing the truncate.
3532 */
8082510e 3533 while (1) {
aa38a711 3534 ret = btrfs_block_rsv_refill_noflush(root, rsv, min_size);
726c35fa
JB
3535
3536 /*
3537 * Try and steal from the global reserve since we will
3538 * likely not use this space anyway, we want to try as
3539 * hard as possible to get this to work.
3540 */
3541 if (ret)
3542 ret = btrfs_block_rsv_migrate(global_rsv, rsv, min_size);
3543
d68fc57b 3544 if (ret) {
4289a667 3545 printk(KERN_WARNING "Could not get space for a "
482e6dc5 3546 "delete, will truncate on mount %d\n", ret);
4289a667
JB
3547 btrfs_orphan_del(NULL, inode);
3548 btrfs_free_block_rsv(root, rsv);
3549 goto no_delete;
3550 }
3551
3552 trans = btrfs_start_transaction(root, 0);
3553 if (IS_ERR(trans)) {
3554 btrfs_orphan_del(NULL, inode);
3555 btrfs_free_block_rsv(root, rsv);
3556 goto no_delete;
d68fc57b 3557 }
7b128766 3558
4289a667
JB
3559 trans->block_rsv = rsv;
3560
d68fc57b 3561 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
8082510e
YZ
3562 if (ret != -EAGAIN)
3563 break;
85e21bac 3564
8082510e
YZ
3565 nr = trans->blocks_used;
3566 btrfs_end_transaction(trans, root);
3567 trans = NULL;
3568 btrfs_btree_balance_dirty(root, nr);
3569 }
5f39d397 3570
4289a667
JB
3571 btrfs_free_block_rsv(root, rsv);
3572
8082510e 3573 if (ret == 0) {
4289a667 3574 trans->block_rsv = root->orphan_block_rsv;
8082510e
YZ
3575 ret = btrfs_orphan_del(trans, inode);
3576 BUG_ON(ret);
3577 }
54aa1f4d 3578
4289a667 3579 trans->block_rsv = &root->fs_info->trans_block_rsv;
581bb050
LZ
3580 if (!(root == root->fs_info->tree_root ||
3581 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
33345d01 3582 btrfs_return_ino(root, btrfs_ino(inode));
581bb050 3583
d3c2fdcf 3584 nr = trans->blocks_used;
54aa1f4d 3585 btrfs_end_transaction(trans, root);
d3c2fdcf 3586 btrfs_btree_balance_dirty(root, nr);
39279cc3 3587no_delete:
bd555975 3588 end_writeback(inode);
8082510e 3589 return;
39279cc3
CM
3590}
3591
3592/*
3593 * this returns the key found in the dir entry in the location pointer.
3594 * If no dir entries were found, location->objectid is 0.
3595 */
3596static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
3597 struct btrfs_key *location)
3598{
3599 const char *name = dentry->d_name.name;
3600 int namelen = dentry->d_name.len;
3601 struct btrfs_dir_item *di;
3602 struct btrfs_path *path;
3603 struct btrfs_root *root = BTRFS_I(dir)->root;
0d9f7f3e 3604 int ret = 0;
39279cc3
CM
3605
3606 path = btrfs_alloc_path();
d8926bb3
MF
3607 if (!path)
3608 return -ENOMEM;
3954401f 3609
33345d01 3610 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir), name,
39279cc3 3611 namelen, 0);
0d9f7f3e
Y
3612 if (IS_ERR(di))
3613 ret = PTR_ERR(di);
d397712b 3614
c704005d 3615 if (IS_ERR_OR_NULL(di))
3954401f 3616 goto out_err;
d397712b 3617
5f39d397 3618 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
39279cc3 3619out:
39279cc3
CM
3620 btrfs_free_path(path);
3621 return ret;
3954401f
CM
3622out_err:
3623 location->objectid = 0;
3624 goto out;
39279cc3
CM
3625}
3626
3627/*
3628 * when we hit a tree root in a directory, the btrfs part of the inode
3629 * needs to be changed to reflect the root directory of the tree root. This
3630 * is kind of like crossing a mount point.
3631 */
3632static int fixup_tree_root_location(struct btrfs_root *root,
4df27c4d
YZ
3633 struct inode *dir,
3634 struct dentry *dentry,
3635 struct btrfs_key *location,
3636 struct btrfs_root **sub_root)
39279cc3 3637{
4df27c4d
YZ
3638 struct btrfs_path *path;
3639 struct btrfs_root *new_root;
3640 struct btrfs_root_ref *ref;
3641 struct extent_buffer *leaf;
3642 int ret;
3643 int err = 0;
39279cc3 3644
4df27c4d
YZ
3645 path = btrfs_alloc_path();
3646 if (!path) {
3647 err = -ENOMEM;
3648 goto out;
3649 }
39279cc3 3650
4df27c4d
YZ
3651 err = -ENOENT;
3652 ret = btrfs_find_root_ref(root->fs_info->tree_root, path,
3653 BTRFS_I(dir)->root->root_key.objectid,
3654 location->objectid);
3655 if (ret) {
3656 if (ret < 0)
3657 err = ret;
3658 goto out;
3659 }
39279cc3 3660
4df27c4d
YZ
3661 leaf = path->nodes[0];
3662 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
33345d01 3663 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
4df27c4d
YZ
3664 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
3665 goto out;
39279cc3 3666
4df27c4d
YZ
3667 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
3668 (unsigned long)(ref + 1),
3669 dentry->d_name.len);
3670 if (ret)
3671 goto out;
3672
b3b4aa74 3673 btrfs_release_path(path);
4df27c4d
YZ
3674
3675 new_root = btrfs_read_fs_root_no_name(root->fs_info, location);
3676 if (IS_ERR(new_root)) {
3677 err = PTR_ERR(new_root);
3678 goto out;
3679 }
3680
3681 if (btrfs_root_refs(&new_root->root_item) == 0) {
3682 err = -ENOENT;
3683 goto out;
3684 }
3685
3686 *sub_root = new_root;
3687 location->objectid = btrfs_root_dirid(&new_root->root_item);
3688 location->type = BTRFS_INODE_ITEM_KEY;
3689 location->offset = 0;
3690 err = 0;
3691out:
3692 btrfs_free_path(path);
3693 return err;
39279cc3
CM
3694}
3695
5d4f98a2
YZ
3696static void inode_tree_add(struct inode *inode)
3697{
3698 struct btrfs_root *root = BTRFS_I(inode)->root;
3699 struct btrfs_inode *entry;
03e860bd
FNP
3700 struct rb_node **p;
3701 struct rb_node *parent;
33345d01 3702 u64 ino = btrfs_ino(inode);
03e860bd
FNP
3703again:
3704 p = &root->inode_tree.rb_node;
3705 parent = NULL;
5d4f98a2 3706
1d3382cb 3707 if (inode_unhashed(inode))
76dda93c
YZ
3708 return;
3709
5d4f98a2
YZ
3710 spin_lock(&root->inode_lock);
3711 while (*p) {
3712 parent = *p;
3713 entry = rb_entry(parent, struct btrfs_inode, rb_node);
3714
33345d01 3715 if (ino < btrfs_ino(&entry->vfs_inode))
03e860bd 3716 p = &parent->rb_left;
33345d01 3717 else if (ino > btrfs_ino(&entry->vfs_inode))
03e860bd 3718 p = &parent->rb_right;
5d4f98a2
YZ
3719 else {
3720 WARN_ON(!(entry->vfs_inode.i_state &
a4ffdde6 3721 (I_WILL_FREE | I_FREEING)));
03e860bd
FNP
3722 rb_erase(parent, &root->inode_tree);
3723 RB_CLEAR_NODE(parent);
3724 spin_unlock(&root->inode_lock);
3725 goto again;
5d4f98a2
YZ
3726 }
3727 }
3728 rb_link_node(&BTRFS_I(inode)->rb_node, parent, p);
3729 rb_insert_color(&BTRFS_I(inode)->rb_node, &root->inode_tree);
3730 spin_unlock(&root->inode_lock);
3731}
3732
3733static void inode_tree_del(struct inode *inode)
3734{
3735 struct btrfs_root *root = BTRFS_I(inode)->root;
76dda93c 3736 int empty = 0;
5d4f98a2 3737
03e860bd 3738 spin_lock(&root->inode_lock);
5d4f98a2 3739 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5d4f98a2 3740 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5d4f98a2 3741 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
76dda93c 3742 empty = RB_EMPTY_ROOT(&root->inode_tree);
5d4f98a2 3743 }
03e860bd 3744 spin_unlock(&root->inode_lock);
76dda93c 3745
0af3d00b
JB
3746 /*
3747 * Free space cache has inodes in the tree root, but the tree root has a
3748 * root_refs of 0, so this could end up dropping the tree root as a
3749 * snapshot, so we need the extra !root->fs_info->tree_root check to
3750 * make sure we don't drop it.
3751 */
3752 if (empty && btrfs_root_refs(&root->root_item) == 0 &&
3753 root != root->fs_info->tree_root) {
76dda93c
YZ
3754 synchronize_srcu(&root->fs_info->subvol_srcu);
3755 spin_lock(&root->inode_lock);
3756 empty = RB_EMPTY_ROOT(&root->inode_tree);
3757 spin_unlock(&root->inode_lock);
3758 if (empty)
3759 btrfs_add_dead_root(root);
3760 }
3761}
3762
3763int btrfs_invalidate_inodes(struct btrfs_root *root)
3764{
3765 struct rb_node *node;
3766 struct rb_node *prev;
3767 struct btrfs_inode *entry;
3768 struct inode *inode;
3769 u64 objectid = 0;
3770
3771 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
3772
3773 spin_lock(&root->inode_lock);
3774again:
3775 node = root->inode_tree.rb_node;
3776 prev = NULL;
3777 while (node) {
3778 prev = node;
3779 entry = rb_entry(node, struct btrfs_inode, rb_node);
3780
33345d01 3781 if (objectid < btrfs_ino(&entry->vfs_inode))
76dda93c 3782 node = node->rb_left;
33345d01 3783 else if (objectid > btrfs_ino(&entry->vfs_inode))
76dda93c
YZ
3784 node = node->rb_right;
3785 else
3786 break;
3787 }
3788 if (!node) {
3789 while (prev) {
3790 entry = rb_entry(prev, struct btrfs_inode, rb_node);
33345d01 3791 if (objectid <= btrfs_ino(&entry->vfs_inode)) {
76dda93c
YZ
3792 node = prev;
3793 break;
3794 }
3795 prev = rb_next(prev);
3796 }
3797 }
3798 while (node) {
3799 entry = rb_entry(node, struct btrfs_inode, rb_node);
33345d01 3800 objectid = btrfs_ino(&entry->vfs_inode) + 1;
76dda93c
YZ
3801 inode = igrab(&entry->vfs_inode);
3802 if (inode) {
3803 spin_unlock(&root->inode_lock);
3804 if (atomic_read(&inode->i_count) > 1)
3805 d_prune_aliases(inode);
3806 /*
45321ac5 3807 * btrfs_drop_inode will have it removed from
76dda93c
YZ
3808 * the inode cache when its usage count
3809 * hits zero.
3810 */
3811 iput(inode);
3812 cond_resched();
3813 spin_lock(&root->inode_lock);
3814 goto again;
3815 }
3816
3817 if (cond_resched_lock(&root->inode_lock))
3818 goto again;
3819
3820 node = rb_next(node);
3821 }
3822 spin_unlock(&root->inode_lock);
3823 return 0;
5d4f98a2
YZ
3824}
3825
e02119d5
CM
3826static int btrfs_init_locked_inode(struct inode *inode, void *p)
3827{
3828 struct btrfs_iget_args *args = p;
3829 inode->i_ino = args->ino;
e02119d5 3830 BTRFS_I(inode)->root = args->root;
6a63209f 3831 btrfs_set_inode_space_info(args->root, inode);
39279cc3
CM
3832 return 0;
3833}
3834
3835static int btrfs_find_actor(struct inode *inode, void *opaque)
3836{
3837 struct btrfs_iget_args *args = opaque;
33345d01 3838 return args->ino == btrfs_ino(inode) &&
d397712b 3839 args->root == BTRFS_I(inode)->root;
39279cc3
CM
3840}
3841
5d4f98a2
YZ
3842static struct inode *btrfs_iget_locked(struct super_block *s,
3843 u64 objectid,
3844 struct btrfs_root *root)
39279cc3
CM
3845{
3846 struct inode *inode;
3847 struct btrfs_iget_args args;
3848 args.ino = objectid;
3849 args.root = root;
3850
3851 inode = iget5_locked(s, objectid, btrfs_find_actor,
3852 btrfs_init_locked_inode,
3853 (void *)&args);
3854 return inode;
3855}
3856
1a54ef8c
BR
3857/* Get an inode object given its location and corresponding root.
3858 * Returns in *is_new if the inode was read from disk
3859 */
3860struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
73f73415 3861 struct btrfs_root *root, int *new)
1a54ef8c
BR
3862{
3863 struct inode *inode;
3864
3865 inode = btrfs_iget_locked(s, location->objectid, root);
3866 if (!inode)
5d4f98a2 3867 return ERR_PTR(-ENOMEM);
1a54ef8c
BR
3868
3869 if (inode->i_state & I_NEW) {
3870 BTRFS_I(inode)->root = root;
3871 memcpy(&BTRFS_I(inode)->location, location, sizeof(*location));
3872 btrfs_read_locked_inode(inode);
1748f843
MF
3873 if (!is_bad_inode(inode)) {
3874 inode_tree_add(inode);
3875 unlock_new_inode(inode);
3876 if (new)
3877 *new = 1;
3878 } else {
e0b6d65b
ST
3879 unlock_new_inode(inode);
3880 iput(inode);
3881 inode = ERR_PTR(-ESTALE);
1748f843
MF
3882 }
3883 }
3884
1a54ef8c
BR
3885 return inode;
3886}
3887
4df27c4d
YZ
3888static struct inode *new_simple_dir(struct super_block *s,
3889 struct btrfs_key *key,
3890 struct btrfs_root *root)
3891{
3892 struct inode *inode = new_inode(s);
3893
3894 if (!inode)
3895 return ERR_PTR(-ENOMEM);
3896
4df27c4d
YZ
3897 BTRFS_I(inode)->root = root;
3898 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
3899 BTRFS_I(inode)->dummy_inode = 1;
3900
3901 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
3902 inode->i_op = &simple_dir_inode_operations;
3903 inode->i_fop = &simple_dir_operations;
3904 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
3905 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
3906
3907 return inode;
3908}
3909
3de4586c 3910struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
39279cc3 3911{
d397712b 3912 struct inode *inode;
4df27c4d 3913 struct btrfs_root *root = BTRFS_I(dir)->root;
39279cc3
CM
3914 struct btrfs_root *sub_root = root;
3915 struct btrfs_key location;
76dda93c 3916 int index;
b4aff1f8 3917 int ret = 0;
39279cc3
CM
3918
3919 if (dentry->d_name.len > BTRFS_NAME_LEN)
3920 return ERR_PTR(-ENAMETOOLONG);
5f39d397 3921
b4aff1f8
JB
3922 if (unlikely(d_need_lookup(dentry))) {
3923 memcpy(&location, dentry->d_fsdata, sizeof(struct btrfs_key));
3924 kfree(dentry->d_fsdata);
3925 dentry->d_fsdata = NULL;
a66e7cc6
JB
3926 /* This thing is hashed, drop it for now */
3927 d_drop(dentry);
b4aff1f8
JB
3928 } else {
3929 ret = btrfs_inode_by_name(dir, dentry, &location);
3930 }
5f39d397 3931
39279cc3
CM
3932 if (ret < 0)
3933 return ERR_PTR(ret);
5f39d397 3934
4df27c4d
YZ
3935 if (location.objectid == 0)
3936 return NULL;
3937
3938 if (location.type == BTRFS_INODE_ITEM_KEY) {
73f73415 3939 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
4df27c4d
YZ
3940 return inode;
3941 }
3942
3943 BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
3944
76dda93c 3945 index = srcu_read_lock(&root->fs_info->subvol_srcu);
4df27c4d
YZ
3946 ret = fixup_tree_root_location(root, dir, dentry,
3947 &location, &sub_root);
3948 if (ret < 0) {
3949 if (ret != -ENOENT)
3950 inode = ERR_PTR(ret);
3951 else
3952 inode = new_simple_dir(dir->i_sb, &location, sub_root);
3953 } else {
73f73415 3954 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
39279cc3 3955 }
76dda93c
YZ
3956 srcu_read_unlock(&root->fs_info->subvol_srcu, index);
3957
34d19bad 3958 if (!IS_ERR(inode) && root != sub_root) {
c71bf099
YZ
3959 down_read(&root->fs_info->cleanup_work_sem);
3960 if (!(inode->i_sb->s_flags & MS_RDONLY))
66b4ffd1 3961 ret = btrfs_orphan_cleanup(sub_root);
c71bf099 3962 up_read(&root->fs_info->cleanup_work_sem);
66b4ffd1
JB
3963 if (ret)
3964 inode = ERR_PTR(ret);
c71bf099
YZ
3965 }
3966
3de4586c
CM
3967 return inode;
3968}
3969
fe15ce44 3970static int btrfs_dentry_delete(const struct dentry *dentry)
76dda93c
YZ
3971{
3972 struct btrfs_root *root;
3973
efefb143
YZ
3974 if (!dentry->d_inode && !IS_ROOT(dentry))
3975 dentry = dentry->d_parent;
76dda93c 3976
efefb143
YZ
3977 if (dentry->d_inode) {
3978 root = BTRFS_I(dentry->d_inode)->root;
3979 if (btrfs_root_refs(&root->root_item) == 0)
3980 return 1;
3981 }
76dda93c
YZ
3982 return 0;
3983}
3984
b4aff1f8
JB
3985static void btrfs_dentry_release(struct dentry *dentry)
3986{
3987 if (dentry->d_fsdata)
3988 kfree(dentry->d_fsdata);
3989}
3990
3de4586c
CM
3991static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
3992 struct nameidata *nd)
3993{
a66e7cc6
JB
3994 struct dentry *ret;
3995
3996 ret = d_splice_alias(btrfs_lookup_dentry(dir, dentry), dentry);
3997 if (unlikely(d_need_lookup(dentry))) {
3998 spin_lock(&dentry->d_lock);
3999 dentry->d_flags &= ~DCACHE_NEED_LOOKUP;
4000 spin_unlock(&dentry->d_lock);
4001 }
4002 return ret;
39279cc3
CM
4003}
4004
16cdcec7 4005unsigned char btrfs_filetype_table[] = {
39279cc3
CM
4006 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
4007};
4008
cbdf5a24
DW
4009static int btrfs_real_readdir(struct file *filp, void *dirent,
4010 filldir_t filldir)
39279cc3 4011{
6da6abae 4012 struct inode *inode = filp->f_dentry->d_inode;
39279cc3
CM
4013 struct btrfs_root *root = BTRFS_I(inode)->root;
4014 struct btrfs_item *item;
4015 struct btrfs_dir_item *di;
4016 struct btrfs_key key;
5f39d397 4017 struct btrfs_key found_key;
39279cc3 4018 struct btrfs_path *path;
16cdcec7
MX
4019 struct list_head ins_list;
4020 struct list_head del_list;
b4aff1f8 4021 struct qstr q;
39279cc3 4022 int ret;
5f39d397 4023 struct extent_buffer *leaf;
39279cc3 4024 int slot;
39279cc3
CM
4025 unsigned char d_type;
4026 int over = 0;
4027 u32 di_cur;
4028 u32 di_total;
4029 u32 di_len;
4030 int key_type = BTRFS_DIR_INDEX_KEY;
5f39d397
CM
4031 char tmp_name[32];
4032 char *name_ptr;
4033 int name_len;
16cdcec7 4034 int is_curr = 0; /* filp->f_pos points to the current index? */
39279cc3
CM
4035
4036 /* FIXME, use a real flag for deciding about the key type */
4037 if (root->fs_info->tree_root == root)
4038 key_type = BTRFS_DIR_ITEM_KEY;
5f39d397 4039
3954401f
CM
4040 /* special case for "." */
4041 if (filp->f_pos == 0) {
3765fefa
HS
4042 over = filldir(dirent, ".", 1,
4043 filp->f_pos, btrfs_ino(inode), DT_DIR);
3954401f
CM
4044 if (over)
4045 return 0;
4046 filp->f_pos = 1;
4047 }
3954401f
CM
4048 /* special case for .., just use the back ref */
4049 if (filp->f_pos == 1) {
5ecc7e5d 4050 u64 pino = parent_ino(filp->f_path.dentry);
3954401f 4051 over = filldir(dirent, "..", 2,
3765fefa 4052 filp->f_pos, pino, DT_DIR);
3954401f 4053 if (over)
49593bfa 4054 return 0;
3954401f
CM
4055 filp->f_pos = 2;
4056 }
49593bfa 4057 path = btrfs_alloc_path();
16cdcec7
MX
4058 if (!path)
4059 return -ENOMEM;
ff5714cc 4060
026fd317 4061 path->reada = 1;
49593bfa 4062
16cdcec7
MX
4063 if (key_type == BTRFS_DIR_INDEX_KEY) {
4064 INIT_LIST_HEAD(&ins_list);
4065 INIT_LIST_HEAD(&del_list);
4066 btrfs_get_delayed_items(inode, &ins_list, &del_list);
4067 }
4068
39279cc3
CM
4069 btrfs_set_key_type(&key, key_type);
4070 key.offset = filp->f_pos;
33345d01 4071 key.objectid = btrfs_ino(inode);
5f39d397 4072
39279cc3
CM
4073 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4074 if (ret < 0)
4075 goto err;
49593bfa
DW
4076
4077 while (1) {
5f39d397 4078 leaf = path->nodes[0];
39279cc3 4079 slot = path->slots[0];
b9e03af0
LZ
4080 if (slot >= btrfs_header_nritems(leaf)) {
4081 ret = btrfs_next_leaf(root, path);
4082 if (ret < 0)
4083 goto err;
4084 else if (ret > 0)
4085 break;
4086 continue;
39279cc3 4087 }
3de4586c 4088
5f39d397
CM
4089 item = btrfs_item_nr(leaf, slot);
4090 btrfs_item_key_to_cpu(leaf, &found_key, slot);
4091
4092 if (found_key.objectid != key.objectid)
39279cc3 4093 break;
5f39d397 4094 if (btrfs_key_type(&found_key) != key_type)
39279cc3 4095 break;
5f39d397 4096 if (found_key.offset < filp->f_pos)
b9e03af0 4097 goto next;
16cdcec7
MX
4098 if (key_type == BTRFS_DIR_INDEX_KEY &&
4099 btrfs_should_delete_dir_index(&del_list,
4100 found_key.offset))
4101 goto next;
5f39d397
CM
4102
4103 filp->f_pos = found_key.offset;
16cdcec7 4104 is_curr = 1;
49593bfa 4105
39279cc3
CM
4106 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
4107 di_cur = 0;
5f39d397 4108 di_total = btrfs_item_size(leaf, item);
49593bfa
DW
4109
4110 while (di_cur < di_total) {
5f39d397 4111 struct btrfs_key location;
b4aff1f8 4112 struct dentry *tmp;
5f39d397 4113
22a94d44
JB
4114 if (verify_dir_item(root, leaf, di))
4115 break;
4116
5f39d397 4117 name_len = btrfs_dir_name_len(leaf, di);
49593bfa 4118 if (name_len <= sizeof(tmp_name)) {
5f39d397
CM
4119 name_ptr = tmp_name;
4120 } else {
4121 name_ptr = kmalloc(name_len, GFP_NOFS);
49593bfa
DW
4122 if (!name_ptr) {
4123 ret = -ENOMEM;
4124 goto err;
4125 }
5f39d397
CM
4126 }
4127 read_extent_buffer(leaf, name_ptr,
4128 (unsigned long)(di + 1), name_len);
4129
4130 d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
4131 btrfs_dir_item_key_to_cpu(leaf, di, &location);
3de4586c 4132
b4aff1f8
JB
4133 q.name = name_ptr;
4134 q.len = name_len;
4135 q.hash = full_name_hash(q.name, q.len);
4136 tmp = d_lookup(filp->f_dentry, &q);
4137 if (!tmp) {
4138 struct btrfs_key *newkey;
4139
4140 newkey = kzalloc(sizeof(struct btrfs_key),
4141 GFP_NOFS);
4142 if (!newkey)
4143 goto no_dentry;
4144 tmp = d_alloc(filp->f_dentry, &q);
4145 if (!tmp) {
4146 kfree(newkey);
4147 dput(tmp);
4148 goto no_dentry;
4149 }
4150 memcpy(newkey, &location,
4151 sizeof(struct btrfs_key));
4152 tmp->d_fsdata = newkey;
4153 tmp->d_flags |= DCACHE_NEED_LOOKUP;
4154 d_rehash(tmp);
4155 dput(tmp);
4156 } else {
4157 dput(tmp);
4158 }
4159no_dentry:
3de4586c
CM
4160 /* is this a reference to our own snapshot? If so
4161 * skip it
4162 */
4163 if (location.type == BTRFS_ROOT_ITEM_KEY &&
4164 location.objectid == root->root_key.objectid) {
4165 over = 0;
4166 goto skip;
4167 }
5f39d397 4168 over = filldir(dirent, name_ptr, name_len,
49593bfa 4169 found_key.offset, location.objectid,
39279cc3 4170 d_type);
5f39d397 4171
3de4586c 4172skip:
5f39d397
CM
4173 if (name_ptr != tmp_name)
4174 kfree(name_ptr);
4175
39279cc3
CM
4176 if (over)
4177 goto nopos;
5103e947 4178 di_len = btrfs_dir_name_len(leaf, di) +
49593bfa 4179 btrfs_dir_data_len(leaf, di) + sizeof(*di);
39279cc3
CM
4180 di_cur += di_len;
4181 di = (struct btrfs_dir_item *)((char *)di + di_len);
4182 }
b9e03af0
LZ
4183next:
4184 path->slots[0]++;
39279cc3 4185 }
49593bfa 4186
16cdcec7
MX
4187 if (key_type == BTRFS_DIR_INDEX_KEY) {
4188 if (is_curr)
4189 filp->f_pos++;
4190 ret = btrfs_readdir_delayed_dir_index(filp, dirent, filldir,
4191 &ins_list);
4192 if (ret)
4193 goto nopos;
4194 }
4195
49593bfa 4196 /* Reached end of directory/root. Bump pos past the last item. */
5e591a07 4197 if (key_type == BTRFS_DIR_INDEX_KEY)
406266ab
JE
4198 /*
4199 * 32-bit glibc will use getdents64, but then strtol -
4200 * so the last number we can serve is this.
4201 */
4202 filp->f_pos = 0x7fffffff;
5e591a07
YZ
4203 else
4204 filp->f_pos++;
39279cc3
CM
4205nopos:
4206 ret = 0;
4207err:
16cdcec7
MX
4208 if (key_type == BTRFS_DIR_INDEX_KEY)
4209 btrfs_put_delayed_items(&ins_list, &del_list);
39279cc3 4210 btrfs_free_path(path);
39279cc3
CM
4211 return ret;
4212}
4213
a9185b41 4214int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
39279cc3
CM
4215{
4216 struct btrfs_root *root = BTRFS_I(inode)->root;
4217 struct btrfs_trans_handle *trans;
4218 int ret = 0;
0af3d00b 4219 bool nolock = false;
39279cc3 4220
8929ecfa 4221 if (BTRFS_I(inode)->dummy_inode)
4ca8b41e
CM
4222 return 0;
4223
2cf8572d 4224 if (btrfs_fs_closing(root->fs_info) && btrfs_is_free_space_inode(root, inode))
82d5902d 4225 nolock = true;
0af3d00b 4226
a9185b41 4227 if (wbc->sync_mode == WB_SYNC_ALL) {
0af3d00b 4228 if (nolock)
7a7eaa40 4229 trans = btrfs_join_transaction_nolock(root);
0af3d00b 4230 else
7a7eaa40 4231 trans = btrfs_join_transaction(root);
3612b495
TI
4232 if (IS_ERR(trans))
4233 return PTR_ERR(trans);
0af3d00b
JB
4234 if (nolock)
4235 ret = btrfs_end_transaction_nolock(trans, root);
4236 else
4237 ret = btrfs_commit_transaction(trans, root);
39279cc3
CM
4238 }
4239 return ret;
4240}
4241
4242/*
54aa1f4d 4243 * This is somewhat expensive, updating the tree every time the
39279cc3
CM
4244 * inode changes. But, it is most likely to find the inode in cache.
4245 * FIXME, needs more benchmarking...there are no reasons other than performance
4246 * to keep or drop this code.
4247 */
aa385729 4248void btrfs_dirty_inode(struct inode *inode, int flags)
39279cc3
CM
4249{
4250 struct btrfs_root *root = BTRFS_I(inode)->root;
4251 struct btrfs_trans_handle *trans;
8929ecfa
YZ
4252 int ret;
4253
4254 if (BTRFS_I(inode)->dummy_inode)
4255 return;
39279cc3 4256
7a7eaa40 4257 trans = btrfs_join_transaction(root);
3612b495 4258 BUG_ON(IS_ERR(trans));
8929ecfa
YZ
4259
4260 ret = btrfs_update_inode(trans, root, inode);
94b60442
CM
4261 if (ret && ret == -ENOSPC) {
4262 /* whoops, lets try again with the full transaction */
4263 btrfs_end_transaction(trans, root);
4264 trans = btrfs_start_transaction(root, 1);
9aeead73 4265 if (IS_ERR(trans)) {
7a36ddec 4266 printk_ratelimited(KERN_ERR "btrfs: fail to "
33345d01
LZ
4267 "dirty inode %llu error %ld\n",
4268 (unsigned long long)btrfs_ino(inode),
4269 PTR_ERR(trans));
9aeead73
CM
4270 return;
4271 }
8929ecfa 4272
94b60442
CM
4273 ret = btrfs_update_inode(trans, root, inode);
4274 if (ret) {
7a36ddec 4275 printk_ratelimited(KERN_ERR "btrfs: fail to "
33345d01
LZ
4276 "dirty inode %llu error %d\n",
4277 (unsigned long long)btrfs_ino(inode),
4278 ret);
94b60442
CM
4279 }
4280 }
39279cc3 4281 btrfs_end_transaction(trans, root);
16cdcec7
MX
4282 if (BTRFS_I(inode)->delayed_node)
4283 btrfs_balance_delayed_items(root);
39279cc3
CM
4284}
4285
d352ac68
CM
4286/*
4287 * find the highest existing sequence number in a directory
4288 * and then set the in-memory index_cnt variable to reflect
4289 * free sequence numbers
4290 */
aec7477b
JB
4291static int btrfs_set_inode_index_count(struct inode *inode)
4292{
4293 struct btrfs_root *root = BTRFS_I(inode)->root;
4294 struct btrfs_key key, found_key;
4295 struct btrfs_path *path;
4296 struct extent_buffer *leaf;
4297 int ret;
4298
33345d01 4299 key.objectid = btrfs_ino(inode);
aec7477b
JB
4300 btrfs_set_key_type(&key, BTRFS_DIR_INDEX_KEY);
4301 key.offset = (u64)-1;
4302
4303 path = btrfs_alloc_path();
4304 if (!path)
4305 return -ENOMEM;
4306
4307 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4308 if (ret < 0)
4309 goto out;
4310 /* FIXME: we should be able to handle this */
4311 if (ret == 0)
4312 goto out;
4313 ret = 0;
4314
4315 /*
4316 * MAGIC NUMBER EXPLANATION:
4317 * since we search a directory based on f_pos we have to start at 2
4318 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
4319 * else has to start at 2
4320 */
4321 if (path->slots[0] == 0) {
4322 BTRFS_I(inode)->index_cnt = 2;
4323 goto out;
4324 }
4325
4326 path->slots[0]--;
4327
4328 leaf = path->nodes[0];
4329 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4330
33345d01 4331 if (found_key.objectid != btrfs_ino(inode) ||
aec7477b
JB
4332 btrfs_key_type(&found_key) != BTRFS_DIR_INDEX_KEY) {
4333 BTRFS_I(inode)->index_cnt = 2;
4334 goto out;
4335 }
4336
4337 BTRFS_I(inode)->index_cnt = found_key.offset + 1;
4338out:
4339 btrfs_free_path(path);
4340 return ret;
4341}
4342
d352ac68
CM
4343/*
4344 * helper to find a free sequence number in a given directory. This current
4345 * code is very simple, later versions will do smarter things in the btree
4346 */
3de4586c 4347int btrfs_set_inode_index(struct inode *dir, u64 *index)
aec7477b
JB
4348{
4349 int ret = 0;
4350
4351 if (BTRFS_I(dir)->index_cnt == (u64)-1) {
16cdcec7
MX
4352 ret = btrfs_inode_delayed_dir_index_count(dir);
4353 if (ret) {
4354 ret = btrfs_set_inode_index_count(dir);
4355 if (ret)
4356 return ret;
4357 }
aec7477b
JB
4358 }
4359
00e4e6b3 4360 *index = BTRFS_I(dir)->index_cnt;
aec7477b
JB
4361 BTRFS_I(dir)->index_cnt++;
4362
4363 return ret;
4364}
4365
39279cc3
CM
4366static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
4367 struct btrfs_root *root,
aec7477b 4368 struct inode *dir,
9c58309d 4369 const char *name, int name_len,
d82a6f1d
JB
4370 u64 ref_objectid, u64 objectid, int mode,
4371 u64 *index)
39279cc3
CM
4372{
4373 struct inode *inode;
5f39d397 4374 struct btrfs_inode_item *inode_item;
39279cc3 4375 struct btrfs_key *location;
5f39d397 4376 struct btrfs_path *path;
9c58309d
CM
4377 struct btrfs_inode_ref *ref;
4378 struct btrfs_key key[2];
4379 u32 sizes[2];
4380 unsigned long ptr;
39279cc3
CM
4381 int ret;
4382 int owner;
4383
5f39d397 4384 path = btrfs_alloc_path();
d8926bb3
MF
4385 if (!path)
4386 return ERR_PTR(-ENOMEM);
5f39d397 4387
39279cc3 4388 inode = new_inode(root->fs_info->sb);
8fb27640
YS
4389 if (!inode) {
4390 btrfs_free_path(path);
39279cc3 4391 return ERR_PTR(-ENOMEM);
8fb27640 4392 }
39279cc3 4393
581bb050
LZ
4394 /*
4395 * we have to initialize this early, so we can reclaim the inode
4396 * number if we fail afterwards in this function.
4397 */
4398 inode->i_ino = objectid;
4399
aec7477b 4400 if (dir) {
1abe9b8a 4401 trace_btrfs_inode_request(dir);
4402
3de4586c 4403 ret = btrfs_set_inode_index(dir, index);
09771430 4404 if (ret) {
8fb27640 4405 btrfs_free_path(path);
09771430 4406 iput(inode);
aec7477b 4407 return ERR_PTR(ret);
09771430 4408 }
aec7477b
JB
4409 }
4410 /*
4411 * index_cnt is ignored for everything but a dir,
4412 * btrfs_get_inode_index_count has an explanation for the magic
4413 * number
4414 */
4415 BTRFS_I(inode)->index_cnt = 2;
39279cc3 4416 BTRFS_I(inode)->root = root;
e02119d5 4417 BTRFS_I(inode)->generation = trans->transid;
76195853 4418 inode->i_generation = BTRFS_I(inode)->generation;
6a63209f 4419 btrfs_set_inode_space_info(root, inode);
b888db2b 4420
569254b0 4421 if (S_ISDIR(mode))
39279cc3
CM
4422 owner = 0;
4423 else
4424 owner = 1;
9c58309d
CM
4425
4426 key[0].objectid = objectid;
4427 btrfs_set_key_type(&key[0], BTRFS_INODE_ITEM_KEY);
4428 key[0].offset = 0;
4429
4430 key[1].objectid = objectid;
4431 btrfs_set_key_type(&key[1], BTRFS_INODE_REF_KEY);
4432 key[1].offset = ref_objectid;
4433
4434 sizes[0] = sizeof(struct btrfs_inode_item);
4435 sizes[1] = name_len + sizeof(*ref);
4436
b9473439 4437 path->leave_spinning = 1;
9c58309d
CM
4438 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, 2);
4439 if (ret != 0)
5f39d397
CM
4440 goto fail;
4441
ecc11fab 4442 inode_init_owner(inode, dir, mode);
a76a3cd4 4443 inode_set_bytes(inode, 0);
39279cc3 4444 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
5f39d397
CM
4445 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
4446 struct btrfs_inode_item);
e02119d5 4447 fill_inode_item(trans, path->nodes[0], inode_item, inode);
9c58309d
CM
4448
4449 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
4450 struct btrfs_inode_ref);
4451 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
00e4e6b3 4452 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
9c58309d
CM
4453 ptr = (unsigned long)(ref + 1);
4454 write_extent_buffer(path->nodes[0], name, ptr, name_len);
4455
5f39d397
CM
4456 btrfs_mark_buffer_dirty(path->nodes[0]);
4457 btrfs_free_path(path);
4458
39279cc3
CM
4459 location = &BTRFS_I(inode)->location;
4460 location->objectid = objectid;
39279cc3
CM
4461 location->offset = 0;
4462 btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY);
4463
6cbff00f
CH
4464 btrfs_inherit_iflags(inode, dir);
4465
569254b0 4466 if (S_ISREG(mode)) {
94272164
CM
4467 if (btrfs_test_opt(root, NODATASUM))
4468 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
75e7cb7f
LB
4469 if (btrfs_test_opt(root, NODATACOW) ||
4470 (BTRFS_I(dir)->flags & BTRFS_INODE_NODATACOW))
94272164
CM
4471 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
4472 }
4473
39279cc3 4474 insert_inode_hash(inode);
5d4f98a2 4475 inode_tree_add(inode);
1abe9b8a 4476
4477 trace_btrfs_inode_new(inode);
1973f0fa 4478 btrfs_set_inode_last_trans(trans, inode);
1abe9b8a 4479
39279cc3 4480 return inode;
5f39d397 4481fail:
aec7477b
JB
4482 if (dir)
4483 BTRFS_I(dir)->index_cnt--;
5f39d397 4484 btrfs_free_path(path);
09771430 4485 iput(inode);
5f39d397 4486 return ERR_PTR(ret);
39279cc3
CM
4487}
4488
4489static inline u8 btrfs_inode_type(struct inode *inode)
4490{
4491 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
4492}
4493
d352ac68
CM
4494/*
4495 * utility function to add 'inode' into 'parent_inode' with
4496 * a give name and a given sequence number.
4497 * if 'add_backref' is true, also insert a backref from the
4498 * inode to the parent directory.
4499 */
e02119d5
CM
4500int btrfs_add_link(struct btrfs_trans_handle *trans,
4501 struct inode *parent_inode, struct inode *inode,
4502 const char *name, int name_len, int add_backref, u64 index)
39279cc3 4503{
4df27c4d 4504 int ret = 0;
39279cc3 4505 struct btrfs_key key;
e02119d5 4506 struct btrfs_root *root = BTRFS_I(parent_inode)->root;
33345d01
LZ
4507 u64 ino = btrfs_ino(inode);
4508 u64 parent_ino = btrfs_ino(parent_inode);
5f39d397 4509
33345d01 4510 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
4df27c4d
YZ
4511 memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
4512 } else {
33345d01 4513 key.objectid = ino;
4df27c4d
YZ
4514 btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
4515 key.offset = 0;
4516 }
4517
33345d01 4518 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
4df27c4d
YZ
4519 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
4520 key.objectid, root->root_key.objectid,
33345d01 4521 parent_ino, index, name, name_len);
4df27c4d 4522 } else if (add_backref) {
33345d01
LZ
4523 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
4524 parent_ino, index);
4df27c4d 4525 }
39279cc3 4526
39279cc3 4527 if (ret == 0) {
4df27c4d 4528 ret = btrfs_insert_dir_item(trans, root, name, name_len,
16cdcec7 4529 parent_inode, &key,
4df27c4d
YZ
4530 btrfs_inode_type(inode), index);
4531 BUG_ON(ret);
4532
dbe674a9 4533 btrfs_i_size_write(parent_inode, parent_inode->i_size +
e02119d5 4534 name_len * 2);
79c44584 4535 parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
e02119d5 4536 ret = btrfs_update_inode(trans, root, parent_inode);
39279cc3
CM
4537 }
4538 return ret;
4539}
4540
4541static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
a1b075d2
JB
4542 struct inode *dir, struct dentry *dentry,
4543 struct inode *inode, int backref, u64 index)
39279cc3 4544{
a1b075d2
JB
4545 int err = btrfs_add_link(trans, dir, inode,
4546 dentry->d_name.name, dentry->d_name.len,
4547 backref, index);
39279cc3
CM
4548 if (!err) {
4549 d_instantiate(dentry, inode);
4550 return 0;
4551 }
4552 if (err > 0)
4553 err = -EEXIST;
4554 return err;
4555}
4556
618e21d5
JB
4557static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
4558 int mode, dev_t rdev)
4559{
4560 struct btrfs_trans_handle *trans;
4561 struct btrfs_root *root = BTRFS_I(dir)->root;
1832a6d5 4562 struct inode *inode = NULL;
618e21d5
JB
4563 int err;
4564 int drop_inode = 0;
4565 u64 objectid;
1832a6d5 4566 unsigned long nr = 0;
00e4e6b3 4567 u64 index = 0;
618e21d5
JB
4568
4569 if (!new_valid_dev(rdev))
4570 return -EINVAL;
4571
9ed74f2d
JB
4572 /*
4573 * 2 for inode item and ref
4574 * 2 for dir items
4575 * 1 for xattr if selinux is on
4576 */
a22285a6
YZ
4577 trans = btrfs_start_transaction(root, 5);
4578 if (IS_ERR(trans))
4579 return PTR_ERR(trans);
1832a6d5 4580
581bb050
LZ
4581 err = btrfs_find_free_ino(root, &objectid);
4582 if (err)
4583 goto out_unlock;
4584
aec7477b 4585 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
33345d01 4586 dentry->d_name.len, btrfs_ino(dir), objectid,
d82a6f1d 4587 mode, &index);
7cf96da3
TI
4588 if (IS_ERR(inode)) {
4589 err = PTR_ERR(inode);
618e21d5 4590 goto out_unlock;
7cf96da3 4591 }
618e21d5 4592
2a7dba39 4593 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
33268eaf
JB
4594 if (err) {
4595 drop_inode = 1;
4596 goto out_unlock;
4597 }
4598
a1b075d2 4599 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
618e21d5
JB
4600 if (err)
4601 drop_inode = 1;
4602 else {
4603 inode->i_op = &btrfs_special_inode_operations;
4604 init_special_inode(inode, inode->i_mode, rdev);
1b4ab1bb 4605 btrfs_update_inode(trans, root, inode);
618e21d5 4606 }
618e21d5 4607out_unlock:
d3c2fdcf 4608 nr = trans->blocks_used;
89ce8a63 4609 btrfs_end_transaction_throttle(trans, root);
a22285a6 4610 btrfs_btree_balance_dirty(root, nr);
618e21d5
JB
4611 if (drop_inode) {
4612 inode_dec_link_count(inode);
4613 iput(inode);
4614 }
618e21d5
JB
4615 return err;
4616}
4617
39279cc3
CM
4618static int btrfs_create(struct inode *dir, struct dentry *dentry,
4619 int mode, struct nameidata *nd)
4620{
4621 struct btrfs_trans_handle *trans;
4622 struct btrfs_root *root = BTRFS_I(dir)->root;
1832a6d5 4623 struct inode *inode = NULL;
39279cc3 4624 int drop_inode = 0;
a22285a6 4625 int err;
1832a6d5 4626 unsigned long nr = 0;
39279cc3 4627 u64 objectid;
00e4e6b3 4628 u64 index = 0;
39279cc3 4629
9ed74f2d
JB
4630 /*
4631 * 2 for inode item and ref
4632 * 2 for dir items
4633 * 1 for xattr if selinux is on
4634 */
a22285a6
YZ
4635 trans = btrfs_start_transaction(root, 5);
4636 if (IS_ERR(trans))
4637 return PTR_ERR(trans);
9ed74f2d 4638
581bb050
LZ
4639 err = btrfs_find_free_ino(root, &objectid);
4640 if (err)
4641 goto out_unlock;
4642
aec7477b 4643 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
33345d01 4644 dentry->d_name.len, btrfs_ino(dir), objectid,
d82a6f1d 4645 mode, &index);
7cf96da3
TI
4646 if (IS_ERR(inode)) {
4647 err = PTR_ERR(inode);
39279cc3 4648 goto out_unlock;
7cf96da3 4649 }
39279cc3 4650
2a7dba39 4651 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
33268eaf
JB
4652 if (err) {
4653 drop_inode = 1;
4654 goto out_unlock;
4655 }
4656
a1b075d2 4657 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
39279cc3
CM
4658 if (err)
4659 drop_inode = 1;
4660 else {
4661 inode->i_mapping->a_ops = &btrfs_aops;
04160088 4662 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
39279cc3
CM
4663 inode->i_fop = &btrfs_file_operations;
4664 inode->i_op = &btrfs_file_inode_operations;
d1310b2e 4665 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
39279cc3 4666 }
39279cc3 4667out_unlock:
d3c2fdcf 4668 nr = trans->blocks_used;
ab78c84d 4669 btrfs_end_transaction_throttle(trans, root);
39279cc3
CM
4670 if (drop_inode) {
4671 inode_dec_link_count(inode);
4672 iput(inode);
4673 }
d3c2fdcf 4674 btrfs_btree_balance_dirty(root, nr);
39279cc3
CM
4675 return err;
4676}
4677
4678static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
4679 struct dentry *dentry)
4680{
4681 struct btrfs_trans_handle *trans;
4682 struct btrfs_root *root = BTRFS_I(dir)->root;
4683 struct inode *inode = old_dentry->d_inode;
00e4e6b3 4684 u64 index;
1832a6d5 4685 unsigned long nr = 0;
39279cc3
CM
4686 int err;
4687 int drop_inode = 0;
4688
4a8be425
TH
4689 /* do not allow sys_link's with other subvols of the same device */
4690 if (root->objectid != BTRFS_I(inode)->root->objectid)
3ab3564f 4691 return -EXDEV;
4a8be425 4692
c055e99e
AV
4693 if (inode->i_nlink == ~0U)
4694 return -EMLINK;
4a8be425 4695
3de4586c 4696 err = btrfs_set_inode_index(dir, &index);
aec7477b
JB
4697 if (err)
4698 goto fail;
4699
a22285a6 4700 /*
7e6b6465 4701 * 2 items for inode and inode ref
a22285a6 4702 * 2 items for dir items
7e6b6465 4703 * 1 item for parent inode
a22285a6 4704 */
7e6b6465 4705 trans = btrfs_start_transaction(root, 5);
a22285a6
YZ
4706 if (IS_ERR(trans)) {
4707 err = PTR_ERR(trans);
4708 goto fail;
4709 }
5f39d397 4710
3153495d
MX
4711 btrfs_inc_nlink(inode);
4712 inode->i_ctime = CURRENT_TIME;
7de9c6ee 4713 ihold(inode);
aec7477b 4714
a1b075d2 4715 err = btrfs_add_nondir(trans, dir, dentry, inode, 1, index);
5f39d397 4716
a5719521 4717 if (err) {
54aa1f4d 4718 drop_inode = 1;
a5719521 4719 } else {
10d9f309 4720 struct dentry *parent = dentry->d_parent;
a5719521
YZ
4721 err = btrfs_update_inode(trans, root, inode);
4722 BUG_ON(err);
6a912213 4723 btrfs_log_new_name(trans, inode, NULL, parent);
a5719521 4724 }
39279cc3 4725
d3c2fdcf 4726 nr = trans->blocks_used;
ab78c84d 4727 btrfs_end_transaction_throttle(trans, root);
1832a6d5 4728fail:
39279cc3
CM
4729 if (drop_inode) {
4730 inode_dec_link_count(inode);
4731 iput(inode);
4732 }
d3c2fdcf 4733 btrfs_btree_balance_dirty(root, nr);
39279cc3
CM
4734 return err;
4735}
4736
39279cc3
CM
4737static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, int mode)
4738{
b9d86667 4739 struct inode *inode = NULL;
39279cc3
CM
4740 struct btrfs_trans_handle *trans;
4741 struct btrfs_root *root = BTRFS_I(dir)->root;
4742 int err = 0;
4743 int drop_on_err = 0;
b9d86667 4744 u64 objectid = 0;
00e4e6b3 4745 u64 index = 0;
d3c2fdcf 4746 unsigned long nr = 1;
39279cc3 4747
9ed74f2d
JB
4748 /*
4749 * 2 items for inode and ref
4750 * 2 items for dir items
4751 * 1 for xattr if selinux is on
4752 */
a22285a6
YZ
4753 trans = btrfs_start_transaction(root, 5);
4754 if (IS_ERR(trans))
4755 return PTR_ERR(trans);
39279cc3 4756
581bb050
LZ
4757 err = btrfs_find_free_ino(root, &objectid);
4758 if (err)
4759 goto out_fail;
4760
aec7477b 4761 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
33345d01 4762 dentry->d_name.len, btrfs_ino(dir), objectid,
d82a6f1d 4763 S_IFDIR | mode, &index);
39279cc3
CM
4764 if (IS_ERR(inode)) {
4765 err = PTR_ERR(inode);
4766 goto out_fail;
4767 }
5f39d397 4768
39279cc3 4769 drop_on_err = 1;
33268eaf 4770
2a7dba39 4771 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
33268eaf
JB
4772 if (err)
4773 goto out_fail;
4774
39279cc3
CM
4775 inode->i_op = &btrfs_dir_inode_operations;
4776 inode->i_fop = &btrfs_dir_file_operations;
39279cc3 4777
dbe674a9 4778 btrfs_i_size_write(inode, 0);
39279cc3
CM
4779 err = btrfs_update_inode(trans, root, inode);
4780 if (err)
4781 goto out_fail;
5f39d397 4782
a1b075d2
JB
4783 err = btrfs_add_link(trans, dir, inode, dentry->d_name.name,
4784 dentry->d_name.len, 0, index);
39279cc3
CM
4785 if (err)
4786 goto out_fail;
5f39d397 4787
39279cc3
CM
4788 d_instantiate(dentry, inode);
4789 drop_on_err = 0;
39279cc3
CM
4790
4791out_fail:
d3c2fdcf 4792 nr = trans->blocks_used;
ab78c84d 4793 btrfs_end_transaction_throttle(trans, root);
39279cc3
CM
4794 if (drop_on_err)
4795 iput(inode);
d3c2fdcf 4796 btrfs_btree_balance_dirty(root, nr);
39279cc3
CM
4797 return err;
4798}
4799
d352ac68
CM
4800/* helper for btfs_get_extent. Given an existing extent in the tree,
4801 * and an extent that you want to insert, deal with overlap and insert
4802 * the new extent into the tree.
4803 */
3b951516
CM
4804static int merge_extent_mapping(struct extent_map_tree *em_tree,
4805 struct extent_map *existing,
e6dcd2dc
CM
4806 struct extent_map *em,
4807 u64 map_start, u64 map_len)
3b951516
CM
4808{
4809 u64 start_diff;
3b951516 4810
e6dcd2dc
CM
4811 BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
4812 start_diff = map_start - em->start;
4813 em->start = map_start;
4814 em->len = map_len;
c8b97818
CM
4815 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
4816 !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
e6dcd2dc 4817 em->block_start += start_diff;
c8b97818
CM
4818 em->block_len -= start_diff;
4819 }
e6dcd2dc 4820 return add_extent_mapping(em_tree, em);
3b951516
CM
4821}
4822
c8b97818
CM
4823static noinline int uncompress_inline(struct btrfs_path *path,
4824 struct inode *inode, struct page *page,
4825 size_t pg_offset, u64 extent_offset,
4826 struct btrfs_file_extent_item *item)
4827{
4828 int ret;
4829 struct extent_buffer *leaf = path->nodes[0];
4830 char *tmp;
4831 size_t max_size;
4832 unsigned long inline_size;
4833 unsigned long ptr;
261507a0 4834 int compress_type;
c8b97818
CM
4835
4836 WARN_ON(pg_offset != 0);
261507a0 4837 compress_type = btrfs_file_extent_compression(leaf, item);
c8b97818
CM
4838 max_size = btrfs_file_extent_ram_bytes(leaf, item);
4839 inline_size = btrfs_file_extent_inline_item_len(leaf,
4840 btrfs_item_nr(leaf, path->slots[0]));
4841 tmp = kmalloc(inline_size, GFP_NOFS);
8d413713
TI
4842 if (!tmp)
4843 return -ENOMEM;
c8b97818
CM
4844 ptr = btrfs_file_extent_inline_start(item);
4845
4846 read_extent_buffer(leaf, tmp, ptr, inline_size);
4847
5b050f04 4848 max_size = min_t(unsigned long, PAGE_CACHE_SIZE, max_size);
261507a0
LZ
4849 ret = btrfs_decompress(compress_type, tmp, page,
4850 extent_offset, inline_size, max_size);
c8b97818
CM
4851 if (ret) {
4852 char *kaddr = kmap_atomic(page, KM_USER0);
4853 unsigned long copy_size = min_t(u64,
4854 PAGE_CACHE_SIZE - pg_offset,
4855 max_size - extent_offset);
4856 memset(kaddr + pg_offset, 0, copy_size);
4857 kunmap_atomic(kaddr, KM_USER0);
4858 }
4859 kfree(tmp);
4860 return 0;
4861}
4862
d352ac68
CM
4863/*
4864 * a bit scary, this does extent mapping from logical file offset to the disk.
d397712b
CM
4865 * the ugly parts come from merging extents from the disk with the in-ram
4866 * representation. This gets more complex because of the data=ordered code,
d352ac68
CM
4867 * where the in-ram extents might be locked pending data=ordered completion.
4868 *
4869 * This also copies inline extents directly into the page.
4870 */
d397712b 4871
a52d9a80 4872struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
70dec807 4873 size_t pg_offset, u64 start, u64 len,
a52d9a80
CM
4874 int create)
4875{
4876 int ret;
4877 int err = 0;
db94535d 4878 u64 bytenr;
a52d9a80
CM
4879 u64 extent_start = 0;
4880 u64 extent_end = 0;
33345d01 4881 u64 objectid = btrfs_ino(inode);
a52d9a80 4882 u32 found_type;
f421950f 4883 struct btrfs_path *path = NULL;
a52d9a80
CM
4884 struct btrfs_root *root = BTRFS_I(inode)->root;
4885 struct btrfs_file_extent_item *item;
5f39d397
CM
4886 struct extent_buffer *leaf;
4887 struct btrfs_key found_key;
a52d9a80
CM
4888 struct extent_map *em = NULL;
4889 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
d1310b2e 4890 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
a52d9a80 4891 struct btrfs_trans_handle *trans = NULL;
261507a0 4892 int compress_type;
a52d9a80 4893
a52d9a80 4894again:
890871be 4895 read_lock(&em_tree->lock);
d1310b2e 4896 em = lookup_extent_mapping(em_tree, start, len);
a061fc8d
CM
4897 if (em)
4898 em->bdev = root->fs_info->fs_devices->latest_bdev;
890871be 4899 read_unlock(&em_tree->lock);
d1310b2e 4900
a52d9a80 4901 if (em) {
e1c4b745
CM
4902 if (em->start > start || em->start + em->len <= start)
4903 free_extent_map(em);
4904 else if (em->block_start == EXTENT_MAP_INLINE && page)
70dec807
CM
4905 free_extent_map(em);
4906 else
4907 goto out;
a52d9a80 4908 }
172ddd60 4909 em = alloc_extent_map();
a52d9a80 4910 if (!em) {
d1310b2e
CM
4911 err = -ENOMEM;
4912 goto out;
a52d9a80 4913 }
e6dcd2dc 4914 em->bdev = root->fs_info->fs_devices->latest_bdev;
d1310b2e 4915 em->start = EXTENT_MAP_HOLE;
445a6944 4916 em->orig_start = EXTENT_MAP_HOLE;
d1310b2e 4917 em->len = (u64)-1;
c8b97818 4918 em->block_len = (u64)-1;
f421950f
CM
4919
4920 if (!path) {
4921 path = btrfs_alloc_path();
026fd317
JB
4922 if (!path) {
4923 err = -ENOMEM;
4924 goto out;
4925 }
4926 /*
4927 * Chances are we'll be called again, so go ahead and do
4928 * readahead
4929 */
4930 path->reada = 1;
f421950f
CM
4931 }
4932
179e29e4
CM
4933 ret = btrfs_lookup_file_extent(trans, root, path,
4934 objectid, start, trans != NULL);
a52d9a80
CM
4935 if (ret < 0) {
4936 err = ret;
4937 goto out;
4938 }
4939
4940 if (ret != 0) {
4941 if (path->slots[0] == 0)
4942 goto not_found;
4943 path->slots[0]--;
4944 }
4945
5f39d397
CM
4946 leaf = path->nodes[0];
4947 item = btrfs_item_ptr(leaf, path->slots[0],
a52d9a80 4948 struct btrfs_file_extent_item);
a52d9a80 4949 /* are we inside the extent that was found? */
5f39d397
CM
4950 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4951 found_type = btrfs_key_type(&found_key);
4952 if (found_key.objectid != objectid ||
a52d9a80
CM
4953 found_type != BTRFS_EXTENT_DATA_KEY) {
4954 goto not_found;
4955 }
4956
5f39d397
CM
4957 found_type = btrfs_file_extent_type(leaf, item);
4958 extent_start = found_key.offset;
261507a0 4959 compress_type = btrfs_file_extent_compression(leaf, item);
d899e052
YZ
4960 if (found_type == BTRFS_FILE_EXTENT_REG ||
4961 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
a52d9a80 4962 extent_end = extent_start +
db94535d 4963 btrfs_file_extent_num_bytes(leaf, item);
9036c102
YZ
4964 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
4965 size_t size;
4966 size = btrfs_file_extent_inline_len(leaf, item);
4967 extent_end = (extent_start + size + root->sectorsize - 1) &
4968 ~((u64)root->sectorsize - 1);
4969 }
4970
4971 if (start >= extent_end) {
4972 path->slots[0]++;
4973 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
4974 ret = btrfs_next_leaf(root, path);
4975 if (ret < 0) {
4976 err = ret;
4977 goto out;
a52d9a80 4978 }
9036c102
YZ
4979 if (ret > 0)
4980 goto not_found;
4981 leaf = path->nodes[0];
a52d9a80 4982 }
9036c102
YZ
4983 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4984 if (found_key.objectid != objectid ||
4985 found_key.type != BTRFS_EXTENT_DATA_KEY)
4986 goto not_found;
4987 if (start + len <= found_key.offset)
4988 goto not_found;
4989 em->start = start;
4990 em->len = found_key.offset - start;
4991 goto not_found_em;
4992 }
4993
d899e052
YZ
4994 if (found_type == BTRFS_FILE_EXTENT_REG ||
4995 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
9036c102
YZ
4996 em->start = extent_start;
4997 em->len = extent_end - extent_start;
ff5b7ee3
YZ
4998 em->orig_start = extent_start -
4999 btrfs_file_extent_offset(leaf, item);
db94535d
CM
5000 bytenr = btrfs_file_extent_disk_bytenr(leaf, item);
5001 if (bytenr == 0) {
5f39d397 5002 em->block_start = EXTENT_MAP_HOLE;
a52d9a80
CM
5003 goto insert;
5004 }
261507a0 5005 if (compress_type != BTRFS_COMPRESS_NONE) {
c8b97818 5006 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
261507a0 5007 em->compress_type = compress_type;
c8b97818
CM
5008 em->block_start = bytenr;
5009 em->block_len = btrfs_file_extent_disk_num_bytes(leaf,
5010 item);
5011 } else {
5012 bytenr += btrfs_file_extent_offset(leaf, item);
5013 em->block_start = bytenr;
5014 em->block_len = em->len;
d899e052
YZ
5015 if (found_type == BTRFS_FILE_EXTENT_PREALLOC)
5016 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
c8b97818 5017 }
a52d9a80
CM
5018 goto insert;
5019 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
5f39d397 5020 unsigned long ptr;
a52d9a80 5021 char *map;
3326d1b0
CM
5022 size_t size;
5023 size_t extent_offset;
5024 size_t copy_size;
a52d9a80 5025
689f9346 5026 em->block_start = EXTENT_MAP_INLINE;
c8b97818 5027 if (!page || create) {
689f9346 5028 em->start = extent_start;
9036c102 5029 em->len = extent_end - extent_start;
689f9346
Y
5030 goto out;
5031 }
5f39d397 5032
9036c102
YZ
5033 size = btrfs_file_extent_inline_len(leaf, item);
5034 extent_offset = page_offset(page) + pg_offset - extent_start;
70dec807 5035 copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
3326d1b0 5036 size - extent_offset);
3326d1b0 5037 em->start = extent_start + extent_offset;
70dec807
CM
5038 em->len = (copy_size + root->sectorsize - 1) &
5039 ~((u64)root->sectorsize - 1);
ff5b7ee3 5040 em->orig_start = EXTENT_MAP_INLINE;
261507a0 5041 if (compress_type) {
c8b97818 5042 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
261507a0
LZ
5043 em->compress_type = compress_type;
5044 }
689f9346 5045 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
179e29e4 5046 if (create == 0 && !PageUptodate(page)) {
261507a0
LZ
5047 if (btrfs_file_extent_compression(leaf, item) !=
5048 BTRFS_COMPRESS_NONE) {
c8b97818
CM
5049 ret = uncompress_inline(path, inode, page,
5050 pg_offset,
5051 extent_offset, item);
5052 BUG_ON(ret);
5053 } else {
5054 map = kmap(page);
5055 read_extent_buffer(leaf, map + pg_offset, ptr,
5056 copy_size);
93c82d57
CM
5057 if (pg_offset + copy_size < PAGE_CACHE_SIZE) {
5058 memset(map + pg_offset + copy_size, 0,
5059 PAGE_CACHE_SIZE - pg_offset -
5060 copy_size);
5061 }
c8b97818
CM
5062 kunmap(page);
5063 }
179e29e4
CM
5064 flush_dcache_page(page);
5065 } else if (create && PageUptodate(page)) {
0ca1f7ce 5066 WARN_ON(1);
179e29e4
CM
5067 if (!trans) {
5068 kunmap(page);
5069 free_extent_map(em);
5070 em = NULL;
ff5714cc 5071
b3b4aa74 5072 btrfs_release_path(path);
7a7eaa40 5073 trans = btrfs_join_transaction(root);
ff5714cc 5074
3612b495
TI
5075 if (IS_ERR(trans))
5076 return ERR_CAST(trans);
179e29e4
CM
5077 goto again;
5078 }
c8b97818 5079 map = kmap(page);
70dec807 5080 write_extent_buffer(leaf, map + pg_offset, ptr,
179e29e4 5081 copy_size);
c8b97818 5082 kunmap(page);
179e29e4 5083 btrfs_mark_buffer_dirty(leaf);
a52d9a80 5084 }
d1310b2e 5085 set_extent_uptodate(io_tree, em->start,
507903b8 5086 extent_map_end(em) - 1, NULL, GFP_NOFS);
a52d9a80
CM
5087 goto insert;
5088 } else {
d397712b 5089 printk(KERN_ERR "btrfs unknown found_type %d\n", found_type);
a52d9a80
CM
5090 WARN_ON(1);
5091 }
5092not_found:
5093 em->start = start;
d1310b2e 5094 em->len = len;
a52d9a80 5095not_found_em:
5f39d397 5096 em->block_start = EXTENT_MAP_HOLE;
9036c102 5097 set_bit(EXTENT_FLAG_VACANCY, &em->flags);
a52d9a80 5098insert:
b3b4aa74 5099 btrfs_release_path(path);
d1310b2e 5100 if (em->start > start || extent_map_end(em) <= start) {
d397712b
CM
5101 printk(KERN_ERR "Btrfs: bad extent! em: [%llu %llu] passed "
5102 "[%llu %llu]\n", (unsigned long long)em->start,
5103 (unsigned long long)em->len,
5104 (unsigned long long)start,
5105 (unsigned long long)len);
a52d9a80
CM
5106 err = -EIO;
5107 goto out;
5108 }
d1310b2e
CM
5109
5110 err = 0;
890871be 5111 write_lock(&em_tree->lock);
a52d9a80 5112 ret = add_extent_mapping(em_tree, em);
3b951516
CM
5113 /* it is possible that someone inserted the extent into the tree
5114 * while we had the lock dropped. It is also possible that
5115 * an overlapping map exists in the tree
5116 */
a52d9a80 5117 if (ret == -EEXIST) {
3b951516 5118 struct extent_map *existing;
e6dcd2dc
CM
5119
5120 ret = 0;
5121
3b951516 5122 existing = lookup_extent_mapping(em_tree, start, len);
e1c4b745
CM
5123 if (existing && (existing->start > start ||
5124 existing->start + existing->len <= start)) {
5125 free_extent_map(existing);
5126 existing = NULL;
5127 }
3b951516
CM
5128 if (!existing) {
5129 existing = lookup_extent_mapping(em_tree, em->start,
5130 em->len);
5131 if (existing) {
5132 err = merge_extent_mapping(em_tree, existing,
e6dcd2dc
CM
5133 em, start,
5134 root->sectorsize);
3b951516
CM
5135 free_extent_map(existing);
5136 if (err) {
5137 free_extent_map(em);
5138 em = NULL;
5139 }
5140 } else {
5141 err = -EIO;
3b951516
CM
5142 free_extent_map(em);
5143 em = NULL;
5144 }
5145 } else {
5146 free_extent_map(em);
5147 em = existing;
e6dcd2dc 5148 err = 0;
a52d9a80 5149 }
a52d9a80 5150 }
890871be 5151 write_unlock(&em_tree->lock);
a52d9a80 5152out:
1abe9b8a 5153
5154 trace_btrfs_get_extent(root, em);
5155
f421950f
CM
5156 if (path)
5157 btrfs_free_path(path);
a52d9a80
CM
5158 if (trans) {
5159 ret = btrfs_end_transaction(trans, root);
d397712b 5160 if (!err)
a52d9a80
CM
5161 err = ret;
5162 }
a52d9a80
CM
5163 if (err) {
5164 free_extent_map(em);
a52d9a80
CM
5165 return ERR_PTR(err);
5166 }
5167 return em;
5168}
5169
ec29ed5b
CM
5170struct extent_map *btrfs_get_extent_fiemap(struct inode *inode, struct page *page,
5171 size_t pg_offset, u64 start, u64 len,
5172 int create)
5173{
5174 struct extent_map *em;
5175 struct extent_map *hole_em = NULL;
5176 u64 range_start = start;
5177 u64 end;
5178 u64 found;
5179 u64 found_end;
5180 int err = 0;
5181
5182 em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
5183 if (IS_ERR(em))
5184 return em;
5185 if (em) {
5186 /*
5187 * if our em maps to a hole, there might
5188 * actually be delalloc bytes behind it
5189 */
5190 if (em->block_start != EXTENT_MAP_HOLE)
5191 return em;
5192 else
5193 hole_em = em;
5194 }
5195
5196 /* check to see if we've wrapped (len == -1 or similar) */
5197 end = start + len;
5198 if (end < start)
5199 end = (u64)-1;
5200 else
5201 end -= 1;
5202
5203 em = NULL;
5204
5205 /* ok, we didn't find anything, lets look for delalloc */
5206 found = count_range_bits(&BTRFS_I(inode)->io_tree, &range_start,
5207 end, len, EXTENT_DELALLOC, 1);
5208 found_end = range_start + found;
5209 if (found_end < range_start)
5210 found_end = (u64)-1;
5211
5212 /*
5213 * we didn't find anything useful, return
5214 * the original results from get_extent()
5215 */
5216 if (range_start > end || found_end <= start) {
5217 em = hole_em;
5218 hole_em = NULL;
5219 goto out;
5220 }
5221
5222 /* adjust the range_start to make sure it doesn't
5223 * go backwards from the start they passed in
5224 */
5225 range_start = max(start,range_start);
5226 found = found_end - range_start;
5227
5228 if (found > 0) {
5229 u64 hole_start = start;
5230 u64 hole_len = len;
5231
172ddd60 5232 em = alloc_extent_map();
ec29ed5b
CM
5233 if (!em) {
5234 err = -ENOMEM;
5235 goto out;
5236 }
5237 /*
5238 * when btrfs_get_extent can't find anything it
5239 * returns one huge hole
5240 *
5241 * make sure what it found really fits our range, and
5242 * adjust to make sure it is based on the start from
5243 * the caller
5244 */
5245 if (hole_em) {
5246 u64 calc_end = extent_map_end(hole_em);
5247
5248 if (calc_end <= start || (hole_em->start > end)) {
5249 free_extent_map(hole_em);
5250 hole_em = NULL;
5251 } else {
5252 hole_start = max(hole_em->start, start);
5253 hole_len = calc_end - hole_start;
5254 }
5255 }
5256 em->bdev = NULL;
5257 if (hole_em && range_start > hole_start) {
5258 /* our hole starts before our delalloc, so we
5259 * have to return just the parts of the hole
5260 * that go until the delalloc starts
5261 */
5262 em->len = min(hole_len,
5263 range_start - hole_start);
5264 em->start = hole_start;
5265 em->orig_start = hole_start;
5266 /*
5267 * don't adjust block start at all,
5268 * it is fixed at EXTENT_MAP_HOLE
5269 */
5270 em->block_start = hole_em->block_start;
5271 em->block_len = hole_len;
5272 } else {
5273 em->start = range_start;
5274 em->len = found;
5275 em->orig_start = range_start;
5276 em->block_start = EXTENT_MAP_DELALLOC;
5277 em->block_len = found;
5278 }
5279 } else if (hole_em) {
5280 return hole_em;
5281 }
5282out:
5283
5284 free_extent_map(hole_em);
5285 if (err) {
5286 free_extent_map(em);
5287 return ERR_PTR(err);
5288 }
5289 return em;
5290}
5291
4b46fce2 5292static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
16d299ac 5293 struct extent_map *em,
4b46fce2
JB
5294 u64 start, u64 len)
5295{
5296 struct btrfs_root *root = BTRFS_I(inode)->root;
5297 struct btrfs_trans_handle *trans;
4b46fce2
JB
5298 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
5299 struct btrfs_key ins;
5300 u64 alloc_hint;
5301 int ret;
16d299ac 5302 bool insert = false;
4b46fce2 5303
16d299ac
JB
5304 /*
5305 * Ok if the extent map we looked up is a hole and is for the exact
5306 * range we want, there is no reason to allocate a new one, however if
5307 * it is not right then we need to free this one and drop the cache for
5308 * our range.
5309 */
5310 if (em->block_start != EXTENT_MAP_HOLE || em->start != start ||
5311 em->len != len) {
5312 free_extent_map(em);
5313 em = NULL;
5314 insert = true;
5315 btrfs_drop_extent_cache(inode, start, start + len - 1, 0);
5316 }
4b46fce2 5317
7a7eaa40 5318 trans = btrfs_join_transaction(root);
3612b495
TI
5319 if (IS_ERR(trans))
5320 return ERR_CAST(trans);
4b46fce2 5321
4cb5300b
CM
5322 if (start <= BTRFS_I(inode)->disk_i_size && len < 64 * 1024)
5323 btrfs_add_inode_defrag(trans, inode);
5324
4b46fce2
JB
5325 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
5326
5327 alloc_hint = get_extent_allocation_hint(inode, start, len);
5328 ret = btrfs_reserve_extent(trans, root, len, root->sectorsize, 0,
5329 alloc_hint, (u64)-1, &ins, 1);
5330 if (ret) {
5331 em = ERR_PTR(ret);
5332 goto out;
5333 }
5334
4b46fce2 5335 if (!em) {
172ddd60 5336 em = alloc_extent_map();
16d299ac
JB
5337 if (!em) {
5338 em = ERR_PTR(-ENOMEM);
5339 goto out;
5340 }
4b46fce2
JB
5341 }
5342
5343 em->start = start;
5344 em->orig_start = em->start;
5345 em->len = ins.offset;
5346
5347 em->block_start = ins.objectid;
5348 em->block_len = ins.offset;
5349 em->bdev = root->fs_info->fs_devices->latest_bdev;
16d299ac
JB
5350
5351 /*
5352 * We need to do this because if we're using the original em we searched
5353 * for, we could have EXTENT_FLAG_VACANCY set, and we don't want that.
5354 */
5355 em->flags = 0;
4b46fce2
JB
5356 set_bit(EXTENT_FLAG_PINNED, &em->flags);
5357
16d299ac 5358 while (insert) {
4b46fce2
JB
5359 write_lock(&em_tree->lock);
5360 ret = add_extent_mapping(em_tree, em);
5361 write_unlock(&em_tree->lock);
5362 if (ret != -EEXIST)
5363 break;
5364 btrfs_drop_extent_cache(inode, start, start + em->len - 1, 0);
5365 }
5366
5367 ret = btrfs_add_ordered_extent_dio(inode, start, ins.objectid,
5368 ins.offset, ins.offset, 0);
5369 if (ret) {
5370 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
5371 em = ERR_PTR(ret);
5372 }
5373out:
5374 btrfs_end_transaction(trans, root);
5375 return em;
5376}
5377
46bfbb5c
CM
5378/*
5379 * returns 1 when the nocow is safe, < 1 on error, 0 if the
5380 * block must be cow'd
5381 */
5382static noinline int can_nocow_odirect(struct btrfs_trans_handle *trans,
5383 struct inode *inode, u64 offset, u64 len)
5384{
5385 struct btrfs_path *path;
5386 int ret;
5387 struct extent_buffer *leaf;
5388 struct btrfs_root *root = BTRFS_I(inode)->root;
5389 struct btrfs_file_extent_item *fi;
5390 struct btrfs_key key;
5391 u64 disk_bytenr;
5392 u64 backref_offset;
5393 u64 extent_end;
5394 u64 num_bytes;
5395 int slot;
5396 int found_type;
5397
5398 path = btrfs_alloc_path();
5399 if (!path)
5400 return -ENOMEM;
5401
33345d01 5402 ret = btrfs_lookup_file_extent(trans, root, path, btrfs_ino(inode),
46bfbb5c
CM
5403 offset, 0);
5404 if (ret < 0)
5405 goto out;
5406
5407 slot = path->slots[0];
5408 if (ret == 1) {
5409 if (slot == 0) {
5410 /* can't find the item, must cow */
5411 ret = 0;
5412 goto out;
5413 }
5414 slot--;
5415 }
5416 ret = 0;
5417 leaf = path->nodes[0];
5418 btrfs_item_key_to_cpu(leaf, &key, slot);
33345d01 5419 if (key.objectid != btrfs_ino(inode) ||
46bfbb5c
CM
5420 key.type != BTRFS_EXTENT_DATA_KEY) {
5421 /* not our file or wrong item type, must cow */
5422 goto out;
5423 }
5424
5425 if (key.offset > offset) {
5426 /* Wrong offset, must cow */
5427 goto out;
5428 }
5429
5430 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
5431 found_type = btrfs_file_extent_type(leaf, fi);
5432 if (found_type != BTRFS_FILE_EXTENT_REG &&
5433 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
5434 /* not a regular extent, must cow */
5435 goto out;
5436 }
5437 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
5438 backref_offset = btrfs_file_extent_offset(leaf, fi);
5439
5440 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
5441 if (extent_end < offset + len) {
5442 /* extent doesn't include our full range, must cow */
5443 goto out;
5444 }
5445
5446 if (btrfs_extent_readonly(root, disk_bytenr))
5447 goto out;
5448
5449 /*
5450 * look for other files referencing this extent, if we
5451 * find any we must cow
5452 */
33345d01 5453 if (btrfs_cross_ref_exist(trans, root, btrfs_ino(inode),
46bfbb5c
CM
5454 key.offset - backref_offset, disk_bytenr))
5455 goto out;
5456
5457 /*
5458 * adjust disk_bytenr and num_bytes to cover just the bytes
5459 * in this extent we are about to write. If there
5460 * are any csums in that range we have to cow in order
5461 * to keep the csums correct
5462 */
5463 disk_bytenr += backref_offset;
5464 disk_bytenr += offset - key.offset;
5465 num_bytes = min(offset + len, extent_end) - offset;
5466 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
5467 goto out;
5468 /*
5469 * all of the above have passed, it is safe to overwrite this extent
5470 * without cow
5471 */
5472 ret = 1;
5473out:
5474 btrfs_free_path(path);
5475 return ret;
5476}
5477
4b46fce2
JB
5478static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
5479 struct buffer_head *bh_result, int create)
5480{
5481 struct extent_map *em;
5482 struct btrfs_root *root = BTRFS_I(inode)->root;
5483 u64 start = iblock << inode->i_blkbits;
5484 u64 len = bh_result->b_size;
46bfbb5c 5485 struct btrfs_trans_handle *trans;
4b46fce2
JB
5486
5487 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
5488 if (IS_ERR(em))
5489 return PTR_ERR(em);
5490
5491 /*
5492 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
5493 * io. INLINE is special, and we could probably kludge it in here, but
5494 * it's still buffered so for safety lets just fall back to the generic
5495 * buffered path.
5496 *
5497 * For COMPRESSED we _have_ to read the entire extent in so we can
5498 * decompress it, so there will be buffering required no matter what we
5499 * do, so go ahead and fallback to buffered.
5500 *
5501 * We return -ENOTBLK because thats what makes DIO go ahead and go back
5502 * to buffered IO. Don't blame me, this is the price we pay for using
5503 * the generic code.
5504 */
5505 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
5506 em->block_start == EXTENT_MAP_INLINE) {
5507 free_extent_map(em);
5508 return -ENOTBLK;
5509 }
5510
5511 /* Just a good old fashioned hole, return */
5512 if (!create && (em->block_start == EXTENT_MAP_HOLE ||
5513 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
5514 free_extent_map(em);
5515 /* DIO will do one hole at a time, so just unlock a sector */
5516 unlock_extent(&BTRFS_I(inode)->io_tree, start,
5517 start + root->sectorsize - 1, GFP_NOFS);
5518 return 0;
5519 }
5520
5521 /*
5522 * We don't allocate a new extent in the following cases
5523 *
5524 * 1) The inode is marked as NODATACOW. In this case we'll just use the
5525 * existing extent.
5526 * 2) The extent is marked as PREALLOC. We're good to go here and can
5527 * just use the extent.
5528 *
5529 */
46bfbb5c
CM
5530 if (!create) {
5531 len = em->len - (start - em->start);
4b46fce2 5532 goto map;
46bfbb5c 5533 }
4b46fce2
JB
5534
5535 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
5536 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
5537 em->block_start != EXTENT_MAP_HOLE)) {
4b46fce2
JB
5538 int type;
5539 int ret;
46bfbb5c 5540 u64 block_start;
4b46fce2
JB
5541
5542 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
5543 type = BTRFS_ORDERED_PREALLOC;
5544 else
5545 type = BTRFS_ORDERED_NOCOW;
46bfbb5c 5546 len = min(len, em->len - (start - em->start));
4b46fce2 5547 block_start = em->block_start + (start - em->start);
46bfbb5c
CM
5548
5549 /*
5550 * we're not going to log anything, but we do need
5551 * to make sure the current transaction stays open
5552 * while we look for nocow cross refs
5553 */
7a7eaa40 5554 trans = btrfs_join_transaction(root);
3612b495 5555 if (IS_ERR(trans))
46bfbb5c
CM
5556 goto must_cow;
5557
5558 if (can_nocow_odirect(trans, inode, start, len) == 1) {
5559 ret = btrfs_add_ordered_extent_dio(inode, start,
5560 block_start, len, len, type);
5561 btrfs_end_transaction(trans, root);
5562 if (ret) {
5563 free_extent_map(em);
5564 return ret;
5565 }
5566 goto unlock;
4b46fce2 5567 }
46bfbb5c 5568 btrfs_end_transaction(trans, root);
4b46fce2 5569 }
46bfbb5c
CM
5570must_cow:
5571 /*
5572 * this will cow the extent, reset the len in case we changed
5573 * it above
5574 */
5575 len = bh_result->b_size;
16d299ac 5576 em = btrfs_new_extent_direct(inode, em, start, len);
46bfbb5c
CM
5577 if (IS_ERR(em))
5578 return PTR_ERR(em);
5579 len = min(len, em->len - (start - em->start));
5580unlock:
4845e44f
CM
5581 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, start + len - 1,
5582 EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DIRTY, 1,
5583 0, NULL, GFP_NOFS);
4b46fce2
JB
5584map:
5585 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
5586 inode->i_blkbits;
46bfbb5c 5587 bh_result->b_size = len;
4b46fce2
JB
5588 bh_result->b_bdev = em->bdev;
5589 set_buffer_mapped(bh_result);
5590 if (create && !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
5591 set_buffer_new(bh_result);
5592
5593 free_extent_map(em);
5594
5595 return 0;
5596}
5597
5598struct btrfs_dio_private {
5599 struct inode *inode;
5600 u64 logical_offset;
5601 u64 disk_bytenr;
5602 u64 bytes;
5603 u32 *csums;
5604 void *private;
e65e1535
MX
5605
5606 /* number of bios pending for this dio */
5607 atomic_t pending_bios;
5608
5609 /* IO errors */
5610 int errors;
5611
5612 struct bio *orig_bio;
4b46fce2
JB
5613};
5614
5615static void btrfs_endio_direct_read(struct bio *bio, int err)
5616{
e65e1535 5617 struct btrfs_dio_private *dip = bio->bi_private;
4b46fce2
JB
5618 struct bio_vec *bvec_end = bio->bi_io_vec + bio->bi_vcnt - 1;
5619 struct bio_vec *bvec = bio->bi_io_vec;
4b46fce2
JB
5620 struct inode *inode = dip->inode;
5621 struct btrfs_root *root = BTRFS_I(inode)->root;
5622 u64 start;
5623 u32 *private = dip->csums;
5624
5625 start = dip->logical_offset;
5626 do {
5627 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
5628 struct page *page = bvec->bv_page;
5629 char *kaddr;
5630 u32 csum = ~(u32)0;
5631 unsigned long flags;
5632
5633 local_irq_save(flags);
5634 kaddr = kmap_atomic(page, KM_IRQ0);
5635 csum = btrfs_csum_data(root, kaddr + bvec->bv_offset,
5636 csum, bvec->bv_len);
5637 btrfs_csum_final(csum, (char *)&csum);
5638 kunmap_atomic(kaddr, KM_IRQ0);
5639 local_irq_restore(flags);
5640
5641 flush_dcache_page(bvec->bv_page);
5642 if (csum != *private) {
33345d01 5643 printk(KERN_ERR "btrfs csum failed ino %llu off"
4b46fce2 5644 " %llu csum %u private %u\n",
33345d01
LZ
5645 (unsigned long long)btrfs_ino(inode),
5646 (unsigned long long)start,
4b46fce2
JB
5647 csum, *private);
5648 err = -EIO;
5649 }
5650 }
5651
5652 start += bvec->bv_len;
5653 private++;
5654 bvec++;
5655 } while (bvec <= bvec_end);
5656
5657 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
5658 dip->logical_offset + dip->bytes - 1, GFP_NOFS);
5659 bio->bi_private = dip->private;
5660
5661 kfree(dip->csums);
5662 kfree(dip);
c0da7aa1
JB
5663
5664 /* If we had a csum failure make sure to clear the uptodate flag */
5665 if (err)
5666 clear_bit(BIO_UPTODATE, &bio->bi_flags);
4b46fce2
JB
5667 dio_end_io(bio, err);
5668}
5669
5670static void btrfs_endio_direct_write(struct bio *bio, int err)
5671{
5672 struct btrfs_dio_private *dip = bio->bi_private;
5673 struct inode *inode = dip->inode;
5674 struct btrfs_root *root = BTRFS_I(inode)->root;
5675 struct btrfs_trans_handle *trans;
5676 struct btrfs_ordered_extent *ordered = NULL;
5677 struct extent_state *cached_state = NULL;
163cf09c
CM
5678 u64 ordered_offset = dip->logical_offset;
5679 u64 ordered_bytes = dip->bytes;
4b46fce2
JB
5680 int ret;
5681
5682 if (err)
5683 goto out_done;
163cf09c
CM
5684again:
5685 ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
5686 &ordered_offset,
5687 ordered_bytes);
4b46fce2 5688 if (!ret)
163cf09c 5689 goto out_test;
4b46fce2
JB
5690
5691 BUG_ON(!ordered);
5692
7a7eaa40 5693 trans = btrfs_join_transaction(root);
3612b495 5694 if (IS_ERR(trans)) {
4b46fce2
JB
5695 err = -ENOMEM;
5696 goto out;
5697 }
5698 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
5699
5700 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags)) {
5701 ret = btrfs_ordered_update_i_size(inode, 0, ordered);
5702 if (!ret)
2115133f 5703 err = btrfs_update_inode_fallback(trans, root, inode);
4b46fce2
JB
5704 goto out;
5705 }
5706
5707 lock_extent_bits(&BTRFS_I(inode)->io_tree, ordered->file_offset,
5708 ordered->file_offset + ordered->len - 1, 0,
5709 &cached_state, GFP_NOFS);
5710
5711 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags)) {
5712 ret = btrfs_mark_extent_written(trans, inode,
5713 ordered->file_offset,
5714 ordered->file_offset +
5715 ordered->len);
5716 if (ret) {
5717 err = ret;
5718 goto out_unlock;
5719 }
5720 } else {
5721 ret = insert_reserved_file_extent(trans, inode,
5722 ordered->file_offset,
5723 ordered->start,
5724 ordered->disk_len,
5725 ordered->len,
5726 ordered->len,
5727 0, 0, 0,
5728 BTRFS_FILE_EXTENT_REG);
5729 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
5730 ordered->file_offset, ordered->len);
5731 if (ret) {
5732 err = ret;
5733 WARN_ON(1);
5734 goto out_unlock;
5735 }
5736 }
5737
5738 add_pending_csums(trans, inode, ordered->file_offset, &ordered->list);
1ef30be1 5739 ret = btrfs_ordered_update_i_size(inode, 0, ordered);
a39f7521 5740 if (!ret || !test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags))
2115133f 5741 btrfs_update_inode_fallback(trans, root, inode);
1ef30be1 5742 ret = 0;
4b46fce2
JB
5743out_unlock:
5744 unlock_extent_cached(&BTRFS_I(inode)->io_tree, ordered->file_offset,
5745 ordered->file_offset + ordered->len - 1,
5746 &cached_state, GFP_NOFS);
5747out:
5748 btrfs_delalloc_release_metadata(inode, ordered->len);
5749 btrfs_end_transaction(trans, root);
163cf09c 5750 ordered_offset = ordered->file_offset + ordered->len;
4b46fce2
JB
5751 btrfs_put_ordered_extent(ordered);
5752 btrfs_put_ordered_extent(ordered);
163cf09c
CM
5753
5754out_test:
5755 /*
5756 * our bio might span multiple ordered extents. If we haven't
5757 * completed the accounting for the whole dio, go back and try again
5758 */
5759 if (ordered_offset < dip->logical_offset + dip->bytes) {
5760 ordered_bytes = dip->logical_offset + dip->bytes -
5761 ordered_offset;
5762 goto again;
5763 }
4b46fce2
JB
5764out_done:
5765 bio->bi_private = dip->private;
5766
5767 kfree(dip->csums);
5768 kfree(dip);
c0da7aa1
JB
5769
5770 /* If we had an error make sure to clear the uptodate flag */
5771 if (err)
5772 clear_bit(BIO_UPTODATE, &bio->bi_flags);
4b46fce2
JB
5773 dio_end_io(bio, err);
5774}
5775
eaf25d93
CM
5776static int __btrfs_submit_bio_start_direct_io(struct inode *inode, int rw,
5777 struct bio *bio, int mirror_num,
5778 unsigned long bio_flags, u64 offset)
5779{
5780 int ret;
5781 struct btrfs_root *root = BTRFS_I(inode)->root;
5782 ret = btrfs_csum_one_bio(root, inode, bio, offset, 1);
5783 BUG_ON(ret);
5784 return 0;
5785}
5786
e65e1535
MX
5787static void btrfs_end_dio_bio(struct bio *bio, int err)
5788{
5789 struct btrfs_dio_private *dip = bio->bi_private;
5790
5791 if (err) {
33345d01 5792 printk(KERN_ERR "btrfs direct IO failed ino %llu rw %lu "
3dd1462e 5793 "sector %#Lx len %u err no %d\n",
33345d01 5794 (unsigned long long)btrfs_ino(dip->inode), bio->bi_rw,
3dd1462e 5795 (unsigned long long)bio->bi_sector, bio->bi_size, err);
e65e1535
MX
5796 dip->errors = 1;
5797
5798 /*
5799 * before atomic variable goto zero, we must make sure
5800 * dip->errors is perceived to be set.
5801 */
5802 smp_mb__before_atomic_dec();
5803 }
5804
5805 /* if there are more bios still pending for this dio, just exit */
5806 if (!atomic_dec_and_test(&dip->pending_bios))
5807 goto out;
5808
5809 if (dip->errors)
5810 bio_io_error(dip->orig_bio);
5811 else {
5812 set_bit(BIO_UPTODATE, &dip->orig_bio->bi_flags);
5813 bio_endio(dip->orig_bio, 0);
5814 }
5815out:
5816 bio_put(bio);
5817}
5818
5819static struct bio *btrfs_dio_bio_alloc(struct block_device *bdev,
5820 u64 first_sector, gfp_t gfp_flags)
5821{
5822 int nr_vecs = bio_get_nr_vecs(bdev);
5823 return btrfs_bio_alloc(bdev, first_sector, nr_vecs, gfp_flags);
5824}
5825
5826static inline int __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode,
5827 int rw, u64 file_offset, int skip_sum,
1ae39938 5828 u32 *csums, int async_submit)
e65e1535
MX
5829{
5830 int write = rw & REQ_WRITE;
5831 struct btrfs_root *root = BTRFS_I(inode)->root;
5832 int ret;
5833
5834 bio_get(bio);
5835 ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
5836 if (ret)
5837 goto err;
5838
1ae39938
JB
5839 if (skip_sum)
5840 goto map;
5841
5842 if (write && async_submit) {
e65e1535
MX
5843 ret = btrfs_wq_submit_bio(root->fs_info,
5844 inode, rw, bio, 0, 0,
5845 file_offset,
5846 __btrfs_submit_bio_start_direct_io,
5847 __btrfs_submit_bio_done);
5848 goto err;
1ae39938
JB
5849 } else if (write) {
5850 /*
5851 * If we aren't doing async submit, calculate the csum of the
5852 * bio now.
5853 */
5854 ret = btrfs_csum_one_bio(root, inode, bio, file_offset, 1);
5855 if (ret)
5856 goto err;
c2db1073
TI
5857 } else if (!skip_sum) {
5858 ret = btrfs_lookup_bio_sums_dio(root, inode, bio,
e65e1535 5859 file_offset, csums);
c2db1073
TI
5860 if (ret)
5861 goto err;
5862 }
e65e1535 5863
1ae39938
JB
5864map:
5865 ret = btrfs_map_bio(root, rw, bio, 0, async_submit);
e65e1535
MX
5866err:
5867 bio_put(bio);
5868 return ret;
5869}
5870
5871static int btrfs_submit_direct_hook(int rw, struct btrfs_dio_private *dip,
5872 int skip_sum)
5873{
5874 struct inode *inode = dip->inode;
5875 struct btrfs_root *root = BTRFS_I(inode)->root;
5876 struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
5877 struct bio *bio;
5878 struct bio *orig_bio = dip->orig_bio;
5879 struct bio_vec *bvec = orig_bio->bi_io_vec;
5880 u64 start_sector = orig_bio->bi_sector;
5881 u64 file_offset = dip->logical_offset;
5882 u64 submit_len = 0;
5883 u64 map_length;
5884 int nr_pages = 0;
5885 u32 *csums = dip->csums;
5886 int ret = 0;
1ae39938 5887 int async_submit = 0;
98bc3149 5888 int write = rw & REQ_WRITE;
e65e1535 5889
e65e1535
MX
5890 map_length = orig_bio->bi_size;
5891 ret = btrfs_map_block(map_tree, READ, start_sector << 9,
5892 &map_length, NULL, 0);
5893 if (ret) {
64728bbb 5894 bio_put(orig_bio);
e65e1535
MX
5895 return -EIO;
5896 }
5897
02f57c7a
JB
5898 if (map_length >= orig_bio->bi_size) {
5899 bio = orig_bio;
5900 goto submit;
5901 }
5902
1ae39938 5903 async_submit = 1;
02f57c7a
JB
5904 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS);
5905 if (!bio)
5906 return -ENOMEM;
5907 bio->bi_private = dip;
5908 bio->bi_end_io = btrfs_end_dio_bio;
5909 atomic_inc(&dip->pending_bios);
5910
e65e1535
MX
5911 while (bvec <= (orig_bio->bi_io_vec + orig_bio->bi_vcnt - 1)) {
5912 if (unlikely(map_length < submit_len + bvec->bv_len ||
5913 bio_add_page(bio, bvec->bv_page, bvec->bv_len,
5914 bvec->bv_offset) < bvec->bv_len)) {
5915 /*
5916 * inc the count before we submit the bio so
5917 * we know the end IO handler won't happen before
5918 * we inc the count. Otherwise, the dip might get freed
5919 * before we're done setting it up
5920 */
5921 atomic_inc(&dip->pending_bios);
5922 ret = __btrfs_submit_dio_bio(bio, inode, rw,
5923 file_offset, skip_sum,
1ae39938 5924 csums, async_submit);
e65e1535
MX
5925 if (ret) {
5926 bio_put(bio);
5927 atomic_dec(&dip->pending_bios);
5928 goto out_err;
5929 }
5930
98bc3149
JB
5931 /* Write's use the ordered csums */
5932 if (!write && !skip_sum)
e65e1535
MX
5933 csums = csums + nr_pages;
5934 start_sector += submit_len >> 9;
5935 file_offset += submit_len;
5936
5937 submit_len = 0;
5938 nr_pages = 0;
5939
5940 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev,
5941 start_sector, GFP_NOFS);
5942 if (!bio)
5943 goto out_err;
5944 bio->bi_private = dip;
5945 bio->bi_end_io = btrfs_end_dio_bio;
5946
5947 map_length = orig_bio->bi_size;
5948 ret = btrfs_map_block(map_tree, READ, start_sector << 9,
5949 &map_length, NULL, 0);
5950 if (ret) {
5951 bio_put(bio);
5952 goto out_err;
5953 }
5954 } else {
5955 submit_len += bvec->bv_len;
5956 nr_pages ++;
5957 bvec++;
5958 }
5959 }
5960
02f57c7a 5961submit:
e65e1535 5962 ret = __btrfs_submit_dio_bio(bio, inode, rw, file_offset, skip_sum,
1ae39938 5963 csums, async_submit);
e65e1535
MX
5964 if (!ret)
5965 return 0;
5966
5967 bio_put(bio);
5968out_err:
5969 dip->errors = 1;
5970 /*
5971 * before atomic variable goto zero, we must
5972 * make sure dip->errors is perceived to be set.
5973 */
5974 smp_mb__before_atomic_dec();
5975 if (atomic_dec_and_test(&dip->pending_bios))
5976 bio_io_error(dip->orig_bio);
5977
5978 /* bio_end_io() will handle error, so we needn't return it */
5979 return 0;
5980}
5981
4b46fce2
JB
5982static void btrfs_submit_direct(int rw, struct bio *bio, struct inode *inode,
5983 loff_t file_offset)
5984{
5985 struct btrfs_root *root = BTRFS_I(inode)->root;
5986 struct btrfs_dio_private *dip;
5987 struct bio_vec *bvec = bio->bi_io_vec;
4b46fce2 5988 int skip_sum;
7b6d91da 5989 int write = rw & REQ_WRITE;
4b46fce2
JB
5990 int ret = 0;
5991
5992 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
5993
5994 dip = kmalloc(sizeof(*dip), GFP_NOFS);
5995 if (!dip) {
5996 ret = -ENOMEM;
5997 goto free_ordered;
5998 }
5999 dip->csums = NULL;
6000
98bc3149
JB
6001 /* Write's use the ordered csum stuff, so we don't need dip->csums */
6002 if (!write && !skip_sum) {
4b46fce2
JB
6003 dip->csums = kmalloc(sizeof(u32) * bio->bi_vcnt, GFP_NOFS);
6004 if (!dip->csums) {
b4966b77 6005 kfree(dip);
4b46fce2
JB
6006 ret = -ENOMEM;
6007 goto free_ordered;
6008 }
6009 }
6010
6011 dip->private = bio->bi_private;
6012 dip->inode = inode;
6013 dip->logical_offset = file_offset;
6014
4b46fce2
JB
6015 dip->bytes = 0;
6016 do {
6017 dip->bytes += bvec->bv_len;
6018 bvec++;
6019 } while (bvec <= (bio->bi_io_vec + bio->bi_vcnt - 1));
6020
46bfbb5c 6021 dip->disk_bytenr = (u64)bio->bi_sector << 9;
4b46fce2 6022 bio->bi_private = dip;
e65e1535
MX
6023 dip->errors = 0;
6024 dip->orig_bio = bio;
6025 atomic_set(&dip->pending_bios, 0);
4b46fce2
JB
6026
6027 if (write)
6028 bio->bi_end_io = btrfs_endio_direct_write;
6029 else
6030 bio->bi_end_io = btrfs_endio_direct_read;
6031
e65e1535
MX
6032 ret = btrfs_submit_direct_hook(rw, dip, skip_sum);
6033 if (!ret)
eaf25d93 6034 return;
4b46fce2
JB
6035free_ordered:
6036 /*
6037 * If this is a write, we need to clean up the reserved space and kill
6038 * the ordered extent.
6039 */
6040 if (write) {
6041 struct btrfs_ordered_extent *ordered;
955256f2 6042 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
4b46fce2
JB
6043 if (!test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags) &&
6044 !test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags))
6045 btrfs_free_reserved_extent(root, ordered->start,
6046 ordered->disk_len);
6047 btrfs_put_ordered_extent(ordered);
6048 btrfs_put_ordered_extent(ordered);
6049 }
6050 bio_endio(bio, ret);
6051}
6052
5a5f79b5
CM
6053static ssize_t check_direct_IO(struct btrfs_root *root, int rw, struct kiocb *iocb,
6054 const struct iovec *iov, loff_t offset,
6055 unsigned long nr_segs)
6056{
6057 int seg;
a1b75f7d 6058 int i;
5a5f79b5
CM
6059 size_t size;
6060 unsigned long addr;
6061 unsigned blocksize_mask = root->sectorsize - 1;
6062 ssize_t retval = -EINVAL;
6063 loff_t end = offset;
6064
6065 if (offset & blocksize_mask)
6066 goto out;
6067
6068 /* Check the memory alignment. Blocks cannot straddle pages */
6069 for (seg = 0; seg < nr_segs; seg++) {
6070 addr = (unsigned long)iov[seg].iov_base;
6071 size = iov[seg].iov_len;
6072 end += size;
a1b75f7d 6073 if ((addr & blocksize_mask) || (size & blocksize_mask))
5a5f79b5 6074 goto out;
a1b75f7d
JB
6075
6076 /* If this is a write we don't need to check anymore */
6077 if (rw & WRITE)
6078 continue;
6079
6080 /*
6081 * Check to make sure we don't have duplicate iov_base's in this
6082 * iovec, if so return EINVAL, otherwise we'll get csum errors
6083 * when reading back.
6084 */
6085 for (i = seg + 1; i < nr_segs; i++) {
6086 if (iov[seg].iov_base == iov[i].iov_base)
6087 goto out;
6088 }
5a5f79b5
CM
6089 }
6090 retval = 0;
6091out:
6092 return retval;
6093}
16432985
CM
6094static ssize_t btrfs_direct_IO(int rw, struct kiocb *iocb,
6095 const struct iovec *iov, loff_t offset,
6096 unsigned long nr_segs)
6097{
4b46fce2
JB
6098 struct file *file = iocb->ki_filp;
6099 struct inode *inode = file->f_mapping->host;
6100 struct btrfs_ordered_extent *ordered;
4845e44f 6101 struct extent_state *cached_state = NULL;
4b46fce2
JB
6102 u64 lockstart, lockend;
6103 ssize_t ret;
4845e44f
CM
6104 int writing = rw & WRITE;
6105 int write_bits = 0;
3f7c579c 6106 size_t count = iov_length(iov, nr_segs);
4b46fce2 6107
5a5f79b5
CM
6108 if (check_direct_IO(BTRFS_I(inode)->root, rw, iocb, iov,
6109 offset, nr_segs)) {
6110 return 0;
6111 }
6112
4b46fce2 6113 lockstart = offset;
3f7c579c
CM
6114 lockend = offset + count - 1;
6115
6116 if (writing) {
6117 ret = btrfs_delalloc_reserve_space(inode, count);
6118 if (ret)
6119 goto out;
6120 }
4845e44f 6121
4b46fce2 6122 while (1) {
4845e44f
CM
6123 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6124 0, &cached_state, GFP_NOFS);
4b46fce2
JB
6125 /*
6126 * We're concerned with the entire range that we're going to be
6127 * doing DIO to, so we need to make sure theres no ordered
6128 * extents in this range.
6129 */
6130 ordered = btrfs_lookup_ordered_range(inode, lockstart,
6131 lockend - lockstart + 1);
6132 if (!ordered)
6133 break;
4845e44f
CM
6134 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6135 &cached_state, GFP_NOFS);
4b46fce2
JB
6136 btrfs_start_ordered_extent(inode, ordered, 1);
6137 btrfs_put_ordered_extent(ordered);
6138 cond_resched();
6139 }
6140
4845e44f
CM
6141 /*
6142 * we don't use btrfs_set_extent_delalloc because we don't want
6143 * the dirty or uptodate bits
6144 */
6145 if (writing) {
6146 write_bits = EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING;
6147 ret = set_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6148 EXTENT_DELALLOC, 0, NULL, &cached_state,
6149 GFP_NOFS);
6150 if (ret) {
6151 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
6152 lockend, EXTENT_LOCKED | write_bits,
6153 1, 0, &cached_state, GFP_NOFS);
6154 goto out;
6155 }
6156 }
6157
6158 free_extent_state(cached_state);
6159 cached_state = NULL;
6160
5a5f79b5
CM
6161 ret = __blockdev_direct_IO(rw, iocb, inode,
6162 BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev,
6163 iov, offset, nr_segs, btrfs_get_blocks_direct, NULL,
6164 btrfs_submit_direct, 0);
4b46fce2
JB
6165
6166 if (ret < 0 && ret != -EIOCBQUEUED) {
4845e44f
CM
6167 clear_extent_bit(&BTRFS_I(inode)->io_tree, offset,
6168 offset + iov_length(iov, nr_segs) - 1,
6169 EXTENT_LOCKED | write_bits, 1, 0,
6170 &cached_state, GFP_NOFS);
4b46fce2
JB
6171 } else if (ret >= 0 && ret < iov_length(iov, nr_segs)) {
6172 /*
6173 * We're falling back to buffered, unlock the section we didn't
6174 * do IO on.
6175 */
4845e44f
CM
6176 clear_extent_bit(&BTRFS_I(inode)->io_tree, offset + ret,
6177 offset + iov_length(iov, nr_segs) - 1,
6178 EXTENT_LOCKED | write_bits, 1, 0,
6179 &cached_state, GFP_NOFS);
4b46fce2 6180 }
4845e44f
CM
6181out:
6182 free_extent_state(cached_state);
4b46fce2 6183 return ret;
16432985
CM
6184}
6185
1506fcc8
YS
6186static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
6187 __u64 start, __u64 len)
6188{
ec29ed5b 6189 return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap);
1506fcc8
YS
6190}
6191
a52d9a80 6192int btrfs_readpage(struct file *file, struct page *page)
9ebefb18 6193{
d1310b2e
CM
6194 struct extent_io_tree *tree;
6195 tree = &BTRFS_I(page->mapping->host)->io_tree;
8ddc7d9c 6196 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
9ebefb18 6197}
1832a6d5 6198
a52d9a80 6199static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
39279cc3 6200{
d1310b2e 6201 struct extent_io_tree *tree;
b888db2b
CM
6202
6203
6204 if (current->flags & PF_MEMALLOC) {
6205 redirty_page_for_writepage(wbc, page);
6206 unlock_page(page);
6207 return 0;
6208 }
d1310b2e 6209 tree = &BTRFS_I(page->mapping->host)->io_tree;
a52d9a80 6210 return extent_write_full_page(tree, page, btrfs_get_extent, wbc);
9ebefb18
CM
6211}
6212
f421950f
CM
6213int btrfs_writepages(struct address_space *mapping,
6214 struct writeback_control *wbc)
b293f02e 6215{
d1310b2e 6216 struct extent_io_tree *tree;
771ed689 6217
d1310b2e 6218 tree = &BTRFS_I(mapping->host)->io_tree;
b293f02e
CM
6219 return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
6220}
6221
3ab2fb5a
CM
6222static int
6223btrfs_readpages(struct file *file, struct address_space *mapping,
6224 struct list_head *pages, unsigned nr_pages)
6225{
d1310b2e
CM
6226 struct extent_io_tree *tree;
6227 tree = &BTRFS_I(mapping->host)->io_tree;
3ab2fb5a
CM
6228 return extent_readpages(tree, mapping, pages, nr_pages,
6229 btrfs_get_extent);
6230}
e6dcd2dc 6231static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
9ebefb18 6232{
d1310b2e
CM
6233 struct extent_io_tree *tree;
6234 struct extent_map_tree *map;
a52d9a80 6235 int ret;
8c2383c3 6236
d1310b2e
CM
6237 tree = &BTRFS_I(page->mapping->host)->io_tree;
6238 map = &BTRFS_I(page->mapping->host)->extent_tree;
70dec807 6239 ret = try_release_extent_mapping(map, tree, page, gfp_flags);
a52d9a80
CM
6240 if (ret == 1) {
6241 ClearPagePrivate(page);
6242 set_page_private(page, 0);
6243 page_cache_release(page);
39279cc3 6244 }
a52d9a80 6245 return ret;
39279cc3
CM
6246}
6247
e6dcd2dc
CM
6248static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
6249{
98509cfc
CM
6250 if (PageWriteback(page) || PageDirty(page))
6251 return 0;
b335b003 6252 return __btrfs_releasepage(page, gfp_flags & GFP_NOFS);
e6dcd2dc
CM
6253}
6254
a52d9a80 6255static void btrfs_invalidatepage(struct page *page, unsigned long offset)
39279cc3 6256{
d1310b2e 6257 struct extent_io_tree *tree;
e6dcd2dc 6258 struct btrfs_ordered_extent *ordered;
2ac55d41 6259 struct extent_state *cached_state = NULL;
e6dcd2dc
CM
6260 u64 page_start = page_offset(page);
6261 u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
39279cc3 6262
8b62b72b
CM
6263
6264 /*
6265 * we have the page locked, so new writeback can't start,
6266 * and the dirty bit won't be cleared while we are here.
6267 *
6268 * Wait for IO on this page so that we can safely clear
6269 * the PagePrivate2 bit and do ordered accounting
6270 */
e6dcd2dc 6271 wait_on_page_writeback(page);
8b62b72b 6272
d1310b2e 6273 tree = &BTRFS_I(page->mapping->host)->io_tree;
e6dcd2dc
CM
6274 if (offset) {
6275 btrfs_releasepage(page, GFP_NOFS);
6276 return;
6277 }
2ac55d41
JB
6278 lock_extent_bits(tree, page_start, page_end, 0, &cached_state,
6279 GFP_NOFS);
e6dcd2dc
CM
6280 ordered = btrfs_lookup_ordered_extent(page->mapping->host,
6281 page_offset(page));
6282 if (ordered) {
eb84ae03
CM
6283 /*
6284 * IO on this page will never be started, so we need
6285 * to account for any ordered extents now
6286 */
e6dcd2dc
CM
6287 clear_extent_bit(tree, page_start, page_end,
6288 EXTENT_DIRTY | EXTENT_DELALLOC |
32c00aff 6289 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING, 1, 0,
2ac55d41 6290 &cached_state, GFP_NOFS);
8b62b72b
CM
6291 /*
6292 * whoever cleared the private bit is responsible
6293 * for the finish_ordered_io
6294 */
6295 if (TestClearPagePrivate2(page)) {
6296 btrfs_finish_ordered_io(page->mapping->host,
6297 page_start, page_end);
6298 }
e6dcd2dc 6299 btrfs_put_ordered_extent(ordered);
2ac55d41
JB
6300 cached_state = NULL;
6301 lock_extent_bits(tree, page_start, page_end, 0, &cached_state,
6302 GFP_NOFS);
e6dcd2dc
CM
6303 }
6304 clear_extent_bit(tree, page_start, page_end,
32c00aff 6305 EXTENT_LOCKED | EXTENT_DIRTY | EXTENT_DELALLOC |
2ac55d41 6306 EXTENT_DO_ACCOUNTING, 1, 1, &cached_state, GFP_NOFS);
e6dcd2dc
CM
6307 __btrfs_releasepage(page, GFP_NOFS);
6308
4a096752 6309 ClearPageChecked(page);
9ad6b7bc 6310 if (PagePrivate(page)) {
9ad6b7bc
CM
6311 ClearPagePrivate(page);
6312 set_page_private(page, 0);
6313 page_cache_release(page);
6314 }
39279cc3
CM
6315}
6316
9ebefb18
CM
6317/*
6318 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
6319 * called from a page fault handler when a page is first dirtied. Hence we must
6320 * be careful to check for EOF conditions here. We set the page up correctly
6321 * for a written page which means we get ENOSPC checking when writing into
6322 * holes and correct delalloc and unwritten extent mapping on filesystems that
6323 * support these features.
6324 *
6325 * We are not allowed to take the i_mutex here so we have to play games to
6326 * protect against truncate races as the page could now be beyond EOF. Because
6327 * vmtruncate() writes the inode size before removing pages, once we have the
6328 * page lock we can determine safely if the page is beyond EOF. If it is not
6329 * beyond EOF, then the page is guaranteed safe against truncation until we
6330 * unlock the page.
6331 */
c2ec175c 6332int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
9ebefb18 6333{
c2ec175c 6334 struct page *page = vmf->page;
6da6abae 6335 struct inode *inode = fdentry(vma->vm_file)->d_inode;
1832a6d5 6336 struct btrfs_root *root = BTRFS_I(inode)->root;
e6dcd2dc
CM
6337 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6338 struct btrfs_ordered_extent *ordered;
2ac55d41 6339 struct extent_state *cached_state = NULL;
e6dcd2dc
CM
6340 char *kaddr;
6341 unsigned long zero_start;
9ebefb18 6342 loff_t size;
1832a6d5 6343 int ret;
a52d9a80 6344 u64 page_start;
e6dcd2dc 6345 u64 page_end;
9ebefb18 6346
0ca1f7ce 6347 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
56a76f82
NP
6348 if (ret) {
6349 if (ret == -ENOMEM)
6350 ret = VM_FAULT_OOM;
6351 else /* -ENOSPC, -EIO, etc */
6352 ret = VM_FAULT_SIGBUS;
1832a6d5 6353 goto out;
56a76f82 6354 }
1832a6d5 6355
56a76f82 6356 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
e6dcd2dc 6357again:
9ebefb18 6358 lock_page(page);
9ebefb18 6359 size = i_size_read(inode);
e6dcd2dc
CM
6360 page_start = page_offset(page);
6361 page_end = page_start + PAGE_CACHE_SIZE - 1;
a52d9a80 6362
9ebefb18 6363 if ((page->mapping != inode->i_mapping) ||
e6dcd2dc 6364 (page_start >= size)) {
9ebefb18
CM
6365 /* page got truncated out from underneath us */
6366 goto out_unlock;
6367 }
e6dcd2dc
CM
6368 wait_on_page_writeback(page);
6369
2ac55d41
JB
6370 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state,
6371 GFP_NOFS);
e6dcd2dc
CM
6372 set_page_extent_mapped(page);
6373
eb84ae03
CM
6374 /*
6375 * we can't set the delalloc bits if there are pending ordered
6376 * extents. Drop our locks and wait for them to finish
6377 */
e6dcd2dc
CM
6378 ordered = btrfs_lookup_ordered_extent(inode, page_start);
6379 if (ordered) {
2ac55d41
JB
6380 unlock_extent_cached(io_tree, page_start, page_end,
6381 &cached_state, GFP_NOFS);
e6dcd2dc 6382 unlock_page(page);
eb84ae03 6383 btrfs_start_ordered_extent(inode, ordered, 1);
e6dcd2dc
CM
6384 btrfs_put_ordered_extent(ordered);
6385 goto again;
6386 }
6387
fbf19087
JB
6388 /*
6389 * XXX - page_mkwrite gets called every time the page is dirtied, even
6390 * if it was already dirty, so for space accounting reasons we need to
6391 * clear any delalloc bits for the range we are fixing to save. There
6392 * is probably a better way to do this, but for now keep consistent with
6393 * prepare_pages in the normal write path.
6394 */
2ac55d41 6395 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
32c00aff 6396 EXTENT_DIRTY | EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING,
2ac55d41 6397 0, 0, &cached_state, GFP_NOFS);
fbf19087 6398
2ac55d41
JB
6399 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
6400 &cached_state);
9ed74f2d 6401 if (ret) {
2ac55d41
JB
6402 unlock_extent_cached(io_tree, page_start, page_end,
6403 &cached_state, GFP_NOFS);
9ed74f2d
JB
6404 ret = VM_FAULT_SIGBUS;
6405 goto out_unlock;
6406 }
e6dcd2dc 6407 ret = 0;
9ebefb18
CM
6408
6409 /* page is wholly or partially inside EOF */
a52d9a80 6410 if (page_start + PAGE_CACHE_SIZE > size)
e6dcd2dc 6411 zero_start = size & ~PAGE_CACHE_MASK;
9ebefb18 6412 else
e6dcd2dc 6413 zero_start = PAGE_CACHE_SIZE;
9ebefb18 6414
e6dcd2dc
CM
6415 if (zero_start != PAGE_CACHE_SIZE) {
6416 kaddr = kmap(page);
6417 memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
6418 flush_dcache_page(page);
6419 kunmap(page);
6420 }
247e743c 6421 ClearPageChecked(page);
e6dcd2dc 6422 set_page_dirty(page);
50a9b214 6423 SetPageUptodate(page);
5a3f23d5 6424
257c62e1
CM
6425 BTRFS_I(inode)->last_trans = root->fs_info->generation;
6426 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
6427
2ac55d41 6428 unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
9ebefb18
CM
6429
6430out_unlock:
50a9b214
CM
6431 if (!ret)
6432 return VM_FAULT_LOCKED;
9ebefb18 6433 unlock_page(page);
0ca1f7ce 6434 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
1832a6d5 6435out:
9ebefb18
CM
6436 return ret;
6437}
6438
a41ad394 6439static int btrfs_truncate(struct inode *inode)
39279cc3
CM
6440{
6441 struct btrfs_root *root = BTRFS_I(inode)->root;
fcb80c2a 6442 struct btrfs_block_rsv *rsv;
39279cc3 6443 int ret;
3893e33b 6444 int err = 0;
39279cc3 6445 struct btrfs_trans_handle *trans;
d3c2fdcf 6446 unsigned long nr;
dbe674a9 6447 u64 mask = root->sectorsize - 1;
07127184 6448 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
39279cc3 6449
5d5e103a
JB
6450 ret = btrfs_truncate_page(inode->i_mapping, inode->i_size);
6451 if (ret)
a41ad394 6452 return ret;
8082510e 6453
4a096752 6454 btrfs_wait_ordered_range(inode, inode->i_size & (~mask), (u64)-1);
8082510e 6455 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
39279cc3 6456
fcb80c2a
JB
6457 /*
6458 * Yes ladies and gentelment, this is indeed ugly. The fact is we have
6459 * 3 things going on here
6460 *
6461 * 1) We need to reserve space for our orphan item and the space to
6462 * delete our orphan item. Lord knows we don't want to have a dangling
6463 * orphan item because we didn't reserve space to remove it.
6464 *
6465 * 2) We need to reserve space to update our inode.
6466 *
6467 * 3) We need to have something to cache all the space that is going to
6468 * be free'd up by the truncate operation, but also have some slack
6469 * space reserved in case it uses space during the truncate (thank you
6470 * very much snapshotting).
6471 *
6472 * And we need these to all be seperate. The fact is we can use alot of
6473 * space doing the truncate, and we have no earthly idea how much space
6474 * we will use, so we need the truncate reservation to be seperate so it
6475 * doesn't end up using space reserved for updating the inode or
6476 * removing the orphan item. We also need to be able to stop the
6477 * transaction and start a new one, which means we need to be able to
6478 * update the inode several times, and we have no idea of knowing how
6479 * many times that will be, so we can't just reserve 1 item for the
6480 * entirety of the opration, so that has to be done seperately as well.
6481 * Then there is the orphan item, which does indeed need to be held on
6482 * to for the whole operation, and we need nobody to touch this reserved
6483 * space except the orphan code.
6484 *
6485 * So that leaves us with
6486 *
6487 * 1) root->orphan_block_rsv - for the orphan deletion.
6488 * 2) rsv - for the truncate reservation, which we will steal from the
6489 * transaction reservation.
6490 * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
6491 * updating the inode.
6492 */
6493 rsv = btrfs_alloc_block_rsv(root);
6494 if (!rsv)
6495 return -ENOMEM;
4a338542 6496 rsv->size = min_size;
f0cd846e 6497
907cbceb 6498 /*
07127184 6499 * 1 for the truncate slack space
907cbceb
JB
6500 * 1 for the orphan item we're going to add
6501 * 1 for the orphan item deletion
6502 * 1 for updating the inode.
6503 */
07127184 6504 trans = btrfs_start_transaction(root, 4);
fcb80c2a
JB
6505 if (IS_ERR(trans)) {
6506 err = PTR_ERR(trans);
6507 goto out;
6508 }
f0cd846e 6509
907cbceb
JB
6510 /* Migrate the slack space for the truncate to our reserve */
6511 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv,
6512 min_size);
fcb80c2a 6513 BUG_ON(ret);
f0cd846e
JB
6514
6515 ret = btrfs_orphan_add(trans, inode);
6516 if (ret) {
6517 btrfs_end_transaction(trans, root);
fcb80c2a 6518 goto out;
f0cd846e
JB
6519 }
6520
5a3f23d5
CM
6521 /*
6522 * setattr is responsible for setting the ordered_data_close flag,
6523 * but that is only tested during the last file release. That
6524 * could happen well after the next commit, leaving a great big
6525 * window where new writes may get lost if someone chooses to write
6526 * to this file after truncating to zero
6527 *
6528 * The inode doesn't have any dirty data here, and so if we commit
6529 * this is a noop. If someone immediately starts writing to the inode
6530 * it is very likely we'll catch some of their writes in this
6531 * transaction, and the commit will find this file on the ordered
6532 * data list with good things to send down.
6533 *
6534 * This is a best effort solution, there is still a window where
6535 * using truncate to replace the contents of the file will
6536 * end up with a zero length file after a crash.
6537 */
6538 if (inode->i_size == 0 && BTRFS_I(inode)->ordered_data_close)
6539 btrfs_add_ordered_operation(trans, root, inode);
6540
8082510e 6541 while (1) {
36ba022a 6542 ret = btrfs_block_rsv_refill(root, rsv, min_size);
907cbceb
JB
6543 if (ret) {
6544 /*
6545 * This can only happen with the original transaction we
6546 * started above, every other time we shouldn't have a
6547 * transaction started yet.
6548 */
6549 if (ret == -EAGAIN)
6550 goto end_trans;
6551 err = ret;
6552 break;
6553 }
6554
d68fc57b 6555 if (!trans) {
907cbceb
JB
6556 /* Just need the 1 for updating the inode */
6557 trans = btrfs_start_transaction(root, 1);
fcb80c2a
JB
6558 if (IS_ERR(trans)) {
6559 err = PTR_ERR(trans);
6560 goto out;
6561 }
d68fc57b
YZ
6562 }
6563
907cbceb
JB
6564 trans->block_rsv = rsv;
6565
8082510e
YZ
6566 ret = btrfs_truncate_inode_items(trans, root, inode,
6567 inode->i_size,
6568 BTRFS_EXTENT_DATA_KEY);
3893e33b
JB
6569 if (ret != -EAGAIN) {
6570 err = ret;
8082510e 6571 break;
3893e33b 6572 }
39279cc3 6573
fcb80c2a 6574 trans->block_rsv = &root->fs_info->trans_block_rsv;
8082510e 6575 ret = btrfs_update_inode(trans, root, inode);
3893e33b
JB
6576 if (ret) {
6577 err = ret;
6578 break;
6579 }
907cbceb 6580end_trans:
8082510e
YZ
6581 nr = trans->blocks_used;
6582 btrfs_end_transaction(trans, root);
d68fc57b 6583 trans = NULL;
8082510e 6584 btrfs_btree_balance_dirty(root, nr);
8082510e
YZ
6585 }
6586
6587 if (ret == 0 && inode->i_nlink > 0) {
fcb80c2a 6588 trans->block_rsv = root->orphan_block_rsv;
8082510e 6589 ret = btrfs_orphan_del(trans, inode);
3893e33b
JB
6590 if (ret)
6591 err = ret;
ded5db9d
JB
6592 } else if (ret && inode->i_nlink > 0) {
6593 /*
6594 * Failed to do the truncate, remove us from the in memory
6595 * orphan list.
6596 */
6597 ret = btrfs_orphan_del(NULL, inode);
8082510e
YZ
6598 }
6599
917c16b2
CM
6600 if (trans) {
6601 trans->block_rsv = &root->fs_info->trans_block_rsv;
6602 ret = btrfs_update_inode(trans, root, inode);
6603 if (ret && !err)
6604 err = ret;
7b128766 6605
917c16b2
CM
6606 nr = trans->blocks_used;
6607 ret = btrfs_end_transaction_throttle(trans, root);
6608 btrfs_btree_balance_dirty(root, nr);
6609 }
fcb80c2a
JB
6610
6611out:
6612 btrfs_free_block_rsv(root, rsv);
6613
3893e33b
JB
6614 if (ret && !err)
6615 err = ret;
a41ad394 6616
3893e33b 6617 return err;
39279cc3
CM
6618}
6619
d352ac68
CM
6620/*
6621 * create a new subvolume directory/inode (helper for the ioctl).
6622 */
d2fb3437 6623int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
d82a6f1d 6624 struct btrfs_root *new_root, u64 new_dirid)
39279cc3 6625{
39279cc3 6626 struct inode *inode;
76dda93c 6627 int err;
00e4e6b3 6628 u64 index = 0;
39279cc3 6629
aec7477b 6630 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2, new_dirid,
d82a6f1d 6631 new_dirid, S_IFDIR | 0700, &index);
54aa1f4d 6632 if (IS_ERR(inode))
f46b5a66 6633 return PTR_ERR(inode);
39279cc3
CM
6634 inode->i_op = &btrfs_dir_inode_operations;
6635 inode->i_fop = &btrfs_dir_file_operations;
6636
39279cc3 6637 inode->i_nlink = 1;
dbe674a9 6638 btrfs_i_size_write(inode, 0);
3b96362c 6639
76dda93c
YZ
6640 err = btrfs_update_inode(trans, new_root, inode);
6641 BUG_ON(err);
cb8e7090 6642
76dda93c 6643 iput(inode);
cb8e7090 6644 return 0;
39279cc3
CM
6645}
6646
39279cc3
CM
6647struct inode *btrfs_alloc_inode(struct super_block *sb)
6648{
6649 struct btrfs_inode *ei;
2ead6ae7 6650 struct inode *inode;
39279cc3
CM
6651
6652 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
6653 if (!ei)
6654 return NULL;
2ead6ae7
YZ
6655
6656 ei->root = NULL;
6657 ei->space_info = NULL;
6658 ei->generation = 0;
6659 ei->sequence = 0;
15ee9bc7 6660 ei->last_trans = 0;
257c62e1 6661 ei->last_sub_trans = 0;
e02119d5 6662 ei->logged_trans = 0;
2ead6ae7 6663 ei->delalloc_bytes = 0;
2ead6ae7
YZ
6664 ei->disk_i_size = 0;
6665 ei->flags = 0;
7709cde3 6666 ei->csum_bytes = 0;
2ead6ae7
YZ
6667 ei->index_cnt = (u64)-1;
6668 ei->last_unlink_trans = 0;
6669
9e0baf60
JB
6670 spin_lock_init(&ei->lock);
6671 ei->outstanding_extents = 0;
6672 ei->reserved_extents = 0;
2ead6ae7
YZ
6673
6674 ei->ordered_data_close = 0;
d68fc57b 6675 ei->orphan_meta_reserved = 0;
2ead6ae7 6676 ei->dummy_inode = 0;
4cb5300b 6677 ei->in_defrag = 0;
7fd2ae21 6678 ei->delalloc_meta_reserved = 0;
261507a0 6679 ei->force_compress = BTRFS_COMPRESS_NONE;
2ead6ae7 6680
16cdcec7
MX
6681 ei->delayed_node = NULL;
6682
2ead6ae7 6683 inode = &ei->vfs_inode;
a8067e02 6684 extent_map_tree_init(&ei->extent_tree);
f993c883
DS
6685 extent_io_tree_init(&ei->io_tree, &inode->i_data);
6686 extent_io_tree_init(&ei->io_failure_tree, &inode->i_data);
2ead6ae7 6687 mutex_init(&ei->log_mutex);
e6dcd2dc 6688 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
7b128766 6689 INIT_LIST_HEAD(&ei->i_orphan);
2ead6ae7 6690 INIT_LIST_HEAD(&ei->delalloc_inodes);
5a3f23d5 6691 INIT_LIST_HEAD(&ei->ordered_operations);
2ead6ae7
YZ
6692 RB_CLEAR_NODE(&ei->rb_node);
6693
6694 return inode;
39279cc3
CM
6695}
6696
fa0d7e3d
NP
6697static void btrfs_i_callback(struct rcu_head *head)
6698{
6699 struct inode *inode = container_of(head, struct inode, i_rcu);
6700 INIT_LIST_HEAD(&inode->i_dentry);
6701 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
6702}
6703
39279cc3
CM
6704void btrfs_destroy_inode(struct inode *inode)
6705{
e6dcd2dc 6706 struct btrfs_ordered_extent *ordered;
5a3f23d5
CM
6707 struct btrfs_root *root = BTRFS_I(inode)->root;
6708
39279cc3
CM
6709 WARN_ON(!list_empty(&inode->i_dentry));
6710 WARN_ON(inode->i_data.nrpages);
9e0baf60
JB
6711 WARN_ON(BTRFS_I(inode)->outstanding_extents);
6712 WARN_ON(BTRFS_I(inode)->reserved_extents);
7709cde3
JB
6713 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
6714 WARN_ON(BTRFS_I(inode)->csum_bytes);
39279cc3 6715
a6dbd429
JB
6716 /*
6717 * This can happen where we create an inode, but somebody else also
6718 * created the same inode and we need to destroy the one we already
6719 * created.
6720 */
6721 if (!root)
6722 goto free;
6723
5a3f23d5
CM
6724 /*
6725 * Make sure we're properly removed from the ordered operation
6726 * lists.
6727 */
6728 smp_mb();
6729 if (!list_empty(&BTRFS_I(inode)->ordered_operations)) {
6730 spin_lock(&root->fs_info->ordered_extent_lock);
6731 list_del_init(&BTRFS_I(inode)->ordered_operations);
6732 spin_unlock(&root->fs_info->ordered_extent_lock);
6733 }
6734
d68fc57b 6735 spin_lock(&root->orphan_lock);
7b128766 6736 if (!list_empty(&BTRFS_I(inode)->i_orphan)) {
33345d01
LZ
6737 printk(KERN_INFO "BTRFS: inode %llu still on the orphan list\n",
6738 (unsigned long long)btrfs_ino(inode));
8082510e 6739 list_del_init(&BTRFS_I(inode)->i_orphan);
7b128766 6740 }
d68fc57b 6741 spin_unlock(&root->orphan_lock);
7b128766 6742
d397712b 6743 while (1) {
e6dcd2dc
CM
6744 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
6745 if (!ordered)
6746 break;
6747 else {
d397712b
CM
6748 printk(KERN_ERR "btrfs found ordered "
6749 "extent %llu %llu on inode cleanup\n",
6750 (unsigned long long)ordered->file_offset,
6751 (unsigned long long)ordered->len);
e6dcd2dc
CM
6752 btrfs_remove_ordered_extent(inode, ordered);
6753 btrfs_put_ordered_extent(ordered);
6754 btrfs_put_ordered_extent(ordered);
6755 }
6756 }
5d4f98a2 6757 inode_tree_del(inode);
5b21f2ed 6758 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
a6dbd429 6759free:
16cdcec7 6760 btrfs_remove_delayed_node(inode);
fa0d7e3d 6761 call_rcu(&inode->i_rcu, btrfs_i_callback);
39279cc3
CM
6762}
6763
45321ac5 6764int btrfs_drop_inode(struct inode *inode)
76dda93c
YZ
6765{
6766 struct btrfs_root *root = BTRFS_I(inode)->root;
45321ac5 6767
0af3d00b 6768 if (btrfs_root_refs(&root->root_item) == 0 &&
2cf8572d 6769 !btrfs_is_free_space_inode(root, inode))
45321ac5 6770 return 1;
76dda93c 6771 else
45321ac5 6772 return generic_drop_inode(inode);
76dda93c
YZ
6773}
6774
0ee0fda0 6775static void init_once(void *foo)
39279cc3
CM
6776{
6777 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
6778
6779 inode_init_once(&ei->vfs_inode);
6780}
6781
6782void btrfs_destroy_cachep(void)
6783{
6784 if (btrfs_inode_cachep)
6785 kmem_cache_destroy(btrfs_inode_cachep);
6786 if (btrfs_trans_handle_cachep)
6787 kmem_cache_destroy(btrfs_trans_handle_cachep);
6788 if (btrfs_transaction_cachep)
6789 kmem_cache_destroy(btrfs_transaction_cachep);
39279cc3
CM
6790 if (btrfs_path_cachep)
6791 kmem_cache_destroy(btrfs_path_cachep);
dc89e982
JB
6792 if (btrfs_free_space_cachep)
6793 kmem_cache_destroy(btrfs_free_space_cachep);
39279cc3
CM
6794}
6795
6796int btrfs_init_cachep(void)
6797{
9601e3f6
CH
6798 btrfs_inode_cachep = kmem_cache_create("btrfs_inode_cache",
6799 sizeof(struct btrfs_inode), 0,
6800 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, init_once);
39279cc3
CM
6801 if (!btrfs_inode_cachep)
6802 goto fail;
9601e3f6
CH
6803
6804 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle_cache",
6805 sizeof(struct btrfs_trans_handle), 0,
6806 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
39279cc3
CM
6807 if (!btrfs_trans_handle_cachep)
6808 goto fail;
9601e3f6
CH
6809
6810 btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction_cache",
6811 sizeof(struct btrfs_transaction), 0,
6812 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
39279cc3
CM
6813 if (!btrfs_transaction_cachep)
6814 goto fail;
9601e3f6
CH
6815
6816 btrfs_path_cachep = kmem_cache_create("btrfs_path_cache",
6817 sizeof(struct btrfs_path), 0,
6818 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
39279cc3
CM
6819 if (!btrfs_path_cachep)
6820 goto fail;
9601e3f6 6821
dc89e982
JB
6822 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space_cache",
6823 sizeof(struct btrfs_free_space), 0,
6824 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
6825 if (!btrfs_free_space_cachep)
6826 goto fail;
6827
39279cc3
CM
6828 return 0;
6829fail:
6830 btrfs_destroy_cachep();
6831 return -ENOMEM;
6832}
6833
6834static int btrfs_getattr(struct vfsmount *mnt,
6835 struct dentry *dentry, struct kstat *stat)
6836{
6837 struct inode *inode = dentry->d_inode;
fadc0d8b
DS
6838 u32 blocksize = inode->i_sb->s_blocksize;
6839
39279cc3 6840 generic_fillattr(inode, stat);
0ee5dc67 6841 stat->dev = BTRFS_I(inode)->root->anon_dev;
d6667462 6842 stat->blksize = PAGE_CACHE_SIZE;
fadc0d8b
DS
6843 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
6844 ALIGN(BTRFS_I(inode)->delalloc_bytes, blocksize)) >> 9;
39279cc3
CM
6845 return 0;
6846}
6847
75e7cb7f
LB
6848/*
6849 * If a file is moved, it will inherit the cow and compression flags of the new
6850 * directory.
6851 */
6852static void fixup_inode_flags(struct inode *dir, struct inode *inode)
6853{
6854 struct btrfs_inode *b_dir = BTRFS_I(dir);
6855 struct btrfs_inode *b_inode = BTRFS_I(inode);
6856
6857 if (b_dir->flags & BTRFS_INODE_NODATACOW)
6858 b_inode->flags |= BTRFS_INODE_NODATACOW;
6859 else
6860 b_inode->flags &= ~BTRFS_INODE_NODATACOW;
6861
6862 if (b_dir->flags & BTRFS_INODE_COMPRESS)
6863 b_inode->flags |= BTRFS_INODE_COMPRESS;
6864 else
6865 b_inode->flags &= ~BTRFS_INODE_COMPRESS;
6866}
6867
d397712b
CM
6868static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
6869 struct inode *new_dir, struct dentry *new_dentry)
39279cc3
CM
6870{
6871 struct btrfs_trans_handle *trans;
6872 struct btrfs_root *root = BTRFS_I(old_dir)->root;
4df27c4d 6873 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
39279cc3
CM
6874 struct inode *new_inode = new_dentry->d_inode;
6875 struct inode *old_inode = old_dentry->d_inode;
6876 struct timespec ctime = CURRENT_TIME;
00e4e6b3 6877 u64 index = 0;
4df27c4d 6878 u64 root_objectid;
39279cc3 6879 int ret;
33345d01 6880 u64 old_ino = btrfs_ino(old_inode);
39279cc3 6881
33345d01 6882 if (btrfs_ino(new_dir) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
f679a840
YZ
6883 return -EPERM;
6884
4df27c4d 6885 /* we only allow rename subvolume link between subvolumes */
33345d01 6886 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
3394e160
CM
6887 return -EXDEV;
6888
33345d01
LZ
6889 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
6890 (new_inode && btrfs_ino(new_inode) == BTRFS_FIRST_FREE_OBJECTID))
39279cc3 6891 return -ENOTEMPTY;
5f39d397 6892
4df27c4d
YZ
6893 if (S_ISDIR(old_inode->i_mode) && new_inode &&
6894 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
6895 return -ENOTEMPTY;
5a3f23d5
CM
6896 /*
6897 * we're using rename to replace one file with another.
6898 * and the replacement file is large. Start IO on it now so
6899 * we don't add too much work to the end of the transaction
6900 */
4baf8c92 6901 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size &&
5a3f23d5
CM
6902 old_inode->i_size > BTRFS_ORDERED_OPERATIONS_FLUSH_LIMIT)
6903 filemap_flush(old_inode->i_mapping);
6904
76dda93c 6905 /* close the racy window with snapshot create/destroy ioctl */
33345d01 6906 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
76dda93c 6907 down_read(&root->fs_info->subvol_sem);
a22285a6
YZ
6908 /*
6909 * We want to reserve the absolute worst case amount of items. So if
6910 * both inodes are subvols and we need to unlink them then that would
6911 * require 4 item modifications, but if they are both normal inodes it
6912 * would require 5 item modifications, so we'll assume their normal
6913 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
6914 * should cover the worst case number of items we'll modify.
6915 */
6916 trans = btrfs_start_transaction(root, 20);
b44c59a8
JL
6917 if (IS_ERR(trans)) {
6918 ret = PTR_ERR(trans);
6919 goto out_notrans;
6920 }
76dda93c 6921
4df27c4d
YZ
6922 if (dest != root)
6923 btrfs_record_root_in_trans(trans, dest);
5f39d397 6924
a5719521
YZ
6925 ret = btrfs_set_inode_index(new_dir, &index);
6926 if (ret)
6927 goto out_fail;
5a3f23d5 6928
33345d01 6929 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
4df27c4d
YZ
6930 /* force full log commit if subvolume involved. */
6931 root->fs_info->last_trans_log_full_commit = trans->transid;
6932 } else {
a5719521
YZ
6933 ret = btrfs_insert_inode_ref(trans, dest,
6934 new_dentry->d_name.name,
6935 new_dentry->d_name.len,
33345d01
LZ
6936 old_ino,
6937 btrfs_ino(new_dir), index);
a5719521
YZ
6938 if (ret)
6939 goto out_fail;
4df27c4d
YZ
6940 /*
6941 * this is an ugly little race, but the rename is required
6942 * to make sure that if we crash, the inode is either at the
6943 * old name or the new one. pinning the log transaction lets
6944 * us make sure we don't allow a log commit to come in after
6945 * we unlink the name but before we add the new name back in.
6946 */
6947 btrfs_pin_log_trans(root);
6948 }
5a3f23d5
CM
6949 /*
6950 * make sure the inode gets flushed if it is replacing
6951 * something.
6952 */
33345d01 6953 if (new_inode && new_inode->i_size && S_ISREG(old_inode->i_mode))
5a3f23d5 6954 btrfs_add_ordered_operation(trans, root, old_inode);
5a3f23d5 6955
39279cc3
CM
6956 old_dir->i_ctime = old_dir->i_mtime = ctime;
6957 new_dir->i_ctime = new_dir->i_mtime = ctime;
6958 old_inode->i_ctime = ctime;
5f39d397 6959
12fcfd22
CM
6960 if (old_dentry->d_parent != new_dentry->d_parent)
6961 btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
6962
33345d01 6963 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
4df27c4d
YZ
6964 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
6965 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
6966 old_dentry->d_name.name,
6967 old_dentry->d_name.len);
6968 } else {
92986796
AV
6969 ret = __btrfs_unlink_inode(trans, root, old_dir,
6970 old_dentry->d_inode,
6971 old_dentry->d_name.name,
6972 old_dentry->d_name.len);
6973 if (!ret)
6974 ret = btrfs_update_inode(trans, root, old_inode);
4df27c4d
YZ
6975 }
6976 BUG_ON(ret);
39279cc3
CM
6977
6978 if (new_inode) {
6979 new_inode->i_ctime = CURRENT_TIME;
33345d01 6980 if (unlikely(btrfs_ino(new_inode) ==
4df27c4d
YZ
6981 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
6982 root_objectid = BTRFS_I(new_inode)->location.objectid;
6983 ret = btrfs_unlink_subvol(trans, dest, new_dir,
6984 root_objectid,
6985 new_dentry->d_name.name,
6986 new_dentry->d_name.len);
6987 BUG_ON(new_inode->i_nlink == 0);
6988 } else {
6989 ret = btrfs_unlink_inode(trans, dest, new_dir,
6990 new_dentry->d_inode,
6991 new_dentry->d_name.name,
6992 new_dentry->d_name.len);
6993 }
6994 BUG_ON(ret);
7b128766 6995 if (new_inode->i_nlink == 0) {
e02119d5 6996 ret = btrfs_orphan_add(trans, new_dentry->d_inode);
4df27c4d 6997 BUG_ON(ret);
7b128766 6998 }
39279cc3 6999 }
aec7477b 7000
75e7cb7f
LB
7001 fixup_inode_flags(new_dir, old_inode);
7002
4df27c4d
YZ
7003 ret = btrfs_add_link(trans, new_dir, old_inode,
7004 new_dentry->d_name.name,
a5719521 7005 new_dentry->d_name.len, 0, index);
4df27c4d 7006 BUG_ON(ret);
39279cc3 7007
33345d01 7008 if (old_ino != BTRFS_FIRST_FREE_OBJECTID) {
10d9f309 7009 struct dentry *parent = new_dentry->d_parent;
6a912213 7010 btrfs_log_new_name(trans, old_inode, old_dir, parent);
4df27c4d
YZ
7011 btrfs_end_log_trans(root);
7012 }
39279cc3 7013out_fail:
ab78c84d 7014 btrfs_end_transaction_throttle(trans, root);
b44c59a8 7015out_notrans:
33345d01 7016 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
76dda93c 7017 up_read(&root->fs_info->subvol_sem);
9ed74f2d 7018
39279cc3
CM
7019 return ret;
7020}
7021
d352ac68
CM
7022/*
7023 * some fairly slow code that needs optimization. This walks the list
7024 * of all the inodes with pending delalloc and forces them to disk.
7025 */
24bbcf04 7026int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
ea8c2819
CM
7027{
7028 struct list_head *head = &root->fs_info->delalloc_inodes;
7029 struct btrfs_inode *binode;
5b21f2ed 7030 struct inode *inode;
ea8c2819 7031
c146afad
YZ
7032 if (root->fs_info->sb->s_flags & MS_RDONLY)
7033 return -EROFS;
7034
75eff68e 7035 spin_lock(&root->fs_info->delalloc_lock);
d397712b 7036 while (!list_empty(head)) {
ea8c2819
CM
7037 binode = list_entry(head->next, struct btrfs_inode,
7038 delalloc_inodes);
5b21f2ed
ZY
7039 inode = igrab(&binode->vfs_inode);
7040 if (!inode)
7041 list_del_init(&binode->delalloc_inodes);
75eff68e 7042 spin_unlock(&root->fs_info->delalloc_lock);
5b21f2ed 7043 if (inode) {
8c8bee1d 7044 filemap_flush(inode->i_mapping);
24bbcf04
YZ
7045 if (delay_iput)
7046 btrfs_add_delayed_iput(inode);
7047 else
7048 iput(inode);
5b21f2ed
ZY
7049 }
7050 cond_resched();
75eff68e 7051 spin_lock(&root->fs_info->delalloc_lock);
ea8c2819 7052 }
75eff68e 7053 spin_unlock(&root->fs_info->delalloc_lock);
8c8bee1d
CM
7054
7055 /* the filemap_flush will queue IO into the worker threads, but
7056 * we have to make sure the IO is actually started and that
7057 * ordered extents get created before we return
7058 */
7059 atomic_inc(&root->fs_info->async_submit_draining);
d397712b 7060 while (atomic_read(&root->fs_info->nr_async_submits) ||
771ed689 7061 atomic_read(&root->fs_info->async_delalloc_pages)) {
8c8bee1d 7062 wait_event(root->fs_info->async_submit_wait,
771ed689
CM
7063 (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
7064 atomic_read(&root->fs_info->async_delalloc_pages) == 0));
8c8bee1d
CM
7065 }
7066 atomic_dec(&root->fs_info->async_submit_draining);
ea8c2819
CM
7067 return 0;
7068}
7069
39279cc3
CM
7070static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
7071 const char *symname)
7072{
7073 struct btrfs_trans_handle *trans;
7074 struct btrfs_root *root = BTRFS_I(dir)->root;
7075 struct btrfs_path *path;
7076 struct btrfs_key key;
1832a6d5 7077 struct inode *inode = NULL;
39279cc3
CM
7078 int err;
7079 int drop_inode = 0;
7080 u64 objectid;
00e4e6b3 7081 u64 index = 0 ;
39279cc3
CM
7082 int name_len;
7083 int datasize;
5f39d397 7084 unsigned long ptr;
39279cc3 7085 struct btrfs_file_extent_item *ei;
5f39d397 7086 struct extent_buffer *leaf;
1832a6d5 7087 unsigned long nr = 0;
39279cc3
CM
7088
7089 name_len = strlen(symname) + 1;
7090 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
7091 return -ENAMETOOLONG;
1832a6d5 7092
9ed74f2d
JB
7093 /*
7094 * 2 items for inode item and ref
7095 * 2 items for dir items
7096 * 1 item for xattr if selinux is on
7097 */
a22285a6
YZ
7098 trans = btrfs_start_transaction(root, 5);
7099 if (IS_ERR(trans))
7100 return PTR_ERR(trans);
1832a6d5 7101
581bb050
LZ
7102 err = btrfs_find_free_ino(root, &objectid);
7103 if (err)
7104 goto out_unlock;
7105
aec7477b 7106 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
33345d01 7107 dentry->d_name.len, btrfs_ino(dir), objectid,
d82a6f1d 7108 S_IFLNK|S_IRWXUGO, &index);
7cf96da3
TI
7109 if (IS_ERR(inode)) {
7110 err = PTR_ERR(inode);
39279cc3 7111 goto out_unlock;
7cf96da3 7112 }
39279cc3 7113
2a7dba39 7114 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
33268eaf
JB
7115 if (err) {
7116 drop_inode = 1;
7117 goto out_unlock;
7118 }
7119
a1b075d2 7120 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
39279cc3
CM
7121 if (err)
7122 drop_inode = 1;
7123 else {
7124 inode->i_mapping->a_ops = &btrfs_aops;
04160088 7125 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
39279cc3
CM
7126 inode->i_fop = &btrfs_file_operations;
7127 inode->i_op = &btrfs_file_inode_operations;
d1310b2e 7128 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
39279cc3 7129 }
39279cc3
CM
7130 if (drop_inode)
7131 goto out_unlock;
7132
7133 path = btrfs_alloc_path();
d8926bb3
MF
7134 if (!path) {
7135 err = -ENOMEM;
7136 drop_inode = 1;
7137 goto out_unlock;
7138 }
33345d01 7139 key.objectid = btrfs_ino(inode);
39279cc3 7140 key.offset = 0;
39279cc3
CM
7141 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
7142 datasize = btrfs_file_extent_calc_inline_size(name_len);
7143 err = btrfs_insert_empty_item(trans, root, path, &key,
7144 datasize);
54aa1f4d
CM
7145 if (err) {
7146 drop_inode = 1;
b0839166 7147 btrfs_free_path(path);
54aa1f4d
CM
7148 goto out_unlock;
7149 }
5f39d397
CM
7150 leaf = path->nodes[0];
7151 ei = btrfs_item_ptr(leaf, path->slots[0],
7152 struct btrfs_file_extent_item);
7153 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
7154 btrfs_set_file_extent_type(leaf, ei,
39279cc3 7155 BTRFS_FILE_EXTENT_INLINE);
c8b97818
CM
7156 btrfs_set_file_extent_encryption(leaf, ei, 0);
7157 btrfs_set_file_extent_compression(leaf, ei, 0);
7158 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
7159 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
7160
39279cc3 7161 ptr = btrfs_file_extent_inline_start(ei);
5f39d397
CM
7162 write_extent_buffer(leaf, symname, ptr, name_len);
7163 btrfs_mark_buffer_dirty(leaf);
39279cc3 7164 btrfs_free_path(path);
5f39d397 7165
39279cc3
CM
7166 inode->i_op = &btrfs_symlink_inode_operations;
7167 inode->i_mapping->a_ops = &btrfs_symlink_aops;
04160088 7168 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
d899e052 7169 inode_set_bytes(inode, name_len);
dbe674a9 7170 btrfs_i_size_write(inode, name_len - 1);
54aa1f4d
CM
7171 err = btrfs_update_inode(trans, root, inode);
7172 if (err)
7173 drop_inode = 1;
39279cc3
CM
7174
7175out_unlock:
d3c2fdcf 7176 nr = trans->blocks_used;
ab78c84d 7177 btrfs_end_transaction_throttle(trans, root);
39279cc3
CM
7178 if (drop_inode) {
7179 inode_dec_link_count(inode);
7180 iput(inode);
7181 }
d3c2fdcf 7182 btrfs_btree_balance_dirty(root, nr);
39279cc3
CM
7183 return err;
7184}
16432985 7185
0af3d00b
JB
7186static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
7187 u64 start, u64 num_bytes, u64 min_size,
7188 loff_t actual_len, u64 *alloc_hint,
7189 struct btrfs_trans_handle *trans)
d899e052 7190{
d899e052
YZ
7191 struct btrfs_root *root = BTRFS_I(inode)->root;
7192 struct btrfs_key ins;
d899e052 7193 u64 cur_offset = start;
55a61d1d 7194 u64 i_size;
d899e052 7195 int ret = 0;
0af3d00b 7196 bool own_trans = true;
d899e052 7197
0af3d00b
JB
7198 if (trans)
7199 own_trans = false;
d899e052 7200 while (num_bytes > 0) {
0af3d00b
JB
7201 if (own_trans) {
7202 trans = btrfs_start_transaction(root, 3);
7203 if (IS_ERR(trans)) {
7204 ret = PTR_ERR(trans);
7205 break;
7206 }
5a303d5d
YZ
7207 }
7208
efa56464
YZ
7209 ret = btrfs_reserve_extent(trans, root, num_bytes, min_size,
7210 0, *alloc_hint, (u64)-1, &ins, 1);
5a303d5d 7211 if (ret) {
0af3d00b
JB
7212 if (own_trans)
7213 btrfs_end_transaction(trans, root);
a22285a6 7214 break;
d899e052 7215 }
5a303d5d 7216
d899e052
YZ
7217 ret = insert_reserved_file_extent(trans, inode,
7218 cur_offset, ins.objectid,
7219 ins.offset, ins.offset,
920bbbfb 7220 ins.offset, 0, 0, 0,
d899e052
YZ
7221 BTRFS_FILE_EXTENT_PREALLOC);
7222 BUG_ON(ret);
a1ed835e
CM
7223 btrfs_drop_extent_cache(inode, cur_offset,
7224 cur_offset + ins.offset -1, 0);
5a303d5d 7225
d899e052
YZ
7226 num_bytes -= ins.offset;
7227 cur_offset += ins.offset;
efa56464 7228 *alloc_hint = ins.objectid + ins.offset;
5a303d5d 7229
d899e052 7230 inode->i_ctime = CURRENT_TIME;
6cbff00f 7231 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
d899e052 7232 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
efa56464
YZ
7233 (actual_len > inode->i_size) &&
7234 (cur_offset > inode->i_size)) {
d1ea6a61 7235 if (cur_offset > actual_len)
55a61d1d 7236 i_size = actual_len;
d1ea6a61 7237 else
55a61d1d
JB
7238 i_size = cur_offset;
7239 i_size_write(inode, i_size);
7240 btrfs_ordered_update_i_size(inode, i_size, NULL);
5a303d5d
YZ
7241 }
7242
d899e052
YZ
7243 ret = btrfs_update_inode(trans, root, inode);
7244 BUG_ON(ret);
d899e052 7245
0af3d00b
JB
7246 if (own_trans)
7247 btrfs_end_transaction(trans, root);
5a303d5d 7248 }
d899e052
YZ
7249 return ret;
7250}
7251
0af3d00b
JB
7252int btrfs_prealloc_file_range(struct inode *inode, int mode,
7253 u64 start, u64 num_bytes, u64 min_size,
7254 loff_t actual_len, u64 *alloc_hint)
7255{
7256 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
7257 min_size, actual_len, alloc_hint,
7258 NULL);
7259}
7260
7261int btrfs_prealloc_file_range_trans(struct inode *inode,
7262 struct btrfs_trans_handle *trans, int mode,
7263 u64 start, u64 num_bytes, u64 min_size,
7264 loff_t actual_len, u64 *alloc_hint)
7265{
7266 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
7267 min_size, actual_len, alloc_hint, trans);
7268}
7269
e6dcd2dc
CM
7270static int btrfs_set_page_dirty(struct page *page)
7271{
e6dcd2dc
CM
7272 return __set_page_dirty_nobuffers(page);
7273}
7274
10556cb2 7275static int btrfs_permission(struct inode *inode, int mask)
fdebe2bd 7276{
b83cc969 7277 struct btrfs_root *root = BTRFS_I(inode)->root;
cb6db4e5 7278 umode_t mode = inode->i_mode;
b83cc969 7279
cb6db4e5
JM
7280 if (mask & MAY_WRITE &&
7281 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
7282 if (btrfs_root_readonly(root))
7283 return -EROFS;
7284 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
7285 return -EACCES;
7286 }
2830ba7f 7287 return generic_permission(inode, mask);
fdebe2bd 7288}
39279cc3 7289
6e1d5dcc 7290static const struct inode_operations btrfs_dir_inode_operations = {
3394e160 7291 .getattr = btrfs_getattr,
39279cc3
CM
7292 .lookup = btrfs_lookup,
7293 .create = btrfs_create,
7294 .unlink = btrfs_unlink,
7295 .link = btrfs_link,
7296 .mkdir = btrfs_mkdir,
7297 .rmdir = btrfs_rmdir,
7298 .rename = btrfs_rename,
7299 .symlink = btrfs_symlink,
7300 .setattr = btrfs_setattr,
618e21d5 7301 .mknod = btrfs_mknod,
95819c05
CH
7302 .setxattr = btrfs_setxattr,
7303 .getxattr = btrfs_getxattr,
5103e947 7304 .listxattr = btrfs_listxattr,
95819c05 7305 .removexattr = btrfs_removexattr,
fdebe2bd 7306 .permission = btrfs_permission,
4e34e719 7307 .get_acl = btrfs_get_acl,
39279cc3 7308};
6e1d5dcc 7309static const struct inode_operations btrfs_dir_ro_inode_operations = {
39279cc3 7310 .lookup = btrfs_lookup,
fdebe2bd 7311 .permission = btrfs_permission,
4e34e719 7312 .get_acl = btrfs_get_acl,
39279cc3 7313};
76dda93c 7314
828c0950 7315static const struct file_operations btrfs_dir_file_operations = {
39279cc3
CM
7316 .llseek = generic_file_llseek,
7317 .read = generic_read_dir,
cbdf5a24 7318 .readdir = btrfs_real_readdir,
34287aa3 7319 .unlocked_ioctl = btrfs_ioctl,
39279cc3 7320#ifdef CONFIG_COMPAT
34287aa3 7321 .compat_ioctl = btrfs_ioctl,
39279cc3 7322#endif
6bf13c0c 7323 .release = btrfs_release_file,
e02119d5 7324 .fsync = btrfs_sync_file,
39279cc3
CM
7325};
7326
d1310b2e 7327static struct extent_io_ops btrfs_extent_io_ops = {
07157aac 7328 .fill_delalloc = run_delalloc_range,
065631f6 7329 .submit_bio_hook = btrfs_submit_bio_hook,
239b14b3 7330 .merge_bio_hook = btrfs_merge_bio_hook,
07157aac 7331 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
e6dcd2dc 7332 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
247e743c 7333 .writepage_start_hook = btrfs_writepage_start_hook,
b0c68f8b
CM
7334 .set_bit_hook = btrfs_set_bit_hook,
7335 .clear_bit_hook = btrfs_clear_bit_hook,
9ed74f2d
JB
7336 .merge_extent_hook = btrfs_merge_extent_hook,
7337 .split_extent_hook = btrfs_split_extent_hook,
07157aac
CM
7338};
7339
35054394
CM
7340/*
7341 * btrfs doesn't support the bmap operation because swapfiles
7342 * use bmap to make a mapping of extents in the file. They assume
7343 * these extents won't change over the life of the file and they
7344 * use the bmap result to do IO directly to the drive.
7345 *
7346 * the btrfs bmap call would return logical addresses that aren't
7347 * suitable for IO and they also will change frequently as COW
7348 * operations happen. So, swapfile + btrfs == corruption.
7349 *
7350 * For now we're avoiding this by dropping bmap.
7351 */
7f09410b 7352static const struct address_space_operations btrfs_aops = {
39279cc3
CM
7353 .readpage = btrfs_readpage,
7354 .writepage = btrfs_writepage,
b293f02e 7355 .writepages = btrfs_writepages,
3ab2fb5a 7356 .readpages = btrfs_readpages,
16432985 7357 .direct_IO = btrfs_direct_IO,
a52d9a80
CM
7358 .invalidatepage = btrfs_invalidatepage,
7359 .releasepage = btrfs_releasepage,
e6dcd2dc 7360 .set_page_dirty = btrfs_set_page_dirty,
465fdd97 7361 .error_remove_page = generic_error_remove_page,
39279cc3
CM
7362};
7363
7f09410b 7364static const struct address_space_operations btrfs_symlink_aops = {
39279cc3
CM
7365 .readpage = btrfs_readpage,
7366 .writepage = btrfs_writepage,
2bf5a725
CM
7367 .invalidatepage = btrfs_invalidatepage,
7368 .releasepage = btrfs_releasepage,
39279cc3
CM
7369};
7370
6e1d5dcc 7371static const struct inode_operations btrfs_file_inode_operations = {
39279cc3
CM
7372 .getattr = btrfs_getattr,
7373 .setattr = btrfs_setattr,
95819c05
CH
7374 .setxattr = btrfs_setxattr,
7375 .getxattr = btrfs_getxattr,
5103e947 7376 .listxattr = btrfs_listxattr,
95819c05 7377 .removexattr = btrfs_removexattr,
fdebe2bd 7378 .permission = btrfs_permission,
1506fcc8 7379 .fiemap = btrfs_fiemap,
4e34e719 7380 .get_acl = btrfs_get_acl,
39279cc3 7381};
6e1d5dcc 7382static const struct inode_operations btrfs_special_inode_operations = {
618e21d5
JB
7383 .getattr = btrfs_getattr,
7384 .setattr = btrfs_setattr,
fdebe2bd 7385 .permission = btrfs_permission,
95819c05
CH
7386 .setxattr = btrfs_setxattr,
7387 .getxattr = btrfs_getxattr,
33268eaf 7388 .listxattr = btrfs_listxattr,
95819c05 7389 .removexattr = btrfs_removexattr,
4e34e719 7390 .get_acl = btrfs_get_acl,
618e21d5 7391};
6e1d5dcc 7392static const struct inode_operations btrfs_symlink_inode_operations = {
39279cc3
CM
7393 .readlink = generic_readlink,
7394 .follow_link = page_follow_link_light,
7395 .put_link = page_put_link,
f209561a 7396 .getattr = btrfs_getattr,
fdebe2bd 7397 .permission = btrfs_permission,
0279b4cd
JO
7398 .setxattr = btrfs_setxattr,
7399 .getxattr = btrfs_getxattr,
7400 .listxattr = btrfs_listxattr,
7401 .removexattr = btrfs_removexattr,
4e34e719 7402 .get_acl = btrfs_get_acl,
39279cc3 7403};
76dda93c 7404
82d339d9 7405const struct dentry_operations btrfs_dentry_operations = {
76dda93c 7406 .d_delete = btrfs_dentry_delete,
b4aff1f8 7407 .d_release = btrfs_dentry_release,
76dda93c 7408};