]> git.ipfire.org Git - people/arne_f/kernel.git/blame - fs/btrfs/extent-tree.c
Btrfs: try to cleanup delayed refs while freeing extents
[people/arne_f/kernel.git] / fs / btrfs / extent-tree.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 */
ec6b910f 18#include <linux/sched.h>
edbd8d4e 19#include <linux/pagemap.h>
ec44a35c 20#include <linux/writeback.h>
21af804c 21#include <linux/blkdev.h>
b7a9f29f 22#include <linux/sort.h>
4184ea7f 23#include <linux/rcupdate.h>
4b4e25f2 24#include "compat.h"
74493f7a 25#include "hash.h"
a5eb62e3 26#include "crc32c.h"
fec577fb
CM
27#include "ctree.h"
28#include "disk-io.h"
29#include "print-tree.h"
e089f05c 30#include "transaction.h"
0b86a832 31#include "volumes.h"
925baedd 32#include "locking.h"
31153d81 33#include "ref-cache.h"
fec577fb 34
31840ae1
ZY
35#define PENDING_EXTENT_INSERT 0
36#define PENDING_EXTENT_DELETE 1
37#define PENDING_BACKREF_UPDATE 2
38
39struct pending_extent_op {
40 int type;
41 u64 bytenr;
42 u64 num_bytes;
43 u64 parent;
44 u64 orig_parent;
45 u64 generation;
46 u64 orig_generation;
47 int level;
f3465ca4
JB
48 struct list_head list;
49 int del;
31840ae1
ZY
50};
51
56bec294
CM
52static int __btrfs_alloc_reserved_extent(struct btrfs_trans_handle *trans,
53 struct btrfs_root *root, u64 parent,
54 u64 root_objectid, u64 ref_generation,
55 u64 owner, struct btrfs_key *ins,
56 int ref_mod);
57static int update_reserved_extents(struct btrfs_root *root,
58 u64 bytenr, u64 num, int reserve);
f3465ca4
JB
59static int pin_down_bytes(struct btrfs_trans_handle *trans,
60 struct btrfs_root *root,
61 u64 bytenr, u64 num_bytes, int is_data);
62static int update_block_group(struct btrfs_trans_handle *trans,
63 struct btrfs_root *root,
64 u64 bytenr, u64 num_bytes, int alloc,
65 int mark_free);
56bec294
CM
66static noinline int __btrfs_free_extent(struct btrfs_trans_handle *trans,
67 struct btrfs_root *root,
68 u64 bytenr, u64 num_bytes, u64 parent,
69 u64 root_objectid, u64 ref_generation,
70 u64 owner_objectid, int pin,
71 int ref_to_drop);
d548ee51 72
6a63209f
JB
73static int do_chunk_alloc(struct btrfs_trans_handle *trans,
74 struct btrfs_root *extent_root, u64 alloc_bytes,
75 u64 flags, int force);
76
0f9dd46c
JB
77static int block_group_bits(struct btrfs_block_group_cache *cache, u64 bits)
78{
79 return (cache->flags & bits) == bits;
80}
81
82/*
83 * this adds the block group to the fs_info rb tree for the block group
84 * cache
85 */
b2950863 86static int btrfs_add_block_group_cache(struct btrfs_fs_info *info,
0f9dd46c
JB
87 struct btrfs_block_group_cache *block_group)
88{
89 struct rb_node **p;
90 struct rb_node *parent = NULL;
91 struct btrfs_block_group_cache *cache;
92
93 spin_lock(&info->block_group_cache_lock);
94 p = &info->block_group_cache_tree.rb_node;
95
96 while (*p) {
97 parent = *p;
98 cache = rb_entry(parent, struct btrfs_block_group_cache,
99 cache_node);
100 if (block_group->key.objectid < cache->key.objectid) {
101 p = &(*p)->rb_left;
102 } else if (block_group->key.objectid > cache->key.objectid) {
103 p = &(*p)->rb_right;
104 } else {
105 spin_unlock(&info->block_group_cache_lock);
106 return -EEXIST;
107 }
108 }
109
110 rb_link_node(&block_group->cache_node, parent, p);
111 rb_insert_color(&block_group->cache_node,
112 &info->block_group_cache_tree);
113 spin_unlock(&info->block_group_cache_lock);
114
115 return 0;
116}
117
118/*
119 * This will return the block group at or after bytenr if contains is 0, else
120 * it will return the block group that contains the bytenr
121 */
122static struct btrfs_block_group_cache *
123block_group_cache_tree_search(struct btrfs_fs_info *info, u64 bytenr,
124 int contains)
125{
126 struct btrfs_block_group_cache *cache, *ret = NULL;
127 struct rb_node *n;
128 u64 end, start;
129
130 spin_lock(&info->block_group_cache_lock);
131 n = info->block_group_cache_tree.rb_node;
132
133 while (n) {
134 cache = rb_entry(n, struct btrfs_block_group_cache,
135 cache_node);
136 end = cache->key.objectid + cache->key.offset - 1;
137 start = cache->key.objectid;
138
139 if (bytenr < start) {
140 if (!contains && (!ret || start < ret->key.objectid))
141 ret = cache;
142 n = n->rb_left;
143 } else if (bytenr > start) {
144 if (contains && bytenr <= end) {
145 ret = cache;
146 break;
147 }
148 n = n->rb_right;
149 } else {
150 ret = cache;
151 break;
152 }
153 }
d2fb3437
YZ
154 if (ret)
155 atomic_inc(&ret->count);
0f9dd46c
JB
156 spin_unlock(&info->block_group_cache_lock);
157
158 return ret;
159}
160
161/*
162 * this is only called by cache_block_group, since we could have freed extents
163 * we need to check the pinned_extents for any extents that can't be used yet
164 * since their free space will be released as soon as the transaction commits.
165 */
166static int add_new_free_space(struct btrfs_block_group_cache *block_group,
167 struct btrfs_fs_info *info, u64 start, u64 end)
168{
169 u64 extent_start, extent_end, size;
170 int ret;
171
25179201 172 mutex_lock(&info->pinned_mutex);
0f9dd46c
JB
173 while (start < end) {
174 ret = find_first_extent_bit(&info->pinned_extents, start,
175 &extent_start, &extent_end,
176 EXTENT_DIRTY);
177 if (ret)
178 break;
179
180 if (extent_start == start) {
181 start = extent_end + 1;
182 } else if (extent_start > start && extent_start < end) {
183 size = extent_start - start;
ea6a478e
JB
184 ret = btrfs_add_free_space(block_group, start,
185 size);
0f9dd46c
JB
186 BUG_ON(ret);
187 start = extent_end + 1;
188 } else {
189 break;
190 }
191 }
192
193 if (start < end) {
194 size = end - start;
ea6a478e 195 ret = btrfs_add_free_space(block_group, start, size);
0f9dd46c
JB
196 BUG_ON(ret);
197 }
25179201 198 mutex_unlock(&info->pinned_mutex);
0f9dd46c
JB
199
200 return 0;
201}
202
a512bbf8
YZ
203static int remove_sb_from_cache(struct btrfs_root *root,
204 struct btrfs_block_group_cache *cache)
205{
206 u64 bytenr;
207 u64 *logical;
208 int stripe_len;
209 int i, nr, ret;
210
211 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
212 bytenr = btrfs_sb_offset(i);
213 ret = btrfs_rmap_block(&root->fs_info->mapping_tree,
214 cache->key.objectid, bytenr, 0,
215 &logical, &nr, &stripe_len);
216 BUG_ON(ret);
217 while (nr--) {
218 btrfs_remove_free_space(cache, logical[nr],
219 stripe_len);
220 }
221 kfree(logical);
222 }
223 return 0;
224}
225
e37c9e69
CM
226static int cache_block_group(struct btrfs_root *root,
227 struct btrfs_block_group_cache *block_group)
228{
229 struct btrfs_path *path;
ef8bbdfe 230 int ret = 0;
e37c9e69 231 struct btrfs_key key;
5f39d397 232 struct extent_buffer *leaf;
e37c9e69 233 int slot;
e4404d6e 234 u64 last;
e37c9e69 235
00f5c795
CM
236 if (!block_group)
237 return 0;
238
e37c9e69 239 root = root->fs_info->extent_root;
e37c9e69
CM
240
241 if (block_group->cached)
242 return 0;
f510cfec 243
e37c9e69
CM
244 path = btrfs_alloc_path();
245 if (!path)
246 return -ENOMEM;
7d7d6068 247
2cc58cf2 248 path->reada = 2;
5cd57b2c
CM
249 /*
250 * we get into deadlocks with paths held by callers of this function.
251 * since the alloc_mutex is protecting things right now, just
252 * skip the locking here
253 */
254 path->skip_locking = 1;
e4404d6e
YZ
255 last = max_t(u64, block_group->key.objectid, BTRFS_SUPER_INFO_OFFSET);
256 key.objectid = last;
e37c9e69
CM
257 key.offset = 0;
258 btrfs_set_key_type(&key, BTRFS_EXTENT_ITEM_KEY);
259 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
260 if (ret < 0)
ef8bbdfe 261 goto err;
a512bbf8 262
d397712b 263 while (1) {
5f39d397 264 leaf = path->nodes[0];
e37c9e69 265 slot = path->slots[0];
5f39d397 266 if (slot >= btrfs_header_nritems(leaf)) {
e37c9e69 267 ret = btrfs_next_leaf(root, path);
54aa1f4d
CM
268 if (ret < 0)
269 goto err;
0f9dd46c 270 if (ret == 0)
e37c9e69 271 continue;
0f9dd46c 272 else
e37c9e69 273 break;
e37c9e69 274 }
5f39d397 275 btrfs_item_key_to_cpu(leaf, &key, slot);
0f9dd46c 276 if (key.objectid < block_group->key.objectid)
7d7d6068 277 goto next;
0f9dd46c 278
e37c9e69 279 if (key.objectid >= block_group->key.objectid +
0f9dd46c 280 block_group->key.offset)
e37c9e69 281 break;
7d7d6068 282
e37c9e69 283 if (btrfs_key_type(&key) == BTRFS_EXTENT_ITEM_KEY) {
0f9dd46c
JB
284 add_new_free_space(block_group, root->fs_info, last,
285 key.objectid);
286
7d7d6068 287 last = key.objectid + key.offset;
e37c9e69 288 }
7d7d6068 289next:
e37c9e69
CM
290 path->slots[0]++;
291 }
292
0f9dd46c
JB
293 add_new_free_space(block_group, root->fs_info, last,
294 block_group->key.objectid +
295 block_group->key.offset);
296
a512bbf8 297 remove_sb_from_cache(root, block_group);
e37c9e69 298 block_group->cached = 1;
ef8bbdfe 299 ret = 0;
54aa1f4d 300err:
e37c9e69 301 btrfs_free_path(path);
ef8bbdfe 302 return ret;
e37c9e69
CM
303}
304
0f9dd46c
JB
305/*
306 * return the block group that starts at or after bytenr
307 */
d397712b
CM
308static struct btrfs_block_group_cache *
309btrfs_lookup_first_block_group(struct btrfs_fs_info *info, u64 bytenr)
0ef3e66b 310{
0f9dd46c 311 struct btrfs_block_group_cache *cache;
0ef3e66b 312
0f9dd46c 313 cache = block_group_cache_tree_search(info, bytenr, 0);
0ef3e66b 314
0f9dd46c 315 return cache;
0ef3e66b
CM
316}
317
0f9dd46c
JB
318/*
319 * return the block group that contains teh given bytenr
320 */
d397712b
CM
321struct btrfs_block_group_cache *btrfs_lookup_block_group(
322 struct btrfs_fs_info *info,
323 u64 bytenr)
be744175 324{
0f9dd46c 325 struct btrfs_block_group_cache *cache;
be744175 326
0f9dd46c 327 cache = block_group_cache_tree_search(info, bytenr, 1);
96b5179d 328
0f9dd46c 329 return cache;
be744175 330}
0b86a832 331
d2fb3437
YZ
332static inline void put_block_group(struct btrfs_block_group_cache *cache)
333{
334 if (atomic_dec_and_test(&cache->count))
335 kfree(cache);
336}
337
0f9dd46c
JB
338static struct btrfs_space_info *__find_space_info(struct btrfs_fs_info *info,
339 u64 flags)
6324fbf3 340{
0f9dd46c 341 struct list_head *head = &info->space_info;
0f9dd46c 342 struct btrfs_space_info *found;
4184ea7f
CM
343
344 rcu_read_lock();
345 list_for_each_entry_rcu(found, head, list) {
346 if (found->flags == flags) {
347 rcu_read_unlock();
0f9dd46c 348 return found;
4184ea7f 349 }
0f9dd46c 350 }
4184ea7f 351 rcu_read_unlock();
0f9dd46c 352 return NULL;
6324fbf3
CM
353}
354
4184ea7f
CM
355/*
356 * after adding space to the filesystem, we need to clear the full flags
357 * on all the space infos.
358 */
359void btrfs_clear_space_info_full(struct btrfs_fs_info *info)
360{
361 struct list_head *head = &info->space_info;
362 struct btrfs_space_info *found;
363
364 rcu_read_lock();
365 list_for_each_entry_rcu(found, head, list)
366 found->full = 0;
367 rcu_read_unlock();
368}
369
80eb234a
JB
370static u64 div_factor(u64 num, int factor)
371{
372 if (factor == 10)
373 return num;
374 num *= factor;
375 do_div(num, 10);
376 return num;
377}
378
d2fb3437
YZ
379u64 btrfs_find_block_group(struct btrfs_root *root,
380 u64 search_start, u64 search_hint, int owner)
cd1bc465 381{
96b5179d 382 struct btrfs_block_group_cache *cache;
cd1bc465 383 u64 used;
d2fb3437
YZ
384 u64 last = max(search_hint, search_start);
385 u64 group_start = 0;
31f3c99b 386 int full_search = 0;
d2fb3437 387 int factor = 9;
0ef3e66b 388 int wrapped = 0;
31f3c99b 389again:
e8569813
ZY
390 while (1) {
391 cache = btrfs_lookup_first_block_group(root->fs_info, last);
0f9dd46c
JB
392 if (!cache)
393 break;
96b5179d 394
c286ac48 395 spin_lock(&cache->lock);
96b5179d
CM
396 last = cache->key.objectid + cache->key.offset;
397 used = btrfs_block_group_used(&cache->item);
398
d2fb3437
YZ
399 if ((full_search || !cache->ro) &&
400 block_group_bits(cache, BTRFS_BLOCK_GROUP_METADATA)) {
e8569813 401 if (used + cache->pinned + cache->reserved <
d2fb3437
YZ
402 div_factor(cache->key.offset, factor)) {
403 group_start = cache->key.objectid;
c286ac48 404 spin_unlock(&cache->lock);
d2fb3437 405 put_block_group(cache);
8790d502
CM
406 goto found;
407 }
6324fbf3 408 }
c286ac48 409 spin_unlock(&cache->lock);
d2fb3437 410 put_block_group(cache);
de428b63 411 cond_resched();
cd1bc465 412 }
0ef3e66b
CM
413 if (!wrapped) {
414 last = search_start;
415 wrapped = 1;
416 goto again;
417 }
418 if (!full_search && factor < 10) {
be744175 419 last = search_start;
31f3c99b 420 full_search = 1;
0ef3e66b 421 factor = 10;
31f3c99b
CM
422 goto again;
423 }
be744175 424found:
d2fb3437 425 return group_start;
925baedd 426}
0f9dd46c 427
e02119d5 428/* simple helper to search for an existing extent at a given offset */
31840ae1 429int btrfs_lookup_extent(struct btrfs_root *root, u64 start, u64 len)
e02119d5
CM
430{
431 int ret;
432 struct btrfs_key key;
31840ae1 433 struct btrfs_path *path;
e02119d5 434
31840ae1
ZY
435 path = btrfs_alloc_path();
436 BUG_ON(!path);
e02119d5
CM
437 key.objectid = start;
438 key.offset = len;
439 btrfs_set_key_type(&key, BTRFS_EXTENT_ITEM_KEY);
440 ret = btrfs_search_slot(NULL, root->fs_info->extent_root, &key, path,
441 0, 0);
31840ae1 442 btrfs_free_path(path);
7bb86316
CM
443 return ret;
444}
445
d8d5f3e1
CM
446/*
447 * Back reference rules. Back refs have three main goals:
448 *
449 * 1) differentiate between all holders of references to an extent so that
450 * when a reference is dropped we can make sure it was a valid reference
451 * before freeing the extent.
452 *
453 * 2) Provide enough information to quickly find the holders of an extent
454 * if we notice a given block is corrupted or bad.
455 *
456 * 3) Make it easy to migrate blocks for FS shrinking or storage pool
457 * maintenance. This is actually the same as #2, but with a slightly
458 * different use case.
459 *
460 * File extents can be referenced by:
461 *
462 * - multiple snapshots, subvolumes, or different generations in one subvol
31840ae1 463 * - different files inside a single subvolume
d8d5f3e1
CM
464 * - different offsets inside a file (bookend extents in file.c)
465 *
466 * The extent ref structure has fields for:
467 *
468 * - Objectid of the subvolume root
469 * - Generation number of the tree holding the reference
470 * - objectid of the file holding the reference
31840ae1
ZY
471 * - number of references holding by parent node (alway 1 for tree blocks)
472 *
473 * Btree leaf may hold multiple references to a file extent. In most cases,
474 * these references are from same file and the corresponding offsets inside
3bb1a1bc 475 * the file are close together.
d8d5f3e1
CM
476 *
477 * When a file extent is allocated the fields are filled in:
3bb1a1bc 478 * (root_key.objectid, trans->transid, inode objectid, 1)
d8d5f3e1
CM
479 *
480 * When a leaf is cow'd new references are added for every file extent found
31840ae1
ZY
481 * in the leaf. It looks similar to the create case, but trans->transid will
482 * be different when the block is cow'd.
d8d5f3e1 483 *
3bb1a1bc 484 * (root_key.objectid, trans->transid, inode objectid,
31840ae1 485 * number of references in the leaf)
d8d5f3e1 486 *
3bb1a1bc
YZ
487 * When a file extent is removed either during snapshot deletion or
488 * file truncation, we find the corresponding back reference and check
489 * the following fields:
d8d5f3e1 490 *
3bb1a1bc
YZ
491 * (btrfs_header_owner(leaf), btrfs_header_generation(leaf),
492 * inode objectid)
d8d5f3e1
CM
493 *
494 * Btree extents can be referenced by:
495 *
496 * - Different subvolumes
497 * - Different generations of the same subvolume
498 *
d8d5f3e1
CM
499 * When a tree block is created, back references are inserted:
500 *
3bb1a1bc 501 * (root->root_key.objectid, trans->transid, level, 1)
d8d5f3e1 502 *
31840ae1
ZY
503 * When a tree block is cow'd, new back references are added for all the
504 * blocks it points to. If the tree block isn't in reference counted root,
505 * the old back references are removed. These new back references are of
506 * the form (trans->transid will have increased since creation):
d8d5f3e1 507 *
3bb1a1bc 508 * (root->root_key.objectid, trans->transid, level, 1)
d8d5f3e1 509 *
31840ae1 510 * When a backref is in deleting, the following fields are checked:
d8d5f3e1
CM
511 *
512 * if backref was for a tree root:
3bb1a1bc 513 * (btrfs_header_owner(itself), btrfs_header_generation(itself), level)
d8d5f3e1 514 * else
3bb1a1bc 515 * (btrfs_header_owner(parent), btrfs_header_generation(parent), level)
d8d5f3e1 516 *
31840ae1 517 * Back Reference Key composing:
d8d5f3e1 518 *
31840ae1
ZY
519 * The key objectid corresponds to the first byte in the extent, the key
520 * type is set to BTRFS_EXTENT_REF_KEY, and the key offset is the first
521 * byte of parent extent. If a extent is tree root, the key offset is set
522 * to the key objectid.
d8d5f3e1 523 */
31840ae1 524
d397712b 525static noinline int lookup_extent_backref(struct btrfs_trans_handle *trans,
31840ae1 526 struct btrfs_root *root,
3bb1a1bc
YZ
527 struct btrfs_path *path,
528 u64 bytenr, u64 parent,
529 u64 ref_root, u64 ref_generation,
530 u64 owner_objectid, int del)
7bb86316 531{
7bb86316 532 struct btrfs_key key;
31840ae1
ZY
533 struct btrfs_extent_ref *ref;
534 struct extent_buffer *leaf;
3bb1a1bc 535 u64 ref_objectid;
74493f7a
CM
536 int ret;
537
31840ae1
ZY
538 key.objectid = bytenr;
539 key.type = BTRFS_EXTENT_REF_KEY;
540 key.offset = parent;
541
542 ret = btrfs_search_slot(trans, root, &key, path, del ? -1 : 0, 1);
543 if (ret < 0)
544 goto out;
545 if (ret > 0) {
546 ret = -ENOENT;
547 goto out;
548 }
549
550 leaf = path->nodes[0];
551 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_ref);
3bb1a1bc 552 ref_objectid = btrfs_ref_objectid(leaf, ref);
31840ae1 553 if (btrfs_ref_root(leaf, ref) != ref_root ||
3bb1a1bc
YZ
554 btrfs_ref_generation(leaf, ref) != ref_generation ||
555 (ref_objectid != owner_objectid &&
556 ref_objectid != BTRFS_MULTIPLE_OBJECTIDS)) {
31840ae1
ZY
557 ret = -EIO;
558 WARN_ON(1);
559 goto out;
560 }
561 ret = 0;
562out:
563 return ret;
564}
565
d397712b 566static noinline int insert_extent_backref(struct btrfs_trans_handle *trans,
31840ae1
ZY
567 struct btrfs_root *root,
568 struct btrfs_path *path,
569 u64 bytenr, u64 parent,
570 u64 ref_root, u64 ref_generation,
56bec294
CM
571 u64 owner_objectid,
572 int refs_to_add)
31840ae1
ZY
573{
574 struct btrfs_key key;
575 struct extent_buffer *leaf;
576 struct btrfs_extent_ref *ref;
577 u32 num_refs;
578 int ret;
74493f7a 579
74493f7a
CM
580 key.objectid = bytenr;
581 key.type = BTRFS_EXTENT_REF_KEY;
31840ae1 582 key.offset = parent;
74493f7a 583
31840ae1
ZY
584 ret = btrfs_insert_empty_item(trans, root, path, &key, sizeof(*ref));
585 if (ret == 0) {
586 leaf = path->nodes[0];
587 ref = btrfs_item_ptr(leaf, path->slots[0],
588 struct btrfs_extent_ref);
589 btrfs_set_ref_root(leaf, ref, ref_root);
590 btrfs_set_ref_generation(leaf, ref, ref_generation);
591 btrfs_set_ref_objectid(leaf, ref, owner_objectid);
56bec294 592 btrfs_set_ref_num_refs(leaf, ref, refs_to_add);
31840ae1
ZY
593 } else if (ret == -EEXIST) {
594 u64 existing_owner;
56bec294 595
31840ae1
ZY
596 BUG_ON(owner_objectid < BTRFS_FIRST_FREE_OBJECTID);
597 leaf = path->nodes[0];
598 ref = btrfs_item_ptr(leaf, path->slots[0],
599 struct btrfs_extent_ref);
600 if (btrfs_ref_root(leaf, ref) != ref_root ||
601 btrfs_ref_generation(leaf, ref) != ref_generation) {
602 ret = -EIO;
603 WARN_ON(1);
7bb86316 604 goto out;
31840ae1
ZY
605 }
606
607 num_refs = btrfs_ref_num_refs(leaf, ref);
608 BUG_ON(num_refs == 0);
56bec294 609 btrfs_set_ref_num_refs(leaf, ref, num_refs + refs_to_add);
31840ae1
ZY
610
611 existing_owner = btrfs_ref_objectid(leaf, ref);
3bb1a1bc
YZ
612 if (existing_owner != owner_objectid &&
613 existing_owner != BTRFS_MULTIPLE_OBJECTIDS) {
31840ae1
ZY
614 btrfs_set_ref_objectid(leaf, ref,
615 BTRFS_MULTIPLE_OBJECTIDS);
31840ae1
ZY
616 }
617 ret = 0;
618 } else {
7bb86316 619 goto out;
31840ae1 620 }
7bb86316
CM
621 btrfs_mark_buffer_dirty(path->nodes[0]);
622out:
623 btrfs_release_path(root, path);
624 return ret;
74493f7a
CM
625}
626
d397712b 627static noinline int remove_extent_backref(struct btrfs_trans_handle *trans,
31840ae1 628 struct btrfs_root *root,
56bec294
CM
629 struct btrfs_path *path,
630 int refs_to_drop)
31840ae1
ZY
631{
632 struct extent_buffer *leaf;
633 struct btrfs_extent_ref *ref;
634 u32 num_refs;
635 int ret = 0;
636
637 leaf = path->nodes[0];
638 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_ref);
639 num_refs = btrfs_ref_num_refs(leaf, ref);
56bec294
CM
640 BUG_ON(num_refs < refs_to_drop);
641 num_refs -= refs_to_drop;
31840ae1
ZY
642 if (num_refs == 0) {
643 ret = btrfs_del_item(trans, root, path);
644 } else {
645 btrfs_set_ref_num_refs(leaf, ref, num_refs);
646 btrfs_mark_buffer_dirty(leaf);
647 }
648 btrfs_release_path(root, path);
649 return ret;
650}
651
4b4e25f2 652#ifdef BIO_RW_DISCARD
15916de8
CM
653static void btrfs_issue_discard(struct block_device *bdev,
654 u64 start, u64 len)
655{
15916de8 656 blkdev_issue_discard(bdev, start >> 9, len >> 9, GFP_KERNEL);
15916de8 657}
4b4e25f2 658#endif
15916de8 659
1f3c79a2
LH
660static int btrfs_discard_extent(struct btrfs_root *root, u64 bytenr,
661 u64 num_bytes)
662{
663#ifdef BIO_RW_DISCARD
664 int ret;
665 u64 map_length = num_bytes;
666 struct btrfs_multi_bio *multi = NULL;
667
668 /* Tell the block device(s) that the sectors can be discarded */
669 ret = btrfs_map_block(&root->fs_info->mapping_tree, READ,
670 bytenr, &map_length, &multi, 0);
671 if (!ret) {
672 struct btrfs_bio_stripe *stripe = multi->stripes;
673 int i;
674
675 if (map_length > num_bytes)
676 map_length = num_bytes;
677
678 for (i = 0; i < multi->num_stripes; i++, stripe++) {
679 btrfs_issue_discard(stripe->dev->bdev,
680 stripe->physical,
681 map_length);
682 }
683 kfree(multi);
684 }
685
686 return ret;
687#else
688 return 0;
689#endif
690}
691
31840ae1
ZY
692static int __btrfs_update_extent_ref(struct btrfs_trans_handle *trans,
693 struct btrfs_root *root, u64 bytenr,
56bec294 694 u64 num_bytes,
31840ae1
ZY
695 u64 orig_parent, u64 parent,
696 u64 orig_root, u64 ref_root,
697 u64 orig_generation, u64 ref_generation,
3bb1a1bc 698 u64 owner_objectid)
31840ae1
ZY
699{
700 int ret;
56bec294 701 int pin = owner_objectid < BTRFS_FIRST_FREE_OBJECTID;
31840ae1 702
56bec294
CM
703 ret = btrfs_update_delayed_ref(trans, bytenr, num_bytes,
704 orig_parent, parent, orig_root,
705 ref_root, orig_generation,
706 ref_generation, owner_objectid, pin);
31840ae1 707 BUG_ON(ret);
31840ae1
ZY
708 return ret;
709}
710
711int btrfs_update_extent_ref(struct btrfs_trans_handle *trans,
712 struct btrfs_root *root, u64 bytenr,
56bec294 713 u64 num_bytes, u64 orig_parent, u64 parent,
31840ae1 714 u64 ref_root, u64 ref_generation,
3bb1a1bc 715 u64 owner_objectid)
31840ae1
ZY
716{
717 int ret;
718 if (ref_root == BTRFS_TREE_LOG_OBJECTID &&
719 owner_objectid < BTRFS_FIRST_FREE_OBJECTID)
720 return 0;
56bec294
CM
721
722 ret = __btrfs_update_extent_ref(trans, root, bytenr, num_bytes,
723 orig_parent, parent, ref_root,
724 ref_root, ref_generation,
725 ref_generation, owner_objectid);
31840ae1
ZY
726 return ret;
727}
925baedd 728static int __btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
31840ae1 729 struct btrfs_root *root, u64 bytenr,
56bec294 730 u64 num_bytes,
31840ae1
ZY
731 u64 orig_parent, u64 parent,
732 u64 orig_root, u64 ref_root,
733 u64 orig_generation, u64 ref_generation,
3bb1a1bc 734 u64 owner_objectid)
56bec294
CM
735{
736 int ret;
737
738 ret = btrfs_add_delayed_ref(trans, bytenr, num_bytes, parent, ref_root,
739 ref_generation, owner_objectid,
740 BTRFS_ADD_DELAYED_REF, 0);
741 BUG_ON(ret);
742 return ret;
743}
744
745static noinline_for_stack int add_extent_ref(struct btrfs_trans_handle *trans,
746 struct btrfs_root *root, u64 bytenr,
747 u64 num_bytes, u64 parent, u64 ref_root,
748 u64 ref_generation, u64 owner_objectid,
749 int refs_to_add)
02217ed2 750{
5caf2a00 751 struct btrfs_path *path;
02217ed2 752 int ret;
e2fa7227 753 struct btrfs_key key;
5f39d397 754 struct extent_buffer *l;
234b63a0 755 struct btrfs_extent_item *item;
cf27e1ee 756 u32 refs;
037e6390 757
5caf2a00 758 path = btrfs_alloc_path();
54aa1f4d
CM
759 if (!path)
760 return -ENOMEM;
26b8003f 761
3c12ac72 762 path->reada = 1;
db94535d 763 key.objectid = bytenr;
31840ae1 764 key.type = BTRFS_EXTENT_ITEM_KEY;
56bec294 765 key.offset = num_bytes;
31840ae1 766
56bec294
CM
767 /* first find the extent item and update its reference count */
768 ret = btrfs_search_slot(trans, root->fs_info->extent_root, &key,
769 path, 0, 1);
54aa1f4d
CM
770 if (ret < 0)
771 return ret;
31840ae1 772
56bec294
CM
773 if (ret > 0) {
774 WARN_ON(1);
775 btrfs_free_path(path);
776 return -EIO;
777 }
5f39d397 778 l = path->nodes[0];
31840ae1
ZY
779
780 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
771ed689
CM
781 if (key.objectid != bytenr) {
782 btrfs_print_leaf(root->fs_info->extent_root, path->nodes[0]);
d397712b
CM
783 printk(KERN_ERR "btrfs wanted %llu found %llu\n",
784 (unsigned long long)bytenr,
785 (unsigned long long)key.objectid);
771ed689
CM
786 BUG();
787 }
31840ae1
ZY
788 BUG_ON(key.type != BTRFS_EXTENT_ITEM_KEY);
789
56bec294
CM
790 item = btrfs_item_ptr(l, path->slots[0], struct btrfs_extent_item);
791
792 refs = btrfs_extent_refs(l, item);
793 btrfs_set_extent_refs(l, item, refs + refs_to_add);
794 btrfs_mark_buffer_dirty(path->nodes[0]);
795
796 btrfs_release_path(root->fs_info->extent_root, path);
797
798 path->reada = 1;
799 /* now insert the actual backref */
800 ret = insert_extent_backref(trans, root->fs_info->extent_root,
801 path, bytenr, parent,
802 ref_root, ref_generation,
803 owner_objectid, refs_to_add);
804 BUG_ON(ret);
805 btrfs_free_path(path);
806 return 0;
807}
808
809int btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
810 struct btrfs_root *root,
811 u64 bytenr, u64 num_bytes, u64 parent,
812 u64 ref_root, u64 ref_generation,
813 u64 owner_objectid)
814{
815 int ret;
816 if (ref_root == BTRFS_TREE_LOG_OBJECTID &&
817 owner_objectid < BTRFS_FIRST_FREE_OBJECTID)
818 return 0;
819
820 ret = __btrfs_inc_extent_ref(trans, root, bytenr, num_bytes, 0, parent,
821 0, ref_root, 0, ref_generation,
822 owner_objectid);
823 return ret;
824}
825
826static int drop_delayed_ref(struct btrfs_trans_handle *trans,
827 struct btrfs_root *root,
828 struct btrfs_delayed_ref_node *node)
829{
830 int ret = 0;
831 struct btrfs_delayed_ref *ref = btrfs_delayed_node_to_ref(node);
832
833 BUG_ON(node->ref_mod == 0);
834 ret = __btrfs_free_extent(trans, root, node->bytenr, node->num_bytes,
835 node->parent, ref->root, ref->generation,
836 ref->owner_objectid, ref->pin, node->ref_mod);
837
838 return ret;
839}
840
841/* helper function to actually process a single delayed ref entry */
842static noinline int run_one_delayed_ref(struct btrfs_trans_handle *trans,
843 struct btrfs_root *root,
844 struct btrfs_delayed_ref_node *node,
845 int insert_reserved)
846{
847 int ret;
848 struct btrfs_delayed_ref *ref;
849
850 if (node->parent == (u64)-1) {
851 struct btrfs_delayed_ref_head *head;
852 /*
853 * we've hit the end of the chain and we were supposed
854 * to insert this extent into the tree. But, it got
855 * deleted before we ever needed to insert it, so all
856 * we have to do is clean up the accounting
857 */
858 if (insert_reserved) {
859 update_reserved_extents(root, node->bytenr,
860 node->num_bytes, 0);
861 }
862 head = btrfs_delayed_node_to_head(node);
863 mutex_unlock(&head->mutex);
864 return 0;
865 }
866
867 ref = btrfs_delayed_node_to_ref(node);
868 if (ref->action == BTRFS_ADD_DELAYED_REF) {
869 if (insert_reserved) {
870 struct btrfs_key ins;
871
872 ins.objectid = node->bytenr;
873 ins.offset = node->num_bytes;
874 ins.type = BTRFS_EXTENT_ITEM_KEY;
875
876 /* record the full extent allocation */
877 ret = __btrfs_alloc_reserved_extent(trans, root,
878 node->parent, ref->root,
879 ref->generation, ref->owner_objectid,
880 &ins, node->ref_mod);
881 update_reserved_extents(root, node->bytenr,
882 node->num_bytes, 0);
883 } else {
884 /* just add one backref */
885 ret = add_extent_ref(trans, root, node->bytenr,
886 node->num_bytes,
887 node->parent, ref->root, ref->generation,
888 ref->owner_objectid, node->ref_mod);
889 }
890 BUG_ON(ret);
891 } else if (ref->action == BTRFS_DROP_DELAYED_REF) {
892 WARN_ON(insert_reserved);
893 ret = drop_delayed_ref(trans, root, node);
894 }
895 return 0;
896}
897
898static noinline struct btrfs_delayed_ref_node *
899select_delayed_ref(struct btrfs_delayed_ref_head *head)
900{
901 struct rb_node *node;
902 struct btrfs_delayed_ref_node *ref;
903 int action = BTRFS_ADD_DELAYED_REF;
904again:
905 /*
906 * select delayed ref of type BTRFS_ADD_DELAYED_REF first.
907 * this prevents ref count from going down to zero when
908 * there still are pending delayed ref.
909 */
910 node = rb_prev(&head->node.rb_node);
911 while (1) {
912 if (!node)
913 break;
914 ref = rb_entry(node, struct btrfs_delayed_ref_node,
915 rb_node);
916 if (ref->bytenr != head->node.bytenr)
917 break;
918 if (btrfs_delayed_node_to_ref(ref)->action == action)
919 return ref;
920 node = rb_prev(node);
921 }
922 if (action == BTRFS_ADD_DELAYED_REF) {
923 action = BTRFS_DROP_DELAYED_REF;
924 goto again;
925 }
926 return NULL;
927}
928
929/*
930 * this starts processing the delayed reference count updates and
931 * extent insertions we have queued up so far. count can be
932 * 0, which means to process everything in the tree at the start
933 * of the run (but not newly added entries), or it can be some target
934 * number you'd like to process.
935 */
936int btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
937 struct btrfs_root *root, unsigned long count)
938{
939 struct rb_node *node;
940 struct btrfs_delayed_ref_root *delayed_refs;
941 struct btrfs_delayed_ref_node *ref;
942 struct btrfs_delayed_ref_head *locked_ref = NULL;
943 int ret;
944 int must_insert_reserved = 0;
945 int run_all = count == (unsigned long)-1;
946
947 if (root == root->fs_info->extent_root)
948 root = root->fs_info->tree_root;
949
950 delayed_refs = &trans->transaction->delayed_refs;
951again:
952 spin_lock(&delayed_refs->lock);
953 if (count == 0)
954 count = delayed_refs->num_entries;
955 while (1) {
956 if (!locked_ref) {
957 /*
958 * no locked ref, go find something we can
959 * process in the rbtree. We start at
960 * the beginning of the tree, there may be less
961 * lock contention if we do something smarter here.
962 */
963 node = rb_first(&delayed_refs->root);
964 if (!node) {
965 spin_unlock(&delayed_refs->lock);
966 break;
967 }
968
969 ref = rb_entry(node, struct btrfs_delayed_ref_node,
970 rb_node);
971 ret = btrfs_lock_delayed_ref(trans, ref, &locked_ref);
972 if (ret) {
973 spin_unlock(&delayed_refs->lock);
974 break;
975 }
976 }
a28ec197 977
56bec294
CM
978 /*
979 * record the must insert reserved flag before we
980 * drop the spin lock.
981 */
982 must_insert_reserved = locked_ref->must_insert_reserved;
983 locked_ref->must_insert_reserved = 0;
7bb86316 984
56bec294
CM
985 /*
986 * locked_ref is the head node, so we have to go one
987 * node back for any delayed ref updates
988 */
74493f7a 989
56bec294
CM
990 ref = select_delayed_ref(locked_ref);
991 if (!ref) {
992 /* All delayed refs have been processed, Go ahead
993 * and send the head node to run_one_delayed_ref,
994 * so that any accounting fixes can happen
995 */
996 ref = &locked_ref->node;
997 locked_ref = NULL;
998 }
02217ed2 999
56bec294
CM
1000 ref->in_tree = 0;
1001 rb_erase(&ref->rb_node, &delayed_refs->root);
1002 delayed_refs->num_entries--;
1003 spin_unlock(&delayed_refs->lock);
925baedd 1004
56bec294
CM
1005 ret = run_one_delayed_ref(trans, root, ref,
1006 must_insert_reserved);
1007 BUG_ON(ret);
1008 btrfs_put_delayed_ref(ref);
eb099670 1009
56bec294
CM
1010 /* once we lock the head ref, we have to process all the
1011 * entries for it. So, we might end up doing more entries
1012 * that count was asking us to do.
1013 */
1014 if (count > 0)
1015 count--;
eb099670 1016
56bec294
CM
1017 /*
1018 * we set locked_ref to null above if we're all done
1019 * with this bytenr
1020 */
1021 if (!locked_ref && count == 0)
1022 break;
1023
1887be66 1024 cond_resched();
56bec294 1025 spin_lock(&delayed_refs->lock);
eb099670 1026 }
56bec294
CM
1027 if (run_all) {
1028 spin_lock(&delayed_refs->lock);
1029 node = rb_first(&delayed_refs->root);
1030 if (!node) {
1031 spin_unlock(&delayed_refs->lock);
1032 goto out;
1033 }
e9d0b13b 1034
56bec294
CM
1035 while (node) {
1036 ref = rb_entry(node, struct btrfs_delayed_ref_node,
1037 rb_node);
1038 if (btrfs_delayed_ref_is_head(ref)) {
1039 struct btrfs_delayed_ref_head *head;
5caf2a00 1040
56bec294
CM
1041 head = btrfs_delayed_node_to_head(ref);
1042 atomic_inc(&ref->refs);
1043
1044 spin_unlock(&delayed_refs->lock);
1045 mutex_lock(&head->mutex);
1046 mutex_unlock(&head->mutex);
1047
1048 btrfs_put_delayed_ref(ref);
1887be66 1049 cond_resched();
56bec294
CM
1050 goto again;
1051 }
1052 node = rb_next(node);
1053 }
1054 spin_unlock(&delayed_refs->lock);
1055 count = (unsigned long)-1;
1056 schedule_timeout(1);
1057 goto again;
5f39d397 1058 }
54aa1f4d 1059out:
a28ec197
CM
1060 return 0;
1061}
1062
80ff3856 1063int btrfs_cross_ref_exist(struct btrfs_trans_handle *trans,
17d217fe 1064 struct btrfs_root *root, u64 objectid, u64 bytenr)
be20aa9d
CM
1065{
1066 struct btrfs_root *extent_root = root->fs_info->extent_root;
1067 struct btrfs_path *path;
f321e491
YZ
1068 struct extent_buffer *leaf;
1069 struct btrfs_extent_ref *ref_item;
1070 struct btrfs_key key;
1071 struct btrfs_key found_key;
80ff3856
YZ
1072 u64 ref_root;
1073 u64 last_snapshot;
be20aa9d
CM
1074 u32 nritems;
1075 int ret;
925baedd 1076
be20aa9d 1077 key.objectid = bytenr;
31840ae1 1078 key.offset = (u64)-1;
f321e491 1079 key.type = BTRFS_EXTENT_ITEM_KEY;
be20aa9d 1080
f321e491 1081 path = btrfs_alloc_path();
be20aa9d
CM
1082 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
1083 if (ret < 0)
1084 goto out;
1085 BUG_ON(ret == 0);
80ff3856
YZ
1086
1087 ret = -ENOENT;
1088 if (path->slots[0] == 0)
31840ae1 1089 goto out;
be20aa9d 1090
31840ae1 1091 path->slots[0]--;
f321e491
YZ
1092 leaf = path->nodes[0];
1093 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
be20aa9d
CM
1094
1095 if (found_key.objectid != bytenr ||
80ff3856 1096 found_key.type != BTRFS_EXTENT_ITEM_KEY)
be20aa9d 1097 goto out;
f321e491 1098
80ff3856 1099 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
be20aa9d 1100 while (1) {
f321e491
YZ
1101 leaf = path->nodes[0];
1102 nritems = btrfs_header_nritems(leaf);
be20aa9d
CM
1103 if (path->slots[0] >= nritems) {
1104 ret = btrfs_next_leaf(extent_root, path);
f321e491
YZ
1105 if (ret < 0)
1106 goto out;
be20aa9d
CM
1107 if (ret == 0)
1108 continue;
1109 break;
1110 }
f321e491 1111 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
be20aa9d
CM
1112 if (found_key.objectid != bytenr)
1113 break;
bd09835d 1114
be20aa9d
CM
1115 if (found_key.type != BTRFS_EXTENT_REF_KEY) {
1116 path->slots[0]++;
1117 continue;
1118 }
1119
f321e491 1120 ref_item = btrfs_item_ptr(leaf, path->slots[0],
be20aa9d 1121 struct btrfs_extent_ref);
80ff3856 1122 ref_root = btrfs_ref_root(leaf, ref_item);
17d217fe
YZ
1123 if ((ref_root != root->root_key.objectid &&
1124 ref_root != BTRFS_TREE_LOG_OBJECTID) ||
1125 objectid != btrfs_ref_objectid(leaf, ref_item)) {
80ff3856 1126 ret = 1;
f321e491 1127 goto out;
80ff3856
YZ
1128 }
1129 if (btrfs_ref_generation(leaf, ref_item) <= last_snapshot) {
f321e491
YZ
1130 ret = 1;
1131 goto out;
1132 }
80ff3856
YZ
1133
1134 path->slots[0]++;
f321e491
YZ
1135 }
1136 ret = 0;
be20aa9d 1137out:
80ff3856 1138 btrfs_free_path(path);
f321e491 1139 return ret;
be20aa9d 1140}
c5739bba 1141
31840ae1
ZY
1142int btrfs_cache_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
1143 struct extent_buffer *buf, u32 nr_extents)
02217ed2 1144{
5f39d397 1145 struct btrfs_key key;
6407bf6d 1146 struct btrfs_file_extent_item *fi;
e4657689
ZY
1147 u64 root_gen;
1148 u32 nritems;
02217ed2 1149 int i;
db94535d 1150 int level;
31840ae1 1151 int ret = 0;
e4657689 1152 int shared = 0;
a28ec197 1153
3768f368 1154 if (!root->ref_cows)
a28ec197 1155 return 0;
5f39d397 1156
e4657689
ZY
1157 if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
1158 shared = 0;
1159 root_gen = root->root_key.offset;
1160 } else {
1161 shared = 1;
1162 root_gen = trans->transid - 1;
1163 }
1164
db94535d 1165 level = btrfs_header_level(buf);
5f39d397 1166 nritems = btrfs_header_nritems(buf);
4a096752 1167
31840ae1 1168 if (level == 0) {
31153d81
YZ
1169 struct btrfs_leaf_ref *ref;
1170 struct btrfs_extent_info *info;
1171
31840ae1 1172 ref = btrfs_alloc_leaf_ref(root, nr_extents);
31153d81 1173 if (!ref) {
31840ae1 1174 ret = -ENOMEM;
31153d81
YZ
1175 goto out;
1176 }
1177
e4657689 1178 ref->root_gen = root_gen;
31153d81
YZ
1179 ref->bytenr = buf->start;
1180 ref->owner = btrfs_header_owner(buf);
1181 ref->generation = btrfs_header_generation(buf);
31840ae1 1182 ref->nritems = nr_extents;
31153d81 1183 info = ref->extents;
bcc63abb 1184
31840ae1 1185 for (i = 0; nr_extents > 0 && i < nritems; i++) {
31153d81
YZ
1186 u64 disk_bytenr;
1187 btrfs_item_key_to_cpu(buf, &key, i);
1188 if (btrfs_key_type(&key) != BTRFS_EXTENT_DATA_KEY)
1189 continue;
1190 fi = btrfs_item_ptr(buf, i,
1191 struct btrfs_file_extent_item);
1192 if (btrfs_file_extent_type(buf, fi) ==
1193 BTRFS_FILE_EXTENT_INLINE)
1194 continue;
1195 disk_bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
1196 if (disk_bytenr == 0)
1197 continue;
1198
1199 info->bytenr = disk_bytenr;
1200 info->num_bytes =
1201 btrfs_file_extent_disk_num_bytes(buf, fi);
1202 info->objectid = key.objectid;
1203 info->offset = key.offset;
1204 info++;
1205 }
1206
e4657689 1207 ret = btrfs_add_leaf_ref(root, ref, shared);
5b84e8d6
YZ
1208 if (ret == -EEXIST && shared) {
1209 struct btrfs_leaf_ref *old;
1210 old = btrfs_lookup_leaf_ref(root, ref->bytenr);
1211 BUG_ON(!old);
1212 btrfs_remove_leaf_ref(root, old);
1213 btrfs_free_leaf_ref(root, old);
1214 ret = btrfs_add_leaf_ref(root, ref, shared);
1215 }
31153d81 1216 WARN_ON(ret);
bcc63abb 1217 btrfs_free_leaf_ref(root, ref);
31153d81
YZ
1218 }
1219out:
31840ae1
ZY
1220 return ret;
1221}
1222
b7a9f29f
CM
1223/* when a block goes through cow, we update the reference counts of
1224 * everything that block points to. The internal pointers of the block
1225 * can be in just about any order, and it is likely to have clusters of
1226 * things that are close together and clusters of things that are not.
1227 *
1228 * To help reduce the seeks that come with updating all of these reference
1229 * counts, sort them by byte number before actual updates are done.
1230 *
1231 * struct refsort is used to match byte number to slot in the btree block.
1232 * we sort based on the byte number and then use the slot to actually
1233 * find the item.
bd56b302
CM
1234 *
1235 * struct refsort is smaller than strcut btrfs_item and smaller than
1236 * struct btrfs_key_ptr. Since we're currently limited to the page size
1237 * for a btree block, there's no way for a kmalloc of refsorts for a
1238 * single node to be bigger than a page.
b7a9f29f
CM
1239 */
1240struct refsort {
1241 u64 bytenr;
1242 u32 slot;
1243};
1244
1245/*
1246 * for passing into sort()
1247 */
1248static int refsort_cmp(const void *a_void, const void *b_void)
1249{
1250 const struct refsort *a = a_void;
1251 const struct refsort *b = b_void;
1252
1253 if (a->bytenr < b->bytenr)
1254 return -1;
1255 if (a->bytenr > b->bytenr)
1256 return 1;
1257 return 0;
1258}
1259
1260
1261noinline int btrfs_inc_ref(struct btrfs_trans_handle *trans,
1262 struct btrfs_root *root,
1263 struct extent_buffer *orig_buf,
1264 struct extent_buffer *buf, u32 *nr_extents)
31840ae1
ZY
1265{
1266 u64 bytenr;
1267 u64 ref_root;
1268 u64 orig_root;
1269 u64 ref_generation;
1270 u64 orig_generation;
b7a9f29f 1271 struct refsort *sorted;
31840ae1
ZY
1272 u32 nritems;
1273 u32 nr_file_extents = 0;
1274 struct btrfs_key key;
1275 struct btrfs_file_extent_item *fi;
1276 int i;
1277 int level;
1278 int ret = 0;
1279 int faili = 0;
b7a9f29f
CM
1280 int refi = 0;
1281 int slot;
31840ae1 1282 int (*process_func)(struct btrfs_trans_handle *, struct btrfs_root *,
56bec294 1283 u64, u64, u64, u64, u64, u64, u64, u64, u64);
31840ae1
ZY
1284
1285 ref_root = btrfs_header_owner(buf);
1286 ref_generation = btrfs_header_generation(buf);
1287 orig_root = btrfs_header_owner(orig_buf);
1288 orig_generation = btrfs_header_generation(orig_buf);
1289
1290 nritems = btrfs_header_nritems(buf);
1291 level = btrfs_header_level(buf);
1292
b7a9f29f
CM
1293 sorted = kmalloc(sizeof(struct refsort) * nritems, GFP_NOFS);
1294 BUG_ON(!sorted);
1295
31840ae1
ZY
1296 if (root->ref_cows) {
1297 process_func = __btrfs_inc_extent_ref;
1298 } else {
1299 if (level == 0 &&
1300 root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID)
1301 goto out;
1302 if (level != 0 &&
1303 root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID)
1304 goto out;
1305 process_func = __btrfs_update_extent_ref;
1306 }
1307
b7a9f29f
CM
1308 /*
1309 * we make two passes through the items. In the first pass we
1310 * only record the byte number and slot. Then we sort based on
1311 * byte number and do the actual work based on the sorted results
1312 */
31840ae1
ZY
1313 for (i = 0; i < nritems; i++) {
1314 cond_resched();
db94535d 1315 if (level == 0) {
5f39d397
CM
1316 btrfs_item_key_to_cpu(buf, &key, i);
1317 if (btrfs_key_type(&key) != BTRFS_EXTENT_DATA_KEY)
54aa1f4d 1318 continue;
5f39d397 1319 fi = btrfs_item_ptr(buf, i,
54aa1f4d 1320 struct btrfs_file_extent_item);
5f39d397 1321 if (btrfs_file_extent_type(buf, fi) ==
54aa1f4d
CM
1322 BTRFS_FILE_EXTENT_INLINE)
1323 continue;
31840ae1
ZY
1324 bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
1325 if (bytenr == 0)
54aa1f4d 1326 continue;
31840ae1
ZY
1327
1328 nr_file_extents++;
b7a9f29f
CM
1329 sorted[refi].bytenr = bytenr;
1330 sorted[refi].slot = i;
1331 refi++;
1332 } else {
1333 bytenr = btrfs_node_blockptr(buf, i);
1334 sorted[refi].bytenr = bytenr;
1335 sorted[refi].slot = i;
1336 refi++;
1337 }
1338 }
1339 /*
1340 * if refi == 0, we didn't actually put anything into the sorted
1341 * array and we're done
1342 */
1343 if (refi == 0)
1344 goto out;
1345
1346 sort(sorted, refi, sizeof(struct refsort), refsort_cmp, NULL);
1347
1348 for (i = 0; i < refi; i++) {
1349 cond_resched();
1350 slot = sorted[i].slot;
1351 bytenr = sorted[i].bytenr;
1352
1353 if (level == 0) {
1354 btrfs_item_key_to_cpu(buf, &key, slot);
56bec294
CM
1355 fi = btrfs_item_ptr(buf, slot,
1356 struct btrfs_file_extent_item);
1357
1358 bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
1359 if (bytenr == 0)
1360 continue;
31840ae1 1361
31840ae1 1362 ret = process_func(trans, root, bytenr,
56bec294
CM
1363 btrfs_file_extent_disk_num_bytes(buf, fi),
1364 orig_buf->start, buf->start,
1365 orig_root, ref_root,
1366 orig_generation, ref_generation,
1367 key.objectid);
31840ae1
ZY
1368
1369 if (ret) {
b7a9f29f 1370 faili = slot;
31840ae1
ZY
1371 WARN_ON(1);
1372 goto fail;
1373 }
54aa1f4d 1374 } else {
56bec294 1375 ret = process_func(trans, root, bytenr, buf->len,
31840ae1
ZY
1376 orig_buf->start, buf->start,
1377 orig_root, ref_root,
1378 orig_generation, ref_generation,
3bb1a1bc 1379 level - 1);
31840ae1 1380 if (ret) {
b7a9f29f 1381 faili = slot;
31840ae1
ZY
1382 WARN_ON(1);
1383 goto fail;
1384 }
54aa1f4d
CM
1385 }
1386 }
31840ae1 1387out:
b7a9f29f 1388 kfree(sorted);
31840ae1
ZY
1389 if (nr_extents) {
1390 if (level == 0)
1391 *nr_extents = nr_file_extents;
1392 else
1393 *nr_extents = nritems;
1394 }
1395 return 0;
1396fail:
b7a9f29f 1397 kfree(sorted);
31840ae1 1398 WARN_ON(1);
54aa1f4d 1399 return ret;
02217ed2
CM
1400}
1401
31840ae1
ZY
1402int btrfs_update_ref(struct btrfs_trans_handle *trans,
1403 struct btrfs_root *root, struct extent_buffer *orig_buf,
1404 struct extent_buffer *buf, int start_slot, int nr)
1405
1406{
1407 u64 bytenr;
1408 u64 ref_root;
1409 u64 orig_root;
1410 u64 ref_generation;
1411 u64 orig_generation;
1412 struct btrfs_key key;
1413 struct btrfs_file_extent_item *fi;
1414 int i;
1415 int ret;
1416 int slot;
1417 int level;
1418
1419 BUG_ON(start_slot < 0);
1420 BUG_ON(start_slot + nr > btrfs_header_nritems(buf));
1421
1422 ref_root = btrfs_header_owner(buf);
1423 ref_generation = btrfs_header_generation(buf);
1424 orig_root = btrfs_header_owner(orig_buf);
1425 orig_generation = btrfs_header_generation(orig_buf);
1426 level = btrfs_header_level(buf);
1427
1428 if (!root->ref_cows) {
1429 if (level == 0 &&
1430 root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID)
1431 return 0;
1432 if (level != 0 &&
1433 root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID)
1434 return 0;
1435 }
1436
1437 for (i = 0, slot = start_slot; i < nr; i++, slot++) {
1438 cond_resched();
1439 if (level == 0) {
1440 btrfs_item_key_to_cpu(buf, &key, slot);
1441 if (btrfs_key_type(&key) != BTRFS_EXTENT_DATA_KEY)
1442 continue;
1443 fi = btrfs_item_ptr(buf, slot,
1444 struct btrfs_file_extent_item);
1445 if (btrfs_file_extent_type(buf, fi) ==
1446 BTRFS_FILE_EXTENT_INLINE)
1447 continue;
1448 bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
1449 if (bytenr == 0)
1450 continue;
31840ae1 1451 ret = __btrfs_update_extent_ref(trans, root, bytenr,
56bec294
CM
1452 btrfs_file_extent_disk_num_bytes(buf, fi),
1453 orig_buf->start, buf->start,
1454 orig_root, ref_root, orig_generation,
1455 ref_generation, key.objectid);
31840ae1
ZY
1456 if (ret)
1457 goto fail;
1458 } else {
1459 bytenr = btrfs_node_blockptr(buf, slot);
31840ae1 1460 ret = __btrfs_update_extent_ref(trans, root, bytenr,
56bec294
CM
1461 buf->len, orig_buf->start,
1462 buf->start, orig_root, ref_root,
31840ae1 1463 orig_generation, ref_generation,
3bb1a1bc 1464 level - 1);
31840ae1
ZY
1465 if (ret)
1466 goto fail;
1467 }
1468 }
1469 return 0;
1470fail:
1471 WARN_ON(1);
1472 return -1;
1473}
1474
9078a3e1
CM
1475static int write_one_cache_group(struct btrfs_trans_handle *trans,
1476 struct btrfs_root *root,
1477 struct btrfs_path *path,
1478 struct btrfs_block_group_cache *cache)
1479{
1480 int ret;
9078a3e1 1481 struct btrfs_root *extent_root = root->fs_info->extent_root;
5f39d397
CM
1482 unsigned long bi;
1483 struct extent_buffer *leaf;
9078a3e1 1484
9078a3e1 1485 ret = btrfs_search_slot(trans, extent_root, &cache->key, path, 0, 1);
54aa1f4d
CM
1486 if (ret < 0)
1487 goto fail;
9078a3e1 1488 BUG_ON(ret);
5f39d397
CM
1489
1490 leaf = path->nodes[0];
1491 bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
1492 write_extent_buffer(leaf, &cache->item, bi, sizeof(cache->item));
1493 btrfs_mark_buffer_dirty(leaf);
9078a3e1 1494 btrfs_release_path(extent_root, path);
54aa1f4d 1495fail:
9078a3e1
CM
1496 if (ret)
1497 return ret;
9078a3e1
CM
1498 return 0;
1499
1500}
1501
96b5179d
CM
1502int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans,
1503 struct btrfs_root *root)
9078a3e1 1504{
0f9dd46c
JB
1505 struct btrfs_block_group_cache *cache, *entry;
1506 struct rb_node *n;
9078a3e1
CM
1507 int err = 0;
1508 int werr = 0;
9078a3e1 1509 struct btrfs_path *path;
96b5179d 1510 u64 last = 0;
9078a3e1
CM
1511
1512 path = btrfs_alloc_path();
1513 if (!path)
1514 return -ENOMEM;
1515
d397712b 1516 while (1) {
0f9dd46c
JB
1517 cache = NULL;
1518 spin_lock(&root->fs_info->block_group_cache_lock);
1519 for (n = rb_first(&root->fs_info->block_group_cache_tree);
1520 n; n = rb_next(n)) {
1521 entry = rb_entry(n, struct btrfs_block_group_cache,
1522 cache_node);
1523 if (entry->dirty) {
1524 cache = entry;
1525 break;
1526 }
1527 }
1528 spin_unlock(&root->fs_info->block_group_cache_lock);
54aa1f4d 1529
0f9dd46c 1530 if (!cache)
96b5179d 1531 break;
0f9dd46c 1532
e8569813 1533 cache->dirty = 0;
0f9dd46c
JB
1534 last += cache->key.offset;
1535
96b5179d
CM
1536 err = write_one_cache_group(trans, root,
1537 path, cache);
1538 /*
1539 * if we fail to write the cache group, we want
1540 * to keep it marked dirty in hopes that a later
1541 * write will work
1542 */
1543 if (err) {
1544 werr = err;
1545 continue;
9078a3e1
CM
1546 }
1547 }
1548 btrfs_free_path(path);
1549 return werr;
1550}
1551
d2fb3437
YZ
1552int btrfs_extent_readonly(struct btrfs_root *root, u64 bytenr)
1553{
1554 struct btrfs_block_group_cache *block_group;
1555 int readonly = 0;
1556
1557 block_group = btrfs_lookup_block_group(root->fs_info, bytenr);
1558 if (!block_group || block_group->ro)
1559 readonly = 1;
1560 if (block_group)
1561 put_block_group(block_group);
1562 return readonly;
1563}
1564
593060d7
CM
1565static int update_space_info(struct btrfs_fs_info *info, u64 flags,
1566 u64 total_bytes, u64 bytes_used,
1567 struct btrfs_space_info **space_info)
1568{
1569 struct btrfs_space_info *found;
1570
1571 found = __find_space_info(info, flags);
1572 if (found) {
25179201 1573 spin_lock(&found->lock);
593060d7
CM
1574 found->total_bytes += total_bytes;
1575 found->bytes_used += bytes_used;
8f18cf13 1576 found->full = 0;
25179201 1577 spin_unlock(&found->lock);
593060d7
CM
1578 *space_info = found;
1579 return 0;
1580 }
c146afad 1581 found = kzalloc(sizeof(*found), GFP_NOFS);
593060d7
CM
1582 if (!found)
1583 return -ENOMEM;
1584
0f9dd46c 1585 INIT_LIST_HEAD(&found->block_groups);
80eb234a 1586 init_rwsem(&found->groups_sem);
0f9dd46c 1587 spin_lock_init(&found->lock);
593060d7
CM
1588 found->flags = flags;
1589 found->total_bytes = total_bytes;
1590 found->bytes_used = bytes_used;
1591 found->bytes_pinned = 0;
e8569813 1592 found->bytes_reserved = 0;
c146afad 1593 found->bytes_readonly = 0;
6a63209f 1594 found->bytes_delalloc = 0;
593060d7 1595 found->full = 0;
0ef3e66b 1596 found->force_alloc = 0;
593060d7 1597 *space_info = found;
4184ea7f 1598 list_add_rcu(&found->list, &info->space_info);
593060d7
CM
1599 return 0;
1600}
1601
8790d502
CM
1602static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
1603{
1604 u64 extra_flags = flags & (BTRFS_BLOCK_GROUP_RAID0 |
611f0e00 1605 BTRFS_BLOCK_GROUP_RAID1 |
321aecc6 1606 BTRFS_BLOCK_GROUP_RAID10 |
611f0e00 1607 BTRFS_BLOCK_GROUP_DUP);
8790d502
CM
1608 if (extra_flags) {
1609 if (flags & BTRFS_BLOCK_GROUP_DATA)
1610 fs_info->avail_data_alloc_bits |= extra_flags;
1611 if (flags & BTRFS_BLOCK_GROUP_METADATA)
1612 fs_info->avail_metadata_alloc_bits |= extra_flags;
1613 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
1614 fs_info->avail_system_alloc_bits |= extra_flags;
1615 }
1616}
593060d7 1617
c146afad
YZ
1618static void set_block_group_readonly(struct btrfs_block_group_cache *cache)
1619{
1620 spin_lock(&cache->space_info->lock);
1621 spin_lock(&cache->lock);
1622 if (!cache->ro) {
1623 cache->space_info->bytes_readonly += cache->key.offset -
1624 btrfs_block_group_used(&cache->item);
1625 cache->ro = 1;
1626 }
1627 spin_unlock(&cache->lock);
1628 spin_unlock(&cache->space_info->lock);
1629}
1630
2b82032c 1631u64 btrfs_reduce_alloc_profile(struct btrfs_root *root, u64 flags)
ec44a35c 1632{
2b82032c 1633 u64 num_devices = root->fs_info->fs_devices->rw_devices;
a061fc8d
CM
1634
1635 if (num_devices == 1)
1636 flags &= ~(BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID0);
1637 if (num_devices < 4)
1638 flags &= ~BTRFS_BLOCK_GROUP_RAID10;
1639
ec44a35c
CM
1640 if ((flags & BTRFS_BLOCK_GROUP_DUP) &&
1641 (flags & (BTRFS_BLOCK_GROUP_RAID1 |
a061fc8d 1642 BTRFS_BLOCK_GROUP_RAID10))) {
ec44a35c 1643 flags &= ~BTRFS_BLOCK_GROUP_DUP;
a061fc8d 1644 }
ec44a35c
CM
1645
1646 if ((flags & BTRFS_BLOCK_GROUP_RAID1) &&
a061fc8d 1647 (flags & BTRFS_BLOCK_GROUP_RAID10)) {
ec44a35c 1648 flags &= ~BTRFS_BLOCK_GROUP_RAID1;
a061fc8d 1649 }
ec44a35c
CM
1650
1651 if ((flags & BTRFS_BLOCK_GROUP_RAID0) &&
1652 ((flags & BTRFS_BLOCK_GROUP_RAID1) |
1653 (flags & BTRFS_BLOCK_GROUP_RAID10) |
1654 (flags & BTRFS_BLOCK_GROUP_DUP)))
1655 flags &= ~BTRFS_BLOCK_GROUP_RAID0;
1656 return flags;
1657}
1658
6a63209f
JB
1659static u64 btrfs_get_alloc_profile(struct btrfs_root *root, u64 data)
1660{
1661 struct btrfs_fs_info *info = root->fs_info;
1662 u64 alloc_profile;
1663
1664 if (data) {
1665 alloc_profile = info->avail_data_alloc_bits &
1666 info->data_alloc_profile;
1667 data = BTRFS_BLOCK_GROUP_DATA | alloc_profile;
1668 } else if (root == root->fs_info->chunk_root) {
1669 alloc_profile = info->avail_system_alloc_bits &
1670 info->system_alloc_profile;
1671 data = BTRFS_BLOCK_GROUP_SYSTEM | alloc_profile;
1672 } else {
1673 alloc_profile = info->avail_metadata_alloc_bits &
1674 info->metadata_alloc_profile;
1675 data = BTRFS_BLOCK_GROUP_METADATA | alloc_profile;
1676 }
1677
1678 return btrfs_reduce_alloc_profile(root, data);
1679}
1680
1681void btrfs_set_inode_space_info(struct btrfs_root *root, struct inode *inode)
1682{
1683 u64 alloc_target;
1684
1685 alloc_target = btrfs_get_alloc_profile(root, 1);
1686 BTRFS_I(inode)->space_info = __find_space_info(root->fs_info,
1687 alloc_target);
1688}
1689
1690/*
1691 * for now this just makes sure we have at least 5% of our metadata space free
1692 * for use.
1693 */
1694int btrfs_check_metadata_free_space(struct btrfs_root *root)
1695{
1696 struct btrfs_fs_info *info = root->fs_info;
1697 struct btrfs_space_info *meta_sinfo;
1698 u64 alloc_target, thresh;
4e06bdd6 1699 int committed = 0, ret;
6a63209f
JB
1700
1701 /* get the space info for where the metadata will live */
1702 alloc_target = btrfs_get_alloc_profile(root, 0);
1703 meta_sinfo = __find_space_info(info, alloc_target);
1704
4e06bdd6 1705again:
6a63209f 1706 spin_lock(&meta_sinfo->lock);
4e06bdd6
JB
1707 if (!meta_sinfo->full)
1708 thresh = meta_sinfo->total_bytes * 80;
1709 else
1710 thresh = meta_sinfo->total_bytes * 95;
6a63209f
JB
1711
1712 do_div(thresh, 100);
1713
1714 if (meta_sinfo->bytes_used + meta_sinfo->bytes_reserved +
1715 meta_sinfo->bytes_pinned + meta_sinfo->bytes_readonly > thresh) {
4e06bdd6
JB
1716 struct btrfs_trans_handle *trans;
1717 if (!meta_sinfo->full) {
1718 meta_sinfo->force_alloc = 1;
1719 spin_unlock(&meta_sinfo->lock);
1720
1721 trans = btrfs_start_transaction(root, 1);
1722 if (!trans)
1723 return -ENOMEM;
1724
1725 ret = do_chunk_alloc(trans, root->fs_info->extent_root,
1726 2 * 1024 * 1024, alloc_target, 0);
1727 btrfs_end_transaction(trans, root);
1728 goto again;
1729 }
6a63209f 1730 spin_unlock(&meta_sinfo->lock);
4e06bdd6
JB
1731
1732 if (!committed) {
1733 committed = 1;
1734 trans = btrfs_join_transaction(root, 1);
1735 if (!trans)
1736 return -ENOMEM;
1737 ret = btrfs_commit_transaction(trans, root);
1738 if (ret)
1739 return ret;
1740 goto again;
1741 }
6a63209f
JB
1742 return -ENOSPC;
1743 }
1744 spin_unlock(&meta_sinfo->lock);
1745
1746 return 0;
1747}
1748
1749/*
1750 * This will check the space that the inode allocates from to make sure we have
1751 * enough space for bytes.
1752 */
1753int btrfs_check_data_free_space(struct btrfs_root *root, struct inode *inode,
1754 u64 bytes)
1755{
1756 struct btrfs_space_info *data_sinfo;
4e06bdd6 1757 int ret = 0, committed = 0;
6a63209f
JB
1758
1759 /* make sure bytes are sectorsize aligned */
1760 bytes = (bytes + root->sectorsize - 1) & ~((u64)root->sectorsize - 1);
1761
1762 data_sinfo = BTRFS_I(inode)->space_info;
1763again:
1764 /* make sure we have enough space to handle the data first */
1765 spin_lock(&data_sinfo->lock);
1766 if (data_sinfo->total_bytes - data_sinfo->bytes_used -
1767 data_sinfo->bytes_delalloc - data_sinfo->bytes_reserved -
1768 data_sinfo->bytes_pinned - data_sinfo->bytes_readonly -
1769 data_sinfo->bytes_may_use < bytes) {
4e06bdd6
JB
1770 struct btrfs_trans_handle *trans;
1771
6a63209f
JB
1772 /*
1773 * if we don't have enough free bytes in this space then we need
1774 * to alloc a new chunk.
1775 */
1776 if (!data_sinfo->full) {
1777 u64 alloc_target;
6a63209f
JB
1778
1779 data_sinfo->force_alloc = 1;
1780 spin_unlock(&data_sinfo->lock);
1781
1782 alloc_target = btrfs_get_alloc_profile(root, 1);
1783 trans = btrfs_start_transaction(root, 1);
1784 if (!trans)
1785 return -ENOMEM;
1786
1787 ret = do_chunk_alloc(trans, root->fs_info->extent_root,
1788 bytes + 2 * 1024 * 1024,
1789 alloc_target, 0);
1790 btrfs_end_transaction(trans, root);
1791 if (ret)
1792 return ret;
1793 goto again;
1794 }
1795 spin_unlock(&data_sinfo->lock);
4e06bdd6
JB
1796
1797 /* commit the current transaction and try again */
1798 if (!committed) {
1799 committed = 1;
1800 trans = btrfs_join_transaction(root, 1);
1801 if (!trans)
1802 return -ENOMEM;
1803 ret = btrfs_commit_transaction(trans, root);
1804 if (ret)
1805 return ret;
1806 goto again;
1807 }
1808
6a63209f
JB
1809 printk(KERN_ERR "no space left, need %llu, %llu delalloc bytes"
1810 ", %llu bytes_used, %llu bytes_reserved, "
1811 "%llu bytes_pinned, %llu bytes_readonly, %llu may use"
1812 "%llu total\n", bytes, data_sinfo->bytes_delalloc,
1813 data_sinfo->bytes_used, data_sinfo->bytes_reserved,
1814 data_sinfo->bytes_pinned, data_sinfo->bytes_readonly,
1815 data_sinfo->bytes_may_use, data_sinfo->total_bytes);
1816 return -ENOSPC;
1817 }
1818 data_sinfo->bytes_may_use += bytes;
1819 BTRFS_I(inode)->reserved_bytes += bytes;
1820 spin_unlock(&data_sinfo->lock);
1821
1822 return btrfs_check_metadata_free_space(root);
1823}
1824
1825/*
1826 * if there was an error for whatever reason after calling
1827 * btrfs_check_data_free_space, call this so we can cleanup the counters.
1828 */
1829void btrfs_free_reserved_data_space(struct btrfs_root *root,
1830 struct inode *inode, u64 bytes)
1831{
1832 struct btrfs_space_info *data_sinfo;
1833
1834 /* make sure bytes are sectorsize aligned */
1835 bytes = (bytes + root->sectorsize - 1) & ~((u64)root->sectorsize - 1);
1836
1837 data_sinfo = BTRFS_I(inode)->space_info;
1838 spin_lock(&data_sinfo->lock);
1839 data_sinfo->bytes_may_use -= bytes;
1840 BTRFS_I(inode)->reserved_bytes -= bytes;
1841 spin_unlock(&data_sinfo->lock);
1842}
1843
1844/* called when we are adding a delalloc extent to the inode's io_tree */
1845void btrfs_delalloc_reserve_space(struct btrfs_root *root, struct inode *inode,
1846 u64 bytes)
1847{
1848 struct btrfs_space_info *data_sinfo;
1849
1850 /* get the space info for where this inode will be storing its data */
1851 data_sinfo = BTRFS_I(inode)->space_info;
1852
1853 /* make sure we have enough space to handle the data first */
1854 spin_lock(&data_sinfo->lock);
1855 data_sinfo->bytes_delalloc += bytes;
1856
1857 /*
1858 * we are adding a delalloc extent without calling
1859 * btrfs_check_data_free_space first. This happens on a weird
1860 * writepage condition, but shouldn't hurt our accounting
1861 */
1862 if (unlikely(bytes > BTRFS_I(inode)->reserved_bytes)) {
1863 data_sinfo->bytes_may_use -= BTRFS_I(inode)->reserved_bytes;
1864 BTRFS_I(inode)->reserved_bytes = 0;
1865 } else {
1866 data_sinfo->bytes_may_use -= bytes;
1867 BTRFS_I(inode)->reserved_bytes -= bytes;
1868 }
1869
1870 spin_unlock(&data_sinfo->lock);
1871}
1872
1873/* called when we are clearing an delalloc extent from the inode's io_tree */
1874void btrfs_delalloc_free_space(struct btrfs_root *root, struct inode *inode,
1875 u64 bytes)
1876{
1877 struct btrfs_space_info *info;
1878
1879 info = BTRFS_I(inode)->space_info;
1880
1881 spin_lock(&info->lock);
1882 info->bytes_delalloc -= bytes;
1883 spin_unlock(&info->lock);
1884}
1885
6324fbf3
CM
1886static int do_chunk_alloc(struct btrfs_trans_handle *trans,
1887 struct btrfs_root *extent_root, u64 alloc_bytes,
0ef3e66b 1888 u64 flags, int force)
6324fbf3
CM
1889{
1890 struct btrfs_space_info *space_info;
1891 u64 thresh;
c146afad
YZ
1892 int ret = 0;
1893
1894 mutex_lock(&extent_root->fs_info->chunk_mutex);
6324fbf3 1895
2b82032c 1896 flags = btrfs_reduce_alloc_profile(extent_root, flags);
ec44a35c 1897
6324fbf3 1898 space_info = __find_space_info(extent_root->fs_info, flags);
593060d7
CM
1899 if (!space_info) {
1900 ret = update_space_info(extent_root->fs_info, flags,
1901 0, 0, &space_info);
1902 BUG_ON(ret);
1903 }
6324fbf3
CM
1904 BUG_ON(!space_info);
1905
25179201 1906 spin_lock(&space_info->lock);
0ef3e66b
CM
1907 if (space_info->force_alloc) {
1908 force = 1;
1909 space_info->force_alloc = 0;
1910 }
25179201
JB
1911 if (space_info->full) {
1912 spin_unlock(&space_info->lock);
925baedd 1913 goto out;
25179201 1914 }
6324fbf3 1915
c146afad
YZ
1916 thresh = space_info->total_bytes - space_info->bytes_readonly;
1917 thresh = div_factor(thresh, 6);
0ef3e66b 1918 if (!force &&
e8569813 1919 (space_info->bytes_used + space_info->bytes_pinned +
25179201
JB
1920 space_info->bytes_reserved + alloc_bytes) < thresh) {
1921 spin_unlock(&space_info->lock);
925baedd 1922 goto out;
25179201 1923 }
25179201
JB
1924 spin_unlock(&space_info->lock);
1925
2b82032c 1926 ret = btrfs_alloc_chunk(trans, extent_root, flags);
d397712b 1927 if (ret)
6324fbf3 1928 space_info->full = 1;
a74a4b97 1929out:
c146afad 1930 mutex_unlock(&extent_root->fs_info->chunk_mutex);
0f9dd46c 1931 return ret;
6324fbf3
CM
1932}
1933
9078a3e1
CM
1934static int update_block_group(struct btrfs_trans_handle *trans,
1935 struct btrfs_root *root,
db94535d 1936 u64 bytenr, u64 num_bytes, int alloc,
0b86a832 1937 int mark_free)
9078a3e1
CM
1938{
1939 struct btrfs_block_group_cache *cache;
1940 struct btrfs_fs_info *info = root->fs_info;
db94535d 1941 u64 total = num_bytes;
9078a3e1 1942 u64 old_val;
db94535d 1943 u64 byte_in_group;
3e1ad54f 1944
d397712b 1945 while (total) {
db94535d 1946 cache = btrfs_lookup_block_group(info, bytenr);
f3465ca4 1947 if (!cache)
9078a3e1 1948 return -1;
db94535d
CM
1949 byte_in_group = bytenr - cache->key.objectid;
1950 WARN_ON(byte_in_group > cache->key.offset);
9078a3e1 1951
25179201 1952 spin_lock(&cache->space_info->lock);
c286ac48 1953 spin_lock(&cache->lock);
0f9dd46c 1954 cache->dirty = 1;
9078a3e1 1955 old_val = btrfs_block_group_used(&cache->item);
db94535d 1956 num_bytes = min(total, cache->key.offset - byte_in_group);
cd1bc465 1957 if (alloc) {
db94535d 1958 old_val += num_bytes;
6324fbf3 1959 cache->space_info->bytes_used += num_bytes;
a512bbf8 1960 if (cache->ro)
c146afad 1961 cache->space_info->bytes_readonly -= num_bytes;
c286ac48
CM
1962 btrfs_set_block_group_used(&cache->item, old_val);
1963 spin_unlock(&cache->lock);
25179201 1964 spin_unlock(&cache->space_info->lock);
cd1bc465 1965 } else {
db94535d 1966 old_val -= num_bytes;
6324fbf3 1967 cache->space_info->bytes_used -= num_bytes;
c146afad
YZ
1968 if (cache->ro)
1969 cache->space_info->bytes_readonly += num_bytes;
c286ac48
CM
1970 btrfs_set_block_group_used(&cache->item, old_val);
1971 spin_unlock(&cache->lock);
25179201 1972 spin_unlock(&cache->space_info->lock);
f510cfec 1973 if (mark_free) {
0f9dd46c 1974 int ret;
1f3c79a2
LH
1975
1976 ret = btrfs_discard_extent(root, bytenr,
1977 num_bytes);
1978 WARN_ON(ret);
1979
0f9dd46c
JB
1980 ret = btrfs_add_free_space(cache, bytenr,
1981 num_bytes);
d2fb3437 1982 WARN_ON(ret);
e37c9e69 1983 }
cd1bc465 1984 }
d2fb3437 1985 put_block_group(cache);
db94535d
CM
1986 total -= num_bytes;
1987 bytenr += num_bytes;
9078a3e1
CM
1988 }
1989 return 0;
1990}
6324fbf3 1991
a061fc8d
CM
1992static u64 first_logical_byte(struct btrfs_root *root, u64 search_start)
1993{
0f9dd46c 1994 struct btrfs_block_group_cache *cache;
d2fb3437 1995 u64 bytenr;
0f9dd46c
JB
1996
1997 cache = btrfs_lookup_first_block_group(root->fs_info, search_start);
1998 if (!cache)
a061fc8d 1999 return 0;
0f9dd46c 2000
d2fb3437
YZ
2001 bytenr = cache->key.objectid;
2002 put_block_group(cache);
2003
2004 return bytenr;
a061fc8d
CM
2005}
2006
e02119d5 2007int btrfs_update_pinned_extents(struct btrfs_root *root,
324ae4df
Y
2008 u64 bytenr, u64 num, int pin)
2009{
2010 u64 len;
2011 struct btrfs_block_group_cache *cache;
2012 struct btrfs_fs_info *fs_info = root->fs_info;
2013
25179201 2014 WARN_ON(!mutex_is_locked(&root->fs_info->pinned_mutex));
324ae4df
Y
2015 if (pin) {
2016 set_extent_dirty(&fs_info->pinned_extents,
2017 bytenr, bytenr + num - 1, GFP_NOFS);
2018 } else {
2019 clear_extent_dirty(&fs_info->pinned_extents,
2020 bytenr, bytenr + num - 1, GFP_NOFS);
2021 }
2022 while (num > 0) {
2023 cache = btrfs_lookup_block_group(fs_info, bytenr);
e8569813
ZY
2024 BUG_ON(!cache);
2025 len = min(num, cache->key.offset -
2026 (bytenr - cache->key.objectid));
324ae4df 2027 if (pin) {
25179201 2028 spin_lock(&cache->space_info->lock);
e8569813
ZY
2029 spin_lock(&cache->lock);
2030 cache->pinned += len;
2031 cache->space_info->bytes_pinned += len;
2032 spin_unlock(&cache->lock);
25179201 2033 spin_unlock(&cache->space_info->lock);
324ae4df
Y
2034 fs_info->total_pinned += len;
2035 } else {
25179201 2036 spin_lock(&cache->space_info->lock);
e8569813
ZY
2037 spin_lock(&cache->lock);
2038 cache->pinned -= len;
2039 cache->space_info->bytes_pinned -= len;
2040 spin_unlock(&cache->lock);
25179201 2041 spin_unlock(&cache->space_info->lock);
324ae4df 2042 fs_info->total_pinned -= len;
07103a3c
JB
2043 if (cache->cached)
2044 btrfs_add_free_space(cache, bytenr, len);
324ae4df 2045 }
d2fb3437 2046 put_block_group(cache);
324ae4df
Y
2047 bytenr += len;
2048 num -= len;
2049 }
2050 return 0;
2051}
9078a3e1 2052
e8569813
ZY
2053static int update_reserved_extents(struct btrfs_root *root,
2054 u64 bytenr, u64 num, int reserve)
2055{
2056 u64 len;
2057 struct btrfs_block_group_cache *cache;
2058 struct btrfs_fs_info *fs_info = root->fs_info;
2059
e8569813
ZY
2060 while (num > 0) {
2061 cache = btrfs_lookup_block_group(fs_info, bytenr);
2062 BUG_ON(!cache);
2063 len = min(num, cache->key.offset -
2064 (bytenr - cache->key.objectid));
25179201
JB
2065
2066 spin_lock(&cache->space_info->lock);
2067 spin_lock(&cache->lock);
e8569813 2068 if (reserve) {
e8569813
ZY
2069 cache->reserved += len;
2070 cache->space_info->bytes_reserved += len;
e8569813 2071 } else {
e8569813
ZY
2072 cache->reserved -= len;
2073 cache->space_info->bytes_reserved -= len;
e8569813 2074 }
25179201
JB
2075 spin_unlock(&cache->lock);
2076 spin_unlock(&cache->space_info->lock);
d2fb3437 2077 put_block_group(cache);
e8569813
ZY
2078 bytenr += len;
2079 num -= len;
2080 }
2081 return 0;
2082}
2083
d1310b2e 2084int btrfs_copy_pinned(struct btrfs_root *root, struct extent_io_tree *copy)
ccd467d6 2085{
ccd467d6 2086 u64 last = 0;
1a5bc167
CM
2087 u64 start;
2088 u64 end;
d1310b2e 2089 struct extent_io_tree *pinned_extents = &root->fs_info->pinned_extents;
ccd467d6 2090 int ret;
ccd467d6 2091
25179201 2092 mutex_lock(&root->fs_info->pinned_mutex);
d397712b 2093 while (1) {
1a5bc167
CM
2094 ret = find_first_extent_bit(pinned_extents, last,
2095 &start, &end, EXTENT_DIRTY);
2096 if (ret)
ccd467d6 2097 break;
1a5bc167
CM
2098 set_extent_dirty(copy, start, end, GFP_NOFS);
2099 last = end + 1;
ccd467d6 2100 }
25179201 2101 mutex_unlock(&root->fs_info->pinned_mutex);
ccd467d6
CM
2102 return 0;
2103}
2104
2105int btrfs_finish_extent_commit(struct btrfs_trans_handle *trans,
2106 struct btrfs_root *root,
d1310b2e 2107 struct extent_io_tree *unpin)
a28ec197 2108{
1a5bc167
CM
2109 u64 start;
2110 u64 end;
a28ec197 2111 int ret;
a28ec197 2112
25179201 2113 mutex_lock(&root->fs_info->pinned_mutex);
d397712b 2114 while (1) {
1a5bc167
CM
2115 ret = find_first_extent_bit(unpin, 0, &start, &end,
2116 EXTENT_DIRTY);
2117 if (ret)
a28ec197 2118 break;
1f3c79a2
LH
2119
2120 ret = btrfs_discard_extent(root, start, end + 1 - start);
2121
e02119d5 2122 btrfs_update_pinned_extents(root, start, end + 1 - start, 0);
1a5bc167 2123 clear_extent_dirty(unpin, start, end, GFP_NOFS);
1f3c79a2 2124
c286ac48 2125 if (need_resched()) {
25179201 2126 mutex_unlock(&root->fs_info->pinned_mutex);
c286ac48 2127 cond_resched();
25179201 2128 mutex_lock(&root->fs_info->pinned_mutex);
c286ac48 2129 }
a28ec197 2130 }
25179201 2131 mutex_unlock(&root->fs_info->pinned_mutex);
1f3c79a2 2132 return ret;
a28ec197
CM
2133}
2134
31840ae1
ZY
2135static int pin_down_bytes(struct btrfs_trans_handle *trans,
2136 struct btrfs_root *root,
2137 u64 bytenr, u64 num_bytes, int is_data)
e20d96d6 2138{
1a5bc167 2139 int err = 0;
31840ae1 2140 struct extent_buffer *buf;
8ef97622 2141
31840ae1
ZY
2142 if (is_data)
2143 goto pinit;
2144
2145 buf = btrfs_find_tree_block(root, bytenr, num_bytes);
2146 if (!buf)
2147 goto pinit;
2148
2149 /* we can reuse a block if it hasn't been written
2150 * and it is from this transaction. We can't
2151 * reuse anything from the tree log root because
2152 * it has tiny sub-transactions.
2153 */
2154 if (btrfs_buffer_uptodate(buf, 0) &&
2155 btrfs_try_tree_lock(buf)) {
2156 u64 header_owner = btrfs_header_owner(buf);
2157 u64 header_transid = btrfs_header_generation(buf);
2158 if (header_owner != BTRFS_TREE_LOG_OBJECTID &&
1a40e23b 2159 header_owner != BTRFS_TREE_RELOC_OBJECTID &&
56bec294 2160 header_owner != BTRFS_DATA_RELOC_TREE_OBJECTID &&
31840ae1
ZY
2161 header_transid == trans->transid &&
2162 !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN)) {
2163 clean_tree_block(NULL, root, buf);
2164 btrfs_tree_unlock(buf);
5f39d397 2165 free_extent_buffer(buf);
31840ae1 2166 return 1;
8ef97622 2167 }
31840ae1 2168 btrfs_tree_unlock(buf);
f4b9aa8d 2169 }
31840ae1
ZY
2170 free_extent_buffer(buf);
2171pinit:
2172 btrfs_update_pinned_extents(root, bytenr, num_bytes, 1);
2173
be744175 2174 BUG_ON(err < 0);
e20d96d6
CM
2175 return 0;
2176}
2177
fec577fb 2178/*
a28ec197 2179 * remove an extent from the root, returns 0 on success
fec577fb 2180 */
31840ae1
ZY
2181static int __free_extent(struct btrfs_trans_handle *trans,
2182 struct btrfs_root *root,
2183 u64 bytenr, u64 num_bytes, u64 parent,
7bb86316 2184 u64 root_objectid, u64 ref_generation,
56bec294
CM
2185 u64 owner_objectid, int pin, int mark_free,
2186 int refs_to_drop)
a28ec197 2187{
5caf2a00 2188 struct btrfs_path *path;
e2fa7227 2189 struct btrfs_key key;
1261ec42
CM
2190 struct btrfs_fs_info *info = root->fs_info;
2191 struct btrfs_root *extent_root = info->extent_root;
5f39d397 2192 struct extent_buffer *leaf;
a28ec197 2193 int ret;
952fccac
CM
2194 int extent_slot = 0;
2195 int found_extent = 0;
2196 int num_to_del = 1;
234b63a0 2197 struct btrfs_extent_item *ei;
cf27e1ee 2198 u32 refs;
037e6390 2199
db94535d 2200 key.objectid = bytenr;
62e2749e 2201 btrfs_set_key_type(&key, BTRFS_EXTENT_ITEM_KEY);
db94535d 2202 key.offset = num_bytes;
5caf2a00 2203 path = btrfs_alloc_path();
54aa1f4d
CM
2204 if (!path)
2205 return -ENOMEM;
5f26f772 2206
3c12ac72 2207 path->reada = 1;
3bb1a1bc
YZ
2208 ret = lookup_extent_backref(trans, extent_root, path,
2209 bytenr, parent, root_objectid,
2210 ref_generation, owner_objectid, 1);
7bb86316 2211 if (ret == 0) {
952fccac
CM
2212 struct btrfs_key found_key;
2213 extent_slot = path->slots[0];
d397712b 2214 while (extent_slot > 0) {
952fccac
CM
2215 extent_slot--;
2216 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
2217 extent_slot);
2218 if (found_key.objectid != bytenr)
2219 break;
2220 if (found_key.type == BTRFS_EXTENT_ITEM_KEY &&
2221 found_key.offset == num_bytes) {
2222 found_extent = 1;
2223 break;
2224 }
2225 if (path->slots[0] - extent_slot > 5)
2226 break;
2227 }
31840ae1 2228 if (!found_extent) {
56bec294
CM
2229 ret = remove_extent_backref(trans, extent_root, path,
2230 refs_to_drop);
31840ae1
ZY
2231 BUG_ON(ret);
2232 btrfs_release_path(extent_root, path);
2233 ret = btrfs_search_slot(trans, extent_root,
2234 &key, path, -1, 1);
f3465ca4
JB
2235 if (ret) {
2236 printk(KERN_ERR "umm, got %d back from search"
d397712b
CM
2237 ", was looking for %llu\n", ret,
2238 (unsigned long long)bytenr);
f3465ca4
JB
2239 btrfs_print_leaf(extent_root, path->nodes[0]);
2240 }
31840ae1
ZY
2241 BUG_ON(ret);
2242 extent_slot = path->slots[0];
2243 }
7bb86316
CM
2244 } else {
2245 btrfs_print_leaf(extent_root, path->nodes[0]);
2246 WARN_ON(1);
d397712b 2247 printk(KERN_ERR "btrfs unable to find ref byte nr %llu "
56bec294 2248 "parent %llu root %llu gen %llu owner %llu\n",
d397712b 2249 (unsigned long long)bytenr,
56bec294 2250 (unsigned long long)parent,
d397712b
CM
2251 (unsigned long long)root_objectid,
2252 (unsigned long long)ref_generation,
2253 (unsigned long long)owner_objectid);
7bb86316 2254 }
5f39d397
CM
2255
2256 leaf = path->nodes[0];
952fccac 2257 ei = btrfs_item_ptr(leaf, extent_slot,
123abc88 2258 struct btrfs_extent_item);
5f39d397 2259 refs = btrfs_extent_refs(leaf, ei);
952fccac 2260
56bec294
CM
2261 /*
2262 * we're not allowed to delete the extent item if there
2263 * are other delayed ref updates pending
2264 */
2265
2266 BUG_ON(refs < refs_to_drop);
2267 refs -= refs_to_drop;
2268 btrfs_set_extent_refs(leaf, ei, refs);
5f39d397
CM
2269 btrfs_mark_buffer_dirty(leaf);
2270
56bec294
CM
2271 if (refs == 0 && found_extent &&
2272 path->slots[0] == extent_slot + 1) {
31840ae1
ZY
2273 struct btrfs_extent_ref *ref;
2274 ref = btrfs_item_ptr(leaf, path->slots[0],
2275 struct btrfs_extent_ref);
56bec294 2276 BUG_ON(btrfs_ref_num_refs(leaf, ref) != refs_to_drop);
952fccac
CM
2277 /* if the back ref and the extent are next to each other
2278 * they get deleted below in one shot
2279 */
2280 path->slots[0] = extent_slot;
2281 num_to_del = 2;
2282 } else if (found_extent) {
2283 /* otherwise delete the extent back ref */
56bec294
CM
2284 ret = remove_extent_backref(trans, extent_root, path,
2285 refs_to_drop);
952fccac
CM
2286 BUG_ON(ret);
2287 /* if refs are 0, we need to setup the path for deletion */
2288 if (refs == 0) {
2289 btrfs_release_path(extent_root, path);
2290 ret = btrfs_search_slot(trans, extent_root, &key, path,
2291 -1, 1);
952fccac
CM
2292 BUG_ON(ret);
2293 }
2294 }
2295
cf27e1ee 2296 if (refs == 0) {
db94535d
CM
2297 u64 super_used;
2298 u64 root_used;
78fae27e
CM
2299
2300 if (pin) {
25179201 2301 mutex_lock(&root->fs_info->pinned_mutex);
31840ae1
ZY
2302 ret = pin_down_bytes(trans, root, bytenr, num_bytes,
2303 owner_objectid >= BTRFS_FIRST_FREE_OBJECTID);
25179201 2304 mutex_unlock(&root->fs_info->pinned_mutex);
c549228f
Y
2305 if (ret > 0)
2306 mark_free = 1;
2307 BUG_ON(ret < 0);
78fae27e 2308 }
58176a96 2309 /* block accounting for super block */
75eff68e 2310 spin_lock(&info->delalloc_lock);
db94535d
CM
2311 super_used = btrfs_super_bytes_used(&info->super_copy);
2312 btrfs_set_super_bytes_used(&info->super_copy,
2313 super_used - num_bytes);
58176a96
JB
2314
2315 /* block accounting for root item */
db94535d 2316 root_used = btrfs_root_used(&root->root_item);
5f39d397 2317 btrfs_set_root_used(&root->root_item,
db94535d 2318 root_used - num_bytes);
34bf63c4 2319 spin_unlock(&info->delalloc_lock);
952fccac
CM
2320 ret = btrfs_del_items(trans, extent_root, path, path->slots[0],
2321 num_to_del);
31840ae1 2322 BUG_ON(ret);
25179201 2323 btrfs_release_path(extent_root, path);
21af804c 2324
459931ec
CM
2325 if (owner_objectid >= BTRFS_FIRST_FREE_OBJECTID) {
2326 ret = btrfs_del_csums(trans, root, bytenr, num_bytes);
2327 BUG_ON(ret);
2328 }
2329
dcbdd4dc
CM
2330 ret = update_block_group(trans, root, bytenr, num_bytes, 0,
2331 mark_free);
2332 BUG_ON(ret);
a28ec197 2333 }
5caf2a00 2334 btrfs_free_path(path);
a28ec197
CM
2335 return ret;
2336}
2337
fec577fb
CM
2338/*
2339 * remove an extent from the root, returns 0 on success
2340 */
925baedd 2341static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
56bec294
CM
2342 struct btrfs_root *root,
2343 u64 bytenr, u64 num_bytes, u64 parent,
2344 u64 root_objectid, u64 ref_generation,
2345 u64 owner_objectid, int pin,
2346 int refs_to_drop)
fec577fb 2347{
db94535d 2348 WARN_ON(num_bytes < root->sectorsize);
31840ae1 2349
56bec294
CM
2350 /*
2351 * if metadata always pin
2352 * if data pin when any transaction has committed this
2353 */
2354 if (owner_objectid < BTRFS_FIRST_FREE_OBJECTID ||
2355 ref_generation != trans->transid)
4bef0848
CM
2356 pin = 1;
2357
4bef0848
CM
2358 if (ref_generation != trans->transid)
2359 pin = 1;
2360
56bec294 2361 return __free_extent(trans, root, bytenr, num_bytes, parent,
3bb1a1bc 2362 root_objectid, ref_generation,
56bec294 2363 owner_objectid, pin, pin == 0, refs_to_drop);
fec577fb
CM
2364}
2365
1887be66
CM
2366/*
2367 * when we free an extent, it is possible (and likely) that we free the last
2368 * delayed ref for that extent as well. This searches the delayed ref tree for
2369 * a given extent, and if there are no other delayed refs to be processed, it
2370 * removes it from the tree.
2371 */
2372static noinline int check_ref_cleanup(struct btrfs_trans_handle *trans,
2373 struct btrfs_root *root, u64 bytenr)
2374{
2375 struct btrfs_delayed_ref_head *head;
2376 struct btrfs_delayed_ref_root *delayed_refs;
2377 struct btrfs_delayed_ref_node *ref;
2378 struct rb_node *node;
2379 int ret;
2380
2381 delayed_refs = &trans->transaction->delayed_refs;
2382 spin_lock(&delayed_refs->lock);
2383 head = btrfs_find_delayed_ref_head(trans, bytenr);
2384 if (!head)
2385 goto out;
2386
2387 node = rb_prev(&head->node.rb_node);
2388 if (!node)
2389 goto out;
2390
2391 ref = rb_entry(node, struct btrfs_delayed_ref_node, rb_node);
2392
2393 /* there are still entries for this ref, we can't drop it */
2394 if (ref->bytenr == bytenr)
2395 goto out;
2396
2397 /*
2398 * waiting for the lock here would deadlock. If someone else has it
2399 * locked they are already in the process of dropping it anyway
2400 */
2401 if (!mutex_trylock(&head->mutex))
2402 goto out;
2403
2404 /*
2405 * at this point we have a head with no other entries. Go
2406 * ahead and process it.
2407 */
2408 head->node.in_tree = 0;
2409 rb_erase(&head->node.rb_node, &delayed_refs->root);
2410 delayed_refs->num_entries--;
2411
2412 /*
2413 * we don't take a ref on the node because we're removing it from the
2414 * tree, so we just steal the ref the tree was holding.
2415 */
2416 spin_unlock(&delayed_refs->lock);
2417
2418 ret = run_one_delayed_ref(trans, root->fs_info->tree_root,
2419 &head->node, head->must_insert_reserved);
2420 BUG_ON(ret);
2421 btrfs_put_delayed_ref(&head->node);
2422 return 0;
2423out:
2424 spin_unlock(&delayed_refs->lock);
2425 return 0;
2426}
2427
925baedd 2428int btrfs_free_extent(struct btrfs_trans_handle *trans,
31840ae1
ZY
2429 struct btrfs_root *root,
2430 u64 bytenr, u64 num_bytes, u64 parent,
2431 u64 root_objectid, u64 ref_generation,
3bb1a1bc 2432 u64 owner_objectid, int pin)
925baedd
CM
2433{
2434 int ret;
2435
56bec294
CM
2436 /*
2437 * tree log blocks never actually go into the extent allocation
2438 * tree, just update pinning info and exit early.
2439 *
2440 * data extents referenced by the tree log do need to have
2441 * their reference counts bumped.
2442 */
2443 if (root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID &&
2444 owner_objectid < BTRFS_FIRST_FREE_OBJECTID) {
2445 mutex_lock(&root->fs_info->pinned_mutex);
2446 btrfs_update_pinned_extents(root, bytenr, num_bytes, 1);
2447 mutex_unlock(&root->fs_info->pinned_mutex);
2448 update_reserved_extents(root, bytenr, num_bytes, 0);
2449 ret = 0;
2450 } else {
2451 ret = btrfs_add_delayed_ref(trans, bytenr, num_bytes, parent,
2452 root_objectid, ref_generation,
2453 owner_objectid,
2454 BTRFS_DROP_DELAYED_REF, 1);
1887be66
CM
2455 BUG_ON(ret);
2456 ret = check_ref_cleanup(trans, root, bytenr);
2457 BUG_ON(ret);
56bec294 2458 }
925baedd
CM
2459 return ret;
2460}
2461
87ee04eb
CM
2462static u64 stripe_align(struct btrfs_root *root, u64 val)
2463{
2464 u64 mask = ((u64)root->stripesize - 1);
2465 u64 ret = (val + mask) & ~mask;
2466 return ret;
2467}
2468
fec577fb
CM
2469/*
2470 * walks the btree of allocated extents and find a hole of a given size.
2471 * The key ins is changed to record the hole:
2472 * ins->objectid == block start
62e2749e 2473 * ins->flags = BTRFS_EXTENT_ITEM_KEY
fec577fb
CM
2474 * ins->offset == number of blocks
2475 * Any available blocks before search_start are skipped.
2476 */
d397712b 2477static noinline int find_free_extent(struct btrfs_trans_handle *trans,
98ed5174
CM
2478 struct btrfs_root *orig_root,
2479 u64 num_bytes, u64 empty_size,
2480 u64 search_start, u64 search_end,
2481 u64 hint_byte, struct btrfs_key *ins,
2482 u64 exclude_start, u64 exclude_nr,
2483 int data)
fec577fb 2484{
80eb234a 2485 int ret = 0;
d397712b 2486 struct btrfs_root *root = orig_root->fs_info->extent_root;
db94535d 2487 u64 total_needed = num_bytes;
239b14b3 2488 u64 *last_ptr = NULL;
4366211c 2489 u64 last_wanted = 0;
80eb234a 2490 struct btrfs_block_group_cache *block_group = NULL;
0ef3e66b 2491 int chunk_alloc_done = 0;
239b14b3 2492 int empty_cluster = 2 * 1024 * 1024;
0ef3e66b 2493 int allowed_chunk_alloc = 0;
80eb234a
JB
2494 struct list_head *head = NULL, *cur = NULL;
2495 int loop = 0;
f5a31e16 2496 int extra_loop = 0;
80eb234a 2497 struct btrfs_space_info *space_info;
fec577fb 2498
db94535d 2499 WARN_ON(num_bytes < root->sectorsize);
b1a4d965 2500 btrfs_set_key_type(ins, BTRFS_EXTENT_ITEM_KEY);
80eb234a
JB
2501 ins->objectid = 0;
2502 ins->offset = 0;
b1a4d965 2503
0ef3e66b
CM
2504 if (orig_root->ref_cows || empty_size)
2505 allowed_chunk_alloc = 1;
2506
239b14b3
CM
2507 if (data & BTRFS_BLOCK_GROUP_METADATA) {
2508 last_ptr = &root->fs_info->last_alloc;
536ac8ae
CM
2509 if (!btrfs_test_opt(root, SSD))
2510 empty_cluster = 64 * 1024;
239b14b3
CM
2511 }
2512
0f9dd46c 2513 if ((data & BTRFS_BLOCK_GROUP_DATA) && btrfs_test_opt(root, SSD))
239b14b3 2514 last_ptr = &root->fs_info->last_data_alloc;
0f9dd46c 2515
239b14b3 2516 if (last_ptr) {
4366211c 2517 if (*last_ptr) {
239b14b3 2518 hint_byte = *last_ptr;
4366211c
CM
2519 last_wanted = *last_ptr;
2520 } else
239b14b3 2521 empty_size += empty_cluster;
4366211c
CM
2522 } else {
2523 empty_cluster = 0;
239b14b3 2524 }
a061fc8d 2525 search_start = max(search_start, first_logical_byte(root, 0));
239b14b3 2526 search_start = max(search_start, hint_byte);
0b86a832 2527
42e70e7a 2528 if (last_wanted && search_start != last_wanted) {
4366211c 2529 last_wanted = 0;
42e70e7a
CM
2530 empty_size += empty_cluster;
2531 }
4366211c 2532
42e70e7a 2533 total_needed += empty_size;
80eb234a 2534 block_group = btrfs_lookup_block_group(root->fs_info, search_start);
d899e052
YZ
2535 if (!block_group)
2536 block_group = btrfs_lookup_first_block_group(root->fs_info,
2537 search_start);
80eb234a 2538 space_info = __find_space_info(root->fs_info, data);
0f9dd46c 2539
80eb234a
JB
2540 down_read(&space_info->groups_sem);
2541 while (1) {
2542 struct btrfs_free_space *free_space;
0f9dd46c 2543 /*
80eb234a
JB
2544 * the only way this happens if our hint points to a block
2545 * group thats not of the proper type, while looping this
2546 * should never happen
0f9dd46c 2547 */
8a1413a2
CM
2548 if (empty_size)
2549 extra_loop = 1;
2550
42e70e7a
CM
2551 if (!block_group)
2552 goto new_group_no_lock;
2553
ea6a478e
JB
2554 if (unlikely(!block_group->cached)) {
2555 mutex_lock(&block_group->cache_mutex);
2556 ret = cache_block_group(root, block_group);
2557 mutex_unlock(&block_group->cache_mutex);
2558 if (ret)
2559 break;
2560 }
2561
25179201 2562 mutex_lock(&block_group->alloc_mutex);
80eb234a 2563 if (unlikely(!block_group_bits(block_group, data)))
0f9dd46c 2564 goto new_group;
0f9dd46c 2565
ea6a478e 2566 if (unlikely(block_group->ro))
80eb234a 2567 goto new_group;
0f9dd46c 2568
80eb234a
JB
2569 free_space = btrfs_find_free_space(block_group, search_start,
2570 total_needed);
2571 if (free_space) {
2572 u64 start = block_group->key.objectid;
2573 u64 end = block_group->key.objectid +
0f9dd46c 2574 block_group->key.offset;
239b14b3 2575
80eb234a 2576 search_start = stripe_align(root, free_space->offset);
0f9dd46c 2577
80eb234a
JB
2578 /* move on to the next group */
2579 if (search_start + num_bytes >= search_end)
2580 goto new_group;
e37c9e69 2581
80eb234a
JB
2582 /* move on to the next group */
2583 if (search_start + num_bytes > end)
2584 goto new_group;
2585
4366211c 2586 if (last_wanted && search_start != last_wanted) {
3b7885bf 2587 total_needed += empty_cluster;
8a1413a2 2588 empty_size += empty_cluster;
4366211c 2589 last_wanted = 0;
3b7885bf
CM
2590 /*
2591 * if search_start is still in this block group
2592 * then we just re-search this block group
2593 */
2594 if (search_start >= start &&
2595 search_start < end) {
2596 mutex_unlock(&block_group->alloc_mutex);
2597 continue;
2598 }
2599
2600 /* else we go to the next block group */
2601 goto new_group;
2602 }
2603
80eb234a
JB
2604 if (exclude_nr > 0 &&
2605 (search_start + num_bytes > exclude_start &&
2606 search_start < exclude_start + exclude_nr)) {
2607 search_start = exclude_start + exclude_nr;
2608 /*
2609 * if search_start is still in this block group
2610 * then we just re-search this block group
2611 */
2612 if (search_start >= start &&
25179201
JB
2613 search_start < end) {
2614 mutex_unlock(&block_group->alloc_mutex);
4366211c 2615 last_wanted = 0;
80eb234a 2616 continue;
25179201 2617 }
80eb234a
JB
2618
2619 /* else we go to the next block group */
2620 goto new_group;
2621 }
2622
2623 ins->objectid = search_start;
2624 ins->offset = num_bytes;
25179201
JB
2625
2626 btrfs_remove_free_space_lock(block_group, search_start,
2627 num_bytes);
80eb234a 2628 /* we are all good, lets return */
25179201 2629 mutex_unlock(&block_group->alloc_mutex);
80eb234a 2630 break;
0f9dd46c 2631 }
80eb234a 2632new_group:
42e70e7a 2633 mutex_unlock(&block_group->alloc_mutex);
d2fb3437
YZ
2634 put_block_group(block_group);
2635 block_group = NULL;
42e70e7a 2636new_group_no_lock:
f5a31e16
CM
2637 /* don't try to compare new allocations against the
2638 * last allocation any more
2639 */
4366211c 2640 last_wanted = 0;
f5a31e16 2641
80eb234a
JB
2642 /*
2643 * Here's how this works.
2644 * loop == 0: we were searching a block group via a hint
2645 * and didn't find anything, so we start at
2646 * the head of the block groups and keep searching
2647 * loop == 1: we're searching through all of the block groups
2648 * if we hit the head again we have searched
2649 * all of the block groups for this space and we
2650 * need to try and allocate, if we cant error out.
2651 * loop == 2: we allocated more space and are looping through
2652 * all of the block groups again.
2653 */
2654 if (loop == 0) {
2655 head = &space_info->block_groups;
2656 cur = head->next;
80eb234a
JB
2657 loop++;
2658 } else if (loop == 1 && cur == head) {
f5a31e16
CM
2659 int keep_going;
2660
2661 /* at this point we give up on the empty_size
2662 * allocations and just try to allocate the min
2663 * space.
2664 *
2665 * The extra_loop field was set if an empty_size
2666 * allocation was attempted above, and if this
2667 * is try we need to try the loop again without
2668 * the additional empty_size.
2669 */
5b7c3fcc
CM
2670 total_needed -= empty_size;
2671 empty_size = 0;
f5a31e16
CM
2672 keep_going = extra_loop;
2673 loop++;
42e70e7a 2674
80eb234a
JB
2675 if (allowed_chunk_alloc && !chunk_alloc_done) {
2676 up_read(&space_info->groups_sem);
2677 ret = do_chunk_alloc(trans, root, num_bytes +
2678 2 * 1024 * 1024, data, 1);
80eb234a 2679 down_read(&space_info->groups_sem);
2ed6d664
CM
2680 if (ret < 0)
2681 goto loop_check;
80eb234a 2682 head = &space_info->block_groups;
f5a31e16
CM
2683 /*
2684 * we've allocated a new chunk, keep
2685 * trying
2686 */
2687 keep_going = 1;
80eb234a
JB
2688 chunk_alloc_done = 1;
2689 } else if (!allowed_chunk_alloc) {
2690 space_info->force_alloc = 1;
f5a31e16 2691 }
2ed6d664 2692loop_check:
f5a31e16
CM
2693 if (keep_going) {
2694 cur = head->next;
2695 extra_loop = 0;
80eb234a
JB
2696 } else {
2697 break;
2698 }
2699 } else if (cur == head) {
2700 break;
0f9dd46c 2701 }
0b86a832 2702
80eb234a
JB
2703 block_group = list_entry(cur, struct btrfs_block_group_cache,
2704 list);
d2fb3437
YZ
2705 atomic_inc(&block_group->count);
2706
80eb234a
JB
2707 search_start = block_group->key.objectid;
2708 cur = cur->next;
f2654de4 2709 }
0b86a832 2710
80eb234a
JB
2711 /* we found what we needed */
2712 if (ins->objectid) {
2713 if (!(data & BTRFS_BLOCK_GROUP_DATA))
d2fb3437 2714 trans->block_group = block_group->key.objectid;
0f9dd46c 2715
80eb234a
JB
2716 if (last_ptr)
2717 *last_ptr = ins->objectid + ins->offset;
2718 ret = 0;
2719 } else if (!ret) {
d397712b
CM
2720 printk(KERN_ERR "btrfs searching for %llu bytes, "
2721 "num_bytes %llu, loop %d, allowed_alloc %d\n",
2722 (unsigned long long)total_needed,
2723 (unsigned long long)num_bytes,
4ce4cb52 2724 loop, allowed_chunk_alloc);
80eb234a 2725 ret = -ENOSPC;
be744175 2726 }
d2fb3437
YZ
2727 if (block_group)
2728 put_block_group(block_group);
be744175 2729
80eb234a 2730 up_read(&space_info->groups_sem);
0f70abe2 2731 return ret;
fec577fb 2732}
ec44a35c 2733
0f9dd46c
JB
2734static void dump_space_info(struct btrfs_space_info *info, u64 bytes)
2735{
2736 struct btrfs_block_group_cache *cache;
0f9dd46c 2737
d397712b
CM
2738 printk(KERN_INFO "space_info has %llu free, is %sfull\n",
2739 (unsigned long long)(info->total_bytes - info->bytes_used -
2740 info->bytes_pinned - info->bytes_reserved),
2741 (info->full) ? "" : "not ");
6a63209f
JB
2742 printk(KERN_INFO "space_info total=%llu, pinned=%llu, delalloc=%llu,"
2743 " may_use=%llu, used=%llu\n", info->total_bytes,
2744 info->bytes_pinned, info->bytes_delalloc, info->bytes_may_use,
2745 info->bytes_used);
0f9dd46c 2746
80eb234a 2747 down_read(&info->groups_sem);
c6e30871 2748 list_for_each_entry(cache, &info->block_groups, list) {
0f9dd46c 2749 spin_lock(&cache->lock);
d397712b
CM
2750 printk(KERN_INFO "block group %llu has %llu bytes, %llu used "
2751 "%llu pinned %llu reserved\n",
2752 (unsigned long long)cache->key.objectid,
2753 (unsigned long long)cache->key.offset,
2754 (unsigned long long)btrfs_block_group_used(&cache->item),
2755 (unsigned long long)cache->pinned,
2756 (unsigned long long)cache->reserved);
0f9dd46c
JB
2757 btrfs_dump_free_space(cache, bytes);
2758 spin_unlock(&cache->lock);
2759 }
80eb234a 2760 up_read(&info->groups_sem);
0f9dd46c 2761}
e8569813 2762
e6dcd2dc
CM
2763static int __btrfs_reserve_extent(struct btrfs_trans_handle *trans,
2764 struct btrfs_root *root,
2765 u64 num_bytes, u64 min_alloc_size,
2766 u64 empty_size, u64 hint_byte,
2767 u64 search_end, struct btrfs_key *ins,
2768 u64 data)
fec577fb
CM
2769{
2770 int ret;
fbdc762b 2771 u64 search_start = 0;
1261ec42 2772 struct btrfs_fs_info *info = root->fs_info;
925baedd 2773
6a63209f 2774 data = btrfs_get_alloc_profile(root, data);
98d20f67 2775again:
0ef3e66b
CM
2776 /*
2777 * the only place that sets empty_size is btrfs_realloc_node, which
2778 * is not called recursively on allocations
2779 */
2780 if (empty_size || root->ref_cows) {
593060d7 2781 if (!(data & BTRFS_BLOCK_GROUP_METADATA)) {
6324fbf3 2782 ret = do_chunk_alloc(trans, root->fs_info->extent_root,
0ef3e66b
CM
2783 2 * 1024 * 1024,
2784 BTRFS_BLOCK_GROUP_METADATA |
2785 (info->metadata_alloc_profile &
2786 info->avail_metadata_alloc_bits), 0);
6324fbf3
CM
2787 }
2788 ret = do_chunk_alloc(trans, root->fs_info->extent_root,
0ef3e66b 2789 num_bytes + 2 * 1024 * 1024, data, 0);
6324fbf3 2790 }
0b86a832 2791
db94535d
CM
2792 WARN_ON(num_bytes < root->sectorsize);
2793 ret = find_free_extent(trans, root, num_bytes, empty_size,
2794 search_start, search_end, hint_byte, ins,
26b8003f
CM
2795 trans->alloc_exclude_start,
2796 trans->alloc_exclude_nr, data);
3b951516 2797
98d20f67
CM
2798 if (ret == -ENOSPC && num_bytes > min_alloc_size) {
2799 num_bytes = num_bytes >> 1;
0f9dd46c 2800 num_bytes = num_bytes & ~(root->sectorsize - 1);
98d20f67 2801 num_bytes = max(num_bytes, min_alloc_size);
0ef3e66b
CM
2802 do_chunk_alloc(trans, root->fs_info->extent_root,
2803 num_bytes, data, 1);
98d20f67
CM
2804 goto again;
2805 }
ec44a35c 2806 if (ret) {
0f9dd46c
JB
2807 struct btrfs_space_info *sinfo;
2808
2809 sinfo = __find_space_info(root->fs_info, data);
d397712b
CM
2810 printk(KERN_ERR "btrfs allocation failed flags %llu, "
2811 "wanted %llu\n", (unsigned long long)data,
2812 (unsigned long long)num_bytes);
0f9dd46c 2813 dump_space_info(sinfo, num_bytes);
925baedd 2814 BUG();
925baedd 2815 }
0f9dd46c
JB
2816
2817 return ret;
e6dcd2dc
CM
2818}
2819
65b51a00
CM
2820int btrfs_free_reserved_extent(struct btrfs_root *root, u64 start, u64 len)
2821{
0f9dd46c 2822 struct btrfs_block_group_cache *cache;
1f3c79a2 2823 int ret = 0;
0f9dd46c 2824
0f9dd46c
JB
2825 cache = btrfs_lookup_block_group(root->fs_info, start);
2826 if (!cache) {
d397712b
CM
2827 printk(KERN_ERR "Unable to find block group for %llu\n",
2828 (unsigned long long)start);
0f9dd46c
JB
2829 return -ENOSPC;
2830 }
1f3c79a2
LH
2831
2832 ret = btrfs_discard_extent(root, start, len);
2833
0f9dd46c 2834 btrfs_add_free_space(cache, start, len);
d2fb3437 2835 put_block_group(cache);
1a40e23b 2836 update_reserved_extents(root, start, len, 0);
1f3c79a2
LH
2837
2838 return ret;
65b51a00
CM
2839}
2840
e6dcd2dc
CM
2841int btrfs_reserve_extent(struct btrfs_trans_handle *trans,
2842 struct btrfs_root *root,
2843 u64 num_bytes, u64 min_alloc_size,
2844 u64 empty_size, u64 hint_byte,
2845 u64 search_end, struct btrfs_key *ins,
2846 u64 data)
2847{
2848 int ret;
e6dcd2dc
CM
2849 ret = __btrfs_reserve_extent(trans, root, num_bytes, min_alloc_size,
2850 empty_size, hint_byte, search_end, ins,
2851 data);
e8569813 2852 update_reserved_extents(root, ins->objectid, ins->offset, 1);
e6dcd2dc
CM
2853 return ret;
2854}
2855
2856static int __btrfs_alloc_reserved_extent(struct btrfs_trans_handle *trans,
31840ae1 2857 struct btrfs_root *root, u64 parent,
e6dcd2dc 2858 u64 root_objectid, u64 ref_generation,
56bec294
CM
2859 u64 owner, struct btrfs_key *ins,
2860 int ref_mod)
e6dcd2dc
CM
2861{
2862 int ret;
e6dcd2dc
CM
2863 u64 super_used;
2864 u64 root_used;
2865 u64 num_bytes = ins->offset;
2866 u32 sizes[2];
2867 struct btrfs_fs_info *info = root->fs_info;
2868 struct btrfs_root *extent_root = info->extent_root;
2869 struct btrfs_extent_item *extent_item;
2870 struct btrfs_extent_ref *ref;
2871 struct btrfs_path *path;
2872 struct btrfs_key keys[2];
fec577fb 2873
31840ae1
ZY
2874 if (parent == 0)
2875 parent = ins->objectid;
2876
58176a96 2877 /* block accounting for super block */
75eff68e 2878 spin_lock(&info->delalloc_lock);
db94535d
CM
2879 super_used = btrfs_super_bytes_used(&info->super_copy);
2880 btrfs_set_super_bytes_used(&info->super_copy, super_used + num_bytes);
26b8003f 2881
58176a96 2882 /* block accounting for root item */
db94535d
CM
2883 root_used = btrfs_root_used(&root->root_item);
2884 btrfs_set_root_used(&root->root_item, root_used + num_bytes);
34bf63c4 2885 spin_unlock(&info->delalloc_lock);
58176a96 2886
47e4bb98 2887 memcpy(&keys[0], ins, sizeof(*ins));
47e4bb98
CM
2888 keys[1].objectid = ins->objectid;
2889 keys[1].type = BTRFS_EXTENT_REF_KEY;
31840ae1 2890 keys[1].offset = parent;
47e4bb98
CM
2891 sizes[0] = sizeof(*extent_item);
2892 sizes[1] = sizeof(*ref);
7bb86316
CM
2893
2894 path = btrfs_alloc_path();
2895 BUG_ON(!path);
47e4bb98
CM
2896
2897 ret = btrfs_insert_empty_items(trans, extent_root, path, keys,
2898 sizes, 2);
ccd467d6 2899 BUG_ON(ret);
0f9dd46c 2900
47e4bb98
CM
2901 extent_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
2902 struct btrfs_extent_item);
56bec294 2903 btrfs_set_extent_refs(path->nodes[0], extent_item, ref_mod);
47e4bb98
CM
2904 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
2905 struct btrfs_extent_ref);
2906
2907 btrfs_set_ref_root(path->nodes[0], ref, root_objectid);
2908 btrfs_set_ref_generation(path->nodes[0], ref, ref_generation);
2909 btrfs_set_ref_objectid(path->nodes[0], ref, owner);
56bec294 2910 btrfs_set_ref_num_refs(path->nodes[0], ref, ref_mod);
47e4bb98
CM
2911
2912 btrfs_mark_buffer_dirty(path->nodes[0]);
2913
2914 trans->alloc_exclude_start = 0;
2915 trans->alloc_exclude_nr = 0;
7bb86316 2916 btrfs_free_path(path);
f510cfec 2917
925baedd
CM
2918 if (ret)
2919 goto out;
26b8003f 2920
d397712b
CM
2921 ret = update_block_group(trans, root, ins->objectid,
2922 ins->offset, 1, 0);
f5947066 2923 if (ret) {
d397712b
CM
2924 printk(KERN_ERR "btrfs update block group failed for %llu "
2925 "%llu\n", (unsigned long long)ins->objectid,
2926 (unsigned long long)ins->offset);
f5947066
CM
2927 BUG();
2928 }
925baedd 2929out:
e6dcd2dc
CM
2930 return ret;
2931}
2932
2933int btrfs_alloc_reserved_extent(struct btrfs_trans_handle *trans,
31840ae1 2934 struct btrfs_root *root, u64 parent,
e6dcd2dc 2935 u64 root_objectid, u64 ref_generation,
3bb1a1bc 2936 u64 owner, struct btrfs_key *ins)
e6dcd2dc
CM
2937{
2938 int ret;
1c2308f8
CM
2939
2940 if (root_objectid == BTRFS_TREE_LOG_OBJECTID)
2941 return 0;
56bec294
CM
2942
2943 ret = btrfs_add_delayed_ref(trans, ins->objectid,
2944 ins->offset, parent, root_objectid,
2945 ref_generation, owner,
2946 BTRFS_ADD_DELAYED_EXTENT, 0);
2947 BUG_ON(ret);
e6dcd2dc
CM
2948 return ret;
2949}
e02119d5
CM
2950
2951/*
2952 * this is used by the tree logging recovery code. It records that
2953 * an extent has been allocated and makes sure to clear the free
2954 * space cache bits as well
2955 */
2956int btrfs_alloc_logged_extent(struct btrfs_trans_handle *trans,
31840ae1 2957 struct btrfs_root *root, u64 parent,
e02119d5 2958 u64 root_objectid, u64 ref_generation,
3bb1a1bc 2959 u64 owner, struct btrfs_key *ins)
e02119d5
CM
2960{
2961 int ret;
2962 struct btrfs_block_group_cache *block_group;
2963
e02119d5 2964 block_group = btrfs_lookup_block_group(root->fs_info, ins->objectid);
ea6a478e 2965 mutex_lock(&block_group->cache_mutex);
e02119d5 2966 cache_block_group(root, block_group);
ea6a478e 2967 mutex_unlock(&block_group->cache_mutex);
e02119d5 2968
ea6a478e
JB
2969 ret = btrfs_remove_free_space(block_group, ins->objectid,
2970 ins->offset);
0f9dd46c 2971 BUG_ON(ret);
d2fb3437 2972 put_block_group(block_group);
3bb1a1bc 2973 ret = __btrfs_alloc_reserved_extent(trans, root, parent, root_objectid,
56bec294 2974 ref_generation, owner, ins, 1);
e02119d5
CM
2975 return ret;
2976}
2977
e6dcd2dc
CM
2978/*
2979 * finds a free extent and does all the dirty work required for allocation
2980 * returns the key for the extent through ins, and a tree buffer for
2981 * the first block of the extent through buf.
2982 *
2983 * returns 0 if everything worked, non-zero otherwise.
2984 */
2985int btrfs_alloc_extent(struct btrfs_trans_handle *trans,
2986 struct btrfs_root *root,
31840ae1 2987 u64 num_bytes, u64 parent, u64 min_alloc_size,
e6dcd2dc 2988 u64 root_objectid, u64 ref_generation,
3bb1a1bc 2989 u64 owner_objectid, u64 empty_size, u64 hint_byte,
e6dcd2dc
CM
2990 u64 search_end, struct btrfs_key *ins, u64 data)
2991{
2992 int ret;
e6dcd2dc
CM
2993 ret = __btrfs_reserve_extent(trans, root, num_bytes,
2994 min_alloc_size, empty_size, hint_byte,
2995 search_end, ins, data);
2996 BUG_ON(ret);
d00aff00 2997 if (root_objectid != BTRFS_TREE_LOG_OBJECTID) {
56bec294
CM
2998 ret = btrfs_add_delayed_ref(trans, ins->objectid,
2999 ins->offset, parent, root_objectid,
3000 ref_generation, owner_objectid,
3001 BTRFS_ADD_DELAYED_EXTENT, 0);
d00aff00 3002 BUG_ON(ret);
d00aff00 3003 }
56bec294 3004 update_reserved_extents(root, ins->objectid, ins->offset, 1);
925baedd 3005 return ret;
fec577fb 3006}
65b51a00
CM
3007
3008struct extent_buffer *btrfs_init_new_buffer(struct btrfs_trans_handle *trans,
3009 struct btrfs_root *root,
4008c04a
CM
3010 u64 bytenr, u32 blocksize,
3011 int level)
65b51a00
CM
3012{
3013 struct extent_buffer *buf;
3014
3015 buf = btrfs_find_create_tree_block(root, bytenr, blocksize);
3016 if (!buf)
3017 return ERR_PTR(-ENOMEM);
3018 btrfs_set_header_generation(buf, trans->transid);
4008c04a 3019 btrfs_set_buffer_lockdep_class(buf, level);
65b51a00
CM
3020 btrfs_tree_lock(buf);
3021 clean_tree_block(trans, root, buf);
b4ce94de
CM
3022
3023 btrfs_set_lock_blocking(buf);
65b51a00 3024 btrfs_set_buffer_uptodate(buf);
b4ce94de 3025
d0c803c4
CM
3026 if (root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID) {
3027 set_extent_dirty(&root->dirty_log_pages, buf->start,
3028 buf->start + buf->len - 1, GFP_NOFS);
3029 } else {
3030 set_extent_dirty(&trans->transaction->dirty_pages, buf->start,
65b51a00 3031 buf->start + buf->len - 1, GFP_NOFS);
d0c803c4 3032 }
65b51a00 3033 trans->blocks_used++;
b4ce94de 3034 /* this returns a buffer locked for blocking */
65b51a00
CM
3035 return buf;
3036}
3037
fec577fb
CM
3038/*
3039 * helper function to allocate a block for a given tree
3040 * returns the tree buffer or NULL.
3041 */
5f39d397 3042struct extent_buffer *btrfs_alloc_free_block(struct btrfs_trans_handle *trans,
7bb86316 3043 struct btrfs_root *root,
31840ae1 3044 u32 blocksize, u64 parent,
7bb86316
CM
3045 u64 root_objectid,
3046 u64 ref_generation,
7bb86316
CM
3047 int level,
3048 u64 hint,
5f39d397 3049 u64 empty_size)
fec577fb 3050{
e2fa7227 3051 struct btrfs_key ins;
fec577fb 3052 int ret;
5f39d397 3053 struct extent_buffer *buf;
fec577fb 3054
31840ae1 3055 ret = btrfs_alloc_extent(trans, root, blocksize, parent, blocksize,
3bb1a1bc 3056 root_objectid, ref_generation, level,
31840ae1 3057 empty_size, hint, (u64)-1, &ins, 0);
fec577fb 3058 if (ret) {
54aa1f4d
CM
3059 BUG_ON(ret > 0);
3060 return ERR_PTR(ret);
fec577fb 3061 }
55c69072 3062
4008c04a
CM
3063 buf = btrfs_init_new_buffer(trans, root, ins.objectid,
3064 blocksize, level);
fec577fb
CM
3065 return buf;
3066}
a28ec197 3067
e02119d5
CM
3068int btrfs_drop_leaf_ref(struct btrfs_trans_handle *trans,
3069 struct btrfs_root *root, struct extent_buffer *leaf)
6407bf6d 3070{
7bb86316
CM
3071 u64 leaf_owner;
3072 u64 leaf_generation;
bd56b302 3073 struct refsort *sorted;
5f39d397 3074 struct btrfs_key key;
6407bf6d
CM
3075 struct btrfs_file_extent_item *fi;
3076 int i;
3077 int nritems;
3078 int ret;
bd56b302
CM
3079 int refi = 0;
3080 int slot;
6407bf6d 3081
5f39d397
CM
3082 BUG_ON(!btrfs_is_leaf(leaf));
3083 nritems = btrfs_header_nritems(leaf);
7bb86316
CM
3084 leaf_owner = btrfs_header_owner(leaf);
3085 leaf_generation = btrfs_header_generation(leaf);
3086
bd56b302
CM
3087 sorted = kmalloc(sizeof(*sorted) * nritems, GFP_NOFS);
3088 /* we do this loop twice. The first time we build a list
3089 * of the extents we have a reference on, then we sort the list
3090 * by bytenr. The second time around we actually do the
3091 * extent freeing.
3092 */
6407bf6d 3093 for (i = 0; i < nritems; i++) {
db94535d 3094 u64 disk_bytenr;
e34a5b4f 3095 cond_resched();
5f39d397
CM
3096
3097 btrfs_item_key_to_cpu(leaf, &key, i);
bd56b302
CM
3098
3099 /* only extents have references, skip everything else */
5f39d397 3100 if (btrfs_key_type(&key) != BTRFS_EXTENT_DATA_KEY)
6407bf6d 3101 continue;
bd56b302 3102
6407bf6d 3103 fi = btrfs_item_ptr(leaf, i, struct btrfs_file_extent_item);
bd56b302
CM
3104
3105 /* inline extents live in the btree, they don't have refs */
5f39d397
CM
3106 if (btrfs_file_extent_type(leaf, fi) ==
3107 BTRFS_FILE_EXTENT_INLINE)
236454df 3108 continue;
bd56b302 3109
db94535d 3110 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
bd56b302
CM
3111
3112 /* holes don't have refs */
db94535d 3113 if (disk_bytenr == 0)
3a686375 3114 continue;
4a096752 3115
bd56b302
CM
3116 sorted[refi].bytenr = disk_bytenr;
3117 sorted[refi].slot = i;
3118 refi++;
3119 }
3120
3121 if (refi == 0)
3122 goto out;
3123
3124 sort(sorted, refi, sizeof(struct refsort), refsort_cmp, NULL);
3125
3126 for (i = 0; i < refi; i++) {
3127 u64 disk_bytenr;
3128
3129 disk_bytenr = sorted[i].bytenr;
3130 slot = sorted[i].slot;
3131
3132 cond_resched();
3133
3134 btrfs_item_key_to_cpu(leaf, &key, slot);
3135 if (btrfs_key_type(&key) != BTRFS_EXTENT_DATA_KEY)
3136 continue;
3137
3138 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
3139
56bec294 3140 ret = btrfs_free_extent(trans, root, disk_bytenr,
7bb86316 3141 btrfs_file_extent_disk_num_bytes(leaf, fi),
31840ae1 3142 leaf->start, leaf_owner, leaf_generation,
3bb1a1bc 3143 key.objectid, 0);
31840ae1 3144 BUG_ON(ret);
2dd3e67b
CM
3145
3146 atomic_inc(&root->fs_info->throttle_gen);
3147 wake_up(&root->fs_info->transaction_throttle);
3148 cond_resched();
6407bf6d 3149 }
bd56b302
CM
3150out:
3151 kfree(sorted);
6407bf6d
CM
3152 return 0;
3153}
3154
d397712b 3155static noinline int cache_drop_leaf_ref(struct btrfs_trans_handle *trans,
e02119d5
CM
3156 struct btrfs_root *root,
3157 struct btrfs_leaf_ref *ref)
31153d81
YZ
3158{
3159 int i;
3160 int ret;
bd56b302
CM
3161 struct btrfs_extent_info *info;
3162 struct refsort *sorted;
3163
3164 if (ref->nritems == 0)
3165 return 0;
31153d81 3166
bd56b302
CM
3167 sorted = kmalloc(sizeof(*sorted) * ref->nritems, GFP_NOFS);
3168 for (i = 0; i < ref->nritems; i++) {
3169 sorted[i].bytenr = ref->extents[i].bytenr;
3170 sorted[i].slot = i;
3171 }
3172 sort(sorted, ref->nritems, sizeof(struct refsort), refsort_cmp, NULL);
3173
3174 /*
3175 * the items in the ref were sorted when the ref was inserted
3176 * into the ref cache, so this is already in order
3177 */
31153d81 3178 for (i = 0; i < ref->nritems; i++) {
bd56b302 3179 info = ref->extents + sorted[i].slot;
56bec294 3180 ret = btrfs_free_extent(trans, root, info->bytenr,
31840ae1
ZY
3181 info->num_bytes, ref->bytenr,
3182 ref->owner, ref->generation,
3bb1a1bc 3183 info->objectid, 0);
2dd3e67b
CM
3184
3185 atomic_inc(&root->fs_info->throttle_gen);
3186 wake_up(&root->fs_info->transaction_throttle);
3187 cond_resched();
3188
31153d81
YZ
3189 BUG_ON(ret);
3190 info++;
3191 }
31153d81 3192
806638bc 3193 kfree(sorted);
31153d81
YZ
3194 return 0;
3195}
3196
56bec294
CM
3197static int drop_snap_lookup_refcount(struct btrfs_trans_handle *trans,
3198 struct btrfs_root *root, u64 start,
d397712b 3199 u64 len, u32 *refs)
333db94c 3200{
017e5369 3201 int ret;
f87f057b 3202
56bec294 3203 ret = btrfs_lookup_extent_ref(trans, root, start, len, refs);
f87f057b
CM
3204 BUG_ON(ret);
3205
d397712b 3206#if 0 /* some debugging code in case we see problems here */
f87f057b
CM
3207 /* if the refs count is one, it won't get increased again. But
3208 * if the ref count is > 1, someone may be decreasing it at
3209 * the same time we are.
3210 */
3211 if (*refs != 1) {
3212 struct extent_buffer *eb = NULL;
3213 eb = btrfs_find_create_tree_block(root, start, len);
3214 if (eb)
3215 btrfs_tree_lock(eb);
3216
3217 mutex_lock(&root->fs_info->alloc_mutex);
3218 ret = lookup_extent_ref(NULL, root, start, len, refs);
3219 BUG_ON(ret);
3220 mutex_unlock(&root->fs_info->alloc_mutex);
3221
3222 if (eb) {
3223 btrfs_tree_unlock(eb);
3224 free_extent_buffer(eb);
3225 }
3226 if (*refs == 1) {
d397712b
CM
3227 printk(KERN_ERR "btrfs block %llu went down to one "
3228 "during drop_snap\n", (unsigned long long)start);
f87f057b
CM
3229 }
3230
3231 }
3232#endif
3233
e7a84565 3234 cond_resched();
017e5369 3235 return ret;
333db94c
CM
3236}
3237
bd56b302
CM
3238/*
3239 * this is used while deleting old snapshots, and it drops the refs
3240 * on a whole subtree starting from a level 1 node.
3241 *
3242 * The idea is to sort all the leaf pointers, and then drop the
3243 * ref on all the leaves in order. Most of the time the leaves
3244 * will have ref cache entries, so no leaf IOs will be required to
3245 * find the extents they have references on.
3246 *
3247 * For each leaf, any references it has are also dropped in order
3248 *
3249 * This ends up dropping the references in something close to optimal
3250 * order for reading and modifying the extent allocation tree.
3251 */
3252static noinline int drop_level_one_refs(struct btrfs_trans_handle *trans,
3253 struct btrfs_root *root,
3254 struct btrfs_path *path)
3255{
3256 u64 bytenr;
3257 u64 root_owner;
3258 u64 root_gen;
3259 struct extent_buffer *eb = path->nodes[1];
3260 struct extent_buffer *leaf;
3261 struct btrfs_leaf_ref *ref;
3262 struct refsort *sorted = NULL;
3263 int nritems = btrfs_header_nritems(eb);
3264 int ret;
3265 int i;
3266 int refi = 0;
3267 int slot = path->slots[1];
3268 u32 blocksize = btrfs_level_size(root, 0);
3269 u32 refs;
3270
3271 if (nritems == 0)
3272 goto out;
3273
3274 root_owner = btrfs_header_owner(eb);
3275 root_gen = btrfs_header_generation(eb);
3276 sorted = kmalloc(sizeof(*sorted) * nritems, GFP_NOFS);
3277
3278 /*
3279 * step one, sort all the leaf pointers so we don't scribble
3280 * randomly into the extent allocation tree
3281 */
3282 for (i = slot; i < nritems; i++) {
3283 sorted[refi].bytenr = btrfs_node_blockptr(eb, i);
3284 sorted[refi].slot = i;
3285 refi++;
3286 }
3287
3288 /*
3289 * nritems won't be zero, but if we're picking up drop_snapshot
3290 * after a crash, slot might be > 0, so double check things
3291 * just in case.
3292 */
3293 if (refi == 0)
3294 goto out;
3295
3296 sort(sorted, refi, sizeof(struct refsort), refsort_cmp, NULL);
3297
3298 /*
3299 * the first loop frees everything the leaves point to
3300 */
3301 for (i = 0; i < refi; i++) {
3302 u64 ptr_gen;
3303
3304 bytenr = sorted[i].bytenr;
3305
3306 /*
3307 * check the reference count on this leaf. If it is > 1
3308 * we just decrement it below and don't update any
3309 * of the refs the leaf points to.
3310 */
56bec294
CM
3311 ret = drop_snap_lookup_refcount(trans, root, bytenr,
3312 blocksize, &refs);
bd56b302
CM
3313 BUG_ON(ret);
3314 if (refs != 1)
3315 continue;
3316
3317 ptr_gen = btrfs_node_ptr_generation(eb, sorted[i].slot);
3318
3319 /*
3320 * the leaf only had one reference, which means the
3321 * only thing pointing to this leaf is the snapshot
3322 * we're deleting. It isn't possible for the reference
3323 * count to increase again later
3324 *
3325 * The reference cache is checked for the leaf,
3326 * and if found we'll be able to drop any refs held by
3327 * the leaf without needing to read it in.
3328 */
3329 ref = btrfs_lookup_leaf_ref(root, bytenr);
3330 if (ref && ref->generation != ptr_gen) {
3331 btrfs_free_leaf_ref(root, ref);
3332 ref = NULL;
3333 }
3334 if (ref) {
3335 ret = cache_drop_leaf_ref(trans, root, ref);
3336 BUG_ON(ret);
3337 btrfs_remove_leaf_ref(root, ref);
3338 btrfs_free_leaf_ref(root, ref);
3339 } else {
3340 /*
3341 * the leaf wasn't in the reference cache, so
3342 * we have to read it.
3343 */
3344 leaf = read_tree_block(root, bytenr, blocksize,
3345 ptr_gen);
3346 ret = btrfs_drop_leaf_ref(trans, root, leaf);
3347 BUG_ON(ret);
3348 free_extent_buffer(leaf);
3349 }
3350 atomic_inc(&root->fs_info->throttle_gen);
3351 wake_up(&root->fs_info->transaction_throttle);
3352 cond_resched();
3353 }
3354
3355 /*
3356 * run through the loop again to free the refs on the leaves.
3357 * This is faster than doing it in the loop above because
3358 * the leaves are likely to be clustered together. We end up
3359 * working in nice chunks on the extent allocation tree.
3360 */
3361 for (i = 0; i < refi; i++) {
3362 bytenr = sorted[i].bytenr;
56bec294 3363 ret = btrfs_free_extent(trans, root, bytenr,
bd56b302
CM
3364 blocksize, eb->start,
3365 root_owner, root_gen, 0, 1);
3366 BUG_ON(ret);
3367
3368 atomic_inc(&root->fs_info->throttle_gen);
3369 wake_up(&root->fs_info->transaction_throttle);
3370 cond_resched();
3371 }
3372out:
3373 kfree(sorted);
3374
3375 /*
3376 * update the path to show we've processed the entire level 1
3377 * node. This will get saved into the root's drop_snapshot_progress
3378 * field so these drops are not repeated again if this transaction
3379 * commits.
3380 */
3381 path->slots[1] = nritems;
3382 return 0;
3383}
3384
9aca1d51
CM
3385/*
3386 * helper function for drop_snapshot, this walks down the tree dropping ref
3387 * counts as it goes.
3388 */
d397712b 3389static noinline int walk_down_tree(struct btrfs_trans_handle *trans,
98ed5174
CM
3390 struct btrfs_root *root,
3391 struct btrfs_path *path, int *level)
20524f02 3392{
7bb86316
CM
3393 u64 root_owner;
3394 u64 root_gen;
3395 u64 bytenr;
ca7a79ad 3396 u64 ptr_gen;
5f39d397
CM
3397 struct extent_buffer *next;
3398 struct extent_buffer *cur;
7bb86316 3399 struct extent_buffer *parent;
db94535d 3400 u32 blocksize;
20524f02
CM
3401 int ret;
3402 u32 refs;
3403
5caf2a00
CM
3404 WARN_ON(*level < 0);
3405 WARN_ON(*level >= BTRFS_MAX_LEVEL);
56bec294 3406 ret = drop_snap_lookup_refcount(trans, root, path->nodes[*level]->start,
db94535d 3407 path->nodes[*level]->len, &refs);
20524f02
CM
3408 BUG_ON(ret);
3409 if (refs > 1)
3410 goto out;
e011599b 3411
9aca1d51
CM
3412 /*
3413 * walk down to the last node level and free all the leaves
3414 */
d397712b 3415 while (*level >= 0) {
5caf2a00
CM
3416 WARN_ON(*level < 0);
3417 WARN_ON(*level >= BTRFS_MAX_LEVEL);
20524f02 3418 cur = path->nodes[*level];
e011599b 3419
5f39d397 3420 if (btrfs_header_level(cur) != *level)
2c90e5d6 3421 WARN_ON(1);
e011599b 3422
7518a238 3423 if (path->slots[*level] >=
5f39d397 3424 btrfs_header_nritems(cur))
20524f02 3425 break;
bd56b302
CM
3426
3427 /* the new code goes down to level 1 and does all the
3428 * leaves pointed to that node in bulk. So, this check
3429 * for level 0 will always be false.
3430 *
3431 * But, the disk format allows the drop_snapshot_progress
3432 * field in the root to leave things in a state where
3433 * a leaf will need cleaning up here. If someone crashes
3434 * with the old code and then boots with the new code,
3435 * we might find a leaf here.
3436 */
6407bf6d 3437 if (*level == 0) {
e02119d5 3438 ret = btrfs_drop_leaf_ref(trans, root, cur);
6407bf6d
CM
3439 BUG_ON(ret);
3440 break;
3441 }
bd56b302
CM
3442
3443 /*
3444 * once we get to level one, process the whole node
3445 * at once, including everything below it.
3446 */
3447 if (*level == 1) {
3448 ret = drop_level_one_refs(trans, root, path);
3449 BUG_ON(ret);
3450 break;
3451 }
3452
db94535d 3453 bytenr = btrfs_node_blockptr(cur, path->slots[*level]);
ca7a79ad 3454 ptr_gen = btrfs_node_ptr_generation(cur, path->slots[*level]);
db94535d 3455 blocksize = btrfs_level_size(root, *level - 1);
925baedd 3456
56bec294
CM
3457 ret = drop_snap_lookup_refcount(trans, root, bytenr,
3458 blocksize, &refs);
6407bf6d 3459 BUG_ON(ret);
bd56b302
CM
3460
3461 /*
3462 * if there is more than one reference, we don't need
3463 * to read that node to drop any references it has. We
3464 * just drop the ref we hold on that node and move on to the
3465 * next slot in this level.
3466 */
6407bf6d 3467 if (refs != 1) {
7bb86316
CM
3468 parent = path->nodes[*level];
3469 root_owner = btrfs_header_owner(parent);
3470 root_gen = btrfs_header_generation(parent);
20524f02 3471 path->slots[*level]++;
f87f057b 3472
56bec294 3473 ret = btrfs_free_extent(trans, root, bytenr,
31840ae1 3474 blocksize, parent->start,
3bb1a1bc
YZ
3475 root_owner, root_gen,
3476 *level - 1, 1);
20524f02 3477 BUG_ON(ret);
18e35e0a
CM
3478
3479 atomic_inc(&root->fs_info->throttle_gen);
3480 wake_up(&root->fs_info->transaction_throttle);
2dd3e67b 3481 cond_resched();
18e35e0a 3482
20524f02
CM
3483 continue;
3484 }
bd56b302 3485
f87f057b 3486 /*
bd56b302
CM
3487 * we need to keep freeing things in the next level down.
3488 * read the block and loop around to process it
f87f057b 3489 */
bd56b302 3490 next = read_tree_block(root, bytenr, blocksize, ptr_gen);
5caf2a00 3491 WARN_ON(*level <= 0);
83e15a28 3492 if (path->nodes[*level-1])
5f39d397 3493 free_extent_buffer(path->nodes[*level-1]);
20524f02 3494 path->nodes[*level-1] = next;
5f39d397 3495 *level = btrfs_header_level(next);
20524f02 3496 path->slots[*level] = 0;
2dd3e67b 3497 cond_resched();
20524f02
CM
3498 }
3499out:
5caf2a00
CM
3500 WARN_ON(*level < 0);
3501 WARN_ON(*level >= BTRFS_MAX_LEVEL);
7bb86316
CM
3502
3503 if (path->nodes[*level] == root->node) {
7bb86316 3504 parent = path->nodes[*level];
31153d81 3505 bytenr = path->nodes[*level]->start;
7bb86316
CM
3506 } else {
3507 parent = path->nodes[*level + 1];
31153d81 3508 bytenr = btrfs_node_blockptr(parent, path->slots[*level + 1]);
7bb86316
CM
3509 }
3510
31153d81
YZ
3511 blocksize = btrfs_level_size(root, *level);
3512 root_owner = btrfs_header_owner(parent);
7bb86316 3513 root_gen = btrfs_header_generation(parent);
31153d81 3514
bd56b302
CM
3515 /*
3516 * cleanup and free the reference on the last node
3517 * we processed
3518 */
56bec294 3519 ret = btrfs_free_extent(trans, root, bytenr, blocksize,
31840ae1 3520 parent->start, root_owner, root_gen,
3bb1a1bc 3521 *level, 1);
5f39d397 3522 free_extent_buffer(path->nodes[*level]);
20524f02 3523 path->nodes[*level] = NULL;
bd56b302 3524
20524f02
CM
3525 *level += 1;
3526 BUG_ON(ret);
f87f057b 3527
e7a84565 3528 cond_resched();
20524f02
CM
3529 return 0;
3530}
3531
f82d02d9
YZ
3532/*
3533 * helper function for drop_subtree, this function is similar to
3534 * walk_down_tree. The main difference is that it checks reference
3535 * counts while tree blocks are locked.
3536 */
d397712b 3537static noinline int walk_down_subtree(struct btrfs_trans_handle *trans,
f82d02d9
YZ
3538 struct btrfs_root *root,
3539 struct btrfs_path *path, int *level)
3540{
3541 struct extent_buffer *next;
3542 struct extent_buffer *cur;
3543 struct extent_buffer *parent;
3544 u64 bytenr;
3545 u64 ptr_gen;
3546 u32 blocksize;
3547 u32 refs;
3548 int ret;
3549
3550 cur = path->nodes[*level];
3551 ret = btrfs_lookup_extent_ref(trans, root, cur->start, cur->len,
3552 &refs);
3553 BUG_ON(ret);
3554 if (refs > 1)
3555 goto out;
3556
3557 while (*level >= 0) {
3558 cur = path->nodes[*level];
3559 if (*level == 0) {
3560 ret = btrfs_drop_leaf_ref(trans, root, cur);
3561 BUG_ON(ret);
3562 clean_tree_block(trans, root, cur);
3563 break;
3564 }
3565 if (path->slots[*level] >= btrfs_header_nritems(cur)) {
3566 clean_tree_block(trans, root, cur);
3567 break;
3568 }
3569
3570 bytenr = btrfs_node_blockptr(cur, path->slots[*level]);
3571 blocksize = btrfs_level_size(root, *level - 1);
3572 ptr_gen = btrfs_node_ptr_generation(cur, path->slots[*level]);
3573
3574 next = read_tree_block(root, bytenr, blocksize, ptr_gen);
3575 btrfs_tree_lock(next);
b4ce94de 3576 btrfs_set_lock_blocking(next);
f82d02d9
YZ
3577
3578 ret = btrfs_lookup_extent_ref(trans, root, bytenr, blocksize,
3579 &refs);
3580 BUG_ON(ret);
3581 if (refs > 1) {
3582 parent = path->nodes[*level];
3583 ret = btrfs_free_extent(trans, root, bytenr,
3584 blocksize, parent->start,
3585 btrfs_header_owner(parent),
3586 btrfs_header_generation(parent),
3587 *level - 1, 1);
3588 BUG_ON(ret);
3589 path->slots[*level]++;
3590 btrfs_tree_unlock(next);
3591 free_extent_buffer(next);
3592 continue;
3593 }
3594
3595 *level = btrfs_header_level(next);
3596 path->nodes[*level] = next;
3597 path->slots[*level] = 0;
3598 path->locks[*level] = 1;
3599 cond_resched();
3600 }
3601out:
3602 parent = path->nodes[*level + 1];
3603 bytenr = path->nodes[*level]->start;
3604 blocksize = path->nodes[*level]->len;
3605
3606 ret = btrfs_free_extent(trans, root, bytenr, blocksize,
3607 parent->start, btrfs_header_owner(parent),
3608 btrfs_header_generation(parent), *level, 1);
3609 BUG_ON(ret);
3610
3611 if (path->locks[*level]) {
3612 btrfs_tree_unlock(path->nodes[*level]);
3613 path->locks[*level] = 0;
3614 }
3615 free_extent_buffer(path->nodes[*level]);
3616 path->nodes[*level] = NULL;
3617 *level += 1;
3618 cond_resched();
3619 return 0;
3620}
3621
9aca1d51
CM
3622/*
3623 * helper for dropping snapshots. This walks back up the tree in the path
3624 * to find the first node higher up where we haven't yet gone through
3625 * all the slots
3626 */
d397712b 3627static noinline int walk_up_tree(struct btrfs_trans_handle *trans,
98ed5174 3628 struct btrfs_root *root,
f82d02d9
YZ
3629 struct btrfs_path *path,
3630 int *level, int max_level)
20524f02 3631{
7bb86316
CM
3632 u64 root_owner;
3633 u64 root_gen;
3634 struct btrfs_root_item *root_item = &root->root_item;
20524f02
CM
3635 int i;
3636 int slot;
3637 int ret;
9f3a7427 3638
f82d02d9 3639 for (i = *level; i < max_level && path->nodes[i]; i++) {
20524f02 3640 slot = path->slots[i];
5f39d397
CM
3641 if (slot < btrfs_header_nritems(path->nodes[i]) - 1) {
3642 struct extent_buffer *node;
3643 struct btrfs_disk_key disk_key;
bd56b302
CM
3644
3645 /*
3646 * there is more work to do in this level.
3647 * Update the drop_progress marker to reflect
3648 * the work we've done so far, and then bump
3649 * the slot number
3650 */
5f39d397 3651 node = path->nodes[i];
20524f02
CM
3652 path->slots[i]++;
3653 *level = i;
9f3a7427 3654 WARN_ON(*level == 0);
5f39d397 3655 btrfs_node_key(node, &disk_key, path->slots[i]);
9f3a7427 3656 memcpy(&root_item->drop_progress,
5f39d397 3657 &disk_key, sizeof(disk_key));
9f3a7427 3658 root_item->drop_level = i;
20524f02
CM
3659 return 0;
3660 } else {
31840ae1 3661 struct extent_buffer *parent;
bd56b302
CM
3662
3663 /*
3664 * this whole node is done, free our reference
3665 * on it and go up one level
3666 */
31840ae1
ZY
3667 if (path->nodes[*level] == root->node)
3668 parent = path->nodes[*level];
3669 else
3670 parent = path->nodes[*level + 1];
3671
3672 root_owner = btrfs_header_owner(parent);
3673 root_gen = btrfs_header_generation(parent);
f82d02d9
YZ
3674
3675 clean_tree_block(trans, root, path->nodes[*level]);
e089f05c 3676 ret = btrfs_free_extent(trans, root,
db94535d 3677 path->nodes[*level]->start,
7bb86316 3678 path->nodes[*level]->len,
3bb1a1bc
YZ
3679 parent->start, root_owner,
3680 root_gen, *level, 1);
6407bf6d 3681 BUG_ON(ret);
f82d02d9
YZ
3682 if (path->locks[*level]) {
3683 btrfs_tree_unlock(path->nodes[*level]);
3684 path->locks[*level] = 0;
3685 }
5f39d397 3686 free_extent_buffer(path->nodes[*level]);
83e15a28 3687 path->nodes[*level] = NULL;
20524f02 3688 *level = i + 1;
20524f02
CM
3689 }
3690 }
3691 return 1;
3692}
3693
9aca1d51
CM
3694/*
3695 * drop the reference count on the tree rooted at 'snap'. This traverses
3696 * the tree freeing any blocks that have a ref count of zero after being
3697 * decremented.
3698 */
e089f05c 3699int btrfs_drop_snapshot(struct btrfs_trans_handle *trans, struct btrfs_root
9f3a7427 3700 *root)
20524f02 3701{
3768f368 3702 int ret = 0;
9aca1d51 3703 int wret;
20524f02 3704 int level;
5caf2a00 3705 struct btrfs_path *path;
20524f02
CM
3706 int i;
3707 int orig_level;
9f3a7427 3708 struct btrfs_root_item *root_item = &root->root_item;
20524f02 3709
a2135011 3710 WARN_ON(!mutex_is_locked(&root->fs_info->drop_mutex));
5caf2a00
CM
3711 path = btrfs_alloc_path();
3712 BUG_ON(!path);
20524f02 3713
5f39d397 3714 level = btrfs_header_level(root->node);
20524f02 3715 orig_level = level;
9f3a7427
CM
3716 if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
3717 path->nodes[level] = root->node;
f510cfec 3718 extent_buffer_get(root->node);
9f3a7427
CM
3719 path->slots[level] = 0;
3720 } else {
3721 struct btrfs_key key;
5f39d397
CM
3722 struct btrfs_disk_key found_key;
3723 struct extent_buffer *node;
6702ed49 3724
9f3a7427 3725 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
6702ed49
CM
3726 level = root_item->drop_level;
3727 path->lowest_level = level;
9f3a7427 3728 wret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6702ed49 3729 if (wret < 0) {
9f3a7427
CM
3730 ret = wret;
3731 goto out;
3732 }
5f39d397
CM
3733 node = path->nodes[level];
3734 btrfs_node_key(node, &found_key, path->slots[level]);
3735 WARN_ON(memcmp(&found_key, &root_item->drop_progress,
3736 sizeof(found_key)));
7d9eb12c
CM
3737 /*
3738 * unlock our path, this is safe because only this
3739 * function is allowed to delete this snapshot
3740 */
925baedd
CM
3741 for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
3742 if (path->nodes[i] && path->locks[i]) {
3743 path->locks[i] = 0;
3744 btrfs_tree_unlock(path->nodes[i]);
3745 }
3746 }
9f3a7427 3747 }
d397712b 3748 while (1) {
5caf2a00 3749 wret = walk_down_tree(trans, root, path, &level);
9aca1d51 3750 if (wret > 0)
20524f02 3751 break;
9aca1d51
CM
3752 if (wret < 0)
3753 ret = wret;
3754
f82d02d9
YZ
3755 wret = walk_up_tree(trans, root, path, &level,
3756 BTRFS_MAX_LEVEL);
9aca1d51 3757 if (wret > 0)
20524f02 3758 break;
9aca1d51
CM
3759 if (wret < 0)
3760 ret = wret;
e7a84565
CM
3761 if (trans->transaction->in_commit) {
3762 ret = -EAGAIN;
3763 break;
3764 }
18e35e0a 3765 atomic_inc(&root->fs_info->throttle_gen);
017e5369 3766 wake_up(&root->fs_info->transaction_throttle);
20524f02 3767 }
83e15a28 3768 for (i = 0; i <= orig_level; i++) {
5caf2a00 3769 if (path->nodes[i]) {
5f39d397 3770 free_extent_buffer(path->nodes[i]);
0f82731f 3771 path->nodes[i] = NULL;
83e15a28 3772 }
20524f02 3773 }
9f3a7427 3774out:
5caf2a00 3775 btrfs_free_path(path);
9aca1d51 3776 return ret;
20524f02 3777}
9078a3e1 3778
f82d02d9
YZ
3779int btrfs_drop_subtree(struct btrfs_trans_handle *trans,
3780 struct btrfs_root *root,
3781 struct extent_buffer *node,
3782 struct extent_buffer *parent)
3783{
3784 struct btrfs_path *path;
3785 int level;
3786 int parent_level;
3787 int ret = 0;
3788 int wret;
3789
3790 path = btrfs_alloc_path();
3791 BUG_ON(!path);
3792
b9447ef8 3793 btrfs_assert_tree_locked(parent);
f82d02d9
YZ
3794 parent_level = btrfs_header_level(parent);
3795 extent_buffer_get(parent);
3796 path->nodes[parent_level] = parent;
3797 path->slots[parent_level] = btrfs_header_nritems(parent);
3798
b9447ef8 3799 btrfs_assert_tree_locked(node);
f82d02d9
YZ
3800 level = btrfs_header_level(node);
3801 extent_buffer_get(node);
3802 path->nodes[level] = node;
3803 path->slots[level] = 0;
3804
3805 while (1) {
3806 wret = walk_down_subtree(trans, root, path, &level);
3807 if (wret < 0)
3808 ret = wret;
3809 if (wret != 0)
3810 break;
3811
3812 wret = walk_up_tree(trans, root, path, &level, parent_level);
3813 if (wret < 0)
3814 ret = wret;
3815 if (wret != 0)
3816 break;
3817 }
3818
3819 btrfs_free_path(path);
3820 return ret;
3821}
3822
8e7bf94f
CM
3823static unsigned long calc_ra(unsigned long start, unsigned long last,
3824 unsigned long nr)
3825{
3826 return min(last, start + nr - 1);
3827}
3828
d397712b 3829static noinline int relocate_inode_pages(struct inode *inode, u64 start,
98ed5174 3830 u64 len)
edbd8d4e
CM
3831{
3832 u64 page_start;
3833 u64 page_end;
1a40e23b 3834 unsigned long first_index;
edbd8d4e 3835 unsigned long last_index;
edbd8d4e
CM
3836 unsigned long i;
3837 struct page *page;
d1310b2e 3838 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4313b399 3839 struct file_ra_state *ra;
3eaa2885 3840 struct btrfs_ordered_extent *ordered;
1a40e23b
ZY
3841 unsigned int total_read = 0;
3842 unsigned int total_dirty = 0;
3843 int ret = 0;
4313b399
CM
3844
3845 ra = kzalloc(sizeof(*ra), GFP_NOFS);
edbd8d4e
CM
3846
3847 mutex_lock(&inode->i_mutex);
1a40e23b 3848 first_index = start >> PAGE_CACHE_SHIFT;
edbd8d4e
CM
3849 last_index = (start + len - 1) >> PAGE_CACHE_SHIFT;
3850
1a40e23b
ZY
3851 /* make sure the dirty trick played by the caller work */
3852 ret = invalidate_inode_pages2_range(inode->i_mapping,
3853 first_index, last_index);
3854 if (ret)
3855 goto out_unlock;
8e7bf94f 3856
4313b399 3857 file_ra_state_init(ra, inode->i_mapping);
edbd8d4e 3858
1a40e23b
ZY
3859 for (i = first_index ; i <= last_index; i++) {
3860 if (total_read % ra->ra_pages == 0) {
8e7bf94f 3861 btrfs_force_ra(inode->i_mapping, ra, NULL, i,
1a40e23b 3862 calc_ra(i, last_index, ra->ra_pages));
8e7bf94f
CM
3863 }
3864 total_read++;
3eaa2885
CM
3865again:
3866 if (((u64)i << PAGE_CACHE_SHIFT) > i_size_read(inode))
1a40e23b 3867 BUG_ON(1);
edbd8d4e 3868 page = grab_cache_page(inode->i_mapping, i);
a061fc8d 3869 if (!page) {
1a40e23b 3870 ret = -ENOMEM;
edbd8d4e 3871 goto out_unlock;
a061fc8d 3872 }
edbd8d4e
CM
3873 if (!PageUptodate(page)) {
3874 btrfs_readpage(NULL, page);
3875 lock_page(page);
3876 if (!PageUptodate(page)) {
3877 unlock_page(page);
3878 page_cache_release(page);
1a40e23b 3879 ret = -EIO;
edbd8d4e
CM
3880 goto out_unlock;
3881 }
3882 }
ec44a35c 3883 wait_on_page_writeback(page);
3eaa2885 3884
edbd8d4e
CM
3885 page_start = (u64)page->index << PAGE_CACHE_SHIFT;
3886 page_end = page_start + PAGE_CACHE_SIZE - 1;
d1310b2e 3887 lock_extent(io_tree, page_start, page_end, GFP_NOFS);
edbd8d4e 3888
3eaa2885
CM
3889 ordered = btrfs_lookup_ordered_extent(inode, page_start);
3890 if (ordered) {
3891 unlock_extent(io_tree, page_start, page_end, GFP_NOFS);
3892 unlock_page(page);
3893 page_cache_release(page);
3894 btrfs_start_ordered_extent(inode, ordered, 1);
3895 btrfs_put_ordered_extent(ordered);
3896 goto again;
3897 }
3898 set_page_extent_mapped(page);
3899
1a40e23b
ZY
3900 if (i == first_index)
3901 set_extent_bits(io_tree, page_start, page_end,
3902 EXTENT_BOUNDARY, GFP_NOFS);
1f80e4db 3903 btrfs_set_extent_delalloc(inode, page_start, page_end);
1a40e23b 3904
a061fc8d 3905 set_page_dirty(page);
1a40e23b 3906 total_dirty++;
edbd8d4e 3907
d1310b2e 3908 unlock_extent(io_tree, page_start, page_end, GFP_NOFS);
edbd8d4e
CM
3909 unlock_page(page);
3910 page_cache_release(page);
3911 }
3912
3913out_unlock:
ec44a35c 3914 kfree(ra);
edbd8d4e 3915 mutex_unlock(&inode->i_mutex);
1a40e23b
ZY
3916 balance_dirty_pages_ratelimited_nr(inode->i_mapping, total_dirty);
3917 return ret;
edbd8d4e
CM
3918}
3919
d397712b 3920static noinline int relocate_data_extent(struct inode *reloc_inode,
1a40e23b
ZY
3921 struct btrfs_key *extent_key,
3922 u64 offset)
3923{
3924 struct btrfs_root *root = BTRFS_I(reloc_inode)->root;
3925 struct extent_map_tree *em_tree = &BTRFS_I(reloc_inode)->extent_tree;
3926 struct extent_map *em;
6643558d
YZ
3927 u64 start = extent_key->objectid - offset;
3928 u64 end = start + extent_key->offset - 1;
bf4ef679 3929
1a40e23b
ZY
3930 em = alloc_extent_map(GFP_NOFS);
3931 BUG_ON(!em || IS_ERR(em));
bf4ef679 3932
6643558d 3933 em->start = start;
1a40e23b 3934 em->len = extent_key->offset;
c8b97818 3935 em->block_len = extent_key->offset;
1a40e23b
ZY
3936 em->block_start = extent_key->objectid;
3937 em->bdev = root->fs_info->fs_devices->latest_bdev;
3938 set_bit(EXTENT_FLAG_PINNED, &em->flags);
3939
3940 /* setup extent map to cheat btrfs_readpage */
6643558d 3941 lock_extent(&BTRFS_I(reloc_inode)->io_tree, start, end, GFP_NOFS);
1a40e23b
ZY
3942 while (1) {
3943 int ret;
3944 spin_lock(&em_tree->lock);
3945 ret = add_extent_mapping(em_tree, em);
3946 spin_unlock(&em_tree->lock);
3947 if (ret != -EEXIST) {
3948 free_extent_map(em);
bf4ef679
CM
3949 break;
3950 }
6643558d 3951 btrfs_drop_extent_cache(reloc_inode, start, end, 0);
bf4ef679 3952 }
6643558d 3953 unlock_extent(&BTRFS_I(reloc_inode)->io_tree, start, end, GFP_NOFS);
bf4ef679 3954
6643558d 3955 return relocate_inode_pages(reloc_inode, start, extent_key->offset);
1a40e23b 3956}
edbd8d4e 3957
1a40e23b
ZY
3958struct btrfs_ref_path {
3959 u64 extent_start;
3960 u64 nodes[BTRFS_MAX_LEVEL];
3961 u64 root_objectid;
3962 u64 root_generation;
3963 u64 owner_objectid;
1a40e23b
ZY
3964 u32 num_refs;
3965 int lowest_level;
3966 int current_level;
f82d02d9
YZ
3967 int shared_level;
3968
3969 struct btrfs_key node_keys[BTRFS_MAX_LEVEL];
3970 u64 new_nodes[BTRFS_MAX_LEVEL];
1a40e23b 3971};
7d9eb12c 3972
1a40e23b 3973struct disk_extent {
c8b97818 3974 u64 ram_bytes;
1a40e23b
ZY
3975 u64 disk_bytenr;
3976 u64 disk_num_bytes;
3977 u64 offset;
3978 u64 num_bytes;
c8b97818
CM
3979 u8 compression;
3980 u8 encryption;
3981 u16 other_encoding;
1a40e23b 3982};
4313b399 3983
1a40e23b
ZY
3984static int is_cowonly_root(u64 root_objectid)
3985{
3986 if (root_objectid == BTRFS_ROOT_TREE_OBJECTID ||
3987 root_objectid == BTRFS_EXTENT_TREE_OBJECTID ||
3988 root_objectid == BTRFS_CHUNK_TREE_OBJECTID ||
3989 root_objectid == BTRFS_DEV_TREE_OBJECTID ||
0403e47e
YZ
3990 root_objectid == BTRFS_TREE_LOG_OBJECTID ||
3991 root_objectid == BTRFS_CSUM_TREE_OBJECTID)
1a40e23b
ZY
3992 return 1;
3993 return 0;
3994}
edbd8d4e 3995
d397712b 3996static noinline int __next_ref_path(struct btrfs_trans_handle *trans,
1a40e23b
ZY
3997 struct btrfs_root *extent_root,
3998 struct btrfs_ref_path *ref_path,
3999 int first_time)
4000{
4001 struct extent_buffer *leaf;
4002 struct btrfs_path *path;
4003 struct btrfs_extent_ref *ref;
4004 struct btrfs_key key;
4005 struct btrfs_key found_key;
4006 u64 bytenr;
4007 u32 nritems;
4008 int level;
4009 int ret = 1;
edbd8d4e 4010
1a40e23b
ZY
4011 path = btrfs_alloc_path();
4012 if (!path)
4013 return -ENOMEM;
bf4ef679 4014
1a40e23b
ZY
4015 if (first_time) {
4016 ref_path->lowest_level = -1;
4017 ref_path->current_level = -1;
f82d02d9 4018 ref_path->shared_level = -1;
1a40e23b
ZY
4019 goto walk_up;
4020 }
4021walk_down:
4022 level = ref_path->current_level - 1;
4023 while (level >= -1) {
4024 u64 parent;
4025 if (level < ref_path->lowest_level)
4026 break;
bf4ef679 4027
d397712b 4028 if (level >= 0)
1a40e23b 4029 bytenr = ref_path->nodes[level];
d397712b 4030 else
1a40e23b 4031 bytenr = ref_path->extent_start;
1a40e23b 4032 BUG_ON(bytenr == 0);
bf4ef679 4033
1a40e23b
ZY
4034 parent = ref_path->nodes[level + 1];
4035 ref_path->nodes[level + 1] = 0;
4036 ref_path->current_level = level;
4037 BUG_ON(parent == 0);
0ef3e66b 4038
1a40e23b
ZY
4039 key.objectid = bytenr;
4040 key.offset = parent + 1;
4041 key.type = BTRFS_EXTENT_REF_KEY;
edbd8d4e 4042
1a40e23b
ZY
4043 ret = btrfs_search_slot(trans, extent_root, &key, path, 0, 0);
4044 if (ret < 0)
edbd8d4e 4045 goto out;
1a40e23b 4046 BUG_ON(ret == 0);
7d9eb12c 4047
1a40e23b
ZY
4048 leaf = path->nodes[0];
4049 nritems = btrfs_header_nritems(leaf);
4050 if (path->slots[0] >= nritems) {
4051 ret = btrfs_next_leaf(extent_root, path);
4052 if (ret < 0)
4053 goto out;
4054 if (ret > 0)
4055 goto next;
4056 leaf = path->nodes[0];
4057 }
0ef3e66b 4058
1a40e23b
ZY
4059 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4060 if (found_key.objectid == bytenr &&
f82d02d9
YZ
4061 found_key.type == BTRFS_EXTENT_REF_KEY) {
4062 if (level < ref_path->shared_level)
4063 ref_path->shared_level = level;
1a40e23b 4064 goto found;
f82d02d9 4065 }
1a40e23b
ZY
4066next:
4067 level--;
4068 btrfs_release_path(extent_root, path);
d899e052 4069 cond_resched();
1a40e23b
ZY
4070 }
4071 /* reached lowest level */
4072 ret = 1;
4073 goto out;
4074walk_up:
4075 level = ref_path->current_level;
4076 while (level < BTRFS_MAX_LEVEL - 1) {
4077 u64 ref_objectid;
d397712b
CM
4078
4079 if (level >= 0)
1a40e23b 4080 bytenr = ref_path->nodes[level];
d397712b 4081 else
1a40e23b 4082 bytenr = ref_path->extent_start;
d397712b 4083
1a40e23b 4084 BUG_ON(bytenr == 0);
edbd8d4e 4085
1a40e23b
ZY
4086 key.objectid = bytenr;
4087 key.offset = 0;
4088 key.type = BTRFS_EXTENT_REF_KEY;
edbd8d4e 4089
1a40e23b
ZY
4090 ret = btrfs_search_slot(trans, extent_root, &key, path, 0, 0);
4091 if (ret < 0)
4092 goto out;
edbd8d4e 4093
1a40e23b
ZY
4094 leaf = path->nodes[0];
4095 nritems = btrfs_header_nritems(leaf);
4096 if (path->slots[0] >= nritems) {
4097 ret = btrfs_next_leaf(extent_root, path);
4098 if (ret < 0)
4099 goto out;
4100 if (ret > 0) {
4101 /* the extent was freed by someone */
4102 if (ref_path->lowest_level == level)
4103 goto out;
4104 btrfs_release_path(extent_root, path);
4105 goto walk_down;
4106 }
4107 leaf = path->nodes[0];
4108 }
edbd8d4e 4109
1a40e23b
ZY
4110 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4111 if (found_key.objectid != bytenr ||
4112 found_key.type != BTRFS_EXTENT_REF_KEY) {
4113 /* the extent was freed by someone */
4114 if (ref_path->lowest_level == level) {
4115 ret = 1;
4116 goto out;
4117 }
4118 btrfs_release_path(extent_root, path);
4119 goto walk_down;
4120 }
4121found:
4122 ref = btrfs_item_ptr(leaf, path->slots[0],
4123 struct btrfs_extent_ref);
4124 ref_objectid = btrfs_ref_objectid(leaf, ref);
4125 if (ref_objectid < BTRFS_FIRST_FREE_OBJECTID) {
4126 if (first_time) {
4127 level = (int)ref_objectid;
4128 BUG_ON(level >= BTRFS_MAX_LEVEL);
4129 ref_path->lowest_level = level;
4130 ref_path->current_level = level;
4131 ref_path->nodes[level] = bytenr;
4132 } else {
4133 WARN_ON(ref_objectid != level);
4134 }
4135 } else {
4136 WARN_ON(level != -1);
4137 }
4138 first_time = 0;
bf4ef679 4139
1a40e23b
ZY
4140 if (ref_path->lowest_level == level) {
4141 ref_path->owner_objectid = ref_objectid;
1a40e23b
ZY
4142 ref_path->num_refs = btrfs_ref_num_refs(leaf, ref);
4143 }
bf4ef679 4144
7d9eb12c 4145 /*
1a40e23b
ZY
4146 * the block is tree root or the block isn't in reference
4147 * counted tree.
7d9eb12c 4148 */
1a40e23b
ZY
4149 if (found_key.objectid == found_key.offset ||
4150 is_cowonly_root(btrfs_ref_root(leaf, ref))) {
4151 ref_path->root_objectid = btrfs_ref_root(leaf, ref);
4152 ref_path->root_generation =
4153 btrfs_ref_generation(leaf, ref);
4154 if (level < 0) {
4155 /* special reference from the tree log */
4156 ref_path->nodes[0] = found_key.offset;
4157 ref_path->current_level = 0;
4158 }
4159 ret = 0;
4160 goto out;
4161 }
7d9eb12c 4162
1a40e23b
ZY
4163 level++;
4164 BUG_ON(ref_path->nodes[level] != 0);
4165 ref_path->nodes[level] = found_key.offset;
4166 ref_path->current_level = level;
bf4ef679 4167
1a40e23b
ZY
4168 /*
4169 * the reference was created in the running transaction,
4170 * no need to continue walking up.
4171 */
4172 if (btrfs_ref_generation(leaf, ref) == trans->transid) {
4173 ref_path->root_objectid = btrfs_ref_root(leaf, ref);
4174 ref_path->root_generation =
4175 btrfs_ref_generation(leaf, ref);
4176 ret = 0;
4177 goto out;
7d9eb12c
CM
4178 }
4179
1a40e23b 4180 btrfs_release_path(extent_root, path);
d899e052 4181 cond_resched();
7d9eb12c 4182 }
1a40e23b
ZY
4183 /* reached max tree level, but no tree root found. */
4184 BUG();
edbd8d4e 4185out:
1a40e23b
ZY
4186 btrfs_free_path(path);
4187 return ret;
edbd8d4e
CM
4188}
4189
1a40e23b
ZY
4190static int btrfs_first_ref_path(struct btrfs_trans_handle *trans,
4191 struct btrfs_root *extent_root,
4192 struct btrfs_ref_path *ref_path,
4193 u64 extent_start)
a061fc8d 4194{
1a40e23b
ZY
4195 memset(ref_path, 0, sizeof(*ref_path));
4196 ref_path->extent_start = extent_start;
a061fc8d 4197
1a40e23b 4198 return __next_ref_path(trans, extent_root, ref_path, 1);
a061fc8d
CM
4199}
4200
1a40e23b
ZY
4201static int btrfs_next_ref_path(struct btrfs_trans_handle *trans,
4202 struct btrfs_root *extent_root,
4203 struct btrfs_ref_path *ref_path)
edbd8d4e 4204{
1a40e23b
ZY
4205 return __next_ref_path(trans, extent_root, ref_path, 0);
4206}
4207
d397712b 4208static noinline int get_new_locations(struct inode *reloc_inode,
1a40e23b
ZY
4209 struct btrfs_key *extent_key,
4210 u64 offset, int no_fragment,
4211 struct disk_extent **extents,
4212 int *nr_extents)
4213{
4214 struct btrfs_root *root = BTRFS_I(reloc_inode)->root;
4215 struct btrfs_path *path;
4216 struct btrfs_file_extent_item *fi;
edbd8d4e 4217 struct extent_buffer *leaf;
1a40e23b
ZY
4218 struct disk_extent *exts = *extents;
4219 struct btrfs_key found_key;
4220 u64 cur_pos;
4221 u64 last_byte;
edbd8d4e 4222 u32 nritems;
1a40e23b
ZY
4223 int nr = 0;
4224 int max = *nr_extents;
4225 int ret;
edbd8d4e 4226
1a40e23b
ZY
4227 WARN_ON(!no_fragment && *extents);
4228 if (!exts) {
4229 max = 1;
4230 exts = kmalloc(sizeof(*exts) * max, GFP_NOFS);
4231 if (!exts)
4232 return -ENOMEM;
a061fc8d 4233 }
edbd8d4e 4234
1a40e23b
ZY
4235 path = btrfs_alloc_path();
4236 BUG_ON(!path);
edbd8d4e 4237
1a40e23b
ZY
4238 cur_pos = extent_key->objectid - offset;
4239 last_byte = extent_key->objectid + extent_key->offset;
4240 ret = btrfs_lookup_file_extent(NULL, root, path, reloc_inode->i_ino,
4241 cur_pos, 0);
4242 if (ret < 0)
4243 goto out;
4244 if (ret > 0) {
4245 ret = -ENOENT;
4246 goto out;
4247 }
edbd8d4e 4248
1a40e23b 4249 while (1) {
edbd8d4e
CM
4250 leaf = path->nodes[0];
4251 nritems = btrfs_header_nritems(leaf);
1a40e23b
ZY
4252 if (path->slots[0] >= nritems) {
4253 ret = btrfs_next_leaf(root, path);
a061fc8d
CM
4254 if (ret < 0)
4255 goto out;
1a40e23b
ZY
4256 if (ret > 0)
4257 break;
bf4ef679 4258 leaf = path->nodes[0];
a061fc8d 4259 }
edbd8d4e
CM
4260
4261 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1a40e23b
ZY
4262 if (found_key.offset != cur_pos ||
4263 found_key.type != BTRFS_EXTENT_DATA_KEY ||
4264 found_key.objectid != reloc_inode->i_ino)
edbd8d4e
CM
4265 break;
4266
1a40e23b
ZY
4267 fi = btrfs_item_ptr(leaf, path->slots[0],
4268 struct btrfs_file_extent_item);
4269 if (btrfs_file_extent_type(leaf, fi) !=
4270 BTRFS_FILE_EXTENT_REG ||
4271 btrfs_file_extent_disk_bytenr(leaf, fi) == 0)
edbd8d4e 4272 break;
1a40e23b
ZY
4273
4274 if (nr == max) {
4275 struct disk_extent *old = exts;
4276 max *= 2;
4277 exts = kzalloc(sizeof(*exts) * max, GFP_NOFS);
4278 memcpy(exts, old, sizeof(*exts) * nr);
4279 if (old != *extents)
4280 kfree(old);
a061fc8d 4281 }
edbd8d4e 4282
1a40e23b
ZY
4283 exts[nr].disk_bytenr =
4284 btrfs_file_extent_disk_bytenr(leaf, fi);
4285 exts[nr].disk_num_bytes =
4286 btrfs_file_extent_disk_num_bytes(leaf, fi);
4287 exts[nr].offset = btrfs_file_extent_offset(leaf, fi);
4288 exts[nr].num_bytes = btrfs_file_extent_num_bytes(leaf, fi);
c8b97818
CM
4289 exts[nr].ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
4290 exts[nr].compression = btrfs_file_extent_compression(leaf, fi);
4291 exts[nr].encryption = btrfs_file_extent_encryption(leaf, fi);
4292 exts[nr].other_encoding = btrfs_file_extent_other_encoding(leaf,
4293 fi);
d899e052
YZ
4294 BUG_ON(exts[nr].offset > 0);
4295 BUG_ON(exts[nr].compression || exts[nr].encryption);
4296 BUG_ON(exts[nr].num_bytes != exts[nr].disk_num_bytes);
edbd8d4e 4297
1a40e23b
ZY
4298 cur_pos += exts[nr].num_bytes;
4299 nr++;
4300
4301 if (cur_pos + offset >= last_byte)
4302 break;
4303
4304 if (no_fragment) {
4305 ret = 1;
edbd8d4e 4306 goto out;
1a40e23b
ZY
4307 }
4308 path->slots[0]++;
4309 }
4310
1f80e4db 4311 BUG_ON(cur_pos + offset > last_byte);
1a40e23b
ZY
4312 if (cur_pos + offset < last_byte) {
4313 ret = -ENOENT;
4314 goto out;
edbd8d4e
CM
4315 }
4316 ret = 0;
4317out:
1a40e23b
ZY
4318 btrfs_free_path(path);
4319 if (ret) {
4320 if (exts != *extents)
4321 kfree(exts);
4322 } else {
4323 *extents = exts;
4324 *nr_extents = nr;
4325 }
4326 return ret;
4327}
4328
d397712b 4329static noinline int replace_one_extent(struct btrfs_trans_handle *trans,
1a40e23b
ZY
4330 struct btrfs_root *root,
4331 struct btrfs_path *path,
4332 struct btrfs_key *extent_key,
4333 struct btrfs_key *leaf_key,
4334 struct btrfs_ref_path *ref_path,
4335 struct disk_extent *new_extents,
4336 int nr_extents)
4337{
4338 struct extent_buffer *leaf;
4339 struct btrfs_file_extent_item *fi;
4340 struct inode *inode = NULL;
4341 struct btrfs_key key;
4342 u64 lock_start = 0;
4343 u64 lock_end = 0;
4344 u64 num_bytes;
4345 u64 ext_offset;
86288a19 4346 u64 search_end = (u64)-1;
1a40e23b 4347 u32 nritems;
3bb1a1bc 4348 int nr_scaned = 0;
1a40e23b 4349 int extent_locked = 0;
d899e052 4350 int extent_type;
1a40e23b
ZY
4351 int ret;
4352
3bb1a1bc 4353 memcpy(&key, leaf_key, sizeof(key));
1a40e23b 4354 if (ref_path->owner_objectid != BTRFS_MULTIPLE_OBJECTIDS) {
3bb1a1bc
YZ
4355 if (key.objectid < ref_path->owner_objectid ||
4356 (key.objectid == ref_path->owner_objectid &&
4357 key.type < BTRFS_EXTENT_DATA_KEY)) {
4358 key.objectid = ref_path->owner_objectid;
4359 key.type = BTRFS_EXTENT_DATA_KEY;
4360 key.offset = 0;
4361 }
1a40e23b
ZY
4362 }
4363
4364 while (1) {
4365 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
4366 if (ret < 0)
4367 goto out;
4368
4369 leaf = path->nodes[0];
4370 nritems = btrfs_header_nritems(leaf);
4371next:
4372 if (extent_locked && ret > 0) {
4373 /*
4374 * the file extent item was modified by someone
4375 * before the extent got locked.
4376 */
1a40e23b
ZY
4377 unlock_extent(&BTRFS_I(inode)->io_tree, lock_start,
4378 lock_end, GFP_NOFS);
4379 extent_locked = 0;
4380 }
4381
4382 if (path->slots[0] >= nritems) {
3bb1a1bc 4383 if (++nr_scaned > 2)
1a40e23b
ZY
4384 break;
4385
4386 BUG_ON(extent_locked);
4387 ret = btrfs_next_leaf(root, path);
4388 if (ret < 0)
4389 goto out;
4390 if (ret > 0)
4391 break;
4392 leaf = path->nodes[0];
4393 nritems = btrfs_header_nritems(leaf);
4394 }
4395
4396 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4397
4398 if (ref_path->owner_objectid != BTRFS_MULTIPLE_OBJECTIDS) {
4399 if ((key.objectid > ref_path->owner_objectid) ||
4400 (key.objectid == ref_path->owner_objectid &&
4401 key.type > BTRFS_EXTENT_DATA_KEY) ||
86288a19 4402 key.offset >= search_end)
1a40e23b
ZY
4403 break;
4404 }
4405
4406 if (inode && key.objectid != inode->i_ino) {
4407 BUG_ON(extent_locked);
4408 btrfs_release_path(root, path);
4409 mutex_unlock(&inode->i_mutex);
4410 iput(inode);
4411 inode = NULL;
4412 continue;
4413 }
4414
4415 if (key.type != BTRFS_EXTENT_DATA_KEY) {
4416 path->slots[0]++;
4417 ret = 1;
4418 goto next;
4419 }
4420 fi = btrfs_item_ptr(leaf, path->slots[0],
4421 struct btrfs_file_extent_item);
d899e052
YZ
4422 extent_type = btrfs_file_extent_type(leaf, fi);
4423 if ((extent_type != BTRFS_FILE_EXTENT_REG &&
4424 extent_type != BTRFS_FILE_EXTENT_PREALLOC) ||
1a40e23b
ZY
4425 (btrfs_file_extent_disk_bytenr(leaf, fi) !=
4426 extent_key->objectid)) {
4427 path->slots[0]++;
4428 ret = 1;
4429 goto next;
4430 }
4431
4432 num_bytes = btrfs_file_extent_num_bytes(leaf, fi);
4433 ext_offset = btrfs_file_extent_offset(leaf, fi);
4434
86288a19
YZ
4435 if (search_end == (u64)-1) {
4436 search_end = key.offset - ext_offset +
4437 btrfs_file_extent_ram_bytes(leaf, fi);
4438 }
1a40e23b
ZY
4439
4440 if (!extent_locked) {
4441 lock_start = key.offset;
4442 lock_end = lock_start + num_bytes - 1;
4443 } else {
6643558d
YZ
4444 if (lock_start > key.offset ||
4445 lock_end + 1 < key.offset + num_bytes) {
4446 unlock_extent(&BTRFS_I(inode)->io_tree,
4447 lock_start, lock_end, GFP_NOFS);
4448 extent_locked = 0;
4449 }
1a40e23b
ZY
4450 }
4451
4452 if (!inode) {
4453 btrfs_release_path(root, path);
4454
4455 inode = btrfs_iget_locked(root->fs_info->sb,
4456 key.objectid, root);
4457 if (inode->i_state & I_NEW) {
4458 BTRFS_I(inode)->root = root;
4459 BTRFS_I(inode)->location.objectid =
4460 key.objectid;
4461 BTRFS_I(inode)->location.type =
4462 BTRFS_INODE_ITEM_KEY;
4463 BTRFS_I(inode)->location.offset = 0;
4464 btrfs_read_locked_inode(inode);
4465 unlock_new_inode(inode);
4466 }
4467 /*
4468 * some code call btrfs_commit_transaction while
4469 * holding the i_mutex, so we can't use mutex_lock
4470 * here.
4471 */
4472 if (is_bad_inode(inode) ||
4473 !mutex_trylock(&inode->i_mutex)) {
4474 iput(inode);
4475 inode = NULL;
4476 key.offset = (u64)-1;
4477 goto skip;
4478 }
4479 }
4480
4481 if (!extent_locked) {
4482 struct btrfs_ordered_extent *ordered;
4483
4484 btrfs_release_path(root, path);
4485
4486 lock_extent(&BTRFS_I(inode)->io_tree, lock_start,
4487 lock_end, GFP_NOFS);
4488 ordered = btrfs_lookup_first_ordered_extent(inode,
4489 lock_end);
4490 if (ordered &&
4491 ordered->file_offset <= lock_end &&
4492 ordered->file_offset + ordered->len > lock_start) {
4493 unlock_extent(&BTRFS_I(inode)->io_tree,
4494 lock_start, lock_end, GFP_NOFS);
4495 btrfs_start_ordered_extent(inode, ordered, 1);
4496 btrfs_put_ordered_extent(ordered);
4497 key.offset += num_bytes;
4498 goto skip;
4499 }
4500 if (ordered)
4501 btrfs_put_ordered_extent(ordered);
4502
1a40e23b
ZY
4503 extent_locked = 1;
4504 continue;
4505 }
4506
4507 if (nr_extents == 1) {
4508 /* update extent pointer in place */
1a40e23b
ZY
4509 btrfs_set_file_extent_disk_bytenr(leaf, fi,
4510 new_extents[0].disk_bytenr);
4511 btrfs_set_file_extent_disk_num_bytes(leaf, fi,
4512 new_extents[0].disk_num_bytes);
1a40e23b
ZY
4513 btrfs_mark_buffer_dirty(leaf);
4514
4515 btrfs_drop_extent_cache(inode, key.offset,
4516 key.offset + num_bytes - 1, 0);
4517
4518 ret = btrfs_inc_extent_ref(trans, root,
4519 new_extents[0].disk_bytenr,
4520 new_extents[0].disk_num_bytes,
4521 leaf->start,
4522 root->root_key.objectid,
4523 trans->transid,
3bb1a1bc 4524 key.objectid);
1a40e23b
ZY
4525 BUG_ON(ret);
4526
4527 ret = btrfs_free_extent(trans, root,
4528 extent_key->objectid,
4529 extent_key->offset,
4530 leaf->start,
4531 btrfs_header_owner(leaf),
4532 btrfs_header_generation(leaf),
3bb1a1bc 4533 key.objectid, 0);
1a40e23b
ZY
4534 BUG_ON(ret);
4535
4536 btrfs_release_path(root, path);
4537 key.offset += num_bytes;
4538 } else {
d899e052
YZ
4539 BUG_ON(1);
4540#if 0
1a40e23b
ZY
4541 u64 alloc_hint;
4542 u64 extent_len;
4543 int i;
4544 /*
4545 * drop old extent pointer at first, then insert the
4546 * new pointers one bye one
4547 */
4548 btrfs_release_path(root, path);
4549 ret = btrfs_drop_extents(trans, root, inode, key.offset,
4550 key.offset + num_bytes,
4551 key.offset, &alloc_hint);
4552 BUG_ON(ret);
4553
4554 for (i = 0; i < nr_extents; i++) {
4555 if (ext_offset >= new_extents[i].num_bytes) {
4556 ext_offset -= new_extents[i].num_bytes;
4557 continue;
4558 }
4559 extent_len = min(new_extents[i].num_bytes -
4560 ext_offset, num_bytes);
4561
4562 ret = btrfs_insert_empty_item(trans, root,
4563 path, &key,
4564 sizeof(*fi));
4565 BUG_ON(ret);
4566
4567 leaf = path->nodes[0];
4568 fi = btrfs_item_ptr(leaf, path->slots[0],
4569 struct btrfs_file_extent_item);
4570 btrfs_set_file_extent_generation(leaf, fi,
4571 trans->transid);
4572 btrfs_set_file_extent_type(leaf, fi,
4573 BTRFS_FILE_EXTENT_REG);
4574 btrfs_set_file_extent_disk_bytenr(leaf, fi,
4575 new_extents[i].disk_bytenr);
4576 btrfs_set_file_extent_disk_num_bytes(leaf, fi,
4577 new_extents[i].disk_num_bytes);
c8b97818
CM
4578 btrfs_set_file_extent_ram_bytes(leaf, fi,
4579 new_extents[i].ram_bytes);
4580
4581 btrfs_set_file_extent_compression(leaf, fi,
4582 new_extents[i].compression);
4583 btrfs_set_file_extent_encryption(leaf, fi,
4584 new_extents[i].encryption);
4585 btrfs_set_file_extent_other_encoding(leaf, fi,
4586 new_extents[i].other_encoding);
4587
1a40e23b
ZY
4588 btrfs_set_file_extent_num_bytes(leaf, fi,
4589 extent_len);
4590 ext_offset += new_extents[i].offset;
4591 btrfs_set_file_extent_offset(leaf, fi,
4592 ext_offset);
4593 btrfs_mark_buffer_dirty(leaf);
4594
4595 btrfs_drop_extent_cache(inode, key.offset,
4596 key.offset + extent_len - 1, 0);
4597
4598 ret = btrfs_inc_extent_ref(trans, root,
4599 new_extents[i].disk_bytenr,
4600 new_extents[i].disk_num_bytes,
4601 leaf->start,
4602 root->root_key.objectid,
3bb1a1bc 4603 trans->transid, key.objectid);
1a40e23b
ZY
4604 BUG_ON(ret);
4605 btrfs_release_path(root, path);
4606
a76a3cd4 4607 inode_add_bytes(inode, extent_len);
1a40e23b
ZY
4608
4609 ext_offset = 0;
4610 num_bytes -= extent_len;
4611 key.offset += extent_len;
4612
4613 if (num_bytes == 0)
4614 break;
4615 }
4616 BUG_ON(i >= nr_extents);
d899e052 4617#endif
1a40e23b
ZY
4618 }
4619
4620 if (extent_locked) {
1a40e23b
ZY
4621 unlock_extent(&BTRFS_I(inode)->io_tree, lock_start,
4622 lock_end, GFP_NOFS);
4623 extent_locked = 0;
4624 }
4625skip:
4626 if (ref_path->owner_objectid != BTRFS_MULTIPLE_OBJECTIDS &&
86288a19 4627 key.offset >= search_end)
1a40e23b
ZY
4628 break;
4629
4630 cond_resched();
4631 }
4632 ret = 0;
4633out:
4634 btrfs_release_path(root, path);
4635 if (inode) {
4636 mutex_unlock(&inode->i_mutex);
4637 if (extent_locked) {
1a40e23b
ZY
4638 unlock_extent(&BTRFS_I(inode)->io_tree, lock_start,
4639 lock_end, GFP_NOFS);
4640 }
4641 iput(inode);
4642 }
4643 return ret;
4644}
4645
1a40e23b
ZY
4646int btrfs_reloc_tree_cache_ref(struct btrfs_trans_handle *trans,
4647 struct btrfs_root *root,
4648 struct extent_buffer *buf, u64 orig_start)
4649{
4650 int level;
4651 int ret;
4652
4653 BUG_ON(btrfs_header_generation(buf) != trans->transid);
4654 BUG_ON(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
4655
4656 level = btrfs_header_level(buf);
4657 if (level == 0) {
4658 struct btrfs_leaf_ref *ref;
4659 struct btrfs_leaf_ref *orig_ref;
4660
4661 orig_ref = btrfs_lookup_leaf_ref(root, orig_start);
4662 if (!orig_ref)
4663 return -ENOENT;
4664
4665 ref = btrfs_alloc_leaf_ref(root, orig_ref->nritems);
4666 if (!ref) {
4667 btrfs_free_leaf_ref(root, orig_ref);
4668 return -ENOMEM;
4669 }
4670
4671 ref->nritems = orig_ref->nritems;
4672 memcpy(ref->extents, orig_ref->extents,
4673 sizeof(ref->extents[0]) * ref->nritems);
4674
4675 btrfs_free_leaf_ref(root, orig_ref);
4676
4677 ref->root_gen = trans->transid;
4678 ref->bytenr = buf->start;
4679 ref->owner = btrfs_header_owner(buf);
4680 ref->generation = btrfs_header_generation(buf);
bd56b302 4681
1a40e23b
ZY
4682 ret = btrfs_add_leaf_ref(root, ref, 0);
4683 WARN_ON(ret);
4684 btrfs_free_leaf_ref(root, ref);
4685 }
4686 return 0;
4687}
4688
d397712b 4689static noinline int invalidate_extent_cache(struct btrfs_root *root,
1a40e23b
ZY
4690 struct extent_buffer *leaf,
4691 struct btrfs_block_group_cache *group,
4692 struct btrfs_root *target_root)
4693{
4694 struct btrfs_key key;
4695 struct inode *inode = NULL;
4696 struct btrfs_file_extent_item *fi;
4697 u64 num_bytes;
4698 u64 skip_objectid = 0;
4699 u32 nritems;
4700 u32 i;
4701
4702 nritems = btrfs_header_nritems(leaf);
4703 for (i = 0; i < nritems; i++) {
4704 btrfs_item_key_to_cpu(leaf, &key, i);
4705 if (key.objectid == skip_objectid ||
4706 key.type != BTRFS_EXTENT_DATA_KEY)
4707 continue;
4708 fi = btrfs_item_ptr(leaf, i, struct btrfs_file_extent_item);
4709 if (btrfs_file_extent_type(leaf, fi) ==
4710 BTRFS_FILE_EXTENT_INLINE)
4711 continue;
4712 if (btrfs_file_extent_disk_bytenr(leaf, fi) == 0)
4713 continue;
4714 if (!inode || inode->i_ino != key.objectid) {
4715 iput(inode);
4716 inode = btrfs_ilookup(target_root->fs_info->sb,
4717 key.objectid, target_root, 1);
4718 }
4719 if (!inode) {
4720 skip_objectid = key.objectid;
4721 continue;
4722 }
4723 num_bytes = btrfs_file_extent_num_bytes(leaf, fi);
4724
4725 lock_extent(&BTRFS_I(inode)->io_tree, key.offset,
4726 key.offset + num_bytes - 1, GFP_NOFS);
1a40e23b
ZY
4727 btrfs_drop_extent_cache(inode, key.offset,
4728 key.offset + num_bytes - 1, 1);
1a40e23b
ZY
4729 unlock_extent(&BTRFS_I(inode)->io_tree, key.offset,
4730 key.offset + num_bytes - 1, GFP_NOFS);
4731 cond_resched();
4732 }
4733 iput(inode);
4734 return 0;
4735}
4736
d397712b 4737static noinline int replace_extents_in_leaf(struct btrfs_trans_handle *trans,
1a40e23b
ZY
4738 struct btrfs_root *root,
4739 struct extent_buffer *leaf,
4740 struct btrfs_block_group_cache *group,
4741 struct inode *reloc_inode)
4742{
4743 struct btrfs_key key;
4744 struct btrfs_key extent_key;
4745 struct btrfs_file_extent_item *fi;
4746 struct btrfs_leaf_ref *ref;
4747 struct disk_extent *new_extent;
4748 u64 bytenr;
4749 u64 num_bytes;
4750 u32 nritems;
4751 u32 i;
4752 int ext_index;
4753 int nr_extent;
4754 int ret;
4755
4756 new_extent = kmalloc(sizeof(*new_extent), GFP_NOFS);
4757 BUG_ON(!new_extent);
4758
4759 ref = btrfs_lookup_leaf_ref(root, leaf->start);
4760 BUG_ON(!ref);
4761
4762 ext_index = -1;
4763 nritems = btrfs_header_nritems(leaf);
4764 for (i = 0; i < nritems; i++) {
4765 btrfs_item_key_to_cpu(leaf, &key, i);
4766 if (btrfs_key_type(&key) != BTRFS_EXTENT_DATA_KEY)
4767 continue;
4768 fi = btrfs_item_ptr(leaf, i, struct btrfs_file_extent_item);
4769 if (btrfs_file_extent_type(leaf, fi) ==
4770 BTRFS_FILE_EXTENT_INLINE)
4771 continue;
4772 bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
4773 num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
4774 if (bytenr == 0)
4775 continue;
4776
4777 ext_index++;
4778 if (bytenr >= group->key.objectid + group->key.offset ||
4779 bytenr + num_bytes <= group->key.objectid)
4780 continue;
4781
4782 extent_key.objectid = bytenr;
4783 extent_key.offset = num_bytes;
4784 extent_key.type = BTRFS_EXTENT_ITEM_KEY;
4785 nr_extent = 1;
4786 ret = get_new_locations(reloc_inode, &extent_key,
4787 group->key.objectid, 1,
4788 &new_extent, &nr_extent);
4789 if (ret > 0)
4790 continue;
4791 BUG_ON(ret < 0);
4792
4793 BUG_ON(ref->extents[ext_index].bytenr != bytenr);
4794 BUG_ON(ref->extents[ext_index].num_bytes != num_bytes);
4795 ref->extents[ext_index].bytenr = new_extent->disk_bytenr;
4796 ref->extents[ext_index].num_bytes = new_extent->disk_num_bytes;
4797
1a40e23b
ZY
4798 btrfs_set_file_extent_disk_bytenr(leaf, fi,
4799 new_extent->disk_bytenr);
4800 btrfs_set_file_extent_disk_num_bytes(leaf, fi,
4801 new_extent->disk_num_bytes);
1a40e23b
ZY
4802 btrfs_mark_buffer_dirty(leaf);
4803
4804 ret = btrfs_inc_extent_ref(trans, root,
4805 new_extent->disk_bytenr,
4806 new_extent->disk_num_bytes,
4807 leaf->start,
4808 root->root_key.objectid,
3bb1a1bc 4809 trans->transid, key.objectid);
1a40e23b 4810 BUG_ON(ret);
56bec294 4811
1a40e23b
ZY
4812 ret = btrfs_free_extent(trans, root,
4813 bytenr, num_bytes, leaf->start,
4814 btrfs_header_owner(leaf),
4815 btrfs_header_generation(leaf),
3bb1a1bc 4816 key.objectid, 0);
1a40e23b
ZY
4817 BUG_ON(ret);
4818 cond_resched();
4819 }
4820 kfree(new_extent);
4821 BUG_ON(ext_index + 1 != ref->nritems);
4822 btrfs_free_leaf_ref(root, ref);
4823 return 0;
4824}
4825
f82d02d9
YZ
4826int btrfs_free_reloc_root(struct btrfs_trans_handle *trans,
4827 struct btrfs_root *root)
1a40e23b
ZY
4828{
4829 struct btrfs_root *reloc_root;
f82d02d9 4830 int ret;
1a40e23b
ZY
4831
4832 if (root->reloc_root) {
4833 reloc_root = root->reloc_root;
4834 root->reloc_root = NULL;
4835 list_add(&reloc_root->dead_list,
4836 &root->fs_info->dead_reloc_roots);
f82d02d9
YZ
4837
4838 btrfs_set_root_bytenr(&reloc_root->root_item,
4839 reloc_root->node->start);
4840 btrfs_set_root_level(&root->root_item,
4841 btrfs_header_level(reloc_root->node));
4842 memset(&reloc_root->root_item.drop_progress, 0,
4843 sizeof(struct btrfs_disk_key));
4844 reloc_root->root_item.drop_level = 0;
4845
4846 ret = btrfs_update_root(trans, root->fs_info->tree_root,
4847 &reloc_root->root_key,
4848 &reloc_root->root_item);
4849 BUG_ON(ret);
1a40e23b
ZY
4850 }
4851 return 0;
4852}
4853
4854int btrfs_drop_dead_reloc_roots(struct btrfs_root *root)
4855{
4856 struct btrfs_trans_handle *trans;
4857 struct btrfs_root *reloc_root;
4858 struct btrfs_root *prev_root = NULL;
4859 struct list_head dead_roots;
4860 int ret;
4861 unsigned long nr;
4862
4863 INIT_LIST_HEAD(&dead_roots);
4864 list_splice_init(&root->fs_info->dead_reloc_roots, &dead_roots);
4865
4866 while (!list_empty(&dead_roots)) {
4867 reloc_root = list_entry(dead_roots.prev,
4868 struct btrfs_root, dead_list);
4869 list_del_init(&reloc_root->dead_list);
4870
4871 BUG_ON(reloc_root->commit_root != NULL);
4872 while (1) {
4873 trans = btrfs_join_transaction(root, 1);
4874 BUG_ON(!trans);
4875
4876 mutex_lock(&root->fs_info->drop_mutex);
4877 ret = btrfs_drop_snapshot(trans, reloc_root);
4878 if (ret != -EAGAIN)
4879 break;
4880 mutex_unlock(&root->fs_info->drop_mutex);
4881
4882 nr = trans->blocks_used;
4883 ret = btrfs_end_transaction(trans, root);
4884 BUG_ON(ret);
4885 btrfs_btree_balance_dirty(root, nr);
4886 }
4887
4888 free_extent_buffer(reloc_root->node);
4889
4890 ret = btrfs_del_root(trans, root->fs_info->tree_root,
4891 &reloc_root->root_key);
4892 BUG_ON(ret);
4893 mutex_unlock(&root->fs_info->drop_mutex);
4894
4895 nr = trans->blocks_used;
4896 ret = btrfs_end_transaction(trans, root);
4897 BUG_ON(ret);
4898 btrfs_btree_balance_dirty(root, nr);
4899
4900 kfree(prev_root);
4901 prev_root = reloc_root;
4902 }
4903 if (prev_root) {
4904 btrfs_remove_leaf_refs(prev_root, (u64)-1, 0);
4905 kfree(prev_root);
4906 }
4907 return 0;
4908}
4909
4910int btrfs_add_dead_reloc_root(struct btrfs_root *root)
4911{
4912 list_add(&root->dead_list, &root->fs_info->dead_reloc_roots);
4913 return 0;
4914}
4915
4916int btrfs_cleanup_reloc_trees(struct btrfs_root *root)
4917{
4918 struct btrfs_root *reloc_root;
4919 struct btrfs_trans_handle *trans;
4920 struct btrfs_key location;
4921 int found;
4922 int ret;
4923
4924 mutex_lock(&root->fs_info->tree_reloc_mutex);
4925 ret = btrfs_find_dead_roots(root, BTRFS_TREE_RELOC_OBJECTID, NULL);
4926 BUG_ON(ret);
4927 found = !list_empty(&root->fs_info->dead_reloc_roots);
4928 mutex_unlock(&root->fs_info->tree_reloc_mutex);
4929
4930 if (found) {
4931 trans = btrfs_start_transaction(root, 1);
4932 BUG_ON(!trans);
4933 ret = btrfs_commit_transaction(trans, root);
4934 BUG_ON(ret);
4935 }
4936
4937 location.objectid = BTRFS_DATA_RELOC_TREE_OBJECTID;
4938 location.offset = (u64)-1;
4939 location.type = BTRFS_ROOT_ITEM_KEY;
4940
4941 reloc_root = btrfs_read_fs_root_no_name(root->fs_info, &location);
4942 BUG_ON(!reloc_root);
4943 btrfs_orphan_cleanup(reloc_root);
4944 return 0;
4945}
4946
d397712b 4947static noinline int init_reloc_tree(struct btrfs_trans_handle *trans,
1a40e23b
ZY
4948 struct btrfs_root *root)
4949{
4950 struct btrfs_root *reloc_root;
4951 struct extent_buffer *eb;
4952 struct btrfs_root_item *root_item;
4953 struct btrfs_key root_key;
4954 int ret;
4955
4956 BUG_ON(!root->ref_cows);
4957 if (root->reloc_root)
4958 return 0;
4959
4960 root_item = kmalloc(sizeof(*root_item), GFP_NOFS);
4961 BUG_ON(!root_item);
4962
4963 ret = btrfs_copy_root(trans, root, root->commit_root,
4964 &eb, BTRFS_TREE_RELOC_OBJECTID);
4965 BUG_ON(ret);
4966
4967 root_key.objectid = BTRFS_TREE_RELOC_OBJECTID;
4968 root_key.offset = root->root_key.objectid;
4969 root_key.type = BTRFS_ROOT_ITEM_KEY;
4970
4971 memcpy(root_item, &root->root_item, sizeof(root_item));
4972 btrfs_set_root_refs(root_item, 0);
4973 btrfs_set_root_bytenr(root_item, eb->start);
4974 btrfs_set_root_level(root_item, btrfs_header_level(eb));
84234f3a 4975 btrfs_set_root_generation(root_item, trans->transid);
1a40e23b
ZY
4976
4977 btrfs_tree_unlock(eb);
4978 free_extent_buffer(eb);
4979
4980 ret = btrfs_insert_root(trans, root->fs_info->tree_root,
4981 &root_key, root_item);
4982 BUG_ON(ret);
4983 kfree(root_item);
4984
4985 reloc_root = btrfs_read_fs_root_no_radix(root->fs_info->tree_root,
4986 &root_key);
4987 BUG_ON(!reloc_root);
4988 reloc_root->last_trans = trans->transid;
4989 reloc_root->commit_root = NULL;
4990 reloc_root->ref_tree = &root->fs_info->reloc_ref_tree;
4991
4992 root->reloc_root = reloc_root;
4993 return 0;
4994}
4995
4996/*
4997 * Core function of space balance.
4998 *
4999 * The idea is using reloc trees to relocate tree blocks in reference
f82d02d9
YZ
5000 * counted roots. There is one reloc tree for each subvol, and all
5001 * reloc trees share same root key objectid. Reloc trees are snapshots
5002 * of the latest committed roots of subvols (root->commit_root).
5003 *
5004 * To relocate a tree block referenced by a subvol, there are two steps.
5005 * COW the block through subvol's reloc tree, then update block pointer
5006 * in the subvol to point to the new block. Since all reloc trees share
5007 * same root key objectid, doing special handing for tree blocks owned
5008 * by them is easy. Once a tree block has been COWed in one reloc tree,
5009 * we can use the resulting new block directly when the same block is
5010 * required to COW again through other reloc trees. By this way, relocated
5011 * tree blocks are shared between reloc trees, so they are also shared
5012 * between subvols.
1a40e23b 5013 */
d397712b 5014static noinline int relocate_one_path(struct btrfs_trans_handle *trans,
1a40e23b
ZY
5015 struct btrfs_root *root,
5016 struct btrfs_path *path,
5017 struct btrfs_key *first_key,
5018 struct btrfs_ref_path *ref_path,
5019 struct btrfs_block_group_cache *group,
5020 struct inode *reloc_inode)
5021{
5022 struct btrfs_root *reloc_root;
5023 struct extent_buffer *eb = NULL;
5024 struct btrfs_key *keys;
5025 u64 *nodes;
5026 int level;
f82d02d9 5027 int shared_level;
1a40e23b 5028 int lowest_level = 0;
1a40e23b
ZY
5029 int ret;
5030
5031 if (ref_path->owner_objectid < BTRFS_FIRST_FREE_OBJECTID)
5032 lowest_level = ref_path->owner_objectid;
5033
f82d02d9 5034 if (!root->ref_cows) {
1a40e23b
ZY
5035 path->lowest_level = lowest_level;
5036 ret = btrfs_search_slot(trans, root, first_key, path, 0, 1);
5037 BUG_ON(ret < 0);
5038 path->lowest_level = 0;
5039 btrfs_release_path(root, path);
5040 return 0;
5041 }
5042
1a40e23b
ZY
5043 mutex_lock(&root->fs_info->tree_reloc_mutex);
5044 ret = init_reloc_tree(trans, root);
5045 BUG_ON(ret);
5046 reloc_root = root->reloc_root;
5047
f82d02d9
YZ
5048 shared_level = ref_path->shared_level;
5049 ref_path->shared_level = BTRFS_MAX_LEVEL - 1;
1a40e23b 5050
f82d02d9
YZ
5051 keys = ref_path->node_keys;
5052 nodes = ref_path->new_nodes;
5053 memset(&keys[shared_level + 1], 0,
5054 sizeof(*keys) * (BTRFS_MAX_LEVEL - shared_level - 1));
5055 memset(&nodes[shared_level + 1], 0,
5056 sizeof(*nodes) * (BTRFS_MAX_LEVEL - shared_level - 1));
1a40e23b 5057
f82d02d9
YZ
5058 if (nodes[lowest_level] == 0) {
5059 path->lowest_level = lowest_level;
5060 ret = btrfs_search_slot(trans, reloc_root, first_key, path,
5061 0, 1);
5062 BUG_ON(ret);
5063 for (level = lowest_level; level < BTRFS_MAX_LEVEL; level++) {
5064 eb = path->nodes[level];
5065 if (!eb || eb == reloc_root->node)
5066 break;
5067 nodes[level] = eb->start;
5068 if (level == 0)
5069 btrfs_item_key_to_cpu(eb, &keys[level], 0);
5070 else
5071 btrfs_node_key_to_cpu(eb, &keys[level], 0);
5072 }
2b82032c
YZ
5073 if (nodes[0] &&
5074 ref_path->owner_objectid >= BTRFS_FIRST_FREE_OBJECTID) {
f82d02d9
YZ
5075 eb = path->nodes[0];
5076 ret = replace_extents_in_leaf(trans, reloc_root, eb,
5077 group, reloc_inode);
5078 BUG_ON(ret);
5079 }
5080 btrfs_release_path(reloc_root, path);
5081 } else {
1a40e23b 5082 ret = btrfs_merge_path(trans, reloc_root, keys, nodes,
f82d02d9 5083 lowest_level);
1a40e23b
ZY
5084 BUG_ON(ret);
5085 }
5086
1a40e23b
ZY
5087 /*
5088 * replace tree blocks in the fs tree with tree blocks in
5089 * the reloc tree.
5090 */
5091 ret = btrfs_merge_path(trans, root, keys, nodes, lowest_level);
5092 BUG_ON(ret < 0);
5093
5094 if (ref_path->owner_objectid >= BTRFS_FIRST_FREE_OBJECTID) {
f82d02d9
YZ
5095 ret = btrfs_search_slot(trans, reloc_root, first_key, path,
5096 0, 0);
5097 BUG_ON(ret);
5098 extent_buffer_get(path->nodes[0]);
5099 eb = path->nodes[0];
5100 btrfs_release_path(reloc_root, path);
1a40e23b
ZY
5101 ret = invalidate_extent_cache(reloc_root, eb, group, root);
5102 BUG_ON(ret);
5103 free_extent_buffer(eb);
5104 }
1a40e23b 5105
f82d02d9 5106 mutex_unlock(&root->fs_info->tree_reloc_mutex);
1a40e23b 5107 path->lowest_level = 0;
1a40e23b
ZY
5108 return 0;
5109}
5110
d397712b 5111static noinline int relocate_tree_block(struct btrfs_trans_handle *trans,
1a40e23b
ZY
5112 struct btrfs_root *root,
5113 struct btrfs_path *path,
5114 struct btrfs_key *first_key,
5115 struct btrfs_ref_path *ref_path)
5116{
5117 int ret;
1a40e23b
ZY
5118
5119 ret = relocate_one_path(trans, root, path, first_key,
5120 ref_path, NULL, NULL);
5121 BUG_ON(ret);
5122
1a40e23b
ZY
5123 return 0;
5124}
5125
d397712b 5126static noinline int del_extent_zero(struct btrfs_trans_handle *trans,
1a40e23b
ZY
5127 struct btrfs_root *extent_root,
5128 struct btrfs_path *path,
5129 struct btrfs_key *extent_key)
5130{
5131 int ret;
5132
1a40e23b
ZY
5133 ret = btrfs_search_slot(trans, extent_root, extent_key, path, -1, 1);
5134 if (ret)
5135 goto out;
5136 ret = btrfs_del_item(trans, extent_root, path);
5137out:
5138 btrfs_release_path(extent_root, path);
1a40e23b
ZY
5139 return ret;
5140}
5141
d397712b 5142static noinline struct btrfs_root *read_ref_root(struct btrfs_fs_info *fs_info,
1a40e23b
ZY
5143 struct btrfs_ref_path *ref_path)
5144{
5145 struct btrfs_key root_key;
5146
5147 root_key.objectid = ref_path->root_objectid;
5148 root_key.type = BTRFS_ROOT_ITEM_KEY;
5149 if (is_cowonly_root(ref_path->root_objectid))
5150 root_key.offset = 0;
5151 else
5152 root_key.offset = (u64)-1;
5153
5154 return btrfs_read_fs_root_no_name(fs_info, &root_key);
5155}
5156
d397712b 5157static noinline int relocate_one_extent(struct btrfs_root *extent_root,
1a40e23b
ZY
5158 struct btrfs_path *path,
5159 struct btrfs_key *extent_key,
5160 struct btrfs_block_group_cache *group,
5161 struct inode *reloc_inode, int pass)
5162{
5163 struct btrfs_trans_handle *trans;
5164 struct btrfs_root *found_root;
5165 struct btrfs_ref_path *ref_path = NULL;
5166 struct disk_extent *new_extents = NULL;
5167 int nr_extents = 0;
5168 int loops;
5169 int ret;
5170 int level;
5171 struct btrfs_key first_key;
5172 u64 prev_block = 0;
5173
1a40e23b
ZY
5174
5175 trans = btrfs_start_transaction(extent_root, 1);
5176 BUG_ON(!trans);
5177
5178 if (extent_key->objectid == 0) {
5179 ret = del_extent_zero(trans, extent_root, path, extent_key);
5180 goto out;
5181 }
5182
5183 ref_path = kmalloc(sizeof(*ref_path), GFP_NOFS);
5184 if (!ref_path) {
d397712b
CM
5185 ret = -ENOMEM;
5186 goto out;
1a40e23b
ZY
5187 }
5188
5189 for (loops = 0; ; loops++) {
5190 if (loops == 0) {
5191 ret = btrfs_first_ref_path(trans, extent_root, ref_path,
5192 extent_key->objectid);
5193 } else {
5194 ret = btrfs_next_ref_path(trans, extent_root, ref_path);
5195 }
5196 if (ret < 0)
5197 goto out;
5198 if (ret > 0)
5199 break;
5200
5201 if (ref_path->root_objectid == BTRFS_TREE_LOG_OBJECTID ||
5202 ref_path->root_objectid == BTRFS_TREE_RELOC_OBJECTID)
5203 continue;
5204
5205 found_root = read_ref_root(extent_root->fs_info, ref_path);
5206 BUG_ON(!found_root);
5207 /*
5208 * for reference counted tree, only process reference paths
5209 * rooted at the latest committed root.
5210 */
5211 if (found_root->ref_cows &&
5212 ref_path->root_generation != found_root->root_key.offset)
5213 continue;
5214
5215 if (ref_path->owner_objectid >= BTRFS_FIRST_FREE_OBJECTID) {
5216 if (pass == 0) {
5217 /*
5218 * copy data extents to new locations
5219 */
5220 u64 group_start = group->key.objectid;
5221 ret = relocate_data_extent(reloc_inode,
5222 extent_key,
5223 group_start);
5224 if (ret < 0)
5225 goto out;
5226 break;
5227 }
5228 level = 0;
5229 } else {
5230 level = ref_path->owner_objectid;
5231 }
5232
5233 if (prev_block != ref_path->nodes[level]) {
5234 struct extent_buffer *eb;
5235 u64 block_start = ref_path->nodes[level];
5236 u64 block_size = btrfs_level_size(found_root, level);
5237
5238 eb = read_tree_block(found_root, block_start,
5239 block_size, 0);
5240 btrfs_tree_lock(eb);
5241 BUG_ON(level != btrfs_header_level(eb));
5242
5243 if (level == 0)
5244 btrfs_item_key_to_cpu(eb, &first_key, 0);
5245 else
5246 btrfs_node_key_to_cpu(eb, &first_key, 0);
5247
5248 btrfs_tree_unlock(eb);
5249 free_extent_buffer(eb);
5250 prev_block = block_start;
5251 }
5252
24562425 5253 mutex_lock(&extent_root->fs_info->trans_mutex);
e4404d6e 5254 btrfs_record_root_in_trans(found_root);
24562425 5255 mutex_unlock(&extent_root->fs_info->trans_mutex);
e4404d6e
YZ
5256 if (ref_path->owner_objectid >= BTRFS_FIRST_FREE_OBJECTID) {
5257 /*
5258 * try to update data extent references while
5259 * keeping metadata shared between snapshots.
5260 */
5261 if (pass == 1) {
5262 ret = relocate_one_path(trans, found_root,
5263 path, &first_key, ref_path,
5264 group, reloc_inode);
5265 if (ret < 0)
5266 goto out;
5267 continue;
5268 }
1a40e23b
ZY
5269 /*
5270 * use fallback method to process the remaining
5271 * references.
5272 */
5273 if (!new_extents) {
5274 u64 group_start = group->key.objectid;
d899e052
YZ
5275 new_extents = kmalloc(sizeof(*new_extents),
5276 GFP_NOFS);
5277 nr_extents = 1;
1a40e23b
ZY
5278 ret = get_new_locations(reloc_inode,
5279 extent_key,
d899e052 5280 group_start, 1,
1a40e23b
ZY
5281 &new_extents,
5282 &nr_extents);
d899e052 5283 if (ret)
1a40e23b
ZY
5284 goto out;
5285 }
1a40e23b
ZY
5286 ret = replace_one_extent(trans, found_root,
5287 path, extent_key,
5288 &first_key, ref_path,
5289 new_extents, nr_extents);
e4404d6e 5290 } else {
1a40e23b
ZY
5291 ret = relocate_tree_block(trans, found_root, path,
5292 &first_key, ref_path);
1a40e23b
ZY
5293 }
5294 if (ret < 0)
5295 goto out;
5296 }
5297 ret = 0;
5298out:
5299 btrfs_end_transaction(trans, extent_root);
5300 kfree(new_extents);
5301 kfree(ref_path);
1a40e23b
ZY
5302 return ret;
5303}
5304
ec44a35c
CM
5305static u64 update_block_group_flags(struct btrfs_root *root, u64 flags)
5306{
5307 u64 num_devices;
5308 u64 stripped = BTRFS_BLOCK_GROUP_RAID0 |
5309 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10;
5310
2b82032c 5311 num_devices = root->fs_info->fs_devices->rw_devices;
ec44a35c
CM
5312 if (num_devices == 1) {
5313 stripped |= BTRFS_BLOCK_GROUP_DUP;
5314 stripped = flags & ~stripped;
5315
5316 /* turn raid0 into single device chunks */
5317 if (flags & BTRFS_BLOCK_GROUP_RAID0)
5318 return stripped;
5319
5320 /* turn mirroring into duplication */
5321 if (flags & (BTRFS_BLOCK_GROUP_RAID1 |
5322 BTRFS_BLOCK_GROUP_RAID10))
5323 return stripped | BTRFS_BLOCK_GROUP_DUP;
5324 return flags;
5325 } else {
5326 /* they already had raid on here, just return */
ec44a35c
CM
5327 if (flags & stripped)
5328 return flags;
5329
5330 stripped |= BTRFS_BLOCK_GROUP_DUP;
5331 stripped = flags & ~stripped;
5332
5333 /* switch duplicated blocks with raid1 */
5334 if (flags & BTRFS_BLOCK_GROUP_DUP)
5335 return stripped | BTRFS_BLOCK_GROUP_RAID1;
5336
5337 /* turn single device chunks into raid0 */
5338 return stripped | BTRFS_BLOCK_GROUP_RAID0;
5339 }
5340 return flags;
5341}
5342
b2950863 5343static int __alloc_chunk_for_shrink(struct btrfs_root *root,
0ef3e66b
CM
5344 struct btrfs_block_group_cache *shrink_block_group,
5345 int force)
5346{
5347 struct btrfs_trans_handle *trans;
5348 u64 new_alloc_flags;
5349 u64 calc;
5350
c286ac48 5351 spin_lock(&shrink_block_group->lock);
0ef3e66b 5352 if (btrfs_block_group_used(&shrink_block_group->item) > 0) {
c286ac48 5353 spin_unlock(&shrink_block_group->lock);
c286ac48 5354
0ef3e66b 5355 trans = btrfs_start_transaction(root, 1);
c286ac48 5356 spin_lock(&shrink_block_group->lock);
7d9eb12c 5357
0ef3e66b
CM
5358 new_alloc_flags = update_block_group_flags(root,
5359 shrink_block_group->flags);
5360 if (new_alloc_flags != shrink_block_group->flags) {
5361 calc =
5362 btrfs_block_group_used(&shrink_block_group->item);
5363 } else {
5364 calc = shrink_block_group->key.offset;
5365 }
c286ac48
CM
5366 spin_unlock(&shrink_block_group->lock);
5367
0ef3e66b
CM
5368 do_chunk_alloc(trans, root->fs_info->extent_root,
5369 calc + 2 * 1024 * 1024, new_alloc_flags, force);
7d9eb12c 5370
0ef3e66b 5371 btrfs_end_transaction(trans, root);
c286ac48
CM
5372 } else
5373 spin_unlock(&shrink_block_group->lock);
0ef3e66b
CM
5374 return 0;
5375}
5376
1a40e23b
ZY
5377static int __insert_orphan_inode(struct btrfs_trans_handle *trans,
5378 struct btrfs_root *root,
5379 u64 objectid, u64 size)
5380{
5381 struct btrfs_path *path;
5382 struct btrfs_inode_item *item;
5383 struct extent_buffer *leaf;
5384 int ret;
5385
5386 path = btrfs_alloc_path();
5387 if (!path)
5388 return -ENOMEM;
5389
5390 ret = btrfs_insert_empty_inode(trans, root, path, objectid);
5391 if (ret)
5392 goto out;
5393
5394 leaf = path->nodes[0];
5395 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_inode_item);
5396 memset_extent_buffer(leaf, 0, (unsigned long)item, sizeof(*item));
5397 btrfs_set_inode_generation(leaf, item, 1);
5398 btrfs_set_inode_size(leaf, item, size);
5399 btrfs_set_inode_mode(leaf, item, S_IFREG | 0600);
0403e47e 5400 btrfs_set_inode_flags(leaf, item, BTRFS_INODE_NOCOMPRESS);
1a40e23b
ZY
5401 btrfs_mark_buffer_dirty(leaf);
5402 btrfs_release_path(root, path);
5403out:
5404 btrfs_free_path(path);
5405 return ret;
5406}
5407
d397712b 5408static noinline struct inode *create_reloc_inode(struct btrfs_fs_info *fs_info,
1a40e23b
ZY
5409 struct btrfs_block_group_cache *group)
5410{
5411 struct inode *inode = NULL;
5412 struct btrfs_trans_handle *trans;
5413 struct btrfs_root *root;
5414 struct btrfs_key root_key;
5415 u64 objectid = BTRFS_FIRST_FREE_OBJECTID;
5416 int err = 0;
5417
5418 root_key.objectid = BTRFS_DATA_RELOC_TREE_OBJECTID;
5419 root_key.type = BTRFS_ROOT_ITEM_KEY;
5420 root_key.offset = (u64)-1;
5421 root = btrfs_read_fs_root_no_name(fs_info, &root_key);
5422 if (IS_ERR(root))
5423 return ERR_CAST(root);
5424
5425 trans = btrfs_start_transaction(root, 1);
5426 BUG_ON(!trans);
5427
5428 err = btrfs_find_free_objectid(trans, root, objectid, &objectid);
5429 if (err)
5430 goto out;
5431
5432 err = __insert_orphan_inode(trans, root, objectid, group->key.offset);
5433 BUG_ON(err);
5434
5435 err = btrfs_insert_file_extent(trans, root, objectid, 0, 0, 0,
c8b97818
CM
5436 group->key.offset, 0, group->key.offset,
5437 0, 0, 0);
1a40e23b
ZY
5438 BUG_ON(err);
5439
5440 inode = btrfs_iget_locked(root->fs_info->sb, objectid, root);
5441 if (inode->i_state & I_NEW) {
5442 BTRFS_I(inode)->root = root;
5443 BTRFS_I(inode)->location.objectid = objectid;
5444 BTRFS_I(inode)->location.type = BTRFS_INODE_ITEM_KEY;
5445 BTRFS_I(inode)->location.offset = 0;
5446 btrfs_read_locked_inode(inode);
5447 unlock_new_inode(inode);
5448 BUG_ON(is_bad_inode(inode));
5449 } else {
5450 BUG_ON(1);
5451 }
17d217fe 5452 BTRFS_I(inode)->index_cnt = group->key.objectid;
1a40e23b
ZY
5453
5454 err = btrfs_orphan_add(trans, inode);
5455out:
5456 btrfs_end_transaction(trans, root);
5457 if (err) {
5458 if (inode)
5459 iput(inode);
5460 inode = ERR_PTR(err);
5461 }
5462 return inode;
5463}
5464
17d217fe
YZ
5465int btrfs_reloc_clone_csums(struct inode *inode, u64 file_pos, u64 len)
5466{
5467
5468 struct btrfs_ordered_sum *sums;
5469 struct btrfs_sector_sum *sector_sum;
5470 struct btrfs_ordered_extent *ordered;
5471 struct btrfs_root *root = BTRFS_I(inode)->root;
5472 struct list_head list;
5473 size_t offset;
5474 int ret;
5475 u64 disk_bytenr;
5476
5477 INIT_LIST_HEAD(&list);
5478
5479 ordered = btrfs_lookup_ordered_extent(inode, file_pos);
5480 BUG_ON(ordered->file_offset != file_pos || ordered->len != len);
5481
5482 disk_bytenr = file_pos + BTRFS_I(inode)->index_cnt;
07d400a6 5483 ret = btrfs_lookup_csums_range(root->fs_info->csum_root, disk_bytenr,
17d217fe
YZ
5484 disk_bytenr + len - 1, &list);
5485
5486 while (!list_empty(&list)) {
5487 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
5488 list_del_init(&sums->list);
5489
5490 sector_sum = sums->sums;
5491 sums->bytenr = ordered->start;
5492
5493 offset = 0;
5494 while (offset < sums->len) {
5495 sector_sum->bytenr += ordered->start - disk_bytenr;
5496 sector_sum++;
5497 offset += root->sectorsize;
5498 }
5499
5500 btrfs_add_ordered_sum(inode, ordered, sums);
5501 }
5502 btrfs_put_ordered_extent(ordered);
5503 return 0;
5504}
5505
1a40e23b 5506int btrfs_relocate_block_group(struct btrfs_root *root, u64 group_start)
edbd8d4e
CM
5507{
5508 struct btrfs_trans_handle *trans;
edbd8d4e 5509 struct btrfs_path *path;
1a40e23b
ZY
5510 struct btrfs_fs_info *info = root->fs_info;
5511 struct extent_buffer *leaf;
5512 struct inode *reloc_inode;
5513 struct btrfs_block_group_cache *block_group;
5514 struct btrfs_key key;
d899e052 5515 u64 skipped;
edbd8d4e
CM
5516 u64 cur_byte;
5517 u64 total_found;
edbd8d4e
CM
5518 u32 nritems;
5519 int ret;
a061fc8d 5520 int progress;
1a40e23b 5521 int pass = 0;
edbd8d4e 5522
1a40e23b
ZY
5523 root = root->fs_info->extent_root;
5524
5525 block_group = btrfs_lookup_block_group(info, group_start);
5526 BUG_ON(!block_group);
8f18cf13 5527
d397712b 5528 printk(KERN_INFO "btrfs relocating block group %llu flags %llu\n",
1a40e23b
ZY
5529 (unsigned long long)block_group->key.objectid,
5530 (unsigned long long)block_group->flags);
8f18cf13 5531
edbd8d4e 5532 path = btrfs_alloc_path();
1a40e23b 5533 BUG_ON(!path);
edbd8d4e 5534
1a40e23b
ZY
5535 reloc_inode = create_reloc_inode(info, block_group);
5536 BUG_ON(IS_ERR(reloc_inode));
323da79c 5537
1a40e23b 5538 __alloc_chunk_for_shrink(root, block_group, 1);
c146afad 5539 set_block_group_readonly(block_group);
323da79c 5540
1a40e23b
ZY
5541 btrfs_start_delalloc_inodes(info->tree_root);
5542 btrfs_wait_ordered_extents(info->tree_root, 0);
5543again:
d899e052 5544 skipped = 0;
edbd8d4e 5545 total_found = 0;
a061fc8d 5546 progress = 0;
1a40e23b 5547 key.objectid = block_group->key.objectid;
edbd8d4e
CM
5548 key.offset = 0;
5549 key.type = 0;
73e48b27 5550 cur_byte = key.objectid;
4313b399 5551
1a40e23b
ZY
5552 trans = btrfs_start_transaction(info->tree_root, 1);
5553 btrfs_commit_transaction(trans, info->tree_root);
ea8c2819 5554
1a40e23b
ZY
5555 mutex_lock(&root->fs_info->cleaner_mutex);
5556 btrfs_clean_old_snapshots(info->tree_root);
5557 btrfs_remove_leaf_refs(info->tree_root, (u64)-1, 1);
5558 mutex_unlock(&root->fs_info->cleaner_mutex);
ea8c2819 5559
56bec294
CM
5560 trans = btrfs_start_transaction(info->tree_root, 1);
5561 btrfs_commit_transaction(trans, info->tree_root);
5562
d397712b 5563 while (1) {
edbd8d4e
CM
5564 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5565 if (ret < 0)
5566 goto out;
7d9eb12c 5567next:
edbd8d4e 5568 leaf = path->nodes[0];
73e48b27 5569 nritems = btrfs_header_nritems(leaf);
73e48b27
Y
5570 if (path->slots[0] >= nritems) {
5571 ret = btrfs_next_leaf(root, path);
5572 if (ret < 0)
5573 goto out;
5574 if (ret == 1) {
5575 ret = 0;
5576 break;
edbd8d4e 5577 }
73e48b27
Y
5578 leaf = path->nodes[0];
5579 nritems = btrfs_header_nritems(leaf);
edbd8d4e 5580 }
73e48b27 5581
1a40e23b 5582 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
725c8463 5583
1a40e23b
ZY
5584 if (key.objectid >= block_group->key.objectid +
5585 block_group->key.offset)
8f18cf13
CM
5586 break;
5587
725c8463 5588 if (progress && need_resched()) {
725c8463 5589 btrfs_release_path(root, path);
1a40e23b 5590 cond_resched();
725c8463 5591 progress = 0;
1a40e23b 5592 continue;
725c8463
CM
5593 }
5594 progress = 1;
5595
1a40e23b
ZY
5596 if (btrfs_key_type(&key) != BTRFS_EXTENT_ITEM_KEY ||
5597 key.objectid + key.offset <= cur_byte) {
edbd8d4e 5598 path->slots[0]++;
edbd8d4e
CM
5599 goto next;
5600 }
73e48b27 5601
edbd8d4e 5602 total_found++;
1a40e23b 5603 cur_byte = key.objectid + key.offset;
edbd8d4e 5604 btrfs_release_path(root, path);
edbd8d4e 5605
1a40e23b
ZY
5606 __alloc_chunk_for_shrink(root, block_group, 0);
5607 ret = relocate_one_extent(root, path, &key, block_group,
5608 reloc_inode, pass);
5609 BUG_ON(ret < 0);
d899e052
YZ
5610 if (ret > 0)
5611 skipped++;
edbd8d4e 5612
1a40e23b
ZY
5613 key.objectid = cur_byte;
5614 key.type = 0;
5615 key.offset = 0;
edbd8d4e
CM
5616 }
5617
1a40e23b 5618 btrfs_release_path(root, path);
7d9eb12c 5619
1a40e23b
ZY
5620 if (pass == 0) {
5621 btrfs_wait_ordered_range(reloc_inode, 0, (u64)-1);
5622 invalidate_mapping_pages(reloc_inode->i_mapping, 0, -1);
8e8a1e31 5623 }
73e48b27 5624
1a40e23b 5625 if (total_found > 0) {
d397712b 5626 printk(KERN_INFO "btrfs found %llu extents in pass %d\n",
1a40e23b
ZY
5627 (unsigned long long)total_found, pass);
5628 pass++;
d899e052
YZ
5629 if (total_found == skipped && pass > 2) {
5630 iput(reloc_inode);
5631 reloc_inode = create_reloc_inode(info, block_group);
5632 pass = 0;
5633 }
1a40e23b 5634 goto again;
0f9dd46c 5635 }
0ef3e66b 5636
1a40e23b
ZY
5637 /* delete reloc_inode */
5638 iput(reloc_inode);
5639
5640 /* unpin extents in this range */
5641 trans = btrfs_start_transaction(info->tree_root, 1);
5642 btrfs_commit_transaction(trans, info->tree_root);
0ef3e66b 5643
1a40e23b
ZY
5644 spin_lock(&block_group->lock);
5645 WARN_ON(block_group->pinned > 0);
5646 WARN_ON(block_group->reserved > 0);
5647 WARN_ON(btrfs_block_group_used(&block_group->item) > 0);
5648 spin_unlock(&block_group->lock);
d2fb3437 5649 put_block_group(block_group);
1a40e23b 5650 ret = 0;
edbd8d4e 5651out:
1a40e23b 5652 btrfs_free_path(path);
edbd8d4e
CM
5653 return ret;
5654}
5655
b2950863
CH
5656static int find_first_block_group(struct btrfs_root *root,
5657 struct btrfs_path *path, struct btrfs_key *key)
0b86a832 5658{
925baedd 5659 int ret = 0;
0b86a832
CM
5660 struct btrfs_key found_key;
5661 struct extent_buffer *leaf;
5662 int slot;
edbd8d4e 5663
0b86a832
CM
5664 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
5665 if (ret < 0)
925baedd
CM
5666 goto out;
5667
d397712b 5668 while (1) {
0b86a832 5669 slot = path->slots[0];
edbd8d4e 5670 leaf = path->nodes[0];
0b86a832
CM
5671 if (slot >= btrfs_header_nritems(leaf)) {
5672 ret = btrfs_next_leaf(root, path);
5673 if (ret == 0)
5674 continue;
5675 if (ret < 0)
925baedd 5676 goto out;
0b86a832 5677 break;
edbd8d4e 5678 }
0b86a832 5679 btrfs_item_key_to_cpu(leaf, &found_key, slot);
edbd8d4e 5680
0b86a832 5681 if (found_key.objectid >= key->objectid &&
925baedd
CM
5682 found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
5683 ret = 0;
5684 goto out;
5685 }
0b86a832 5686 path->slots[0]++;
edbd8d4e 5687 }
0b86a832 5688 ret = -ENOENT;
925baedd 5689out:
0b86a832 5690 return ret;
edbd8d4e
CM
5691}
5692
1a40e23b
ZY
5693int btrfs_free_block_groups(struct btrfs_fs_info *info)
5694{
5695 struct btrfs_block_group_cache *block_group;
4184ea7f 5696 struct btrfs_space_info *space_info;
1a40e23b
ZY
5697 struct rb_node *n;
5698
1a40e23b
ZY
5699 spin_lock(&info->block_group_cache_lock);
5700 while ((n = rb_last(&info->block_group_cache_tree)) != NULL) {
5701 block_group = rb_entry(n, struct btrfs_block_group_cache,
5702 cache_node);
1a40e23b
ZY
5703 rb_erase(&block_group->cache_node,
5704 &info->block_group_cache_tree);
d899e052
YZ
5705 spin_unlock(&info->block_group_cache_lock);
5706
5707 btrfs_remove_free_space_cache(block_group);
80eb234a 5708 down_write(&block_group->space_info->groups_sem);
1a40e23b 5709 list_del(&block_group->list);
80eb234a 5710 up_write(&block_group->space_info->groups_sem);
d2fb3437
YZ
5711
5712 WARN_ON(atomic_read(&block_group->count) != 1);
1a40e23b 5713 kfree(block_group);
d899e052
YZ
5714
5715 spin_lock(&info->block_group_cache_lock);
1a40e23b
ZY
5716 }
5717 spin_unlock(&info->block_group_cache_lock);
4184ea7f
CM
5718
5719 /* now that all the block groups are freed, go through and
5720 * free all the space_info structs. This is only called during
5721 * the final stages of unmount, and so we know nobody is
5722 * using them. We call synchronize_rcu() once before we start,
5723 * just to be on the safe side.
5724 */
5725 synchronize_rcu();
5726
5727 while(!list_empty(&info->space_info)) {
5728 space_info = list_entry(info->space_info.next,
5729 struct btrfs_space_info,
5730 list);
5731
5732 list_del(&space_info->list);
5733 kfree(space_info);
5734 }
1a40e23b
ZY
5735 return 0;
5736}
5737
9078a3e1
CM
5738int btrfs_read_block_groups(struct btrfs_root *root)
5739{
5740 struct btrfs_path *path;
5741 int ret;
9078a3e1 5742 struct btrfs_block_group_cache *cache;
be744175 5743 struct btrfs_fs_info *info = root->fs_info;
6324fbf3 5744 struct btrfs_space_info *space_info;
9078a3e1
CM
5745 struct btrfs_key key;
5746 struct btrfs_key found_key;
5f39d397 5747 struct extent_buffer *leaf;
96b5179d 5748
be744175 5749 root = info->extent_root;
9078a3e1 5750 key.objectid = 0;
0b86a832 5751 key.offset = 0;
9078a3e1 5752 btrfs_set_key_type(&key, BTRFS_BLOCK_GROUP_ITEM_KEY);
9078a3e1
CM
5753 path = btrfs_alloc_path();
5754 if (!path)
5755 return -ENOMEM;
5756
d397712b 5757 while (1) {
0b86a832
CM
5758 ret = find_first_block_group(root, path, &key);
5759 if (ret > 0) {
5760 ret = 0;
5761 goto error;
9078a3e1 5762 }
0b86a832
CM
5763 if (ret != 0)
5764 goto error;
5765
5f39d397
CM
5766 leaf = path->nodes[0];
5767 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
8f18cf13 5768 cache = kzalloc(sizeof(*cache), GFP_NOFS);
9078a3e1 5769 if (!cache) {
0b86a832 5770 ret = -ENOMEM;
9078a3e1
CM
5771 break;
5772 }
3e1ad54f 5773
d2fb3437 5774 atomic_set(&cache->count, 1);
c286ac48 5775 spin_lock_init(&cache->lock);
25179201 5776 mutex_init(&cache->alloc_mutex);
ea6a478e 5777 mutex_init(&cache->cache_mutex);
0f9dd46c 5778 INIT_LIST_HEAD(&cache->list);
5f39d397
CM
5779 read_extent_buffer(leaf, &cache->item,
5780 btrfs_item_ptr_offset(leaf, path->slots[0]),
5781 sizeof(cache->item));
9078a3e1 5782 memcpy(&cache->key, &found_key, sizeof(found_key));
0b86a832 5783
9078a3e1
CM
5784 key.objectid = found_key.objectid + found_key.offset;
5785 btrfs_release_path(root, path);
0b86a832 5786 cache->flags = btrfs_block_group_flags(&cache->item);
96b5179d 5787
6324fbf3
CM
5788 ret = update_space_info(info, cache->flags, found_key.offset,
5789 btrfs_block_group_used(&cache->item),
5790 &space_info);
5791 BUG_ON(ret);
5792 cache->space_info = space_info;
80eb234a
JB
5793 down_write(&space_info->groups_sem);
5794 list_add_tail(&cache->list, &space_info->block_groups);
5795 up_write(&space_info->groups_sem);
0f9dd46c
JB
5796
5797 ret = btrfs_add_block_group_cache(root->fs_info, cache);
5798 BUG_ON(ret);
75ccf47d
CM
5799
5800 set_avail_alloc_bits(root->fs_info, cache->flags);
2b82032c
YZ
5801 if (btrfs_chunk_readonly(root, cache->key.objectid))
5802 set_block_group_readonly(cache);
9078a3e1 5803 }
0b86a832
CM
5804 ret = 0;
5805error:
9078a3e1 5806 btrfs_free_path(path);
0b86a832 5807 return ret;
9078a3e1 5808}
6324fbf3
CM
5809
5810int btrfs_make_block_group(struct btrfs_trans_handle *trans,
5811 struct btrfs_root *root, u64 bytes_used,
e17cade2 5812 u64 type, u64 chunk_objectid, u64 chunk_offset,
6324fbf3
CM
5813 u64 size)
5814{
5815 int ret;
6324fbf3
CM
5816 struct btrfs_root *extent_root;
5817 struct btrfs_block_group_cache *cache;
6324fbf3
CM
5818
5819 extent_root = root->fs_info->extent_root;
6324fbf3 5820
e02119d5
CM
5821 root->fs_info->last_trans_new_blockgroup = trans->transid;
5822
8f18cf13 5823 cache = kzalloc(sizeof(*cache), GFP_NOFS);
0f9dd46c
JB
5824 if (!cache)
5825 return -ENOMEM;
5826
e17cade2 5827 cache->key.objectid = chunk_offset;
6324fbf3 5828 cache->key.offset = size;
d2fb3437
YZ
5829 cache->key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
5830 atomic_set(&cache->count, 1);
c286ac48 5831 spin_lock_init(&cache->lock);
25179201 5832 mutex_init(&cache->alloc_mutex);
ea6a478e 5833 mutex_init(&cache->cache_mutex);
0f9dd46c 5834 INIT_LIST_HEAD(&cache->list);
0ef3e66b 5835
6324fbf3 5836 btrfs_set_block_group_used(&cache->item, bytes_used);
6324fbf3
CM
5837 btrfs_set_block_group_chunk_objectid(&cache->item, chunk_objectid);
5838 cache->flags = type;
5839 btrfs_set_block_group_flags(&cache->item, type);
5840
5841 ret = update_space_info(root->fs_info, cache->flags, size, bytes_used,
5842 &cache->space_info);
5843 BUG_ON(ret);
80eb234a
JB
5844 down_write(&cache->space_info->groups_sem);
5845 list_add_tail(&cache->list, &cache->space_info->block_groups);
5846 up_write(&cache->space_info->groups_sem);
6324fbf3 5847
0f9dd46c
JB
5848 ret = btrfs_add_block_group_cache(root->fs_info, cache);
5849 BUG_ON(ret);
c286ac48 5850
6324fbf3
CM
5851 ret = btrfs_insert_item(trans, extent_root, &cache->key, &cache->item,
5852 sizeof(cache->item));
5853 BUG_ON(ret);
5854
d18a2c44 5855 set_avail_alloc_bits(extent_root->fs_info, type);
925baedd 5856
6324fbf3
CM
5857 return 0;
5858}
1a40e23b
ZY
5859
5860int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
5861 struct btrfs_root *root, u64 group_start)
5862{
5863 struct btrfs_path *path;
5864 struct btrfs_block_group_cache *block_group;
5865 struct btrfs_key key;
5866 int ret;
5867
1a40e23b
ZY
5868 root = root->fs_info->extent_root;
5869
5870 block_group = btrfs_lookup_block_group(root->fs_info, group_start);
5871 BUG_ON(!block_group);
c146afad 5872 BUG_ON(!block_group->ro);
1a40e23b
ZY
5873
5874 memcpy(&key, &block_group->key, sizeof(key));
5875
5876 path = btrfs_alloc_path();
5877 BUG_ON(!path);
5878
3dfdb934 5879 spin_lock(&root->fs_info->block_group_cache_lock);
1a40e23b
ZY
5880 rb_erase(&block_group->cache_node,
5881 &root->fs_info->block_group_cache_tree);
3dfdb934
YZ
5882 spin_unlock(&root->fs_info->block_group_cache_lock);
5883 btrfs_remove_free_space_cache(block_group);
80eb234a 5884 down_write(&block_group->space_info->groups_sem);
1a40e23b 5885 list_del(&block_group->list);
80eb234a 5886 up_write(&block_group->space_info->groups_sem);
1a40e23b 5887
c146afad
YZ
5888 spin_lock(&block_group->space_info->lock);
5889 block_group->space_info->total_bytes -= block_group->key.offset;
5890 block_group->space_info->bytes_readonly -= block_group->key.offset;
5891 spin_unlock(&block_group->space_info->lock);
2b82032c 5892 block_group->space_info->full = 0;
c146afad 5893
d2fb3437
YZ
5894 put_block_group(block_group);
5895 put_block_group(block_group);
1a40e23b
ZY
5896
5897 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
5898 if (ret > 0)
5899 ret = -EIO;
5900 if (ret < 0)
5901 goto out;
5902
5903 ret = btrfs_del_item(trans, root, path);
5904out:
5905 btrfs_free_path(path);
5906 return ret;
5907}