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