Fix race in create_empty_buffers() vs __set_page_dirty_buffers()
[sfrench/cifs-2.6.git] / fs / btrfs / extent-tree.c
1 /*
2  * Copyright (C) 2007 Oracle.  All rights reserved.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public
6  * License v2 as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public
14  * License along with this program; if not, write to the
15  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16  * Boston, MA 021110-1307, USA.
17  */
18 #include <linux/sched.h>
19 #include <linux/pagemap.h>
20 #include <linux/writeback.h>
21 #include <linux/blkdev.h>
22 #include <linux/sort.h>
23 #include "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
34 #define PENDING_EXTENT_INSERT 0
35 #define PENDING_EXTENT_DELETE 1
36 #define PENDING_BACKREF_UPDATE 2
37
38 struct pending_extent_op {
39         int type;
40         u64 bytenr;
41         u64 num_bytes;
42         u64 parent;
43         u64 orig_parent;
44         u64 generation;
45         u64 orig_generation;
46         int level;
47         struct list_head list;
48         int del;
49 };
50
51 static int finish_current_insert(struct btrfs_trans_handle *trans,
52                                  struct btrfs_root *extent_root, int all);
53 static int del_pending_extents(struct btrfs_trans_handle *trans,
54                                struct btrfs_root *extent_root, int all);
55 static int pin_down_bytes(struct btrfs_trans_handle *trans,
56                           struct btrfs_root *root,
57                           u64 bytenr, u64 num_bytes, int is_data);
58 static int update_block_group(struct btrfs_trans_handle *trans,
59                               struct btrfs_root *root,
60                               u64 bytenr, u64 num_bytes, int alloc,
61                               int mark_free);
62
63 static int do_chunk_alloc(struct btrfs_trans_handle *trans,
64                           struct btrfs_root *extent_root, u64 alloc_bytes,
65                           u64 flags, int force);
66
67 static int block_group_bits(struct btrfs_block_group_cache *cache, u64 bits)
68 {
69         return (cache->flags & bits) == bits;
70 }
71
72 /*
73  * this adds the block group to the fs_info rb tree for the block group
74  * cache
75  */
76 static int btrfs_add_block_group_cache(struct btrfs_fs_info *info,
77                                 struct btrfs_block_group_cache *block_group)
78 {
79         struct rb_node **p;
80         struct rb_node *parent = NULL;
81         struct btrfs_block_group_cache *cache;
82
83         spin_lock(&info->block_group_cache_lock);
84         p = &info->block_group_cache_tree.rb_node;
85
86         while (*p) {
87                 parent = *p;
88                 cache = rb_entry(parent, struct btrfs_block_group_cache,
89                                  cache_node);
90                 if (block_group->key.objectid < cache->key.objectid) {
91                         p = &(*p)->rb_left;
92                 } else if (block_group->key.objectid > cache->key.objectid) {
93                         p = &(*p)->rb_right;
94                 } else {
95                         spin_unlock(&info->block_group_cache_lock);
96                         return -EEXIST;
97                 }
98         }
99
100         rb_link_node(&block_group->cache_node, parent, p);
101         rb_insert_color(&block_group->cache_node,
102                         &info->block_group_cache_tree);
103         spin_unlock(&info->block_group_cache_lock);
104
105         return 0;
106 }
107
108 /*
109  * This will return the block group at or after bytenr if contains is 0, else
110  * it will return the block group that contains the bytenr
111  */
112 static struct btrfs_block_group_cache *
113 block_group_cache_tree_search(struct btrfs_fs_info *info, u64 bytenr,
114                               int contains)
115 {
116         struct btrfs_block_group_cache *cache, *ret = NULL;
117         struct rb_node *n;
118         u64 end, start;
119
120         spin_lock(&info->block_group_cache_lock);
121         n = info->block_group_cache_tree.rb_node;
122
123         while (n) {
124                 cache = rb_entry(n, struct btrfs_block_group_cache,
125                                  cache_node);
126                 end = cache->key.objectid + cache->key.offset - 1;
127                 start = cache->key.objectid;
128
129                 if (bytenr < start) {
130                         if (!contains && (!ret || start < ret->key.objectid))
131                                 ret = cache;
132                         n = n->rb_left;
133                 } else if (bytenr > start) {
134                         if (contains && bytenr <= end) {
135                                 ret = cache;
136                                 break;
137                         }
138                         n = n->rb_right;
139                 } else {
140                         ret = cache;
141                         break;
142                 }
143         }
144         if (ret)
145                 atomic_inc(&ret->count);
146         spin_unlock(&info->block_group_cache_lock);
147
148         return ret;
149 }
150
151 /*
152  * this is only called by cache_block_group, since we could have freed extents
153  * we need to check the pinned_extents for any extents that can't be used yet
154  * since their free space will be released as soon as the transaction commits.
155  */
156 static int add_new_free_space(struct btrfs_block_group_cache *block_group,
157                               struct btrfs_fs_info *info, u64 start, u64 end)
158 {
159         u64 extent_start, extent_end, size;
160         int ret;
161
162         mutex_lock(&info->pinned_mutex);
163         while (start < end) {
164                 ret = find_first_extent_bit(&info->pinned_extents, start,
165                                             &extent_start, &extent_end,
166                                             EXTENT_DIRTY);
167                 if (ret)
168                         break;
169
170                 if (extent_start == start) {
171                         start = extent_end + 1;
172                 } else if (extent_start > start && extent_start < end) {
173                         size = extent_start - start;
174                         ret = btrfs_add_free_space(block_group, start,
175                                                    size);
176                         BUG_ON(ret);
177                         start = extent_end + 1;
178                 } else {
179                         break;
180                 }
181         }
182
183         if (start < end) {
184                 size = end - start;
185                 ret = btrfs_add_free_space(block_group, start, size);
186                 BUG_ON(ret);
187         }
188         mutex_unlock(&info->pinned_mutex);
189
190         return 0;
191 }
192
193 static int remove_sb_from_cache(struct btrfs_root *root,
194                                 struct btrfs_block_group_cache *cache)
195 {
196         u64 bytenr;
197         u64 *logical;
198         int stripe_len;
199         int i, nr, ret;
200
201         for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
202                 bytenr = btrfs_sb_offset(i);
203                 ret = btrfs_rmap_block(&root->fs_info->mapping_tree,
204                                        cache->key.objectid, bytenr, 0,
205                                        &logical, &nr, &stripe_len);
206                 BUG_ON(ret);
207                 while (nr--) {
208                         btrfs_remove_free_space(cache, logical[nr],
209                                                 stripe_len);
210                 }
211                 kfree(logical);
212         }
213         return 0;
214 }
215
216 static int cache_block_group(struct btrfs_root *root,
217                              struct btrfs_block_group_cache *block_group)
218 {
219         struct btrfs_path *path;
220         int ret = 0;
221         struct btrfs_key key;
222         struct extent_buffer *leaf;
223         int slot;
224         u64 last;
225
226         if (!block_group)
227                 return 0;
228
229         root = root->fs_info->extent_root;
230
231         if (block_group->cached)
232                 return 0;
233
234         path = btrfs_alloc_path();
235         if (!path)
236                 return -ENOMEM;
237
238         path->reada = 2;
239         /*
240          * we get into deadlocks with paths held by callers of this function.
241          * since the alloc_mutex is protecting things right now, just
242          * skip the locking here
243          */
244         path->skip_locking = 1;
245         last = max_t(u64, block_group->key.objectid, BTRFS_SUPER_INFO_OFFSET);
246         key.objectid = last;
247         key.offset = 0;
248         btrfs_set_key_type(&key, BTRFS_EXTENT_ITEM_KEY);
249         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
250         if (ret < 0)
251                 goto err;
252
253         while (1) {
254                 leaf = path->nodes[0];
255                 slot = path->slots[0];
256                 if (slot >= btrfs_header_nritems(leaf)) {
257                         ret = btrfs_next_leaf(root, path);
258                         if (ret < 0)
259                                 goto err;
260                         if (ret == 0)
261                                 continue;
262                         else
263                                 break;
264                 }
265                 btrfs_item_key_to_cpu(leaf, &key, slot);
266                 if (key.objectid < block_group->key.objectid)
267                         goto next;
268
269                 if (key.objectid >= block_group->key.objectid +
270                     block_group->key.offset)
271                         break;
272
273                 if (btrfs_key_type(&key) == BTRFS_EXTENT_ITEM_KEY) {
274                         add_new_free_space(block_group, root->fs_info, last,
275                                            key.objectid);
276
277                         last = key.objectid + key.offset;
278                 }
279 next:
280                 path->slots[0]++;
281         }
282
283         add_new_free_space(block_group, root->fs_info, last,
284                            block_group->key.objectid +
285                            block_group->key.offset);
286
287         remove_sb_from_cache(root, block_group);
288         block_group->cached = 1;
289         ret = 0;
290 err:
291         btrfs_free_path(path);
292         return ret;
293 }
294
295 /*
296  * return the block group that starts at or after bytenr
297  */
298 static struct btrfs_block_group_cache *
299 btrfs_lookup_first_block_group(struct btrfs_fs_info *info, u64 bytenr)
300 {
301         struct btrfs_block_group_cache *cache;
302
303         cache = block_group_cache_tree_search(info, bytenr, 0);
304
305         return cache;
306 }
307
308 /*
309  * return the block group that contains teh given bytenr
310  */
311 struct btrfs_block_group_cache *btrfs_lookup_block_group(
312                                                  struct btrfs_fs_info *info,
313                                                  u64 bytenr)
314 {
315         struct btrfs_block_group_cache *cache;
316
317         cache = block_group_cache_tree_search(info, bytenr, 1);
318
319         return cache;
320 }
321
322 static inline void put_block_group(struct btrfs_block_group_cache *cache)
323 {
324         if (atomic_dec_and_test(&cache->count))
325                 kfree(cache);
326 }
327
328 static struct btrfs_space_info *__find_space_info(struct btrfs_fs_info *info,
329                                                   u64 flags)
330 {
331         struct list_head *head = &info->space_info;
332         struct btrfs_space_info *found;
333         list_for_each_entry(found, head, list) {
334                 if (found->flags == flags)
335                         return found;
336         }
337         return NULL;
338 }
339
340 static u64 div_factor(u64 num, int factor)
341 {
342         if (factor == 10)
343                 return num;
344         num *= factor;
345         do_div(num, 10);
346         return num;
347 }
348
349 u64 btrfs_find_block_group(struct btrfs_root *root,
350                            u64 search_start, u64 search_hint, int owner)
351 {
352         struct btrfs_block_group_cache *cache;
353         u64 used;
354         u64 last = max(search_hint, search_start);
355         u64 group_start = 0;
356         int full_search = 0;
357         int factor = 9;
358         int wrapped = 0;
359 again:
360         while (1) {
361                 cache = btrfs_lookup_first_block_group(root->fs_info, last);
362                 if (!cache)
363                         break;
364
365                 spin_lock(&cache->lock);
366                 last = cache->key.objectid + cache->key.offset;
367                 used = btrfs_block_group_used(&cache->item);
368
369                 if ((full_search || !cache->ro) &&
370                     block_group_bits(cache, BTRFS_BLOCK_GROUP_METADATA)) {
371                         if (used + cache->pinned + cache->reserved <
372                             div_factor(cache->key.offset, factor)) {
373                                 group_start = cache->key.objectid;
374                                 spin_unlock(&cache->lock);
375                                 put_block_group(cache);
376                                 goto found;
377                         }
378                 }
379                 spin_unlock(&cache->lock);
380                 put_block_group(cache);
381                 cond_resched();
382         }
383         if (!wrapped) {
384                 last = search_start;
385                 wrapped = 1;
386                 goto again;
387         }
388         if (!full_search && factor < 10) {
389                 last = search_start;
390                 full_search = 1;
391                 factor = 10;
392                 goto again;
393         }
394 found:
395         return group_start;
396 }
397
398 /* simple helper to search for an existing extent at a given offset */
399 int btrfs_lookup_extent(struct btrfs_root *root, u64 start, u64 len)
400 {
401         int ret;
402         struct btrfs_key key;
403         struct btrfs_path *path;
404
405         path = btrfs_alloc_path();
406         BUG_ON(!path);
407         key.objectid = start;
408         key.offset = len;
409         btrfs_set_key_type(&key, BTRFS_EXTENT_ITEM_KEY);
410         ret = btrfs_search_slot(NULL, root->fs_info->extent_root, &key, path,
411                                 0, 0);
412         btrfs_free_path(path);
413         return ret;
414 }
415
416 /*
417  * Back reference rules.  Back refs have three main goals:
418  *
419  * 1) differentiate between all holders of references to an extent so that
420  *    when a reference is dropped we can make sure it was a valid reference
421  *    before freeing the extent.
422  *
423  * 2) Provide enough information to quickly find the holders of an extent
424  *    if we notice a given block is corrupted or bad.
425  *
426  * 3) Make it easy to migrate blocks for FS shrinking or storage pool
427  *    maintenance.  This is actually the same as #2, but with a slightly
428  *    different use case.
429  *
430  * File extents can be referenced by:
431  *
432  * - multiple snapshots, subvolumes, or different generations in one subvol
433  * - different files inside a single subvolume
434  * - different offsets inside a file (bookend extents in file.c)
435  *
436  * The extent ref structure has fields for:
437  *
438  * - Objectid of the subvolume root
439  * - Generation number of the tree holding the reference
440  * - objectid of the file holding the reference
441  * - number of references holding by parent node (alway 1 for tree blocks)
442  *
443  * Btree leaf may hold multiple references to a file extent. In most cases,
444  * these references are from same file and the corresponding offsets inside
445  * the file are close together.
446  *
447  * When a file extent is allocated the fields are filled in:
448  *     (root_key.objectid, trans->transid, inode objectid, 1)
449  *
450  * When a leaf is cow'd new references are added for every file extent found
451  * in the leaf.  It looks similar to the create case, but trans->transid will
452  * be different when the block is cow'd.
453  *
454  *     (root_key.objectid, trans->transid, inode objectid,
455  *      number of references in the leaf)
456  *
457  * When a file extent is removed either during snapshot deletion or
458  * file truncation, we find the corresponding back reference and check
459  * the following fields:
460  *
461  *     (btrfs_header_owner(leaf), btrfs_header_generation(leaf),
462  *      inode objectid)
463  *
464  * Btree extents can be referenced by:
465  *
466  * - Different subvolumes
467  * - Different generations of the same subvolume
468  *
469  * When a tree block is created, back references are inserted:
470  *
471  * (root->root_key.objectid, trans->transid, level, 1)
472  *
473  * When a tree block is cow'd, new back references are added for all the
474  * blocks it points to. If the tree block isn't in reference counted root,
475  * the old back references are removed. These new back references are of
476  * the form (trans->transid will have increased since creation):
477  *
478  * (root->root_key.objectid, trans->transid, level, 1)
479  *
480  * When a backref is in deleting, the following fields are checked:
481  *
482  * if backref was for a tree root:
483  *     (btrfs_header_owner(itself), btrfs_header_generation(itself), level)
484  * else
485  *     (btrfs_header_owner(parent), btrfs_header_generation(parent), level)
486  *
487  * Back Reference Key composing:
488  *
489  * The key objectid corresponds to the first byte in the extent, the key
490  * type is set to BTRFS_EXTENT_REF_KEY, and the key offset is the first
491  * byte of parent extent. If a extent is tree root, the key offset is set
492  * to the key objectid.
493  */
494
495 static noinline int lookup_extent_backref(struct btrfs_trans_handle *trans,
496                                           struct btrfs_root *root,
497                                           struct btrfs_path *path,
498                                           u64 bytenr, u64 parent,
499                                           u64 ref_root, u64 ref_generation,
500                                           u64 owner_objectid, int del)
501 {
502         struct btrfs_key key;
503         struct btrfs_extent_ref *ref;
504         struct extent_buffer *leaf;
505         u64 ref_objectid;
506         int ret;
507
508         key.objectid = bytenr;
509         key.type = BTRFS_EXTENT_REF_KEY;
510         key.offset = parent;
511
512         ret = btrfs_search_slot(trans, root, &key, path, del ? -1 : 0, 1);
513         if (ret < 0)
514                 goto out;
515         if (ret > 0) {
516                 ret = -ENOENT;
517                 goto out;
518         }
519
520         leaf = path->nodes[0];
521         ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_ref);
522         ref_objectid = btrfs_ref_objectid(leaf, ref);
523         if (btrfs_ref_root(leaf, ref) != ref_root ||
524             btrfs_ref_generation(leaf, ref) != ref_generation ||
525             (ref_objectid != owner_objectid &&
526              ref_objectid != BTRFS_MULTIPLE_OBJECTIDS)) {
527                 ret = -EIO;
528                 WARN_ON(1);
529                 goto out;
530         }
531         ret = 0;
532 out:
533         return ret;
534 }
535
536 /*
537  * updates all the backrefs that are pending on update_list for the
538  * extent_root
539  */
540 static noinline int update_backrefs(struct btrfs_trans_handle *trans,
541                                     struct btrfs_root *extent_root,
542                                     struct btrfs_path *path,
543                                     struct list_head *update_list)
544 {
545         struct btrfs_key key;
546         struct btrfs_extent_ref *ref;
547         struct btrfs_fs_info *info = extent_root->fs_info;
548         struct pending_extent_op *op;
549         struct extent_buffer *leaf;
550         int ret = 0;
551         struct list_head *cur = update_list->next;
552         u64 ref_objectid;
553         u64 ref_root = extent_root->root_key.objectid;
554
555         op = list_entry(cur, struct pending_extent_op, list);
556
557 search:
558         key.objectid = op->bytenr;
559         key.type = BTRFS_EXTENT_REF_KEY;
560         key.offset = op->orig_parent;
561
562         ret = btrfs_search_slot(trans, extent_root, &key, path, 0, 1);
563         BUG_ON(ret);
564
565         leaf = path->nodes[0];
566
567 loop:
568         ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_ref);
569
570         ref_objectid = btrfs_ref_objectid(leaf, ref);
571
572         if (btrfs_ref_root(leaf, ref) != ref_root ||
573             btrfs_ref_generation(leaf, ref) != op->orig_generation ||
574             (ref_objectid != op->level &&
575              ref_objectid != BTRFS_MULTIPLE_OBJECTIDS)) {
576                 printk(KERN_ERR "btrfs couldn't find %llu, parent %llu, "
577                        "root %llu, owner %u\n",
578                        (unsigned long long)op->bytenr,
579                        (unsigned long long)op->orig_parent,
580                        (unsigned long long)ref_root, op->level);
581                 btrfs_print_leaf(extent_root, leaf);
582                 BUG();
583         }
584
585         key.objectid = op->bytenr;
586         key.offset = op->parent;
587         key.type = BTRFS_EXTENT_REF_KEY;
588         ret = btrfs_set_item_key_safe(trans, extent_root, path, &key);
589         BUG_ON(ret);
590         ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_ref);
591         btrfs_set_ref_generation(leaf, ref, op->generation);
592
593         cur = cur->next;
594
595         list_del_init(&op->list);
596         unlock_extent(&info->extent_ins, op->bytenr,
597                       op->bytenr + op->num_bytes - 1, GFP_NOFS);
598         kfree(op);
599
600         if (cur == update_list) {
601                 btrfs_mark_buffer_dirty(path->nodes[0]);
602                 btrfs_release_path(extent_root, path);
603                 goto out;
604         }
605
606         op = list_entry(cur, struct pending_extent_op, list);
607
608         path->slots[0]++;
609         while (path->slots[0] < btrfs_header_nritems(leaf)) {
610                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
611                 if (key.objectid == op->bytenr &&
612                     key.type == BTRFS_EXTENT_REF_KEY)
613                         goto loop;
614                 path->slots[0]++;
615         }
616
617         btrfs_mark_buffer_dirty(path->nodes[0]);
618         btrfs_release_path(extent_root, path);
619         goto search;
620
621 out:
622         return 0;
623 }
624
625 static noinline int insert_extents(struct btrfs_trans_handle *trans,
626                                    struct btrfs_root *extent_root,
627                                    struct btrfs_path *path,
628                                    struct list_head *insert_list, int nr)
629 {
630         struct btrfs_key *keys;
631         u32 *data_size;
632         struct pending_extent_op *op;
633         struct extent_buffer *leaf;
634         struct list_head *cur = insert_list->next;
635         struct btrfs_fs_info *info = extent_root->fs_info;
636         u64 ref_root = extent_root->root_key.objectid;
637         int i = 0, last = 0, ret;
638         int total = nr * 2;
639
640         if (!nr)
641                 return 0;
642
643         keys = kzalloc(total * sizeof(struct btrfs_key), GFP_NOFS);
644         if (!keys)
645                 return -ENOMEM;
646
647         data_size = kzalloc(total * sizeof(u32), GFP_NOFS);
648         if (!data_size) {
649                 kfree(keys);
650                 return -ENOMEM;
651         }
652
653         list_for_each_entry(op, insert_list, list) {
654                 keys[i].objectid = op->bytenr;
655                 keys[i].offset = op->num_bytes;
656                 keys[i].type = BTRFS_EXTENT_ITEM_KEY;
657                 data_size[i] = sizeof(struct btrfs_extent_item);
658                 i++;
659
660                 keys[i].objectid = op->bytenr;
661                 keys[i].offset = op->parent;
662                 keys[i].type = BTRFS_EXTENT_REF_KEY;
663                 data_size[i] = sizeof(struct btrfs_extent_ref);
664                 i++;
665         }
666
667         op = list_entry(cur, struct pending_extent_op, list);
668         i = 0;
669         while (i < total) {
670                 int c;
671                 ret = btrfs_insert_some_items(trans, extent_root, path,
672                                               keys+i, data_size+i, total-i);
673                 BUG_ON(ret < 0);
674
675                 if (last && ret > 1)
676                         BUG();
677
678                 leaf = path->nodes[0];
679                 for (c = 0; c < ret; c++) {
680                         int ref_first = keys[i].type == BTRFS_EXTENT_REF_KEY;
681
682                         /*
683                          * if the first item we inserted was a backref, then
684                          * the EXTENT_ITEM will be the odd c's, else it will
685                          * be the even c's
686                          */
687                         if ((ref_first && (c % 2)) ||
688                             (!ref_first && !(c % 2))) {
689                                 struct btrfs_extent_item *itm;
690
691                                 itm = btrfs_item_ptr(leaf, path->slots[0] + c,
692                                                      struct btrfs_extent_item);
693                                 btrfs_set_extent_refs(path->nodes[0], itm, 1);
694                                 op->del++;
695                         } else {
696                                 struct btrfs_extent_ref *ref;
697
698                                 ref = btrfs_item_ptr(leaf, path->slots[0] + c,
699                                                      struct btrfs_extent_ref);
700                                 btrfs_set_ref_root(leaf, ref, ref_root);
701                                 btrfs_set_ref_generation(leaf, ref,
702                                                          op->generation);
703                                 btrfs_set_ref_objectid(leaf, ref, op->level);
704                                 btrfs_set_ref_num_refs(leaf, ref, 1);
705                                 op->del++;
706                         }
707
708                         /*
709                          * using del to see when its ok to free up the
710                          * pending_extent_op.  In the case where we insert the
711                          * last item on the list in order to help do batching
712                          * we need to not free the extent op until we actually
713                          * insert the extent_item
714                          */
715                         if (op->del == 2) {
716                                 unlock_extent(&info->extent_ins, op->bytenr,
717                                               op->bytenr + op->num_bytes - 1,
718                                               GFP_NOFS);
719                                 cur = cur->next;
720                                 list_del_init(&op->list);
721                                 kfree(op);
722                                 if (cur != insert_list)
723                                         op = list_entry(cur,
724                                                 struct pending_extent_op,
725                                                 list);
726                         }
727                 }
728                 btrfs_mark_buffer_dirty(leaf);
729                 btrfs_release_path(extent_root, path);
730
731                 /*
732                  * Ok backref's and items usually go right next to eachother,
733                  * but if we could only insert 1 item that means that we
734                  * inserted on the end of a leaf, and we have no idea what may
735                  * be on the next leaf so we just play it safe.  In order to
736                  * try and help this case we insert the last thing on our
737                  * insert list so hopefully it will end up being the last
738                  * thing on the leaf and everything else will be before it,
739                  * which will let us insert a whole bunch of items at the same
740                  * time.
741                  */
742                 if (ret == 1 && !last && (i + ret < total)) {
743                         /*
744                          * last: where we will pick up the next time around
745                          * i: our current key to insert, will be total - 1
746                          * cur: the current op we are screwing with
747                          * op: duh
748                          */
749                         last = i + ret;
750                         i = total - 1;
751                         cur = insert_list->prev;
752                         op = list_entry(cur, struct pending_extent_op, list);
753                 } else if (last) {
754                         /*
755                          * ok we successfully inserted the last item on the
756                          * list, lets reset everything
757                          *
758                          * i: our current key to insert, so where we left off
759                          *    last time
760                          * last: done with this
761                          * cur: the op we are messing with
762                          * op: duh
763                          * total: since we inserted the last key, we need to
764                          *        decrement total so we dont overflow
765                          */
766                         i = last;
767                         last = 0;
768                         total--;
769                         if (i < total) {
770                                 cur = insert_list->next;
771                                 op = list_entry(cur, struct pending_extent_op,
772                                                 list);
773                         }
774                 } else {
775                         i += ret;
776                 }
777
778                 cond_resched();
779         }
780         ret = 0;
781         kfree(keys);
782         kfree(data_size);
783         return ret;
784 }
785
786 static noinline int insert_extent_backref(struct btrfs_trans_handle *trans,
787                                           struct btrfs_root *root,
788                                           struct btrfs_path *path,
789                                           u64 bytenr, u64 parent,
790                                           u64 ref_root, u64 ref_generation,
791                                           u64 owner_objectid)
792 {
793         struct btrfs_key key;
794         struct extent_buffer *leaf;
795         struct btrfs_extent_ref *ref;
796         u32 num_refs;
797         int ret;
798
799         key.objectid = bytenr;
800         key.type = BTRFS_EXTENT_REF_KEY;
801         key.offset = parent;
802
803         ret = btrfs_insert_empty_item(trans, root, path, &key, sizeof(*ref));
804         if (ret == 0) {
805                 leaf = path->nodes[0];
806                 ref = btrfs_item_ptr(leaf, path->slots[0],
807                                      struct btrfs_extent_ref);
808                 btrfs_set_ref_root(leaf, ref, ref_root);
809                 btrfs_set_ref_generation(leaf, ref, ref_generation);
810                 btrfs_set_ref_objectid(leaf, ref, owner_objectid);
811                 btrfs_set_ref_num_refs(leaf, ref, 1);
812         } else if (ret == -EEXIST) {
813                 u64 existing_owner;
814                 BUG_ON(owner_objectid < BTRFS_FIRST_FREE_OBJECTID);
815                 leaf = path->nodes[0];
816                 ref = btrfs_item_ptr(leaf, path->slots[0],
817                                      struct btrfs_extent_ref);
818                 if (btrfs_ref_root(leaf, ref) != ref_root ||
819                     btrfs_ref_generation(leaf, ref) != ref_generation) {
820                         ret = -EIO;
821                         WARN_ON(1);
822                         goto out;
823                 }
824
825                 num_refs = btrfs_ref_num_refs(leaf, ref);
826                 BUG_ON(num_refs == 0);
827                 btrfs_set_ref_num_refs(leaf, ref, num_refs + 1);
828
829                 existing_owner = btrfs_ref_objectid(leaf, ref);
830                 if (existing_owner != owner_objectid &&
831                     existing_owner != BTRFS_MULTIPLE_OBJECTIDS) {
832                         btrfs_set_ref_objectid(leaf, ref,
833                                         BTRFS_MULTIPLE_OBJECTIDS);
834                 }
835                 ret = 0;
836         } else {
837                 goto out;
838         }
839         btrfs_mark_buffer_dirty(path->nodes[0]);
840 out:
841         btrfs_release_path(root, path);
842         return ret;
843 }
844
845 static noinline int remove_extent_backref(struct btrfs_trans_handle *trans,
846                                           struct btrfs_root *root,
847                                           struct btrfs_path *path)
848 {
849         struct extent_buffer *leaf;
850         struct btrfs_extent_ref *ref;
851         u32 num_refs;
852         int ret = 0;
853
854         leaf = path->nodes[0];
855         ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_ref);
856         num_refs = btrfs_ref_num_refs(leaf, ref);
857         BUG_ON(num_refs == 0);
858         num_refs -= 1;
859         if (num_refs == 0) {
860                 ret = btrfs_del_item(trans, root, path);
861         } else {
862                 btrfs_set_ref_num_refs(leaf, ref, num_refs);
863                 btrfs_mark_buffer_dirty(leaf);
864         }
865         btrfs_release_path(root, path);
866         return ret;
867 }
868
869 #ifdef BIO_RW_DISCARD
870 static void btrfs_issue_discard(struct block_device *bdev,
871                                 u64 start, u64 len)
872 {
873         blkdev_issue_discard(bdev, start >> 9, len >> 9, GFP_KERNEL);
874 }
875 #endif
876
877 static int btrfs_discard_extent(struct btrfs_root *root, u64 bytenr,
878                                 u64 num_bytes)
879 {
880 #ifdef BIO_RW_DISCARD
881         int ret;
882         u64 map_length = num_bytes;
883         struct btrfs_multi_bio *multi = NULL;
884
885         /* Tell the block device(s) that the sectors can be discarded */
886         ret = btrfs_map_block(&root->fs_info->mapping_tree, READ,
887                               bytenr, &map_length, &multi, 0);
888         if (!ret) {
889                 struct btrfs_bio_stripe *stripe = multi->stripes;
890                 int i;
891
892                 if (map_length > num_bytes)
893                         map_length = num_bytes;
894
895                 for (i = 0; i < multi->num_stripes; i++, stripe++) {
896                         btrfs_issue_discard(stripe->dev->bdev,
897                                             stripe->physical,
898                                             map_length);
899                 }
900                 kfree(multi);
901         }
902
903         return ret;
904 #else
905         return 0;
906 #endif
907 }
908
909 static noinline int free_extents(struct btrfs_trans_handle *trans,
910                                  struct btrfs_root *extent_root,
911                                  struct list_head *del_list)
912 {
913         struct btrfs_fs_info *info = extent_root->fs_info;
914         struct btrfs_path *path;
915         struct btrfs_key key, found_key;
916         struct extent_buffer *leaf;
917         struct list_head *cur;
918         struct pending_extent_op *op;
919         struct btrfs_extent_item *ei;
920         int ret, num_to_del, extent_slot = 0, found_extent = 0;
921         u32 refs;
922         u64 bytes_freed = 0;
923
924         path = btrfs_alloc_path();
925         if (!path)
926                 return -ENOMEM;
927         path->reada = 1;
928
929 search:
930         /* search for the backref for the current ref we want to delete */
931         cur = del_list->next;
932         op = list_entry(cur, struct pending_extent_op, list);
933         ret = lookup_extent_backref(trans, extent_root, path, op->bytenr,
934                                     op->orig_parent,
935                                     extent_root->root_key.objectid,
936                                     op->orig_generation, op->level, 1);
937         if (ret) {
938                 printk(KERN_ERR "btrfs unable to find backref byte nr %llu "
939                        "root %llu gen %llu owner %u\n",
940                        (unsigned long long)op->bytenr,
941                        (unsigned long long)extent_root->root_key.objectid,
942                        (unsigned long long)op->orig_generation, op->level);
943                 btrfs_print_leaf(extent_root, path->nodes[0]);
944                 WARN_ON(1);
945                 goto out;
946         }
947
948         extent_slot = path->slots[0];
949         num_to_del = 1;
950         found_extent = 0;
951
952         /*
953          * if we aren't the first item on the leaf we can move back one and see
954          * if our ref is right next to our extent item
955          */
956         if (likely(extent_slot)) {
957                 extent_slot--;
958                 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
959                                       extent_slot);
960                 if (found_key.objectid == op->bytenr &&
961                     found_key.type == BTRFS_EXTENT_ITEM_KEY &&
962                     found_key.offset == op->num_bytes) {
963                         num_to_del++;
964                         found_extent = 1;
965                 }
966         }
967
968         /*
969          * if we didn't find the extent we need to delete the backref and then
970          * search for the extent item key so we can update its ref count
971          */
972         if (!found_extent) {
973                 key.objectid = op->bytenr;
974                 key.type = BTRFS_EXTENT_ITEM_KEY;
975                 key.offset = op->num_bytes;
976
977                 ret = remove_extent_backref(trans, extent_root, path);
978                 BUG_ON(ret);
979                 btrfs_release_path(extent_root, path);
980                 ret = btrfs_search_slot(trans, extent_root, &key, path, -1, 1);
981                 BUG_ON(ret);
982                 extent_slot = path->slots[0];
983         }
984
985         /* this is where we update the ref count for the extent */
986         leaf = path->nodes[0];
987         ei = btrfs_item_ptr(leaf, extent_slot, struct btrfs_extent_item);
988         refs = btrfs_extent_refs(leaf, ei);
989         BUG_ON(refs == 0);
990         refs--;
991         btrfs_set_extent_refs(leaf, ei, refs);
992
993         btrfs_mark_buffer_dirty(leaf);
994
995         /*
996          * This extent needs deleting.  The reason cur_slot is extent_slot +
997          * num_to_del is because extent_slot points to the slot where the extent
998          * is, and if the backref was not right next to the extent we will be
999          * deleting at least 1 item, and will want to start searching at the
1000          * slot directly next to extent_slot.  However if we did find the
1001          * backref next to the extent item them we will be deleting at least 2
1002          * items and will want to start searching directly after the ref slot
1003          */
1004         if (!refs) {
1005                 struct list_head *pos, *n, *end;
1006                 int cur_slot = extent_slot+num_to_del;
1007                 u64 super_used;
1008                 u64 root_used;
1009
1010                 path->slots[0] = extent_slot;
1011                 bytes_freed = op->num_bytes;
1012
1013                 mutex_lock(&info->pinned_mutex);
1014                 ret = pin_down_bytes(trans, extent_root, op->bytenr,
1015                                      op->num_bytes, op->level >=
1016                                      BTRFS_FIRST_FREE_OBJECTID);
1017                 mutex_unlock(&info->pinned_mutex);
1018                 BUG_ON(ret < 0);
1019                 op->del = ret;
1020
1021                 /*
1022                  * we need to see if we can delete multiple things at once, so
1023                  * start looping through the list of extents we are wanting to
1024                  * delete and see if their extent/backref's are right next to
1025                  * eachother and the extents only have 1 ref
1026                  */
1027                 for (pos = cur->next; pos != del_list; pos = pos->next) {
1028                         struct pending_extent_op *tmp;
1029
1030                         tmp = list_entry(pos, struct pending_extent_op, list);
1031
1032                         /* we only want to delete extent+ref at this stage */
1033                         if (cur_slot >= btrfs_header_nritems(leaf) - 1)
1034                                 break;
1035
1036                         btrfs_item_key_to_cpu(leaf, &found_key, cur_slot);
1037                         if (found_key.objectid != tmp->bytenr ||
1038                             found_key.type != BTRFS_EXTENT_ITEM_KEY ||
1039                             found_key.offset != tmp->num_bytes)
1040                                 break;
1041
1042                         /* check to make sure this extent only has one ref */
1043                         ei = btrfs_item_ptr(leaf, cur_slot,
1044                                             struct btrfs_extent_item);
1045                         if (btrfs_extent_refs(leaf, ei) != 1)
1046                                 break;
1047
1048                         btrfs_item_key_to_cpu(leaf, &found_key, cur_slot+1);
1049                         if (found_key.objectid != tmp->bytenr ||
1050                             found_key.type != BTRFS_EXTENT_REF_KEY ||
1051                             found_key.offset != tmp->orig_parent)
1052                                 break;
1053
1054                         /*
1055                          * the ref is right next to the extent, we can set the
1056                          * ref count to 0 since we will delete them both now
1057                          */
1058                         btrfs_set_extent_refs(leaf, ei, 0);
1059
1060                         /* pin down the bytes for this extent */
1061                         mutex_lock(&info->pinned_mutex);
1062                         ret = pin_down_bytes(trans, extent_root, tmp->bytenr,
1063                                              tmp->num_bytes, tmp->level >=
1064                                              BTRFS_FIRST_FREE_OBJECTID);
1065                         mutex_unlock(&info->pinned_mutex);
1066                         BUG_ON(ret < 0);
1067
1068                         /*
1069                          * use the del field to tell if we need to go ahead and
1070                          * free up the extent when we delete the item or not.
1071                          */
1072                         tmp->del = ret;
1073                         bytes_freed += tmp->num_bytes;
1074
1075                         num_to_del += 2;
1076                         cur_slot += 2;
1077                 }
1078                 end = pos;
1079
1080                 /* update the free space counters */
1081                 spin_lock(&info->delalloc_lock);
1082                 super_used = btrfs_super_bytes_used(&info->super_copy);
1083                 btrfs_set_super_bytes_used(&info->super_copy,
1084                                            super_used - bytes_freed);
1085
1086                 root_used = btrfs_root_used(&extent_root->root_item);
1087                 btrfs_set_root_used(&extent_root->root_item,
1088                                     root_used - bytes_freed);
1089                 spin_unlock(&info->delalloc_lock);
1090
1091                 /* delete the items */
1092                 ret = btrfs_del_items(trans, extent_root, path,
1093                                       path->slots[0], num_to_del);
1094                 BUG_ON(ret);
1095
1096                 /*
1097                  * loop through the extents we deleted and do the cleanup work
1098                  * on them
1099                  */
1100                 for (pos = cur, n = pos->next; pos != end;
1101                      pos = n, n = pos->next) {
1102                         struct pending_extent_op *tmp;
1103                         tmp = list_entry(pos, struct pending_extent_op, list);
1104
1105                         /*
1106                          * remember tmp->del tells us wether or not we pinned
1107                          * down the extent
1108                          */
1109                         ret = update_block_group(trans, extent_root,
1110                                                  tmp->bytenr, tmp->num_bytes, 0,
1111                                                  tmp->del);
1112                         BUG_ON(ret);
1113
1114                         list_del_init(&tmp->list);
1115                         unlock_extent(&info->extent_ins, tmp->bytenr,
1116                                       tmp->bytenr + tmp->num_bytes - 1,
1117                                       GFP_NOFS);
1118                         kfree(tmp);
1119                 }
1120         } else if (refs && found_extent) {
1121                 /*
1122                  * the ref and extent were right next to eachother, but the
1123                  * extent still has a ref, so just free the backref and keep
1124                  * going
1125                  */
1126                 ret = remove_extent_backref(trans, extent_root, path);
1127                 BUG_ON(ret);
1128
1129                 list_del_init(&op->list);
1130                 unlock_extent(&info->extent_ins, op->bytenr,
1131                               op->bytenr + op->num_bytes - 1, GFP_NOFS);
1132                 kfree(op);
1133         } else {
1134                 /*
1135                  * the extent has multiple refs and the backref we were looking
1136                  * for was not right next to it, so just unlock and go next,
1137                  * we're good to go
1138                  */
1139                 list_del_init(&op->list);
1140                 unlock_extent(&info->extent_ins, op->bytenr,
1141                               op->bytenr + op->num_bytes - 1, GFP_NOFS);
1142                 kfree(op);
1143         }
1144
1145         btrfs_release_path(extent_root, path);
1146         if (!list_empty(del_list))
1147                 goto search;
1148
1149 out:
1150         btrfs_free_path(path);
1151         return ret;
1152 }
1153
1154 static int __btrfs_update_extent_ref(struct btrfs_trans_handle *trans,
1155                                      struct btrfs_root *root, u64 bytenr,
1156                                      u64 orig_parent, u64 parent,
1157                                      u64 orig_root, u64 ref_root,
1158                                      u64 orig_generation, u64 ref_generation,
1159                                      u64 owner_objectid)
1160 {
1161         int ret;
1162         struct btrfs_root *extent_root = root->fs_info->extent_root;
1163         struct btrfs_path *path;
1164
1165         if (root == root->fs_info->extent_root) {
1166                 struct pending_extent_op *extent_op;
1167                 u64 num_bytes;
1168
1169                 BUG_ON(owner_objectid >= BTRFS_MAX_LEVEL);
1170                 num_bytes = btrfs_level_size(root, (int)owner_objectid);
1171                 mutex_lock(&root->fs_info->extent_ins_mutex);
1172                 if (test_range_bit(&root->fs_info->extent_ins, bytenr,
1173                                 bytenr + num_bytes - 1, EXTENT_WRITEBACK, 0)) {
1174                         u64 priv;
1175                         ret = get_state_private(&root->fs_info->extent_ins,
1176                                                 bytenr, &priv);
1177                         BUG_ON(ret);
1178                         extent_op = (struct pending_extent_op *)
1179                                                         (unsigned long)priv;
1180                         BUG_ON(extent_op->parent != orig_parent);
1181                         BUG_ON(extent_op->generation != orig_generation);
1182
1183                         extent_op->parent = parent;
1184                         extent_op->generation = ref_generation;
1185                 } else {
1186                         extent_op = kmalloc(sizeof(*extent_op), GFP_NOFS);
1187                         BUG_ON(!extent_op);
1188
1189                         extent_op->type = PENDING_BACKREF_UPDATE;
1190                         extent_op->bytenr = bytenr;
1191                         extent_op->num_bytes = num_bytes;
1192                         extent_op->parent = parent;
1193                         extent_op->orig_parent = orig_parent;
1194                         extent_op->generation = ref_generation;
1195                         extent_op->orig_generation = orig_generation;
1196                         extent_op->level = (int)owner_objectid;
1197                         INIT_LIST_HEAD(&extent_op->list);
1198                         extent_op->del = 0;
1199
1200                         set_extent_bits(&root->fs_info->extent_ins,
1201                                         bytenr, bytenr + num_bytes - 1,
1202                                         EXTENT_WRITEBACK, GFP_NOFS);
1203                         set_state_private(&root->fs_info->extent_ins,
1204                                           bytenr, (unsigned long)extent_op);
1205                 }
1206                 mutex_unlock(&root->fs_info->extent_ins_mutex);
1207                 return 0;
1208         }
1209
1210         path = btrfs_alloc_path();
1211         if (!path)
1212                 return -ENOMEM;
1213         ret = lookup_extent_backref(trans, extent_root, path,
1214                                     bytenr, orig_parent, orig_root,
1215                                     orig_generation, owner_objectid, 1);
1216         if (ret)
1217                 goto out;
1218         ret = remove_extent_backref(trans, extent_root, path);
1219         if (ret)
1220                 goto out;
1221         ret = insert_extent_backref(trans, extent_root, path, bytenr,
1222                                     parent, ref_root, ref_generation,
1223                                     owner_objectid);
1224         BUG_ON(ret);
1225         finish_current_insert(trans, extent_root, 0);
1226         del_pending_extents(trans, extent_root, 0);
1227 out:
1228         btrfs_free_path(path);
1229         return ret;
1230 }
1231
1232 int btrfs_update_extent_ref(struct btrfs_trans_handle *trans,
1233                             struct btrfs_root *root, u64 bytenr,
1234                             u64 orig_parent, u64 parent,
1235                             u64 ref_root, u64 ref_generation,
1236                             u64 owner_objectid)
1237 {
1238         int ret;
1239         if (ref_root == BTRFS_TREE_LOG_OBJECTID &&
1240             owner_objectid < BTRFS_FIRST_FREE_OBJECTID)
1241                 return 0;
1242         ret = __btrfs_update_extent_ref(trans, root, bytenr, orig_parent,
1243                                         parent, ref_root, ref_root,
1244                                         ref_generation, ref_generation,
1245                                         owner_objectid);
1246         return ret;
1247 }
1248
1249 static int __btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
1250                                   struct btrfs_root *root, u64 bytenr,
1251                                   u64 orig_parent, u64 parent,
1252                                   u64 orig_root, u64 ref_root,
1253                                   u64 orig_generation, u64 ref_generation,
1254                                   u64 owner_objectid)
1255 {
1256         struct btrfs_path *path;
1257         int ret;
1258         struct btrfs_key key;
1259         struct extent_buffer *l;
1260         struct btrfs_extent_item *item;
1261         u32 refs;
1262
1263         path = btrfs_alloc_path();
1264         if (!path)
1265                 return -ENOMEM;
1266
1267         path->reada = 1;
1268         key.objectid = bytenr;
1269         key.type = BTRFS_EXTENT_ITEM_KEY;
1270         key.offset = (u64)-1;
1271
1272         ret = btrfs_search_slot(trans, root->fs_info->extent_root, &key, path,
1273                                 0, 1);
1274         if (ret < 0)
1275                 return ret;
1276         BUG_ON(ret == 0 || path->slots[0] == 0);
1277
1278         path->slots[0]--;
1279         l = path->nodes[0];
1280
1281         btrfs_item_key_to_cpu(l, &key, path->slots[0]);
1282         if (key.objectid != bytenr) {
1283                 btrfs_print_leaf(root->fs_info->extent_root, path->nodes[0]);
1284                 printk(KERN_ERR "btrfs wanted %llu found %llu\n",
1285                        (unsigned long long)bytenr,
1286                        (unsigned long long)key.objectid);
1287                 BUG();
1288         }
1289         BUG_ON(key.type != BTRFS_EXTENT_ITEM_KEY);
1290
1291         item = btrfs_item_ptr(l, path->slots[0], struct btrfs_extent_item);
1292         refs = btrfs_extent_refs(l, item);
1293         btrfs_set_extent_refs(l, item, refs + 1);
1294         btrfs_mark_buffer_dirty(path->nodes[0]);
1295
1296         btrfs_release_path(root->fs_info->extent_root, path);
1297
1298         path->reada = 1;
1299         ret = insert_extent_backref(trans, root->fs_info->extent_root,
1300                                     path, bytenr, parent,
1301                                     ref_root, ref_generation,
1302                                     owner_objectid);
1303         BUG_ON(ret);
1304         finish_current_insert(trans, root->fs_info->extent_root, 0);
1305         del_pending_extents(trans, root->fs_info->extent_root, 0);
1306
1307         btrfs_free_path(path);
1308         return 0;
1309 }
1310
1311 int btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
1312                          struct btrfs_root *root,
1313                          u64 bytenr, u64 num_bytes, u64 parent,
1314                          u64 ref_root, u64 ref_generation,
1315                          u64 owner_objectid)
1316 {
1317         int ret;
1318         if (ref_root == BTRFS_TREE_LOG_OBJECTID &&
1319             owner_objectid < BTRFS_FIRST_FREE_OBJECTID)
1320                 return 0;
1321         ret = __btrfs_inc_extent_ref(trans, root, bytenr, 0, parent,
1322                                      0, ref_root, 0, ref_generation,
1323                                      owner_objectid);
1324         return ret;
1325 }
1326
1327 int btrfs_extent_post_op(struct btrfs_trans_handle *trans,
1328                          struct btrfs_root *root)
1329 {
1330         u64 start;
1331         u64 end;
1332         int ret;
1333
1334         while(1) {
1335                 finish_current_insert(trans, root->fs_info->extent_root, 1);
1336                 del_pending_extents(trans, root->fs_info->extent_root, 1);
1337
1338                 /* is there more work to do? */
1339                 ret = find_first_extent_bit(&root->fs_info->pending_del,
1340                                             0, &start, &end, EXTENT_WRITEBACK);
1341                 if (!ret)
1342                         continue;
1343                 ret = find_first_extent_bit(&root->fs_info->extent_ins,
1344                                             0, &start, &end, EXTENT_WRITEBACK);
1345                 if (!ret)
1346                         continue;
1347                 break;
1348         }
1349         return 0;
1350 }
1351
1352 int btrfs_lookup_extent_ref(struct btrfs_trans_handle *trans,
1353                             struct btrfs_root *root, u64 bytenr,
1354                             u64 num_bytes, u32 *refs)
1355 {
1356         struct btrfs_path *path;
1357         int ret;
1358         struct btrfs_key key;
1359         struct extent_buffer *l;
1360         struct btrfs_extent_item *item;
1361
1362         WARN_ON(num_bytes < root->sectorsize);
1363         path = btrfs_alloc_path();
1364         path->reada = 1;
1365         key.objectid = bytenr;
1366         key.offset = num_bytes;
1367         btrfs_set_key_type(&key, BTRFS_EXTENT_ITEM_KEY);
1368         ret = btrfs_search_slot(trans, root->fs_info->extent_root, &key, path,
1369                                 0, 0);
1370         if (ret < 0)
1371                 goto out;
1372         if (ret != 0) {
1373                 btrfs_print_leaf(root, path->nodes[0]);
1374                 printk(KERN_INFO "btrfs failed to find block number %llu\n",
1375                        (unsigned long long)bytenr);
1376                 BUG();
1377         }
1378         l = path->nodes[0];
1379         item = btrfs_item_ptr(l, path->slots[0], struct btrfs_extent_item);
1380         *refs = btrfs_extent_refs(l, item);
1381 out:
1382         btrfs_free_path(path);
1383         return 0;
1384 }
1385
1386 int btrfs_cross_ref_exist(struct btrfs_trans_handle *trans,
1387                           struct btrfs_root *root, u64 objectid, u64 bytenr)
1388 {
1389         struct btrfs_root *extent_root = root->fs_info->extent_root;
1390         struct btrfs_path *path;
1391         struct extent_buffer *leaf;
1392         struct btrfs_extent_ref *ref_item;
1393         struct btrfs_key key;
1394         struct btrfs_key found_key;
1395         u64 ref_root;
1396         u64 last_snapshot;
1397         u32 nritems;
1398         int ret;
1399
1400         key.objectid = bytenr;
1401         key.offset = (u64)-1;
1402         key.type = BTRFS_EXTENT_ITEM_KEY;
1403
1404         path = btrfs_alloc_path();
1405         ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
1406         if (ret < 0)
1407                 goto out;
1408         BUG_ON(ret == 0);
1409
1410         ret = -ENOENT;
1411         if (path->slots[0] == 0)
1412                 goto out;
1413
1414         path->slots[0]--;
1415         leaf = path->nodes[0];
1416         btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1417
1418         if (found_key.objectid != bytenr ||
1419             found_key.type != BTRFS_EXTENT_ITEM_KEY)
1420                 goto out;
1421
1422         last_snapshot = btrfs_root_last_snapshot(&root->root_item);
1423         while (1) {
1424                 leaf = path->nodes[0];
1425                 nritems = btrfs_header_nritems(leaf);
1426                 if (path->slots[0] >= nritems) {
1427                         ret = btrfs_next_leaf(extent_root, path);
1428                         if (ret < 0)
1429                                 goto out;
1430                         if (ret == 0)
1431                                 continue;
1432                         break;
1433                 }
1434                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1435                 if (found_key.objectid != bytenr)
1436                         break;
1437
1438                 if (found_key.type != BTRFS_EXTENT_REF_KEY) {
1439                         path->slots[0]++;
1440                         continue;
1441                 }
1442
1443                 ref_item = btrfs_item_ptr(leaf, path->slots[0],
1444                                           struct btrfs_extent_ref);
1445                 ref_root = btrfs_ref_root(leaf, ref_item);
1446                 if ((ref_root != root->root_key.objectid &&
1447                      ref_root != BTRFS_TREE_LOG_OBJECTID) ||
1448                      objectid != btrfs_ref_objectid(leaf, ref_item)) {
1449                         ret = 1;
1450                         goto out;
1451                 }
1452                 if (btrfs_ref_generation(leaf, ref_item) <= last_snapshot) {
1453                         ret = 1;
1454                         goto out;
1455                 }
1456
1457                 path->slots[0]++;
1458         }
1459         ret = 0;
1460 out:
1461         btrfs_free_path(path);
1462         return ret;
1463 }
1464
1465 int btrfs_cache_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
1466                     struct extent_buffer *buf, u32 nr_extents)
1467 {
1468         struct btrfs_key key;
1469         struct btrfs_file_extent_item *fi;
1470         u64 root_gen;
1471         u32 nritems;
1472         int i;
1473         int level;
1474         int ret = 0;
1475         int shared = 0;
1476
1477         if (!root->ref_cows)
1478                 return 0;
1479
1480         if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
1481                 shared = 0;
1482                 root_gen = root->root_key.offset;
1483         } else {
1484                 shared = 1;
1485                 root_gen = trans->transid - 1;
1486         }
1487
1488         level = btrfs_header_level(buf);
1489         nritems = btrfs_header_nritems(buf);
1490
1491         if (level == 0) {
1492                 struct btrfs_leaf_ref *ref;
1493                 struct btrfs_extent_info *info;
1494
1495                 ref = btrfs_alloc_leaf_ref(root, nr_extents);
1496                 if (!ref) {
1497                         ret = -ENOMEM;
1498                         goto out;
1499                 }
1500
1501                 ref->root_gen = root_gen;
1502                 ref->bytenr = buf->start;
1503                 ref->owner = btrfs_header_owner(buf);
1504                 ref->generation = btrfs_header_generation(buf);
1505                 ref->nritems = nr_extents;
1506                 info = ref->extents;
1507
1508                 for (i = 0; nr_extents > 0 && i < nritems; i++) {
1509                         u64 disk_bytenr;
1510                         btrfs_item_key_to_cpu(buf, &key, i);
1511                         if (btrfs_key_type(&key) != BTRFS_EXTENT_DATA_KEY)
1512                                 continue;
1513                         fi = btrfs_item_ptr(buf, i,
1514                                             struct btrfs_file_extent_item);
1515                         if (btrfs_file_extent_type(buf, fi) ==
1516                             BTRFS_FILE_EXTENT_INLINE)
1517                                 continue;
1518                         disk_bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
1519                         if (disk_bytenr == 0)
1520                                 continue;
1521
1522                         info->bytenr = disk_bytenr;
1523                         info->num_bytes =
1524                                 btrfs_file_extent_disk_num_bytes(buf, fi);
1525                         info->objectid = key.objectid;
1526                         info->offset = key.offset;
1527                         info++;
1528                 }
1529
1530                 ret = btrfs_add_leaf_ref(root, ref, shared);
1531                 if (ret == -EEXIST && shared) {
1532                         struct btrfs_leaf_ref *old;
1533                         old = btrfs_lookup_leaf_ref(root, ref->bytenr);
1534                         BUG_ON(!old);
1535                         btrfs_remove_leaf_ref(root, old);
1536                         btrfs_free_leaf_ref(root, old);
1537                         ret = btrfs_add_leaf_ref(root, ref, shared);
1538                 }
1539                 WARN_ON(ret);
1540                 btrfs_free_leaf_ref(root, ref);
1541         }
1542 out:
1543         return ret;
1544 }
1545
1546 /* when a block goes through cow, we update the reference counts of
1547  * everything that block points to.  The internal pointers of the block
1548  * can be in just about any order, and it is likely to have clusters of
1549  * things that are close together and clusters of things that are not.
1550  *
1551  * To help reduce the seeks that come with updating all of these reference
1552  * counts, sort them by byte number before actual updates are done.
1553  *
1554  * struct refsort is used to match byte number to slot in the btree block.
1555  * we sort based on the byte number and then use the slot to actually
1556  * find the item.
1557  *
1558  * struct refsort is smaller than strcut btrfs_item and smaller than
1559  * struct btrfs_key_ptr.  Since we're currently limited to the page size
1560  * for a btree block, there's no way for a kmalloc of refsorts for a
1561  * single node to be bigger than a page.
1562  */
1563 struct refsort {
1564         u64 bytenr;
1565         u32 slot;
1566 };
1567
1568 /*
1569  * for passing into sort()
1570  */
1571 static int refsort_cmp(const void *a_void, const void *b_void)
1572 {
1573         const struct refsort *a = a_void;
1574         const struct refsort *b = b_void;
1575
1576         if (a->bytenr < b->bytenr)
1577                 return -1;
1578         if (a->bytenr > b->bytenr)
1579                 return 1;
1580         return 0;
1581 }
1582
1583
1584 noinline int btrfs_inc_ref(struct btrfs_trans_handle *trans,
1585                            struct btrfs_root *root,
1586                            struct extent_buffer *orig_buf,
1587                            struct extent_buffer *buf, u32 *nr_extents)
1588 {
1589         u64 bytenr;
1590         u64 ref_root;
1591         u64 orig_root;
1592         u64 ref_generation;
1593         u64 orig_generation;
1594         struct refsort *sorted;
1595         u32 nritems;
1596         u32 nr_file_extents = 0;
1597         struct btrfs_key key;
1598         struct btrfs_file_extent_item *fi;
1599         int i;
1600         int level;
1601         int ret = 0;
1602         int faili = 0;
1603         int refi = 0;
1604         int slot;
1605         int (*process_func)(struct btrfs_trans_handle *, struct btrfs_root *,
1606                             u64, u64, u64, u64, u64, u64, u64, u64);
1607
1608         ref_root = btrfs_header_owner(buf);
1609         ref_generation = btrfs_header_generation(buf);
1610         orig_root = btrfs_header_owner(orig_buf);
1611         orig_generation = btrfs_header_generation(orig_buf);
1612
1613         nritems = btrfs_header_nritems(buf);
1614         level = btrfs_header_level(buf);
1615
1616         sorted = kmalloc(sizeof(struct refsort) * nritems, GFP_NOFS);
1617         BUG_ON(!sorted);
1618
1619         if (root->ref_cows) {
1620                 process_func = __btrfs_inc_extent_ref;
1621         } else {
1622                 if (level == 0 &&
1623                     root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID)
1624                         goto out;
1625                 if (level != 0 &&
1626                     root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID)
1627                         goto out;
1628                 process_func = __btrfs_update_extent_ref;
1629         }
1630
1631         /*
1632          * we make two passes through the items.  In the first pass we
1633          * only record the byte number and slot.  Then we sort based on
1634          * byte number and do the actual work based on the sorted results
1635          */
1636         for (i = 0; i < nritems; i++) {
1637                 cond_resched();
1638                 if (level == 0) {
1639                         btrfs_item_key_to_cpu(buf, &key, i);
1640                         if (btrfs_key_type(&key) != BTRFS_EXTENT_DATA_KEY)
1641                                 continue;
1642                         fi = btrfs_item_ptr(buf, i,
1643                                             struct btrfs_file_extent_item);
1644                         if (btrfs_file_extent_type(buf, fi) ==
1645                             BTRFS_FILE_EXTENT_INLINE)
1646                                 continue;
1647                         bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
1648                         if (bytenr == 0)
1649                                 continue;
1650
1651                         nr_file_extents++;
1652                         sorted[refi].bytenr = bytenr;
1653                         sorted[refi].slot = i;
1654                         refi++;
1655                 } else {
1656                         bytenr = btrfs_node_blockptr(buf, i);
1657                         sorted[refi].bytenr = bytenr;
1658                         sorted[refi].slot = i;
1659                         refi++;
1660                 }
1661         }
1662         /*
1663          * if refi == 0, we didn't actually put anything into the sorted
1664          * array and we're done
1665          */
1666         if (refi == 0)
1667                 goto out;
1668
1669         sort(sorted, refi, sizeof(struct refsort), refsort_cmp, NULL);
1670
1671         for (i = 0; i < refi; i++) {
1672                 cond_resched();
1673                 slot = sorted[i].slot;
1674                 bytenr = sorted[i].bytenr;
1675
1676                 if (level == 0) {
1677                         btrfs_item_key_to_cpu(buf, &key, slot);
1678
1679                         ret = process_func(trans, root, bytenr,
1680                                            orig_buf->start, buf->start,
1681                                            orig_root, ref_root,
1682                                            orig_generation, ref_generation,
1683                                            key.objectid);
1684
1685                         if (ret) {
1686                                 faili = slot;
1687                                 WARN_ON(1);
1688                                 goto fail;
1689                         }
1690                 } else {
1691                         ret = process_func(trans, root, bytenr,
1692                                            orig_buf->start, buf->start,
1693                                            orig_root, ref_root,
1694                                            orig_generation, ref_generation,
1695                                            level - 1);
1696                         if (ret) {
1697                                 faili = slot;
1698                                 WARN_ON(1);
1699                                 goto fail;
1700                         }
1701                 }
1702         }
1703 out:
1704         kfree(sorted);
1705         if (nr_extents) {
1706                 if (level == 0)
1707                         *nr_extents = nr_file_extents;
1708                 else
1709                         *nr_extents = nritems;
1710         }
1711         return 0;
1712 fail:
1713         kfree(sorted);
1714         WARN_ON(1);
1715         return ret;
1716 }
1717
1718 int btrfs_update_ref(struct btrfs_trans_handle *trans,
1719                      struct btrfs_root *root, struct extent_buffer *orig_buf,
1720                      struct extent_buffer *buf, int start_slot, int nr)
1721
1722 {
1723         u64 bytenr;
1724         u64 ref_root;
1725         u64 orig_root;
1726         u64 ref_generation;
1727         u64 orig_generation;
1728         struct btrfs_key key;
1729         struct btrfs_file_extent_item *fi;
1730         int i;
1731         int ret;
1732         int slot;
1733         int level;
1734
1735         BUG_ON(start_slot < 0);
1736         BUG_ON(start_slot + nr > btrfs_header_nritems(buf));
1737
1738         ref_root = btrfs_header_owner(buf);
1739         ref_generation = btrfs_header_generation(buf);
1740         orig_root = btrfs_header_owner(orig_buf);
1741         orig_generation = btrfs_header_generation(orig_buf);
1742         level = btrfs_header_level(buf);
1743
1744         if (!root->ref_cows) {
1745                 if (level == 0 &&
1746                     root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID)
1747                         return 0;
1748                 if (level != 0 &&
1749                     root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID)
1750                         return 0;
1751         }
1752
1753         for (i = 0, slot = start_slot; i < nr; i++, slot++) {
1754                 cond_resched();
1755                 if (level == 0) {
1756                         btrfs_item_key_to_cpu(buf, &key, slot);
1757                         if (btrfs_key_type(&key) != BTRFS_EXTENT_DATA_KEY)
1758                                 continue;
1759                         fi = btrfs_item_ptr(buf, slot,
1760                                             struct btrfs_file_extent_item);
1761                         if (btrfs_file_extent_type(buf, fi) ==
1762                             BTRFS_FILE_EXTENT_INLINE)
1763                                 continue;
1764                         bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
1765                         if (bytenr == 0)
1766                                 continue;
1767                         ret = __btrfs_update_extent_ref(trans, root, bytenr,
1768                                             orig_buf->start, buf->start,
1769                                             orig_root, ref_root,
1770                                             orig_generation, ref_generation,
1771                                             key.objectid);
1772                         if (ret)
1773                                 goto fail;
1774                 } else {
1775                         bytenr = btrfs_node_blockptr(buf, slot);
1776                         ret = __btrfs_update_extent_ref(trans, root, bytenr,
1777                                             orig_buf->start, buf->start,
1778                                             orig_root, ref_root,
1779                                             orig_generation, ref_generation,
1780                                             level - 1);
1781                         if (ret)
1782                                 goto fail;
1783                 }
1784         }
1785         return 0;
1786 fail:
1787         WARN_ON(1);
1788         return -1;
1789 }
1790
1791 static int write_one_cache_group(struct btrfs_trans_handle *trans,
1792                                  struct btrfs_root *root,
1793                                  struct btrfs_path *path,
1794                                  struct btrfs_block_group_cache *cache)
1795 {
1796         int ret;
1797         int pending_ret;
1798         struct btrfs_root *extent_root = root->fs_info->extent_root;
1799         unsigned long bi;
1800         struct extent_buffer *leaf;
1801
1802         ret = btrfs_search_slot(trans, extent_root, &cache->key, path, 0, 1);
1803         if (ret < 0)
1804                 goto fail;
1805         BUG_ON(ret);
1806
1807         leaf = path->nodes[0];
1808         bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
1809         write_extent_buffer(leaf, &cache->item, bi, sizeof(cache->item));
1810         btrfs_mark_buffer_dirty(leaf);
1811         btrfs_release_path(extent_root, path);
1812 fail:
1813         finish_current_insert(trans, extent_root, 0);
1814         pending_ret = del_pending_extents(trans, extent_root, 0);
1815         if (ret)
1816                 return ret;
1817         if (pending_ret)
1818                 return pending_ret;
1819         return 0;
1820
1821 }
1822
1823 int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans,
1824                                    struct btrfs_root *root)
1825 {
1826         struct btrfs_block_group_cache *cache, *entry;
1827         struct rb_node *n;
1828         int err = 0;
1829         int werr = 0;
1830         struct btrfs_path *path;
1831         u64 last = 0;
1832
1833         path = btrfs_alloc_path();
1834         if (!path)
1835                 return -ENOMEM;
1836
1837         while (1) {
1838                 cache = NULL;
1839                 spin_lock(&root->fs_info->block_group_cache_lock);
1840                 for (n = rb_first(&root->fs_info->block_group_cache_tree);
1841                      n; n = rb_next(n)) {
1842                         entry = rb_entry(n, struct btrfs_block_group_cache,
1843                                          cache_node);
1844                         if (entry->dirty) {
1845                                 cache = entry;
1846                                 break;
1847                         }
1848                 }
1849                 spin_unlock(&root->fs_info->block_group_cache_lock);
1850
1851                 if (!cache)
1852                         break;
1853
1854                 cache->dirty = 0;
1855                 last += cache->key.offset;
1856
1857                 err = write_one_cache_group(trans, root,
1858                                             path, cache);
1859                 /*
1860                  * if we fail to write the cache group, we want
1861                  * to keep it marked dirty in hopes that a later
1862                  * write will work
1863                  */
1864                 if (err) {
1865                         werr = err;
1866                         continue;
1867                 }
1868         }
1869         btrfs_free_path(path);
1870         return werr;
1871 }
1872
1873 int btrfs_extent_readonly(struct btrfs_root *root, u64 bytenr)
1874 {
1875         struct btrfs_block_group_cache *block_group;
1876         int readonly = 0;
1877
1878         block_group = btrfs_lookup_block_group(root->fs_info, bytenr);
1879         if (!block_group || block_group->ro)
1880                 readonly = 1;
1881         if (block_group)
1882                 put_block_group(block_group);
1883         return readonly;
1884 }
1885
1886 static int update_space_info(struct btrfs_fs_info *info, u64 flags,
1887                              u64 total_bytes, u64 bytes_used,
1888                              struct btrfs_space_info **space_info)
1889 {
1890         struct btrfs_space_info *found;
1891
1892         found = __find_space_info(info, flags);
1893         if (found) {
1894                 spin_lock(&found->lock);
1895                 found->total_bytes += total_bytes;
1896                 found->bytes_used += bytes_used;
1897                 found->full = 0;
1898                 spin_unlock(&found->lock);
1899                 *space_info = found;
1900                 return 0;
1901         }
1902         found = kzalloc(sizeof(*found), GFP_NOFS);
1903         if (!found)
1904                 return -ENOMEM;
1905
1906         list_add(&found->list, &info->space_info);
1907         INIT_LIST_HEAD(&found->block_groups);
1908         init_rwsem(&found->groups_sem);
1909         spin_lock_init(&found->lock);
1910         found->flags = flags;
1911         found->total_bytes = total_bytes;
1912         found->bytes_used = bytes_used;
1913         found->bytes_pinned = 0;
1914         found->bytes_reserved = 0;
1915         found->bytes_readonly = 0;
1916         found->bytes_delalloc = 0;
1917         found->full = 0;
1918         found->force_alloc = 0;
1919         *space_info = found;
1920         return 0;
1921 }
1922
1923 static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
1924 {
1925         u64 extra_flags = flags & (BTRFS_BLOCK_GROUP_RAID0 |
1926                                    BTRFS_BLOCK_GROUP_RAID1 |
1927                                    BTRFS_BLOCK_GROUP_RAID10 |
1928                                    BTRFS_BLOCK_GROUP_DUP);
1929         if (extra_flags) {
1930                 if (flags & BTRFS_BLOCK_GROUP_DATA)
1931                         fs_info->avail_data_alloc_bits |= extra_flags;
1932                 if (flags & BTRFS_BLOCK_GROUP_METADATA)
1933                         fs_info->avail_metadata_alloc_bits |= extra_flags;
1934                 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
1935                         fs_info->avail_system_alloc_bits |= extra_flags;
1936         }
1937 }
1938
1939 static void set_block_group_readonly(struct btrfs_block_group_cache *cache)
1940 {
1941         spin_lock(&cache->space_info->lock);
1942         spin_lock(&cache->lock);
1943         if (!cache->ro) {
1944                 cache->space_info->bytes_readonly += cache->key.offset -
1945                                         btrfs_block_group_used(&cache->item);
1946                 cache->ro = 1;
1947         }
1948         spin_unlock(&cache->lock);
1949         spin_unlock(&cache->space_info->lock);
1950 }
1951
1952 u64 btrfs_reduce_alloc_profile(struct btrfs_root *root, u64 flags)
1953 {
1954         u64 num_devices = root->fs_info->fs_devices->rw_devices;
1955
1956         if (num_devices == 1)
1957                 flags &= ~(BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID0);
1958         if (num_devices < 4)
1959                 flags &= ~BTRFS_BLOCK_GROUP_RAID10;
1960
1961         if ((flags & BTRFS_BLOCK_GROUP_DUP) &&
1962             (flags & (BTRFS_BLOCK_GROUP_RAID1 |
1963                       BTRFS_BLOCK_GROUP_RAID10))) {
1964                 flags &= ~BTRFS_BLOCK_GROUP_DUP;
1965         }
1966
1967         if ((flags & BTRFS_BLOCK_GROUP_RAID1) &&
1968             (flags & BTRFS_BLOCK_GROUP_RAID10)) {
1969                 flags &= ~BTRFS_BLOCK_GROUP_RAID1;
1970         }
1971
1972         if ((flags & BTRFS_BLOCK_GROUP_RAID0) &&
1973             ((flags & BTRFS_BLOCK_GROUP_RAID1) |
1974              (flags & BTRFS_BLOCK_GROUP_RAID10) |
1975              (flags & BTRFS_BLOCK_GROUP_DUP)))
1976                 flags &= ~BTRFS_BLOCK_GROUP_RAID0;
1977         return flags;
1978 }
1979
1980 static u64 btrfs_get_alloc_profile(struct btrfs_root *root, u64 data)
1981 {
1982         struct btrfs_fs_info *info = root->fs_info;
1983         u64 alloc_profile;
1984
1985         if (data) {
1986                 alloc_profile = info->avail_data_alloc_bits &
1987                         info->data_alloc_profile;
1988                 data = BTRFS_BLOCK_GROUP_DATA | alloc_profile;
1989         } else if (root == root->fs_info->chunk_root) {
1990                 alloc_profile = info->avail_system_alloc_bits &
1991                         info->system_alloc_profile;
1992                 data = BTRFS_BLOCK_GROUP_SYSTEM | alloc_profile;
1993         } else {
1994                 alloc_profile = info->avail_metadata_alloc_bits &
1995                         info->metadata_alloc_profile;
1996                 data = BTRFS_BLOCK_GROUP_METADATA | alloc_profile;
1997         }
1998
1999         return btrfs_reduce_alloc_profile(root, data);
2000 }
2001
2002 void btrfs_set_inode_space_info(struct btrfs_root *root, struct inode *inode)
2003 {
2004         u64 alloc_target;
2005
2006         alloc_target = btrfs_get_alloc_profile(root, 1);
2007         BTRFS_I(inode)->space_info = __find_space_info(root->fs_info,
2008                                                        alloc_target);
2009 }
2010
2011 /*
2012  * for now this just makes sure we have at least 5% of our metadata space free
2013  * for use.
2014  */
2015 int btrfs_check_metadata_free_space(struct btrfs_root *root)
2016 {
2017         struct btrfs_fs_info *info = root->fs_info;
2018         struct btrfs_space_info *meta_sinfo;
2019         u64 alloc_target, thresh;
2020         int committed = 0, ret;
2021
2022         /* get the space info for where the metadata will live */
2023         alloc_target = btrfs_get_alloc_profile(root, 0);
2024         meta_sinfo = __find_space_info(info, alloc_target);
2025
2026 again:
2027         spin_lock(&meta_sinfo->lock);
2028         if (!meta_sinfo->full)
2029                 thresh = meta_sinfo->total_bytes * 80;
2030         else
2031                 thresh = meta_sinfo->total_bytes * 95;
2032
2033         do_div(thresh, 100);
2034
2035         if (meta_sinfo->bytes_used + meta_sinfo->bytes_reserved +
2036             meta_sinfo->bytes_pinned + meta_sinfo->bytes_readonly > thresh) {
2037                 struct btrfs_trans_handle *trans;
2038                 if (!meta_sinfo->full) {
2039                         meta_sinfo->force_alloc = 1;
2040                         spin_unlock(&meta_sinfo->lock);
2041
2042                         trans = btrfs_start_transaction(root, 1);
2043                         if (!trans)
2044                                 return -ENOMEM;
2045
2046                         ret = do_chunk_alloc(trans, root->fs_info->extent_root,
2047                                              2 * 1024 * 1024, alloc_target, 0);
2048                         btrfs_end_transaction(trans, root);
2049                         goto again;
2050                 }
2051                 spin_unlock(&meta_sinfo->lock);
2052
2053                 if (!committed) {
2054                         committed = 1;
2055                         trans = btrfs_join_transaction(root, 1);
2056                         if (!trans)
2057                                 return -ENOMEM;
2058                         ret = btrfs_commit_transaction(trans, root);
2059                         if (ret)
2060                                 return ret;
2061                         goto again;
2062                 }
2063                 return -ENOSPC;
2064         }
2065         spin_unlock(&meta_sinfo->lock);
2066
2067         return 0;
2068 }
2069
2070 /*
2071  * This will check the space that the inode allocates from to make sure we have
2072  * enough space for bytes.
2073  */
2074 int btrfs_check_data_free_space(struct btrfs_root *root, struct inode *inode,
2075                                 u64 bytes)
2076 {
2077         struct btrfs_space_info *data_sinfo;
2078         int ret = 0, committed = 0;
2079
2080         /* make sure bytes are sectorsize aligned */
2081         bytes = (bytes + root->sectorsize - 1) & ~((u64)root->sectorsize - 1);
2082
2083         data_sinfo = BTRFS_I(inode)->space_info;
2084 again:
2085         /* make sure we have enough space to handle the data first */
2086         spin_lock(&data_sinfo->lock);
2087         if (data_sinfo->total_bytes - data_sinfo->bytes_used -
2088             data_sinfo->bytes_delalloc - data_sinfo->bytes_reserved -
2089             data_sinfo->bytes_pinned - data_sinfo->bytes_readonly -
2090             data_sinfo->bytes_may_use < bytes) {
2091                 struct btrfs_trans_handle *trans;
2092
2093                 /*
2094                  * if we don't have enough free bytes in this space then we need
2095                  * to alloc a new chunk.
2096                  */
2097                 if (!data_sinfo->full) {
2098                         u64 alloc_target;
2099
2100                         data_sinfo->force_alloc = 1;
2101                         spin_unlock(&data_sinfo->lock);
2102
2103                         alloc_target = btrfs_get_alloc_profile(root, 1);
2104                         trans = btrfs_start_transaction(root, 1);
2105                         if (!trans)
2106                                 return -ENOMEM;
2107
2108                         ret = do_chunk_alloc(trans, root->fs_info->extent_root,
2109                                              bytes + 2 * 1024 * 1024,
2110                                              alloc_target, 0);
2111                         btrfs_end_transaction(trans, root);
2112                         if (ret)
2113                                 return ret;
2114                         goto again;
2115                 }
2116                 spin_unlock(&data_sinfo->lock);
2117
2118                 /* commit the current transaction and try again */
2119                 if (!committed) {
2120                         committed = 1;
2121                         trans = btrfs_join_transaction(root, 1);
2122                         if (!trans)
2123                                 return -ENOMEM;
2124                         ret = btrfs_commit_transaction(trans, root);
2125                         if (ret)
2126                                 return ret;
2127                         goto again;
2128                 }
2129
2130                 printk(KERN_ERR "no space left, need %llu, %llu delalloc bytes"
2131                        ", %llu bytes_used, %llu bytes_reserved, "
2132                        "%llu bytes_pinned, %llu bytes_readonly, %llu may use"
2133                        "%llu total\n", bytes, data_sinfo->bytes_delalloc,
2134                        data_sinfo->bytes_used, data_sinfo->bytes_reserved,
2135                        data_sinfo->bytes_pinned, data_sinfo->bytes_readonly,
2136                        data_sinfo->bytes_may_use, data_sinfo->total_bytes);
2137                 return -ENOSPC;
2138         }
2139         data_sinfo->bytes_may_use += bytes;
2140         BTRFS_I(inode)->reserved_bytes += bytes;
2141         spin_unlock(&data_sinfo->lock);
2142
2143         return btrfs_check_metadata_free_space(root);
2144 }
2145
2146 /*
2147  * if there was an error for whatever reason after calling
2148  * btrfs_check_data_free_space, call this so we can cleanup the counters.
2149  */
2150 void btrfs_free_reserved_data_space(struct btrfs_root *root,
2151                                     struct inode *inode, u64 bytes)
2152 {
2153         struct btrfs_space_info *data_sinfo;
2154
2155         /* make sure bytes are sectorsize aligned */
2156         bytes = (bytes + root->sectorsize - 1) & ~((u64)root->sectorsize - 1);
2157
2158         data_sinfo = BTRFS_I(inode)->space_info;
2159         spin_lock(&data_sinfo->lock);
2160         data_sinfo->bytes_may_use -= bytes;
2161         BTRFS_I(inode)->reserved_bytes -= bytes;
2162         spin_unlock(&data_sinfo->lock);
2163 }
2164
2165 /* called when we are adding a delalloc extent to the inode's io_tree */
2166 void btrfs_delalloc_reserve_space(struct btrfs_root *root, struct inode *inode,
2167                                   u64 bytes)
2168 {
2169         struct btrfs_space_info *data_sinfo;
2170
2171         /* get the space info for where this inode will be storing its data */
2172         data_sinfo = BTRFS_I(inode)->space_info;
2173
2174         /* make sure we have enough space to handle the data first */
2175         spin_lock(&data_sinfo->lock);
2176         data_sinfo->bytes_delalloc += bytes;
2177
2178         /*
2179          * we are adding a delalloc extent without calling
2180          * btrfs_check_data_free_space first.  This happens on a weird
2181          * writepage condition, but shouldn't hurt our accounting
2182          */
2183         if (unlikely(bytes > BTRFS_I(inode)->reserved_bytes)) {
2184                 data_sinfo->bytes_may_use -= BTRFS_I(inode)->reserved_bytes;
2185                 BTRFS_I(inode)->reserved_bytes = 0;
2186         } else {
2187                 data_sinfo->bytes_may_use -= bytes;
2188                 BTRFS_I(inode)->reserved_bytes -= bytes;
2189         }
2190
2191         spin_unlock(&data_sinfo->lock);
2192 }
2193
2194 /* called when we are clearing an delalloc extent from the inode's io_tree */
2195 void btrfs_delalloc_free_space(struct btrfs_root *root, struct inode *inode,
2196                               u64 bytes)
2197 {
2198         struct btrfs_space_info *info;
2199
2200         info = BTRFS_I(inode)->space_info;
2201
2202         spin_lock(&info->lock);
2203         info->bytes_delalloc -= bytes;
2204         spin_unlock(&info->lock);
2205 }
2206
2207 static int do_chunk_alloc(struct btrfs_trans_handle *trans,
2208                           struct btrfs_root *extent_root, u64 alloc_bytes,
2209                           u64 flags, int force)
2210 {
2211         struct btrfs_space_info *space_info;
2212         u64 thresh;
2213         int ret = 0;
2214
2215         mutex_lock(&extent_root->fs_info->chunk_mutex);
2216
2217         flags = btrfs_reduce_alloc_profile(extent_root, flags);
2218
2219         space_info = __find_space_info(extent_root->fs_info, flags);
2220         if (!space_info) {
2221                 ret = update_space_info(extent_root->fs_info, flags,
2222                                         0, 0, &space_info);
2223                 BUG_ON(ret);
2224         }
2225         BUG_ON(!space_info);
2226
2227         spin_lock(&space_info->lock);
2228         if (space_info->force_alloc) {
2229                 force = 1;
2230                 space_info->force_alloc = 0;
2231         }
2232         if (space_info->full) {
2233                 spin_unlock(&space_info->lock);
2234                 goto out;
2235         }
2236
2237         thresh = space_info->total_bytes - space_info->bytes_readonly;
2238         thresh = div_factor(thresh, 6);
2239         if (!force &&
2240            (space_info->bytes_used + space_info->bytes_pinned +
2241             space_info->bytes_reserved + alloc_bytes) < thresh) {
2242                 spin_unlock(&space_info->lock);
2243                 goto out;
2244         }
2245         spin_unlock(&space_info->lock);
2246
2247         ret = btrfs_alloc_chunk(trans, extent_root, flags);
2248         if (ret)
2249                 space_info->full = 1;
2250 out:
2251         mutex_unlock(&extent_root->fs_info->chunk_mutex);
2252         return ret;
2253 }
2254
2255 static int update_block_group(struct btrfs_trans_handle *trans,
2256                               struct btrfs_root *root,
2257                               u64 bytenr, u64 num_bytes, int alloc,
2258                               int mark_free)
2259 {
2260         struct btrfs_block_group_cache *cache;
2261         struct btrfs_fs_info *info = root->fs_info;
2262         u64 total = num_bytes;
2263         u64 old_val;
2264         u64 byte_in_group;
2265
2266         while (total) {
2267                 cache = btrfs_lookup_block_group(info, bytenr);
2268                 if (!cache)
2269                         return -1;
2270                 byte_in_group = bytenr - cache->key.objectid;
2271                 WARN_ON(byte_in_group > cache->key.offset);
2272
2273                 spin_lock(&cache->space_info->lock);
2274                 spin_lock(&cache->lock);
2275                 cache->dirty = 1;
2276                 old_val = btrfs_block_group_used(&cache->item);
2277                 num_bytes = min(total, cache->key.offset - byte_in_group);
2278                 if (alloc) {
2279                         old_val += num_bytes;
2280                         cache->space_info->bytes_used += num_bytes;
2281                         if (cache->ro)
2282                                 cache->space_info->bytes_readonly -= num_bytes;
2283                         btrfs_set_block_group_used(&cache->item, old_val);
2284                         spin_unlock(&cache->lock);
2285                         spin_unlock(&cache->space_info->lock);
2286                 } else {
2287                         old_val -= num_bytes;
2288                         cache->space_info->bytes_used -= num_bytes;
2289                         if (cache->ro)
2290                                 cache->space_info->bytes_readonly += num_bytes;
2291                         btrfs_set_block_group_used(&cache->item, old_val);
2292                         spin_unlock(&cache->lock);
2293                         spin_unlock(&cache->space_info->lock);
2294                         if (mark_free) {
2295                                 int ret;
2296
2297                                 ret = btrfs_discard_extent(root, bytenr,
2298                                                            num_bytes);
2299                                 WARN_ON(ret);
2300
2301                                 ret = btrfs_add_free_space(cache, bytenr,
2302                                                            num_bytes);
2303                                 WARN_ON(ret);
2304                         }
2305                 }
2306                 put_block_group(cache);
2307                 total -= num_bytes;
2308                 bytenr += num_bytes;
2309         }
2310         return 0;
2311 }
2312
2313 static u64 first_logical_byte(struct btrfs_root *root, u64 search_start)
2314 {
2315         struct btrfs_block_group_cache *cache;
2316         u64 bytenr;
2317
2318         cache = btrfs_lookup_first_block_group(root->fs_info, search_start);
2319         if (!cache)
2320                 return 0;
2321
2322         bytenr = cache->key.objectid;
2323         put_block_group(cache);
2324
2325         return bytenr;
2326 }
2327
2328 int btrfs_update_pinned_extents(struct btrfs_root *root,
2329                                 u64 bytenr, u64 num, int pin)
2330 {
2331         u64 len;
2332         struct btrfs_block_group_cache *cache;
2333         struct btrfs_fs_info *fs_info = root->fs_info;
2334
2335         WARN_ON(!mutex_is_locked(&root->fs_info->pinned_mutex));
2336         if (pin) {
2337                 set_extent_dirty(&fs_info->pinned_extents,
2338                                 bytenr, bytenr + num - 1, GFP_NOFS);
2339         } else {
2340                 clear_extent_dirty(&fs_info->pinned_extents,
2341                                 bytenr, bytenr + num - 1, GFP_NOFS);
2342         }
2343         while (num > 0) {
2344                 cache = btrfs_lookup_block_group(fs_info, bytenr);
2345                 BUG_ON(!cache);
2346                 len = min(num, cache->key.offset -
2347                           (bytenr - cache->key.objectid));
2348                 if (pin) {
2349                         spin_lock(&cache->space_info->lock);
2350                         spin_lock(&cache->lock);
2351                         cache->pinned += len;
2352                         cache->space_info->bytes_pinned += len;
2353                         spin_unlock(&cache->lock);
2354                         spin_unlock(&cache->space_info->lock);
2355                         fs_info->total_pinned += len;
2356                 } else {
2357                         spin_lock(&cache->space_info->lock);
2358                         spin_lock(&cache->lock);
2359                         cache->pinned -= len;
2360                         cache->space_info->bytes_pinned -= len;
2361                         spin_unlock(&cache->lock);
2362                         spin_unlock(&cache->space_info->lock);
2363                         fs_info->total_pinned -= len;
2364                         if (cache->cached)
2365                                 btrfs_add_free_space(cache, bytenr, len);
2366                 }
2367                 put_block_group(cache);
2368                 bytenr += len;
2369                 num -= len;
2370         }
2371         return 0;
2372 }
2373
2374 static int update_reserved_extents(struct btrfs_root *root,
2375                                    u64 bytenr, u64 num, int reserve)
2376 {
2377         u64 len;
2378         struct btrfs_block_group_cache *cache;
2379         struct btrfs_fs_info *fs_info = root->fs_info;
2380
2381         while (num > 0) {
2382                 cache = btrfs_lookup_block_group(fs_info, bytenr);
2383                 BUG_ON(!cache);
2384                 len = min(num, cache->key.offset -
2385                           (bytenr - cache->key.objectid));
2386
2387                 spin_lock(&cache->space_info->lock);
2388                 spin_lock(&cache->lock);
2389                 if (reserve) {
2390                         cache->reserved += len;
2391                         cache->space_info->bytes_reserved += len;
2392                 } else {
2393                         cache->reserved -= len;
2394                         cache->space_info->bytes_reserved -= len;
2395                 }
2396                 spin_unlock(&cache->lock);
2397                 spin_unlock(&cache->space_info->lock);
2398                 put_block_group(cache);
2399                 bytenr += len;
2400                 num -= len;
2401         }
2402         return 0;
2403 }
2404
2405 int btrfs_copy_pinned(struct btrfs_root *root, struct extent_io_tree *copy)
2406 {
2407         u64 last = 0;
2408         u64 start;
2409         u64 end;
2410         struct extent_io_tree *pinned_extents = &root->fs_info->pinned_extents;
2411         int ret;
2412
2413         mutex_lock(&root->fs_info->pinned_mutex);
2414         while (1) {
2415                 ret = find_first_extent_bit(pinned_extents, last,
2416                                             &start, &end, EXTENT_DIRTY);
2417                 if (ret)
2418                         break;
2419                 set_extent_dirty(copy, start, end, GFP_NOFS);
2420                 last = end + 1;
2421         }
2422         mutex_unlock(&root->fs_info->pinned_mutex);
2423         return 0;
2424 }
2425
2426 int btrfs_finish_extent_commit(struct btrfs_trans_handle *trans,
2427                                struct btrfs_root *root,
2428                                struct extent_io_tree *unpin)
2429 {
2430         u64 start;
2431         u64 end;
2432         int ret;
2433
2434         mutex_lock(&root->fs_info->pinned_mutex);
2435         while (1) {
2436                 ret = find_first_extent_bit(unpin, 0, &start, &end,
2437                                             EXTENT_DIRTY);
2438                 if (ret)
2439                         break;
2440
2441                 ret = btrfs_discard_extent(root, start, end + 1 - start);
2442
2443                 btrfs_update_pinned_extents(root, start, end + 1 - start, 0);
2444                 clear_extent_dirty(unpin, start, end, GFP_NOFS);
2445
2446                 if (need_resched()) {
2447                         mutex_unlock(&root->fs_info->pinned_mutex);
2448                         cond_resched();
2449                         mutex_lock(&root->fs_info->pinned_mutex);
2450                 }
2451         }
2452         mutex_unlock(&root->fs_info->pinned_mutex);
2453         return ret;
2454 }
2455
2456 static int finish_current_insert(struct btrfs_trans_handle *trans,
2457                                  struct btrfs_root *extent_root, int all)
2458 {
2459         u64 start;
2460         u64 end;
2461         u64 priv;
2462         u64 search = 0;
2463         struct btrfs_fs_info *info = extent_root->fs_info;
2464         struct btrfs_path *path;
2465         struct pending_extent_op *extent_op, *tmp;
2466         struct list_head insert_list, update_list;
2467         int ret;
2468         int num_inserts = 0, max_inserts, restart = 0;
2469
2470         path = btrfs_alloc_path();
2471         INIT_LIST_HEAD(&insert_list);
2472         INIT_LIST_HEAD(&update_list);
2473
2474         max_inserts = extent_root->leafsize /
2475                 (2 * sizeof(struct btrfs_key) + 2 * sizeof(struct btrfs_item) +
2476                  sizeof(struct btrfs_extent_ref) +
2477                  sizeof(struct btrfs_extent_item));
2478 again:
2479         mutex_lock(&info->extent_ins_mutex);
2480         while (1) {
2481                 ret = find_first_extent_bit(&info->extent_ins, search, &start,
2482                                             &end, EXTENT_WRITEBACK);
2483                 if (ret) {
2484                         if (restart && !num_inserts &&
2485                             list_empty(&update_list)) {
2486                                 restart = 0;
2487                                 search = 0;
2488                                 continue;
2489                         }
2490                         break;
2491                 }
2492
2493                 ret = try_lock_extent(&info->extent_ins, start, end, GFP_NOFS);
2494                 if (!ret) {
2495                         if (all)
2496                                 restart = 1;
2497                         search = end + 1;
2498                         if (need_resched()) {
2499                                 mutex_unlock(&info->extent_ins_mutex);
2500                                 cond_resched();
2501                                 mutex_lock(&info->extent_ins_mutex);
2502                         }
2503                         continue;
2504                 }
2505
2506                 ret = get_state_private(&info->extent_ins, start, &priv);
2507                 BUG_ON(ret);
2508                 extent_op = (struct pending_extent_op *)(unsigned long) priv;
2509
2510                 if (extent_op->type == PENDING_EXTENT_INSERT) {
2511                         num_inserts++;
2512                         list_add_tail(&extent_op->list, &insert_list);
2513                         search = end + 1;
2514                         if (num_inserts == max_inserts) {
2515                                 restart = 1;
2516                                 break;
2517                         }
2518                 } else if (extent_op->type == PENDING_BACKREF_UPDATE) {
2519                         list_add_tail(&extent_op->list, &update_list);
2520                         search = end + 1;
2521                 } else {
2522                         BUG();
2523                 }
2524         }
2525
2526         /*
2527          * process the update list, clear the writeback bit for it, and if
2528          * somebody marked this thing for deletion then just unlock it and be
2529          * done, the free_extents will handle it
2530          */
2531         list_for_each_entry_safe(extent_op, tmp, &update_list, list) {
2532                 clear_extent_bits(&info->extent_ins, extent_op->bytenr,
2533                                   extent_op->bytenr + extent_op->num_bytes - 1,
2534                                   EXTENT_WRITEBACK, GFP_NOFS);
2535                 if (extent_op->del) {
2536                         list_del_init(&extent_op->list);
2537                         unlock_extent(&info->extent_ins, extent_op->bytenr,
2538                                       extent_op->bytenr + extent_op->num_bytes
2539                                       - 1, GFP_NOFS);
2540                         kfree(extent_op);
2541                 }
2542         }
2543         mutex_unlock(&info->extent_ins_mutex);
2544
2545         /*
2546          * still have things left on the update list, go ahead an update
2547          * everything
2548          */
2549         if (!list_empty(&update_list)) {
2550                 ret = update_backrefs(trans, extent_root, path, &update_list);
2551                 BUG_ON(ret);
2552
2553                 /* we may have COW'ed new blocks, so lets start over */
2554                 if (all)
2555                         restart = 1;
2556         }
2557
2558         /*
2559          * if no inserts need to be done, but we skipped some extents and we
2560          * need to make sure everything is cleaned then reset everything and
2561          * go back to the beginning
2562          */
2563         if (!num_inserts && restart) {
2564                 search = 0;
2565                 restart = 0;
2566                 INIT_LIST_HEAD(&update_list);
2567                 INIT_LIST_HEAD(&insert_list);
2568                 goto again;
2569         } else if (!num_inserts) {
2570                 goto out;
2571         }
2572
2573         /*
2574          * process the insert extents list.  Again if we are deleting this
2575          * extent, then just unlock it, pin down the bytes if need be, and be
2576          * done with it.  Saves us from having to actually insert the extent
2577          * into the tree and then subsequently come along and delete it
2578          */
2579         mutex_lock(&info->extent_ins_mutex);
2580         list_for_each_entry_safe(extent_op, tmp, &insert_list, list) {
2581                 clear_extent_bits(&info->extent_ins, extent_op->bytenr,
2582                                   extent_op->bytenr + extent_op->num_bytes - 1,
2583                                   EXTENT_WRITEBACK, GFP_NOFS);
2584                 if (extent_op->del) {
2585                         u64 used;
2586                         list_del_init(&extent_op->list);
2587                         unlock_extent(&info->extent_ins, extent_op->bytenr,
2588                                       extent_op->bytenr + extent_op->num_bytes
2589                                       - 1, GFP_NOFS);
2590
2591                         mutex_lock(&extent_root->fs_info->pinned_mutex);
2592                         ret = pin_down_bytes(trans, extent_root,
2593                                              extent_op->bytenr,
2594                                              extent_op->num_bytes, 0);
2595                         mutex_unlock(&extent_root->fs_info->pinned_mutex);
2596
2597                         spin_lock(&info->delalloc_lock);
2598                         used = btrfs_super_bytes_used(&info->super_copy);
2599                         btrfs_set_super_bytes_used(&info->super_copy,
2600                                         used - extent_op->num_bytes);
2601                         used = btrfs_root_used(&extent_root->root_item);
2602                         btrfs_set_root_used(&extent_root->root_item,
2603                                         used - extent_op->num_bytes);
2604                         spin_unlock(&info->delalloc_lock);
2605
2606                         ret = update_block_group(trans, extent_root,
2607                                                  extent_op->bytenr,
2608                                                  extent_op->num_bytes,
2609                                                  0, ret > 0);
2610                         BUG_ON(ret);
2611                         kfree(extent_op);
2612                         num_inserts--;
2613                 }
2614         }
2615         mutex_unlock(&info->extent_ins_mutex);
2616
2617         ret = insert_extents(trans, extent_root, path, &insert_list,
2618                              num_inserts);
2619         BUG_ON(ret);
2620
2621         /*
2622          * if restart is set for whatever reason we need to go back and start
2623          * searching through the pending list again.
2624          *
2625          * We just inserted some extents, which could have resulted in new
2626          * blocks being allocated, which would result in new blocks needing
2627          * updates, so if all is set we _must_ restart to get the updated
2628          * blocks.
2629          */
2630         if (restart || all) {
2631                 INIT_LIST_HEAD(&insert_list);
2632                 INIT_LIST_HEAD(&update_list);
2633                 search = 0;
2634                 restart = 0;
2635                 num_inserts = 0;
2636                 goto again;
2637         }
2638 out:
2639         btrfs_free_path(path);
2640         return 0;
2641 }
2642
2643 static int pin_down_bytes(struct btrfs_trans_handle *trans,
2644                           struct btrfs_root *root,
2645                           u64 bytenr, u64 num_bytes, int is_data)
2646 {
2647         int err = 0;
2648         struct extent_buffer *buf;
2649
2650         if (is_data)
2651                 goto pinit;
2652
2653         buf = btrfs_find_tree_block(root, bytenr, num_bytes);
2654         if (!buf)
2655                 goto pinit;
2656
2657         /* we can reuse a block if it hasn't been written
2658          * and it is from this transaction.  We can't
2659          * reuse anything from the tree log root because
2660          * it has tiny sub-transactions.
2661          */
2662         if (btrfs_buffer_uptodate(buf, 0) &&
2663             btrfs_try_tree_lock(buf)) {
2664                 u64 header_owner = btrfs_header_owner(buf);
2665                 u64 header_transid = btrfs_header_generation(buf);
2666                 if (header_owner != BTRFS_TREE_LOG_OBJECTID &&
2667                     header_owner != BTRFS_TREE_RELOC_OBJECTID &&
2668                     header_transid == trans->transid &&
2669                     !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN)) {
2670                         clean_tree_block(NULL, root, buf);
2671                         btrfs_tree_unlock(buf);
2672                         free_extent_buffer(buf);
2673                         return 1;
2674                 }
2675                 btrfs_tree_unlock(buf);
2676         }
2677         free_extent_buffer(buf);
2678 pinit:
2679         btrfs_update_pinned_extents(root, bytenr, num_bytes, 1);
2680
2681         BUG_ON(err < 0);
2682         return 0;
2683 }
2684
2685 /*
2686  * remove an extent from the root, returns 0 on success
2687  */
2688 static int __free_extent(struct btrfs_trans_handle *trans,
2689                          struct btrfs_root *root,
2690                          u64 bytenr, u64 num_bytes, u64 parent,
2691                          u64 root_objectid, u64 ref_generation,
2692                          u64 owner_objectid, int pin, int mark_free)
2693 {
2694         struct btrfs_path *path;
2695         struct btrfs_key key;
2696         struct btrfs_fs_info *info = root->fs_info;
2697         struct btrfs_root *extent_root = info->extent_root;
2698         struct extent_buffer *leaf;
2699         int ret;
2700         int extent_slot = 0;
2701         int found_extent = 0;
2702         int num_to_del = 1;
2703         struct btrfs_extent_item *ei;
2704         u32 refs;
2705
2706         key.objectid = bytenr;
2707         btrfs_set_key_type(&key, BTRFS_EXTENT_ITEM_KEY);
2708         key.offset = num_bytes;
2709         path = btrfs_alloc_path();
2710         if (!path)
2711                 return -ENOMEM;
2712
2713         path->reada = 1;
2714         ret = lookup_extent_backref(trans, extent_root, path,
2715                                     bytenr, parent, root_objectid,
2716                                     ref_generation, owner_objectid, 1);
2717         if (ret == 0) {
2718                 struct btrfs_key found_key;
2719                 extent_slot = path->slots[0];
2720                 while (extent_slot > 0) {
2721                         extent_slot--;
2722                         btrfs_item_key_to_cpu(path->nodes[0], &found_key,
2723                                               extent_slot);
2724                         if (found_key.objectid != bytenr)
2725                                 break;
2726                         if (found_key.type == BTRFS_EXTENT_ITEM_KEY &&
2727                             found_key.offset == num_bytes) {
2728                                 found_extent = 1;
2729                                 break;
2730                         }
2731                         if (path->slots[0] - extent_slot > 5)
2732                                 break;
2733                 }
2734                 if (!found_extent) {
2735                         ret = remove_extent_backref(trans, extent_root, path);
2736                         BUG_ON(ret);
2737                         btrfs_release_path(extent_root, path);
2738                         ret = btrfs_search_slot(trans, extent_root,
2739                                                 &key, path, -1, 1);
2740                         if (ret) {
2741                                 printk(KERN_ERR "umm, got %d back from search"
2742                                        ", was looking for %llu\n", ret,
2743                                        (unsigned long long)bytenr);
2744                                 btrfs_print_leaf(extent_root, path->nodes[0]);
2745                         }
2746                         BUG_ON(ret);
2747                         extent_slot = path->slots[0];
2748                 }
2749         } else {
2750                 btrfs_print_leaf(extent_root, path->nodes[0]);
2751                 WARN_ON(1);
2752                 printk(KERN_ERR "btrfs unable to find ref byte nr %llu "
2753                        "root %llu gen %llu owner %llu\n",
2754                        (unsigned long long)bytenr,
2755                        (unsigned long long)root_objectid,
2756                        (unsigned long long)ref_generation,
2757                        (unsigned long long)owner_objectid);
2758         }
2759
2760         leaf = path->nodes[0];
2761         ei = btrfs_item_ptr(leaf, extent_slot,
2762                             struct btrfs_extent_item);
2763         refs = btrfs_extent_refs(leaf, ei);
2764         BUG_ON(refs == 0);
2765         refs -= 1;
2766         btrfs_set_extent_refs(leaf, ei, refs);
2767
2768         btrfs_mark_buffer_dirty(leaf);
2769
2770         if (refs == 0 && found_extent && path->slots[0] == extent_slot + 1) {
2771                 struct btrfs_extent_ref *ref;
2772                 ref = btrfs_item_ptr(leaf, path->slots[0],
2773                                      struct btrfs_extent_ref);
2774                 BUG_ON(btrfs_ref_num_refs(leaf, ref) != 1);
2775                 /* if the back ref and the extent are next to each other
2776                  * they get deleted below in one shot
2777                  */
2778                 path->slots[0] = extent_slot;
2779                 num_to_del = 2;
2780         } else if (found_extent) {
2781                 /* otherwise delete the extent back ref */
2782                 ret = remove_extent_backref(trans, extent_root, path);
2783                 BUG_ON(ret);
2784                 /* if refs are 0, we need to setup the path for deletion */
2785                 if (refs == 0) {
2786                         btrfs_release_path(extent_root, path);
2787                         ret = btrfs_search_slot(trans, extent_root, &key, path,
2788                                                 -1, 1);
2789                         BUG_ON(ret);
2790                 }
2791         }
2792
2793         if (refs == 0) {
2794                 u64 super_used;
2795                 u64 root_used;
2796
2797                 if (pin) {
2798                         mutex_lock(&root->fs_info->pinned_mutex);
2799                         ret = pin_down_bytes(trans, root, bytenr, num_bytes,
2800                                 owner_objectid >= BTRFS_FIRST_FREE_OBJECTID);
2801                         mutex_unlock(&root->fs_info->pinned_mutex);
2802                         if (ret > 0)
2803                                 mark_free = 1;
2804                         BUG_ON(ret < 0);
2805                 }
2806                 /* block accounting for super block */
2807                 spin_lock(&info->delalloc_lock);
2808                 super_used = btrfs_super_bytes_used(&info->super_copy);
2809                 btrfs_set_super_bytes_used(&info->super_copy,
2810                                            super_used - num_bytes);
2811
2812                 /* block accounting for root item */
2813                 root_used = btrfs_root_used(&root->root_item);
2814                 btrfs_set_root_used(&root->root_item,
2815                                            root_used - num_bytes);
2816                 spin_unlock(&info->delalloc_lock);
2817                 ret = btrfs_del_items(trans, extent_root, path, path->slots[0],
2818                                       num_to_del);
2819                 BUG_ON(ret);
2820                 btrfs_release_path(extent_root, path);
2821
2822                 if (owner_objectid >= BTRFS_FIRST_FREE_OBJECTID) {
2823                         ret = btrfs_del_csums(trans, root, bytenr, num_bytes);
2824                         BUG_ON(ret);
2825                 }
2826
2827                 ret = update_block_group(trans, root, bytenr, num_bytes, 0,
2828                                          mark_free);
2829                 BUG_ON(ret);
2830         }
2831         btrfs_free_path(path);
2832         finish_current_insert(trans, extent_root, 0);
2833         return ret;
2834 }
2835
2836 /*
2837  * find all the blocks marked as pending in the radix tree and remove
2838  * them from the extent map
2839  */
2840 static int del_pending_extents(struct btrfs_trans_handle *trans,
2841                                struct btrfs_root *extent_root, int all)
2842 {
2843         int ret;
2844         int err = 0;
2845         u64 start;
2846         u64 end;
2847         u64 priv;
2848         u64 search = 0;
2849         int nr = 0, skipped = 0;
2850         struct extent_io_tree *pending_del;
2851         struct extent_io_tree *extent_ins;
2852         struct pending_extent_op *extent_op;
2853         struct btrfs_fs_info *info = extent_root->fs_info;
2854         struct list_head delete_list;
2855
2856         INIT_LIST_HEAD(&delete_list);
2857         extent_ins = &extent_root->fs_info->extent_ins;
2858         pending_del = &extent_root->fs_info->pending_del;
2859
2860 again:
2861         mutex_lock(&info->extent_ins_mutex);
2862         while (1) {
2863                 ret = find_first_extent_bit(pending_del, search, &start, &end,
2864                                             EXTENT_WRITEBACK);
2865                 if (ret) {
2866                         if (all && skipped && !nr) {
2867                                 search = 0;
2868                                 skipped = 0;
2869                                 continue;
2870                         }
2871                         mutex_unlock(&info->extent_ins_mutex);
2872                         break;
2873                 }
2874
2875                 ret = try_lock_extent(extent_ins, start, end, GFP_NOFS);
2876                 if (!ret) {
2877                         search = end+1;
2878                         skipped = 1;
2879
2880                         if (need_resched()) {
2881                                 mutex_unlock(&info->extent_ins_mutex);
2882                                 cond_resched();
2883                                 mutex_lock(&info->extent_ins_mutex);
2884                         }
2885
2886                         continue;
2887                 }
2888                 BUG_ON(ret < 0);
2889
2890                 ret = get_state_private(pending_del, start, &priv);
2891                 BUG_ON(ret);
2892                 extent_op = (struct pending_extent_op *)(unsigned long)priv;
2893
2894                 clear_extent_bits(pending_del, start, end, EXTENT_WRITEBACK,
2895                                   GFP_NOFS);
2896                 if (!test_range_bit(extent_ins, start, end,
2897                                     EXTENT_WRITEBACK, 0)) {
2898                         list_add_tail(&extent_op->list, &delete_list);
2899                         nr++;
2900                 } else {
2901                         kfree(extent_op);
2902
2903                         ret = get_state_private(&info->extent_ins, start,
2904                                                 &priv);
2905                         BUG_ON(ret);
2906                         extent_op = (struct pending_extent_op *)
2907                                                 (unsigned long)priv;
2908
2909                         clear_extent_bits(&info->extent_ins, start, end,
2910                                           EXTENT_WRITEBACK, GFP_NOFS);
2911
2912                         if (extent_op->type == PENDING_BACKREF_UPDATE) {
2913                                 list_add_tail(&extent_op->list, &delete_list);
2914                                 search = end + 1;
2915                                 nr++;
2916                                 continue;
2917                         }
2918
2919                         mutex_lock(&extent_root->fs_info->pinned_mutex);
2920                         ret = pin_down_bytes(trans, extent_root, start,
2921                                              end + 1 - start, 0);
2922                         mutex_unlock(&extent_root->fs_info->pinned_mutex);
2923
2924                         ret = update_block_group(trans, extent_root, start,
2925                                                 end + 1 - start, 0, ret > 0);
2926
2927                         unlock_extent(extent_ins, start, end, GFP_NOFS);
2928                         BUG_ON(ret);
2929                         kfree(extent_op);
2930                 }
2931                 if (ret)
2932                         err = ret;
2933
2934                 search = end + 1;
2935
2936                 if (need_resched()) {
2937                         mutex_unlock(&info->extent_ins_mutex);
2938                         cond_resched();
2939                         mutex_lock(&info->extent_ins_mutex);
2940                 }
2941         }
2942
2943         if (nr) {
2944                 ret = free_extents(trans, extent_root, &delete_list);
2945                 BUG_ON(ret);
2946         }
2947
2948         if (all && skipped) {
2949                 INIT_LIST_HEAD(&delete_list);
2950                 search = 0;
2951                 nr = 0;
2952                 goto again;
2953         }
2954
2955         if (!err)
2956                 finish_current_insert(trans, extent_root, 0);
2957         return err;
2958 }
2959
2960 /*
2961  * remove an extent from the root, returns 0 on success
2962  */
2963 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
2964                                struct btrfs_root *root,
2965                                u64 bytenr, u64 num_bytes, u64 parent,
2966                                u64 root_objectid, u64 ref_generation,
2967                                u64 owner_objectid, int pin)
2968 {
2969         struct btrfs_root *extent_root = root->fs_info->extent_root;
2970         int pending_ret;
2971         int ret;
2972
2973         WARN_ON(num_bytes < root->sectorsize);
2974         if (root == extent_root) {
2975                 struct pending_extent_op *extent_op = NULL;
2976
2977                 mutex_lock(&root->fs_info->extent_ins_mutex);
2978                 if (test_range_bit(&root->fs_info->extent_ins, bytenr,
2979                                 bytenr + num_bytes - 1, EXTENT_WRITEBACK, 0)) {
2980                         u64 priv;
2981                         ret = get_state_private(&root->fs_info->extent_ins,
2982                                                 bytenr, &priv);
2983                         BUG_ON(ret);
2984                         extent_op = (struct pending_extent_op *)
2985                                                 (unsigned long)priv;
2986
2987                         extent_op->del = 1;
2988                         if (extent_op->type == PENDING_EXTENT_INSERT) {
2989                                 mutex_unlock(&root->fs_info->extent_ins_mutex);
2990                                 return 0;
2991                         }
2992                 }
2993
2994                 if (extent_op) {
2995                         ref_generation = extent_op->orig_generation;
2996                         parent = extent_op->orig_parent;
2997                 }
2998
2999                 extent_op = kmalloc(sizeof(*extent_op), GFP_NOFS);
3000                 BUG_ON(!extent_op);
3001
3002                 extent_op->type = PENDING_EXTENT_DELETE;
3003                 extent_op->bytenr = bytenr;
3004                 extent_op->num_bytes = num_bytes;
3005                 extent_op->parent = parent;
3006                 extent_op->orig_parent = parent;
3007                 extent_op->generation = ref_generation;
3008                 extent_op->orig_generation = ref_generation;
3009                 extent_op->level = (int)owner_objectid;
3010                 INIT_LIST_HEAD(&extent_op->list);
3011                 extent_op->del = 0;
3012
3013                 set_extent_bits(&root->fs_info->pending_del,
3014                                 bytenr, bytenr + num_bytes - 1,
3015                                 EXTENT_WRITEBACK, GFP_NOFS);
3016                 set_state_private(&root->fs_info->pending_del,
3017                                   bytenr, (unsigned long)extent_op);
3018                 mutex_unlock(&root->fs_info->extent_ins_mutex);
3019                 return 0;
3020         }
3021         /* if metadata always pin */
3022         if (owner_objectid < BTRFS_FIRST_FREE_OBJECTID) {
3023                 if (root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID) {
3024                         mutex_lock(&root->fs_info->pinned_mutex);
3025                         btrfs_update_pinned_extents(root, bytenr, num_bytes, 1);
3026                         mutex_unlock(&root->fs_info->pinned_mutex);
3027                         update_reserved_extents(root, bytenr, num_bytes, 0);
3028                         return 0;
3029                 }
3030                 pin = 1;
3031         }
3032
3033         /* if data pin when any transaction has committed this */
3034         if (ref_generation != trans->tra