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