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