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