Merge branch 'delayed_inode' into inode_numbers
[deliverable/linux.git] / fs / btrfs / extent-tree.c
1 /*
2 * Copyright (C) 2007 Oracle. All rights reserved.
3 *
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public
6 * License v2 as published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public
14 * License along with this program; if not, write to the
15 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16 * Boston, MA 021110-1307, USA.
17 */
18 #include <linux/sched.h>
19 #include <linux/pagemap.h>
20 #include <linux/writeback.h>
21 #include <linux/blkdev.h>
22 #include <linux/sort.h>
23 #include <linux/rcupdate.h>
24 #include <linux/kthread.h>
25 #include <linux/slab.h>
26 #include "compat.h"
27 #include "hash.h"
28 #include "ctree.h"
29 #include "disk-io.h"
30 #include "print-tree.h"
31 #include "transaction.h"
32 #include "volumes.h"
33 #include "locking.h"
34 #include "free-space-cache.h"
35
36 /* control flags for do_chunk_alloc's force field
37 * CHUNK_ALLOC_NO_FORCE means to only allocate a chunk
38 * if we really need one.
39 *
40 * CHUNK_ALLOC_FORCE means it must try to allocate one
41 *
42 * CHUNK_ALLOC_LIMITED means to only try and allocate one
43 * if we have very few chunks already allocated. This is
44 * used as part of the clustering code to help make sure
45 * we have a good pool of storage to cluster in, without
46 * filling the FS with empty chunks
47 *
48 */
49 enum {
50 CHUNK_ALLOC_NO_FORCE = 0,
51 CHUNK_ALLOC_FORCE = 1,
52 CHUNK_ALLOC_LIMITED = 2,
53 };
54
55 static int update_block_group(struct btrfs_trans_handle *trans,
56 struct btrfs_root *root,
57 u64 bytenr, u64 num_bytes, int alloc);
58 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
59 struct btrfs_root *root,
60 u64 bytenr, u64 num_bytes, u64 parent,
61 u64 root_objectid, u64 owner_objectid,
62 u64 owner_offset, int refs_to_drop,
63 struct btrfs_delayed_extent_op *extra_op);
64 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
65 struct extent_buffer *leaf,
66 struct btrfs_extent_item *ei);
67 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
68 struct btrfs_root *root,
69 u64 parent, u64 root_objectid,
70 u64 flags, u64 owner, u64 offset,
71 struct btrfs_key *ins, int ref_mod);
72 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
73 struct btrfs_root *root,
74 u64 parent, u64 root_objectid,
75 u64 flags, struct btrfs_disk_key *key,
76 int level, struct btrfs_key *ins);
77 static int do_chunk_alloc(struct btrfs_trans_handle *trans,
78 struct btrfs_root *extent_root, u64 alloc_bytes,
79 u64 flags, int force);
80 static int find_next_key(struct btrfs_path *path, int level,
81 struct btrfs_key *key);
82 static void dump_space_info(struct btrfs_space_info *info, u64 bytes,
83 int dump_block_groups);
84
85 static noinline int
86 block_group_cache_done(struct btrfs_block_group_cache *cache)
87 {
88 smp_mb();
89 return cache->cached == BTRFS_CACHE_FINISHED;
90 }
91
92 static int block_group_bits(struct btrfs_block_group_cache *cache, u64 bits)
93 {
94 return (cache->flags & bits) == bits;
95 }
96
97 void btrfs_get_block_group(struct btrfs_block_group_cache *cache)
98 {
99 atomic_inc(&cache->count);
100 }
101
102 void btrfs_put_block_group(struct btrfs_block_group_cache *cache)
103 {
104 if (atomic_dec_and_test(&cache->count)) {
105 WARN_ON(cache->pinned > 0);
106 WARN_ON(cache->reserved > 0);
107 WARN_ON(cache->reserved_pinned > 0);
108 kfree(cache->free_space_ctl);
109 kfree(cache);
110 }
111 }
112
113 /*
114 * this adds the block group to the fs_info rb tree for the block group
115 * cache
116 */
117 static int btrfs_add_block_group_cache(struct btrfs_fs_info *info,
118 struct btrfs_block_group_cache *block_group)
119 {
120 struct rb_node **p;
121 struct rb_node *parent = NULL;
122 struct btrfs_block_group_cache *cache;
123
124 spin_lock(&info->block_group_cache_lock);
125 p = &info->block_group_cache_tree.rb_node;
126
127 while (*p) {
128 parent = *p;
129 cache = rb_entry(parent, struct btrfs_block_group_cache,
130 cache_node);
131 if (block_group->key.objectid < cache->key.objectid) {
132 p = &(*p)->rb_left;
133 } else if (block_group->key.objectid > cache->key.objectid) {
134 p = &(*p)->rb_right;
135 } else {
136 spin_unlock(&info->block_group_cache_lock);
137 return -EEXIST;
138 }
139 }
140
141 rb_link_node(&block_group->cache_node, parent, p);
142 rb_insert_color(&block_group->cache_node,
143 &info->block_group_cache_tree);
144 spin_unlock(&info->block_group_cache_lock);
145
146 return 0;
147 }
148
149 /*
150 * This will return the block group at or after bytenr if contains is 0, else
151 * it will return the block group that contains the bytenr
152 */
153 static struct btrfs_block_group_cache *
154 block_group_cache_tree_search(struct btrfs_fs_info *info, u64 bytenr,
155 int contains)
156 {
157 struct btrfs_block_group_cache *cache, *ret = NULL;
158 struct rb_node *n;
159 u64 end, start;
160
161 spin_lock(&info->block_group_cache_lock);
162 n = info->block_group_cache_tree.rb_node;
163
164 while (n) {
165 cache = rb_entry(n, struct btrfs_block_group_cache,
166 cache_node);
167 end = cache->key.objectid + cache->key.offset - 1;
168 start = cache->key.objectid;
169
170 if (bytenr < start) {
171 if (!contains && (!ret || start < ret->key.objectid))
172 ret = cache;
173 n = n->rb_left;
174 } else if (bytenr > start) {
175 if (contains && bytenr <= end) {
176 ret = cache;
177 break;
178 }
179 n = n->rb_right;
180 } else {
181 ret = cache;
182 break;
183 }
184 }
185 if (ret)
186 btrfs_get_block_group(ret);
187 spin_unlock(&info->block_group_cache_lock);
188
189 return ret;
190 }
191
192 static int add_excluded_extent(struct btrfs_root *root,
193 u64 start, u64 num_bytes)
194 {
195 u64 end = start + num_bytes - 1;
196 set_extent_bits(&root->fs_info->freed_extents[0],
197 start, end, EXTENT_UPTODATE, GFP_NOFS);
198 set_extent_bits(&root->fs_info->freed_extents[1],
199 start, end, EXTENT_UPTODATE, GFP_NOFS);
200 return 0;
201 }
202
203 static void free_excluded_extents(struct btrfs_root *root,
204 struct btrfs_block_group_cache *cache)
205 {
206 u64 start, end;
207
208 start = cache->key.objectid;
209 end = start + cache->key.offset - 1;
210
211 clear_extent_bits(&root->fs_info->freed_extents[0],
212 start, end, EXTENT_UPTODATE, GFP_NOFS);
213 clear_extent_bits(&root->fs_info->freed_extents[1],
214 start, end, EXTENT_UPTODATE, GFP_NOFS);
215 }
216
217 static int exclude_super_stripes(struct btrfs_root *root,
218 struct btrfs_block_group_cache *cache)
219 {
220 u64 bytenr;
221 u64 *logical;
222 int stripe_len;
223 int i, nr, ret;
224
225 if (cache->key.objectid < BTRFS_SUPER_INFO_OFFSET) {
226 stripe_len = BTRFS_SUPER_INFO_OFFSET - cache->key.objectid;
227 cache->bytes_super += stripe_len;
228 ret = add_excluded_extent(root, cache->key.objectid,
229 stripe_len);
230 BUG_ON(ret);
231 }
232
233 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
234 bytenr = btrfs_sb_offset(i);
235 ret = btrfs_rmap_block(&root->fs_info->mapping_tree,
236 cache->key.objectid, bytenr,
237 0, &logical, &nr, &stripe_len);
238 BUG_ON(ret);
239
240 while (nr--) {
241 cache->bytes_super += stripe_len;
242 ret = add_excluded_extent(root, logical[nr],
243 stripe_len);
244 BUG_ON(ret);
245 }
246
247 kfree(logical);
248 }
249 return 0;
250 }
251
252 static struct btrfs_caching_control *
253 get_caching_control(struct btrfs_block_group_cache *cache)
254 {
255 struct btrfs_caching_control *ctl;
256
257 spin_lock(&cache->lock);
258 if (cache->cached != BTRFS_CACHE_STARTED) {
259 spin_unlock(&cache->lock);
260 return NULL;
261 }
262
263 /* We're loading it the fast way, so we don't have a caching_ctl. */
264 if (!cache->caching_ctl) {
265 spin_unlock(&cache->lock);
266 return NULL;
267 }
268
269 ctl = cache->caching_ctl;
270 atomic_inc(&ctl->count);
271 spin_unlock(&cache->lock);
272 return ctl;
273 }
274
275 static void put_caching_control(struct btrfs_caching_control *ctl)
276 {
277 if (atomic_dec_and_test(&ctl->count))
278 kfree(ctl);
279 }
280
281 /*
282 * this is only called by cache_block_group, since we could have freed extents
283 * we need to check the pinned_extents for any extents that can't be used yet
284 * since their free space will be released as soon as the transaction commits.
285 */
286 static u64 add_new_free_space(struct btrfs_block_group_cache *block_group,
287 struct btrfs_fs_info *info, u64 start, u64 end)
288 {
289 u64 extent_start, extent_end, size, total_added = 0;
290 int ret;
291
292 while (start < end) {
293 ret = find_first_extent_bit(info->pinned_extents, start,
294 &extent_start, &extent_end,
295 EXTENT_DIRTY | EXTENT_UPTODATE);
296 if (ret)
297 break;
298
299 if (extent_start <= start) {
300 start = extent_end + 1;
301 } else if (extent_start > start && extent_start < end) {
302 size = extent_start - start;
303 total_added += size;
304 ret = btrfs_add_free_space(block_group, start,
305 size);
306 BUG_ON(ret);
307 start = extent_end + 1;
308 } else {
309 break;
310 }
311 }
312
313 if (start < end) {
314 size = end - start;
315 total_added += size;
316 ret = btrfs_add_free_space(block_group, start, size);
317 BUG_ON(ret);
318 }
319
320 return total_added;
321 }
322
323 static int caching_kthread(void *data)
324 {
325 struct btrfs_block_group_cache *block_group = data;
326 struct btrfs_fs_info *fs_info = block_group->fs_info;
327 struct btrfs_caching_control *caching_ctl = block_group->caching_ctl;
328 struct btrfs_root *extent_root = fs_info->extent_root;
329 struct btrfs_path *path;
330 struct extent_buffer *leaf;
331 struct btrfs_key key;
332 u64 total_found = 0;
333 u64 last = 0;
334 u32 nritems;
335 int ret = 0;
336
337 path = btrfs_alloc_path();
338 if (!path)
339 return -ENOMEM;
340
341 last = max_t(u64, block_group->key.objectid, BTRFS_SUPER_INFO_OFFSET);
342
343 /*
344 * We don't want to deadlock with somebody trying to allocate a new
345 * extent for the extent root while also trying to search the extent
346 * root to add free space. So we skip locking and search the commit
347 * root, since its read-only
348 */
349 path->skip_locking = 1;
350 path->search_commit_root = 1;
351 path->reada = 2;
352
353 key.objectid = last;
354 key.offset = 0;
355 key.type = BTRFS_EXTENT_ITEM_KEY;
356 again:
357 mutex_lock(&caching_ctl->mutex);
358 /* need to make sure the commit_root doesn't disappear */
359 down_read(&fs_info->extent_commit_sem);
360
361 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
362 if (ret < 0)
363 goto err;
364
365 leaf = path->nodes[0];
366 nritems = btrfs_header_nritems(leaf);
367
368 while (1) {
369 smp_mb();
370 if (fs_info->closing > 1) {
371 last = (u64)-1;
372 break;
373 }
374
375 if (path->slots[0] < nritems) {
376 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
377 } else {
378 ret = find_next_key(path, 0, &key);
379 if (ret)
380 break;
381
382 caching_ctl->progress = last;
383 btrfs_release_path(extent_root, path);
384 up_read(&fs_info->extent_commit_sem);
385 mutex_unlock(&caching_ctl->mutex);
386 if (btrfs_transaction_in_commit(fs_info))
387 schedule_timeout(1);
388 else
389 cond_resched();
390 goto again;
391 }
392
393 if (key.objectid < block_group->key.objectid) {
394 path->slots[0]++;
395 continue;
396 }
397
398 if (key.objectid >= block_group->key.objectid +
399 block_group->key.offset)
400 break;
401
402 if (key.type == BTRFS_EXTENT_ITEM_KEY) {
403 total_found += add_new_free_space(block_group,
404 fs_info, last,
405 key.objectid);
406 last = key.objectid + key.offset;
407
408 if (total_found > (1024 * 1024 * 2)) {
409 total_found = 0;
410 wake_up(&caching_ctl->wait);
411 }
412 }
413 path->slots[0]++;
414 }
415 ret = 0;
416
417 total_found += add_new_free_space(block_group, fs_info, last,
418 block_group->key.objectid +
419 block_group->key.offset);
420 caching_ctl->progress = (u64)-1;
421
422 spin_lock(&block_group->lock);
423 block_group->caching_ctl = NULL;
424 block_group->cached = BTRFS_CACHE_FINISHED;
425 spin_unlock(&block_group->lock);
426
427 err:
428 btrfs_free_path(path);
429 up_read(&fs_info->extent_commit_sem);
430
431 free_excluded_extents(extent_root, block_group);
432
433 mutex_unlock(&caching_ctl->mutex);
434 wake_up(&caching_ctl->wait);
435
436 put_caching_control(caching_ctl);
437 atomic_dec(&block_group->space_info->caching_threads);
438 btrfs_put_block_group(block_group);
439
440 return 0;
441 }
442
443 static int cache_block_group(struct btrfs_block_group_cache *cache,
444 struct btrfs_trans_handle *trans,
445 struct btrfs_root *root,
446 int load_cache_only)
447 {
448 struct btrfs_fs_info *fs_info = cache->fs_info;
449 struct btrfs_caching_control *caching_ctl;
450 struct task_struct *tsk;
451 int ret = 0;
452
453 smp_mb();
454 if (cache->cached != BTRFS_CACHE_NO)
455 return 0;
456
457 /*
458 * We can't do the read from on-disk cache during a commit since we need
459 * to have the normal tree locking. Also if we are currently trying to
460 * allocate blocks for the tree root we can't do the fast caching since
461 * we likely hold important locks.
462 */
463 if (trans && (!trans->transaction->in_commit) &&
464 (root && root != root->fs_info->tree_root)) {
465 spin_lock(&cache->lock);
466 if (cache->cached != BTRFS_CACHE_NO) {
467 spin_unlock(&cache->lock);
468 return 0;
469 }
470 cache->cached = BTRFS_CACHE_STARTED;
471 spin_unlock(&cache->lock);
472
473 ret = load_free_space_cache(fs_info, cache);
474
475 spin_lock(&cache->lock);
476 if (ret == 1) {
477 cache->cached = BTRFS_CACHE_FINISHED;
478 cache->last_byte_to_unpin = (u64)-1;
479 } else {
480 cache->cached = BTRFS_CACHE_NO;
481 }
482 spin_unlock(&cache->lock);
483 if (ret == 1) {
484 free_excluded_extents(fs_info->extent_root, cache);
485 return 0;
486 }
487 }
488
489 if (load_cache_only)
490 return 0;
491
492 caching_ctl = kzalloc(sizeof(*caching_ctl), GFP_NOFS);
493 BUG_ON(!caching_ctl);
494
495 INIT_LIST_HEAD(&caching_ctl->list);
496 mutex_init(&caching_ctl->mutex);
497 init_waitqueue_head(&caching_ctl->wait);
498 caching_ctl->block_group = cache;
499 caching_ctl->progress = cache->key.objectid;
500 /* one for caching kthread, one for caching block group list */
501 atomic_set(&caching_ctl->count, 2);
502
503 spin_lock(&cache->lock);
504 if (cache->cached != BTRFS_CACHE_NO) {
505 spin_unlock(&cache->lock);
506 kfree(caching_ctl);
507 return 0;
508 }
509 cache->caching_ctl = caching_ctl;
510 cache->cached = BTRFS_CACHE_STARTED;
511 spin_unlock(&cache->lock);
512
513 down_write(&fs_info->extent_commit_sem);
514 list_add_tail(&caching_ctl->list, &fs_info->caching_block_groups);
515 up_write(&fs_info->extent_commit_sem);
516
517 atomic_inc(&cache->space_info->caching_threads);
518 btrfs_get_block_group(cache);
519
520 tsk = kthread_run(caching_kthread, cache, "btrfs-cache-%llu\n",
521 cache->key.objectid);
522 if (IS_ERR(tsk)) {
523 ret = PTR_ERR(tsk);
524 printk(KERN_ERR "error running thread %d\n", ret);
525 BUG();
526 }
527
528 return ret;
529 }
530
531 /*
532 * return the block group that starts at or after bytenr
533 */
534 static struct btrfs_block_group_cache *
535 btrfs_lookup_first_block_group(struct btrfs_fs_info *info, u64 bytenr)
536 {
537 struct btrfs_block_group_cache *cache;
538
539 cache = block_group_cache_tree_search(info, bytenr, 0);
540
541 return cache;
542 }
543
544 /*
545 * return the block group that contains the given bytenr
546 */
547 struct btrfs_block_group_cache *btrfs_lookup_block_group(
548 struct btrfs_fs_info *info,
549 u64 bytenr)
550 {
551 struct btrfs_block_group_cache *cache;
552
553 cache = block_group_cache_tree_search(info, bytenr, 1);
554
555 return cache;
556 }
557
558 static struct btrfs_space_info *__find_space_info(struct btrfs_fs_info *info,
559 u64 flags)
560 {
561 struct list_head *head = &info->space_info;
562 struct btrfs_space_info *found;
563
564 flags &= BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_SYSTEM |
565 BTRFS_BLOCK_GROUP_METADATA;
566
567 rcu_read_lock();
568 list_for_each_entry_rcu(found, head, list) {
569 if (found->flags & flags) {
570 rcu_read_unlock();
571 return found;
572 }
573 }
574 rcu_read_unlock();
575 return NULL;
576 }
577
578 /*
579 * after adding space to the filesystem, we need to clear the full flags
580 * on all the space infos.
581 */
582 void btrfs_clear_space_info_full(struct btrfs_fs_info *info)
583 {
584 struct list_head *head = &info->space_info;
585 struct btrfs_space_info *found;
586
587 rcu_read_lock();
588 list_for_each_entry_rcu(found, head, list)
589 found->full = 0;
590 rcu_read_unlock();
591 }
592
593 static u64 div_factor(u64 num, int factor)
594 {
595 if (factor == 10)
596 return num;
597 num *= factor;
598 do_div(num, 10);
599 return num;
600 }
601
602 static u64 div_factor_fine(u64 num, int factor)
603 {
604 if (factor == 100)
605 return num;
606 num *= factor;
607 do_div(num, 100);
608 return num;
609 }
610
611 u64 btrfs_find_block_group(struct btrfs_root *root,
612 u64 search_start, u64 search_hint, int owner)
613 {
614 struct btrfs_block_group_cache *cache;
615 u64 used;
616 u64 last = max(search_hint, search_start);
617 u64 group_start = 0;
618 int full_search = 0;
619 int factor = 9;
620 int wrapped = 0;
621 again:
622 while (1) {
623 cache = btrfs_lookup_first_block_group(root->fs_info, last);
624 if (!cache)
625 break;
626
627 spin_lock(&cache->lock);
628 last = cache->key.objectid + cache->key.offset;
629 used = btrfs_block_group_used(&cache->item);
630
631 if ((full_search || !cache->ro) &&
632 block_group_bits(cache, BTRFS_BLOCK_GROUP_METADATA)) {
633 if (used + cache->pinned + cache->reserved <
634 div_factor(cache->key.offset, factor)) {
635 group_start = cache->key.objectid;
636 spin_unlock(&cache->lock);
637 btrfs_put_block_group(cache);
638 goto found;
639 }
640 }
641 spin_unlock(&cache->lock);
642 btrfs_put_block_group(cache);
643 cond_resched();
644 }
645 if (!wrapped) {
646 last = search_start;
647 wrapped = 1;
648 goto again;
649 }
650 if (!full_search && factor < 10) {
651 last = search_start;
652 full_search = 1;
653 factor = 10;
654 goto again;
655 }
656 found:
657 return group_start;
658 }
659
660 /* simple helper to search for an existing extent at a given offset */
661 int btrfs_lookup_extent(struct btrfs_root *root, u64 start, u64 len)
662 {
663 int ret;
664 struct btrfs_key key;
665 struct btrfs_path *path;
666
667 path = btrfs_alloc_path();
668 BUG_ON(!path);
669 key.objectid = start;
670 key.offset = len;
671 btrfs_set_key_type(&key, BTRFS_EXTENT_ITEM_KEY);
672 ret = btrfs_search_slot(NULL, root->fs_info->extent_root, &key, path,
673 0, 0);
674 btrfs_free_path(path);
675 return ret;
676 }
677
678 /*
679 * helper function to lookup reference count and flags of extent.
680 *
681 * the head node for delayed ref is used to store the sum of all the
682 * reference count modifications queued up in the rbtree. the head
683 * node may also store the extent flags to set. This way you can check
684 * to see what the reference count and extent flags would be if all of
685 * the delayed refs are not processed.
686 */
687 int btrfs_lookup_extent_info(struct btrfs_trans_handle *trans,
688 struct btrfs_root *root, u64 bytenr,
689 u64 num_bytes, u64 *refs, u64 *flags)
690 {
691 struct btrfs_delayed_ref_head *head;
692 struct btrfs_delayed_ref_root *delayed_refs;
693 struct btrfs_path *path;
694 struct btrfs_extent_item *ei;
695 struct extent_buffer *leaf;
696 struct btrfs_key key;
697 u32 item_size;
698 u64 num_refs;
699 u64 extent_flags;
700 int ret;
701
702 path = btrfs_alloc_path();
703 if (!path)
704 return -ENOMEM;
705
706 key.objectid = bytenr;
707 key.type = BTRFS_EXTENT_ITEM_KEY;
708 key.offset = num_bytes;
709 if (!trans) {
710 path->skip_locking = 1;
711 path->search_commit_root = 1;
712 }
713 again:
714 ret = btrfs_search_slot(trans, root->fs_info->extent_root,
715 &key, path, 0, 0);
716 if (ret < 0)
717 goto out_free;
718
719 if (ret == 0) {
720 leaf = path->nodes[0];
721 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
722 if (item_size >= sizeof(*ei)) {
723 ei = btrfs_item_ptr(leaf, path->slots[0],
724 struct btrfs_extent_item);
725 num_refs = btrfs_extent_refs(leaf, ei);
726 extent_flags = btrfs_extent_flags(leaf, ei);
727 } else {
728 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
729 struct btrfs_extent_item_v0 *ei0;
730 BUG_ON(item_size != sizeof(*ei0));
731 ei0 = btrfs_item_ptr(leaf, path->slots[0],
732 struct btrfs_extent_item_v0);
733 num_refs = btrfs_extent_refs_v0(leaf, ei0);
734 /* FIXME: this isn't correct for data */
735 extent_flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
736 #else
737 BUG();
738 #endif
739 }
740 BUG_ON(num_refs == 0);
741 } else {
742 num_refs = 0;
743 extent_flags = 0;
744 ret = 0;
745 }
746
747 if (!trans)
748 goto out;
749
750 delayed_refs = &trans->transaction->delayed_refs;
751 spin_lock(&delayed_refs->lock);
752 head = btrfs_find_delayed_ref_head(trans, bytenr);
753 if (head) {
754 if (!mutex_trylock(&head->mutex)) {
755 atomic_inc(&head->node.refs);
756 spin_unlock(&delayed_refs->lock);
757
758 btrfs_release_path(root->fs_info->extent_root, path);
759
760 mutex_lock(&head->mutex);
761 mutex_unlock(&head->mutex);
762 btrfs_put_delayed_ref(&head->node);
763 goto again;
764 }
765 if (head->extent_op && head->extent_op->update_flags)
766 extent_flags |= head->extent_op->flags_to_set;
767 else
768 BUG_ON(num_refs == 0);
769
770 num_refs += head->node.ref_mod;
771 mutex_unlock(&head->mutex);
772 }
773 spin_unlock(&delayed_refs->lock);
774 out:
775 WARN_ON(num_refs == 0);
776 if (refs)
777 *refs = num_refs;
778 if (flags)
779 *flags = extent_flags;
780 out_free:
781 btrfs_free_path(path);
782 return ret;
783 }
784
785 /*
786 * Back reference rules. Back refs have three main goals:
787 *
788 * 1) differentiate between all holders of references to an extent so that
789 * when a reference is dropped we can make sure it was a valid reference
790 * before freeing the extent.
791 *
792 * 2) Provide enough information to quickly find the holders of an extent
793 * if we notice a given block is corrupted or bad.
794 *
795 * 3) Make it easy to migrate blocks for FS shrinking or storage pool
796 * maintenance. This is actually the same as #2, but with a slightly
797 * different use case.
798 *
799 * There are two kinds of back refs. The implicit back refs is optimized
800 * for pointers in non-shared tree blocks. For a given pointer in a block,
801 * back refs of this kind provide information about the block's owner tree
802 * and the pointer's key. These information allow us to find the block by
803 * b-tree searching. The full back refs is for pointers in tree blocks not
804 * referenced by their owner trees. The location of tree block is recorded
805 * in the back refs. Actually the full back refs is generic, and can be
806 * used in all cases the implicit back refs is used. The major shortcoming
807 * of the full back refs is its overhead. Every time a tree block gets
808 * COWed, we have to update back refs entry for all pointers in it.
809 *
810 * For a newly allocated tree block, we use implicit back refs for
811 * pointers in it. This means most tree related operations only involve
812 * implicit back refs. For a tree block created in old transaction, the
813 * only way to drop a reference to it is COW it. So we can detect the
814 * event that tree block loses its owner tree's reference and do the
815 * back refs conversion.
816 *
817 * When a tree block is COW'd through a tree, there are four cases:
818 *
819 * The reference count of the block is one and the tree is the block's
820 * owner tree. Nothing to do in this case.
821 *
822 * The reference count of the block is one and the tree is not the
823 * block's owner tree. In this case, full back refs is used for pointers
824 * in the block. Remove these full back refs, add implicit back refs for
825 * every pointers in the new block.
826 *
827 * The reference count of the block is greater than one and the tree is
828 * the block's owner tree. In this case, implicit back refs is used for
829 * pointers in the block. Add full back refs for every pointers in the
830 * block, increase lower level extents' reference counts. The original
831 * implicit back refs are entailed to the new block.
832 *
833 * The reference count of the block is greater than one and the tree is
834 * not the block's owner tree. Add implicit back refs for every pointer in
835 * the new block, increase lower level extents' reference count.
836 *
837 * Back Reference Key composing:
838 *
839 * The key objectid corresponds to the first byte in the extent,
840 * The key type is used to differentiate between types of back refs.
841 * There are different meanings of the key offset for different types
842 * of back refs.
843 *
844 * File extents can be referenced by:
845 *
846 * - multiple snapshots, subvolumes, or different generations in one subvol
847 * - different files inside a single subvolume
848 * - different offsets inside a file (bookend extents in file.c)
849 *
850 * The extent ref structure for the implicit back refs has fields for:
851 *
852 * - Objectid of the subvolume root
853 * - objectid of the file holding the reference
854 * - original offset in the file
855 * - how many bookend extents
856 *
857 * The key offset for the implicit back refs is hash of the first
858 * three fields.
859 *
860 * The extent ref structure for the full back refs has field for:
861 *
862 * - number of pointers in the tree leaf
863 *
864 * The key offset for the implicit back refs is the first byte of
865 * the tree leaf
866 *
867 * When a file extent is allocated, The implicit back refs is used.
868 * the fields are filled in:
869 *
870 * (root_key.objectid, inode objectid, offset in file, 1)
871 *
872 * When a file extent is removed file truncation, we find the
873 * corresponding implicit back refs and check the following fields:
874 *
875 * (btrfs_header_owner(leaf), inode objectid, offset in file)
876 *
877 * Btree extents can be referenced by:
878 *
879 * - Different subvolumes
880 *
881 * Both the implicit back refs and the full back refs for tree blocks
882 * only consist of key. The key offset for the implicit back refs is
883 * objectid of block's owner tree. The key offset for the full back refs
884 * is the first byte of parent block.
885 *
886 * When implicit back refs is used, information about the lowest key and
887 * level of the tree block are required. These information are stored in
888 * tree block info structure.
889 */
890
891 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
892 static int convert_extent_item_v0(struct btrfs_trans_handle *trans,
893 struct btrfs_root *root,
894 struct btrfs_path *path,
895 u64 owner, u32 extra_size)
896 {
897 struct btrfs_extent_item *item;
898 struct btrfs_extent_item_v0 *ei0;
899 struct btrfs_extent_ref_v0 *ref0;
900 struct btrfs_tree_block_info *bi;
901 struct extent_buffer *leaf;
902 struct btrfs_key key;
903 struct btrfs_key found_key;
904 u32 new_size = sizeof(*item);
905 u64 refs;
906 int ret;
907
908 leaf = path->nodes[0];
909 BUG_ON(btrfs_item_size_nr(leaf, path->slots[0]) != sizeof(*ei0));
910
911 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
912 ei0 = btrfs_item_ptr(leaf, path->slots[0],
913 struct btrfs_extent_item_v0);
914 refs = btrfs_extent_refs_v0(leaf, ei0);
915
916 if (owner == (u64)-1) {
917 while (1) {
918 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
919 ret = btrfs_next_leaf(root, path);
920 if (ret < 0)
921 return ret;
922 BUG_ON(ret > 0);
923 leaf = path->nodes[0];
924 }
925 btrfs_item_key_to_cpu(leaf, &found_key,
926 path->slots[0]);
927 BUG_ON(key.objectid != found_key.objectid);
928 if (found_key.type != BTRFS_EXTENT_REF_V0_KEY) {
929 path->slots[0]++;
930 continue;
931 }
932 ref0 = btrfs_item_ptr(leaf, path->slots[0],
933 struct btrfs_extent_ref_v0);
934 owner = btrfs_ref_objectid_v0(leaf, ref0);
935 break;
936 }
937 }
938 btrfs_release_path(root, path);
939
940 if (owner < BTRFS_FIRST_FREE_OBJECTID)
941 new_size += sizeof(*bi);
942
943 new_size -= sizeof(*ei0);
944 ret = btrfs_search_slot(trans, root, &key, path,
945 new_size + extra_size, 1);
946 if (ret < 0)
947 return ret;
948 BUG_ON(ret);
949
950 ret = btrfs_extend_item(trans, root, path, new_size);
951 BUG_ON(ret);
952
953 leaf = path->nodes[0];
954 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
955 btrfs_set_extent_refs(leaf, item, refs);
956 /* FIXME: get real generation */
957 btrfs_set_extent_generation(leaf, item, 0);
958 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
959 btrfs_set_extent_flags(leaf, item,
960 BTRFS_EXTENT_FLAG_TREE_BLOCK |
961 BTRFS_BLOCK_FLAG_FULL_BACKREF);
962 bi = (struct btrfs_tree_block_info *)(item + 1);
963 /* FIXME: get first key of the block */
964 memset_extent_buffer(leaf, 0, (unsigned long)bi, sizeof(*bi));
965 btrfs_set_tree_block_level(leaf, bi, (int)owner);
966 } else {
967 btrfs_set_extent_flags(leaf, item, BTRFS_EXTENT_FLAG_DATA);
968 }
969 btrfs_mark_buffer_dirty(leaf);
970 return 0;
971 }
972 #endif
973
974 static u64 hash_extent_data_ref(u64 root_objectid, u64 owner, u64 offset)
975 {
976 u32 high_crc = ~(u32)0;
977 u32 low_crc = ~(u32)0;
978 __le64 lenum;
979
980 lenum = cpu_to_le64(root_objectid);
981 high_crc = crc32c(high_crc, &lenum, sizeof(lenum));
982 lenum = cpu_to_le64(owner);
983 low_crc = crc32c(low_crc, &lenum, sizeof(lenum));
984 lenum = cpu_to_le64(offset);
985 low_crc = crc32c(low_crc, &lenum, sizeof(lenum));
986
987 return ((u64)high_crc << 31) ^ (u64)low_crc;
988 }
989
990 static u64 hash_extent_data_ref_item(struct extent_buffer *leaf,
991 struct btrfs_extent_data_ref *ref)
992 {
993 return hash_extent_data_ref(btrfs_extent_data_ref_root(leaf, ref),
994 btrfs_extent_data_ref_objectid(leaf, ref),
995 btrfs_extent_data_ref_offset(leaf, ref));
996 }
997
998 static int match_extent_data_ref(struct extent_buffer *leaf,
999 struct btrfs_extent_data_ref *ref,
1000 u64 root_objectid, u64 owner, u64 offset)
1001 {
1002 if (btrfs_extent_data_ref_root(leaf, ref) != root_objectid ||
1003 btrfs_extent_data_ref_objectid(leaf, ref) != owner ||
1004 btrfs_extent_data_ref_offset(leaf, ref) != offset)
1005 return 0;
1006 return 1;
1007 }
1008
1009 static noinline int lookup_extent_data_ref(struct btrfs_trans_handle *trans,
1010 struct btrfs_root *root,
1011 struct btrfs_path *path,
1012 u64 bytenr, u64 parent,
1013 u64 root_objectid,
1014 u64 owner, u64 offset)
1015 {
1016 struct btrfs_key key;
1017 struct btrfs_extent_data_ref *ref;
1018 struct extent_buffer *leaf;
1019 u32 nritems;
1020 int ret;
1021 int recow;
1022 int err = -ENOENT;
1023
1024 key.objectid = bytenr;
1025 if (parent) {
1026 key.type = BTRFS_SHARED_DATA_REF_KEY;
1027 key.offset = parent;
1028 } else {
1029 key.type = BTRFS_EXTENT_DATA_REF_KEY;
1030 key.offset = hash_extent_data_ref(root_objectid,
1031 owner, offset);
1032 }
1033 again:
1034 recow = 0;
1035 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1036 if (ret < 0) {
1037 err = ret;
1038 goto fail;
1039 }
1040
1041 if (parent) {
1042 if (!ret)
1043 return 0;
1044 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1045 key.type = BTRFS_EXTENT_REF_V0_KEY;
1046 btrfs_release_path(root, path);
1047 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1048 if (ret < 0) {
1049 err = ret;
1050 goto fail;
1051 }
1052 if (!ret)
1053 return 0;
1054 #endif
1055 goto fail;
1056 }
1057
1058 leaf = path->nodes[0];
1059 nritems = btrfs_header_nritems(leaf);
1060 while (1) {
1061 if (path->slots[0] >= nritems) {
1062 ret = btrfs_next_leaf(root, path);
1063 if (ret < 0)
1064 err = ret;
1065 if (ret)
1066 goto fail;
1067
1068 leaf = path->nodes[0];
1069 nritems = btrfs_header_nritems(leaf);
1070 recow = 1;
1071 }
1072
1073 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1074 if (key.objectid != bytenr ||
1075 key.type != BTRFS_EXTENT_DATA_REF_KEY)
1076 goto fail;
1077
1078 ref = btrfs_item_ptr(leaf, path->slots[0],
1079 struct btrfs_extent_data_ref);
1080
1081 if (match_extent_data_ref(leaf, ref, root_objectid,
1082 owner, offset)) {
1083 if (recow) {
1084 btrfs_release_path(root, path);
1085 goto again;
1086 }
1087 err = 0;
1088 break;
1089 }
1090 path->slots[0]++;
1091 }
1092 fail:
1093 return err;
1094 }
1095
1096 static noinline int insert_extent_data_ref(struct btrfs_trans_handle *trans,
1097 struct btrfs_root *root,
1098 struct btrfs_path *path,
1099 u64 bytenr, u64 parent,
1100 u64 root_objectid, u64 owner,
1101 u64 offset, int refs_to_add)
1102 {
1103 struct btrfs_key key;
1104 struct extent_buffer *leaf;
1105 u32 size;
1106 u32 num_refs;
1107 int ret;
1108
1109 key.objectid = bytenr;
1110 if (parent) {
1111 key.type = BTRFS_SHARED_DATA_REF_KEY;
1112 key.offset = parent;
1113 size = sizeof(struct btrfs_shared_data_ref);
1114 } else {
1115 key.type = BTRFS_EXTENT_DATA_REF_KEY;
1116 key.offset = hash_extent_data_ref(root_objectid,
1117 owner, offset);
1118 size = sizeof(struct btrfs_extent_data_ref);
1119 }
1120
1121 ret = btrfs_insert_empty_item(trans, root, path, &key, size);
1122 if (ret && ret != -EEXIST)
1123 goto fail;
1124
1125 leaf = path->nodes[0];
1126 if (parent) {
1127 struct btrfs_shared_data_ref *ref;
1128 ref = btrfs_item_ptr(leaf, path->slots[0],
1129 struct btrfs_shared_data_ref);
1130 if (ret == 0) {
1131 btrfs_set_shared_data_ref_count(leaf, ref, refs_to_add);
1132 } else {
1133 num_refs = btrfs_shared_data_ref_count(leaf, ref);
1134 num_refs += refs_to_add;
1135 btrfs_set_shared_data_ref_count(leaf, ref, num_refs);
1136 }
1137 } else {
1138 struct btrfs_extent_data_ref *ref;
1139 while (ret == -EEXIST) {
1140 ref = btrfs_item_ptr(leaf, path->slots[0],
1141 struct btrfs_extent_data_ref);
1142 if (match_extent_data_ref(leaf, ref, root_objectid,
1143 owner, offset))
1144 break;
1145 btrfs_release_path(root, path);
1146 key.offset++;
1147 ret = btrfs_insert_empty_item(trans, root, path, &key,
1148 size);
1149 if (ret && ret != -EEXIST)
1150 goto fail;
1151
1152 leaf = path->nodes[0];
1153 }
1154 ref = btrfs_item_ptr(leaf, path->slots[0],
1155 struct btrfs_extent_data_ref);
1156 if (ret == 0) {
1157 btrfs_set_extent_data_ref_root(leaf, ref,
1158 root_objectid);
1159 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
1160 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
1161 btrfs_set_extent_data_ref_count(leaf, ref, refs_to_add);
1162 } else {
1163 num_refs = btrfs_extent_data_ref_count(leaf, ref);
1164 num_refs += refs_to_add;
1165 btrfs_set_extent_data_ref_count(leaf, ref, num_refs);
1166 }
1167 }
1168 btrfs_mark_buffer_dirty(leaf);
1169 ret = 0;
1170 fail:
1171 btrfs_release_path(root, path);
1172 return ret;
1173 }
1174
1175 static noinline int remove_extent_data_ref(struct btrfs_trans_handle *trans,
1176 struct btrfs_root *root,
1177 struct btrfs_path *path,
1178 int refs_to_drop)
1179 {
1180 struct btrfs_key key;
1181 struct btrfs_extent_data_ref *ref1 = NULL;
1182 struct btrfs_shared_data_ref *ref2 = NULL;
1183 struct extent_buffer *leaf;
1184 u32 num_refs = 0;
1185 int ret = 0;
1186
1187 leaf = path->nodes[0];
1188 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1189
1190 if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1191 ref1 = btrfs_item_ptr(leaf, path->slots[0],
1192 struct btrfs_extent_data_ref);
1193 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1194 } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1195 ref2 = btrfs_item_ptr(leaf, path->slots[0],
1196 struct btrfs_shared_data_ref);
1197 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1198 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1199 } else if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
1200 struct btrfs_extent_ref_v0 *ref0;
1201 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1202 struct btrfs_extent_ref_v0);
1203 num_refs = btrfs_ref_count_v0(leaf, ref0);
1204 #endif
1205 } else {
1206 BUG();
1207 }
1208
1209 BUG_ON(num_refs < refs_to_drop);
1210 num_refs -= refs_to_drop;
1211
1212 if (num_refs == 0) {
1213 ret = btrfs_del_item(trans, root, path);
1214 } else {
1215 if (key.type == BTRFS_EXTENT_DATA_REF_KEY)
1216 btrfs_set_extent_data_ref_count(leaf, ref1, num_refs);
1217 else if (key.type == BTRFS_SHARED_DATA_REF_KEY)
1218 btrfs_set_shared_data_ref_count(leaf, ref2, num_refs);
1219 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1220 else {
1221 struct btrfs_extent_ref_v0 *ref0;
1222 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1223 struct btrfs_extent_ref_v0);
1224 btrfs_set_ref_count_v0(leaf, ref0, num_refs);
1225 }
1226 #endif
1227 btrfs_mark_buffer_dirty(leaf);
1228 }
1229 return ret;
1230 }
1231
1232 static noinline u32 extent_data_ref_count(struct btrfs_root *root,
1233 struct btrfs_path *path,
1234 struct btrfs_extent_inline_ref *iref)
1235 {
1236 struct btrfs_key key;
1237 struct extent_buffer *leaf;
1238 struct btrfs_extent_data_ref *ref1;
1239 struct btrfs_shared_data_ref *ref2;
1240 u32 num_refs = 0;
1241
1242 leaf = path->nodes[0];
1243 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1244 if (iref) {
1245 if (btrfs_extent_inline_ref_type(leaf, iref) ==
1246 BTRFS_EXTENT_DATA_REF_KEY) {
1247 ref1 = (struct btrfs_extent_data_ref *)(&iref->offset);
1248 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1249 } else {
1250 ref2 = (struct btrfs_shared_data_ref *)(iref + 1);
1251 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1252 }
1253 } else if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1254 ref1 = btrfs_item_ptr(leaf, path->slots[0],
1255 struct btrfs_extent_data_ref);
1256 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1257 } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1258 ref2 = btrfs_item_ptr(leaf, path->slots[0],
1259 struct btrfs_shared_data_ref);
1260 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1261 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1262 } else if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
1263 struct btrfs_extent_ref_v0 *ref0;
1264 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1265 struct btrfs_extent_ref_v0);
1266 num_refs = btrfs_ref_count_v0(leaf, ref0);
1267 #endif
1268 } else {
1269 WARN_ON(1);
1270 }
1271 return num_refs;
1272 }
1273
1274 static noinline int lookup_tree_block_ref(struct btrfs_trans_handle *trans,
1275 struct btrfs_root *root,
1276 struct btrfs_path *path,
1277 u64 bytenr, u64 parent,
1278 u64 root_objectid)
1279 {
1280 struct btrfs_key key;
1281 int ret;
1282
1283 key.objectid = bytenr;
1284 if (parent) {
1285 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1286 key.offset = parent;
1287 } else {
1288 key.type = BTRFS_TREE_BLOCK_REF_KEY;
1289 key.offset = root_objectid;
1290 }
1291
1292 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1293 if (ret > 0)
1294 ret = -ENOENT;
1295 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1296 if (ret == -ENOENT && parent) {
1297 btrfs_release_path(root, path);
1298 key.type = BTRFS_EXTENT_REF_V0_KEY;
1299 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1300 if (ret > 0)
1301 ret = -ENOENT;
1302 }
1303 #endif
1304 return ret;
1305 }
1306
1307 static noinline int insert_tree_block_ref(struct btrfs_trans_handle *trans,
1308 struct btrfs_root *root,
1309 struct btrfs_path *path,
1310 u64 bytenr, u64 parent,
1311 u64 root_objectid)
1312 {
1313 struct btrfs_key key;
1314 int ret;
1315
1316 key.objectid = bytenr;
1317 if (parent) {
1318 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1319 key.offset = parent;
1320 } else {
1321 key.type = BTRFS_TREE_BLOCK_REF_KEY;
1322 key.offset = root_objectid;
1323 }
1324
1325 ret = btrfs_insert_empty_item(trans, root, path, &key, 0);
1326 btrfs_release_path(root, path);
1327 return ret;
1328 }
1329
1330 static inline int extent_ref_type(u64 parent, u64 owner)
1331 {
1332 int type;
1333 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1334 if (parent > 0)
1335 type = BTRFS_SHARED_BLOCK_REF_KEY;
1336 else
1337 type = BTRFS_TREE_BLOCK_REF_KEY;
1338 } else {
1339 if (parent > 0)
1340 type = BTRFS_SHARED_DATA_REF_KEY;
1341 else
1342 type = BTRFS_EXTENT_DATA_REF_KEY;
1343 }
1344 return type;
1345 }
1346
1347 static int find_next_key(struct btrfs_path *path, int level,
1348 struct btrfs_key *key)
1349
1350 {
1351 for (; level < BTRFS_MAX_LEVEL; level++) {
1352 if (!path->nodes[level])
1353 break;
1354 if (path->slots[level] + 1 >=
1355 btrfs_header_nritems(path->nodes[level]))
1356 continue;
1357 if (level == 0)
1358 btrfs_item_key_to_cpu(path->nodes[level], key,
1359 path->slots[level] + 1);
1360 else
1361 btrfs_node_key_to_cpu(path->nodes[level], key,
1362 path->slots[level] + 1);
1363 return 0;
1364 }
1365 return 1;
1366 }
1367
1368 /*
1369 * look for inline back ref. if back ref is found, *ref_ret is set
1370 * to the address of inline back ref, and 0 is returned.
1371 *
1372 * if back ref isn't found, *ref_ret is set to the address where it
1373 * should be inserted, and -ENOENT is returned.
1374 *
1375 * if insert is true and there are too many inline back refs, the path
1376 * points to the extent item, and -EAGAIN is returned.
1377 *
1378 * NOTE: inline back refs are ordered in the same way that back ref
1379 * items in the tree are ordered.
1380 */
1381 static noinline_for_stack
1382 int lookup_inline_extent_backref(struct btrfs_trans_handle *trans,
1383 struct btrfs_root *root,
1384 struct btrfs_path *path,
1385 struct btrfs_extent_inline_ref **ref_ret,
1386 u64 bytenr, u64 num_bytes,
1387 u64 parent, u64 root_objectid,
1388 u64 owner, u64 offset, int insert)
1389 {
1390 struct btrfs_key key;
1391 struct extent_buffer *leaf;
1392 struct btrfs_extent_item *ei;
1393 struct btrfs_extent_inline_ref *iref;
1394 u64 flags;
1395 u64 item_size;
1396 unsigned long ptr;
1397 unsigned long end;
1398 int extra_size;
1399 int type;
1400 int want;
1401 int ret;
1402 int err = 0;
1403
1404 key.objectid = bytenr;
1405 key.type = BTRFS_EXTENT_ITEM_KEY;
1406 key.offset = num_bytes;
1407
1408 want = extent_ref_type(parent, owner);
1409 if (insert) {
1410 extra_size = btrfs_extent_inline_ref_size(want);
1411 path->keep_locks = 1;
1412 } else
1413 extra_size = -1;
1414 ret = btrfs_search_slot(trans, root, &key, path, extra_size, 1);
1415 if (ret < 0) {
1416 err = ret;
1417 goto out;
1418 }
1419 BUG_ON(ret);
1420
1421 leaf = path->nodes[0];
1422 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1423 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1424 if (item_size < sizeof(*ei)) {
1425 if (!insert) {
1426 err = -ENOENT;
1427 goto out;
1428 }
1429 ret = convert_extent_item_v0(trans, root, path, owner,
1430 extra_size);
1431 if (ret < 0) {
1432 err = ret;
1433 goto out;
1434 }
1435 leaf = path->nodes[0];
1436 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1437 }
1438 #endif
1439 BUG_ON(item_size < sizeof(*ei));
1440
1441 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1442 flags = btrfs_extent_flags(leaf, ei);
1443
1444 ptr = (unsigned long)(ei + 1);
1445 end = (unsigned long)ei + item_size;
1446
1447 if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
1448 ptr += sizeof(struct btrfs_tree_block_info);
1449 BUG_ON(ptr > end);
1450 } else {
1451 BUG_ON(!(flags & BTRFS_EXTENT_FLAG_DATA));
1452 }
1453
1454 err = -ENOENT;
1455 while (1) {
1456 if (ptr >= end) {
1457 WARN_ON(ptr > end);
1458 break;
1459 }
1460 iref = (struct btrfs_extent_inline_ref *)ptr;
1461 type = btrfs_extent_inline_ref_type(leaf, iref);
1462 if (want < type)
1463 break;
1464 if (want > type) {
1465 ptr += btrfs_extent_inline_ref_size(type);
1466 continue;
1467 }
1468
1469 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1470 struct btrfs_extent_data_ref *dref;
1471 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1472 if (match_extent_data_ref(leaf, dref, root_objectid,
1473 owner, offset)) {
1474 err = 0;
1475 break;
1476 }
1477 if (hash_extent_data_ref_item(leaf, dref) <
1478 hash_extent_data_ref(root_objectid, owner, offset))
1479 break;
1480 } else {
1481 u64 ref_offset;
1482 ref_offset = btrfs_extent_inline_ref_offset(leaf, iref);
1483 if (parent > 0) {
1484 if (parent == ref_offset) {
1485 err = 0;
1486 break;
1487 }
1488 if (ref_offset < parent)
1489 break;
1490 } else {
1491 if (root_objectid == ref_offset) {
1492 err = 0;
1493 break;
1494 }
1495 if (ref_offset < root_objectid)
1496 break;
1497 }
1498 }
1499 ptr += btrfs_extent_inline_ref_size(type);
1500 }
1501 if (err == -ENOENT && insert) {
1502 if (item_size + extra_size >=
1503 BTRFS_MAX_EXTENT_ITEM_SIZE(root)) {
1504 err = -EAGAIN;
1505 goto out;
1506 }
1507 /*
1508 * To add new inline back ref, we have to make sure
1509 * there is no corresponding back ref item.
1510 * For simplicity, we just do not add new inline back
1511 * ref if there is any kind of item for this block
1512 */
1513 if (find_next_key(path, 0, &key) == 0 &&
1514 key.objectid == bytenr &&
1515 key.type < BTRFS_BLOCK_GROUP_ITEM_KEY) {
1516 err = -EAGAIN;
1517 goto out;
1518 }
1519 }
1520 *ref_ret = (struct btrfs_extent_inline_ref *)ptr;
1521 out:
1522 if (insert) {
1523 path->keep_locks = 0;
1524 btrfs_unlock_up_safe(path, 1);
1525 }
1526 return err;
1527 }
1528
1529 /*
1530 * helper to add new inline back ref
1531 */
1532 static noinline_for_stack
1533 int setup_inline_extent_backref(struct btrfs_trans_handle *trans,
1534 struct btrfs_root *root,
1535 struct btrfs_path *path,
1536 struct btrfs_extent_inline_ref *iref,
1537 u64 parent, u64 root_objectid,
1538 u64 owner, u64 offset, int refs_to_add,
1539 struct btrfs_delayed_extent_op *extent_op)
1540 {
1541 struct extent_buffer *leaf;
1542 struct btrfs_extent_item *ei;
1543 unsigned long ptr;
1544 unsigned long end;
1545 unsigned long item_offset;
1546 u64 refs;
1547 int size;
1548 int type;
1549 int ret;
1550
1551 leaf = path->nodes[0];
1552 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1553 item_offset = (unsigned long)iref - (unsigned long)ei;
1554
1555 type = extent_ref_type(parent, owner);
1556 size = btrfs_extent_inline_ref_size(type);
1557
1558 ret = btrfs_extend_item(trans, root, path, size);
1559 BUG_ON(ret);
1560
1561 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1562 refs = btrfs_extent_refs(leaf, ei);
1563 refs += refs_to_add;
1564 btrfs_set_extent_refs(leaf, ei, refs);
1565 if (extent_op)
1566 __run_delayed_extent_op(extent_op, leaf, ei);
1567
1568 ptr = (unsigned long)ei + item_offset;
1569 end = (unsigned long)ei + btrfs_item_size_nr(leaf, path->slots[0]);
1570 if (ptr < end - size)
1571 memmove_extent_buffer(leaf, ptr + size, ptr,
1572 end - size - ptr);
1573
1574 iref = (struct btrfs_extent_inline_ref *)ptr;
1575 btrfs_set_extent_inline_ref_type(leaf, iref, type);
1576 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1577 struct btrfs_extent_data_ref *dref;
1578 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1579 btrfs_set_extent_data_ref_root(leaf, dref, root_objectid);
1580 btrfs_set_extent_data_ref_objectid(leaf, dref, owner);
1581 btrfs_set_extent_data_ref_offset(leaf, dref, offset);
1582 btrfs_set_extent_data_ref_count(leaf, dref, refs_to_add);
1583 } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1584 struct btrfs_shared_data_ref *sref;
1585 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1586 btrfs_set_shared_data_ref_count(leaf, sref, refs_to_add);
1587 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1588 } else if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
1589 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1590 } else {
1591 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
1592 }
1593 btrfs_mark_buffer_dirty(leaf);
1594 return 0;
1595 }
1596
1597 static int lookup_extent_backref(struct btrfs_trans_handle *trans,
1598 struct btrfs_root *root,
1599 struct btrfs_path *path,
1600 struct btrfs_extent_inline_ref **ref_ret,
1601 u64 bytenr, u64 num_bytes, u64 parent,
1602 u64 root_objectid, u64 owner, u64 offset)
1603 {
1604 int ret;
1605
1606 ret = lookup_inline_extent_backref(trans, root, path, ref_ret,
1607 bytenr, num_bytes, parent,
1608 root_objectid, owner, offset, 0);
1609 if (ret != -ENOENT)
1610 return ret;
1611
1612 btrfs_release_path(root, path);
1613 *ref_ret = NULL;
1614
1615 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1616 ret = lookup_tree_block_ref(trans, root, path, bytenr, parent,
1617 root_objectid);
1618 } else {
1619 ret = lookup_extent_data_ref(trans, root, path, bytenr, parent,
1620 root_objectid, owner, offset);
1621 }
1622 return ret;
1623 }
1624
1625 /*
1626 * helper to update/remove inline back ref
1627 */
1628 static noinline_for_stack
1629 int update_inline_extent_backref(struct btrfs_trans_handle *trans,
1630 struct btrfs_root *root,
1631 struct btrfs_path *path,
1632 struct btrfs_extent_inline_ref *iref,
1633 int refs_to_mod,
1634 struct btrfs_delayed_extent_op *extent_op)
1635 {
1636 struct extent_buffer *leaf;
1637 struct btrfs_extent_item *ei;
1638 struct btrfs_extent_data_ref *dref = NULL;
1639 struct btrfs_shared_data_ref *sref = NULL;
1640 unsigned long ptr;
1641 unsigned long end;
1642 u32 item_size;
1643 int size;
1644 int type;
1645 int ret;
1646 u64 refs;
1647
1648 leaf = path->nodes[0];
1649 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1650 refs = btrfs_extent_refs(leaf, ei);
1651 WARN_ON(refs_to_mod < 0 && refs + refs_to_mod <= 0);
1652 refs += refs_to_mod;
1653 btrfs_set_extent_refs(leaf, ei, refs);
1654 if (extent_op)
1655 __run_delayed_extent_op(extent_op, leaf, ei);
1656
1657 type = btrfs_extent_inline_ref_type(leaf, iref);
1658
1659 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1660 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1661 refs = btrfs_extent_data_ref_count(leaf, dref);
1662 } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1663 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1664 refs = btrfs_shared_data_ref_count(leaf, sref);
1665 } else {
1666 refs = 1;
1667 BUG_ON(refs_to_mod != -1);
1668 }
1669
1670 BUG_ON(refs_to_mod < 0 && refs < -refs_to_mod);
1671 refs += refs_to_mod;
1672
1673 if (refs > 0) {
1674 if (type == BTRFS_EXTENT_DATA_REF_KEY)
1675 btrfs_set_extent_data_ref_count(leaf, dref, refs);
1676 else
1677 btrfs_set_shared_data_ref_count(leaf, sref, refs);
1678 } else {
1679 size = btrfs_extent_inline_ref_size(type);
1680 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1681 ptr = (unsigned long)iref;
1682 end = (unsigned long)ei + item_size;
1683 if (ptr + size < end)
1684 memmove_extent_buffer(leaf, ptr, ptr + size,
1685 end - ptr - size);
1686 item_size -= size;
1687 ret = btrfs_truncate_item(trans, root, path, item_size, 1);
1688 BUG_ON(ret);
1689 }
1690 btrfs_mark_buffer_dirty(leaf);
1691 return 0;
1692 }
1693
1694 static noinline_for_stack
1695 int insert_inline_extent_backref(struct btrfs_trans_handle *trans,
1696 struct btrfs_root *root,
1697 struct btrfs_path *path,
1698 u64 bytenr, u64 num_bytes, u64 parent,
1699 u64 root_objectid, u64 owner,
1700 u64 offset, int refs_to_add,
1701 struct btrfs_delayed_extent_op *extent_op)
1702 {
1703 struct btrfs_extent_inline_ref *iref;
1704 int ret;
1705
1706 ret = lookup_inline_extent_backref(trans, root, path, &iref,
1707 bytenr, num_bytes, parent,
1708 root_objectid, owner, offset, 1);
1709 if (ret == 0) {
1710 BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID);
1711 ret = update_inline_extent_backref(trans, root, path, iref,
1712 refs_to_add, extent_op);
1713 } else if (ret == -ENOENT) {
1714 ret = setup_inline_extent_backref(trans, root, path, iref,
1715 parent, root_objectid,
1716 owner, offset, refs_to_add,
1717 extent_op);
1718 }
1719 return ret;
1720 }
1721
1722 static int insert_extent_backref(struct btrfs_trans_handle *trans,
1723 struct btrfs_root *root,
1724 struct btrfs_path *path,
1725 u64 bytenr, u64 parent, u64 root_objectid,
1726 u64 owner, u64 offset, int refs_to_add)
1727 {
1728 int ret;
1729 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1730 BUG_ON(refs_to_add != 1);
1731 ret = insert_tree_block_ref(trans, root, path, bytenr,
1732 parent, root_objectid);
1733 } else {
1734 ret = insert_extent_data_ref(trans, root, path, bytenr,
1735 parent, root_objectid,
1736 owner, offset, refs_to_add);
1737 }
1738 return ret;
1739 }
1740
1741 static int remove_extent_backref(struct btrfs_trans_handle *trans,
1742 struct btrfs_root *root,
1743 struct btrfs_path *path,
1744 struct btrfs_extent_inline_ref *iref,
1745 int refs_to_drop, int is_data)
1746 {
1747 int ret;
1748
1749 BUG_ON(!is_data && refs_to_drop != 1);
1750 if (iref) {
1751 ret = update_inline_extent_backref(trans, root, path, iref,
1752 -refs_to_drop, NULL);
1753 } else if (is_data) {
1754 ret = remove_extent_data_ref(trans, root, path, refs_to_drop);
1755 } else {
1756 ret = btrfs_del_item(trans, root, path);
1757 }
1758 return ret;
1759 }
1760
1761 static int btrfs_issue_discard(struct block_device *bdev,
1762 u64 start, u64 len)
1763 {
1764 return blkdev_issue_discard(bdev, start >> 9, len >> 9, GFP_NOFS, 0);
1765 }
1766
1767 static int btrfs_discard_extent(struct btrfs_root *root, u64 bytenr,
1768 u64 num_bytes, u64 *actual_bytes)
1769 {
1770 int ret;
1771 u64 discarded_bytes = 0;
1772 struct btrfs_multi_bio *multi = NULL;
1773
1774
1775 /* Tell the block device(s) that the sectors can be discarded */
1776 ret = btrfs_map_block(&root->fs_info->mapping_tree, REQ_DISCARD,
1777 bytenr, &num_bytes, &multi, 0);
1778 if (!ret) {
1779 struct btrfs_bio_stripe *stripe = multi->stripes;
1780 int i;
1781
1782
1783 for (i = 0; i < multi->num_stripes; i++, stripe++) {
1784 ret = btrfs_issue_discard(stripe->dev->bdev,
1785 stripe->physical,
1786 stripe->length);
1787 if (!ret)
1788 discarded_bytes += stripe->length;
1789 else if (ret != -EOPNOTSUPP)
1790 break;
1791 }
1792 kfree(multi);
1793 }
1794 if (discarded_bytes && ret == -EOPNOTSUPP)
1795 ret = 0;
1796
1797 if (actual_bytes)
1798 *actual_bytes = discarded_bytes;
1799
1800
1801 return ret;
1802 }
1803
1804 int btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
1805 struct btrfs_root *root,
1806 u64 bytenr, u64 num_bytes, u64 parent,
1807 u64 root_objectid, u64 owner, u64 offset)
1808 {
1809 int ret;
1810 BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID &&
1811 root_objectid == BTRFS_TREE_LOG_OBJECTID);
1812
1813 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1814 ret = btrfs_add_delayed_tree_ref(trans, bytenr, num_bytes,
1815 parent, root_objectid, (int)owner,
1816 BTRFS_ADD_DELAYED_REF, NULL);
1817 } else {
1818 ret = btrfs_add_delayed_data_ref(trans, bytenr, num_bytes,
1819 parent, root_objectid, owner, offset,
1820 BTRFS_ADD_DELAYED_REF, NULL);
1821 }
1822 return ret;
1823 }
1824
1825 static int __btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
1826 struct btrfs_root *root,
1827 u64 bytenr, u64 num_bytes,
1828 u64 parent, u64 root_objectid,
1829 u64 owner, u64 offset, int refs_to_add,
1830 struct btrfs_delayed_extent_op *extent_op)
1831 {
1832 struct btrfs_path *path;
1833 struct extent_buffer *leaf;
1834 struct btrfs_extent_item *item;
1835 u64 refs;
1836 int ret;
1837 int err = 0;
1838
1839 path = btrfs_alloc_path();
1840 if (!path)
1841 return -ENOMEM;
1842
1843 path->reada = 1;
1844 path->leave_spinning = 1;
1845 /* this will setup the path even if it fails to insert the back ref */
1846 ret = insert_inline_extent_backref(trans, root->fs_info->extent_root,
1847 path, bytenr, num_bytes, parent,
1848 root_objectid, owner, offset,
1849 refs_to_add, extent_op);
1850 if (ret == 0)
1851 goto out;
1852
1853 if (ret != -EAGAIN) {
1854 err = ret;
1855 goto out;
1856 }
1857
1858 leaf = path->nodes[0];
1859 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1860 refs = btrfs_extent_refs(leaf, item);
1861 btrfs_set_extent_refs(leaf, item, refs + refs_to_add);
1862 if (extent_op)
1863 __run_delayed_extent_op(extent_op, leaf, item);
1864
1865 btrfs_mark_buffer_dirty(leaf);
1866 btrfs_release_path(root->fs_info->extent_root, path);
1867
1868 path->reada = 1;
1869 path->leave_spinning = 1;
1870
1871 /* now insert the actual backref */
1872 ret = insert_extent_backref(trans, root->fs_info->extent_root,
1873 path, bytenr, parent, root_objectid,
1874 owner, offset, refs_to_add);
1875 BUG_ON(ret);
1876 out:
1877 btrfs_free_path(path);
1878 return err;
1879 }
1880
1881 static int run_delayed_data_ref(struct btrfs_trans_handle *trans,
1882 struct btrfs_root *root,
1883 struct btrfs_delayed_ref_node *node,
1884 struct btrfs_delayed_extent_op *extent_op,
1885 int insert_reserved)
1886 {
1887 int ret = 0;
1888 struct btrfs_delayed_data_ref *ref;
1889 struct btrfs_key ins;
1890 u64 parent = 0;
1891 u64 ref_root = 0;
1892 u64 flags = 0;
1893
1894 ins.objectid = node->bytenr;
1895 ins.offset = node->num_bytes;
1896 ins.type = BTRFS_EXTENT_ITEM_KEY;
1897
1898 ref = btrfs_delayed_node_to_data_ref(node);
1899 if (node->type == BTRFS_SHARED_DATA_REF_KEY)
1900 parent = ref->parent;
1901 else
1902 ref_root = ref->root;
1903
1904 if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
1905 if (extent_op) {
1906 BUG_ON(extent_op->update_key);
1907 flags |= extent_op->flags_to_set;
1908 }
1909 ret = alloc_reserved_file_extent(trans, root,
1910 parent, ref_root, flags,
1911 ref->objectid, ref->offset,
1912 &ins, node->ref_mod);
1913 } else if (node->action == BTRFS_ADD_DELAYED_REF) {
1914 ret = __btrfs_inc_extent_ref(trans, root, node->bytenr,
1915 node->num_bytes, parent,
1916 ref_root, ref->objectid,
1917 ref->offset, node->ref_mod,
1918 extent_op);
1919 } else if (node->action == BTRFS_DROP_DELAYED_REF) {
1920 ret = __btrfs_free_extent(trans, root, node->bytenr,
1921 node->num_bytes, parent,
1922 ref_root, ref->objectid,
1923 ref->offset, node->ref_mod,
1924 extent_op);
1925 } else {
1926 BUG();
1927 }
1928 return ret;
1929 }
1930
1931 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
1932 struct extent_buffer *leaf,
1933 struct btrfs_extent_item *ei)
1934 {
1935 u64 flags = btrfs_extent_flags(leaf, ei);
1936 if (extent_op->update_flags) {
1937 flags |= extent_op->flags_to_set;
1938 btrfs_set_extent_flags(leaf, ei, flags);
1939 }
1940
1941 if (extent_op->update_key) {
1942 struct btrfs_tree_block_info *bi;
1943 BUG_ON(!(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK));
1944 bi = (struct btrfs_tree_block_info *)(ei + 1);
1945 btrfs_set_tree_block_key(leaf, bi, &extent_op->key);
1946 }
1947 }
1948
1949 static int run_delayed_extent_op(struct btrfs_trans_handle *trans,
1950 struct btrfs_root *root,
1951 struct btrfs_delayed_ref_node *node,
1952 struct btrfs_delayed_extent_op *extent_op)
1953 {
1954 struct btrfs_key key;
1955 struct btrfs_path *path;
1956 struct btrfs_extent_item *ei;
1957 struct extent_buffer *leaf;
1958 u32 item_size;
1959 int ret;
1960 int err = 0;
1961
1962 path = btrfs_alloc_path();
1963 if (!path)
1964 return -ENOMEM;
1965
1966 key.objectid = node->bytenr;
1967 key.type = BTRFS_EXTENT_ITEM_KEY;
1968 key.offset = node->num_bytes;
1969
1970 path->reada = 1;
1971 path->leave_spinning = 1;
1972 ret = btrfs_search_slot(trans, root->fs_info->extent_root, &key,
1973 path, 0, 1);
1974 if (ret < 0) {
1975 err = ret;
1976 goto out;
1977 }
1978 if (ret > 0) {
1979 err = -EIO;
1980 goto out;
1981 }
1982
1983 leaf = path->nodes[0];
1984 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1985 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1986 if (item_size < sizeof(*ei)) {
1987 ret = convert_extent_item_v0(trans, root->fs_info->extent_root,
1988 path, (u64)-1, 0);
1989 if (ret < 0) {
1990 err = ret;
1991 goto out;
1992 }
1993 leaf = path->nodes[0];
1994 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1995 }
1996 #endif
1997 BUG_ON(item_size < sizeof(*ei));
1998 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1999 __run_delayed_extent_op(extent_op, leaf, ei);
2000
2001 btrfs_mark_buffer_dirty(leaf);
2002 out:
2003 btrfs_free_path(path);
2004 return err;
2005 }
2006
2007 static int run_delayed_tree_ref(struct btrfs_trans_handle *trans,
2008 struct btrfs_root *root,
2009 struct btrfs_delayed_ref_node *node,
2010 struct btrfs_delayed_extent_op *extent_op,
2011 int insert_reserved)
2012 {
2013 int ret = 0;
2014 struct btrfs_delayed_tree_ref *ref;
2015 struct btrfs_key ins;
2016 u64 parent = 0;
2017 u64 ref_root = 0;
2018
2019 ins.objectid = node->bytenr;
2020 ins.offset = node->num_bytes;
2021 ins.type = BTRFS_EXTENT_ITEM_KEY;
2022
2023 ref = btrfs_delayed_node_to_tree_ref(node);
2024 if (node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2025 parent = ref->parent;
2026 else
2027 ref_root = ref->root;
2028
2029 BUG_ON(node->ref_mod != 1);
2030 if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
2031 BUG_ON(!extent_op || !extent_op->update_flags ||
2032 !extent_op->update_key);
2033 ret = alloc_reserved_tree_block(trans, root,
2034 parent, ref_root,
2035 extent_op->flags_to_set,
2036 &extent_op->key,
2037 ref->level, &ins);
2038 } else if (node->action == BTRFS_ADD_DELAYED_REF) {
2039 ret = __btrfs_inc_extent_ref(trans, root, node->bytenr,
2040 node->num_bytes, parent, ref_root,
2041 ref->level, 0, 1, extent_op);
2042 } else if (node->action == BTRFS_DROP_DELAYED_REF) {
2043 ret = __btrfs_free_extent(trans, root, node->bytenr,
2044 node->num_bytes, parent, ref_root,
2045 ref->level, 0, 1, extent_op);
2046 } else {
2047 BUG();
2048 }
2049 return ret;
2050 }
2051
2052 /* helper function to actually process a single delayed ref entry */
2053 static int run_one_delayed_ref(struct btrfs_trans_handle *trans,
2054 struct btrfs_root *root,
2055 struct btrfs_delayed_ref_node *node,
2056 struct btrfs_delayed_extent_op *extent_op,
2057 int insert_reserved)
2058 {
2059 int ret;
2060 if (btrfs_delayed_ref_is_head(node)) {
2061 struct btrfs_delayed_ref_head *head;
2062 /*
2063 * we've hit the end of the chain and we were supposed
2064 * to insert this extent into the tree. But, it got
2065 * deleted before we ever needed to insert it, so all
2066 * we have to do is clean up the accounting
2067 */
2068 BUG_ON(extent_op);
2069 head = btrfs_delayed_node_to_head(node);
2070 if (insert_reserved) {
2071 btrfs_pin_extent(root, node->bytenr,
2072 node->num_bytes, 1);
2073 if (head->is_data) {
2074 ret = btrfs_del_csums(trans, root,
2075 node->bytenr,
2076 node->num_bytes);
2077 BUG_ON(ret);
2078 }
2079 }
2080 mutex_unlock(&head->mutex);
2081 return 0;
2082 }
2083
2084 if (node->type == BTRFS_TREE_BLOCK_REF_KEY ||
2085 node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2086 ret = run_delayed_tree_ref(trans, root, node, extent_op,
2087 insert_reserved);
2088 else if (node->type == BTRFS_EXTENT_DATA_REF_KEY ||
2089 node->type == BTRFS_SHARED_DATA_REF_KEY)
2090 ret = run_delayed_data_ref(trans, root, node, extent_op,
2091 insert_reserved);
2092 else
2093 BUG();
2094 return ret;
2095 }
2096
2097 static noinline struct btrfs_delayed_ref_node *
2098 select_delayed_ref(struct btrfs_delayed_ref_head *head)
2099 {
2100 struct rb_node *node;
2101 struct btrfs_delayed_ref_node *ref;
2102 int action = BTRFS_ADD_DELAYED_REF;
2103 again:
2104 /*
2105 * select delayed ref of type BTRFS_ADD_DELAYED_REF first.
2106 * this prevents ref count from going down to zero when
2107 * there still are pending delayed ref.
2108 */
2109 node = rb_prev(&head->node.rb_node);
2110 while (1) {
2111 if (!node)
2112 break;
2113 ref = rb_entry(node, struct btrfs_delayed_ref_node,
2114 rb_node);
2115 if (ref->bytenr != head->node.bytenr)
2116 break;
2117 if (ref->action == action)
2118 return ref;
2119 node = rb_prev(node);
2120 }
2121 if (action == BTRFS_ADD_DELAYED_REF) {
2122 action = BTRFS_DROP_DELAYED_REF;
2123 goto again;
2124 }
2125 return NULL;
2126 }
2127
2128 static noinline int run_clustered_refs(struct btrfs_trans_handle *trans,
2129 struct btrfs_root *root,
2130 struct list_head *cluster)
2131 {
2132 struct btrfs_delayed_ref_root *delayed_refs;
2133 struct btrfs_delayed_ref_node *ref;
2134 struct btrfs_delayed_ref_head *locked_ref = NULL;
2135 struct btrfs_delayed_extent_op *extent_op;
2136 int ret;
2137 int count = 0;
2138 int must_insert_reserved = 0;
2139
2140 delayed_refs = &trans->transaction->delayed_refs;
2141 while (1) {
2142 if (!locked_ref) {
2143 /* pick a new head ref from the cluster list */
2144 if (list_empty(cluster))
2145 break;
2146
2147 locked_ref = list_entry(cluster->next,
2148 struct btrfs_delayed_ref_head, cluster);
2149
2150 /* grab the lock that says we are going to process
2151 * all the refs for this head */
2152 ret = btrfs_delayed_ref_lock(trans, locked_ref);
2153
2154 /*
2155 * we may have dropped the spin lock to get the head
2156 * mutex lock, and that might have given someone else
2157 * time to free the head. If that's true, it has been
2158 * removed from our list and we can move on.
2159 */
2160 if (ret == -EAGAIN) {
2161 locked_ref = NULL;
2162 count++;
2163 continue;
2164 }
2165 }
2166
2167 /*
2168 * record the must insert reserved flag before we
2169 * drop the spin lock.
2170 */
2171 must_insert_reserved = locked_ref->must_insert_reserved;
2172 locked_ref->must_insert_reserved = 0;
2173
2174 extent_op = locked_ref->extent_op;
2175 locked_ref->extent_op = NULL;
2176
2177 /*
2178 * locked_ref is the head node, so we have to go one
2179 * node back for any delayed ref updates
2180 */
2181 ref = select_delayed_ref(locked_ref);
2182 if (!ref) {
2183 /* All delayed refs have been processed, Go ahead
2184 * and send the head node to run_one_delayed_ref,
2185 * so that any accounting fixes can happen
2186 */
2187 ref = &locked_ref->node;
2188
2189 if (extent_op && must_insert_reserved) {
2190 kfree(extent_op);
2191 extent_op = NULL;
2192 }
2193
2194 if (extent_op) {
2195 spin_unlock(&delayed_refs->lock);
2196
2197 ret = run_delayed_extent_op(trans, root,
2198 ref, extent_op);
2199 BUG_ON(ret);
2200 kfree(extent_op);
2201
2202 cond_resched();
2203 spin_lock(&delayed_refs->lock);
2204 continue;
2205 }
2206
2207 list_del_init(&locked_ref->cluster);
2208 locked_ref = NULL;
2209 }
2210
2211 ref->in_tree = 0;
2212 rb_erase(&ref->rb_node, &delayed_refs->root);
2213 delayed_refs->num_entries--;
2214
2215 spin_unlock(&delayed_refs->lock);
2216
2217 ret = run_one_delayed_ref(trans, root, ref, extent_op,
2218 must_insert_reserved);
2219 BUG_ON(ret);
2220
2221 btrfs_put_delayed_ref(ref);
2222 kfree(extent_op);
2223 count++;
2224
2225 cond_resched();
2226 spin_lock(&delayed_refs->lock);
2227 }
2228 return count;
2229 }
2230
2231 /*
2232 * this starts processing the delayed reference count updates and
2233 * extent insertions we have queued up so far. count can be
2234 * 0, which means to process everything in the tree at the start
2235 * of the run (but not newly added entries), or it can be some target
2236 * number you'd like to process.
2237 */
2238 int btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2239 struct btrfs_root *root, unsigned long count)
2240 {
2241 struct rb_node *node;
2242 struct btrfs_delayed_ref_root *delayed_refs;
2243 struct btrfs_delayed_ref_node *ref;
2244 struct list_head cluster;
2245 int ret;
2246 int run_all = count == (unsigned long)-1;
2247 int run_most = 0;
2248
2249 if (root == root->fs_info->extent_root)
2250 root = root->fs_info->tree_root;
2251
2252 delayed_refs = &trans->transaction->delayed_refs;
2253 INIT_LIST_HEAD(&cluster);
2254 again:
2255 spin_lock(&delayed_refs->lock);
2256 if (count == 0) {
2257 count = delayed_refs->num_entries * 2;
2258 run_most = 1;
2259 }
2260 while (1) {
2261 if (!(run_all || run_most) &&
2262 delayed_refs->num_heads_ready < 64)
2263 break;
2264
2265 /*
2266 * go find something we can process in the rbtree. We start at
2267 * the beginning of the tree, and then build a cluster
2268 * of refs to process starting at the first one we are able to
2269 * lock
2270 */
2271 ret = btrfs_find_ref_cluster(trans, &cluster,
2272 delayed_refs->run_delayed_start);
2273 if (ret)
2274 break;
2275
2276 ret = run_clustered_refs(trans, root, &cluster);
2277 BUG_ON(ret < 0);
2278
2279 count -= min_t(unsigned long, ret, count);
2280
2281 if (count == 0)
2282 break;
2283 }
2284
2285 if (run_all) {
2286 node = rb_first(&delayed_refs->root);
2287 if (!node)
2288 goto out;
2289 count = (unsigned long)-1;
2290
2291 while (node) {
2292 ref = rb_entry(node, struct btrfs_delayed_ref_node,
2293 rb_node);
2294 if (btrfs_delayed_ref_is_head(ref)) {
2295 struct btrfs_delayed_ref_head *head;
2296
2297 head = btrfs_delayed_node_to_head(ref);
2298 atomic_inc(&ref->refs);
2299
2300 spin_unlock(&delayed_refs->lock);
2301 mutex_lock(&head->mutex);
2302 mutex_unlock(&head->mutex);
2303
2304 btrfs_put_delayed_ref(ref);
2305 cond_resched();
2306 goto again;
2307 }
2308 node = rb_next(node);
2309 }
2310 spin_unlock(&delayed_refs->lock);
2311 schedule_timeout(1);
2312 goto again;
2313 }
2314 out:
2315 spin_unlock(&delayed_refs->lock);
2316 return 0;
2317 }
2318
2319 int btrfs_set_disk_extent_flags(struct btrfs_trans_handle *trans,
2320 struct btrfs_root *root,
2321 u64 bytenr, u64 num_bytes, u64 flags,
2322 int is_data)
2323 {
2324 struct btrfs_delayed_extent_op *extent_op;
2325 int ret;
2326
2327 extent_op = kmalloc(sizeof(*extent_op), GFP_NOFS);
2328 if (!extent_op)
2329 return -ENOMEM;
2330
2331 extent_op->flags_to_set = flags;
2332 extent_op->update_flags = 1;
2333 extent_op->update_key = 0;
2334 extent_op->is_data = is_data ? 1 : 0;
2335
2336 ret = btrfs_add_delayed_extent_op(trans, bytenr, num_bytes, extent_op);
2337 if (ret)
2338 kfree(extent_op);
2339 return ret;
2340 }
2341
2342 static noinline int check_delayed_ref(struct btrfs_trans_handle *trans,
2343 struct btrfs_root *root,
2344 struct btrfs_path *path,
2345 u64 objectid, u64 offset, u64 bytenr)
2346 {
2347 struct btrfs_delayed_ref_head *head;
2348 struct btrfs_delayed_ref_node *ref;
2349 struct btrfs_delayed_data_ref *data_ref;
2350 struct btrfs_delayed_ref_root *delayed_refs;
2351 struct rb_node *node;
2352 int ret = 0;
2353
2354 ret = -ENOENT;
2355 delayed_refs = &trans->transaction->delayed_refs;
2356 spin_lock(&delayed_refs->lock);
2357 head = btrfs_find_delayed_ref_head(trans, bytenr);
2358 if (!head)
2359 goto out;
2360
2361 if (!mutex_trylock(&head->mutex)) {
2362 atomic_inc(&head->node.refs);
2363 spin_unlock(&delayed_refs->lock);
2364
2365 btrfs_release_path(root->fs_info->extent_root, path);
2366
2367 mutex_lock(&head->mutex);
2368 mutex_unlock(&head->mutex);
2369 btrfs_put_delayed_ref(&head->node);
2370 return -EAGAIN;
2371 }
2372
2373 node = rb_prev(&head->node.rb_node);
2374 if (!node)
2375 goto out_unlock;
2376
2377 ref = rb_entry(node, struct btrfs_delayed_ref_node, rb_node);
2378
2379 if (ref->bytenr != bytenr)
2380 goto out_unlock;
2381
2382 ret = 1;
2383 if (ref->type != BTRFS_EXTENT_DATA_REF_KEY)
2384 goto out_unlock;
2385
2386 data_ref = btrfs_delayed_node_to_data_ref(ref);
2387
2388 node = rb_prev(node);
2389 if (node) {
2390 ref = rb_entry(node, struct btrfs_delayed_ref_node, rb_node);
2391 if (ref->bytenr == bytenr)
2392 goto out_unlock;
2393 }
2394
2395 if (data_ref->root != root->root_key.objectid ||
2396 data_ref->objectid != objectid || data_ref->offset != offset)
2397 goto out_unlock;
2398
2399 ret = 0;
2400 out_unlock:
2401 mutex_unlock(&head->mutex);
2402 out:
2403 spin_unlock(&delayed_refs->lock);
2404 return ret;
2405 }
2406
2407 static noinline int check_committed_ref(struct btrfs_trans_handle *trans,
2408 struct btrfs_root *root,
2409 struct btrfs_path *path,
2410 u64 objectid, u64 offset, u64 bytenr)
2411 {
2412 struct btrfs_root *extent_root = root->fs_info->extent_root;
2413 struct extent_buffer *leaf;
2414 struct btrfs_extent_data_ref *ref;
2415 struct btrfs_extent_inline_ref *iref;
2416 struct btrfs_extent_item *ei;
2417 struct btrfs_key key;
2418 u32 item_size;
2419 int ret;
2420
2421 key.objectid = bytenr;
2422 key.offset = (u64)-1;
2423 key.type = BTRFS_EXTENT_ITEM_KEY;
2424
2425 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
2426 if (ret < 0)
2427 goto out;
2428 BUG_ON(ret == 0);
2429
2430 ret = -ENOENT;
2431 if (path->slots[0] == 0)
2432 goto out;
2433
2434 path->slots[0]--;
2435 leaf = path->nodes[0];
2436 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2437
2438 if (key.objectid != bytenr || key.type != BTRFS_EXTENT_ITEM_KEY)
2439 goto out;
2440
2441 ret = 1;
2442 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2443 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
2444 if (item_size < sizeof(*ei)) {
2445 WARN_ON(item_size != sizeof(struct btrfs_extent_item_v0));
2446 goto out;
2447 }
2448 #endif
2449 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2450
2451 if (item_size != sizeof(*ei) +
2452 btrfs_extent_inline_ref_size(BTRFS_EXTENT_DATA_REF_KEY))
2453 goto out;
2454
2455 if (btrfs_extent_generation(leaf, ei) <=
2456 btrfs_root_last_snapshot(&root->root_item))
2457 goto out;
2458
2459 iref = (struct btrfs_extent_inline_ref *)(ei + 1);
2460 if (btrfs_extent_inline_ref_type(leaf, iref) !=
2461 BTRFS_EXTENT_DATA_REF_KEY)
2462 goto out;
2463
2464 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
2465 if (btrfs_extent_refs(leaf, ei) !=
2466 btrfs_extent_data_ref_count(leaf, ref) ||
2467 btrfs_extent_data_ref_root(leaf, ref) !=
2468 root->root_key.objectid ||
2469 btrfs_extent_data_ref_objectid(leaf, ref) != objectid ||
2470 btrfs_extent_data_ref_offset(leaf, ref) != offset)
2471 goto out;
2472
2473 ret = 0;
2474 out:
2475 return ret;
2476 }
2477
2478 int btrfs_cross_ref_exist(struct btrfs_trans_handle *trans,
2479 struct btrfs_root *root,
2480 u64 objectid, u64 offset, u64 bytenr)
2481 {
2482 struct btrfs_path *path;
2483 int ret;
2484 int ret2;
2485
2486 path = btrfs_alloc_path();
2487 if (!path)
2488 return -ENOENT;
2489
2490 do {
2491 ret = check_committed_ref(trans, root, path, objectid,
2492 offset, bytenr);
2493 if (ret && ret != -ENOENT)
2494 goto out;
2495
2496 ret2 = check_delayed_ref(trans, root, path, objectid,
2497 offset, bytenr);
2498 } while (ret2 == -EAGAIN);
2499
2500 if (ret2 && ret2 != -ENOENT) {
2501 ret = ret2;
2502 goto out;
2503 }
2504
2505 if (ret != -ENOENT || ret2 != -ENOENT)
2506 ret = 0;
2507 out:
2508 btrfs_free_path(path);
2509 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2510 WARN_ON(ret > 0);
2511 return ret;
2512 }
2513
2514 #if 0
2515 int btrfs_cache_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2516 struct extent_buffer *buf, u32 nr_extents)
2517 {
2518 struct btrfs_key key;
2519 struct btrfs_file_extent_item *fi;
2520 u64 root_gen;
2521 u32 nritems;
2522 int i;
2523 int level;
2524 int ret = 0;
2525 int shared = 0;
2526
2527 if (!root->ref_cows)
2528 return 0;
2529
2530 if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
2531 shared = 0;
2532 root_gen = root->root_key.offset;
2533 } else {
2534 shared = 1;
2535 root_gen = trans->transid - 1;
2536 }
2537
2538 level = btrfs_header_level(buf);
2539 nritems = btrfs_header_nritems(buf);
2540
2541 if (level == 0) {
2542 struct btrfs_leaf_ref *ref;
2543 struct btrfs_extent_info *info;
2544
2545 ref = btrfs_alloc_leaf_ref(root, nr_extents);
2546 if (!ref) {
2547 ret = -ENOMEM;
2548 goto out;
2549 }
2550
2551 ref->root_gen = root_gen;
2552 ref->bytenr = buf->start;
2553 ref->owner = btrfs_header_owner(buf);
2554 ref->generation = btrfs_header_generation(buf);
2555 ref->nritems = nr_extents;
2556 info = ref->extents;
2557
2558 for (i = 0; nr_extents > 0 && i < nritems; i++) {
2559 u64 disk_bytenr;
2560 btrfs_item_key_to_cpu(buf, &key, i);
2561 if (btrfs_key_type(&key) != BTRFS_EXTENT_DATA_KEY)
2562 continue;
2563 fi = btrfs_item_ptr(buf, i,
2564 struct btrfs_file_extent_item);
2565 if (btrfs_file_extent_type(buf, fi) ==
2566 BTRFS_FILE_EXTENT_INLINE)
2567 continue;
2568 disk_bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
2569 if (disk_bytenr == 0)
2570 continue;
2571
2572 info->bytenr = disk_bytenr;
2573 info->num_bytes =
2574 btrfs_file_extent_disk_num_bytes(buf, fi);
2575 info->objectid = key.objectid;
2576 info->offset = key.offset;
2577 info++;
2578 }
2579
2580 ret = btrfs_add_leaf_ref(root, ref, shared);
2581 if (ret == -EEXIST && shared) {
2582 struct btrfs_leaf_ref *old;
2583 old = btrfs_lookup_leaf_ref(root, ref->bytenr);
2584 BUG_ON(!old);
2585 btrfs_remove_leaf_ref(root, old);
2586 btrfs_free_leaf_ref(root, old);
2587 ret = btrfs_add_leaf_ref(root, ref, shared);
2588 }
2589 WARN_ON(ret);
2590 btrfs_free_leaf_ref(root, ref);
2591 }
2592 out:
2593 return ret;
2594 }
2595
2596 /* when a block goes through cow, we update the reference counts of
2597 * everything that block points to. The internal pointers of the block
2598 * can be in just about any order, and it is likely to have clusters of
2599 * things that are close together and clusters of things that are not.
2600 *
2601 * To help reduce the seeks that come with updating all of these reference
2602 * counts, sort them by byte number before actual updates are done.
2603 *
2604 * struct refsort is used to match byte number to slot in the btree block.
2605 * we sort based on the byte number and then use the slot to actually
2606 * find the item.
2607 *
2608 * struct refsort is smaller than strcut btrfs_item and smaller than
2609 * struct btrfs_key_ptr. Since we're currently limited to the page size
2610 * for a btree block, there's no way for a kmalloc of refsorts for a
2611 * single node to be bigger than a page.
2612 */
2613 struct refsort {
2614 u64 bytenr;
2615 u32 slot;
2616 };
2617
2618 /*
2619 * for passing into sort()
2620 */
2621 static int refsort_cmp(const void *a_void, const void *b_void)
2622 {
2623 const struct refsort *a = a_void;
2624 const struct refsort *b = b_void;
2625
2626 if (a->bytenr < b->bytenr)
2627 return -1;
2628 if (a->bytenr > b->bytenr)
2629 return 1;
2630 return 0;
2631 }
2632 #endif
2633
2634 static int __btrfs_mod_ref(struct btrfs_trans_handle *trans,
2635 struct btrfs_root *root,
2636 struct extent_buffer *buf,
2637 int full_backref, int inc)
2638 {
2639 u64 bytenr;
2640 u64 num_bytes;
2641 u64 parent;
2642 u64 ref_root;
2643 u32 nritems;
2644 struct btrfs_key key;
2645 struct btrfs_file_extent_item *fi;
2646 int i;
2647 int level;
2648 int ret = 0;
2649 int (*process_func)(struct btrfs_trans_handle *, struct btrfs_root *,
2650 u64, u64, u64, u64, u64, u64);
2651
2652 ref_root = btrfs_header_owner(buf);
2653 nritems = btrfs_header_nritems(buf);
2654 level = btrfs_header_level(buf);
2655
2656 if (!root->ref_cows && level == 0)
2657 return 0;
2658
2659 if (inc)
2660 process_func = btrfs_inc_extent_ref;
2661 else
2662 process_func = btrfs_free_extent;
2663
2664 if (full_backref)
2665 parent = buf->start;
2666 else
2667 parent = 0;
2668
2669 for (i = 0; i < nritems; i++) {
2670 if (level == 0) {
2671 btrfs_item_key_to_cpu(buf, &key, i);
2672 if (btrfs_key_type(&key) != BTRFS_EXTENT_DATA_KEY)
2673 continue;
2674 fi = btrfs_item_ptr(buf, i,
2675 struct btrfs_file_extent_item);
2676 if (btrfs_file_extent_type(buf, fi) ==
2677 BTRFS_FILE_EXTENT_INLINE)
2678 continue;
2679 bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
2680 if (bytenr == 0)
2681 continue;
2682
2683 num_bytes = btrfs_file_extent_disk_num_bytes(buf, fi);
2684 key.offset -= btrfs_file_extent_offset(buf, fi);
2685 ret = process_func(trans, root, bytenr, num_bytes,
2686 parent, ref_root, key.objectid,
2687 key.offset);
2688 if (ret)
2689 goto fail;
2690 } else {
2691 bytenr = btrfs_node_blockptr(buf, i);
2692 num_bytes = btrfs_level_size(root, level - 1);
2693 ret = process_func(trans, root, bytenr, num_bytes,
2694 parent, ref_root, level - 1, 0);
2695 if (ret)
2696 goto fail;
2697 }
2698 }
2699 return 0;
2700 fail:
2701 BUG();
2702 return ret;
2703 }
2704
2705 int btrfs_inc_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2706 struct extent_buffer *buf, int full_backref)
2707 {
2708 return __btrfs_mod_ref(trans, root, buf, full_backref, 1);
2709 }
2710
2711 int btrfs_dec_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2712 struct extent_buffer *buf, int full_backref)
2713 {
2714 return __btrfs_mod_ref(trans, root, buf, full_backref, 0);
2715 }
2716
2717 static int write_one_cache_group(struct btrfs_trans_handle *trans,
2718 struct btrfs_root *root,
2719 struct btrfs_path *path,
2720 struct btrfs_block_group_cache *cache)
2721 {
2722 int ret;
2723 struct btrfs_root *extent_root = root->fs_info->extent_root;
2724 unsigned long bi;
2725 struct extent_buffer *leaf;
2726
2727 ret = btrfs_search_slot(trans, extent_root, &cache->key, path, 0, 1);
2728 if (ret < 0)
2729 goto fail;
2730 BUG_ON(ret);
2731
2732 leaf = path->nodes[0];
2733 bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
2734 write_extent_buffer(leaf, &cache->item, bi, sizeof(cache->item));
2735 btrfs_mark_buffer_dirty(leaf);
2736 btrfs_release_path(extent_root, path);
2737 fail:
2738 if (ret)
2739 return ret;
2740 return 0;
2741
2742 }
2743
2744 static struct btrfs_block_group_cache *
2745 next_block_group(struct btrfs_root *root,
2746 struct btrfs_block_group_cache *cache)
2747 {
2748 struct rb_node *node;
2749 spin_lock(&root->fs_info->block_group_cache_lock);
2750 node = rb_next(&cache->cache_node);
2751 btrfs_put_block_group(cache);
2752 if (node) {
2753 cache = rb_entry(node, struct btrfs_block_group_cache,
2754 cache_node);
2755 btrfs_get_block_group(cache);
2756 } else
2757 cache = NULL;
2758 spin_unlock(&root->fs_info->block_group_cache_lock);
2759 return cache;
2760 }
2761
2762 static int cache_save_setup(struct btrfs_block_group_cache *block_group,
2763 struct btrfs_trans_handle *trans,
2764 struct btrfs_path *path)
2765 {
2766 struct btrfs_root *root = block_group->fs_info->tree_root;
2767 struct inode *inode = NULL;
2768 u64 alloc_hint = 0;
2769 int dcs = BTRFS_DC_ERROR;
2770 int num_pages = 0;
2771 int retries = 0;
2772 int ret = 0;
2773
2774 /*
2775 * If this block group is smaller than 100 megs don't bother caching the
2776 * block group.
2777 */
2778 if (block_group->key.offset < (100 * 1024 * 1024)) {
2779 spin_lock(&block_group->lock);
2780 block_group->disk_cache_state = BTRFS_DC_WRITTEN;
2781 spin_unlock(&block_group->lock);
2782 return 0;
2783 }
2784
2785 again:
2786 inode = lookup_free_space_inode(root, block_group, path);
2787 if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
2788 ret = PTR_ERR(inode);
2789 btrfs_release_path(root, path);
2790 goto out;
2791 }
2792
2793 if (IS_ERR(inode)) {
2794 BUG_ON(retries);
2795 retries++;
2796
2797 if (block_group->ro)
2798 goto out_free;
2799
2800 ret = create_free_space_inode(root, trans, block_group, path);
2801 if (ret)
2802 goto out_free;
2803 goto again;
2804 }
2805
2806 /*
2807 * We want to set the generation to 0, that way if anything goes wrong
2808 * from here on out we know not to trust this cache when we load up next
2809 * time.
2810 */
2811 BTRFS_I(inode)->generation = 0;
2812 ret = btrfs_update_inode(trans, root, inode);
2813 WARN_ON(ret);
2814
2815 if (i_size_read(inode) > 0) {
2816 ret = btrfs_truncate_free_space_cache(root, trans, path,
2817 inode);
2818 if (ret)
2819 goto out_put;
2820 }
2821
2822 spin_lock(&block_group->lock);
2823 if (block_group->cached != BTRFS_CACHE_FINISHED) {
2824 /* We're not cached, don't bother trying to write stuff out */
2825 dcs = BTRFS_DC_WRITTEN;
2826 spin_unlock(&block_group->lock);
2827 goto out_put;
2828 }
2829 spin_unlock(&block_group->lock);
2830
2831 num_pages = (int)div64_u64(block_group->key.offset, 1024 * 1024 * 1024);
2832 if (!num_pages)
2833 num_pages = 1;
2834
2835 /*
2836 * Just to make absolutely sure we have enough space, we're going to
2837 * preallocate 12 pages worth of space for each block group. In
2838 * practice we ought to use at most 8, but we need extra space so we can
2839 * add our header and have a terminator between the extents and the
2840 * bitmaps.
2841 */
2842 num_pages *= 16;
2843 num_pages *= PAGE_CACHE_SIZE;
2844
2845 ret = btrfs_check_data_free_space(inode, num_pages);
2846 if (ret)
2847 goto out_put;
2848
2849 ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, num_pages,
2850 num_pages, num_pages,
2851 &alloc_hint);
2852 if (!ret)
2853 dcs = BTRFS_DC_SETUP;
2854 btrfs_free_reserved_data_space(inode, num_pages);
2855 out_put:
2856 iput(inode);
2857 out_free:
2858 btrfs_release_path(root, path);
2859 out:
2860 spin_lock(&block_group->lock);
2861 block_group->disk_cache_state = dcs;
2862 spin_unlock(&block_group->lock);
2863
2864 return ret;
2865 }
2866
2867 int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans,
2868 struct btrfs_root *root)
2869 {
2870 struct btrfs_block_group_cache *cache;
2871 int err = 0;
2872 struct btrfs_path *path;
2873 u64 last = 0;
2874
2875 path = btrfs_alloc_path();
2876 if (!path)
2877 return -ENOMEM;
2878
2879 again:
2880 while (1) {
2881 cache = btrfs_lookup_first_block_group(root->fs_info, last);
2882 while (cache) {
2883 if (cache->disk_cache_state == BTRFS_DC_CLEAR)
2884 break;
2885 cache = next_block_group(root, cache);
2886 }
2887 if (!cache) {
2888 if (last == 0)
2889 break;
2890 last = 0;
2891 continue;
2892 }
2893 err = cache_save_setup(cache, trans, path);
2894 last = cache->key.objectid + cache->key.offset;
2895 btrfs_put_block_group(cache);
2896 }
2897
2898 while (1) {
2899 if (last == 0) {
2900 err = btrfs_run_delayed_refs(trans, root,
2901 (unsigned long)-1);
2902 BUG_ON(err);
2903 }
2904
2905 cache = btrfs_lookup_first_block_group(root->fs_info, last);
2906 while (cache) {
2907 if (cache->disk_cache_state == BTRFS_DC_CLEAR) {
2908 btrfs_put_block_group(cache);
2909 goto again;
2910 }
2911
2912 if (cache->dirty)
2913 break;
2914 cache = next_block_group(root, cache);
2915 }
2916 if (!cache) {
2917 if (last == 0)
2918 break;
2919 last = 0;
2920 continue;
2921 }
2922
2923 if (cache->disk_cache_state == BTRFS_DC_SETUP)
2924 cache->disk_cache_state = BTRFS_DC_NEED_WRITE;
2925 cache->dirty = 0;
2926 last = cache->key.objectid + cache->key.offset;
2927
2928 err = write_one_cache_group(trans, root, path, cache);
2929 BUG_ON(err);
2930 btrfs_put_block_group(cache);
2931 }
2932
2933 while (1) {
2934 /*
2935 * I don't think this is needed since we're just marking our
2936 * preallocated extent as written, but just in case it can't
2937 * hurt.
2938 */
2939 if (last == 0) {
2940 err = btrfs_run_delayed_refs(trans, root,
2941 (unsigned long)-1);
2942 BUG_ON(err);
2943 }
2944
2945 cache = btrfs_lookup_first_block_group(root->fs_info, last);
2946 while (cache) {
2947 /*
2948 * Really this shouldn't happen, but it could if we
2949 * couldn't write the entire preallocated extent and
2950 * splitting the extent resulted in a new block.
2951 */
2952 if (cache->dirty) {
2953 btrfs_put_block_group(cache);
2954 goto again;
2955 }
2956 if (cache->disk_cache_state == BTRFS_DC_NEED_WRITE)
2957 break;
2958 cache = next_block_group(root, cache);
2959 }
2960 if (!cache) {
2961 if (last == 0)
2962 break;
2963 last = 0;
2964 continue;
2965 }
2966
2967 btrfs_write_out_cache(root, trans, cache, path);
2968
2969 /*
2970 * If we didn't have an error then the cache state is still
2971 * NEED_WRITE, so we can set it to WRITTEN.
2972 */
2973 if (cache->disk_cache_state == BTRFS_DC_NEED_WRITE)
2974 cache->disk_cache_state = BTRFS_DC_WRITTEN;
2975 last = cache->key.objectid + cache->key.offset;
2976 btrfs_put_block_group(cache);
2977 }
2978
2979 btrfs_free_path(path);
2980 return 0;
2981 }
2982
2983 int btrfs_extent_readonly(struct btrfs_root *root, u64 bytenr)
2984 {
2985 struct btrfs_block_group_cache *block_group;
2986 int readonly = 0;
2987
2988 block_group = btrfs_lookup_block_group(root->fs_info, bytenr);
2989 if (!block_group || block_group->ro)
2990 readonly = 1;
2991 if (block_group)
2992 btrfs_put_block_group(block_group);
2993 return readonly;
2994 }
2995
2996 static int update_space_info(struct btrfs_fs_info *info, u64 flags,
2997 u64 total_bytes, u64 bytes_used,
2998 struct btrfs_space_info **space_info)
2999 {
3000 struct btrfs_space_info *found;
3001 int i;
3002 int factor;
3003
3004 if (flags & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
3005 BTRFS_BLOCK_GROUP_RAID10))
3006 factor = 2;
3007 else
3008 factor = 1;
3009
3010 found = __find_space_info(info, flags);
3011 if (found) {
3012 spin_lock(&found->lock);
3013 found->total_bytes += total_bytes;
3014 found->disk_total += total_bytes * factor;
3015 found->bytes_used += bytes_used;
3016 found->disk_used += bytes_used * factor;
3017 found->full = 0;
3018 spin_unlock(&found->lock);
3019 *space_info = found;
3020 return 0;
3021 }
3022 found = kzalloc(sizeof(*found), GFP_NOFS);
3023 if (!found)
3024 return -ENOMEM;
3025
3026 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++)
3027 INIT_LIST_HEAD(&found->block_groups[i]);
3028 init_rwsem(&found->groups_sem);
3029 spin_lock_init(&found->lock);
3030 found->flags = flags & (BTRFS_BLOCK_GROUP_DATA |
3031 BTRFS_BLOCK_GROUP_SYSTEM |
3032 BTRFS_BLOCK_GROUP_METADATA);
3033 found->total_bytes = total_bytes;
3034 found->disk_total = total_bytes * factor;
3035 found->bytes_used = bytes_used;
3036 found->disk_used = bytes_used * factor;
3037 found->bytes_pinned = 0;
3038 found->bytes_reserved = 0;
3039 found->bytes_readonly = 0;
3040 found->bytes_may_use = 0;
3041 found->full = 0;
3042 found->force_alloc = CHUNK_ALLOC_NO_FORCE;
3043 found->chunk_alloc = 0;
3044 *space_info = found;
3045 list_add_rcu(&found->list, &info->space_info);
3046 atomic_set(&found->caching_threads, 0);
3047 return 0;
3048 }
3049
3050 static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
3051 {
3052 u64 extra_flags = flags & (BTRFS_BLOCK_GROUP_RAID0 |
3053 BTRFS_BLOCK_GROUP_RAID1 |
3054 BTRFS_BLOCK_GROUP_RAID10 |
3055 BTRFS_BLOCK_GROUP_DUP);
3056 if (extra_flags) {
3057 if (flags & BTRFS_BLOCK_GROUP_DATA)
3058 fs_info->avail_data_alloc_bits |= extra_flags;
3059 if (flags & BTRFS_BLOCK_GROUP_METADATA)
3060 fs_info->avail_metadata_alloc_bits |= extra_flags;
3061 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
3062 fs_info->avail_system_alloc_bits |= extra_flags;
3063 }
3064 }
3065
3066 u64 btrfs_reduce_alloc_profile(struct btrfs_root *root, u64 flags)
3067 {
3068 /*
3069 * we add in the count of missing devices because we want
3070 * to make sure that any RAID levels on a degraded FS
3071 * continue to be honored.
3072 */
3073 u64 num_devices = root->fs_info->fs_devices->rw_devices +
3074 root->fs_info->fs_devices->missing_devices;
3075
3076 if (num_devices == 1)
3077 flags &= ~(BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID0);
3078 if (num_devices < 4)
3079 flags &= ~BTRFS_BLOCK_GROUP_RAID10;
3080
3081 if ((flags & BTRFS_BLOCK_GROUP_DUP) &&
3082 (flags & (BTRFS_BLOCK_GROUP_RAID1 |
3083 BTRFS_BLOCK_GROUP_RAID10))) {
3084 flags &= ~BTRFS_BLOCK_GROUP_DUP;
3085 }
3086
3087 if ((flags & BTRFS_BLOCK_GROUP_RAID1) &&
3088 (flags & BTRFS_BLOCK_GROUP_RAID10)) {
3089 flags &= ~BTRFS_BLOCK_GROUP_RAID1;
3090 }
3091
3092 if ((flags & BTRFS_BLOCK_GROUP_RAID0) &&
3093 ((flags & BTRFS_BLOCK_GROUP_RAID1) |
3094 (flags & BTRFS_BLOCK_GROUP_RAID10) |
3095 (flags & BTRFS_BLOCK_GROUP_DUP)))
3096 flags &= ~BTRFS_BLOCK_GROUP_RAID0;
3097 return flags;
3098 }
3099
3100 static u64 get_alloc_profile(struct btrfs_root *root, u64 flags)
3101 {
3102 if (flags & BTRFS_BLOCK_GROUP_DATA)
3103 flags |= root->fs_info->avail_data_alloc_bits &
3104 root->fs_info->data_alloc_profile;
3105 else if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
3106 flags |= root->fs_info->avail_system_alloc_bits &
3107 root->fs_info->system_alloc_profile;
3108 else if (flags & BTRFS_BLOCK_GROUP_METADATA)
3109 flags |= root->fs_info->avail_metadata_alloc_bits &
3110 root->fs_info->metadata_alloc_profile;
3111 return btrfs_reduce_alloc_profile(root, flags);
3112 }
3113
3114 u64 btrfs_get_alloc_profile(struct btrfs_root *root, int data)
3115 {
3116 u64 flags;
3117
3118 if (data)
3119 flags = BTRFS_BLOCK_GROUP_DATA;
3120 else if (root == root->fs_info->chunk_root)
3121 flags = BTRFS_BLOCK_GROUP_SYSTEM;
3122 else
3123 flags = BTRFS_BLOCK_GROUP_METADATA;
3124
3125 return get_alloc_profile(root, flags);
3126 }
3127
3128 void btrfs_set_inode_space_info(struct btrfs_root *root, struct inode *inode)
3129 {
3130 BTRFS_I(inode)->space_info = __find_space_info(root->fs_info,
3131 BTRFS_BLOCK_GROUP_DATA);
3132 }
3133
3134 /*
3135 * This will check the space that the inode allocates from to make sure we have
3136 * enough space for bytes.
3137 */
3138 int btrfs_check_data_free_space(struct inode *inode, u64 bytes)
3139 {
3140 struct btrfs_space_info *data_sinfo;
3141 struct btrfs_root *root = BTRFS_I(inode)->root;
3142 u64 used;
3143 int ret = 0, committed = 0, alloc_chunk = 1;
3144
3145 /* make sure bytes are sectorsize aligned */
3146 bytes = (bytes + root->sectorsize - 1) & ~((u64)root->sectorsize - 1);
3147
3148 if (root == root->fs_info->tree_root ||
3149 BTRFS_I(inode)->location.objectid == BTRFS_FREE_INO_OBJECTID) {
3150 alloc_chunk = 0;
3151 committed = 1;
3152 }
3153
3154 data_sinfo = BTRFS_I(inode)->space_info;
3155 if (!data_sinfo)
3156 goto alloc;
3157
3158 again:
3159 /* make sure we have enough space to handle the data first */
3160 spin_lock(&data_sinfo->lock);
3161 used = data_sinfo->bytes_used + data_sinfo->bytes_reserved +
3162 data_sinfo->bytes_pinned + data_sinfo->bytes_readonly +
3163 data_sinfo->bytes_may_use;
3164
3165 if (used + bytes > data_sinfo->total_bytes) {
3166 struct btrfs_trans_handle *trans;
3167
3168 /*
3169 * if we don't have enough free bytes in this space then we need
3170 * to alloc a new chunk.
3171 */
3172 if (!data_sinfo->full && alloc_chunk) {
3173 u64 alloc_target;
3174
3175 data_sinfo->force_alloc = CHUNK_ALLOC_FORCE;
3176 spin_unlock(&data_sinfo->lock);
3177 alloc:
3178 alloc_target = btrfs_get_alloc_profile(root, 1);
3179 trans = btrfs_join_transaction(root, 1);
3180 if (IS_ERR(trans))
3181 return PTR_ERR(trans);
3182
3183 ret = do_chunk_alloc(trans, root->fs_info->extent_root,
3184 bytes + 2 * 1024 * 1024,
3185 alloc_target,
3186 CHUNK_ALLOC_NO_FORCE);
3187 btrfs_end_transaction(trans, root);
3188 if (ret < 0) {
3189 if (ret != -ENOSPC)
3190 return ret;
3191 else
3192 goto commit_trans;
3193 }
3194
3195 if (!data_sinfo) {
3196 btrfs_set_inode_space_info(root, inode);
3197 data_sinfo = BTRFS_I(inode)->space_info;
3198 }
3199 goto again;
3200 }
3201 spin_unlock(&data_sinfo->lock);
3202
3203 /* commit the current transaction and try again */
3204 commit_trans:
3205 if (!committed && !root->fs_info->open_ioctl_trans) {
3206 committed = 1;
3207 trans = btrfs_join_transaction(root, 1);
3208 if (IS_ERR(trans))
3209 return PTR_ERR(trans);
3210 ret = btrfs_commit_transaction(trans, root);
3211 if (ret)
3212 return ret;
3213 goto again;
3214 }
3215
3216 #if 0 /* I hope we never need this code again, just in case */
3217 printk(KERN_ERR "no space left, need %llu, %llu bytes_used, "
3218 "%llu bytes_reserved, " "%llu bytes_pinned, "
3219 "%llu bytes_readonly, %llu may use %llu total\n",
3220 (unsigned long long)bytes,
3221 (unsigned long long)data_sinfo->bytes_used,
3222 (unsigned long long)data_sinfo->bytes_reserved,
3223 (unsigned long long)data_sinfo->bytes_pinned,
3224 (unsigned long long)data_sinfo->bytes_readonly,
3225 (unsigned long long)data_sinfo->bytes_may_use,
3226 (unsigned long long)data_sinfo->total_bytes);
3227 #endif
3228 return -ENOSPC;
3229 }
3230 data_sinfo->bytes_may_use += bytes;
3231 BTRFS_I(inode)->reserved_bytes += bytes;
3232 spin_unlock(&data_sinfo->lock);
3233
3234 return 0;
3235 }
3236
3237 /*
3238 * called when we are clearing an delalloc extent from the
3239 * inode's io_tree or there was an error for whatever reason
3240 * after calling btrfs_check_data_free_space
3241 */
3242 void btrfs_free_reserved_data_space(struct inode *inode, u64 bytes)
3243 {
3244 struct btrfs_root *root = BTRFS_I(inode)->root;
3245 struct btrfs_space_info *data_sinfo;
3246
3247 /* make sure bytes are sectorsize aligned */
3248 bytes = (bytes + root->sectorsize - 1) & ~((u64)root->sectorsize - 1);
3249
3250 data_sinfo = BTRFS_I(inode)->space_info;
3251 spin_lock(&data_sinfo->lock);
3252 data_sinfo->bytes_may_use -= bytes;
3253 BTRFS_I(inode)->reserved_bytes -= bytes;
3254 spin_unlock(&data_sinfo->lock);
3255 }
3256
3257 static void force_metadata_allocation(struct btrfs_fs_info *info)
3258 {
3259 struct list_head *head = &info->space_info;
3260 struct btrfs_space_info *found;
3261
3262 rcu_read_lock();
3263 list_for_each_entry_rcu(found, head, list) {
3264 if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
3265 found->force_alloc = CHUNK_ALLOC_FORCE;
3266 }
3267 rcu_read_unlock();
3268 }
3269
3270 static int should_alloc_chunk(struct btrfs_root *root,
3271 struct btrfs_space_info *sinfo, u64 alloc_bytes,
3272 int force)
3273 {
3274 u64 num_bytes = sinfo->total_bytes - sinfo->bytes_readonly;
3275 u64 num_allocated = sinfo->bytes_used + sinfo->bytes_reserved;
3276 u64 thresh;
3277
3278 if (force == CHUNK_ALLOC_FORCE)
3279 return 1;
3280
3281 /*
3282 * in limited mode, we want to have some free space up to
3283 * about 1% of the FS size.
3284 */
3285 if (force == CHUNK_ALLOC_LIMITED) {
3286 thresh = btrfs_super_total_bytes(&root->fs_info->super_copy);
3287 thresh = max_t(u64, 64 * 1024 * 1024,
3288 div_factor_fine(thresh, 1));
3289
3290 if (num_bytes - num_allocated < thresh)
3291 return 1;
3292 }
3293
3294 /*
3295 * we have two similar checks here, one based on percentage
3296 * and once based on a hard number of 256MB. The idea
3297 * is that if we have a good amount of free
3298 * room, don't allocate a chunk. A good mount is
3299 * less than 80% utilized of the chunks we have allocated,
3300 * or more than 256MB free
3301 */
3302 if (num_allocated + alloc_bytes + 256 * 1024 * 1024 < num_bytes)
3303 return 0;
3304
3305 if (num_allocated + alloc_bytes < div_factor(num_bytes, 8))
3306 return 0;
3307
3308 thresh = btrfs_super_total_bytes(&root->fs_info->super_copy);
3309
3310 /* 256MB or 5% of the FS */
3311 thresh = max_t(u64, 256 * 1024 * 1024, div_factor_fine(thresh, 5));
3312
3313 if (num_bytes > thresh && sinfo->bytes_used < div_factor(num_bytes, 3))
3314 return 0;
3315 return 1;
3316 }
3317
3318 static int do_chunk_alloc(struct btrfs_trans_handle *trans,
3319 struct btrfs_root *extent_root, u64 alloc_bytes,
3320 u64 flags, int force)
3321 {
3322 struct btrfs_space_info *space_info;
3323 struct btrfs_fs_info *fs_info = extent_root->fs_info;
3324 int wait_for_alloc = 0;
3325 int ret = 0;
3326
3327 flags = btrfs_reduce_alloc_profile(extent_root, flags);
3328
3329 space_info = __find_space_info(extent_root->fs_info, flags);
3330 if (!space_info) {
3331 ret = update_space_info(extent_root->fs_info, flags,
3332 0, 0, &space_info);
3333 BUG_ON(ret);
3334 }
3335 BUG_ON(!space_info);
3336
3337 again:
3338 spin_lock(&space_info->lock);
3339 if (space_info->force_alloc)
3340 force = space_info->force_alloc;
3341 if (space_info->full) {
3342 spin_unlock(&space_info->lock);
3343 return 0;
3344 }
3345
3346 if (!should_alloc_chunk(extent_root, space_info, alloc_bytes, force)) {
3347 spin_unlock(&space_info->lock);
3348 return 0;
3349 } else if (space_info->chunk_alloc) {
3350 wait_for_alloc = 1;
3351 } else {
3352 space_info->chunk_alloc = 1;
3353 }
3354
3355 spin_unlock(&space_info->lock);
3356
3357 mutex_lock(&fs_info->chunk_mutex);
3358
3359 /*
3360 * The chunk_mutex is held throughout the entirety of a chunk
3361 * allocation, so once we've acquired the chunk_mutex we know that the
3362 * other guy is done and we need to recheck and see if we should
3363 * allocate.
3364 */
3365 if (wait_for_alloc) {
3366 mutex_unlock(&fs_info->chunk_mutex);
3367 wait_for_alloc = 0;
3368 goto again;
3369 }
3370
3371 /*
3372 * If we have mixed data/metadata chunks we want to make sure we keep
3373 * allocating mixed chunks instead of individual chunks.
3374 */
3375 if (btrfs_mixed_space_info(space_info))
3376 flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
3377
3378 /*
3379 * if we're doing a data chunk, go ahead and make sure that
3380 * we keep a reasonable number of metadata chunks allocated in the
3381 * FS as well.
3382 */
3383 if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
3384 fs_info->data_chunk_allocations++;
3385 if (!(fs_info->data_chunk_allocations %
3386 fs_info->metadata_ratio))
3387 force_metadata_allocation(fs_info);
3388 }
3389
3390 ret = btrfs_alloc_chunk(trans, extent_root, flags);
3391 spin_lock(&space_info->lock);
3392 if (ret)
3393 space_info->full = 1;
3394 else
3395 ret = 1;
3396
3397 space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
3398 space_info->chunk_alloc = 0;
3399 spin_unlock(&space_info->lock);
3400 mutex_unlock(&extent_root->fs_info->chunk_mutex);
3401 return ret;
3402 }
3403
3404 /*
3405 * shrink metadata reservation for delalloc
3406 */
3407 static int shrink_delalloc(struct btrfs_trans_handle *trans,
3408 struct btrfs_root *root, u64 to_reclaim, int sync)
3409 {
3410 struct btrfs_block_rsv *block_rsv;
3411 struct btrfs_space_info *space_info;
3412 u64 reserved;
3413 u64 max_reclaim;
3414 u64 reclaimed = 0;
3415 long time_left;
3416 int nr_pages = (2 * 1024 * 1024) >> PAGE_CACHE_SHIFT;
3417 int loops = 0;
3418 unsigned long progress;
3419
3420 block_rsv = &root->fs_info->delalloc_block_rsv;
3421 space_info = block_rsv->space_info;
3422
3423 smp_mb();
3424 reserved = space_info->bytes_reserved;
3425 progress = space_info->reservation_progress;
3426
3427 if (reserved == 0)
3428 return 0;
3429
3430 max_reclaim = min(reserved, to_reclaim);
3431
3432 while (loops < 1024) {
3433 /* have the flusher threads jump in and do some IO */
3434 smp_mb();
3435 nr_pages = min_t(unsigned long, nr_pages,
3436 root->fs_info->delalloc_bytes >> PAGE_CACHE_SHIFT);
3437 writeback_inodes_sb_nr_if_idle(root->fs_info->sb, nr_pages);
3438
3439 spin_lock(&space_info->lock);
3440 if (reserved > space_info->bytes_reserved)
3441 reclaimed += reserved - space_info->bytes_reserved;
3442 reserved = space_info->bytes_reserved;
3443 spin_unlock(&space_info->lock);
3444
3445 loops++;
3446
3447 if (reserved == 0 || reclaimed >= max_reclaim)
3448 break;
3449
3450 if (trans && trans->transaction->blocked)
3451 return -EAGAIN;
3452
3453 time_left = schedule_timeout_interruptible(1);
3454
3455 /* We were interrupted, exit */
3456 if (time_left)
3457 break;
3458
3459 /* we've kicked the IO a few times, if anything has been freed,
3460 * exit. There is no sense in looping here for a long time
3461 * when we really need to commit the transaction, or there are
3462 * just too many writers without enough free space
3463 */
3464
3465 if (loops > 3) {
3466 smp_mb();
3467 if (progress != space_info->reservation_progress)
3468 break;
3469 }
3470
3471 }
3472 return reclaimed >= to_reclaim;
3473 }
3474
3475 /*
3476 * Retries tells us how many times we've called reserve_metadata_bytes. The
3477 * idea is if this is the first call (retries == 0) then we will add to our
3478 * reserved count if we can't make the allocation in order to hold our place
3479 * while we go and try and free up space. That way for retries > 1 we don't try
3480 * and add space, we just check to see if the amount of unused space is >= the
3481 * total space, meaning that our reservation is valid.
3482 *
3483 * However if we don't intend to retry this reservation, pass -1 as retries so
3484 * that it short circuits this logic.
3485 */
3486 static int reserve_metadata_bytes(struct btrfs_trans_handle *trans,
3487 struct btrfs_root *root,
3488 struct btrfs_block_rsv *block_rsv,
3489 u64 orig_bytes, int flush)
3490 {
3491 struct btrfs_space_info *space_info = block_rsv->space_info;
3492 u64 unused;
3493 u64 num_bytes = orig_bytes;
3494 int retries = 0;
3495 int ret = 0;
3496 bool reserved = false;
3497 bool committed = false;
3498
3499 again:
3500 ret = -ENOSPC;
3501 if (reserved)
3502 num_bytes = 0;
3503
3504 spin_lock(&space_info->lock);
3505 unused = space_info->bytes_used + space_info->bytes_reserved +
3506 space_info->bytes_pinned + space_info->bytes_readonly +
3507 space_info->bytes_may_use;
3508
3509 /*
3510 * The idea here is that we've not already over-reserved the block group
3511 * then we can go ahead and save our reservation first and then start
3512 * flushing if we need to. Otherwise if we've already overcommitted
3513 * lets start flushing stuff first and then come back and try to make
3514 * our reservation.
3515 */
3516 if (unused <= space_info->total_bytes) {
3517 unused = space_info->total_bytes - unused;
3518 if (unused >= num_bytes) {
3519 if (!reserved)
3520 space_info->bytes_reserved += orig_bytes;
3521 ret = 0;
3522 } else {
3523 /*
3524 * Ok set num_bytes to orig_bytes since we aren't
3525 * overocmmitted, this way we only try and reclaim what
3526 * we need.
3527 */
3528 num_bytes = orig_bytes;
3529 }
3530 } else {
3531 /*
3532 * Ok we're over committed, set num_bytes to the overcommitted
3533 * amount plus the amount of bytes that we need for this
3534 * reservation.
3535 */
3536 num_bytes = unused - space_info->total_bytes +
3537 (orig_bytes * (retries + 1));
3538 }
3539
3540 /*
3541 * Couldn't make our reservation, save our place so while we're trying
3542 * to reclaim space we can actually use it instead of somebody else
3543 * stealing it from us.
3544 */
3545 if (ret && !reserved) {
3546 space_info->bytes_reserved += orig_bytes;
3547 reserved = true;
3548 }
3549
3550 spin_unlock(&space_info->lock);
3551
3552 if (!ret)
3553 return 0;
3554
3555 if (!flush)
3556 goto out;
3557
3558 /*
3559 * We do synchronous shrinking since we don't actually unreserve
3560 * metadata until after the IO is completed.
3561 */
3562 ret = shrink_delalloc(trans, root, num_bytes, 1);
3563 if (ret > 0)
3564 return 0;
3565 else if (ret < 0)
3566 goto out;
3567
3568 /*
3569 * So if we were overcommitted it's possible that somebody else flushed
3570 * out enough space and we simply didn't have enough space to reclaim,
3571 * so go back around and try again.
3572 */
3573 if (retries < 2) {
3574 retries++;
3575 goto again;
3576 }
3577
3578 spin_lock(&space_info->lock);
3579 /*
3580 * Not enough space to be reclaimed, don't bother committing the
3581 * transaction.
3582 */
3583 if (space_info->bytes_pinned < orig_bytes)
3584 ret = -ENOSPC;
3585 spin_unlock(&space_info->lock);
3586 if (ret)
3587 goto out;
3588
3589 ret = -EAGAIN;
3590 if (trans || committed)
3591 goto out;
3592
3593 ret = -ENOSPC;
3594 trans = btrfs_join_transaction(root, 1);
3595 if (IS_ERR(trans))
3596 goto out;
3597 ret = btrfs_commit_transaction(trans, root);
3598 if (!ret) {
3599 trans = NULL;
3600 committed = true;
3601 goto again;
3602 }
3603
3604 out:
3605 if (reserved) {
3606 spin_lock(&space_info->lock);
3607 space_info->bytes_reserved -= orig_bytes;
3608 spin_unlock(&space_info->lock);
3609 }
3610
3611 return ret;
3612 }
3613
3614 static struct btrfs_block_rsv *get_block_rsv(struct btrfs_trans_handle *trans,
3615 struct btrfs_root *root)
3616 {
3617 struct btrfs_block_rsv *block_rsv;
3618 if (root->ref_cows)
3619 block_rsv = trans->block_rsv;
3620 else
3621 block_rsv = root->block_rsv;
3622
3623 if (!block_rsv)
3624 block_rsv = &root->fs_info->empty_block_rsv;
3625
3626 return block_rsv;
3627 }
3628
3629 static int block_rsv_use_bytes(struct btrfs_block_rsv *block_rsv,
3630 u64 num_bytes)
3631 {
3632 int ret = -ENOSPC;
3633 spin_lock(&block_rsv->lock);
3634 if (block_rsv->reserved >= num_bytes) {
3635 block_rsv->reserved -= num_bytes;
3636 if (block_rsv->reserved < block_rsv->size)
3637 block_rsv->full = 0;
3638 ret = 0;
3639 }
3640 spin_unlock(&block_rsv->lock);
3641 return ret;
3642 }
3643
3644 static void block_rsv_add_bytes(struct btrfs_block_rsv *block_rsv,
3645 u64 num_bytes, int update_size)
3646 {
3647 spin_lock(&block_rsv->lock);
3648 block_rsv->reserved += num_bytes;
3649 if (update_size)
3650 block_rsv->size += num_bytes;
3651 else if (block_rsv->reserved >= block_rsv->size)
3652 block_rsv->full = 1;
3653 spin_unlock(&block_rsv->lock);
3654 }
3655
3656 void block_rsv_release_bytes(struct btrfs_block_rsv *block_rsv,
3657 struct btrfs_block_rsv *dest, u64 num_bytes)
3658 {
3659 struct btrfs_space_info *space_info = block_rsv->space_info;
3660
3661 spin_lock(&block_rsv->lock);
3662 if (num_bytes == (u64)-1)
3663 num_bytes = block_rsv->size;
3664 block_rsv->size -= num_bytes;
3665 if (block_rsv->reserved >= block_rsv->size) {
3666 num_bytes = block_rsv->reserved - block_rsv->size;
3667 block_rsv->reserved = block_rsv->size;
3668 block_rsv->full = 1;
3669 } else {
3670 num_bytes = 0;
3671 }
3672 spin_unlock(&block_rsv->lock);
3673
3674 if (num_bytes > 0) {
3675 if (dest) {
3676 spin_lock(&dest->lock);
3677 if (!dest->full) {
3678 u64 bytes_to_add;
3679
3680 bytes_to_add = dest->size - dest->reserved;
3681 bytes_to_add = min(num_bytes, bytes_to_add);
3682 dest->reserved += bytes_to_add;
3683 if (dest->reserved >= dest->size)
3684 dest->full = 1;
3685 num_bytes -= bytes_to_add;
3686 }
3687 spin_unlock(&dest->lock);
3688 }
3689 if (num_bytes) {
3690 spin_lock(&space_info->lock);
3691 space_info->bytes_reserved -= num_bytes;
3692 space_info->reservation_progress++;
3693 spin_unlock(&space_info->lock);
3694 }
3695 }
3696 }
3697
3698 static int block_rsv_migrate_bytes(struct btrfs_block_rsv *src,
3699 struct btrfs_block_rsv *dst, u64 num_bytes)
3700 {
3701 int ret;
3702
3703 ret = block_rsv_use_bytes(src, num_bytes);
3704 if (ret)
3705 return ret;
3706
3707 block_rsv_add_bytes(dst, num_bytes, 1);
3708 return 0;
3709 }
3710
3711 void btrfs_init_block_rsv(struct btrfs_block_rsv *rsv)
3712 {
3713 memset(rsv, 0, sizeof(*rsv));
3714 spin_lock_init(&rsv->lock);
3715 atomic_set(&rsv->usage, 1);
3716 rsv->priority = 6;
3717 INIT_LIST_HEAD(&rsv->list);
3718 }
3719
3720 struct btrfs_block_rsv *btrfs_alloc_block_rsv(struct btrfs_root *root)
3721 {
3722 struct btrfs_block_rsv *block_rsv;
3723 struct btrfs_fs_info *fs_info = root->fs_info;
3724
3725 block_rsv = kmalloc(sizeof(*block_rsv), GFP_NOFS);
3726 if (!block_rsv)
3727 return NULL;
3728
3729 btrfs_init_block_rsv(block_rsv);
3730 block_rsv->space_info = __find_space_info(fs_info,
3731 BTRFS_BLOCK_GROUP_METADATA);
3732 return block_rsv;
3733 }
3734
3735 void btrfs_free_block_rsv(struct btrfs_root *root,
3736 struct btrfs_block_rsv *rsv)
3737 {
3738 if (rsv && atomic_dec_and_test(&rsv->usage)) {
3739 btrfs_block_rsv_release(root, rsv, (u64)-1);
3740 if (!rsv->durable)
3741 kfree(rsv);
3742 }
3743 }
3744
3745 /*
3746 * make the block_rsv struct be able to capture freed space.
3747 * the captured space will re-add to the the block_rsv struct
3748 * after transaction commit
3749 */
3750 void btrfs_add_durable_block_rsv(struct btrfs_fs_info *fs_info,
3751 struct btrfs_block_rsv *block_rsv)
3752 {
3753 block_rsv->durable = 1;
3754 mutex_lock(&fs_info->durable_block_rsv_mutex);
3755 list_add_tail(&block_rsv->list, &fs_info->durable_block_rsv_list);
3756 mutex_unlock(&fs_info->durable_block_rsv_mutex);
3757 }
3758
3759 int btrfs_block_rsv_add(struct btrfs_trans_handle *trans,
3760 struct btrfs_root *root,
3761 struct btrfs_block_rsv *block_rsv,
3762 u64 num_bytes)
3763 {
3764 int ret;
3765
3766 if (num_bytes == 0)
3767 return 0;
3768
3769 ret = reserve_metadata_bytes(trans, root, block_rsv, num_bytes, 1);
3770 if (!ret) {
3771 block_rsv_add_bytes(block_rsv, num_bytes, 1);
3772 return 0;
3773 }
3774
3775 return ret;
3776 }
3777
3778 int btrfs_block_rsv_check(struct btrfs_trans_handle *trans,
3779 struct btrfs_root *root,
3780 struct btrfs_block_rsv *block_rsv,
3781 u64 min_reserved, int min_factor)
3782 {
3783 u64 num_bytes = 0;
3784 int commit_trans = 0;
3785 int ret = -ENOSPC;
3786
3787 if (!block_rsv)
3788 return 0;
3789
3790 spin_lock(&block_rsv->lock);
3791 if (min_factor > 0)
3792 num_bytes = div_factor(block_rsv->size, min_factor);
3793 if (min_reserved > num_bytes)
3794 num_bytes = min_reserved;
3795
3796 if (block_rsv->reserved >= num_bytes) {
3797 ret = 0;
3798 } else {
3799 num_bytes -= block_rsv->reserved;
3800 if (block_rsv->durable &&
3801 block_rsv->freed[0] + block_rsv->freed[1] >= num_bytes)
3802 commit_trans = 1;
3803 }
3804 spin_unlock(&block_rsv->lock);
3805 if (!ret)
3806 return 0;
3807
3808 if (block_rsv->refill_used) {
3809 ret = reserve_metadata_bytes(trans, root, block_rsv,
3810 num_bytes, 0);
3811 if (!ret) {
3812 block_rsv_add_bytes(block_rsv, num_bytes, 0);
3813 return 0;
3814 }
3815 }
3816
3817 if (commit_trans) {
3818 if (trans)
3819 return -EAGAIN;
3820
3821 trans = btrfs_join_transaction(root, 1);
3822 BUG_ON(IS_ERR(trans));
3823 ret = btrfs_commit_transaction(trans, root);
3824 return 0;
3825 }
3826
3827 return -ENOSPC;
3828 }
3829
3830 int btrfs_block_rsv_migrate(struct btrfs_block_rsv *src_rsv,
3831 struct btrfs_block_rsv *dst_rsv,
3832 u64 num_bytes)
3833 {
3834 return block_rsv_migrate_bytes(src_rsv, dst_rsv, num_bytes);
3835 }
3836
3837 void btrfs_block_rsv_release(struct btrfs_root *root,
3838 struct btrfs_block_rsv *block_rsv,
3839 u64 num_bytes)
3840 {
3841 struct btrfs_block_rsv *global_rsv = &root->fs_info->global_block_rsv;
3842 if (global_rsv->full || global_rsv == block_rsv ||
3843 block_rsv->space_info != global_rsv->space_info)
3844 global_rsv = NULL;
3845 block_rsv_release_bytes(block_rsv, global_rsv, num_bytes);
3846 }
3847
3848 /*
3849 * helper to calculate size of global block reservation.
3850 * the desired value is sum of space used by extent tree,
3851 * checksum tree and root tree
3852 */
3853 static u64 calc_global_metadata_size(struct btrfs_fs_info *fs_info)
3854 {
3855 struct btrfs_space_info *sinfo;
3856 u64 num_bytes;
3857 u64 meta_used;
3858 u64 data_used;
3859 int csum_size = btrfs_super_csum_size(&fs_info->super_copy);
3860 #if 0
3861 /*
3862 * per tree used space accounting can be inaccuracy, so we
3863 * can't rely on it.
3864 */
3865 spin_lock(&fs_info->extent_root->accounting_lock);
3866 num_bytes = btrfs_root_used(&fs_info->extent_root->root_item);
3867 spin_unlock(&fs_info->extent_root->accounting_lock);
3868
3869 spin_lock(&fs_info->csum_root->accounting_lock);
3870 num_bytes += btrfs_root_used(&fs_info->csum_root->root_item);
3871 spin_unlock(&fs_info->csum_root->accounting_lock);
3872
3873 spin_lock(&fs_info->tree_root->accounting_lock);
3874 num_bytes += btrfs_root_used(&fs_info->tree_root->root_item);
3875 spin_unlock(&fs_info->tree_root->accounting_lock);
3876 #endif
3877 sinfo = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_DATA);
3878 spin_lock(&sinfo->lock);
3879 data_used = sinfo->bytes_used;
3880 spin_unlock(&sinfo->lock);
3881
3882 sinfo = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
3883 spin_lock(&sinfo->lock);
3884 if (sinfo->flags & BTRFS_BLOCK_GROUP_DATA)
3885 data_used = 0;
3886 meta_used = sinfo->bytes_used;
3887 spin_unlock(&sinfo->lock);
3888
3889 num_bytes = (data_used >> fs_info->sb->s_blocksize_bits) *
3890 csum_size * 2;
3891 num_bytes += div64_u64(data_used + meta_used, 50);
3892
3893 if (num_bytes * 3 > meta_used)
3894 num_bytes = div64_u64(meta_used, 3);
3895
3896 return ALIGN(num_bytes, fs_info->extent_root->leafsize << 10);
3897 }
3898
3899 static void update_global_block_rsv(struct btrfs_fs_info *fs_info)
3900 {
3901 struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
3902 struct btrfs_space_info *sinfo = block_rsv->space_info;
3903 u64 num_bytes;
3904
3905 num_bytes = calc_global_metadata_size(fs_info);
3906
3907 spin_lock(&block_rsv->lock);
3908 spin_lock(&sinfo->lock);
3909
3910 block_rsv->size = num_bytes;
3911
3912 num_bytes = sinfo->bytes_used + sinfo->bytes_pinned +
3913 sinfo->bytes_reserved + sinfo->bytes_readonly +
3914 sinfo->bytes_may_use;
3915
3916 if (sinfo->total_bytes > num_bytes) {
3917 num_bytes = sinfo->total_bytes - num_bytes;
3918 block_rsv->reserved += num_bytes;
3919 sinfo->bytes_reserved += num_bytes;
3920 }
3921
3922 if (block_rsv->reserved >= block_rsv->size) {
3923 num_bytes = block_rsv->reserved - block_rsv->size;
3924 sinfo->bytes_reserved -= num_bytes;
3925 sinfo->reservation_progress++;
3926 block_rsv->reserved = block_rsv->size;
3927 block_rsv->full = 1;
3928 }
3929 #if 0
3930 printk(KERN_INFO"global block rsv size %llu reserved %llu\n",
3931 block_rsv->size, block_rsv->reserved);
3932 #endif
3933 spin_unlock(&sinfo->lock);
3934 spin_unlock(&block_rsv->lock);
3935 }
3936
3937 static void init_global_block_rsv(struct btrfs_fs_info *fs_info)
3938 {
3939 struct btrfs_space_info *space_info;
3940
3941 space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
3942 fs_info->chunk_block_rsv.space_info = space_info;
3943 fs_info->chunk_block_rsv.priority = 10;
3944
3945 space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
3946 fs_info->global_block_rsv.space_info = space_info;
3947 fs_info->global_block_rsv.priority = 10;
3948 fs_info->global_block_rsv.refill_used = 1;
3949 fs_info->delalloc_block_rsv.space_info = space_info;
3950 fs_info->trans_block_rsv.space_info = space_info;
3951 fs_info->empty_block_rsv.space_info = space_info;
3952 fs_info->empty_block_rsv.priority = 10;
3953
3954 fs_info->extent_root->block_rsv = &fs_info->global_block_rsv;
3955 fs_info->csum_root->block_rsv = &fs_info->global_block_rsv;
3956 fs_info->dev_root->block_rsv = &fs_info->global_block_rsv;
3957 fs_info->tree_root->block_rsv = &fs_info->global_block_rsv;
3958 fs_info->chunk_root->block_rsv = &fs_info->chunk_block_rsv;
3959
3960 btrfs_add_durable_block_rsv(fs_info, &fs_info->global_block_rsv);
3961
3962 btrfs_add_durable_block_rsv(fs_info, &fs_info->delalloc_block_rsv);
3963
3964 update_global_block_rsv(fs_info);
3965 }
3966
3967 static void release_global_block_rsv(struct btrfs_fs_info *fs_info)
3968 {
3969 block_rsv_release_bytes(&fs_info->global_block_rsv, NULL, (u64)-1);
3970 WARN_ON(fs_info->delalloc_block_rsv.size > 0);
3971 WARN_ON(fs_info->delalloc_block_rsv.reserved > 0);
3972 WARN_ON(fs_info->trans_block_rsv.size > 0);
3973 WARN_ON(fs_info->trans_block_rsv.reserved > 0);
3974 WARN_ON(fs_info->chunk_block_rsv.size > 0);
3975 WARN_ON(fs_info->chunk_block_rsv.reserved > 0);
3976 }
3977
3978 int btrfs_trans_reserve_metadata(struct btrfs_trans_handle *trans,
3979 struct btrfs_root *root,
3980 int num_items)
3981 {
3982 u64 num_bytes;
3983 int ret;
3984
3985 if (num_items == 0 || root->fs_info->chunk_root == root)
3986 return 0;
3987
3988 num_bytes = btrfs_calc_trans_metadata_size(root, num_items);
3989 ret = btrfs_block_rsv_add(trans, root, &root->fs_info->trans_block_rsv,
3990 num_bytes);
3991 if (!ret) {
3992 trans->bytes_reserved += num_bytes;
3993 trans->block_rsv = &root->fs_info->trans_block_rsv;
3994 }
3995 return ret;
3996 }
3997
3998 void btrfs_trans_release_metadata(struct btrfs_trans_handle *trans,
3999 struct btrfs_root *root)
4000 {
4001 if (!trans->bytes_reserved)
4002 return;
4003
4004 BUG_ON(trans->block_rsv != &root->fs_info->trans_block_rsv);
4005 btrfs_block_rsv_release(root, trans->block_rsv,
4006 trans->bytes_reserved);
4007 trans->bytes_reserved = 0;
4008 }
4009
4010 int btrfs_orphan_reserve_metadata(struct btrfs_trans_handle *trans,
4011 struct inode *inode)
4012 {
4013 struct btrfs_root *root = BTRFS_I(inode)->root;
4014 struct btrfs_block_rsv *src_rsv = get_block_rsv(trans, root);
4015 struct btrfs_block_rsv *dst_rsv = root->orphan_block_rsv;
4016
4017 /*
4018 * one for deleting orphan item, one for updating inode and
4019 * two for calling btrfs_truncate_inode_items.
4020 *
4021 * btrfs_truncate_inode_items is a delete operation, it frees
4022 * more space than it uses in most cases. So two units of
4023 * metadata space should be enough for calling it many times.
4024 * If all of the metadata space is used, we can commit
4025 * transaction and use space it freed.
4026 */
4027 u64 num_bytes = btrfs_calc_trans_metadata_size(root, 4);
4028 return block_rsv_migrate_bytes(src_rsv, dst_rsv, num_bytes);
4029 }
4030
4031 void btrfs_orphan_release_metadata(struct inode *inode)
4032 {
4033 struct btrfs_root *root = BTRFS_I(inode)->root;
4034 u64 num_bytes = btrfs_calc_trans_metadata_size(root, 4);
4035 btrfs_block_rsv_release(root, root->orphan_block_rsv, num_bytes);
4036 }
4037
4038 int btrfs_snap_reserve_metadata(struct btrfs_trans_handle *trans,
4039 struct btrfs_pending_snapshot *pending)
4040 {
4041 struct btrfs_root *root = pending->root;
4042 struct btrfs_block_rsv *src_rsv = get_block_rsv(trans, root);
4043 struct btrfs_block_rsv *dst_rsv = &pending->block_rsv;
4044 /*
4045 * two for root back/forward refs, two for directory entries
4046 * and one for root of the snapshot.
4047 */
4048 u64 num_bytes = btrfs_calc_trans_metadata_size(root, 5);
4049 dst_rsv->space_info = src_rsv->space_info;
4050 return block_rsv_migrate_bytes(src_rsv, dst_rsv, num_bytes);
4051 }
4052
4053 static u64 calc_csum_metadata_size(struct inode *inode, u64 num_bytes)
4054 {
4055 return num_bytes >>= 3;
4056 }
4057
4058 int btrfs_delalloc_reserve_metadata(struct inode *inode, u64 num_bytes)
4059 {
4060 struct btrfs_root *root = BTRFS_I(inode)->root;
4061 struct btrfs_block_rsv *block_rsv = &root->fs_info->delalloc_block_rsv;
4062 u64 to_reserve;
4063 int nr_extents;
4064 int reserved_extents;
4065 int ret;
4066
4067 if (btrfs_transaction_in_commit(root->fs_info))
4068 schedule_timeout(1);
4069
4070 num_bytes = ALIGN(num_bytes, root->sectorsize);
4071
4072 nr_extents = atomic_read(&BTRFS_I(inode)->outstanding_extents) + 1;
4073 reserved_extents = atomic_read(&BTRFS_I(inode)->reserved_extents);
4074
4075 if (nr_extents > reserved_extents) {
4076 nr_extents -= reserved_extents;
4077 to_reserve = btrfs_calc_trans_metadata_size(root, nr_extents);
4078 } else {
4079 nr_extents = 0;
4080 to_reserve = 0;
4081 }
4082
4083 to_reserve += calc_csum_metadata_size(inode, num_bytes);
4084 ret = reserve_metadata_bytes(NULL, root, block_rsv, to_reserve, 1);
4085 if (ret)
4086 return ret;
4087
4088 atomic_add(nr_extents, &BTRFS_I(inode)->reserved_extents);
4089 atomic_inc(&BTRFS_I(inode)->outstanding_extents);
4090
4091 block_rsv_add_bytes(block_rsv, to_reserve, 1);
4092
4093 if (block_rsv->size > 512 * 1024 * 1024)
4094 shrink_delalloc(NULL, root, to_reserve, 0);
4095
4096 return 0;
4097 }
4098
4099 void btrfs_delalloc_release_metadata(struct inode *inode, u64 num_bytes)
4100 {
4101 struct btrfs_root *root = BTRFS_I(inode)->root;
4102 u64 to_free;
4103 int nr_extents;
4104 int reserved_extents;
4105
4106 num_bytes = ALIGN(num_bytes, root->sectorsize);
4107 atomic_dec(&BTRFS_I(inode)->outstanding_extents);
4108 WARN_ON(atomic_read(&BTRFS_I(inode)->outstanding_extents) < 0);
4109
4110 reserved_extents = atomic_read(&BTRFS_I(inode)->reserved_extents);
4111 do {
4112 int old, new;
4113
4114 nr_extents = atomic_read(&BTRFS_I(inode)->outstanding_extents);
4115 if (nr_extents >= reserved_extents) {
4116 nr_extents = 0;
4117 break;
4118 }
4119 old = reserved_extents;
4120 nr_extents = reserved_extents - nr_extents;
4121 new = reserved_extents - nr_extents;
4122 old = atomic_cmpxchg(&BTRFS_I(inode)->reserved_extents,
4123 reserved_extents, new);
4124 if (likely(old == reserved_extents))
4125 break;
4126 reserved_extents = old;
4127 } while (1);
4128
4129 to_free = calc_csum_metadata_size(inode, num_bytes);
4130 if (nr_extents > 0)
4131 to_free += btrfs_calc_trans_metadata_size(root, nr_extents);
4132
4133 btrfs_block_rsv_release(root, &root->fs_info->delalloc_block_rsv,
4134 to_free);
4135 }
4136
4137 int btrfs_delalloc_reserve_space(struct inode *inode, u64 num_bytes)
4138 {
4139 int ret;
4140
4141 ret = btrfs_check_data_free_space(inode, num_bytes);
4142 if (ret)
4143 return ret;
4144
4145 ret = btrfs_delalloc_reserve_metadata(inode, num_bytes);
4146 if (ret) {
4147 btrfs_free_reserved_data_space(inode, num_bytes);
4148 return ret;
4149 }
4150
4151 return 0;
4152 }
4153
4154 void btrfs_delalloc_release_space(struct inode *inode, u64 num_bytes)
4155 {
4156 btrfs_delalloc_release_metadata(inode, num_bytes);
4157 btrfs_free_reserved_data_space(inode, num_bytes);
4158 }
4159
4160 static int update_block_group(struct btrfs_trans_handle *trans,
4161 struct btrfs_root *root,
4162 u64 bytenr, u64 num_bytes, int alloc)
4163 {
4164 struct btrfs_block_group_cache *cache = NULL;
4165 struct btrfs_fs_info *info = root->fs_info;
4166 u64 total = num_bytes;
4167 u64 old_val;
4168 u64 byte_in_group;
4169 int factor;
4170
4171 /* block accounting for super block */
4172 spin_lock(&info->delalloc_lock);
4173 old_val = btrfs_super_bytes_used(&info->super_copy);
4174 if (alloc)
4175 old_val += num_bytes;
4176 else
4177 old_val -= num_bytes;
4178 btrfs_set_super_bytes_used(&info->super_copy, old_val);
4179 spin_unlock(&info->delalloc_lock);
4180
4181 while (total) {
4182 cache = btrfs_lookup_block_group(info, bytenr);
4183 if (!cache)
4184 return -1;
4185 if (cache->flags & (BTRFS_BLOCK_GROUP_DUP |
4186 BTRFS_BLOCK_GROUP_RAID1 |
4187 BTRFS_BLOCK_GROUP_RAID10))
4188 factor = 2;
4189 else
4190 factor = 1;
4191 /*
4192 * If this block group has free space cache written out, we
4193 * need to make sure to load it if we are removing space. This
4194 * is because we need the unpinning stage to actually add the
4195 * space back to the block group, otherwise we will leak space.
4196 */
4197 if (!alloc && cache->cached == BTRFS_CACHE_NO)
4198 cache_block_group(cache, trans, NULL, 1);
4199
4200 byte_in_group = bytenr - cache->key.objectid;
4201 WARN_ON(byte_in_group > cache->key.offset);
4202
4203 spin_lock(&cache->space_info->lock);
4204 spin_lock(&cache->lock);
4205
4206 if (btrfs_super_cache_generation(&info->super_copy) != 0 &&
4207 cache->disk_cache_state < BTRFS_DC_CLEAR)
4208 cache->disk_cache_state = BTRFS_DC_CLEAR;
4209
4210 cache->dirty = 1;
4211 old_val = btrfs_block_group_used(&cache->item);
4212 num_bytes = min(total, cache->key.offset - byte_in_group);
4213 if (alloc) {
4214 old_val += num_bytes;
4215 btrfs_set_block_group_used(&cache->item, old_val);
4216 cache->reserved -= num_bytes;
4217 cache->space_info->bytes_reserved -= num_bytes;
4218 cache->space_info->reservation_progress++;
4219 cache->space_info->bytes_used += num_bytes;
4220 cache->space_info->disk_used += num_bytes * factor;
4221 spin_unlock(&cache->lock);
4222 spin_unlock(&cache->space_info->lock);
4223 } else {
4224 old_val -= num_bytes;
4225 btrfs_set_block_group_used(&cache->item, old_val);
4226 cache->pinned += num_bytes;
4227 cache->space_info->bytes_pinned += num_bytes;
4228 cache->space_info->bytes_used -= num_bytes;
4229 cache->space_info->disk_used -= num_bytes * factor;
4230 spin_unlock(&cache->lock);
4231 spin_unlock(&cache->space_info->lock);
4232
4233 set_extent_dirty(info->pinned_extents,
4234 bytenr, bytenr + num_bytes - 1,
4235 GFP_NOFS | __GFP_NOFAIL);
4236 }
4237 btrfs_put_block_group(cache);
4238 total -= num_bytes;
4239 bytenr += num_bytes;
4240 }
4241 return 0;
4242 }
4243
4244 static u64 first_logical_byte(struct btrfs_root *root, u64 search_start)
4245 {
4246 struct btrfs_block_group_cache *cache;
4247 u64 bytenr;
4248
4249 cache = btrfs_lookup_first_block_group(root->fs_info, search_start);
4250 if (!cache)
4251 return 0;
4252
4253 bytenr = cache->key.objectid;
4254 btrfs_put_block_group(cache);
4255
4256 return bytenr;
4257 }
4258
4259 static int pin_down_extent(struct btrfs_root *root,
4260 struct btrfs_block_group_cache *cache,
4261 u64 bytenr, u64 num_bytes, int reserved)
4262 {
4263 spin_lock(&cache->space_info->lock);
4264 spin_lock(&cache->lock);
4265 cache->pinned += num_bytes;
4266 cache->space_info->bytes_pinned += num_bytes;
4267 if (reserved) {
4268 cache->reserved -= num_bytes;
4269 cache->space_info->bytes_reserved -= num_bytes;
4270 cache->space_info->reservation_progress++;
4271 }
4272 spin_unlock(&cache->lock);
4273 spin_unlock(&cache->space_info->lock);
4274
4275 set_extent_dirty(root->fs_info->pinned_extents, bytenr,
4276 bytenr + num_bytes - 1, GFP_NOFS | __GFP_NOFAIL);
4277 return 0;
4278 }
4279
4280 /*
4281 * this function must be called within transaction
4282 */
4283 int btrfs_pin_extent(struct btrfs_root *root,
4284 u64 bytenr, u64 num_bytes, int reserved)
4285 {
4286 struct btrfs_block_group_cache *cache;
4287
4288 cache = btrfs_lookup_block_group(root->fs_info, bytenr);
4289 BUG_ON(!cache);
4290
4291 pin_down_extent(root, cache, bytenr, num_bytes, reserved);
4292
4293 btrfs_put_block_group(cache);
4294 return 0;
4295 }
4296
4297 /*
4298 * update size of reserved extents. this function may return -EAGAIN
4299 * if 'reserve' is true or 'sinfo' is false.
4300 */
4301 int btrfs_update_reserved_bytes(struct btrfs_block_group_cache *cache,
4302 u64 num_bytes, int reserve, int sinfo)
4303 {
4304 int ret = 0;
4305 if (sinfo) {
4306 struct btrfs_space_info *space_info = cache->space_info;
4307 spin_lock(&space_info->lock);
4308 spin_lock(&cache->lock);
4309 if (reserve) {
4310 if (cache->ro) {
4311 ret = -EAGAIN;
4312 } else {
4313 cache->reserved += num_bytes;
4314 space_info->bytes_reserved += num_bytes;
4315 }
4316 } else {
4317 if (cache->ro)
4318 space_info->bytes_readonly += num_bytes;
4319 cache->reserved -= num_bytes;
4320 space_info->bytes_reserved -= num_bytes;
4321 space_info->reservation_progress++;
4322 }
4323 spin_unlock(&cache->lock);
4324 spin_unlock(&space_info->lock);
4325 } else {
4326 spin_lock(&cache->lock);
4327 if (cache->ro) {
4328 ret = -EAGAIN;
4329 } else {
4330 if (reserve)
4331 cache->reserved += num_bytes;
4332 else
4333 cache->reserved -= num_bytes;
4334 }
4335 spin_unlock(&cache->lock);
4336 }
4337 return ret;
4338 }
4339
4340 int btrfs_prepare_extent_commit(struct btrfs_trans_handle *trans,
4341 struct btrfs_root *root)
4342 {
4343 struct btrfs_fs_info *fs_info = root->fs_info;
4344 struct btrfs_caching_control *next;
4345 struct btrfs_caching_control *caching_ctl;
4346 struct btrfs_block_group_cache *cache;
4347
4348 down_write(&fs_info->extent_commit_sem);
4349
4350 list_for_each_entry_safe(caching_ctl, next,
4351 &fs_info->caching_block_groups, list) {
4352 cache = caching_ctl->block_group;
4353 if (block_group_cache_done(cache)) {
4354 cache->last_byte_to_unpin = (u64)-1;
4355 list_del_init(&caching_ctl->list);
4356 put_caching_control(caching_ctl);
4357 } else {
4358 cache->last_byte_to_unpin = caching_ctl->progress;
4359 }
4360 }
4361
4362 if (fs_info->pinned_extents == &fs_info->freed_extents[0])
4363 fs_info->pinned_extents = &fs_info->freed_extents[1];
4364 else
4365 fs_info->pinned_extents = &fs_info->freed_extents[0];
4366
4367 up_write(&fs_info->extent_commit_sem);
4368
4369 update_global_block_rsv(fs_info);
4370 return 0;
4371 }
4372
4373 static int unpin_extent_range(struct btrfs_root *root, u64 start, u64 end)
4374 {
4375 struct btrfs_fs_info *fs_info = root->fs_info;
4376 struct btrfs_block_group_cache *cache = NULL;
4377 u64 len;
4378
4379 while (start <= end) {
4380 if (!cache ||
4381 start >= cache->key.objectid + cache->key.offset) {
4382 if (cache)
4383 btrfs_put_block_group(cache);
4384 cache = btrfs_lookup_block_group(fs_info, start);
4385 BUG_ON(!cache);
4386 }
4387
4388 len = cache->key.objectid + cache->key.offset - start;
4389 len = min(len, end + 1 - start);
4390
4391 if (start < cache->last_byte_to_unpin) {
4392 len = min(len, cache->last_byte_to_unpin - start);
4393 btrfs_add_free_space(cache, start, len);
4394 }
4395
4396 start += len;
4397
4398 spin_lock(&cache->space_info->lock);
4399 spin_lock(&cache->lock);
4400 cache->pinned -= len;
4401 cache->space_info->bytes_pinned -= len;
4402 if (cache->ro) {
4403 cache->space_info->bytes_readonly += len;
4404 } else if (cache->reserved_pinned > 0) {
4405 len = min(len, cache->reserved_pinned);
4406 cache->reserved_pinned -= len;
4407 cache->space_info->bytes_reserved += len;
4408 }
4409 spin_unlock(&cache->lock);
4410 spin_unlock(&cache->space_info->lock);
4411 }
4412
4413 if (cache)
4414 btrfs_put_block_group(cache);
4415 return 0;
4416 }
4417
4418 int btrfs_finish_extent_commit(struct btrfs_trans_handle *trans,
4419 struct btrfs_root *root)
4420 {
4421 struct btrfs_fs_info *fs_info = root->fs_info;
4422 struct extent_io_tree *unpin;
4423 struct btrfs_block_rsv *block_rsv;
4424 struct btrfs_block_rsv *next_rsv;
4425 u64 start;
4426 u64 end;
4427 int idx;
4428 int ret;
4429
4430 if (fs_info->pinned_extents == &fs_info->freed_extents[0])
4431 unpin = &fs_info->freed_extents[1];
4432 else
4433 unpin = &fs_info->freed_extents[0];
4434
4435 while (1) {
4436 ret = find_first_extent_bit(unpin, 0, &start, &end,
4437 EXTENT_DIRTY);
4438 if (ret)
4439 break;
4440
4441 if (btrfs_test_opt(root, DISCARD))
4442 ret = btrfs_discard_extent(root, start,
4443 end + 1 - start, NULL);
4444
4445 clear_extent_dirty(unpin, start, end, GFP_NOFS);
4446 unpin_extent_range(root, start, end);
4447 cond_resched();
4448 }
4449
4450 mutex_lock(&fs_info->durable_block_rsv_mutex);
4451 list_for_each_entry_safe(block_rsv, next_rsv,
4452 &fs_info->durable_block_rsv_list, list) {
4453
4454 idx = trans->transid & 0x1;
4455 if (block_rsv->freed[idx] > 0) {
4456 block_rsv_add_bytes(block_rsv,
4457 block_rsv->freed[idx], 0);
4458 block_rsv->freed[idx] = 0;
4459 }
4460 if (atomic_read(&block_rsv->usage) == 0) {
4461 btrfs_block_rsv_release(root, block_rsv, (u64)-1);
4462
4463 if (block_rsv->freed[0] == 0 &&
4464 block_rsv->freed[1] == 0) {
4465 list_del_init(&block_rsv->list);
4466 kfree(block_rsv);
4467 }
4468 } else {
4469 btrfs_block_rsv_release(root, block_rsv, 0);
4470 }
4471 }
4472 mutex_unlock(&fs_info->durable_block_rsv_mutex);
4473
4474 return 0;
4475 }
4476
4477 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
4478 struct btrfs_root *root,
4479 u64 bytenr, u64 num_bytes, u64 parent,
4480 u64 root_objectid, u64 owner_objectid,
4481 u64 owner_offset, int refs_to_drop,
4482 struct btrfs_delayed_extent_op *extent_op)
4483 {
4484 struct btrfs_key key;
4485 struct btrfs_path *path;
4486 struct btrfs_fs_info *info = root->fs_info;
4487 struct btrfs_root *extent_root = info->extent_root;
4488 struct extent_buffer *leaf;
4489 struct btrfs_extent_item *ei;
4490 struct btrfs_extent_inline_ref *iref;
4491 int ret;
4492 int is_data;
4493 int extent_slot = 0;
4494 int found_extent = 0;
4495 int num_to_del = 1;
4496 u32 item_size;
4497 u64 refs;
4498
4499 path = btrfs_alloc_path();
4500 if (!path)
4501 return -ENOMEM;
4502
4503 path->reada = 1;
4504 path->leave_spinning = 1;
4505
4506 is_data = owner_objectid >= BTRFS_FIRST_FREE_OBJECTID;
4507 BUG_ON(!is_data && refs_to_drop != 1);
4508
4509 ret = lookup_extent_backref(trans, extent_root, path, &iref,
4510 bytenr, num_bytes, parent,
4511 root_objectid, owner_objectid,
4512 owner_offset);
4513 if (ret == 0) {
4514 extent_slot = path->slots[0];
4515 while (extent_slot >= 0) {
4516 btrfs_item_key_to_cpu(path->nodes[0], &key,
4517 extent_slot);
4518 if (key.objectid != bytenr)
4519 break;
4520 if (key.type == BTRFS_EXTENT_ITEM_KEY &&
4521 key.offset == num_bytes) {
4522 found_extent = 1;
4523 break;
4524 }
4525 if (path->slots[0] - extent_slot > 5)
4526 break;
4527 extent_slot--;
4528 }
4529 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
4530 item_size = btrfs_item_size_nr(path->nodes[0], extent_slot);
4531 if (found_extent && item_size < sizeof(*ei))
4532 found_extent = 0;
4533 #endif
4534 if (!found_extent) {
4535 BUG_ON(iref);
4536 ret = remove_extent_backref(trans, extent_root, path,
4537 NULL, refs_to_drop,
4538 is_data);
4539 BUG_ON(ret);
4540 btrfs_release_path(extent_root, path);
4541 path->leave_spinning = 1;
4542
4543 key.objectid = bytenr;
4544 key.type = BTRFS_EXTENT_ITEM_KEY;
4545 key.offset = num_bytes;
4546
4547 ret = btrfs_search_slot(trans, extent_root,
4548 &key, path, -1, 1);
4549 if (ret) {
4550 printk(KERN_ERR "umm, got %d back from search"
4551 ", was looking for %llu\n", ret,
4552 (unsigned long long)bytenr);
4553 btrfs_print_leaf(extent_root, path->nodes[0]);
4554 }
4555 BUG_ON(ret);
4556 extent_slot = path->slots[0];
4557 }
4558 } else {
4559 btrfs_print_leaf(extent_root, path->nodes[0]);
4560 WARN_ON(1);
4561 printk(KERN_ERR "btrfs unable to find ref byte nr %llu "
4562 "parent %llu root %llu owner %llu offset %llu\n",
4563 (unsigned long long)bytenr,
4564 (unsigned long long)parent,
4565 (unsigned long long)root_objectid,
4566 (unsigned long long)owner_objectid,
4567 (unsigned long long)owner_offset);
4568 }
4569
4570 leaf = path->nodes[0];
4571 item_size = btrfs_item_size_nr(leaf, extent_slot);
4572 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
4573 if (item_size < sizeof(*ei)) {
4574 BUG_ON(found_extent || extent_slot != path->slots[0]);
4575 ret = convert_extent_item_v0(trans, extent_root, path,
4576 owner_objectid, 0);
4577 BUG_ON(ret < 0);
4578
4579 btrfs_release_path(extent_root, path);
4580 path->leave_spinning = 1;
4581
4582 key.objectid = bytenr;
4583 key.type = BTRFS_EXTENT_ITEM_KEY;
4584 key.offset = num_bytes;
4585
4586 ret = btrfs_search_slot(trans, extent_root, &key, path,
4587 -1, 1);
4588 if (ret) {
4589 printk(KERN_ERR "umm, got %d back from search"
4590 ", was looking for %llu\n", ret,
4591 (unsigned long long)bytenr);
4592 btrfs_print_leaf(extent_root, path->nodes[0]);
4593 }
4594 BUG_ON(ret);
4595 extent_slot = path->slots[0];
4596 leaf = path->nodes[0];
4597 item_size = btrfs_item_size_nr(leaf, extent_slot);
4598 }
4599 #endif
4600 BUG_ON(item_size < sizeof(*ei));
4601 ei = btrfs_item_ptr(leaf, extent_slot,
4602 struct btrfs_extent_item);
4603 if (owner_objectid < BTRFS_FIRST_FREE_OBJECTID) {
4604 struct btrfs_tree_block_info *bi;
4605 BUG_ON(item_size < sizeof(*ei) + sizeof(*bi));
4606 bi = (struct btrfs_tree_block_info *)(ei + 1);
4607 WARN_ON(owner_objectid != btrfs_tree_block_level(leaf, bi));
4608 }
4609
4610 refs = btrfs_extent_refs(leaf, ei);
4611 BUG_ON(refs < refs_to_drop);
4612 refs -= refs_to_drop;
4613
4614 if (refs > 0) {
4615 if (extent_op)
4616 __run_delayed_extent_op(extent_op, leaf, ei);
4617 /*
4618 * In the case of inline back ref, reference count will
4619 * be updated by remove_extent_backref
4620 */
4621 if (iref) {
4622 BUG_ON(!found_extent);
4623 } else {
4624 btrfs_set_extent_refs(leaf, ei, refs);
4625 btrfs_mark_buffer_dirty(leaf);
4626 }
4627 if (found_extent) {
4628 ret = remove_extent_backref(trans, extent_root, path,
4629 iref, refs_to_drop,
4630 is_data);
4631 BUG_ON(ret);
4632 }
4633 } else {
4634 if (found_extent) {
4635 BUG_ON(is_data && refs_to_drop !=
4636 extent_data_ref_count(root, path, iref));
4637 if (iref) {
4638 BUG_ON(path->slots[0] != extent_slot);
4639 } else {
4640 BUG_ON(path->slots[0] != extent_slot + 1);
4641 path->slots[0] = extent_slot;
4642 num_to_del = 2;
4643 }
4644 }
4645
4646 ret = btrfs_del_items(trans, extent_root, path, path->slots[0],
4647 num_to_del);
4648 BUG_ON(ret);
4649 btrfs_release_path(extent_root, path);
4650
4651 if (is_data) {
4652 ret = btrfs_del_csums(trans, root, bytenr, num_bytes);
4653 BUG_ON(ret);
4654 } else {
4655 invalidate_mapping_pages(info->btree_inode->i_mapping,
4656 bytenr >> PAGE_CACHE_SHIFT,
4657 (bytenr + num_bytes - 1) >> PAGE_CACHE_SHIFT);
4658 }
4659
4660 ret = update_block_group(trans, root, bytenr, num_bytes, 0);
4661 BUG_ON(ret);
4662 }
4663 btrfs_free_path(path);
4664 return ret;
4665 }
4666
4667 /*
4668 * when we free an block, it is possible (and likely) that we free the last
4669 * delayed ref for that extent as well. This searches the delayed ref tree for
4670 * a given extent, and if there are no other delayed refs to be processed, it
4671 * removes it from the tree.
4672 */
4673 static noinline int check_ref_cleanup(struct btrfs_trans_handle *trans,
4674 struct btrfs_root *root, u64 bytenr)
4675 {
4676 struct btrfs_delayed_ref_head *head;
4677 struct btrfs_delayed_ref_root *delayed_refs;
4678 struct btrfs_delayed_ref_node *ref;
4679 struct rb_node *node;
4680 int ret = 0;
4681
4682 delayed_refs = &trans->transaction->delayed_refs;
4683 spin_lock(&delayed_refs->lock);
4684 head = btrfs_find_delayed_ref_head(trans, bytenr);
4685 if (!head)
4686 goto out;
4687
4688 node = rb_prev(&head->node.rb_node);
4689 if (!node)
4690 goto out;
4691
4692 ref = rb_entry(node, struct btrfs_delayed_ref_node, rb_node);
4693
4694 /* there are still entries for this ref, we can't drop it */
4695 if (ref->bytenr == bytenr)
4696 goto out;
4697
4698 if (head->extent_op) {
4699 if (!head->must_insert_reserved)
4700 goto out;
4701 kfree(head->extent_op);
4702 head->extent_op = NULL;
4703 }
4704
4705 /*
4706 * waiting for the lock here would deadlock. If someone else has it
4707 * locked they are already in the process of dropping it anyway
4708 */
4709 if (!mutex_trylock(&head->mutex))
4710 goto out;
4711
4712 /*
4713 * at this point we have a head with no other entries. Go
4714 * ahead and process it.
4715 */
4716 head->node.in_tree = 0;
4717 rb_erase(&head->node.rb_node, &delayed_refs->root);
4718
4719 delayed_refs->num_entries--;
4720
4721 /*
4722 * we don't take a ref on the node because we're removing it from the
4723 * tree, so we just steal the ref the tree was holding.
4724 */
4725 delayed_refs->num_heads--;
4726 if (list_empty(&head->cluster))
4727 delayed_refs->num_heads_ready--;
4728
4729 list_del_init(&head->cluster);
4730 spin_unlock(&delayed_refs->lock);
4731
4732 BUG_ON(head->extent_op);
4733 if (head->must_insert_reserved)
4734 ret = 1;
4735
4736 mutex_unlock(&head->mutex);
4737 btrfs_put_delayed_ref(&head->node);
4738 return ret;
4739 out:
4740 spin_unlock(&delayed_refs->lock);
4741 return 0;
4742 }
4743
4744 void btrfs_free_tree_block(struct btrfs_trans_handle *trans,
4745 struct btrfs_root *root,
4746 struct extent_buffer *buf,
4747 u64 parent, int last_ref)
4748 {
4749 struct btrfs_block_rsv *block_rsv;
4750 struct btrfs_block_group_cache *cache = NULL;
4751 int ret;
4752
4753 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4754 ret = btrfs_add_delayed_tree_ref(trans, buf->start, buf->len,
4755 parent, root->root_key.objectid,
4756 btrfs_header_level(buf),
4757 BTRFS_DROP_DELAYED_REF, NULL);
4758 BUG_ON(ret);
4759 }
4760
4761 if (!last_ref)
4762 return;
4763
4764 block_rsv = get_block_rsv(trans, root);
4765 cache = btrfs_lookup_block_group(root->fs_info, buf->start);
4766 if (block_rsv->space_info != cache->space_info)
4767 goto out;
4768
4769 if (btrfs_header_generation(buf) == trans->transid) {
4770 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4771 ret = check_ref_cleanup(trans, root, buf->start);
4772 if (!ret)
4773 goto pin;
4774 }
4775
4776 if (btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN)) {
4777 pin_down_extent(root, cache, buf->start, buf->len, 1);
4778 goto pin;
4779 }
4780
4781 WARN_ON(test_bit(EXTENT_BUFFER_DIRTY, &buf->bflags));
4782
4783 btrfs_add_free_space(cache, buf->start, buf->len);
4784 ret = btrfs_update_reserved_bytes(cache, buf->len, 0, 0);
4785 if (ret == -EAGAIN) {
4786 /* block group became read-only */
4787 btrfs_update_reserved_bytes(cache, buf->len, 0, 1);
4788 goto out;
4789 }
4790
4791 ret = 1;
4792 spin_lock(&block_rsv->lock);
4793 if (block_rsv->reserved < block_rsv->size) {
4794 block_rsv->reserved += buf->len;
4795 ret = 0;
4796 }
4797 spin_unlock(&block_rsv->lock);
4798
4799 if (ret) {
4800 spin_lock(&cache->space_info->lock);
4801 cache->space_info->bytes_reserved -= buf->len;
4802 cache->space_info->reservation_progress++;
4803 spin_unlock(&cache->space_info->lock);
4804 }
4805 goto out;
4806 }
4807 pin:
4808 if (block_rsv->durable && !cache->ro) {
4809 ret = 0;
4810 spin_lock(&cache->lock);
4811 if (!cache->ro) {
4812 cache->reserved_pinned += buf->len;
4813 ret = 1;
4814 }
4815 spin_unlock(&cache->lock);
4816
4817 if (ret) {
4818 spin_lock(&block_rsv->lock);
4819 block_rsv->freed[trans->transid & 0x1] += buf->len;
4820 spin_unlock(&block_rsv->lock);
4821 }
4822 }
4823 out:
4824 /*
4825 * Deleting the buffer, clear the corrupt flag since it doesn't matter
4826 * anymore.
4827 */
4828 clear_bit(EXTENT_BUFFER_CORRUPT, &buf->bflags);
4829 btrfs_put_block_group(cache);
4830 }
4831
4832 int btrfs_free_extent(struct btrfs_trans_handle *trans,
4833 struct btrfs_root *root,
4834 u64 bytenr, u64 num_bytes, u64 parent,
4835 u64 root_objectid, u64 owner, u64 offset)
4836 {
4837 int ret;
4838
4839 /*
4840 * tree log blocks never actually go into the extent allocation
4841 * tree, just update pinning info and exit early.
4842 */
4843 if (root_objectid == BTRFS_TREE_LOG_OBJECTID) {
4844 WARN_ON(owner >= BTRFS_FIRST_FREE_OBJECTID);
4845 /* unlocks the pinned mutex */
4846 btrfs_pin_extent(root, bytenr, num_bytes, 1);
4847 ret = 0;
4848 } else if (owner < BTRFS_FIRST_FREE_OBJECTID) {
4849 ret = btrfs_add_delayed_tree_ref(trans, bytenr, num_bytes,
4850 parent, root_objectid, (int)owner,
4851 BTRFS_DROP_DELAYED_REF, NULL);
4852 BUG_ON(ret);
4853 } else {
4854 ret = btrfs_add_delayed_data_ref(trans, bytenr, num_bytes,
4855 parent, root_objectid, owner,
4856 offset, BTRFS_DROP_DELAYED_REF, NULL);
4857 BUG_ON(ret);
4858 }
4859 return ret;
4860 }
4861
4862 static u64 stripe_align(struct btrfs_root *root, u64 val)
4863 {
4864 u64 mask = ((u64)root->stripesize - 1);
4865 u64 ret = (val + mask) & ~mask;
4866 return ret;
4867 }
4868
4869 /*
4870 * when we wait for progress in the block group caching, its because
4871 * our allocation attempt failed at least once. So, we must sleep
4872 * and let some progress happen before we try again.
4873 *
4874 * This function will sleep at least once waiting for new free space to
4875 * show up, and then it will check the block group free space numbers
4876 * for our min num_bytes. Another option is to have it go ahead
4877 * and look in the rbtree for a free extent of a given size, but this
4878 * is a good start.
4879 */
4880 static noinline int
4881 wait_block_group_cache_progress(struct btrfs_block_group_cache *cache,
4882 u64 num_bytes)
4883 {
4884 struct btrfs_caching_control *caching_ctl;
4885 DEFINE_WAIT(wait);
4886
4887 caching_ctl = get_caching_control(cache);
4888 if (!caching_ctl)
4889 return 0;
4890
4891 wait_event(caching_ctl->wait, block_group_cache_done(cache) ||
4892 (cache->free_space_ctl->free_space >= num_bytes));
4893
4894 put_caching_control(caching_ctl);
4895 return 0;
4896 }
4897
4898 static noinline int
4899 wait_block_group_cache_done(struct btrfs_block_group_cache *cache)
4900 {
4901 struct btrfs_caching_control *caching_ctl;
4902 DEFINE_WAIT(wait);
4903
4904 caching_ctl = get_caching_control(cache);
4905 if (!caching_ctl)
4906 return 0;
4907
4908 wait_event(caching_ctl->wait, block_group_cache_done(cache));
4909
4910 put_caching_control(caching_ctl);
4911 return 0;
4912 }
4913
4914 static int get_block_group_index(struct btrfs_block_group_cache *cache)
4915 {
4916 int index;
4917 if (cache->flags & BTRFS_BLOCK_GROUP_RAID10)
4918 index = 0;
4919 else if (cache->flags & BTRFS_BLOCK_GROUP_RAID1)
4920 index = 1;
4921 else if (cache->flags & BTRFS_BLOCK_GROUP_DUP)
4922 index = 2;
4923 else if (cache->flags & BTRFS_BLOCK_GROUP_RAID0)
4924 index = 3;
4925 else
4926 index = 4;
4927 return index;
4928 }
4929
4930 enum btrfs_loop_type {
4931 LOOP_FIND_IDEAL = 0,
4932 LOOP_CACHING_NOWAIT = 1,
4933 LOOP_CACHING_WAIT = 2,
4934 LOOP_ALLOC_CHUNK = 3,
4935 LOOP_NO_EMPTY_SIZE = 4,
4936 };
4937
4938 /*
4939 * walks the btree of allocated extents and find a hole of a given size.
4940 * The key ins is changed to record the hole:
4941 * ins->objectid == block start
4942 * ins->flags = BTRFS_EXTENT_ITEM_KEY
4943 * ins->offset == number of blocks
4944 * Any available blocks before search_start are skipped.
4945 */
4946 static noinline int find_free_extent(struct btrfs_trans_handle *trans,
4947 struct btrfs_root *orig_root,
4948 u64 num_bytes, u64 empty_size,
4949 u64 search_start, u64 search_end,
4950 u64 hint_byte, struct btrfs_key *ins,
4951 int data)
4952 {
4953 int ret = 0;
4954 struct btrfs_root *root = orig_root->fs_info->extent_root;
4955 struct btrfs_free_cluster *last_ptr = NULL;
4956 struct btrfs_block_group_cache *block_group = NULL;
4957 int empty_cluster = 2 * 1024 * 1024;
4958 int allowed_chunk_alloc = 0;
4959 int done_chunk_alloc = 0;
4960 struct btrfs_space_info *space_info;
4961 int last_ptr_loop = 0;
4962 int loop = 0;
4963 int index = 0;
4964 bool found_uncached_bg = false;
4965 bool failed_cluster_refill = false;
4966 bool failed_alloc = false;
4967 bool use_cluster = true;
4968 u64 ideal_cache_percent = 0;
4969 u64 ideal_cache_offset = 0;
4970
4971 WARN_ON(num_bytes < root->sectorsize);
4972 btrfs_set_key_type(ins, BTRFS_EXTENT_ITEM_KEY);
4973 ins->objectid = 0;
4974 ins->offset = 0;
4975
4976 space_info = __find_space_info(root->fs_info, data);
4977 if (!space_info) {
4978 printk(KERN_ERR "No space info for %d\n", data);
4979 return -ENOSPC;
4980 }
4981
4982 /*
4983 * If the space info is for both data and metadata it means we have a
4984 * small filesystem and we can't use the clustering stuff.
4985 */
4986 if (btrfs_mixed_space_info(space_info))
4987 use_cluster = false;
4988
4989 if (orig_root->ref_cows || empty_size)
4990 allowed_chunk_alloc = 1;
4991
4992 if (data & BTRFS_BLOCK_GROUP_METADATA && use_cluster) {
4993 last_ptr = &root->fs_info->meta_alloc_cluster;
4994 if (!btrfs_test_opt(root, SSD))
4995 empty_cluster = 64 * 1024;
4996 }
4997
4998 if ((data & BTRFS_BLOCK_GROUP_DATA) && use_cluster &&
4999 btrfs_test_opt(root, SSD)) {
5000 last_ptr = &root->fs_info->data_alloc_cluster;
5001 }
5002
5003 if (last_ptr) {
5004 spin_lock(&last_ptr->lock);
5005 if (last_ptr->block_group)
5006 hint_byte = last_ptr->window_start;
5007 spin_unlock(&last_ptr->lock);
5008 }
5009
5010 search_start = max(search_start, first_logical_byte(root, 0));
5011 search_start = max(search_start, hint_byte);
5012
5013 if (!last_ptr)
5014 empty_cluster = 0;
5015
5016 if (search_start == hint_byte) {
5017 ideal_cache:
5018 block_group = btrfs_lookup_block_group(root->fs_info,
5019 search_start);
5020 /*
5021 * we don't want to use the block group if it doesn't match our
5022 * allocation bits, or if its not cached.
5023 *
5024 * However if we are re-searching with an ideal block group
5025 * picked out then we don't care that the block group is cached.
5026 */
5027 if (block_group && block_group_bits(block_group, data) &&
5028 (block_group->cached != BTRFS_CACHE_NO ||
5029 search_start == ideal_cache_offset)) {
5030 down_read(&space_info->groups_sem);
5031 if (list_empty(&block_group->list) ||
5032 block_group->ro) {
5033 /*
5034 * someone is removing this block group,
5035 * we can't jump into the have_block_group
5036 * target because our list pointers are not
5037 * valid
5038 */
5039 btrfs_put_block_group(block_group);
5040 up_read(&space_info->groups_sem);
5041 } else {
5042 index = get_block_group_index(block_group);
5043 goto have_block_group;
5044 }
5045 } else if (block_group) {
5046 btrfs_put_block_group(block_group);
5047 }
5048 }
5049 search:
5050 down_read(&space_info->groups_sem);
5051 list_for_each_entry(block_group, &space_info->block_groups[index],
5052 list) {
5053 u64 offset;
5054 int cached;
5055
5056 btrfs_get_block_group(block_group);
5057 search_start = block_group->key.objectid;
5058
5059 /*
5060 * this can happen if we end up cycling through all the
5061 * raid types, but we want to make sure we only allocate
5062 * for the proper type.
5063 */
5064 if (!block_group_bits(block_group, data)) {
5065 u64 extra = BTRFS_BLOCK_GROUP_DUP |
5066 BTRFS_BLOCK_GROUP_RAID1 |
5067 BTRFS_BLOCK_GROUP_RAID10;
5068
5069 /*
5070 * if they asked for extra copies and this block group
5071 * doesn't provide them, bail. This does allow us to
5072 * fill raid0 from raid1.
5073 */
5074 if ((data & extra) && !(block_group->flags & extra))
5075 goto loop;
5076 }
5077
5078 have_block_group:
5079 if (unlikely(block_group->cached == BTRFS_CACHE_NO)) {
5080 u64 free_percent;
5081
5082 ret = cache_block_group(block_group, trans,
5083 orig_root, 1);
5084 if (block_group->cached == BTRFS_CACHE_FINISHED)
5085 goto have_block_group;
5086
5087 free_percent = btrfs_block_group_used(&block_group->item);
5088 free_percent *= 100;
5089 free_percent = div64_u64(free_percent,
5090 block_group->key.offset);
5091 free_percent = 100 - free_percent;
5092 if (free_percent > ideal_cache_percent &&
5093 likely(!block_group->ro)) {
5094 ideal_cache_offset = block_group->key.objectid;
5095 ideal_cache_percent = free_percent;
5096 }
5097
5098 /*
5099 * We only want to start kthread caching if we are at
5100 * the point where we will wait for caching to make
5101 * progress, or if our ideal search is over and we've
5102 * found somebody to start caching.
5103 */
5104 if (loop > LOOP_CACHING_NOWAIT ||
5105 (loop > LOOP_FIND_IDEAL &&
5106 atomic_read(&space_info->caching_threads) < 2)) {
5107 ret = cache_block_group(block_group, trans,
5108 orig_root, 0);
5109 BUG_ON(ret);
5110 }
5111 found_uncached_bg = true;
5112
5113 /*
5114 * If loop is set for cached only, try the next block
5115 * group.
5116 */
5117 if (loop == LOOP_FIND_IDEAL)
5118 goto loop;
5119 }
5120
5121 cached = block_group_cache_done(block_group);
5122 if (unlikely(!cached))
5123 found_uncached_bg = true;
5124
5125 if (unlikely(block_group->ro))
5126 goto loop;
5127
5128 /*
5129 * Ok we want to try and use the cluster allocator, so lets look
5130 * there, unless we are on LOOP_NO_EMPTY_SIZE, since we will
5131 * have tried the cluster allocator plenty of times at this
5132 * point and not have found anything, so we are likely way too
5133 * fragmented for the clustering stuff to find anything, so lets
5134 * just skip it and let the allocator find whatever block it can
5135 * find
5136 */
5137 if (last_ptr && loop < LOOP_NO_EMPTY_SIZE) {
5138 /*
5139 * the refill lock keeps out other
5140 * people trying to start a new cluster
5141 */
5142 spin_lock(&last_ptr->refill_lock);
5143 if (last_ptr->block_group &&
5144 (last_ptr->block_group->ro ||
5145 !block_group_bits(last_ptr->block_group, data))) {
5146 offset = 0;
5147 goto refill_cluster;
5148 }
5149
5150 offset = btrfs_alloc_from_cluster(block_group, last_ptr,
5151 num_bytes, search_start);
5152 if (offset) {
5153 /* we have a block, we're done */
5154 spin_unlock(&last_ptr->refill_lock);
5155 goto checks;
5156 }
5157
5158 spin_lock(&last_ptr->lock);
5159 /*
5160 * whoops, this cluster doesn't actually point to
5161 * this block group. Get a ref on the block
5162 * group is does point to and try again
5163 */
5164 if (!last_ptr_loop && last_ptr->block_group &&
5165 last_ptr->block_group != block_group) {
5166
5167 btrfs_put_block_group(block_group);
5168 block_group = last_ptr->block_group;
5169 btrfs_get_block_group(block_group);
5170 spin_unlock(&last_ptr->lock);
5171 spin_unlock(&last_ptr->refill_lock);
5172
5173 last_ptr_loop = 1;
5174 search_start = block_group->key.objectid;
5175 /*
5176 * we know this block group is properly
5177 * in the list because
5178 * btrfs_remove_block_group, drops the
5179 * cluster before it removes the block
5180 * group from the list
5181 */
5182 goto have_block_group;
5183 }
5184 spin_unlock(&last_ptr->lock);
5185 refill_cluster:
5186 /*
5187 * this cluster didn't work out, free it and
5188 * start over
5189 */
5190 btrfs_return_cluster_to_free_space(NULL, last_ptr);
5191
5192 last_ptr_loop = 0;
5193
5194 /* allocate a cluster in this block group */
5195 ret = btrfs_find_space_cluster(trans, root,
5196 block_group, last_ptr,
5197 offset, num_bytes,
5198 empty_cluster + empty_size);
5199 if (ret == 0) {
5200 /*
5201 * now pull our allocation out of this
5202 * cluster
5203 */
5204 offset = btrfs_alloc_from_cluster(block_group,
5205 last_ptr, num_bytes,
5206 search_start);
5207 if (offset) {
5208 /* we found one, proceed */
5209 spin_unlock(&last_ptr->refill_lock);
5210 goto checks;
5211 }
5212 } else if (!cached && loop > LOOP_CACHING_NOWAIT
5213 && !failed_cluster_refill) {
5214 spin_unlock(&last_ptr->refill_lock);
5215
5216 failed_cluster_refill = true;
5217 wait_block_group_cache_progress(block_group,
5218 num_bytes + empty_cluster + empty_size);
5219 goto have_block_group;
5220 }
5221
5222 /*
5223 * at this point we either didn't find a cluster
5224 * or we weren't able to allocate a block from our
5225 * cluster. Free the cluster we've been trying
5226 * to use, and go to the next block group
5227 */
5228 btrfs_return_cluster_to_free_space(NULL, last_ptr);
5229 spin_unlock(&last_ptr->refill_lock);
5230 goto loop;
5231 }
5232
5233 offset = btrfs_find_space_for_alloc(block_group, search_start,
5234 num_bytes, empty_size);
5235 /*
5236 * If we didn't find a chunk, and we haven't failed on this
5237 * block group before, and this block group is in the middle of
5238 * caching and we are ok with waiting, then go ahead and wait
5239 * for progress to be made, and set failed_alloc to true.
5240 *
5241 * If failed_alloc is true then we've already waited on this
5242 * block group once and should move on to the next block group.
5243 */
5244 if (!offset && !failed_alloc && !cached &&
5245 loop > LOOP_CACHING_NOWAIT) {
5246 wait_block_group_cache_progress(block_group,
5247 num_bytes + empty_size);
5248 failed_alloc = true;
5249 goto have_block_group;
5250 } else if (!offset) {
5251 goto loop;
5252 }
5253 checks:
5254 search_start = stripe_align(root, offset);
5255 /* move on to the next group */
5256 if (search_start + num_bytes >= search_end) {
5257 btrfs_add_free_space(block_group, offset, num_bytes);
5258 goto loop;
5259 }
5260
5261 /* move on to the next group */
5262 if (search_start + num_bytes >
5263 block_group->key.objectid + block_group->key.offset) {
5264 btrfs_add_free_space(block_group, offset, num_bytes);
5265 goto loop;
5266 }
5267
5268 ins->objectid = search_start;
5269 ins->offset = num_bytes;
5270
5271 if (offset < search_start)
5272 btrfs_add_free_space(block_group, offset,
5273 search_start - offset);
5274 BUG_ON(offset > search_start);
5275
5276 ret = btrfs_update_reserved_bytes(block_group, num_bytes, 1,
5277 (data & BTRFS_BLOCK_GROUP_DATA));
5278 if (ret == -EAGAIN) {
5279 btrfs_add_free_space(block_group, offset, num_bytes);
5280 goto loop;
5281 }
5282
5283 /* we are all good, lets return */
5284 ins->objectid = search_start;
5285 ins->offset = num_bytes;
5286
5287 if (offset < search_start)
5288 btrfs_add_free_space(block_group, offset,
5289 search_start - offset);
5290 BUG_ON(offset > search_start);
5291 break;
5292 loop:
5293 failed_cluster_refill = false;
5294 failed_alloc = false;
5295 BUG_ON(index != get_block_group_index(block_group));
5296 btrfs_put_block_group(block_group);
5297 }
5298 up_read(&space_info->groups_sem);
5299
5300 if (!ins->objectid && ++index < BTRFS_NR_RAID_TYPES)
5301 goto search;
5302
5303 /* LOOP_FIND_IDEAL, only search caching/cached bg's, and don't wait for
5304 * for them to make caching progress. Also
5305 * determine the best possible bg to cache
5306 * LOOP_CACHING_NOWAIT, search partially cached block groups, kicking
5307 * caching kthreads as we move along
5308 * LOOP_CACHING_WAIT, search everything, and wait if our bg is caching
5309 * LOOP_ALLOC_CHUNK, force a chunk allocation and try again
5310 * LOOP_NO_EMPTY_SIZE, set empty_size and empty_cluster to 0 and try
5311 * again
5312 */
5313 if (!ins->objectid && loop < LOOP_NO_EMPTY_SIZE &&
5314 (found_uncached_bg || empty_size || empty_cluster ||
5315 allowed_chunk_alloc)) {
5316 index = 0;
5317 if (loop == LOOP_FIND_IDEAL && found_uncached_bg) {
5318 found_uncached_bg = false;
5319 loop++;
5320 if (!ideal_cache_percent &&
5321 atomic_read(&space_info->caching_threads))
5322 goto search;
5323
5324 /*
5325 * 1 of the following 2 things have happened so far
5326 *
5327 * 1) We found an ideal block group for caching that
5328 * is mostly full and will cache quickly, so we might
5329 * as well wait for it.
5330 *
5331 * 2) We searched for cached only and we didn't find
5332 * anything, and we didn't start any caching kthreads
5333 * either, so chances are we will loop through and
5334 * start a couple caching kthreads, and then come back
5335 * around and just wait for them. This will be slower
5336 * because we will have 2 caching kthreads reading at
5337 * the same time when we could have just started one
5338 * and waited for it to get far enough to give us an
5339 * allocation, so go ahead and go to the wait caching
5340 * loop.
5341 */
5342 loop = LOOP_CACHING_WAIT;
5343 search_start = ideal_cache_offset;
5344 ideal_cache_percent = 0;
5345 goto ideal_cache;
5346 } else if (loop == LOOP_FIND_IDEAL) {
5347 /*
5348 * Didn't find a uncached bg, wait on anything we find
5349 * next.
5350 */
5351 loop = LOOP_CACHING_WAIT;
5352 goto search;
5353 }
5354
5355 if (loop < LOOP_CACHING_WAIT) {
5356 loop++;
5357 goto search;
5358 }
5359
5360 if (loop == LOOP_ALLOC_CHUNK) {
5361 empty_size = 0;
5362 empty_cluster = 0;
5363 }
5364
5365 if (allowed_chunk_alloc) {
5366 ret = do_chunk_alloc(trans, root, num_bytes +
5367 2 * 1024 * 1024, data,
5368 CHUNK_ALLOC_LIMITED);
5369 allowed_chunk_alloc = 0;
5370 done_chunk_alloc = 1;
5371 } else if (!done_chunk_alloc &&
5372 space_info->force_alloc == CHUNK_ALLOC_NO_FORCE) {
5373 space_info->force_alloc = CHUNK_ALLOC_LIMITED;
5374 }
5375
5376 if (loop < LOOP_NO_EMPTY_SIZE) {
5377 loop++;
5378 goto search;
5379 }
5380 ret = -ENOSPC;
5381 } else if (!ins->objectid) {
5382 ret = -ENOSPC;
5383 }
5384
5385 /* we found what we needed */
5386 if (ins->objectid) {
5387 if (!(data & BTRFS_BLOCK_GROUP_DATA))
5388 trans->block_group = block_group->key.objectid;
5389
5390 btrfs_put_block_group(block_group);
5391 ret = 0;
5392 }
5393
5394 return ret;
5395 }
5396
5397 static void dump_space_info(struct btrfs_space_info *info, u64 bytes,
5398 int dump_block_groups)
5399 {
5400 struct btrfs_block_group_cache *cache;
5401 int index = 0;
5402
5403 spin_lock(&info->lock);
5404 printk(KERN_INFO "space_info has %llu free, is %sfull\n",
5405 (unsigned long long)(info->total_bytes - info->bytes_used -
5406 info->bytes_pinned - info->bytes_reserved -
5407 info->bytes_readonly),
5408 (info->full) ? "" : "not ");
5409 printk(KERN_INFO "space_info total=%llu, used=%llu, pinned=%llu, "
5410 "reserved=%llu, may_use=%llu, readonly=%llu\n",
5411 (unsigned long long)info->total_bytes,
5412 (unsigned long long)info->bytes_used,
5413 (unsigned long long)info->bytes_pinned,
5414 (unsigned long long)info->bytes_reserved,
5415 (unsigned long long)info->bytes_may_use,
5416 (unsigned long long)info->bytes_readonly);
5417 spin_unlock(&info->lock);
5418
5419 if (!dump_block_groups)
5420 return;
5421
5422 down_read(&info->groups_sem);
5423 again:
5424 list_for_each_entry(cache, &info->block_groups[index], list) {
5425 spin_lock(&cache->lock);
5426 printk(KERN_INFO "block group %llu has %llu bytes, %llu used "
5427 "%llu pinned %llu reserved\n",
5428 (unsigned long long)cache->key.objectid,
5429 (unsigned long long)cache->key.offset,
5430 (unsigned long long)btrfs_block_group_used(&cache->item),
5431 (unsigned long long)cache->pinned,
5432 (unsigned long long)cache->reserved);
5433 btrfs_dump_free_space(cache, bytes);
5434 spin_unlock(&cache->lock);
5435 }
5436 if (++index < BTRFS_NR_RAID_TYPES)
5437 goto again;
5438 up_read(&info->groups_sem);
5439 }
5440
5441 int btrfs_reserve_extent(struct btrfs_trans_handle *trans,
5442 struct btrfs_root *root,
5443 u64 num_bytes, u64 min_alloc_size,
5444 u64 empty_size, u64 hint_byte,
5445 u64 search_end, struct btrfs_key *ins,
5446 u64 data)
5447 {
5448 int ret;
5449 u64 search_start = 0;
5450
5451 data = btrfs_get_alloc_profile(root, data);
5452 again:
5453 /*
5454 * the only place that sets empty_size is btrfs_realloc_node, which
5455 * is not called recursively on allocations
5456 */
5457 if (empty_size || root->ref_cows)
5458 ret = do_chunk_alloc(trans, root->fs_info->extent_root,
5459 num_bytes + 2 * 1024 * 1024, data,
5460 CHUNK_ALLOC_NO_FORCE);
5461
5462 WARN_ON(num_bytes < root->sectorsize);
5463 ret = find_free_extent(trans, root, num_bytes, empty_size,
5464 search_start, search_end, hint_byte,
5465 ins, data);
5466
5467 if (ret == -ENOSPC && num_bytes > min_alloc_size) {
5468 num_bytes = num_bytes >> 1;
5469 num_bytes = num_bytes & ~(root->sectorsize - 1);
5470 num_bytes = max(num_bytes, min_alloc_size);
5471 do_chunk_alloc(trans, root->fs_info->extent_root,
5472 num_bytes, data, CHUNK_ALLOC_FORCE);
5473 goto again;
5474 }
5475 if (ret == -ENOSPC && btrfs_test_opt(root, ENOSPC_DEBUG)) {
5476 struct btrfs_space_info *sinfo;
5477
5478 sinfo = __find_space_info(root->fs_info, data);
5479 printk(KERN_ERR "btrfs allocation failed flags %llu, "
5480 "wanted %llu\n", (unsigned long long)data,
5481 (unsigned long long)num_bytes);
5482 dump_space_info(sinfo, num_bytes, 1);
5483 }
5484
5485 trace_btrfs_reserved_extent_alloc(root, ins->objectid, ins->offset);
5486
5487 return ret;
5488 }
5489
5490 int btrfs_free_reserved_extent(struct btrfs_root *root, u64 start, u64 len)
5491 {
5492 struct btrfs_block_group_cache *cache;
5493 int ret = 0;
5494
5495 cache = btrfs_lookup_block_group(root->fs_info, start);
5496 if (!cache) {
5497 printk(KERN_ERR "Unable to find block group for %llu\n",
5498 (unsigned long long)start);
5499 return -ENOSPC;
5500 }
5501
5502 if (btrfs_test_opt(root, DISCARD))
5503 ret = btrfs_discard_extent(root, start, len, NULL);
5504
5505 btrfs_add_free_space(cache, start, len);
5506 btrfs_update_reserved_bytes(cache, len, 0, 1);
5507 btrfs_put_block_group(cache);
5508
5509 trace_btrfs_reserved_extent_free(root, start, len);
5510
5511 return ret;
5512 }
5513
5514 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
5515 struct btrfs_root *root,
5516 u64 parent, u64 root_objectid,
5517 u64 flags, u64 owner, u64 offset,
5518 struct btrfs_key *ins, int ref_mod)
5519 {
5520 int ret;
5521 struct btrfs_fs_info *fs_info = root->fs_info;
5522 struct btrfs_extent_item *extent_item;
5523 struct btrfs_extent_inline_ref *iref;
5524 struct btrfs_path *path;
5525 struct extent_buffer *leaf;
5526 int type;
5527 u32 size;
5528
5529 if (parent > 0)
5530 type = BTRFS_SHARED_DATA_REF_KEY;
5531 else
5532 type = BTRFS_EXTENT_DATA_REF_KEY;
5533
5534 size = sizeof(*extent_item) + btrfs_extent_inline_ref_size(type);
5535
5536 path = btrfs_alloc_path();
5537 if (!path)
5538 return -ENOMEM;
5539
5540 path->leave_spinning = 1;
5541 ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
5542 ins, size);
5543 BUG_ON(ret);
5544
5545 leaf = path->nodes[0];
5546 extent_item = btrfs_item_ptr(leaf, path->slots[0],
5547 struct btrfs_extent_item);
5548 btrfs_set_extent_refs(leaf, extent_item, ref_mod);
5549 btrfs_set_extent_generation(leaf, extent_item, trans->transid);
5550 btrfs_set_extent_flags(leaf, extent_item,
5551 flags | BTRFS_EXTENT_FLAG_DATA);
5552
5553 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
5554 btrfs_set_extent_inline_ref_type(leaf, iref, type);
5555 if (parent > 0) {
5556 struct btrfs_shared_data_ref *ref;
5557 ref = (struct btrfs_shared_data_ref *)(iref + 1);
5558 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
5559 btrfs_set_shared_data_ref_count(leaf, ref, ref_mod);
5560 } else {
5561 struct btrfs_extent_data_ref *ref;
5562 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
5563 btrfs_set_extent_data_ref_root(leaf, ref, root_objectid);
5564 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
5565 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
5566 btrfs_set_extent_data_ref_count(leaf, ref, ref_mod);
5567 }
5568
5569 btrfs_mark_buffer_dirty(path->nodes[0]);
5570 btrfs_free_path(path);
5571
5572 ret = update_block_group(trans, root, ins->objectid, ins->offset, 1);
5573 if (ret) {
5574 printk(KERN_ERR "btrfs update block group failed for %llu "
5575 "%llu\n", (unsigned long long)ins->objectid,
5576 (unsigned long long)ins->offset);
5577 BUG();
5578 }
5579 return ret;
5580 }
5581
5582 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
5583 struct btrfs_root *root,
5584 u64 parent, u64 root_objectid,
5585 u64 flags, struct btrfs_disk_key *key,
5586 int level, struct btrfs_key *ins)
5587 {
5588 int ret;
5589 struct btrfs_fs_info *fs_info = root->fs_info;
5590 struct btrfs_extent_item *extent_item;
5591 struct btrfs_tree_block_info *block_info;
5592 struct btrfs_extent_inline_ref *iref;
5593 struct btrfs_path *path;
5594 struct extent_buffer *leaf;
5595 u32 size = sizeof(*extent_item) + sizeof(*block_info) + sizeof(*iref);
5596
5597 path = btrfs_alloc_path();
5598 BUG_ON(!path);
5599
5600 path->leave_spinning = 1;
5601 ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
5602 ins, size);
5603 BUG_ON(ret);
5604
5605 leaf = path->nodes[0];
5606 extent_item = btrfs_item_ptr(leaf, path->slots[0],
5607 struct btrfs_extent_item);
5608 btrfs_set_extent_refs(leaf, extent_item, 1);
5609 btrfs_set_extent_generation(leaf, extent_item, trans->transid);
5610 btrfs_set_extent_flags(leaf, extent_item,
5611 flags | BTRFS_EXTENT_FLAG_TREE_BLOCK);
5612 block_info = (struct btrfs_tree_block_info *)(extent_item + 1);
5613
5614 btrfs_set_tree_block_key(leaf, block_info, key);
5615 btrfs_set_tree_block_level(leaf, block_info, level);
5616
5617 iref = (struct btrfs_extent_inline_ref *)(block_info + 1);
5618 if (parent > 0) {
5619 BUG_ON(!(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
5620 btrfs_set_extent_inline_ref_type(leaf, iref,
5621 BTRFS_SHARED_BLOCK_REF_KEY);
5622 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
5623 } else {
5624 btrfs_set_extent_inline_ref_type(leaf, iref,
5625 BTRFS_TREE_BLOCK_REF_KEY);
5626 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
5627 }
5628
5629 btrfs_mark_buffer_dirty(leaf);
5630 btrfs_free_path(path);
5631
5632 ret = update_block_group(trans, root, ins->objectid, ins->offset, 1);
5633 if (ret) {
5634 printk(KERN_ERR "btrfs update block group failed for %llu "
5635 "%llu\n", (unsigned long long)ins->objectid,
5636 (unsigned long long)ins->offset);
5637 BUG();
5638 }
5639 return ret;
5640 }
5641
5642 int btrfs_alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
5643 struct btrfs_root *root,
5644 u64 root_objectid, u64 owner,
5645 u64 offset, struct btrfs_key *ins)
5646 {
5647 int ret;
5648
5649 BUG_ON(root_objectid == BTRFS_TREE_LOG_OBJECTID);
5650
5651 ret = btrfs_add_delayed_data_ref(trans, ins->objectid, ins->offset,
5652 0, root_objectid, owner, offset,
5653 BTRFS_ADD_DELAYED_EXTENT, NULL);
5654 return ret;
5655 }
5656
5657 /*
5658 * this is used by the tree logging recovery code. It records that
5659 * an extent has been allocated and makes sure to clear the free
5660 * space cache bits as well
5661 */
5662 int btrfs_alloc_logged_file_extent(struct btrfs_trans_handle *trans,
5663 struct btrfs_root *root,
5664 u64 root_objectid, u64 owner, u64 offset,
5665 struct btrfs_key *ins)
5666 {
5667 int ret;
5668 struct btrfs_block_group_cache *block_group;
5669 struct btrfs_caching_control *caching_ctl;
5670 u64 start = ins->objectid;
5671 u64 num_bytes = ins->offset;
5672
5673 block_group = btrfs_lookup_block_group(root->fs_info, ins->objectid);
5674 cache_block_group(block_group, trans, NULL, 0);
5675 caching_ctl = get_caching_control(block_group);
5676
5677 if (!caching_ctl) {
5678 BUG_ON(!block_group_cache_done(block_group));
5679 ret = btrfs_remove_free_space(block_group, start, num_bytes);
5680 BUG_ON(ret);
5681 } else {
5682 mutex_lock(&caching_ctl->mutex);
5683
5684 if (start >= caching_ctl->progress) {
5685 ret = add_excluded_extent(root, start, num_bytes);
5686 BUG_ON(ret);
5687 } else if (start + num_bytes <= caching_ctl->progress) {
5688 ret = btrfs_remove_free_space(block_group,
5689 start, num_bytes);
5690 BUG_ON(ret);
5691 } else {
5692 num_bytes = caching_ctl->progress - start;
5693 ret = btrfs_remove_free_space(block_group,
5694 start, num_bytes);
5695 BUG_ON(ret);
5696
5697 start = caching_ctl->progress;
5698 num_bytes = ins->objectid + ins->offset -
5699 caching_ctl->progress;
5700 ret = add_excluded_extent(root, start, num_bytes);
5701 BUG_ON(ret);
5702 }
5703
5704 mutex_unlock(&caching_ctl->mutex);
5705 put_caching_control(caching_ctl);
5706 }
5707
5708 ret = btrfs_update_reserved_bytes(block_group, ins->offset, 1, 1);
5709 BUG_ON(ret);
5710 btrfs_put_block_group(block_group);
5711 ret = alloc_reserved_file_extent(trans, root, 0, root_objectid,
5712 0, owner, offset, ins, 1);
5713 return ret;
5714 }
5715
5716 struct extent_buffer *btrfs_init_new_buffer(struct btrfs_trans_handle *trans,
5717 struct btrfs_root *root,
5718 u64 bytenr, u32 blocksize,
5719 int level)
5720 {
5721 struct extent_buffer *buf;
5722
5723 buf = btrfs_find_create_tree_block(root, bytenr, blocksize);
5724 if (!buf)
5725 return ERR_PTR(-ENOMEM);
5726 btrfs_set_header_generation(buf, trans->transid);
5727 btrfs_set_buffer_lockdep_class(buf, level);
5728 btrfs_tree_lock(buf);
5729 clean_tree_block(trans, root, buf);
5730
5731 btrfs_set_lock_blocking(buf);
5732 btrfs_set_buffer_uptodate(buf);
5733
5734 if (root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID) {
5735 /*
5736 * we allow two log transactions at a time, use different
5737 * EXENT bit to differentiate dirty pages.
5738 */
5739 if (root->log_transid % 2 == 0)
5740 set_extent_dirty(&root->dirty_log_pages, buf->start,
5741 buf->start + buf->len - 1, GFP_NOFS);
5742 else
5743 set_extent_new(&root->dirty_log_pages, buf->start,
5744 buf->start + buf->len - 1, GFP_NOFS);
5745 } else {
5746 set_extent_dirty(&trans->transaction->dirty_pages, buf->start,
5747 buf->start + buf->len - 1, GFP_NOFS);
5748 }
5749 trans->blocks_used++;
5750 /* this returns a buffer locked for blocking */
5751 return buf;
5752 }
5753
5754 static struct btrfs_block_rsv *
5755 use_block_rsv(struct btrfs_trans_handle *trans,
5756 struct btrfs_root *root, u32 blocksize)
5757 {
5758 struct btrfs_block_rsv *block_rsv;
5759 struct btrfs_block_rsv *global_rsv = &root->fs_info->global_block_rsv;
5760 int ret;
5761
5762 block_rsv = get_block_rsv(trans, root);
5763
5764 if (block_rsv->size == 0) {
5765 ret = reserve_metadata_bytes(trans, root, block_rsv,
5766 blocksize, 0);
5767 /*
5768 * If we couldn't reserve metadata bytes try and use some from
5769 * the global reserve.
5770 */
5771 if (ret && block_rsv != global_rsv) {
5772 ret = block_rsv_use_bytes(global_rsv, blocksize);
5773 if (!ret)
5774 return global_rsv;
5775 return ERR_PTR(ret);
5776 } else if (ret) {
5777 return ERR_PTR(ret);
5778 }
5779 return block_rsv;
5780 }
5781
5782 ret = block_rsv_use_bytes(block_rsv, blocksize);
5783 if (!ret)
5784 return block_rsv;
5785 if (ret) {
5786 WARN_ON(1);
5787 ret = reserve_metadata_bytes(trans, root, block_rsv, blocksize,
5788 0);
5789 if (!ret) {
5790 spin_lock(&block_rsv->lock);
5791 block_rsv->size += blocksize;
5792 spin_unlock(&block_rsv->lock);
5793 return block_rsv;
5794 } else if (ret && block_rsv != global_rsv) {
5795 ret = block_rsv_use_bytes(global_rsv, blocksize);
5796 if (!ret)
5797 return global_rsv;
5798 }
5799 }
5800
5801 return ERR_PTR(-ENOSPC);
5802 }
5803
5804 static void unuse_block_rsv(struct btrfs_block_rsv *block_rsv, u32 blocksize)
5805 {
5806 block_rsv_add_bytes(block_rsv, blocksize, 0);
5807 block_rsv_release_bytes(block_rsv, NULL, 0);
5808 }
5809
5810 /*
5811 * finds a free extent and does all the dirty work required for allocation
5812 * returns the key for the extent through ins, and a tree buffer for
5813 * the first block of the extent through buf.
5814 *
5815 * returns the tree buffer or NULL.
5816 */
5817 struct extent_buffer *btrfs_alloc_free_block(struct btrfs_trans_handle *trans,
5818 struct btrfs_root *root, u32 blocksize,
5819 u64 parent, u64 root_objectid,
5820 struct btrfs_disk_key *key, int level,
5821 u64 hint, u64 empty_size)
5822 {
5823 struct btrfs_key ins;
5824 struct btrfs_block_rsv *block_rsv;
5825 struct extent_buffer *buf;
5826 u64 flags = 0;
5827 int ret;
5828
5829
5830 block_rsv = use_block_rsv(trans, root, blocksize);
5831 if (IS_ERR(block_rsv))
5832 return ERR_CAST(block_rsv);
5833
5834 ret = btrfs_reserve_extent(trans, root, blocksize, blocksize,
5835 empty_size, hint, (u64)-1, &ins, 0);
5836 if (ret) {
5837 unuse_block_rsv(block_rsv, blocksize);
5838 return ERR_PTR(ret);
5839 }
5840
5841 buf = btrfs_init_new_buffer(trans, root, ins.objectid,
5842 blocksize, level);
5843 BUG_ON(IS_ERR(buf));
5844
5845 if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
5846 if (parent == 0)
5847 parent = ins.objectid;
5848 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
5849 } else
5850 BUG_ON(parent > 0);
5851
5852 if (root_objectid != BTRFS_TREE_LOG_OBJECTID) {
5853 struct btrfs_delayed_extent_op *extent_op;
5854 extent_op = kmalloc(sizeof(*extent_op), GFP_NOFS);
5855 BUG_ON(!extent_op);
5856 if (key)
5857 memcpy(&extent_op->key, key, sizeof(extent_op->key));
5858 else
5859 memset(&extent_op->key, 0, sizeof(extent_op->key));
5860 extent_op->flags_to_set = flags;
5861 extent_op->update_key = 1;
5862 extent_op->update_flags = 1;
5863 extent_op->is_data = 0;
5864
5865 ret = btrfs_add_delayed_tree_ref(trans, ins.objectid,
5866 ins.offset, parent, root_objectid,
5867 level, BTRFS_ADD_DELAYED_EXTENT,
5868 extent_op);
5869 BUG_ON(ret);
5870 }
5871 return buf;
5872 }
5873
5874 struct walk_control {
5875 u64 refs[BTRFS_MAX_LEVEL];
5876 u64 flags[BTRFS_MAX_LEVEL];
5877 struct btrfs_key update_progress;
5878 int stage;
5879 int level;
5880 int shared_level;
5881 int update_ref;
5882 int keep_locks;
5883 int reada_slot;
5884 int reada_count;
5885 };
5886
5887 #define DROP_REFERENCE 1
5888 #define UPDATE_BACKREF 2
5889
5890 static noinline void reada_walk_down(struct btrfs_trans_handle *trans,
5891 struct btrfs_root *root,
5892 struct walk_control *wc,
5893 struct btrfs_path *path)
5894 {
5895 u64 bytenr;
5896 u64 generation;
5897 u64 refs;
5898 u64 flags;
5899 u32 nritems;
5900 u32 blocksize;
5901 struct btrfs_key key;
5902 struct extent_buffer *eb;
5903 int ret;
5904 int slot;
5905 int nread = 0;
5906
5907 if (path->slots[wc->level] < wc->reada_slot) {
5908 wc->reada_count = wc->reada_count * 2 / 3;
5909 wc->reada_count = max(wc->reada_count, 2);
5910 } else {
5911 wc->reada_count = wc->reada_count * 3 / 2;
5912 wc->reada_count = min_t(int, wc->reada_count,
5913 BTRFS_NODEPTRS_PER_BLOCK(root));
5914 }
5915
5916 eb = path->nodes[wc->level];
5917 nritems = btrfs_header_nritems(eb);
5918 blocksize = btrfs_level_size(root, wc->level - 1);
5919
5920 for (slot = path->slots[wc->level]; slot < nritems; slot++) {
5921 if (nread >= wc->reada_count)
5922 break;
5923
5924 cond_resched();
5925 bytenr = btrfs_node_blockptr(eb, slot);
5926 generation = btrfs_node_ptr_generation(eb, slot);
5927
5928 if (slot == path->slots[wc->level])
5929 goto reada;
5930
5931 if (wc->stage == UPDATE_BACKREF &&
5932 generation <= root->root_key.offset)
5933 continue;
5934
5935 /* We don't lock the tree block, it's OK to be racy here */
5936 ret = btrfs_lookup_extent_info(trans, root, bytenr, blocksize,
5937 &refs, &flags);
5938 BUG_ON(ret);
5939 BUG_ON(refs == 0);
5940
5941 if (wc->stage == DROP_REFERENCE) {
5942 if (refs == 1)
5943 goto reada;
5944
5945 if (wc->level == 1 &&
5946 (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
5947 continue;
5948 if (!wc->update_ref ||
5949 generation <= root->root_key.offset)
5950 continue;
5951 btrfs_node_key_to_cpu(eb, &key, slot);
5952 ret = btrfs_comp_cpu_keys(&key,
5953 &wc->update_progress);
5954 if (ret < 0)
5955 continue;
5956 } else {
5957 if (wc->level == 1 &&
5958 (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
5959 continue;
5960 }
5961 reada:
5962 ret = readahead_tree_block(root, bytenr, blocksize,
5963 generation);
5964 if (ret)
5965 break;
5966 nread++;
5967 }
5968 wc->reada_slot = slot;
5969 }
5970
5971 /*
5972 * hepler to process tree block while walking down the tree.
5973 *
5974 * when wc->stage == UPDATE_BACKREF, this function updates
5975 * back refs for pointers in the block.
5976 *
5977 * NOTE: return value 1 means we should stop walking down.
5978 */
5979 static noinline int walk_down_proc(struct btrfs_trans_handle *trans,
5980 struct btrfs_root *root,
5981 struct btrfs_path *path,
5982 struct walk_control *wc, int lookup_info)
5983 {
5984 int level = wc->level;
5985 struct extent_buffer *eb = path->nodes[level];
5986 u64 flag = BTRFS_BLOCK_FLAG_FULL_BACKREF;
5987 int ret;
5988
5989 if (wc->stage == UPDATE_BACKREF &&
5990 btrfs_header_owner(eb) != root->root_key.objectid)
5991 return 1;
5992
5993 /*
5994 * when reference count of tree block is 1, it won't increase
5995 * again. once full backref flag is set, we never clear it.
5996 */
5997 if (lookup_info &&
5998 ((wc->stage == DROP_REFERENCE && wc->refs[level] != 1) ||
5999 (wc->stage == UPDATE_BACKREF && !(wc->flags[level] & flag)))) {
6000 BUG_ON(!path->locks[level]);
6001 ret = btrfs_lookup_extent_info(trans, root,
6002 eb->start, eb->len,
6003 &wc->refs[level],
6004 &wc->flags[level]);
6005 BUG_ON(ret);
6006 BUG_ON(wc->refs[level] == 0);
6007 }
6008
6009 if (wc->stage == DROP_REFERENCE) {
6010 if (wc->refs[level] > 1)
6011 return 1;
6012
6013 if (path->locks[level] && !wc->keep_locks) {
6014 btrfs_tree_unlock(eb);
6015 path->locks[level] = 0;
6016 }
6017 return 0;
6018 }
6019
6020 /* wc->stage == UPDATE_BACKREF */
6021 if (!(wc->flags[level] & flag)) {
6022 BUG_ON(!path->locks[level]);
6023 ret = btrfs_inc_ref(trans, root, eb, 1);
6024 BUG_ON(ret);
6025 ret = btrfs_dec_ref(trans, root, eb, 0);
6026 BUG_ON(ret);
6027 ret = btrfs_set_disk_extent_flags(trans, root, eb->start,
6028 eb->len, flag, 0);
6029 BUG_ON(ret);
6030 wc->flags[level] |= flag;
6031 }
6032
6033 /*
6034 * the block is shared by multiple trees, so it's not good to
6035 * keep the tree lock
6036 */
6037 if (path->locks[level] && level > 0) {
6038 btrfs_tree_unlock(eb);
6039 path->locks[level] = 0;
6040 }
6041 return 0;
6042 }
6043
6044 /*
6045 * hepler to process tree block pointer.
6046 *
6047 * when wc->stage == DROP_REFERENCE, this function checks
6048 * reference count of the block pointed to. if the block
6049 * is shared and we need update back refs for the subtree
6050 * rooted at the block, this function changes wc->stage to
6051 * UPDATE_BACKREF. if the block is shared and there is no
6052 * need to update back, this function drops the reference
6053 * to the block.
6054 *
6055 * NOTE: return value 1 means we should stop walking down.
6056 */
6057 static noinline int do_walk_down(struct btrfs_trans_handle *trans,
6058 struct btrfs_root *root,
6059 struct btrfs_path *path,
6060 struct walk_control *wc, int *lookup_info)
6061 {
6062 u64 bytenr;
6063 u64 generation;
6064 u64 parent;
6065 u32 blocksize;
6066 struct btrfs_key key;
6067 struct extent_buffer *next;
6068 int level = wc->level;
6069 int reada = 0;
6070 int ret = 0;
6071
6072 generation = btrfs_node_ptr_generation(path->nodes[level],
6073 path->slots[level]);
6074 /*
6075 * if the lower level block was created before the snapshot
6076 * was created, we know there is no need to update back refs
6077 * for the subtree
6078 */
6079 if (wc->stage == UPDATE_BACKREF &&
6080 generation <= root->root_key.offset) {
6081 *lookup_info = 1;
6082 return 1;
6083 }
6084
6085 bytenr = btrfs_node_blockptr(path->nodes[level], path->slots[level]);
6086 blocksize = btrfs_level_size(root, level - 1);
6087
6088 next = btrfs_find_tree_block(root, bytenr, blocksize);
6089 if (!next) {
6090 next = btrfs_find_create_tree_block(root, bytenr, blocksize);
6091 if (!next)
6092 return -ENOMEM;
6093 reada = 1;
6094 }
6095 btrfs_tree_lock(next);
6096 btrfs_set_lock_blocking(next);
6097
6098 ret = btrfs_lookup_extent_info(trans, root, bytenr, blocksize,
6099 &wc->refs[level - 1],
6100 &wc->flags[level - 1]);
6101 BUG_ON(ret);
6102 BUG_ON(wc->refs[level - 1] == 0);
6103 *lookup_info = 0;
6104
6105 if (wc->stage == DROP_REFERENCE) {
6106 if (wc->refs[level - 1] > 1) {
6107 if (level == 1 &&
6108 (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
6109 goto skip;
6110
6111 if (!wc->update_ref ||
6112 generation <= root->root_key.offset)
6113 goto skip;
6114
6115 btrfs_node_key_to_cpu(path->nodes[level], &key,
6116 path->slots[level]);
6117 ret = btrfs_comp_cpu_keys(&key, &wc->update_progress);
6118 if (ret < 0)
6119 goto skip;
6120
6121 wc->stage = UPDATE_BACKREF;
6122 wc->shared_level = level - 1;
6123 }
6124 } else {
6125 if (level == 1 &&
6126 (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
6127 goto skip;
6128 }
6129
6130 if (!btrfs_buffer_uptodate(next, generation)) {
6131 btrfs_tree_unlock(next);
6132 free_extent_buffer(next);
6133 next = NULL;
6134 *lookup_info = 1;
6135 }
6136
6137 if (!next) {
6138 if (reada && level == 1)
6139 reada_walk_down(trans, root, wc, path);
6140 next = read_tree_block(root, bytenr, blocksize, generation);
6141 if (!next)
6142 return -EIO;
6143 btrfs_tree_lock(next);
6144 btrfs_set_lock_blocking(next);
6145 }
6146
6147 level--;
6148 BUG_ON(level != btrfs_header_level(next));
6149 path->nodes[level] = next;
6150 path->slots[level] = 0;
6151 path->locks[level] = 1;
6152 wc->level = level;
6153 if (wc->level == 1)
6154 wc->reada_slot = 0;
6155 return 0;
6156 skip:
6157 wc->refs[level - 1] = 0;
6158 wc->flags[level - 1] = 0;
6159 if (wc->stage == DROP_REFERENCE) {
6160 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
6161 parent = path->nodes[level]->start;
6162 } else {
6163 BUG_ON(root->root_key.objectid !=
6164 btrfs_header_owner(path->nodes[level]));
6165 parent = 0;
6166 }
6167
6168 ret = btrfs_free_extent(trans, root, bytenr, blocksize, parent,
6169 root->root_key.objectid, level - 1, 0);
6170 BUG_ON(ret);
6171 }
6172 btrfs_tree_unlock(next);
6173 free_extent_buffer(next);
6174 *lookup_info = 1;
6175 return 1;
6176 }
6177
6178 /*
6179 * hepler to process tree block while walking up the tree.
6180 *
6181 * when wc->stage == DROP_REFERENCE, this function drops
6182 * reference count on the block.
6183 *
6184 * when wc->stage == UPDATE_BACKREF, this function changes
6185 * wc->stage back to DROP_REFERENCE if we changed wc->stage
6186 * to UPDATE_BACKREF previously while processing the block.
6187 *
6188 * NOTE: return value 1 means we should stop walking up.
6189 */
6190 static noinline int walk_up_proc(struct btrfs_trans_handle *trans,
6191 struct btrfs_root *root,
6192 struct btrfs_path *path,
6193 struct walk_control *wc)
6194 {
6195 int ret;
6196 int level = wc->level;
6197 struct extent_buffer *eb = path->nodes[level];
6198 u64 parent = 0;
6199
6200 if (wc->stage == UPDATE_BACKREF) {
6201 BUG_ON(wc->shared_level < level);
6202 if (level < wc->shared_level)
6203 goto out;
6204
6205 ret = find_next_key(path, level + 1, &wc->update_progress);
6206 if (ret > 0)
6207 wc->update_ref = 0;
6208
6209 wc->stage = DROP_REFERENCE;
6210 wc->shared_level = -1;
6211 path->slots[level] = 0;
6212
6213 /*
6214 * check reference count again if the block isn't locked.
6215 * we should start walking down the tree again if reference
6216 * count is one.
6217 */
6218 if (!path->locks[level]) {
6219 BUG_ON(level == 0);
6220 btrfs_tree_lock(eb);
6221 btrfs_set_lock_blocking(eb);
6222 path->locks[level] = 1;
6223
6224 ret = btrfs_lookup_extent_info(trans, root,
6225 eb->start, eb->len,
6226 &wc->refs[level],
6227 &wc->flags[level]);
6228 BUG_ON(ret);
6229 BUG_ON(wc->refs[level] == 0);
6230 if (wc->refs[level] == 1) {
6231 btrfs_tree_unlock(eb);
6232 path->locks[level] = 0;
6233 return 1;
6234 }
6235 }
6236 }
6237
6238 /* wc->stage == DROP_REFERENCE */
6239 BUG_ON(wc->refs[level] > 1 && !path->locks[level]);
6240
6241 if (wc->refs[level] == 1) {
6242 if (level == 0) {
6243 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
6244 ret = btrfs_dec_ref(trans, root, eb, 1);
6245 else
6246 ret = btrfs_dec_ref(trans, root, eb, 0);
6247 BUG_ON(ret);
6248 }
6249 /* make block locked assertion in clean_tree_block happy */
6250 if (!path->locks[level] &&
6251 btrfs_header_generation(eb) == trans->transid) {
6252 btrfs_tree_lock(eb);
6253 btrfs_set_lock_blocking(eb);
6254 path->locks[level] = 1;
6255 }
6256 clean_tree_block(trans, root, eb);
6257 }
6258
6259 if (eb == root->node) {
6260 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
6261 parent = eb->start;
6262 else
6263 BUG_ON(root->root_key.objectid !=
6264 btrfs_header_owner(eb));
6265 } else {
6266 if (wc->flags[level + 1] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
6267 parent = path->nodes[level + 1]->start;
6268 else
6269 BUG_ON(root->root_key.objectid !=
6270 btrfs_header_owner(path->nodes[level + 1]));
6271 }
6272
6273 btrfs_free_tree_block(trans, root, eb, parent, wc->refs[level] == 1);
6274 out:
6275 wc->refs[level] = 0;
6276 wc->flags[level] = 0;
6277 return 0;
6278 }
6279
6280 static noinline int walk_down_tree(struct btrfs_trans_handle *trans,
6281 struct btrfs_root *root,
6282 struct btrfs_path *path,
6283 struct walk_control *wc)
6284 {
6285 int level = wc->level;
6286 int lookup_info = 1;
6287 int ret;
6288
6289 while (level >= 0) {
6290 ret = walk_down_proc(trans, root, path, wc, lookup_info);
6291 if (ret > 0)
6292 break;
6293
6294 if (level == 0)
6295 break;
6296
6297 if (path->slots[level] >=
6298 btrfs_header_nritems(path->nodes[level]))
6299 break;
6300
6301 ret = do_walk_down(trans, root, path, wc, &lookup_info);
6302 if (ret > 0) {
6303 path->slots[level]++;
6304 continue;
6305 } else if (ret < 0)
6306 return ret;
6307 level = wc->level;
6308 }
6309 return 0;
6310 }
6311
6312 static noinline int walk_up_tree(struct btrfs_trans_handle *trans,
6313 struct btrfs_root *root,
6314 struct btrfs_path *path,
6315 struct walk_control *wc, int max_level)
6316 {
6317 int level = wc->level;
6318 int ret;
6319
6320 path->slots[level] = btrfs_header_nritems(path->nodes[level]);
6321 while (level < max_level && path->nodes[level]) {
6322 wc->level = level;
6323 if (path->slots[level] + 1 <
6324 btrfs_header_nritems(path->nodes[level])) {
6325 path->slots[level]++;
6326 return 0;
6327 } else {
6328 ret = walk_up_proc(trans, root, path, wc);
6329 if (ret > 0)
6330 return 0;
6331
6332 if (path->locks[level]) {
6333 btrfs_tree_unlock(path->nodes[level]);
6334 path->locks[level] = 0;
6335 }
6336 free_extent_buffer(path->nodes[level]);
6337 path->nodes[level] = NULL;
6338 level++;
6339 }
6340 }
6341 return 1;
6342 }
6343
6344 /*
6345 * drop a subvolume tree.
6346 *
6347 * this function traverses the tree freeing any blocks that only
6348 * referenced by the tree.
6349 *
6350 * when a shared tree block is found. this function decreases its
6351 * reference count by one. if update_ref is true, this function
6352 * also make sure backrefs for the shared block and all lower level
6353 * blocks are properly updated.
6354 */
6355 int btrfs_drop_snapshot(struct btrfs_root *root,
6356 struct btrfs_block_rsv *block_rsv, int update_ref)
6357 {
6358 struct btrfs_path *path;
6359 struct btrfs_trans_handle *trans;
6360 struct btrfs_root *tree_root = root->fs_info->tree_root;
6361 struct btrfs_root_item *root_item = &root->root_item;
6362 struct walk_control *wc;
6363 struct btrfs_key key;
6364 int err = 0;
6365 int ret;
6366 int level;
6367
6368 path = btrfs_alloc_path();
6369 BUG_ON(!path);
6370
6371 wc = kzalloc(sizeof(*wc), GFP_NOFS);
6372 BUG_ON(!wc);
6373
6374 trans = btrfs_start_transaction(tree_root, 0);
6375 BUG_ON(IS_ERR(trans));
6376
6377 if (block_rsv)
6378 trans->block_rsv = block_rsv;
6379
6380 if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
6381 level = btrfs_header_level(root->node);
6382 path->nodes[level] = btrfs_lock_root_node(root);
6383 btrfs_set_lock_blocking(path->nodes[level]);
6384 path->slots[level] = 0;
6385 path->locks[level] = 1;
6386 memset(&wc->update_progress, 0,
6387 sizeof(wc->update_progress));
6388 } else {
6389 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
6390 memcpy(&wc->update_progress, &key,
6391 sizeof(wc->update_progress));
6392
6393 level = root_item->drop_level;
6394 BUG_ON(level == 0);
6395 path->lowest_level = level;
6396 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6397 path->lowest_level = 0;
6398 if (ret < 0) {
6399 err = ret;
6400 goto out;
6401 }
6402 WARN_ON(ret > 0);
6403
6404 /*
6405 * unlock our path, this is safe because only this
6406 * function is allowed to delete this snapshot
6407 */
6408 btrfs_unlock_up_safe(path, 0);
6409
6410 level = btrfs_header_level(root->node);
6411 while (1) {
6412 btrfs_tree_lock(path->nodes[level]);
6413 btrfs_set_lock_blocking(path->nodes[level]);
6414
6415 ret = btrfs_lookup_extent_info(trans, root,
6416 path->nodes[level]->start,
6417 path->nodes[level]->len,
6418 &wc->refs[level],
6419 &wc->flags[level]);
6420 BUG_ON(ret);
6421 BUG_ON(wc->refs[level] == 0);
6422
6423 if (level == root_item->drop_level)
6424 break;
6425
6426 btrfs_tree_unlock(path->nodes[level]);
6427 WARN_ON(wc->refs[level] != 1);
6428 level--;
6429 }
6430 }
6431
6432 wc->level = level;
6433 wc->shared_level = -1;
6434 wc->stage = DROP_REFERENCE;
6435 wc->update_ref = update_ref;
6436 wc->keep_locks = 0;
6437 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(root);
6438
6439 while (1) {
6440 ret = walk_down_tree(trans, root, path, wc);
6441 if (ret < 0) {
6442 err = ret;
6443 break;
6444 }
6445
6446 ret = walk_up_tree(trans, root, path, wc, BTRFS_MAX_LEVEL);
6447 if (ret < 0) {
6448 err = ret;
6449 break;
6450 }
6451
6452 if (ret > 0) {
6453 BUG_ON(wc->stage != DROP_REFERENCE);
6454 break;
6455 }
6456
6457 if (wc->stage == DROP_REFERENCE) {
6458 level = wc->level;
6459 btrfs_node_key(path->nodes[level],
6460 &root_item->drop_progress,
6461 path->slots[level]);
6462 root_item->drop_level = level;
6463 }
6464
6465 BUG_ON(wc->level == 0);
6466 if (btrfs_should_end_transaction(trans, tree_root)) {
6467 ret = btrfs_update_root(trans, tree_root,
6468 &root->root_key,
6469 root_item);
6470 BUG_ON(ret);
6471
6472 btrfs_end_transaction_throttle(trans, tree_root);
6473 trans = btrfs_start_transaction(tree_root, 0);
6474 BUG_ON(IS_ERR(trans));
6475 if (block_rsv)
6476 trans->block_rsv = block_rsv;
6477 }
6478 }
6479 btrfs_release_path(root, path);
6480 BUG_ON(err);
6481
6482 ret = btrfs_del_root(trans, tree_root, &root->root_key);
6483 BUG_ON(ret);
6484
6485 if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
6486 ret = btrfs_find_last_root(tree_root, root->root_key.objectid,
6487 NULL, NULL);
6488 BUG_ON(ret < 0);
6489 if (ret > 0) {
6490 /* if we fail to delete the orphan item this time
6491 * around, it'll get picked up the next time.
6492 *
6493 * The most common failure here is just -ENOENT.
6494 */
6495 btrfs_del_orphan_item(trans, tree_root,
6496 root->root_key.objectid);
6497 }
6498 }
6499
6500 if (root->in_radix) {
6501 btrfs_free_fs_root(tree_root->fs_info, root);
6502 } else {
6503 free_extent_buffer(root->node);
6504 free_extent_buffer(root->commit_root);
6505 kfree(root);
6506 }
6507 out:
6508 btrfs_end_transaction_throttle(trans, tree_root);
6509 kfree(wc);
6510 btrfs_free_path(path);
6511 return err;
6512 }
6513
6514 /*
6515 * drop subtree rooted at tree block 'node'.
6516 *
6517 * NOTE: this function will unlock and release tree block 'node'
6518 */
6519 int btrfs_drop_subtree(struct btrfs_trans_handle *trans,
6520 struct btrfs_root *root,
6521 struct extent_buffer *node,
6522 struct extent_buffer *parent)
6523 {
6524 struct btrfs_path *path;
6525 struct walk_control *wc;
6526 int level;
6527 int parent_level;
6528 int ret = 0;
6529 int wret;
6530
6531 BUG_ON(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
6532
6533 path = btrfs_alloc_path();
6534 if (!path)
6535 return -ENOMEM;
6536
6537 wc = kzalloc(sizeof(*wc), GFP_NOFS);
6538 if (!wc) {
6539 btrfs_free_path(path);
6540 return -ENOMEM;
6541 }
6542
6543 btrfs_assert_tree_locked(parent);
6544 parent_level = btrfs_header_level(parent);
6545 extent_buffer_get(parent);
6546 path->nodes[parent_level] = parent;
6547 path->slots[parent_level] = btrfs_header_nritems(parent);
6548
6549 btrfs_assert_tree_locked(node);
6550 level = btrfs_header_level(node);
6551 path->nodes[level] = node;
6552 path->slots[level] = 0;
6553 path->locks[level] = 1;
6554
6555 wc->refs[parent_level] = 1;
6556 wc->flags[parent_level] = BTRFS_BLOCK_FLAG_FULL_BACKREF;
6557 wc->level = level;
6558 wc->shared_level = -1;
6559 wc->stage = DROP_REFERENCE;
6560 wc->update_ref = 0;
6561 wc->keep_locks = 1;
6562 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(root);
6563
6564 while (1) {
6565 wret = walk_down_tree(trans, root, path, wc);
6566 if (wret < 0) {
6567 ret = wret;
6568 break;
6569 }
6570
6571 wret = walk_up_tree(trans, root, path, wc, parent_level);
6572 if (wret < 0)
6573 ret = wret;
6574 if (wret != 0)
6575 break;
6576 }
6577
6578 kfree(wc);
6579 btrfs_free_path(path);
6580 return ret;
6581 }
6582
6583 #if 0
6584 static unsigned long calc_ra(unsigned long start, unsigned long last,
6585 unsigned long nr)
6586 {
6587 return min(last, start + nr - 1);
6588 }
6589
6590 static noinline int relocate_inode_pages(struct inode *inode, u64 start,
6591 u64 len)
6592 {
6593 u64 page_start;
6594 u64 page_end;
6595 unsigned long first_index;
6596 unsigned long last_index;
6597 unsigned long i;
6598 struct page *page;
6599 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6600 struct file_ra_state *ra;
6601 struct btrfs_ordered_extent *ordered;
6602 unsigned int total_read = 0;
6603 unsigned int total_dirty = 0;
6604 int ret = 0;
6605
6606 ra = kzalloc(sizeof(*ra), GFP_NOFS);
6607 if (!ra)
6608 return -ENOMEM;
6609
6610 mutex_lock(&inode->i_mutex);
6611 first_index = start >> PAGE_CACHE_SHIFT;
6612 last_index = (start + len - 1) >> PAGE_CACHE_SHIFT;
6613
6614 /* make sure the dirty trick played by the caller work */
6615 ret = invalidate_inode_pages2_range(inode->i_mapping,
6616 first_index, last_index);
6617 if (ret)
6618 goto out_unlock;
6619
6620 file_ra_state_init(ra, inode->i_mapping);
6621
6622 for (i = first_index ; i <= last_index; i++) {
6623 if (total_read % ra->ra_pages == 0) {
6624 btrfs_force_ra(inode->i_mapping, ra, NULL, i,
6625 calc_ra(i, last_index, ra->ra_pages));
6626 }
6627 total_read++;
6628 again:
6629 if (((u64)i << PAGE_CACHE_SHIFT) > i_size_read(inode))
6630 BUG_ON(1);
6631 page = grab_cache_page(inode->i_mapping, i);
6632 if (!page) {
6633 ret = -ENOMEM;
6634 goto out_unlock;
6635 }
6636 if (!PageUptodate(page)) {
6637 btrfs_readpage(NULL, page);
6638 lock_page(page);
6639 if (!PageUptodate(page)) {
6640 unlock_page(page);
6641 page_cache_release(page);
6642 ret = -EIO;
6643 goto out_unlock;
6644 }
6645 }
6646 wait_on_page_writeback(page);
6647
6648 page_start = (u64)page->index << PAGE_CACHE_SHIFT;
6649 page_end = page_start + PAGE_CACHE_SIZE - 1;
6650 lock_extent(io_tree, page_start, page_end, GFP_NOFS);
6651
6652 ordered = btrfs_lookup_ordered_extent(inode, page_start);
6653 if (ordered) {
6654 unlock_extent(io_tree, page_start, page_end, GFP_NOFS);
6655 unlock_page(page);
6656 page_cache_release(page);
6657 btrfs_start_ordered_extent(inode, ordered, 1);
6658 btrfs_put_ordered_extent(ordered);
6659 goto again;
6660 }
6661 set_page_extent_mapped(page);
6662
6663 if (i == first_index)
6664 set_extent_bits(io_tree, page_start, page_end,
6665 EXTENT_BOUNDARY, GFP_NOFS);
6666 btrfs_set_extent_delalloc(inode, page_start, page_end);
6667
6668 set_page_dirty(page);
6669 total_dirty++;
6670
6671 unlock_extent(io_tree, page_start, page_end, GFP_NOFS);
6672 unlock_page(page);
6673 page_cache_release(page);
6674 }
6675
6676 out_unlock:
6677 kfree(ra);
6678 mutex_unlock(&inode->i_mutex);
6679 balance_dirty_pages_ratelimited_nr(inode->i_mapping, total_dirty);
6680 return ret;
6681 }
6682
6683 static noinline int relocate_data_extent(struct inode *reloc_inode,
6684 struct btrfs_key *extent_key,
6685 u64 offset)
6686 {
6687 struct btrfs_root *root = BTRFS_I(reloc_inode)->root;
6688 struct extent_map_tree *em_tree = &BTRFS_I(reloc_inode)->extent_tree;
6689 struct extent_map *em;
6690 u64 start = extent_key->objectid - offset;
6691 u64 end = start + extent_key->offset - 1;
6692
6693 em = alloc_extent_map(GFP_NOFS);
6694 BUG_ON(!em);
6695
6696 em->start = start;
6697 em->len = extent_key->offset;
6698 em->block_len = extent_key->offset;
6699 em->block_start = extent_key->objectid;
6700 em->bdev = root->fs_info->fs_devices->latest_bdev;
6701 set_bit(EXTENT_FLAG_PINNED, &em->flags);
6702
6703 /* setup extent map to cheat btrfs_readpage */
6704 lock_extent(&BTRFS_I(reloc_inode)->io_tree, start, end, GFP_NOFS);
6705 while (1) {
6706 int ret;
6707 write_lock(&em_tree->lock);
6708 ret = add_extent_mapping(em_tree, em);
6709 write_unlock(&em_tree->lock);
6710 if (ret != -EEXIST) {
6711 free_extent_map(em);
6712 break;
6713 }
6714 btrfs_drop_extent_cache(reloc_inode, start, end, 0);
6715 }
6716 unlock_extent(&BTRFS_I(reloc_inode)->io_tree, start, end, GFP_NOFS);
6717
6718 return relocate_inode_pages(reloc_inode, start, extent_key->offset);
6719 }
6720
6721 struct btrfs_ref_path {
6722 u64 extent_start;
6723 u64 nodes[BTRFS_MAX_LEVEL];
6724 u64 root_objectid;
6725 u64 root_generation;
6726 u64 owner_objectid;
6727 u32 num_refs;
6728 int lowest_level;
6729 int current_level;
6730 int shared_level;
6731
6732 struct btrfs_key node_keys[BTRFS_MAX_LEVEL];
6733 u64 new_nodes[BTRFS_MAX_LEVEL];
6734 };
6735
6736 struct disk_extent {
6737 u64 ram_bytes;
6738 u64 disk_bytenr;
6739 u64 disk_num_bytes;
6740 u64 offset;
6741 u64 num_bytes;
6742 u8 compression;
6743 u8 encryption;
6744 u16 other_encoding;
6745 };
6746
6747 static int is_cowonly_root(u64 root_objectid)
6748 {
6749 if (root_objectid == BTRFS_ROOT_TREE_OBJECTID ||
6750 root_objectid == BTRFS_EXTENT_TREE_OBJECTID ||
6751 root_objectid == BTRFS_CHUNK_TREE_OBJECTID ||
6752 root_objectid == BTRFS_DEV_TREE_OBJECTID ||
6753 root_objectid == BTRFS_TREE_LOG_OBJECTID ||
6754 root_objectid == BTRFS_CSUM_TREE_OBJECTID)
6755 return 1;
6756 return 0;
6757 }
6758
6759 static noinline int __next_ref_path(struct btrfs_trans_handle *trans,
6760 struct btrfs_root *extent_root,
6761 struct btrfs_ref_path *ref_path,
6762 int first_time)
6763 {
6764 struct extent_buffer *leaf;
6765 struct btrfs_path *path;
6766 struct btrfs_extent_ref *ref;
6767 struct btrfs_key key;
6768 struct btrfs_key found_key;
6769 u64 bytenr;
6770 u32 nritems;
6771 int level;
6772 int ret = 1;
6773
6774 path = btrfs_alloc_path();
6775 if (!path)
6776 return -ENOMEM;
6777
6778 if (first_time) {
6779 ref_path->lowest_level = -1;
6780 ref_path->current_level = -1;
6781 ref_path->shared_level = -1;
6782 goto walk_up;
6783 }
6784 walk_down:
6785 level = ref_path->current_level - 1;
6786 while (level >= -1) {
6787 u64 parent;
6788 if (level < ref_path->lowest_level)
6789 break;
6790
6791 if (level >= 0)
6792 bytenr = ref_path->nodes[level];
6793 else
6794 bytenr = ref_path->extent_start;
6795 BUG_ON(bytenr == 0);
6796
6797 parent = ref_path->nodes[level + 1];
6798 ref_path->nodes[level + 1] = 0;
6799 ref_path->current_level = level;
6800 BUG_ON(parent == 0);
6801
6802 key.objectid = bytenr;
6803 key.offset = parent + 1;
6804 key.type = BTRFS_EXTENT_REF_KEY;
6805
6806 ret = btrfs_search_slot(trans, extent_root, &key, path, 0, 0);
6807 if (ret < 0)
6808 goto out;
6809 BUG_ON(ret == 0);
6810
6811 leaf = path->nodes[0];
6812 nritems = btrfs_header_nritems(leaf);
6813 if (path->slots[0] >= nritems) {
6814 ret = btrfs_next_leaf(extent_root, path);
6815 if (ret < 0)
6816 goto out;
6817 if (ret > 0)
6818 goto next;
6819 leaf = path->nodes[0];
6820 }
6821
6822 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6823 if (found_key.objectid == bytenr &&
6824 found_key.type == BTRFS_EXTENT_REF_KEY) {
6825 if (level < ref_path->shared_level)
6826 ref_path->shared_level = level;
6827 goto found;
6828 }
6829 next:
6830 level--;
6831 btrfs_release_path(extent_root, path);
6832 cond_resched();
6833 }
6834 /* reached lowest level */
6835 ret = 1;
6836 goto out;
6837 walk_up:
6838 level = ref_path->current_level;
6839 while (level < BTRFS_MAX_LEVEL - 1) {
6840 u64 ref_objectid;
6841
6842 if (level >= 0)
6843 bytenr = ref_path->nodes[level];
6844 else
6845 bytenr = ref_path->extent_start;
6846
6847 BUG_ON(bytenr == 0);
6848
6849 key.objectid = bytenr;
6850 key.offset = 0;
6851 key.type = BTRFS_EXTENT_REF_KEY;
6852
6853 ret = btrfs_search_slot(trans, extent_root, &key, path, 0, 0);
6854 if (ret < 0)
6855 goto out;
6856
6857 leaf = path->nodes[0];
6858 nritems = btrfs_header_nritems(leaf);
6859 if (path->slots[0] >= nritems) {
6860 ret = btrfs_next_leaf(extent_root, path);
6861 if (ret < 0)
6862 goto out;
6863 if (ret > 0) {
6864 /* the extent was freed by someone */
6865 if (ref_path->lowest_level == level)
6866 goto out;
6867 btrfs_release_path(extent_root, path);
6868 goto walk_down;
6869 }
6870 leaf = path->nodes[0];
6871 }
6872
6873 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6874 if (found_key.objectid != bytenr ||
6875 found_key.type != BTRFS_EXTENT_REF_KEY) {
6876 /* the extent was freed by someone */
6877 if (ref_path->lowest_level == level) {
6878 ret = 1;
6879 goto out;
6880 }
6881 btrfs_release_path(extent_root, path);
6882 goto walk_down;
6883 }
6884 found:
6885 ref = btrfs_item_ptr(leaf, path->slots[0],
6886 struct btrfs_extent_ref);
6887 ref_objectid = btrfs_ref_objectid(leaf, ref);
6888 if (ref_objectid < BTRFS_FIRST_FREE_OBJECTID) {
6889 if (first_time) {
6890 level = (int)ref_objectid;
6891 BUG_ON(level >= BTRFS_MAX_LEVEL);
6892 ref_path->lowest_level = level;
6893 ref_path->current_level = level;
6894 ref_path->nodes[level] = bytenr;
6895 } else {
6896 WARN_ON(ref_objectid != level);
6897 }
6898 } else {
6899 WARN_ON(level != -1);
6900 }
6901 first_time = 0;
6902
6903 if (ref_path->lowest_level == level) {
6904 ref_path->owner_objectid = ref_objectid;
6905 ref_path->num_refs = btrfs_ref_num_refs(leaf, ref);
6906 }
6907
6908 /*
6909 * the block is tree root or the block isn't in reference
6910 * counted tree.
6911 */
6912 if (found_key.objectid == found_key.offset ||
6913 is_cowonly_root(btrfs_ref_root(leaf, ref))) {
6914 ref_path->root_objectid = btrfs_ref_root(leaf, ref);
6915 ref_path->root_generation =
6916 btrfs_ref_generation(leaf, ref);
6917 if (level < 0) {
6918 /* special reference from the tree log */
6919 ref_path->nodes[0] = found_key.offset;
6920 ref_path->current_level = 0;
6921 }
6922 ret = 0;
6923 goto out;
6924 }
6925
6926 level++;
6927 BUG_ON(ref_path->nodes[level] != 0);
6928 ref_path->nodes[level] = found_key.offset;
6929 ref_path->current_level = level;
6930
6931 /*
6932 * the reference was created in the running transaction,
6933 * no need to continue walking up.
6934 */
6935 if (btrfs_ref_generation(leaf, ref) == trans->transid) {
6936 ref_path->root_objectid = btrfs_ref_root(leaf, ref);
6937 ref_path->root_generation =
6938 btrfs_ref_generation(leaf, ref);
6939 ret = 0;
6940 goto out;
6941 }
6942
6943 btrfs_release_path(extent_root, path);
6944 cond_resched();
6945 }
6946 /* reached max tree level, but no tree root found. */
6947 BUG();
6948 out:
6949 btrfs_free_path(path);
6950 return ret;
6951 }
6952
6953 static int btrfs_first_ref_path(struct btrfs_trans_handle *trans,
6954 struct btrfs_root *extent_root,
6955 struct btrfs_ref_path *ref_path,
6956 u64 extent_start)
6957 {
6958 memset(ref_path, 0, sizeof(*ref_path));
6959 ref_path->extent_start = extent_start;
6960
6961 return __next_ref_path(trans, extent_root, ref_path, 1);
6962 }
6963
6964 static int btrfs_next_ref_path(struct btrfs_trans_handle *trans,
6965 struct btrfs_root *extent_root,
6966 struct btrfs_ref_path *ref_path)
6967 {
6968 return __next_ref_path(trans, extent_root, ref_path, 0);
6969 }
6970
6971 static noinline int get_new_locations(struct inode *reloc_inode,
6972 struct btrfs_key *extent_key,
6973 u64 offset, int no_fragment,
6974 struct disk_extent **extents,
6975 int *nr_extents)
6976 {
6977 struct btrfs_root *root = BTRFS_I(reloc_inode)->root;
6978 struct btrfs_path *path;
6979 struct btrfs_file_extent_item *fi;
6980 struct extent_buffer *leaf;
6981 struct disk_extent *exts = *extents;
6982 struct btrfs_key found_key;
6983 u64 cur_pos;
6984 u64 last_byte;
6985 u32 nritems;
6986 int nr = 0;
6987 int max = *nr_extents;
6988 int ret;
6989
6990 WARN_ON(!no_fragment && *extents);
6991 if (!exts) {
6992 max = 1;
6993 exts = kmalloc(sizeof(*exts) * max, GFP_NOFS);
6994 if (!exts)
6995 return -ENOMEM;
6996 }
6997
6998 path = btrfs_alloc_path();
6999 if (!path) {
7000 if (exts != *extents)
7001 kfree(exts);
7002 return -ENOMEM;
7003 }
7004
7005 cur_pos = extent_key->objectid - offset;
7006 last_byte = extent_key->objectid + extent_key->offset;
7007 ret = btrfs_lookup_file_extent(NULL, root, path,
7008 btrfs_ino(reloc_inode), cur_pos, 0);
7009 if (ret < 0)
7010 goto out;
7011 if (ret > 0) {
7012 ret = -ENOENT;
7013 goto out;
7014 }
7015
7016 while (1) {
7017 leaf = path->nodes[0];
7018 nritems = btrfs_header_nritems(leaf);
7019 if (path->slots[0] >= nritems) {
7020 ret = btrfs_next_leaf(root, path);
7021 if (ret < 0)
7022 goto out;
7023 if (ret > 0)
7024 break;
7025 leaf = path->nodes[0];
7026 }
7027
7028 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
7029 if (found_key.offset != cur_pos ||
7030 found_key.type != BTRFS_EXTENT_DATA_KEY ||
7031 found_key.objectid != btrfs_ino(reloc_inode))
7032 break;
7033
7034 fi = btrfs_item_ptr(leaf, path->slots[0],
7035 struct btrfs_file_extent_item);
7036 if (btrfs_file_extent_type(leaf, fi) !=
7037 BTRFS_FILE_EXTENT_REG ||
7038 btrfs_file_extent_disk_bytenr(leaf, fi) == 0)
7039 break;
7040
7041 if (nr == max) {
7042 struct disk_extent *old = exts;
7043 max *= 2;
7044 exts = kzalloc(sizeof(*exts) * max, GFP_NOFS);
7045 if (!exts) {
7046 ret = -ENOMEM;
7047 goto out;
7048 }
7049 memcpy(exts, old, sizeof(*exts) * nr);
7050 if (old != *extents)
7051 kfree(old);
7052 }
7053
7054 exts[nr].disk_bytenr =
7055 btrfs_file_extent_disk_bytenr(leaf, fi);
7056 exts[nr].disk_num_bytes =
7057 btrfs_file_extent_disk_num_bytes(leaf, fi);
7058 exts[nr].offset = btrfs_file_extent_offset(leaf, fi);
7059 exts[nr].num_bytes = btrfs_file_extent_num_bytes(leaf, fi);
7060 exts[nr].ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
7061 exts[nr].compression = btrfs_file_extent_compression(leaf, fi);
7062 exts[nr].encryption = btrfs_file_extent_encryption(leaf, fi);
7063 exts[nr].other_encoding = btrfs_file_extent_other_encoding(leaf,
7064 fi);
7065 BUG_ON(exts[nr].offset > 0);
7066 BUG_ON(exts[nr].compression || exts[nr].encryption);
7067 BUG_ON(exts[nr].num_bytes != exts[nr].disk_num_bytes);
7068
7069 cur_pos += exts[nr].num_bytes;
7070 nr++;
7071
7072 if (cur_pos + offset >= last_byte)
7073 break;
7074
7075 if (no_fragment) {
7076 ret = 1;
7077 goto out;
7078 }
7079 path->slots[0]++;
7080 }
7081
7082 BUG_ON(cur_pos + offset > last_byte);
7083 if (cur_pos + offset < last_byte) {
7084 ret = -ENOENT;
7085 goto out;
7086 }
7087 ret = 0;
7088 out:
7089 btrfs_free_path(path);
7090 if (ret) {
7091 if (exts != *extents)
7092 kfree(exts);
7093 } else {
7094 *extents = exts;
7095 *nr_extents = nr;
7096 }
7097 return ret;
7098 }
7099
7100 static noinline int replace_one_extent(struct btrfs_trans_handle *trans,
7101 struct btrfs_root *root,
7102 struct btrfs_path *path,
7103 struct btrfs_key *extent_key,
7104 struct btrfs_key *leaf_key,
7105 struct btrfs_ref_path *ref_path,
7106 struct disk_extent *new_extents,
7107 int nr_extents)
7108 {
7109 struct extent_buffer *leaf;
7110 struct btrfs_file_extent_item *fi;
7111 struct inode *inode = NULL;
7112 struct btrfs_key key;
7113 u64 lock_start = 0;
7114 u64 lock_end = 0;
7115 u64 num_bytes;
7116 u64 ext_offset;
7117 u64 search_end = (u64)-1;
7118 u32 nritems;
7119 int nr_scaned = 0;
7120 int extent_locked = 0;
7121 int extent_type;
7122 int ret;
7123
7124 memcpy(&key, leaf_key, sizeof(key));
7125 if (ref_path->owner_objectid != BTRFS_MULTIPLE_OBJECTIDS) {
7126 if (key.objectid < ref_path->owner_objectid ||
7127 (key.objectid == ref_path->owner_objectid &&
7128 key.type < BTRFS_EXTENT_DATA_KEY)) {
7129 key.objectid = ref_path->owner_objectid;
7130 key.type = BTRFS_EXTENT_DATA_KEY;
7131 key.offset = 0;
7132 }
7133 }
7134
7135 while (1) {
7136 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
7137 if (ret < 0)
7138 goto out;
7139
7140 leaf = path->nodes[0];
7141 nritems = btrfs_header_nritems(leaf);
7142 next:
7143 if (extent_locked && ret > 0) {
7144 /*
7145 * the file extent item was modified by someone
7146 * before the extent got locked.
7147 */
7148 unlock_extent(&BTRFS_I(inode)->io_tree, lock_start,
7149 lock_end, GFP_NOFS);
7150 extent_locked = 0;
7151 }
7152
7153 if (path->slots[0] >= nritems) {
7154 if (++nr_scaned > 2)
7155 break;
7156
7157 BUG_ON(extent_locked);
7158 ret = btrfs_next_leaf(root, path);
7159 if (ret < 0)
7160 goto out;
7161 if (ret > 0)
7162 break;
7163 leaf = path->nodes[0];
7164 nritems = btrfs_header_nritems(leaf);
7165 }
7166
7167 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
7168
7169 if (ref_path->owner_objectid != BTRFS_MULTIPLE_OBJECTIDS) {
7170 if ((key.objectid > ref_path->owner_objectid) ||
7171 (key.objectid == ref_path->owner_objectid &&
7172 key.type > BTRFS_EXTENT_DATA_KEY) ||
7173 key.offset >= search_end)
7174 break;
7175 }
7176
7177 if (inode && key.objectid != btrfs_ino(inode)) {
7178 BUG_ON(extent_locked);
7179 btrfs_release_path(root, path);
7180 mutex_unlock(&inode->i_mutex);
7181 iput(inode);
7182 inode = NULL;
7183 continue;
7184 }
7185
7186 if (key.type != BTRFS_EXTENT_DATA_KEY) {
7187 path->slots[0]++;
7188 ret = 1;
7189 goto next;
7190 }
7191 fi = btrfs_item_ptr(leaf, path->slots[0],
7192 struct btrfs_file_extent_item);
7193 extent_type = btrfs_file_extent_type(leaf, fi);
7194 if ((extent_type != BTRFS_FILE_EXTENT_REG &&
7195 extent_type != BTRFS_FILE_EXTENT_PREALLOC) ||
7196 (btrfs_file_extent_disk_bytenr(leaf, fi) !=
7197 extent_key->objectid)) {
7198 path->slots[0]++;
7199 ret = 1;
7200 goto next;
7201 }
7202
7203 num_bytes = btrfs_file_extent_num_bytes(leaf, fi);
7204 ext_offset = btrfs_file_extent_offset(leaf, fi);
7205
7206 if (search_end == (u64)-1) {
7207 search_end = key.offset - ext_offset +
7208 btrfs_file_extent_ram_bytes(leaf, fi);
7209 }
7210
7211 if (!extent_locked) {
7212 lock_start = key.offset;
7213 lock_end = lock_start + num_bytes - 1;
7214 } else {
7215 if (lock_start > key.offset ||
7216 lock_end + 1 < key.offset + num_bytes) {
7217 unlock_extent(&BTRFS_I(inode)->io_tree,
7218 lock_start, lock_end, GFP_NOFS);
7219 extent_locked = 0;
7220 }
7221 }
7222
7223 if (!inode) {
7224 btrfs_release_path(root, path);
7225
7226 inode = btrfs_iget_locked(root->fs_info->sb,
7227 key.objectid, root);
7228 if (inode->i_state & I_NEW) {
7229 BTRFS_I(inode)->root = root;
7230 BTRFS_I(inode)->location.objectid =
7231 key.objectid;
7232 BTRFS_I(inode)->location.type =
7233 BTRFS_INODE_ITEM_KEY;
7234 BTRFS_I(inode)->location.offset = 0;
7235 btrfs_read_locked_inode(inode);
7236 unlock_new_inode(inode);
7237 }
7238 /*
7239 * some code call btrfs_commit_transaction while
7240 * holding the i_mutex, so we can't use mutex_lock
7241 * here.
7242 */
7243 if (is_bad_inode(inode) ||
7244 !mutex_trylock(&inode->i_mutex)) {
7245 iput(inode);
7246 inode = NULL;
7247 key.offset = (u64)-1;
7248 goto skip;
7249 }
7250 }
7251
7252 if (!extent_locked) {
7253 struct btrfs_ordered_extent *ordered;
7254
7255 btrfs_release_path(root, path);
7256
7257 lock_extent(&BTRFS_I(inode)->io_tree, lock_start,
7258 lock_end, GFP_NOFS);
7259 ordered = btrfs_lookup_first_ordered_extent(inode,
7260 lock_end);
7261 if (ordered &&
7262 ordered->file_offset <= lock_end &&
7263 ordered->file_offset + ordered->len > lock_start) {
7264 unlock_extent(&BTRFS_I(inode)->io_tree,
7265 lock_start, lock_end, GFP_NOFS);
7266 btrfs_start_ordered_extent(inode, ordered, 1);
7267 btrfs_put_ordered_extent(ordered);
7268 key.offset += num_bytes;
7269 goto skip;
7270 }
7271 if (ordered)
7272 btrfs_put_ordered_extent(ordered);
7273
7274 extent_locked = 1;
7275 continue;
7276 }
7277
7278 if (nr_extents == 1) {
7279 /* update extent pointer in place */
7280 btrfs_set_file_extent_disk_bytenr(leaf, fi,
7281 new_extents[0].disk_bytenr);
7282 btrfs_set_file_extent_disk_num_bytes(leaf, fi,
7283 new_extents[0].disk_num_bytes);
7284 btrfs_mark_buffer_dirty(leaf);
7285
7286 btrfs_drop_extent_cache(inode, key.offset,
7287 key.offset + num_bytes - 1, 0);
7288
7289 ret = btrfs_inc_extent_ref(trans, root,
7290 new_extents[0].disk_bytenr,
7291 new_extents[0].disk_num_bytes,
7292 leaf->start,
7293 root->root_key.objectid,
7294 trans->transid,
7295 key.objectid);
7296 BUG_ON(ret);
7297
7298 ret = btrfs_free_extent(trans, root,
7299 extent_key->objectid,
7300 extent_key->offset,
7301 leaf->start,
7302 btrfs_header_owner(leaf),
7303 btrfs_header_generation(leaf),
7304 key.objectid, 0);
7305 BUG_ON(ret);
7306
7307 btrfs_release_path(root, path);
7308 key.offset += num_bytes;
7309 } else {
7310 BUG_ON(1);
7311 #if 0
7312 u64 alloc_hint;
7313 u64 extent_len;
7314 int i;
7315 /*
7316 * drop old extent pointer at first, then insert the
7317 * new pointers one bye one
7318 */
7319 btrfs_release_path(root, path);
7320 ret = btrfs_drop_extents(trans, root, inode, key.offset,
7321 key.offset + num_bytes,
7322 key.offset, &alloc_hint);
7323 BUG_ON(ret);
7324
7325 for (i = 0; i < nr_extents; i++) {
7326 if (ext_offset >= new_extents[i].num_bytes) {
7327 ext_offset -= new_extents[i].num_bytes;
7328 continue;
7329 }
7330 extent_len = min(new_extents[i].num_bytes -
7331 ext_offset, num_bytes);
7332
7333 ret = btrfs_insert_empty_item(trans, root,
7334 path, &key,
7335 sizeof(*fi));
7336 BUG_ON(ret);
7337
7338 leaf = path->nodes[0];
7339 fi = btrfs_item_ptr(leaf, path->slots[0],
7340 struct btrfs_file_extent_item);
7341 btrfs_set_file_extent_generation(leaf, fi,
7342 trans->transid);
7343 btrfs_set_file_extent_type(leaf, fi,
7344 BTRFS_FILE_EXTENT_REG);
7345 btrfs_set_file_extent_disk_bytenr(leaf, fi,
7346 new_extents[i].disk_bytenr);
7347 btrfs_set_file_extent_disk_num_bytes(leaf, fi,
7348 new_extents[i].disk_num_bytes);
7349 btrfs_set_file_extent_ram_bytes(leaf, fi,
7350 new_extents[i].ram_bytes);
7351
7352 btrfs_set_file_extent_compression(leaf, fi,
7353 new_extents[i].compression);
7354 btrfs_set_file_extent_encryption(leaf, fi,
7355 new_extents[i].encryption);
7356 btrfs_set_file_extent_other_encoding(leaf, fi,
7357 new_extents[i].other_encoding);
7358
7359 btrfs_set_file_extent_num_bytes(leaf, fi,
7360 extent_len);
7361 ext_offset += new_extents[i].offset;
7362 btrfs_set_file_extent_offset(leaf, fi,
7363 ext_offset);
7364 btrfs_mark_buffer_dirty(leaf);
7365
7366 btrfs_drop_extent_cache(inode, key.offset,
7367 key.offset + extent_len - 1, 0);
7368
7369 ret = btrfs_inc_extent_ref(trans, root,
7370 new_extents[i].disk_bytenr,
7371 new_extents[i].disk_num_bytes,
7372 leaf->start,
7373 root->root_key.objectid,
7374 trans->transid, key.objectid);
7375 BUG_ON(ret);
7376 btrfs_release_path(root, path);
7377
7378 inode_add_bytes(inode, extent_len);
7379
7380 ext_offset = 0;
7381 num_bytes -= extent_len;
7382 key.offset += extent_len;
7383
7384 if (num_bytes == 0)
7385 break;
7386 }
7387 BUG_ON(i >= nr_extents);
7388 #endif
7389 }
7390
7391 if (extent_locked) {
7392 unlock_extent(&BTRFS_I(inode)->io_tree, lock_start,
7393 lock_end, GFP_NOFS);
7394 extent_locked = 0;
7395 }
7396 skip:
7397 if (ref_path->owner_objectid != BTRFS_MULTIPLE_OBJECTIDS &&
7398 key.offset >= search_end)
7399 break;
7400
7401 cond_resched();
7402 }
7403 ret = 0;
7404 out:
7405 btrfs_release_path(root, path);
7406 if (inode) {
7407 mutex_unlock(&inode->i_mutex);
7408 if (extent_locked) {
7409 unlock_extent(&BTRFS_I(inode)->io_tree, lock_start,
7410 lock_end, GFP_NOFS);
7411 }
7412 iput(inode);
7413 }
7414 return ret;
7415 }
7416
7417 int btrfs_reloc_tree_cache_ref(struct btrfs_trans_handle *trans,
7418 struct btrfs_root *root,
7419 struct extent_buffer *buf, u64 orig_start)
7420 {
7421 int level;
7422 int ret;
7423
7424 BUG_ON(btrfs_header_generation(buf) != trans->transid);
7425 BUG_ON(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
7426
7427 level = btrfs_header_level(buf);
7428 if (level == 0) {
7429 struct btrfs_leaf_ref *ref;
7430 struct btrfs_leaf_ref *orig_ref;
7431
7432 orig_ref = btrfs_lookup_leaf_ref(root, orig_start);
7433 if (!orig_ref)
7434 return -ENOENT;
7435
7436 ref = btrfs_alloc_leaf_ref(root, orig_ref->nritems);
7437 if (!ref) {
7438 btrfs_free_leaf_ref(root, orig_ref);
7439 return -ENOMEM;
7440 }
7441
7442 ref->nritems = orig_ref->nritems;
7443 memcpy(ref->extents, orig_ref->extents,
7444 sizeof(ref->extents[0]) * ref->nritems);
7445
7446 btrfs_free_leaf_ref(root, orig_ref);
7447
7448 ref->root_gen = trans->transid;
7449 ref->bytenr = buf->start;
7450 ref->owner = btrfs_header_owner(buf);
7451 ref->generation = btrfs_header_generation(buf);
7452
7453 ret = btrfs_add_leaf_ref(root, ref, 0);
7454 WARN_ON(ret);
7455 btrfs_free_leaf_ref(root, ref);
7456 }
7457 return 0;
7458 }
7459
7460 static noinline int invalidate_extent_cache(struct btrfs_root *root,
7461 struct extent_buffer *leaf,
7462 struct btrfs_block_group_cache *group,
7463 struct btrfs_root *target_root)
7464 {
7465 struct btrfs_key key;
7466 struct inode *inode = NULL;
7467 struct btrfs_file_extent_item *fi;
7468 struct extent_state *cached_state = NULL;
7469 u64 num_bytes;
7470 u64 skip_objectid = 0;
7471 u32 nritems;
7472 u32 i;
7473
7474 nritems = btrfs_header_nritems(leaf);
7475 for (i = 0; i < nritems; i++) {
7476 btrfs_item_key_to_cpu(leaf, &key, i);
7477 if (key.objectid == skip_objectid ||
7478 key.type != BTRFS_EXTENT_DATA_KEY)
7479 continue;
7480 fi = btrfs_item_ptr(leaf, i, struct btrfs_file_extent_item);
7481 if (btrfs_file_extent_type(leaf, fi) ==
7482 BTRFS_FILE_EXTENT_INLINE)
7483 continue;
7484 if (btrfs_file_extent_disk_bytenr(leaf, fi) == 0)
7485 continue;
7486 if (!inode || btrfs_ino(inode) != key.objectid) {
7487 iput(inode);
7488 inode = btrfs_ilookup(target_root->fs_info->sb,
7489 key.objectid, target_root, 1);
7490 }
7491 if (!inode) {
7492 skip_objectid = key.objectid;
7493 continue;
7494 }
7495 num_bytes = btrfs_file_extent_num_bytes(leaf, fi);
7496
7497 lock_extent_bits(&BTRFS_I(inode)->io_tree, key.offset,
7498 key.offset + num_bytes - 1, 0, &cached_state,
7499 GFP_NOFS);
7500 btrfs_drop_extent_cache(inode, key.offset,
7501 key.offset + num_bytes - 1, 1);
7502 unlock_extent_cached(&BTRFS_I(inode)->io_tree, key.offset,
7503 key.offset + num_bytes - 1, &cached_state,
7504 GFP_NOFS);
7505 cond_resched();
7506 }
7507 iput(inode);
7508 return 0;
7509 }
7510
7511 static noinline int replace_extents_in_leaf(struct btrfs_trans_handle *trans,
7512 struct btrfs_root *root,
7513 struct extent_buffer *leaf,
7514 struct btrfs_block_group_cache *group,
7515 struct inode *reloc_inode)
7516 {
7517 struct btrfs_key key;
7518 struct btrfs_key extent_key;
7519 struct btrfs_file_extent_item *fi;
7520 struct btrfs_leaf_ref *ref;
7521 struct disk_extent *new_extent;
7522 u64 bytenr;
7523 u64 num_bytes;
7524 u32 nritems;
7525 u32 i;
7526 int ext_index;
7527 int nr_extent;
7528 int ret;
7529
7530 new_extent = kmalloc(sizeof(*new_extent), GFP_NOFS);
7531 if (!new_extent)
7532 return -ENOMEM;
7533
7534 ref = btrfs_lookup_leaf_ref(root, leaf->start);
7535 BUG_ON(!ref);
7536
7537 ext_index = -1;
7538 nritems = btrfs_header_nritems(leaf);
7539 for (i = 0; i < nritems; i++) {
7540 btrfs_item_key_to_cpu(leaf, &key, i);
7541 if (btrfs_key_type(&key) != BTRFS_EXTENT_DATA_KEY)
7542 continue;
7543 fi = btrfs_item_ptr(leaf, i, struct btrfs_file_extent_item);
7544 if (btrfs_file_extent_type(leaf, fi) ==
7545 BTRFS_FILE_EXTENT_INLINE)
7546 continue;
7547 bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
7548 num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
7549 if (bytenr == 0)
7550 continue;
7551
7552 ext_index++;
7553 if (bytenr >= group->key.objectid + group->key.offset ||
7554 bytenr + num_bytes <= group->key.objectid)
7555 continue;
7556
7557 extent_key.objectid = bytenr;
7558 extent_key.offset = num_bytes;
7559 extent_key.type = BTRFS_EXTENT_ITEM_KEY;
7560 nr_extent = 1;
7561 ret = get_new_locations(reloc_inode, &extent_key,
7562 group->key.objectid, 1,
7563 &new_extent, &nr_extent);
7564 if (ret > 0)
7565 continue;
7566 BUG_ON(ret < 0);
7567
7568 BUG_ON(ref->extents[ext_index].bytenr != bytenr);
7569 BUG_ON(ref->extents[ext_index].num_bytes != num_bytes);
7570 ref->extents[ext_index].bytenr = new_extent->disk_bytenr;
7571 ref->extents[ext_index].num_bytes = new_extent->disk_num_bytes;
7572
7573 btrfs_set_file_extent_disk_bytenr(leaf, fi,
7574 new_extent->disk_bytenr);
7575 btrfs_set_file_extent_disk_num_bytes(leaf, fi,
7576 new_extent->disk_num_bytes);
7577 btrfs_mark_buffer_dirty(leaf);
7578
7579 ret = btrfs_inc_extent_ref(trans, root,
7580 new_extent->disk_bytenr,
7581 new_extent->disk_num_bytes,
7582 leaf->start,
7583 root->root_key.objectid,
7584 trans->transid, key.objectid);
7585 BUG_ON(ret);
7586
7587 ret = btrfs_free_extent(trans, root,
7588 bytenr, num_bytes, leaf->start,
7589 btrfs_header_owner(leaf),
7590 btrfs_header_generation(leaf),
7591 key.objectid, 0);
7592 BUG_ON(ret);
7593 cond_resched();
7594 }
7595 kfree(new_extent);
7596 BUG_ON(ext_index + 1 != ref->nritems);
7597 btrfs_free_leaf_ref(root, ref);
7598 return 0;
7599 }
7600
7601 int btrfs_free_reloc_root(struct btrfs_trans_handle *trans,
7602 struct btrfs_root *root)
7603 {
7604 struct btrfs_root *reloc_root;
7605 int ret;
7606
7607 if (root->reloc_root) {
7608 reloc_root = root->reloc_root;
7609 root->reloc_root = NULL;
7610 list_add(&reloc_root->dead_list,
7611 &root->fs_info->dead_reloc_roots);
7612
7613 btrfs_set_root_bytenr(&reloc_root->root_item,
7614 reloc_root->node->start);
7615 btrfs_set_root_level(&root->root_item,
7616 btrfs_header_level(reloc_root->node));
7617 memset(&reloc_root->root_item.drop_progress, 0,
7618 sizeof(struct btrfs_disk_key));
7619 reloc_root->root_item.drop_level = 0;
7620
7621 ret = btrfs_update_root(trans, root->fs_info->tree_root,
7622 &reloc_root->root_key,
7623 &reloc_root->root_item);
7624 BUG_ON(ret);
7625 }
7626 return 0;
7627 }
7628
7629 int btrfs_drop_dead_reloc_roots(struct btrfs_root *root)
7630 {
7631 struct btrfs_trans_handle *trans;
7632 struct btrfs_root *reloc_root;
7633 struct btrfs_root *prev_root = NULL;
7634 struct list_head dead_roots;
7635 int ret;
7636 unsigned long nr;
7637
7638 INIT_LIST_HEAD(&dead_roots);
7639 list_splice_init(&root->fs_info->dead_reloc_roots, &dead_roots);
7640
7641 while (!list_empty(&dead_roots)) {
7642 reloc_root = list_entry(dead_roots.prev,
7643 struct btrfs_root, dead_list);
7644 list_del_init(&reloc_root->dead_list);
7645
7646 BUG_ON(reloc_root->commit_root != NULL);
7647 while (1) {
7648 trans = btrfs_join_transaction(root, 1);
7649 BUG_ON(IS_ERR(trans));
7650
7651 mutex_lock(&root->fs_info->drop_mutex);
7652 ret = btrfs_drop_snapshot(trans, reloc_root);
7653 if (ret != -EAGAIN)
7654 break;
7655 mutex_unlock(&root->fs_info->drop_mutex);
7656
7657 nr = trans->blocks_used;
7658 ret = btrfs_end_transaction(trans, root);
7659 BUG_ON(ret);
7660 btrfs_btree_balance_dirty(root, nr);
7661 }
7662
7663 free_extent_buffer(reloc_root->node);
7664
7665 ret = btrfs_del_root(trans, root->fs_info->tree_root,
7666 &reloc_root->root_key);
7667 BUG_ON(ret);
7668 mutex_unlock(&root->fs_info->drop_mutex);
7669
7670 nr = trans->blocks_used;
7671 ret = btrfs_end_transaction(trans, root);
7672 BUG_ON(ret);
7673 btrfs_btree_balance_dirty(root, nr);
7674
7675 kfree(prev_root);
7676 prev_root = reloc_root;
7677 }
7678 if (prev_root) {
7679 btrfs_remove_leaf_refs(prev_root, (u64)-1, 0);
7680 kfree(prev_root);
7681 }
7682 return 0;
7683 }
7684
7685 int btrfs_add_dead_reloc_root(struct btrfs_root *root)
7686 {
7687 list_add(&root->dead_list, &root->fs_info->dead_reloc_roots);
7688 return 0;
7689 }
7690
7691 int btrfs_cleanup_reloc_trees(struct btrfs_root *root)
7692 {
7693 struct btrfs_root *reloc_root;
7694 struct btrfs_trans_handle *trans;
7695 struct btrfs_key location;
7696 int found;
7697 int ret;
7698
7699 mutex_lock(&root->fs_info->tree_reloc_mutex);
7700 ret = btrfs_find_dead_roots(root, BTRFS_TREE_RELOC_OBJECTID, NULL);
7701 BUG_ON(ret);
7702 found = !list_empty(&root->fs_info->dead_reloc_roots);
7703 mutex_unlock(&root->fs_info->tree_reloc_mutex);
7704
7705 if (found) {
7706 trans = btrfs_start_transaction(root, 1);
7707 BUG_ON(IS_ERR(trans));
7708 ret = btrfs_commit_transaction(trans, root);
7709 BUG_ON(ret);
7710 }
7711
7712 location.objectid = BTRFS_DATA_RELOC_TREE_OBJECTID;
7713 location.offset = (u64)-1;
7714 location.type = BTRFS_ROOT_ITEM_KEY;
7715
7716 reloc_root = btrfs_read_fs_root_no_name(root->fs_info, &location);
7717 BUG_ON(!reloc_root);
7718 ret = btrfs_orphan_cleanup(reloc_root);
7719 BUG_ON(ret);
7720 return 0;
7721 }
7722
7723 static noinline int init_reloc_tree(struct btrfs_trans_handle *trans,
7724 struct btrfs_root *root)
7725 {
7726 struct btrfs_root *reloc_root;
7727 struct extent_buffer *eb;
7728 struct btrfs_root_item *root_item;
7729 struct btrfs_key root_key;
7730 int ret;
7731
7732 BUG_ON(!root->ref_cows);
7733 if (root->reloc_root)
7734 return 0;
7735
7736 root_item = kmalloc(sizeof(*root_item), GFP_NOFS);
7737 if (!root_item)
7738 return -ENOMEM;
7739
7740 ret = btrfs_copy_root(trans, root, root->commit_root,
7741 &eb, BTRFS_TREE_RELOC_OBJECTID);
7742 BUG_ON(ret);
7743
7744 root_key.objectid = BTRFS_TREE_RELOC_OBJECTID;
7745 root_key.offset = root->root_key.objectid;
7746 root_key.type = BTRFS_ROOT_ITEM_KEY;
7747
7748 memcpy(root_item, &root->root_item, sizeof(root_item));
7749 btrfs_set_root_refs(root_item, 0);
7750 btrfs_set_root_bytenr(root_item, eb->start);
7751 btrfs_set_root_level(root_item, btrfs_header_level(eb));
7752 btrfs_set_root_generation(root_item, trans->transid);
7753
7754 btrfs_tree_unlock(eb);
7755 free_extent_buffer(eb);
7756
7757 ret = btrfs_insert_root(trans, root->fs_info->tree_root,
7758 &root_key, root_item);
7759 BUG_ON(ret);
7760 kfree(root_item);
7761
7762 reloc_root = btrfs_read_fs_root_no_radix(root->fs_info->tree_root,
7763 &root_key);
7764 BUG_ON(IS_ERR(reloc_root));
7765 reloc_root->last_trans = trans->transid;
7766 reloc_root->commit_root = NULL;
7767 reloc_root->ref_tree = &root->fs_info->reloc_ref_tree;
7768
7769 root->reloc_root = reloc_root;
7770 return 0;
7771 }
7772
7773 /*
7774 * Core function of space balance.
7775 *
7776 * The idea is using reloc trees to relocate tree blocks in reference
7777 * counted roots. There is one reloc tree for each subvol, and all
7778 * reloc trees share same root key objectid. Reloc trees are snapshots
7779 * of the latest committed roots of subvols (root->commit_root).
7780 *
7781 * To relocate a tree block referenced by a subvol, there are two steps.
7782 * COW the block through subvol's reloc tree, then update block pointer
7783 * in the subvol to point to the new block. Since all reloc trees share
7784 * same root key objectid, doing special handing for tree blocks owned
7785 * by them is easy. Once a tree block has been COWed in one reloc tree,
7786 * we can use the resulting new block directly when the same block is
7787 * required to COW again through other reloc trees. By this way, relocated
7788 * tree blocks are shared between reloc trees, so they are also shared
7789 * between subvols.
7790 */
7791 static noinline int relocate_one_path(struct btrfs_trans_handle *trans,
7792 struct btrfs_root *root,
7793 struct btrfs_path *path,
7794 struct btrfs_key *first_key,
7795 struct btrfs_ref_path *ref_path,
7796 struct btrfs_block_group_cache *group,
7797 struct inode *reloc_inode)
7798 {
7799 struct btrfs_root *reloc_root;
7800 struct extent_buffer *eb = NULL;
7801 struct btrfs_key *keys;
7802 u64 *nodes;
7803 int level;
7804 int shared_level;
7805 int lowest_level = 0;
7806 int ret;
7807
7808 if (ref_path->owner_objectid < BTRFS_FIRST_FREE_OBJECTID)
7809 lowest_level = ref_path->owner_objectid;
7810
7811 if (!root->ref_cows) {
7812 path->lowest_level = lowest_level;
7813 ret = btrfs_search_slot(trans, root, first_key, path, 0, 1);
7814 BUG_ON(ret < 0);
7815 path->lowest_level = 0;
7816 btrfs_release_path(root, path);
7817 return 0;
7818 }
7819
7820 mutex_lock(&root->fs_info->tree_reloc_mutex);
7821 ret = init_reloc_tree(trans, root);
7822 BUG_ON(ret);
7823 reloc_root = root->reloc_root;
7824
7825 shared_level = ref_path->shared_level;
7826 ref_path->shared_level = BTRFS_MAX_LEVEL - 1;
7827
7828 keys = ref_path->node_keys;
7829 nodes = ref_path->new_nodes;
7830 memset(&keys[shared_level + 1], 0,
7831 sizeof(*keys) * (BTRFS_MAX_LEVEL - shared_level - 1));
7832 memset(&nodes[shared_level + 1], 0,
7833 sizeof(*nodes) * (BTRFS_MAX_LEVEL - shared_level - 1));
7834
7835 if (nodes[lowest_level] == 0) {
7836 path->lowest_level = lowest_level;
7837 ret = btrfs_search_slot(trans, reloc_root, first_key, path,
7838 0, 1);
7839 BUG_ON(ret);
7840 for (level = lowest_level; level < BTRFS_MAX_LEVEL; level++) {
7841 eb = path->nodes[level];
7842 if (!eb || eb == reloc_root->node)
7843 break;
7844 nodes[level] = eb->start;
7845 if (level == 0)
7846 btrfs_item_key_to_cpu(eb, &keys[level], 0);
7847 else
7848 btrfs_node_key_to_cpu(eb, &keys[level], 0);
7849 }
7850 if (nodes[0] &&
7851 ref_path->owner_objectid >= BTRFS_FIRST_FREE_OBJECTID) {
7852 eb = path->nodes[0];
7853 ret = replace_extents_in_leaf(trans, reloc_root, eb,
7854 group, reloc_inode);
7855 BUG_ON(ret);
7856 }
7857 btrfs_release_path(reloc_root, path);
7858 } else {
7859 ret = btrfs_merge_path(trans, reloc_root, keys, nodes,
7860 lowest_level);
7861 BUG_ON(ret);
7862 }
7863
7864 /*
7865 * replace tree blocks in the fs tree with tree blocks in
7866 * the reloc tree.
7867 */
7868 ret = btrfs_merge_path(trans, root, keys, nodes, lowest_level);
7869 BUG_ON(ret < 0);
7870
7871 if (ref_path->owner_objectid >= BTRFS_FIRST_FREE_OBJECTID) {
7872 ret = btrfs_search_slot(trans, reloc_root, first_key, path,
7873 0, 0);
7874 BUG_ON(ret);
7875 extent_buffer_get(path->nodes[0]);
7876 eb = path->nodes[0];
7877 btrfs_release_path(reloc_root, path);
7878 ret = invalidate_extent_cache(reloc_root, eb, group, root);
7879 BUG_ON(ret);
7880 free_extent_buffer(eb);
7881 }
7882
7883 mutex_unlock(&root->fs_info->tree_reloc_mutex);
7884 path->lowest_level = 0;
7885 return 0;
7886 }
7887
7888 static noinline int relocate_tree_block(struct btrfs_trans_handle *trans,
7889 struct btrfs_root *root,
7890 struct btrfs_path *path,
7891 struct btrfs_key *first_key,
7892 struct btrfs_ref_path *ref_path)
7893 {
7894 int ret;
7895
7896 ret = relocate_one_path(trans, root, path, first_key,
7897 ref_path, NULL, NULL);
7898 BUG_ON(ret);
7899
7900 return 0;
7901 }
7902
7903 static noinline int del_extent_zero(struct btrfs_trans_handle *trans,
7904 struct btrfs_root *extent_root,
7905 struct btrfs_path *path,
7906 struct btrfs_key *extent_key)
7907 {
7908 int ret;
7909
7910 ret = btrfs_search_slot(trans, extent_root, extent_key, path, -1, 1);
7911 if (ret)
7912 goto out;
7913 ret = btrfs_del_item(trans, extent_root, path);
7914 out:
7915 btrfs_release_path(extent_root, path);
7916 return ret;
7917 }
7918
7919 static noinline struct btrfs_root *read_ref_root(struct btrfs_fs_info *fs_info,
7920 struct btrfs_ref_path *ref_path)
7921 {
7922 struct btrfs_key root_key;
7923
7924 root_key.objectid = ref_path->root_objectid;
7925 root_key.type = BTRFS_ROOT_ITEM_KEY;
7926 if (is_cowonly_root(ref_path->root_objectid))
7927 root_key.offset = 0;
7928 else
7929 root_key.offset = (u64)-1;
7930
7931 return btrfs_read_fs_root_no_name(fs_info, &root_key);
7932 }
7933
7934 static noinline int relocate_one_extent(struct btrfs_root *extent_root,
7935 struct btrfs_path *path,
7936 struct btrfs_key *extent_key,
7937 struct btrfs_block_group_cache *group,
7938 struct inode *reloc_inode, int pass)
7939 {
7940 struct btrfs_trans_handle *trans;
7941 struct btrfs_root *found_root;
7942 struct btrfs_ref_path *ref_path = NULL;
7943 struct disk_extent *new_extents = NULL;
7944 int nr_extents = 0;
7945 int loops;
7946 int ret;
7947 int level;
7948 struct btrfs_key first_key;
7949 u64 prev_block = 0;
7950
7951
7952 trans = btrfs_start_transaction(extent_root, 1);
7953 BUG_ON(IS_ERR(trans));
7954
7955 if (extent_key->objectid == 0) {
7956 ret = del_extent_zero(trans, extent_root, path, extent_key);
7957 goto out;
7958 }
7959
7960 ref_path = kmalloc(sizeof(*ref_path), GFP_NOFS);
7961 if (!ref_path) {
7962 ret = -ENOMEM;
7963 goto out;
7964 }
7965
7966 for (loops = 0; ; loops++) {
7967 if (loops == 0) {
7968 ret = btrfs_first_ref_path(trans, extent_root, ref_path,
7969 extent_key->objectid);
7970 } else {
7971 ret = btrfs_next_ref_path(trans, extent_root, ref_path);
7972 }
7973 if (ret < 0)
7974 goto out;
7975 if (ret > 0)
7976 break;
7977
7978 if (ref_path->root_objectid == BTRFS_TREE_LOG_OBJECTID ||
7979 ref_path->root_objectid == BTRFS_TREE_RELOC_OBJECTID)
7980 continue;
7981
7982 found_root = read_ref_root(extent_root->fs_info, ref_path);
7983 BUG_ON(!found_root);
7984 /*
7985 * for reference counted tree, only process reference paths
7986 * rooted at the latest committed root.
7987 */
7988 if (found_root->ref_cows &&
7989 ref_path->root_generation != found_root->root_key.offset)
7990 continue;
7991
7992 if (ref_path->owner_objectid >= BTRFS_FIRST_FREE_OBJECTID) {
7993 if (pass == 0) {
7994 /*
7995 * copy data extents to new locations
7996 */
7997 u64 group_start = group->key.objectid;
7998 ret = relocate_data_extent(reloc_inode,
7999 extent_key,
8000 group_start);
8001 if (ret < 0)
8002 goto out;
8003 break;
8004 }
8005 level = 0;
8006 } else {
8007 level = ref_path->owner_objectid;
8008 }
8009
8010 if (prev_block != ref_path->nodes[level]) {
8011 struct extent_buffer *eb;
8012 u64 block_start = ref_path->nodes[level];
8013 u64 block_size = btrfs_level_size(found_root, level);
8014
8015 eb = read_tree_block(found_root, block_start,
8016 block_size, 0);
8017 if (!eb) {
8018 ret = -EIO;
8019 goto out;
8020 }
8021 btrfs_tree_lock(eb);
8022 BUG_ON(level != btrfs_header_level(eb));
8023
8024 if (level == 0)
8025 btrfs_item_key_to_cpu(eb, &first_key, 0);
8026 else
8027 btrfs_node_key_to_cpu(eb, &first_key, 0);
8028
8029 btrfs_tree_unlock(eb);
8030 free_extent_buffer(eb);
8031 prev_block = block_start;
8032 }
8033
8034 mutex_lock(&extent_root->fs_info->trans_mutex);
8035 btrfs_record_root_in_trans(found_root);
8036 mutex_unlock(&extent_root->fs_info->trans_mutex);
8037 if (ref_path->owner_objectid >= BTRFS_FIRST_FREE_OBJECTID) {
8038 /*
8039 * try to update data extent references while
8040 * keeping metadata shared between snapshots.
8041 */
8042 if (pass == 1) {
8043 ret = relocate_one_path(trans, found_root,
8044 path, &first_key, ref_path,
8045 group, reloc_inode);
8046 if (ret < 0)
8047 goto out;
8048 continue;
8049 }
8050 /*
8051 * use fallback method to process the remaining
8052 * references.
8053 */
8054 if (!new_extents) {
8055 u64 group_start = group->key.objectid;
8056 new_extents = kmalloc(sizeof(*new_extents),
8057 GFP_NOFS);
8058 if (!new_extents) {
8059 ret = -ENOMEM;
8060 goto out;
8061 }
8062 nr_extents = 1;
8063 ret = get_new_locations(reloc_inode,
8064 extent_key,
8065 group_start, 1,
8066 &new_extents,
8067 &nr_extents);
8068 if (ret)
8069 goto out;
8070 }
8071 ret = replace_one_extent(trans, found_root,
8072 path, extent_key,
8073 &first_key, ref_path,
8074 new_extents, nr_extents);
8075 } else {
8076 ret = relocate_tree_block(trans, found_root, path,
8077 &first_key, ref_path);
8078 }
8079 if (ret < 0)
8080 goto out;
8081 }
8082 ret = 0;
8083 out:
8084 btrfs_end_transaction(trans, extent_root);
8085 kfree(new_extents);
8086 kfree(ref_path);
8087 return ret;
8088 }
8089 #endif
8090
8091 static u64 update_block_group_flags(struct btrfs_root *root, u64 flags)
8092 {
8093 u64 num_devices;
8094 u64 stripped = BTRFS_BLOCK_GROUP_RAID0 |
8095 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10;
8096
8097 /*
8098 * we add in the count of missing devices because we want
8099 * to make sure that any RAID levels on a degraded FS
8100 * continue to be honored.
8101 */
8102 num_devices = root->fs_info->fs_devices->rw_devices +
8103 root->fs_info->fs_devices->missing_devices;
8104
8105 if (num_devices == 1) {
8106 stripped |= BTRFS_BLOCK_GROUP_DUP;
8107 stripped = flags & ~stripped;
8108
8109 /* turn raid0 into single device chunks */
8110 if (flags & BTRFS_BLOCK_GROUP_RAID0)
8111 return stripped;
8112
8113 /* turn mirroring into duplication */
8114 if (flags & (BTRFS_BLOCK_GROUP_RAID1 |
8115 BTRFS_BLOCK_GROUP_RAID10))
8116 return stripped | BTRFS_BLOCK_GROUP_DUP;
8117 return flags;
8118 } else {
8119 /* they already had raid on here, just return */
8120 if (flags & stripped)
8121 return flags;
8122
8123 stripped |= BTRFS_BLOCK_GROUP_DUP;
8124 stripped = flags & ~stripped;
8125
8126 /* switch duplicated blocks with raid1 */
8127 if (flags & BTRFS_BLOCK_GROUP_DUP)
8128 return stripped | BTRFS_BLOCK_GROUP_RAID1;
8129
8130 /* turn single device chunks into raid0 */
8131 return stripped | BTRFS_BLOCK_GROUP_RAID0;
8132 }
8133 return flags;
8134 }
8135
8136 static int set_block_group_ro(struct btrfs_block_group_cache *cache)
8137 {
8138 struct btrfs_space_info *sinfo = cache->space_info;
8139 u64 num_bytes;
8140 int ret = -ENOSPC;
8141
8142 if (cache->ro)
8143 return 0;
8144
8145 spin_lock(&sinfo->lock);
8146 spin_lock(&cache->lock);
8147 num_bytes = cache->key.offset - cache->reserved - cache->pinned -
8148 cache->bytes_super - btrfs_block_group_used(&cache->item);
8149
8150 if (sinfo->bytes_used + sinfo->bytes_reserved + sinfo->bytes_pinned +
8151 sinfo->bytes_may_use + sinfo->bytes_readonly +
8152 cache->reserved_pinned + num_bytes <= sinfo->total_bytes) {
8153 sinfo->bytes_readonly += num_bytes;
8154 sinfo->bytes_reserved += cache->reserved_pinned;
8155 cache->reserved_pinned = 0;
8156 cache->ro = 1;
8157 ret = 0;
8158 }
8159
8160 spin_unlock(&cache->lock);
8161 spin_unlock(&sinfo->lock);
8162 return ret;
8163 }
8164
8165 int btrfs_set_block_group_ro(struct btrfs_root *root,
8166 struct btrfs_block_group_cache *cache)
8167
8168 {
8169 struct btrfs_trans_handle *trans;
8170 u64 alloc_flags;
8171 int ret;
8172
8173 BUG_ON(cache->ro);
8174
8175 trans = btrfs_join_transaction(root, 1);
8176 BUG_ON(IS_ERR(trans));
8177
8178 alloc_flags = update_block_group_flags(root, cache->flags);
8179 if (alloc_flags != cache->flags)
8180 do_chunk_alloc(trans, root, 2 * 1024 * 1024, alloc_flags,
8181 CHUNK_ALLOC_FORCE);
8182
8183 ret = set_block_group_ro(cache);
8184 if (!ret)
8185 goto out;
8186 alloc_flags = get_alloc_profile(root, cache->space_info->flags);
8187 ret = do_chunk_alloc(trans, root, 2 * 1024 * 1024, alloc_flags,
8188 CHUNK_ALLOC_FORCE);
8189 if (ret < 0)
8190 goto out;
8191 ret = set_block_group_ro(cache);
8192 out:
8193 btrfs_end_transaction(trans, root);
8194 return ret;
8195 }
8196
8197 int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans,
8198 struct btrfs_root *root, u64 type)
8199 {
8200 u64 alloc_flags = get_alloc_profile(root, type);
8201 return do_chunk_alloc(trans, root, 2 * 1024 * 1024, alloc_flags,
8202 CHUNK_ALLOC_FORCE);
8203 }
8204
8205 /*
8206 * helper to account the unused space of all the readonly block group in the
8207 * list. takes mirrors into account.
8208 */
8209 static u64 __btrfs_get_ro_block_group_free_space(struct list_head *groups_list)
8210 {
8211 struct btrfs_block_group_cache *block_group;
8212 u64 free_bytes = 0;
8213 int factor;
8214
8215 list_for_each_entry(block_group, groups_list, list) {
8216 spin_lock(&block_group->lock);
8217
8218 if (!block_group->ro) {
8219 spin_unlock(&block_group->lock);
8220 continue;
8221 }
8222
8223 if (block_group->flags & (BTRFS_BLOCK_GROUP_RAID1 |
8224 BTRFS_BLOCK_GROUP_RAID10 |
8225 BTRFS_BLOCK_GROUP_DUP))
8226 factor = 2;
8227 else
8228 factor = 1;
8229
8230 free_bytes += (block_group->key.offset -
8231 btrfs_block_group_used(&block_group->item)) *
8232 factor;
8233
8234 spin_unlock(&block_group->lock);
8235 }
8236
8237 return free_bytes;
8238 }
8239
8240 /*
8241 * helper to account the unused space of all the readonly block group in the
8242 * space_info. takes mirrors into account.
8243 */
8244 u64 btrfs_account_ro_block_groups_free_space(struct btrfs_space_info *sinfo)
8245 {
8246 int i;
8247 u64 free_bytes = 0;
8248
8249 spin_lock(&sinfo->lock);
8250
8251 for(i = 0; i < BTRFS_NR_RAID_TYPES; i++)
8252 if (!list_empty(&sinfo->block_groups[i]))
8253 free_bytes += __btrfs_get_ro_block_group_free_space(
8254 &sinfo->block_groups[i]);
8255
8256 spin_unlock(&sinfo->lock);
8257
8258 return free_bytes;
8259 }
8260
8261 int btrfs_set_block_group_rw(struct btrfs_root *root,
8262 struct btrfs_block_group_cache *cache)
8263 {
8264 struct btrfs_space_info *sinfo = cache->space_info;
8265 u64 num_bytes;
8266
8267 BUG_ON(!cache->ro);
8268
8269 spin_lock(&sinfo->lock);
8270 spin_lock(&cache->lock);
8271 num_bytes = cache->key.offset - cache->reserved - cache->pinned -
8272 cache->bytes_super - btrfs_block_group_used(&cache->item);
8273 sinfo->bytes_readonly -= num_bytes;
8274 cache->ro = 0;
8275 spin_unlock(&cache->lock);
8276 spin_unlock(&sinfo->lock);
8277 return 0;
8278 }
8279
8280 /*
8281 * checks to see if its even possible to relocate this block group.
8282 *
8283 * @return - -1 if it's not a good idea to relocate this block group, 0 if its
8284 * ok to go ahead and try.
8285 */
8286 int btrfs_can_relocate(struct btrfs_root *root, u64 bytenr)
8287 {
8288 struct btrfs_block_group_cache *block_group;
8289 struct btrfs_space_info *space_info;
8290 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
8291 struct btrfs_device *device;
8292 int full = 0;
8293 int ret = 0;
8294
8295 block_group = btrfs_lookup_block_group(root->fs_info, bytenr);
8296
8297 /* odd, couldn't find the block group, leave it alone */
8298 if (!block_group)
8299 return -1;
8300
8301 /* no bytes used, we're good */
8302 if (!btrfs_block_group_used(&block_group->item))
8303 goto out;
8304
8305 space_info = block_group->space_info;
8306 spin_lock(&space_info->lock);
8307
8308 full = space_info->full;
8309
8310 /*
8311 * if this is the last block group we have in this space, we can't
8312 * relocate it unless we're able to allocate a new chunk below.
8313 *
8314 * Otherwise, we need to make sure we have room in the space to handle
8315 * all of the extents from this block group. If we can, we're good
8316 */
8317 if ((space_info->total_bytes != block_group->key.offset) &&
8318 (space_info->bytes_used + space_info->bytes_reserved +
8319 space_info->bytes_pinned + space_info->bytes_readonly +
8320 btrfs_block_group_used(&block_group->item) <
8321 space_info->total_bytes)) {
8322 spin_unlock(&space_info->lock);
8323 goto out;
8324 }
8325 spin_unlock(&space_info->lock);
8326
8327 /*
8328 * ok we don't have enough space, but maybe we have free space on our
8329 * devices to allocate new chunks for relocation, so loop through our
8330 * alloc devices and guess if we have enough space. However, if we
8331 * were marked as full, then we know there aren't enough chunks, and we
8332 * can just return.
8333 */
8334 ret = -1;
8335 if (full)
8336 goto out;
8337
8338 mutex_lock(&root->fs_info->chunk_mutex);
8339 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
8340 u64 min_free = btrfs_block_group_used(&block_group->item);
8341 u64 dev_offset;
8342
8343 /*
8344 * check to make sure we can actually find a chunk with enough
8345 * space to fit our block group in.
8346 */
8347 if (device->total_bytes > device->bytes_used + min_free) {
8348 ret = find_free_dev_extent(NULL, device, min_free,
8349 &dev_offset, NULL);
8350 if (!ret)
8351 break;
8352 ret = -1;
8353 }
8354 }
8355 mutex_unlock(&root->fs_info->chunk_mutex);
8356 out:
8357 btrfs_put_block_group(block_group);
8358 return ret;
8359 }
8360
8361 static int find_first_block_group(struct btrfs_root *root,
8362 struct btrfs_path *path, struct btrfs_key *key)
8363 {
8364 int ret = 0;
8365 struct btrfs_key found_key;
8366 struct extent_buffer *leaf;
8367 int slot;
8368
8369 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
8370 if (ret < 0)
8371 goto out;
8372
8373 while (1) {
8374 slot = path->slots[0];
8375 leaf = path->nodes[0];
8376 if (slot >= btrfs_header_nritems(leaf)) {
8377 ret = btrfs_next_leaf(root, path);
8378 if (ret == 0)
8379 continue;
8380 if (ret < 0)
8381 goto out;
8382 break;
8383 }
8384 btrfs_item_key_to_cpu(leaf, &found_key, slot);
8385
8386 if (found_key.objectid >= key->objectid &&
8387 found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
8388 ret = 0;
8389 goto out;
8390 }
8391 path->slots[0]++;
8392 }
8393 out:
8394 return ret;
8395 }
8396
8397 void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
8398 {
8399 struct btrfs_block_group_cache *block_group;
8400 u64 last = 0;
8401
8402 while (1) {
8403 struct inode *inode;
8404
8405 block_group = btrfs_lookup_first_block_group(info, last);
8406 while (block_group) {
8407 spin_lock(&block_group->lock);
8408 if (block_group->iref)
8409 break;
8410 spin_unlock(&block_group->lock);
8411 block_group = next_block_group(info->tree_root,
8412 block_group);
8413 }
8414 if (!block_group) {
8415 if (last == 0)
8416 break;
8417 last = 0;
8418 continue;
8419 }
8420
8421 inode = block_group->inode;
8422 block_group->iref = 0;
8423 block_group->inode = NULL;
8424 spin_unlock(&block_group->lock);
8425 iput(inode);
8426 last = block_group->key.objectid + block_group->key.offset;
8427 btrfs_put_block_group(block_group);
8428 }
8429 }
8430
8431 int btrfs_free_block_groups(struct btrfs_fs_info *info)
8432 {
8433 struct btrfs_block_group_cache *block_group;
8434 struct btrfs_space_info *space_info;
8435 struct btrfs_caching_control *caching_ctl;
8436 struct rb_node *n;
8437
8438 down_write(&info->extent_commit_sem);
8439 while (!list_empty(&info->caching_block_groups)) {
8440 caching_ctl = list_entry(info->caching_block_groups.next,
8441 struct btrfs_caching_control, list);
8442 list_del(&caching_ctl->list);
8443 put_caching_control(caching_ctl);
8444 }
8445 up_write(&info->extent_commit_sem);
8446
8447 spin_lock(&info->block_group_cache_lock);
8448 while ((n = rb_last(&info->block_group_cache_tree)) != NULL) {
8449 block_group = rb_entry(n, struct btrfs_block_group_cache,
8450 cache_node);
8451 rb_erase(&block_group->cache_node,
8452 &info->block_group_cache_tree);
8453 spin_unlock(&info->block_group_cache_lock);
8454
8455 down_write(&block_group->space_info->groups_sem);
8456 list_del(&block_group->list);
8457 up_write(&block_group->space_info->groups_sem);
8458
8459 if (block_group->cached == BTRFS_CACHE_STARTED)
8460 wait_block_group_cache_done(block_group);
8461
8462 /*
8463 * We haven't cached this block group, which means we could
8464 * possibly have excluded extents on this block group.
8465 */
8466 if (block_group->cached == BTRFS_CACHE_NO)
8467 free_excluded_extents(info->extent_root, block_group);
8468
8469 btrfs_remove_free_space_cache(block_group);
8470 btrfs_put_block_group(block_group);
8471
8472 spin_lock(&info->block_group_cache_lock);
8473 }
8474 spin_unlock(&info->block_group_cache_lock);
8475
8476 /* now that all the block groups are freed, go through and
8477 * free all the space_info structs. This is only called during
8478 * the final stages of unmount, and so we know nobody is
8479 * using them. We call synchronize_rcu() once before we start,
8480 * just to be on the safe side.
8481 */
8482 synchronize_rcu();
8483
8484 release_global_block_rsv(info);
8485
8486 while(!list_empty(&info->space_info)) {
8487 space_info = list_entry(info->space_info.next,
8488 struct btrfs_space_info,
8489 list);
8490 if (space_info->bytes_pinned > 0 ||
8491 space_info->bytes_reserved > 0) {
8492 WARN_ON(1);
8493 dump_space_info(space_info, 0, 0);
8494 }
8495 list_del(&space_info->list);
8496 kfree(space_info);
8497 }
8498 return 0;
8499 }
8500
8501 static void __link_block_group(struct btrfs_space_info *space_info,
8502 struct btrfs_block_group_cache *cache)
8503 {
8504 int index = get_block_group_index(cache);
8505
8506 down_write(&space_info->groups_sem);
8507 list_add_tail(&cache->list, &space_info->block_groups[index]);
8508 up_write(&space_info->groups_sem);
8509 }
8510
8511 int btrfs_read_block_groups(struct btrfs_root *root)
8512 {
8513 struct btrfs_path *path;
8514 int ret;
8515 struct btrfs_block_group_cache *cache;
8516 struct btrfs_fs_info *info = root->fs_info;
8517 struct btrfs_space_info *space_info;
8518 struct btrfs_key key;
8519 struct btrfs_key found_key;
8520 struct extent_buffer *leaf;
8521 int need_clear = 0;
8522 u64 cache_gen;
8523
8524 root = info->extent_root;
8525 key.objectid = 0;
8526 key.offset = 0;
8527 btrfs_set_key_type(&key, BTRFS_BLOCK_GROUP_ITEM_KEY);
8528 path = btrfs_alloc_path();
8529 if (!path)
8530 return -ENOMEM;
8531
8532 cache_gen = btrfs_super_cache_generation(&root->fs_info->super_copy);
8533 if (cache_gen != 0 &&
8534 btrfs_super_generation(&root->fs_info->super_copy) != cache_gen)
8535 need_clear = 1;
8536 if (btrfs_test_opt(root, CLEAR_CACHE))
8537 need_clear = 1;
8538 if (!btrfs_test_opt(root, SPACE_CACHE) && cache_gen)
8539 printk(KERN_INFO "btrfs: disk space caching is enabled\n");
8540
8541 while (1) {
8542 ret = find_first_block_group(root, path, &key);
8543 if (ret > 0)
8544 break;
8545 if (ret != 0)
8546 goto error;
8547 leaf = path->nodes[0];
8548 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
8549 cache = kzalloc(sizeof(*cache), GFP_NOFS);
8550 if (!cache) {
8551 ret = -ENOMEM;
8552 goto error;
8553 }
8554 cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
8555 GFP_NOFS);
8556 if (!cache->free_space_ctl) {
8557 kfree(cache);
8558 ret = -ENOMEM;
8559 goto error;
8560 }
8561
8562 atomic_set(&cache->count, 1);
8563 spin_lock_init(&cache->lock);
8564 cache->fs_info = info;
8565 INIT_LIST_HEAD(&cache->list);
8566 INIT_LIST_HEAD(&cache->cluster_list);
8567
8568 if (need_clear)
8569 cache->disk_cache_state = BTRFS_DC_CLEAR;
8570
8571 read_extent_buffer(leaf, &cache->item,
8572 btrfs_item_ptr_offset(leaf, path->slots[0]),
8573 sizeof(cache->item));
8574 memcpy(&cache->key, &found_key, sizeof(found_key));
8575
8576 key.objectid = found_key.objectid + found_key.offset;
8577 btrfs_release_path(root, path);
8578 cache->flags = btrfs_block_group_flags(&cache->item);
8579 cache->sectorsize = root->sectorsize;
8580
8581 btrfs_init_free_space_ctl(cache);
8582
8583 /*
8584 * We need to exclude the super stripes now so that the space
8585 * info has super bytes accounted for, otherwise we'll think
8586 * we have more space than we actually do.
8587 */
8588 exclude_super_stripes(root, cache);
8589
8590 /*
8591 * check for two cases, either we are full, and therefore
8592 * don't need to bother with the caching work since we won't
8593 * find any space, or we are empty, and we can just add all
8594 * the space in and be done with it. This saves us _alot_ of
8595 * time, particularly in the full case.
8596 */
8597 if (found_key.offset == btrfs_block_group_used(&cache->item)) {
8598 cache->last_byte_to_unpin = (u64)-1;
8599 cache->cached = BTRFS_CACHE_FINISHED;
8600 free_excluded_extents(root, cache);
8601 } else if (btrfs_block_group_used(&cache->item) == 0) {
8602 cache->last_byte_to_unpin = (u64)-1;
8603 cache->cached = BTRFS_CACHE_FINISHED;
8604 add_new_free_space(cache, root->fs_info,
8605 found_key.objectid,
8606 found_key.objectid +
8607 found_key.offset);
8608 free_excluded_extents(root, cache);
8609 }
8610
8611 ret = update_space_info(info, cache->flags, found_key.offset,
8612 btrfs_block_group_used(&cache->item),
8613 &space_info);
8614 BUG_ON(ret);
8615 cache->space_info = space_info;
8616 spin_lock(&cache->space_info->lock);
8617 cache->space_info->bytes_readonly += cache->bytes_super;
8618 spin_unlock(&cache->space_info->lock);
8619
8620 __link_block_group(space_info, cache);
8621
8622 ret = btrfs_add_block_group_cache(root->fs_info, cache);
8623 BUG_ON(ret);
8624
8625 set_avail_alloc_bits(root->fs_info, cache->flags);
8626 if (btrfs_chunk_readonly(root, cache->key.objectid))
8627 set_block_group_ro(cache);
8628 }
8629
8630 list_for_each_entry_rcu(space_info, &root->fs_info->space_info, list) {
8631 if (!(get_alloc_profile(root, space_info->flags) &
8632 (BTRFS_BLOCK_GROUP_RAID10 |
8633 BTRFS_BLOCK_GROUP_RAID1 |
8634 BTRFS_BLOCK_GROUP_DUP)))
8635 continue;
8636 /*
8637 * avoid allocating from un-mirrored block group if there are
8638 * mirrored block groups.
8639 */
8640 list_for_each_entry(cache, &space_info->block_groups[3], list)
8641 set_block_group_ro(cache);
8642 list_for_each_entry(cache, &space_info->block_groups[4], list)
8643 set_block_group_ro(cache);
8644 }
8645
8646 init_global_block_rsv(info);
8647 ret = 0;
8648 error:
8649 btrfs_free_path(path);
8650 return ret;
8651 }
8652
8653 int btrfs_make_block_group(struct btrfs_trans_handle *trans,
8654 struct btrfs_root *root, u64 bytes_used,
8655 u64 type, u64 chunk_objectid, u64 chunk_offset,
8656 u64 size)
8657 {
8658 int ret;
8659 struct btrfs_root *extent_root;
8660 struct btrfs_block_group_cache *cache;
8661
8662 extent_root = root->fs_info->extent_root;
8663
8664 root->fs_info->last_trans_log_full_commit = trans->transid;
8665
8666 cache = kzalloc(sizeof(*cache), GFP_NOFS);
8667 if (!cache)
8668 return -ENOMEM;
8669 cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
8670 GFP_NOFS);
8671 if (!cache->free_space_ctl) {
8672 kfree(cache);
8673 return -ENOMEM;
8674 }
8675
8676 cache->key.objectid = chunk_offset;
8677 cache->key.offset = size;
8678 cache->key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
8679 cache->sectorsize = root->sectorsize;
8680 cache->fs_info = root->fs_info;
8681
8682 atomic_set(&cache->count, 1);
8683 spin_lock_init(&cache->lock);
8684 INIT_LIST_HEAD(&cache->list);
8685 INIT_LIST_HEAD(&cache->cluster_list);
8686
8687 btrfs_init_free_space_ctl(cache);
8688
8689 btrfs_set_block_group_used(&cache->item, bytes_used);
8690 btrfs_set_block_group_chunk_objectid(&cache->item, chunk_objectid);
8691 cache->flags = type;
8692 btrfs_set_block_group_flags(&cache->item, type);
8693
8694 cache->last_byte_to_unpin = (u64)-1;
8695 cache->cached = BTRFS_CACHE_FINISHED;
8696 exclude_super_stripes(root, cache);
8697
8698 add_new_free_space(cache, root->fs_info, chunk_offset,
8699 chunk_offset + size);
8700
8701 free_excluded_extents(root, cache);
8702
8703 ret = update_space_info(root->fs_info, cache->flags, size, bytes_used,
8704 &cache->space_info);
8705 BUG_ON(ret);
8706
8707 spin_lock(&cache->space_info->lock);
8708 cache->space_info->bytes_readonly += cache->bytes_super;
8709 spin_unlock(&cache->space_info->lock);
8710
8711 __link_block_group(cache->space_info, cache);
8712
8713 ret = btrfs_add_block_group_cache(root->fs_info, cache);
8714 BUG_ON(ret);
8715
8716 ret = btrfs_insert_item(trans, extent_root, &cache->key, &cache->item,
8717 sizeof(cache->item));
8718 BUG_ON(ret);
8719
8720 set_avail_alloc_bits(extent_root->fs_info, type);
8721
8722 return 0;
8723 }
8724
8725 int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
8726 struct btrfs_root *root, u64 group_start)
8727 {
8728 struct btrfs_path *path;
8729 struct btrfs_block_group_cache *block_group;
8730 struct btrfs_free_cluster *cluster;
8731 struct btrfs_root *tree_root = root->fs_info->tree_root;
8732 struct btrfs_key key;
8733 struct inode *inode;
8734 int ret;
8735 int factor;
8736
8737 root = root->fs_info->extent_root;
8738
8739 block_group = btrfs_lookup_block_group(root->fs_info, group_start);
8740 BUG_ON(!block_group);
8741 BUG_ON(!block_group->ro);
8742
8743 /*
8744 * Free the reserved super bytes from this block group before
8745 * remove it.
8746 */
8747 free_excluded_extents(root, block_group);
8748
8749 memcpy(&key, &block_group->key, sizeof(key));
8750 if (block_group->flags & (BTRFS_BLOCK_GROUP_DUP |
8751 BTRFS_BLOCK_GROUP_RAID1 |
8752 BTRFS_BLOCK_GROUP_RAID10))
8753 factor = 2;
8754 else
8755 factor = 1;
8756
8757 /* make sure this block group isn't part of an allocation cluster */
8758 cluster = &root->fs_info->data_alloc_cluster;
8759 spin_lock(&cluster->refill_lock);
8760 btrfs_return_cluster_to_free_space(block_group, cluster);
8761 spin_unlock(&cluster->refill_lock);
8762
8763 /*
8764 * make sure this block group isn't part of a metadata
8765 * allocation cluster
8766 */
8767 cluster = &root->fs_info->meta_alloc_cluster;
8768 spin_lock(&cluster->refill_lock);
8769 btrfs_return_cluster_to_free_space(block_group, cluster);
8770 spin_unlock(&cluster->refill_lock);
8771
8772 path = btrfs_alloc_path();
8773 BUG_ON(!path);
8774
8775 inode = lookup_free_space_inode(root, block_group, path);
8776 if (!IS_ERR(inode)) {
8777 btrfs_orphan_add(trans, inode);
8778 clear_nlink(inode);
8779 /* One for the block groups ref */
8780 spin_lock(&block_group->lock);
8781 if (block_group->iref) {
8782 block_group->iref = 0;
8783 block_group->inode = NULL;
8784 spin_unlock(&block_group->lock);
8785 iput(inode);
8786 } else {
8787 spin_unlock(&block_group->lock);
8788 }
8789 /* One for our lookup ref */
8790 iput(inode);
8791 }
8792
8793 key.objectid = BTRFS_FREE_SPACE_OBJECTID;
8794 key.offset = block_group->key.objectid;
8795 key.type = 0;
8796
8797 ret = btrfs_search_slot(trans, tree_root, &key, path, -1, 1);
8798 if (ret < 0)
8799 goto out;
8800 if (ret > 0)
8801 btrfs_release_path(tree_root, path);
8802 if (ret == 0) {
8803 ret = btrfs_del_item(trans, tree_root, path);
8804 if (ret)
8805 goto out;
8806 btrfs_release_path(tree_root, path);
8807 }
8808
8809 spin_lock(&root->fs_info->block_group_cache_lock);
8810 rb_erase(&block_group->cache_node,
8811 &root->fs_info->block_group_cache_tree);
8812 spin_unlock(&root->fs_info->block_group_cache_lock);
8813
8814 down_write(&block_group->space_info->groups_sem);
8815 /*
8816 * we must use list_del_init so people can check to see if they
8817 * are still on the list after taking the semaphore
8818 */
8819 list_del_init(&block_group->list);
8820 up_write(&block_group->space_info->groups_sem);
8821
8822 if (block_group->cached == BTRFS_CACHE_STARTED)
8823 wait_block_group_cache_done(block_group);
8824
8825 btrfs_remove_free_space_cache(block_group);
8826
8827 spin_lock(&block_group->space_info->lock);
8828 block_group->space_info->total_bytes -= block_group->key.offset;
8829 block_group->space_info->bytes_readonly -= block_group->key.offset;
8830 block_group->space_info->disk_total -= block_group->key.offset * factor;
8831 spin_unlock(&block_group->space_info->lock);
8832
8833 memcpy(&key, &block_group->key, sizeof(key));
8834
8835 btrfs_clear_space_info_full(root->fs_info);
8836
8837 btrfs_put_block_group(block_group);
8838 btrfs_put_block_group(block_group);
8839
8840 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
8841 if (ret > 0)
8842 ret = -EIO;
8843 if (ret < 0)
8844 goto out;
8845
8846 ret = btrfs_del_item(trans, root, path);
8847 out:
8848 btrfs_free_path(path);
8849 return ret;
8850 }
8851
8852 int btrfs_init_space_info(struct btrfs_fs_info *fs_info)
8853 {
8854 struct btrfs_space_info *space_info;
8855 struct btrfs_super_block *disk_super;
8856 u64 features;
8857 u64 flags;
8858 int mixed = 0;
8859 int ret;
8860
8861 disk_super = &fs_info->super_copy;
8862 if (!btrfs_super_root(disk_super))
8863 return 1;
8864
8865 features = btrfs_super_incompat_flags(disk_super);
8866 if (features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
8867 mixed = 1;
8868
8869 flags = BTRFS_BLOCK_GROUP_SYSTEM;
8870 ret = update_space_info(fs_info, flags, 0, 0, &space_info);
8871 if (ret)
8872 goto out;
8873
8874 if (mixed) {
8875 flags = BTRFS_BLOCK_GROUP_METADATA | BTRFS_BLOCK_GROUP_DATA;
8876 ret = update_space_info(fs_info, flags, 0, 0, &space_info);
8877 } else {
8878 flags = BTRFS_BLOCK_GROUP_METADATA;
8879 ret = update_space_info(fs_info, flags, 0, 0, &space_info);
8880 if (ret)
8881 goto out;
8882
8883 flags = BTRFS_BLOCK_GROUP_DATA;
8884 ret = update_space_info(fs_info, flags, 0, 0, &space_info);
8885 }
8886 out:
8887 return ret;
8888 }
8889
8890 int btrfs_error_unpin_extent_range(struct btrfs_root *root, u64 start, u64 end)
8891 {
8892 return unpin_extent_range(root, start, end);
8893 }
8894
8895 int btrfs_error_discard_extent(struct btrfs_root *root, u64 bytenr,
8896 u64 num_bytes, u64 *actual_bytes)
8897 {
8898 return btrfs_discard_extent(root, bytenr, num_bytes, actual_bytes);
8899 }
8900
8901 int btrfs_trim_fs(struct btrfs_root *root, struct fstrim_range *range)
8902 {
8903 struct btrfs_fs_info *fs_info = root->fs_info;
8904 struct btrfs_block_group_cache *cache = NULL;
8905 u64 group_trimmed;
8906 u64 start;
8907 u64 end;
8908 u64 trimmed = 0;
8909 int ret = 0;
8910
8911 cache = btrfs_lookup_block_group(fs_info, range->start);
8912
8913 while (cache) {
8914 if (cache->key.objectid >= (range->start + range->len)) {
8915 btrfs_put_block_group(cache);
8916 break;
8917 }
8918
8919 start = max(range->start, cache->key.objectid);
8920 end = min(range->start + range->len,
8921 cache->key.objectid + cache->key.offset);
8922
8923 if (end - start >= range->minlen) {
8924 if (!block_group_cache_done(cache)) {
8925 ret = cache_block_group(cache, NULL, root, 0);
8926 if (!ret)
8927 wait_block_group_cache_done(cache);
8928 }
8929 ret = btrfs_trim_block_group(cache,
8930 &group_trimmed,
8931 start,
8932 end,
8933 range->minlen);
8934
8935 trimmed += group_trimmed;
8936 if (ret) {
8937 btrfs_put_block_group(cache);
8938 break;
8939 }
8940 }
8941
8942 cache = next_block_group(fs_info->tree_root, cache);
8943 }
8944
8945 range->len = trimmed;
8946 return ret;
8947 }
This page took 0.3426 seconds and 5 git commands to generate.