[PARISC] slub: fix panic with DISCONTIGMEM
[pandora-kernel.git] / fs / btrfs / free-space-cache.c
1 /*
2  * Copyright (C) 2008 Red Hat.  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
19 #include <linux/pagemap.h>
20 #include <linux/sched.h>
21 #include <linux/slab.h>
22 #include <linux/math64.h>
23 #include "ctree.h"
24 #include "free-space-cache.h"
25 #include "transaction.h"
26 #include "disk-io.h"
27 #include "extent_io.h"
28
29 #define BITS_PER_BITMAP         (PAGE_CACHE_SIZE * 8)
30 #define MAX_CACHE_BYTES_PER_GIG (32 * 1024)
31
32 static void recalculate_thresholds(struct btrfs_block_group_cache
33                                    *block_group);
34 static int link_free_space(struct btrfs_block_group_cache *block_group,
35                            struct btrfs_free_space *info);
36
37 struct inode *lookup_free_space_inode(struct btrfs_root *root,
38                                       struct btrfs_block_group_cache
39                                       *block_group, struct btrfs_path *path)
40 {
41         struct btrfs_key key;
42         struct btrfs_key location;
43         struct btrfs_disk_key disk_key;
44         struct btrfs_free_space_header *header;
45         struct extent_buffer *leaf;
46         struct inode *inode = NULL;
47         int ret;
48
49         spin_lock(&block_group->lock);
50         if (block_group->inode)
51                 inode = igrab(block_group->inode);
52         spin_unlock(&block_group->lock);
53         if (inode)
54                 return inode;
55
56         key.objectid = BTRFS_FREE_SPACE_OBJECTID;
57         key.offset = block_group->key.objectid;
58         key.type = 0;
59
60         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
61         if (ret < 0)
62                 return ERR_PTR(ret);
63         if (ret > 0) {
64                 btrfs_release_path(root, path);
65                 return ERR_PTR(-ENOENT);
66         }
67
68         leaf = path->nodes[0];
69         header = btrfs_item_ptr(leaf, path->slots[0],
70                                 struct btrfs_free_space_header);
71         btrfs_free_space_key(leaf, header, &disk_key);
72         btrfs_disk_key_to_cpu(&location, &disk_key);
73         btrfs_release_path(root, path);
74
75         inode = btrfs_iget(root->fs_info->sb, &location, root, NULL);
76         if (!inode)
77                 return ERR_PTR(-ENOENT);
78         if (IS_ERR(inode))
79                 return inode;
80         if (is_bad_inode(inode)) {
81                 iput(inode);
82                 return ERR_PTR(-ENOENT);
83         }
84
85         inode->i_mapping->flags &= ~__GFP_FS;
86
87         spin_lock(&block_group->lock);
88         if (!root->fs_info->closing) {
89                 block_group->inode = igrab(inode);
90                 block_group->iref = 1;
91         }
92         spin_unlock(&block_group->lock);
93
94         return inode;
95 }
96
97 int create_free_space_inode(struct btrfs_root *root,
98                             struct btrfs_trans_handle *trans,
99                             struct btrfs_block_group_cache *block_group,
100                             struct btrfs_path *path)
101 {
102         struct btrfs_key key;
103         struct btrfs_disk_key disk_key;
104         struct btrfs_free_space_header *header;
105         struct btrfs_inode_item *inode_item;
106         struct extent_buffer *leaf;
107         u64 objectid;
108         int ret;
109
110         ret = btrfs_find_free_objectid(trans, root, 0, &objectid);
111         if (ret < 0)
112                 return ret;
113
114         ret = btrfs_insert_empty_inode(trans, root, path, objectid);
115         if (ret)
116                 return ret;
117
118         leaf = path->nodes[0];
119         inode_item = btrfs_item_ptr(leaf, path->slots[0],
120                                     struct btrfs_inode_item);
121         btrfs_item_key(leaf, &disk_key, path->slots[0]);
122         memset_extent_buffer(leaf, 0, (unsigned long)inode_item,
123                              sizeof(*inode_item));
124         btrfs_set_inode_generation(leaf, inode_item, trans->transid);
125         btrfs_set_inode_size(leaf, inode_item, 0);
126         btrfs_set_inode_nbytes(leaf, inode_item, 0);
127         btrfs_set_inode_uid(leaf, inode_item, 0);
128         btrfs_set_inode_gid(leaf, inode_item, 0);
129         btrfs_set_inode_mode(leaf, inode_item, S_IFREG | 0600);
130         btrfs_set_inode_flags(leaf, inode_item, BTRFS_INODE_NOCOMPRESS |
131                               BTRFS_INODE_PREALLOC | BTRFS_INODE_NODATASUM);
132         btrfs_set_inode_nlink(leaf, inode_item, 1);
133         btrfs_set_inode_transid(leaf, inode_item, trans->transid);
134         btrfs_set_inode_block_group(leaf, inode_item,
135                                     block_group->key.objectid);
136         btrfs_mark_buffer_dirty(leaf);
137         btrfs_release_path(root, path);
138
139         key.objectid = BTRFS_FREE_SPACE_OBJECTID;
140         key.offset = block_group->key.objectid;
141         key.type = 0;
142
143         ret = btrfs_insert_empty_item(trans, root, path, &key,
144                                       sizeof(struct btrfs_free_space_header));
145         if (ret < 0) {
146                 btrfs_release_path(root, path);
147                 return ret;
148         }
149         leaf = path->nodes[0];
150         header = btrfs_item_ptr(leaf, path->slots[0],
151                                 struct btrfs_free_space_header);
152         memset_extent_buffer(leaf, 0, (unsigned long)header, sizeof(*header));
153         btrfs_set_free_space_key(leaf, header, &disk_key);
154         btrfs_mark_buffer_dirty(leaf);
155         btrfs_release_path(root, path);
156
157         return 0;
158 }
159
160 int btrfs_truncate_free_space_cache(struct btrfs_root *root,
161                                     struct btrfs_trans_handle *trans,
162                                     struct btrfs_path *path,
163                                     struct inode *inode)
164 {
165         loff_t oldsize;
166         int ret = 0;
167
168         trans->block_rsv = root->orphan_block_rsv;
169         ret = btrfs_block_rsv_check(trans, root,
170                                     root->orphan_block_rsv,
171                                     0, 5);
172         if (ret)
173                 return ret;
174
175         oldsize = i_size_read(inode);
176         btrfs_i_size_write(inode, 0);
177         truncate_pagecache(inode, oldsize, 0);
178
179         /*
180          * We don't need an orphan item because truncating the free space cache
181          * will never be split across transactions.
182          */
183         ret = btrfs_truncate_inode_items(trans, root, inode,
184                                          0, BTRFS_EXTENT_DATA_KEY);
185         if (ret) {
186                 WARN_ON(1);
187                 return ret;
188         }
189
190         return btrfs_update_inode(trans, root, inode);
191 }
192
193 static int readahead_cache(struct inode *inode)
194 {
195         struct file_ra_state *ra;
196         unsigned long last_index;
197
198         ra = kzalloc(sizeof(*ra), GFP_NOFS);
199         if (!ra)
200                 return -ENOMEM;
201
202         file_ra_state_init(ra, inode->i_mapping);
203         last_index = (i_size_read(inode) - 1) >> PAGE_CACHE_SHIFT;
204
205         page_cache_sync_readahead(inode->i_mapping, ra, NULL, 0, last_index);
206
207         kfree(ra);
208
209         return 0;
210 }
211
212 int load_free_space_cache(struct btrfs_fs_info *fs_info,
213                           struct btrfs_block_group_cache *block_group)
214 {
215         struct btrfs_root *root = fs_info->tree_root;
216         struct inode *inode;
217         struct btrfs_free_space_header *header;
218         struct extent_buffer *leaf;
219         struct page *page;
220         struct btrfs_path *path;
221         u32 *checksums = NULL, *crc;
222         char *disk_crcs = NULL;
223         struct btrfs_key key;
224         struct list_head bitmaps;
225         u64 num_entries;
226         u64 num_bitmaps;
227         u64 generation;
228         u64 used = btrfs_block_group_used(&block_group->item);
229         u32 cur_crc = ~(u32)0;
230         pgoff_t index = 0;
231         unsigned long first_page_offset;
232         int num_checksums;
233         int ret = 0;
234
235         /*
236          * If we're unmounting then just return, since this does a search on the
237          * normal root and not the commit root and we could deadlock.
238          */
239         smp_mb();
240         if (fs_info->closing)
241                 return 0;
242
243         /*
244          * If this block group has been marked to be cleared for one reason or
245          * another then we can't trust the on disk cache, so just return.
246          */
247         spin_lock(&block_group->lock);
248         if (block_group->disk_cache_state != BTRFS_DC_WRITTEN) {
249                 spin_unlock(&block_group->lock);
250                 return 0;
251         }
252         spin_unlock(&block_group->lock);
253
254         INIT_LIST_HEAD(&bitmaps);
255
256         path = btrfs_alloc_path();
257         if (!path)
258                 return 0;
259
260         inode = lookup_free_space_inode(root, block_group, path);
261         if (IS_ERR(inode)) {
262                 btrfs_free_path(path);
263                 return 0;
264         }
265
266         /* Nothing in the space cache, goodbye */
267         if (!i_size_read(inode)) {
268                 btrfs_free_path(path);
269                 goto out;
270         }
271
272         key.objectid = BTRFS_FREE_SPACE_OBJECTID;
273         key.offset = block_group->key.objectid;
274         key.type = 0;
275
276         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
277         if (ret) {
278                 btrfs_free_path(path);
279                 goto out;
280         }
281
282         leaf = path->nodes[0];
283         header = btrfs_item_ptr(leaf, path->slots[0],
284                                 struct btrfs_free_space_header);
285         num_entries = btrfs_free_space_entries(leaf, header);
286         num_bitmaps = btrfs_free_space_bitmaps(leaf, header);
287         generation = btrfs_free_space_generation(leaf, header);
288         btrfs_free_path(path);
289
290         if (BTRFS_I(inode)->generation != generation) {
291                 printk(KERN_ERR "btrfs: free space inode generation (%llu) did"
292                        " not match free space cache generation (%llu) for "
293                        "block group %llu\n",
294                        (unsigned long long)BTRFS_I(inode)->generation,
295                        (unsigned long long)generation,
296                        (unsigned long long)block_group->key.objectid);
297                 goto free_cache;
298         }
299
300         if (!num_entries)
301                 goto out;
302
303         /* Setup everything for doing checksumming */
304         num_checksums = i_size_read(inode) / PAGE_CACHE_SIZE;
305         checksums = crc = kzalloc(sizeof(u32) * num_checksums, GFP_NOFS);
306         if (!checksums)
307                 goto out;
308         first_page_offset = (sizeof(u32) * num_checksums) + sizeof(u64);
309         disk_crcs = kzalloc(first_page_offset, GFP_NOFS);
310         if (!disk_crcs)
311                 goto out;
312
313         ret = readahead_cache(inode);
314         if (ret) {
315                 ret = 0;
316                 goto out;
317         }
318
319         while (1) {
320                 struct btrfs_free_space_entry *entry;
321                 struct btrfs_free_space *e;
322                 void *addr;
323                 unsigned long offset = 0;
324                 unsigned long start_offset = 0;
325                 int need_loop = 0;
326
327                 if (!num_entries && !num_bitmaps)
328                         break;
329
330                 if (index == 0) {
331                         start_offset = first_page_offset;
332                         offset = start_offset;
333                 }
334
335                 page = grab_cache_page(inode->i_mapping, index);
336                 if (!page) {
337                         ret = 0;
338                         goto free_cache;
339                 }
340
341                 if (!PageUptodate(page)) {
342                         btrfs_readpage(NULL, page);
343                         lock_page(page);
344                         if (!PageUptodate(page)) {
345                                 unlock_page(page);
346                                 page_cache_release(page);
347                                 printk(KERN_ERR "btrfs: error reading free "
348                                        "space cache: %llu\n",
349                                        (unsigned long long)
350                                        block_group->key.objectid);
351                                 goto free_cache;
352                         }
353                 }
354                 addr = kmap(page);
355
356                 if (index == 0) {
357                         u64 *gen;
358
359                         memcpy(disk_crcs, addr, first_page_offset);
360                         gen = addr + (sizeof(u32) * num_checksums);
361                         if (*gen != BTRFS_I(inode)->generation) {
362                                 printk(KERN_ERR "btrfs: space cache generation"
363                                        " (%llu) does not match inode (%llu) "
364                                        "for block group %llu\n",
365                                        (unsigned long long)*gen,
366                                        (unsigned long long)
367                                        BTRFS_I(inode)->generation,
368                                        (unsigned long long)
369                                        block_group->key.objectid);
370                                 kunmap(page);
371                                 unlock_page(page);
372                                 page_cache_release(page);
373                                 goto free_cache;
374                         }
375                         crc = (u32 *)disk_crcs;
376                 }
377                 entry = addr + start_offset;
378
379                 /* First lets check our crc before we do anything fun */
380                 cur_crc = ~(u32)0;
381                 cur_crc = btrfs_csum_data(root, addr + start_offset, cur_crc,
382                                           PAGE_CACHE_SIZE - start_offset);
383                 btrfs_csum_final(cur_crc, (char *)&cur_crc);
384                 if (cur_crc != *crc) {
385                         printk(KERN_ERR "btrfs: crc mismatch for page %lu in "
386                                "block group %llu\n", index,
387                                (unsigned long long)block_group->key.objectid);
388                         kunmap(page);
389                         unlock_page(page);
390                         page_cache_release(page);
391                         goto free_cache;
392                 }
393                 crc++;
394
395                 while (1) {
396                         if (!num_entries)
397                                 break;
398
399                         need_loop = 1;
400                         e = kmem_cache_zalloc(btrfs_free_space_cachep,
401                                               GFP_NOFS);
402                         if (!e) {
403                                 kunmap(page);
404                                 unlock_page(page);
405                                 page_cache_release(page);
406                                 goto free_cache;
407                         }
408
409                         e->offset = le64_to_cpu(entry->offset);
410                         e->bytes = le64_to_cpu(entry->bytes);
411                         if (!e->bytes) {
412                                 kunmap(page);
413                                 kmem_cache_free(btrfs_free_space_cachep, e);
414                                 unlock_page(page);
415                                 page_cache_release(page);
416                                 goto free_cache;
417                         }
418
419                         if (entry->type == BTRFS_FREE_SPACE_EXTENT) {
420                                 spin_lock(&block_group->tree_lock);
421                                 ret = link_free_space(block_group, e);
422                                 spin_unlock(&block_group->tree_lock);
423                                 BUG_ON(ret);
424                         } else {
425                                 e->bitmap = kzalloc(PAGE_CACHE_SIZE, GFP_NOFS);
426                                 if (!e->bitmap) {
427                                         kunmap(page);
428                                         kmem_cache_free(
429                                                 btrfs_free_space_cachep, e);
430                                         unlock_page(page);
431                                         page_cache_release(page);
432                                         goto free_cache;
433                                 }
434                                 spin_lock(&block_group->tree_lock);
435                                 ret = link_free_space(block_group, e);
436                                 block_group->total_bitmaps++;
437                                 recalculate_thresholds(block_group);
438                                 spin_unlock(&block_group->tree_lock);
439                                 list_add_tail(&e->list, &bitmaps);
440                         }
441
442                         num_entries--;
443                         offset += sizeof(struct btrfs_free_space_entry);
444                         if (offset + sizeof(struct btrfs_free_space_entry) >=
445                             PAGE_CACHE_SIZE)
446                                 break;
447                         entry++;
448                 }
449
450                 /*
451                  * We read an entry out of this page, we need to move on to the
452                  * next page.
453                  */
454                 if (need_loop) {
455                         kunmap(page);
456                         goto next;
457                 }
458
459                 /*
460                  * We add the bitmaps at the end of the entries in order that
461                  * the bitmap entries are added to the cache.
462                  */
463                 e = list_entry(bitmaps.next, struct btrfs_free_space, list);
464                 list_del_init(&e->list);
465                 memcpy(e->bitmap, addr, PAGE_CACHE_SIZE);
466                 kunmap(page);
467                 num_bitmaps--;
468 next:
469                 unlock_page(page);
470                 page_cache_release(page);
471                 index++;
472         }
473
474         spin_lock(&block_group->tree_lock);
475         if (block_group->free_space != (block_group->key.offset - used -
476                                         block_group->bytes_super)) {
477                 spin_unlock(&block_group->tree_lock);
478                 printk(KERN_ERR "block group %llu has an wrong amount of free "
479                        "space\n", block_group->key.objectid);
480                 ret = 0;
481                 goto free_cache;
482         }
483         spin_unlock(&block_group->tree_lock);
484
485         ret = 1;
486 out:
487         kfree(checksums);
488         kfree(disk_crcs);
489         iput(inode);
490         return ret;
491
492 free_cache:
493         /* This cache is bogus, make sure it gets cleared */
494         spin_lock(&block_group->lock);
495         block_group->disk_cache_state = BTRFS_DC_CLEAR;
496         spin_unlock(&block_group->lock);
497         btrfs_remove_free_space_cache(block_group);
498         goto out;
499 }
500
501 int btrfs_write_out_cache(struct btrfs_root *root,
502                           struct btrfs_trans_handle *trans,
503                           struct btrfs_block_group_cache *block_group,
504                           struct btrfs_path *path)
505 {
506         struct btrfs_free_space_header *header;
507         struct extent_buffer *leaf;
508         struct inode *inode;
509         struct rb_node *node;
510         struct list_head *pos, *n;
511         struct page *page;
512         struct extent_state *cached_state = NULL;
513         struct btrfs_free_cluster *cluster = NULL;
514         struct extent_io_tree *unpin = NULL;
515         struct list_head bitmap_list;
516         struct btrfs_key key;
517         u64 start, end, len;
518         u64 bytes = 0;
519         u32 *crc, *checksums;
520         pgoff_t index = 0, last_index = 0;
521         unsigned long first_page_offset;
522         int num_checksums;
523         int entries = 0;
524         int bitmaps = 0;
525         int ret = 0;
526         bool next_page = false;
527
528         root = root->fs_info->tree_root;
529
530         INIT_LIST_HEAD(&bitmap_list);
531
532         spin_lock(&block_group->lock);
533         if (block_group->disk_cache_state < BTRFS_DC_SETUP) {
534                 spin_unlock(&block_group->lock);
535                 return 0;
536         }
537         spin_unlock(&block_group->lock);
538
539         inode = lookup_free_space_inode(root, block_group, path);
540         if (IS_ERR(inode))
541                 return 0;
542
543         if (!i_size_read(inode)) {
544                 iput(inode);
545                 return 0;
546         }
547
548         node = rb_first(&block_group->free_space_offset);
549         if (!node) {
550                 iput(inode);
551                 return 0;
552         }
553
554         last_index = (i_size_read(inode) - 1) >> PAGE_CACHE_SHIFT;
555         filemap_write_and_wait(inode->i_mapping);
556         btrfs_wait_ordered_range(inode, inode->i_size &
557                                  ~(root->sectorsize - 1), (u64)-1);
558
559         /* We need a checksum per page. */
560         num_checksums = i_size_read(inode) / PAGE_CACHE_SIZE;
561         crc = checksums  = kzalloc(sizeof(u32) * num_checksums, GFP_NOFS);
562         if (!crc) {
563                 iput(inode);
564                 return 0;
565         }
566
567         /* Since the first page has all of our checksums and our generation we
568          * need to calculate the offset into the page that we can start writing
569          * our entries.
570          */
571         first_page_offset = (sizeof(u32) * num_checksums) + sizeof(u64);
572
573         /* Get the cluster for this block_group if it exists */
574         if (!list_empty(&block_group->cluster_list))
575                 cluster = list_entry(block_group->cluster_list.next,
576                                      struct btrfs_free_cluster,
577                                      block_group_list);
578
579         /*
580          * We shouldn't have switched the pinned extents yet so this is the
581          * right one
582          */
583         unpin = root->fs_info->pinned_extents;
584
585         /*
586          * Lock all pages first so we can lock the extent safely.
587          *
588          * NOTE: Because we hold the ref the entire time we're going to write to
589          * the page find_get_page should never fail, so we don't do a check
590          * after find_get_page at this point.  Just putting this here so people
591          * know and don't freak out.
592          */
593         while (index <= last_index) {
594                 page = grab_cache_page(inode->i_mapping, index);
595                 if (!page) {
596                         pgoff_t i = 0;
597
598                         while (i < index) {
599                                 page = find_get_page(inode->i_mapping, i);
600                                 unlock_page(page);
601                                 page_cache_release(page);
602                                 page_cache_release(page);
603                                 i++;
604                         }
605                         goto out_free;
606                 }
607                 index++;
608         }
609
610         index = 0;
611         lock_extent_bits(&BTRFS_I(inode)->io_tree, 0, i_size_read(inode) - 1,
612                          0, &cached_state, GFP_NOFS);
613
614         /*
615          * When searching for pinned extents, we need to start at our start
616          * offset.
617          */
618         start = block_group->key.objectid;
619
620         /* Write out the extent entries */
621         do {
622                 struct btrfs_free_space_entry *entry;
623                 void *addr;
624                 unsigned long offset = 0;
625                 unsigned long start_offset = 0;
626
627                 next_page = false;
628
629                 if (index == 0) {
630                         start_offset = first_page_offset;
631                         offset = start_offset;
632                 }
633
634                 page = find_get_page(inode->i_mapping, index);
635
636                 addr = kmap(page);
637                 entry = addr + start_offset;
638
639                 memset(addr, 0, PAGE_CACHE_SIZE);
640                 while (node && !next_page) {
641                         struct btrfs_free_space *e;
642
643                         e = rb_entry(node, struct btrfs_free_space, offset_index);
644                         entries++;
645
646                         entry->offset = cpu_to_le64(e->offset);
647                         entry->bytes = cpu_to_le64(e->bytes);
648                         if (e->bitmap) {
649                                 entry->type = BTRFS_FREE_SPACE_BITMAP;
650                                 list_add_tail(&e->list, &bitmap_list);
651                                 bitmaps++;
652                         } else {
653                                 entry->type = BTRFS_FREE_SPACE_EXTENT;
654                         }
655                         node = rb_next(node);
656                         if (!node && cluster) {
657                                 node = rb_first(&cluster->root);
658                                 cluster = NULL;
659                         }
660                         offset += sizeof(struct btrfs_free_space_entry);
661                         if (offset + sizeof(struct btrfs_free_space_entry) >=
662                             PAGE_CACHE_SIZE)
663                                 next_page = true;
664                         entry++;
665                 }
666
667                 /*
668                  * We want to add any pinned extents to our free space cache
669                  * so we don't leak the space
670                  */
671                 while (!next_page && (start < block_group->key.objectid +
672                                       block_group->key.offset)) {
673                         ret = find_first_extent_bit(unpin, start, &start, &end,
674                                                     EXTENT_DIRTY);
675                         if (ret) {
676                                 ret = 0;
677                                 break;
678                         }
679
680                         /* This pinned extent is out of our range */
681                         if (start >= block_group->key.objectid +
682                             block_group->key.offset)
683                                 break;
684
685                         len = block_group->key.objectid +
686                                 block_group->key.offset - start;
687                         len = min(len, end + 1 - start);
688
689                         entries++;
690                         entry->offset = cpu_to_le64(start);
691                         entry->bytes = cpu_to_le64(len);
692                         entry->type = BTRFS_FREE_SPACE_EXTENT;
693
694                         start = end + 1;
695                         offset += sizeof(struct btrfs_free_space_entry);
696                         if (offset + sizeof(struct btrfs_free_space_entry) >=
697                             PAGE_CACHE_SIZE)
698                                 next_page = true;
699                         entry++;
700                 }
701                 *crc = ~(u32)0;
702                 *crc = btrfs_csum_data(root, addr + start_offset, *crc,
703                                        PAGE_CACHE_SIZE - start_offset);
704                 kunmap(page);
705
706                 btrfs_csum_final(*crc, (char *)crc);
707                 crc++;
708
709                 bytes += PAGE_CACHE_SIZE;
710
711                 ClearPageChecked(page);
712                 set_page_extent_mapped(page);
713                 SetPageUptodate(page);
714                 set_page_dirty(page);
715
716                 /*
717                  * We need to release our reference we got for grab_cache_page,
718                  * except for the first page which will hold our checksums, we
719                  * do that below.
720                  */
721                 if (index != 0) {
722                         unlock_page(page);
723                         page_cache_release(page);
724                 }
725
726                 page_cache_release(page);
727
728                 index++;
729         } while (node || next_page);
730
731         /* Write out the bitmaps */
732         list_for_each_safe(pos, n, &bitmap_list) {
733                 void *addr;
734                 struct btrfs_free_space *entry =
735                         list_entry(pos, struct btrfs_free_space, list);
736
737                 page = find_get_page(inode->i_mapping, index);
738
739                 addr = kmap(page);
740                 memcpy(addr, entry->bitmap, PAGE_CACHE_SIZE);
741                 *crc = ~(u32)0;
742                 *crc = btrfs_csum_data(root, addr, *crc, PAGE_CACHE_SIZE);
743                 kunmap(page);
744                 btrfs_csum_final(*crc, (char *)crc);
745                 crc++;
746                 bytes += PAGE_CACHE_SIZE;
747
748                 ClearPageChecked(page);
749                 set_page_extent_mapped(page);
750                 SetPageUptodate(page);
751                 set_page_dirty(page);
752                 unlock_page(page);
753                 page_cache_release(page);
754                 page_cache_release(page);
755                 list_del_init(&entry->list);
756                 index++;
757         }
758
759         /* Zero out the rest of the pages just to make sure */
760         while (index <= last_index) {
761                 void *addr;
762
763                 page = find_get_page(inode->i_mapping, index);
764
765                 addr = kmap(page);
766                 memset(addr, 0, PAGE_CACHE_SIZE);
767                 kunmap(page);
768                 ClearPageChecked(page);
769                 set_page_extent_mapped(page);
770                 SetPageUptodate(page);
771                 set_page_dirty(page);
772                 unlock_page(page);
773                 page_cache_release(page);
774                 page_cache_release(page);
775                 bytes += PAGE_CACHE_SIZE;
776                 index++;
777         }
778
779         btrfs_set_extent_delalloc(inode, 0, bytes - 1, &cached_state);
780
781         /* Write the checksums and trans id to the first page */
782         {
783                 void *addr;
784                 u64 *gen;
785
786                 page = find_get_page(inode->i_mapping, 0);
787
788                 addr = kmap(page);
789                 memcpy(addr, checksums, sizeof(u32) * num_checksums);
790                 gen = addr + (sizeof(u32) * num_checksums);
791                 *gen = trans->transid;
792                 kunmap(page);
793                 ClearPageChecked(page);
794                 set_page_extent_mapped(page);
795                 SetPageUptodate(page);
796                 set_page_dirty(page);
797                 unlock_page(page);
798                 page_cache_release(page);
799                 page_cache_release(page);
800         }
801         BTRFS_I(inode)->generation = trans->transid;
802
803         unlock_extent_cached(&BTRFS_I(inode)->io_tree, 0,
804                              i_size_read(inode) - 1, &cached_state, GFP_NOFS);
805
806         filemap_write_and_wait(inode->i_mapping);
807
808         key.objectid = BTRFS_FREE_SPACE_OBJECTID;
809         key.offset = block_group->key.objectid;
810         key.type = 0;
811
812         ret = btrfs_search_slot(trans, root, &key, path, 1, 1);
813         if (ret < 0) {
814                 ret = 0;
815                 clear_extent_bit(&BTRFS_I(inode)->io_tree, 0, bytes - 1,
816                                  EXTENT_DIRTY | EXTENT_DELALLOC |
817                                  EXTENT_DO_ACCOUNTING, 0, 0, NULL, GFP_NOFS);
818                 goto out_free;
819         }
820         leaf = path->nodes[0];
821         if (ret > 0) {
822                 struct btrfs_key found_key;
823                 BUG_ON(!path->slots[0]);
824                 path->slots[0]--;
825                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
826                 if (found_key.objectid != BTRFS_FREE_SPACE_OBJECTID ||
827                     found_key.offset != block_group->key.objectid) {
828                         ret = 0;
829                         clear_extent_bit(&BTRFS_I(inode)->io_tree, 0, bytes - 1,
830                                          EXTENT_DIRTY | EXTENT_DELALLOC |
831                                          EXTENT_DO_ACCOUNTING, 0, 0, NULL,
832                                          GFP_NOFS);
833                         btrfs_release_path(root, path);
834                         goto out_free;
835                 }
836         }
837         header = btrfs_item_ptr(leaf, path->slots[0],
838                                 struct btrfs_free_space_header);
839         btrfs_set_free_space_entries(leaf, header, entries);
840         btrfs_set_free_space_bitmaps(leaf, header, bitmaps);
841         btrfs_set_free_space_generation(leaf, header, trans->transid);
842         btrfs_mark_buffer_dirty(leaf);
843         btrfs_release_path(root, path);
844
845         ret = 1;
846
847 out_free:
848         if (ret == 0) {
849                 invalidate_inode_pages2_range(inode->i_mapping, 0, index);
850                 spin_lock(&block_group->lock);
851                 block_group->disk_cache_state = BTRFS_DC_ERROR;
852                 spin_unlock(&block_group->lock);
853                 BTRFS_I(inode)->generation = 0;
854         }
855         kfree(checksums);
856         btrfs_update_inode(trans, root, inode);
857         iput(inode);
858         return ret;
859 }
860
861 static inline unsigned long offset_to_bit(u64 bitmap_start, u64 sectorsize,
862                                           u64 offset)
863 {
864         BUG_ON(offset < bitmap_start);
865         offset -= bitmap_start;
866         return (unsigned long)(div64_u64(offset, sectorsize));
867 }
868
869 static inline unsigned long bytes_to_bits(u64 bytes, u64 sectorsize)
870 {
871         return (unsigned long)(div64_u64(bytes, sectorsize));
872 }
873
874 static inline u64 offset_to_bitmap(struct btrfs_block_group_cache *block_group,
875                                    u64 offset)
876 {
877         u64 bitmap_start;
878         u64 bytes_per_bitmap;
879
880         bytes_per_bitmap = BITS_PER_BITMAP * block_group->sectorsize;
881         bitmap_start = offset - block_group->key.objectid;
882         bitmap_start = div64_u64(bitmap_start, bytes_per_bitmap);
883         bitmap_start *= bytes_per_bitmap;
884         bitmap_start += block_group->key.objectid;
885
886         return bitmap_start;
887 }
888
889 static int tree_insert_offset(struct rb_root *root, u64 offset,
890                               struct rb_node *node, int bitmap)
891 {
892         struct rb_node **p = &root->rb_node;
893         struct rb_node *parent = NULL;
894         struct btrfs_free_space *info;
895
896         while (*p) {
897                 parent = *p;
898                 info = rb_entry(parent, struct btrfs_free_space, offset_index);
899
900                 if (offset < info->offset) {
901                         p = &(*p)->rb_left;
902                 } else if (offset > info->offset) {
903                         p = &(*p)->rb_right;
904                 } else {
905                         /*
906                          * we could have a bitmap entry and an extent entry
907                          * share the same offset.  If this is the case, we want
908                          * the extent entry to always be found first if we do a
909                          * linear search through the tree, since we want to have
910                          * the quickest allocation time, and allocating from an
911                          * extent is faster than allocating from a bitmap.  So
912                          * if we're inserting a bitmap and we find an entry at
913                          * this offset, we want to go right, or after this entry
914                          * logically.  If we are inserting an extent and we've
915                          * found a bitmap, we want to go left, or before
916                          * logically.
917                          */
918                         if (bitmap) {
919                                 WARN_ON(info->bitmap);
920                                 p = &(*p)->rb_right;
921                         } else {
922                                 WARN_ON(!info->bitmap);
923                                 p = &(*p)->rb_left;
924                         }
925                 }
926         }
927
928         rb_link_node(node, parent, p);
929         rb_insert_color(node, root);
930
931         return 0;
932 }
933
934 /*
935  * searches the tree for the given offset.
936  *
937  * fuzzy - If this is set, then we are trying to make an allocation, and we just
938  * want a section that has at least bytes size and comes at or after the given
939  * offset.
940  */
941 static struct btrfs_free_space *
942 tree_search_offset(struct btrfs_block_group_cache *block_group,
943                    u64 offset, int bitmap_only, int fuzzy)
944 {
945         struct rb_node *n = block_group->free_space_offset.rb_node;
946         struct btrfs_free_space *entry, *prev = NULL;
947
948         /* find entry that is closest to the 'offset' */
949         while (1) {
950                 if (!n) {
951                         entry = NULL;
952                         break;
953                 }
954
955                 entry = rb_entry(n, struct btrfs_free_space, offset_index);
956                 prev = entry;
957
958                 if (offset < entry->offset)
959                         n = n->rb_left;
960                 else if (offset > entry->offset)
961                         n = n->rb_right;
962                 else
963                         break;
964         }
965
966         if (bitmap_only) {
967                 if (!entry)
968                         return NULL;
969                 if (entry->bitmap)
970                         return entry;
971
972                 /*
973                  * bitmap entry and extent entry may share same offset,
974                  * in that case, bitmap entry comes after extent entry.
975                  */
976                 n = rb_next(n);
977                 if (!n)
978                         return NULL;
979                 entry = rb_entry(n, struct btrfs_free_space, offset_index);
980                 if (entry->offset != offset)
981                         return NULL;
982
983                 WARN_ON(!entry->bitmap);
984                 return entry;
985         } else if (entry) {
986                 if (entry->bitmap) {
987                         /*
988                          * if previous extent entry covers the offset,
989                          * we should return it instead of the bitmap entry
990                          */
991                         n = &entry->offset_index;
992                         while (1) {
993                                 n = rb_prev(n);
994                                 if (!n)
995                                         break;
996                                 prev = rb_entry(n, struct btrfs_free_space,
997                                                 offset_index);
998                                 if (!prev->bitmap) {
999                                         if (prev->offset + prev->bytes > offset)
1000                                                 entry = prev;
1001                                         break;
1002                                 }
1003                         }
1004                 }
1005                 return entry;
1006         }
1007
1008         if (!prev)
1009                 return NULL;
1010
1011         /* find last entry before the 'offset' */
1012         entry = prev;
1013         if (entry->offset > offset) {
1014                 n = rb_prev(&entry->offset_index);
1015                 if (n) {
1016                         entry = rb_entry(n, struct btrfs_free_space,
1017                                         offset_index);
1018                         BUG_ON(entry->offset > offset);
1019                 } else {
1020                         if (fuzzy)
1021                                 return entry;
1022                         else
1023                                 return NULL;
1024                 }
1025         }
1026
1027         if (entry->bitmap) {
1028                 n = &entry->offset_index;
1029                 while (1) {
1030                         n = rb_prev(n);
1031                         if (!n)
1032                                 break;
1033                         prev = rb_entry(n, struct btrfs_free_space,
1034                                         offset_index);
1035                         if (!prev->bitmap) {
1036                                 if (prev->offset + prev->bytes > offset)
1037                                         return prev;
1038                                 break;
1039                         }
1040                 }
1041                 if (entry->offset + BITS_PER_BITMAP *
1042                     block_group->sectorsize > offset)
1043                         return entry;
1044         } else if (entry->offset + entry->bytes > offset)
1045                 return entry;
1046
1047         if (!fuzzy)
1048                 return NULL;
1049
1050         while (1) {
1051                 if (entry->bitmap) {
1052                         if (entry->offset + BITS_PER_BITMAP *
1053                             block_group->sectorsize > offset)
1054                                 break;
1055                 } else {
1056                         if (entry->offset + entry->bytes > offset)
1057                                 break;
1058                 }
1059
1060                 n = rb_next(&entry->offset_index);
1061                 if (!n)
1062                         return NULL;
1063                 entry = rb_entry(n, struct btrfs_free_space, offset_index);
1064         }
1065         return entry;
1066 }
1067
1068 static inline void
1069 __unlink_free_space(struct btrfs_block_group_cache *block_group,
1070                     struct btrfs_free_space *info)
1071 {
1072         rb_erase(&info->offset_index, &block_group->free_space_offset);
1073         block_group->free_extents--;
1074 }
1075
1076 static void unlink_free_space(struct btrfs_block_group_cache *block_group,
1077                               struct btrfs_free_space *info)
1078 {
1079         __unlink_free_space(block_group, info);
1080         block_group->free_space -= info->bytes;
1081 }
1082
1083 static int link_free_space(struct btrfs_block_group_cache *block_group,
1084                            struct btrfs_free_space *info)
1085 {
1086         int ret = 0;
1087
1088         BUG_ON(!info->bitmap && !info->bytes);
1089         ret = tree_insert_offset(&block_group->free_space_offset, info->offset,
1090                                  &info->offset_index, (info->bitmap != NULL));
1091         if (ret)
1092                 return ret;
1093
1094         block_group->free_space += info->bytes;
1095         block_group->free_extents++;
1096         return ret;
1097 }
1098
1099 static void recalculate_thresholds(struct btrfs_block_group_cache *block_group)
1100 {
1101         u64 max_bytes;
1102         u64 bitmap_bytes;
1103         u64 extent_bytes;
1104         u64 size = block_group->key.offset;
1105
1106         /*
1107          * The goal is to keep the total amount of memory used per 1gb of space
1108          * at or below 32k, so we need to adjust how much memory we allow to be
1109          * used by extent based free space tracking
1110          */
1111         if (size < 1024 * 1024 * 1024)
1112                 max_bytes = MAX_CACHE_BYTES_PER_GIG;
1113         else
1114                 max_bytes = MAX_CACHE_BYTES_PER_GIG *
1115                         div64_u64(size, 1024 * 1024 * 1024);
1116
1117         /*
1118          * we want to account for 1 more bitmap than what we have so we can make
1119          * sure we don't go over our overall goal of MAX_CACHE_BYTES_PER_GIG as
1120          * we add more bitmaps.
1121          */
1122         bitmap_bytes = (block_group->total_bitmaps + 1) * PAGE_CACHE_SIZE;
1123
1124         if (bitmap_bytes >= max_bytes) {
1125                 block_group->extents_thresh = 0;
1126                 return;
1127         }
1128
1129         /*
1130          * we want the extent entry threshold to always be at most 1/2 the maxw
1131          * bytes we can have, or whatever is less than that.
1132          */
1133         extent_bytes = max_bytes - bitmap_bytes;
1134         extent_bytes = min_t(u64, extent_bytes, div64_u64(max_bytes, 2));
1135
1136         block_group->extents_thresh =
1137                 div64_u64(extent_bytes, (sizeof(struct btrfs_free_space)));
1138 }
1139
1140 static void bitmap_clear_bits(struct btrfs_block_group_cache *block_group,
1141                               struct btrfs_free_space *info, u64 offset,
1142                               u64 bytes)
1143 {
1144         unsigned long start, end;
1145         unsigned long i;
1146
1147         start = offset_to_bit(info->offset, block_group->sectorsize, offset);
1148         end = start + bytes_to_bits(bytes, block_group->sectorsize);
1149         BUG_ON(end > BITS_PER_BITMAP);
1150
1151         for (i = start; i < end; i++)
1152                 clear_bit(i, info->bitmap);
1153
1154         info->bytes -= bytes;
1155         block_group->free_space -= bytes;
1156 }
1157
1158 static void bitmap_set_bits(struct btrfs_block_group_cache *block_group,
1159                             struct btrfs_free_space *info, u64 offset,
1160                             u64 bytes)
1161 {
1162         unsigned long start, end;
1163         unsigned long i;
1164
1165         start = offset_to_bit(info->offset, block_group->sectorsize, offset);
1166         end = start + bytes_to_bits(bytes, block_group->sectorsize);
1167         BUG_ON(end > BITS_PER_BITMAP);
1168
1169         for (i = start; i < end; i++)
1170                 set_bit(i, info->bitmap);
1171
1172         info->bytes += bytes;
1173         block_group->free_space += bytes;
1174 }
1175
1176 static int search_bitmap(struct btrfs_block_group_cache *block_group,
1177                          struct btrfs_free_space *bitmap_info, u64 *offset,
1178                          u64 *bytes)
1179 {
1180         unsigned long found_bits = 0;
1181         unsigned long bits, i;
1182         unsigned long next_zero;
1183
1184         i = offset_to_bit(bitmap_info->offset, block_group->sectorsize,
1185                           max_t(u64, *offset, bitmap_info->offset));
1186         bits = bytes_to_bits(*bytes, block_group->sectorsize);
1187
1188         for (i = find_next_bit(bitmap_info->bitmap, BITS_PER_BITMAP, i);
1189              i < BITS_PER_BITMAP;
1190              i = find_next_bit(bitmap_info->bitmap, BITS_PER_BITMAP, i + 1)) {
1191                 next_zero = find_next_zero_bit(bitmap_info->bitmap,
1192                                                BITS_PER_BITMAP, i);
1193                 if ((next_zero - i) >= bits) {
1194                         found_bits = next_zero - i;
1195                         break;
1196                 }
1197                 i = next_zero;
1198         }
1199
1200         if (found_bits) {
1201                 *offset = (u64)(i * block_group->sectorsize) +
1202                         bitmap_info->offset;
1203                 *bytes = (u64)(found_bits) * block_group->sectorsize;
1204                 return 0;
1205         }
1206
1207         return -1;
1208 }
1209
1210 static struct btrfs_free_space *find_free_space(struct btrfs_block_group_cache
1211                                                 *block_group, u64 *offset,
1212                                                 u64 *bytes, int debug)
1213 {
1214         struct btrfs_free_space *entry;
1215         struct rb_node *node;
1216         int ret;
1217
1218         if (!block_group->free_space_offset.rb_node)
1219                 return NULL;
1220
1221         entry = tree_search_offset(block_group,
1222                                    offset_to_bitmap(block_group, *offset),
1223                                    0, 1);
1224         if (!entry)
1225                 return NULL;
1226
1227         for (node = &entry->offset_index; node; node = rb_next(node)) {
1228                 entry = rb_entry(node, struct btrfs_free_space, offset_index);
1229                 if (entry->bytes < *bytes)
1230                         continue;
1231
1232                 if (entry->bitmap) {
1233                         ret = search_bitmap(block_group, entry, offset, bytes);
1234                         if (!ret)
1235                                 return entry;
1236                         continue;
1237                 }
1238
1239                 *offset = entry->offset;
1240                 *bytes = entry->bytes;
1241                 return entry;
1242         }
1243
1244         return NULL;
1245 }
1246
1247 static void add_new_bitmap(struct btrfs_block_group_cache *block_group,
1248                            struct btrfs_free_space *info, u64 offset)
1249 {
1250         u64 bytes_per_bg = BITS_PER_BITMAP * block_group->sectorsize;
1251         int max_bitmaps = (int)div64_u64(block_group->key.offset +
1252                                          bytes_per_bg - 1, bytes_per_bg);
1253         BUG_ON(block_group->total_bitmaps >= max_bitmaps);
1254
1255         info->offset = offset_to_bitmap(block_group, offset);
1256         info->bytes = 0;
1257         link_free_space(block_group, info);
1258         block_group->total_bitmaps++;
1259
1260         recalculate_thresholds(block_group);
1261 }
1262
1263 static void free_bitmap(struct btrfs_block_group_cache *block_group,
1264                         struct btrfs_free_space *bitmap_info)
1265 {
1266         unlink_free_space(block_group, bitmap_info);
1267         kfree(bitmap_info->bitmap);
1268         kmem_cache_free(btrfs_free_space_cachep, bitmap_info);
1269         block_group->total_bitmaps--;
1270         recalculate_thresholds(block_group);
1271 }
1272
1273 static noinline int remove_from_bitmap(struct btrfs_block_group_cache *block_group,
1274                               struct btrfs_free_space *bitmap_info,
1275                               u64 *offset, u64 *bytes)
1276 {
1277         u64 end;
1278         u64 search_start, search_bytes;
1279         int ret;
1280
1281 again:
1282         end = bitmap_info->offset +
1283                 (u64)(BITS_PER_BITMAP * block_group->sectorsize) - 1;
1284
1285         /*
1286          * XXX - this can go away after a few releases.
1287          *
1288          * since the only user of btrfs_remove_free_space is the tree logging
1289          * stuff, and the only way to test that is under crash conditions, we
1290          * want to have this debug stuff here just in case somethings not
1291          * working.  Search the bitmap for the space we are trying to use to
1292          * make sure its actually there.  If its not there then we need to stop
1293          * because something has gone wrong.
1294          */
1295         search_start = *offset;
1296         search_bytes = *bytes;
1297         search_bytes = min(search_bytes, end - search_start + 1);
1298         ret = search_bitmap(block_group, bitmap_info, &search_start,
1299                             &search_bytes);
1300         BUG_ON(ret < 0 || search_start != *offset);
1301
1302         if (*offset > bitmap_info->offset && *offset + *bytes > end) {
1303                 bitmap_clear_bits(block_group, bitmap_info, *offset,
1304                                   end - *offset + 1);
1305                 *bytes -= end - *offset + 1;
1306                 *offset = end + 1;
1307         } else if (*offset >= bitmap_info->offset && *offset + *bytes <= end) {
1308                 bitmap_clear_bits(block_group, bitmap_info, *offset, *bytes);
1309                 *bytes = 0;
1310         }
1311
1312         if (*bytes) {
1313                 struct rb_node *next = rb_next(&bitmap_info->offset_index);
1314                 if (!bitmap_info->bytes)
1315                         free_bitmap(block_group, bitmap_info);
1316
1317                 /*
1318                  * no entry after this bitmap, but we still have bytes to
1319                  * remove, so something has gone wrong.
1320                  */
1321                 if (!next)
1322                         return -EINVAL;
1323
1324                 bitmap_info = rb_entry(next, struct btrfs_free_space,
1325                                        offset_index);
1326
1327                 /*
1328                  * if the next entry isn't a bitmap we need to return to let the
1329                  * extent stuff do its work.
1330                  */
1331                 if (!bitmap_info->bitmap)
1332                         return -EAGAIN;
1333
1334                 /*
1335                  * Ok the next item is a bitmap, but it may not actually hold
1336                  * the information for the rest of this free space stuff, so
1337                  * look for it, and if we don't find it return so we can try
1338                  * everything over again.
1339                  */
1340                 search_start = *offset;
1341                 search_bytes = *bytes;
1342                 ret = search_bitmap(block_group, bitmap_info, &search_start,
1343                                     &search_bytes);
1344                 if (ret < 0 || search_start != *offset)
1345                         return -EAGAIN;
1346
1347                 goto again;
1348         } else if (!bitmap_info->bytes)
1349                 free_bitmap(block_group, bitmap_info);
1350
1351         return 0;
1352 }
1353
1354 static int insert_into_bitmap(struct btrfs_block_group_cache *block_group,
1355                               struct btrfs_free_space *info)
1356 {
1357         struct btrfs_free_space *bitmap_info;
1358         int added = 0;
1359         u64 bytes, offset, end;
1360         int ret;
1361
1362         /*
1363          * If we are below the extents threshold then we can add this as an
1364          * extent, and don't have to deal with the bitmap
1365          */
1366         if (block_group->free_extents < block_group->extents_thresh) {
1367                 /*
1368                  * If this block group has some small extents we don't want to
1369                  * use up all of our free slots in the cache with them, we want
1370                  * to reserve them to larger extents, however if we have plent
1371                  * of cache left then go ahead an dadd them, no sense in adding
1372                  * the overhead of a bitmap if we don't have to.
1373                  */
1374                 if (info->bytes <= block_group->sectorsize * 4) {
1375                         if (block_group->free_extents * 2 <=
1376                             block_group->extents_thresh)
1377                                 return 0;
1378                 } else {
1379                         return 0;
1380                 }
1381         }
1382
1383         /*
1384          * some block groups are so tiny they can't be enveloped by a bitmap, so
1385          * don't even bother to create a bitmap for this
1386          */
1387         if (BITS_PER_BITMAP * block_group->sectorsize >
1388             block_group->key.offset)
1389                 return 0;
1390
1391         bytes = info->bytes;
1392         offset = info->offset;
1393
1394 again:
1395         bitmap_info = tree_search_offset(block_group,
1396                                          offset_to_bitmap(block_group, offset),
1397                                          1, 0);
1398         if (!bitmap_info) {
1399                 BUG_ON(added);
1400                 goto new_bitmap;
1401         }
1402
1403         end = bitmap_info->offset +
1404                 (u64)(BITS_PER_BITMAP * block_group->sectorsize);
1405
1406         if (offset >= bitmap_info->offset && offset + bytes > end) {
1407                 bitmap_set_bits(block_group, bitmap_info, offset,
1408                                 end - offset);
1409                 bytes -= end - offset;
1410                 offset = end;
1411                 added = 0;
1412         } else if (offset >= bitmap_info->offset && offset + bytes <= end) {
1413                 bitmap_set_bits(block_group, bitmap_info, offset, bytes);
1414                 bytes = 0;
1415         } else {
1416                 BUG();
1417         }
1418
1419         if (!bytes) {
1420                 ret = 1;
1421                 goto out;
1422         } else
1423                 goto again;
1424
1425 new_bitmap:
1426         if (info && info->bitmap) {
1427                 add_new_bitmap(block_group, info, offset);
1428                 added = 1;
1429                 info = NULL;
1430                 goto again;
1431         } else {
1432                 spin_unlock(&block_group->tree_lock);
1433
1434                 /* no pre-allocated info, allocate a new one */
1435                 if (!info) {
1436                         info = kmem_cache_zalloc(btrfs_free_space_cachep,
1437                                                  GFP_NOFS);
1438                         if (!info) {
1439                                 spin_lock(&block_group->tree_lock);
1440                                 ret = -ENOMEM;
1441                                 goto out;
1442                         }
1443                 }
1444
1445                 /* allocate the bitmap */
1446                 info->bitmap = kzalloc(PAGE_CACHE_SIZE, GFP_NOFS);
1447                 spin_lock(&block_group->tree_lock);
1448                 if (!info->bitmap) {
1449                         ret = -ENOMEM;
1450                         goto out;
1451                 }
1452                 goto again;
1453         }
1454
1455 out:
1456         if (info) {
1457                 if (info->bitmap)
1458                         kfree(info->bitmap);
1459                 kmem_cache_free(btrfs_free_space_cachep, info);
1460         }
1461
1462         return ret;
1463 }
1464
1465 bool try_merge_free_space(struct btrfs_block_group_cache *block_group,
1466                           struct btrfs_free_space *info, bool update_stat)
1467 {
1468         struct btrfs_free_space *left_info;
1469         struct btrfs_free_space *right_info;
1470         bool merged = false;
1471         u64 offset = info->offset;
1472         u64 bytes = info->bytes;
1473
1474         /*
1475          * first we want to see if there is free space adjacent to the range we
1476          * are adding, if there is remove that struct and add a new one to
1477          * cover the entire range
1478          */
1479         right_info = tree_search_offset(block_group, offset + bytes, 0, 0);
1480         if (right_info && rb_prev(&right_info->offset_index))
1481                 left_info = rb_entry(rb_prev(&right_info->offset_index),
1482                                      struct btrfs_free_space, offset_index);
1483         else
1484                 left_info = tree_search_offset(block_group, offset - 1, 0, 0);
1485
1486         if (right_info && !right_info->bitmap) {
1487                 if (update_stat)
1488                         unlink_free_space(block_group, right_info);
1489                 else
1490                         __unlink_free_space(block_group, right_info);
1491                 info->bytes += right_info->bytes;
1492                 kmem_cache_free(btrfs_free_space_cachep, right_info);
1493                 merged = true;
1494         }
1495
1496         if (left_info && !left_info->bitmap &&
1497             left_info->offset + left_info->bytes == offset) {
1498                 if (update_stat)
1499                         unlink_free_space(block_group, left_info);
1500                 else
1501                         __unlink_free_space(block_group, left_info);
1502                 info->offset = left_info->offset;
1503                 info->bytes += left_info->bytes;
1504                 kmem_cache_free(btrfs_free_space_cachep, left_info);
1505                 merged = true;
1506         }
1507
1508         return merged;
1509 }
1510
1511 int btrfs_add_free_space(struct btrfs_block_group_cache *block_group,
1512                          u64 offset, u64 bytes)
1513 {
1514         struct btrfs_free_space *info;
1515         int ret = 0;
1516
1517         info = kmem_cache_zalloc(btrfs_free_space_cachep, GFP_NOFS);
1518         if (!info)
1519                 return -ENOMEM;
1520
1521         info->offset = offset;
1522         info->bytes = bytes;
1523
1524         spin_lock(&block_group->tree_lock);
1525
1526         if (try_merge_free_space(block_group, info, true))
1527                 goto link;
1528
1529         /*
1530          * There was no extent directly to the left or right of this new
1531          * extent then we know we're going to have to allocate a new extent, so
1532          * before we do that see if we need to drop this into a bitmap
1533          */
1534         ret = insert_into_bitmap(block_group, info);
1535         if (ret < 0) {
1536                 goto out;
1537         } else if (ret) {
1538                 ret = 0;
1539                 goto out;
1540         }
1541 link:
1542         ret = link_free_space(block_group, info);
1543         if (ret)
1544                 kmem_cache_free(btrfs_free_space_cachep, info);
1545 out:
1546         spin_unlock(&block_group->tree_lock);
1547
1548         if (ret) {
1549                 printk(KERN_CRIT "btrfs: unable to add free space :%d\n", ret);
1550                 BUG_ON(ret == -EEXIST);
1551         }
1552
1553         return ret;
1554 }
1555
1556 int btrfs_remove_free_space(struct btrfs_block_group_cache *block_group,
1557                             u64 offset, u64 bytes)
1558 {
1559         struct btrfs_free_space *info;
1560         struct btrfs_free_space *next_info = NULL;
1561         int ret = 0;
1562
1563         spin_lock(&block_group->tree_lock);
1564
1565 again:
1566         info = tree_search_offset(block_group, offset, 0, 0);
1567         if (!info) {
1568                 /*
1569                  * oops didn't find an extent that matched the space we wanted
1570                  * to remove, look for a bitmap instead
1571                  */
1572                 info = tree_search_offset(block_group,
1573                                           offset_to_bitmap(block_group, offset),
1574                                           1, 0);
1575                 if (!info) {
1576                         WARN_ON(1);
1577                         goto out_lock;
1578                 }
1579         }
1580
1581         if (info->bytes < bytes && rb_next(&info->offset_index)) {
1582                 u64 end;
1583                 next_info = rb_entry(rb_next(&info->offset_index),
1584                                              struct btrfs_free_space,
1585                                              offset_index);
1586
1587                 if (next_info->bitmap)
1588                         end = next_info->offset + BITS_PER_BITMAP *
1589                                 block_group->sectorsize - 1;
1590                 else
1591                         end = next_info->offset + next_info->bytes;
1592
1593                 if (next_info->bytes < bytes ||
1594                     next_info->offset > offset || offset > end) {
1595                         printk(KERN_CRIT "Found free space at %llu, size %llu,"
1596                               " trying to use %llu\n",
1597                               (unsigned long long)info->offset,
1598                               (unsigned long long)info->bytes,
1599                               (unsigned long long)bytes);
1600                         WARN_ON(1);
1601                         ret = -EINVAL;
1602                         goto out_lock;
1603                 }
1604
1605                 info = next_info;
1606         }
1607
1608         if (info->bytes == bytes) {
1609                 unlink_free_space(block_group, info);
1610                 if (info->bitmap) {
1611                         kfree(info->bitmap);
1612                         block_group->total_bitmaps--;
1613                 }
1614                 kmem_cache_free(btrfs_free_space_cachep, info);
1615                 goto out_lock;
1616         }
1617
1618         if (!info->bitmap && info->offset == offset) {
1619                 unlink_free_space(block_group, info);
1620                 info->offset += bytes;
1621                 info->bytes -= bytes;
1622                 link_free_space(block_group, info);
1623                 goto out_lock;
1624         }
1625
1626         if (!info->bitmap && info->offset <= offset &&
1627             info->offset + info->bytes >= offset + bytes) {
1628                 u64 old_start = info->offset;
1629                 /*
1630                  * we're freeing space in the middle of the info,
1631                  * this can happen during tree log replay
1632                  *
1633                  * first unlink the old info and then
1634                  * insert it again after the hole we're creating
1635                  */
1636                 unlink_free_space(block_group, info);
1637                 if (offset + bytes < info->offset + info->bytes) {
1638                         u64 old_end = info->offset + info->bytes;
1639
1640                         info->offset = offset + bytes;
1641                         info->bytes = old_end - info->offset;
1642                         ret = link_free_space(block_group, info);
1643                         WARN_ON(ret);
1644                         if (ret)
1645                                 goto out_lock;
1646                 } else {
1647                         /* the hole we're creating ends at the end
1648                          * of the info struct, just free the info
1649                          */
1650                         kmem_cache_free(btrfs_free_space_cachep, info);
1651                 }
1652                 spin_unlock(&block_group->tree_lock);
1653
1654                 /* step two, insert a new info struct to cover
1655                  * anything before the hole
1656                  */
1657                 ret = btrfs_add_free_space(block_group, old_start,
1658                                            offset - old_start);
1659                 WARN_ON(ret);
1660                 goto out;
1661         }
1662
1663         ret = remove_from_bitmap(block_group, info, &offset, &bytes);
1664         if (ret == -EAGAIN)
1665                 goto again;
1666         BUG_ON(ret);
1667 out_lock:
1668         spin_unlock(&block_group->tree_lock);
1669 out:
1670         return ret;
1671 }
1672
1673 void btrfs_dump_free_space(struct btrfs_block_group_cache *block_group,
1674                            u64 bytes)
1675 {
1676         struct btrfs_free_space *info;
1677         struct rb_node *n;
1678         int count = 0;
1679
1680         for (n = rb_first(&block_group->free_space_offset); n; n = rb_next(n)) {
1681                 info = rb_entry(n, struct btrfs_free_space, offset_index);
1682                 if (info->bytes >= bytes)
1683                         count++;
1684                 printk(KERN_CRIT "entry offset %llu, bytes %llu, bitmap %s\n",
1685                        (unsigned long long)info->offset,
1686                        (unsigned long long)info->bytes,
1687                        (info->bitmap) ? "yes" : "no");
1688         }
1689         printk(KERN_INFO "block group has cluster?: %s\n",
1690                list_empty(&block_group->cluster_list) ? "no" : "yes");
1691         printk(KERN_INFO "%d blocks of free space at or bigger than bytes is"
1692                "\n", count);
1693 }
1694
1695 u64 btrfs_block_group_free_space(struct btrfs_block_group_cache *block_group)
1696 {
1697         struct btrfs_free_space *info;
1698         struct rb_node *n;
1699         u64 ret = 0;
1700
1701         for (n = rb_first(&block_group->free_space_offset); n;
1702              n = rb_next(n)) {
1703                 info = rb_entry(n, struct btrfs_free_space, offset_index);
1704                 ret += info->bytes;
1705         }
1706
1707         return ret;
1708 }
1709
1710 /*
1711  * for a given cluster, put all of its extents back into the free
1712  * space cache.  If the block group passed doesn't match the block group
1713  * pointed to by the cluster, someone else raced in and freed the
1714  * cluster already.  In that case, we just return without changing anything
1715  */
1716 static int
1717 __btrfs_return_cluster_to_free_space(
1718                              struct btrfs_block_group_cache *block_group,
1719                              struct btrfs_free_cluster *cluster)
1720 {
1721         struct btrfs_free_space *entry;
1722         struct rb_node *node;
1723
1724         spin_lock(&cluster->lock);
1725         if (cluster->block_group != block_group)
1726                 goto out;
1727
1728         cluster->block_group = NULL;
1729         cluster->window_start = 0;
1730         list_del_init(&cluster->block_group_list);
1731
1732         node = rb_first(&cluster->root);
1733         while (node) {
1734                 bool bitmap;
1735
1736                 entry = rb_entry(node, struct btrfs_free_space, offset_index);
1737                 node = rb_next(&entry->offset_index);
1738                 rb_erase(&entry->offset_index, &cluster->root);
1739
1740                 bitmap = (entry->bitmap != NULL);
1741                 if (!bitmap)
1742                         try_merge_free_space(block_group, entry, false);
1743                 tree_insert_offset(&block_group->free_space_offset,
1744                                    entry->offset, &entry->offset_index, bitmap);
1745         }
1746         cluster->root = RB_ROOT;
1747
1748 out:
1749         spin_unlock(&cluster->lock);
1750         btrfs_put_block_group(block_group);
1751         return 0;
1752 }
1753
1754 void btrfs_remove_free_space_cache(struct btrfs_block_group_cache *block_group)
1755 {
1756         struct btrfs_free_space *info;
1757         struct rb_node *node;
1758         struct btrfs_free_cluster *cluster;
1759         struct list_head *head;
1760
1761         spin_lock(&block_group->tree_lock);
1762         while ((head = block_group->cluster_list.next) !=
1763                &block_group->cluster_list) {
1764                 cluster = list_entry(head, struct btrfs_free_cluster,
1765                                      block_group_list);
1766
1767                 WARN_ON(cluster->block_group != block_group);
1768                 __btrfs_return_cluster_to_free_space(block_group, cluster);
1769                 if (need_resched()) {
1770                         spin_unlock(&block_group->tree_lock);
1771                         cond_resched();
1772                         spin_lock(&block_group->tree_lock);
1773                 }
1774         }
1775
1776         while ((node = rb_last(&block_group->free_space_offset)) != NULL) {
1777                 info = rb_entry(node, struct btrfs_free_space, offset_index);
1778                 unlink_free_space(block_group, info);
1779                 if (info->bitmap)
1780                         kfree(info->bitmap);
1781                 kmem_cache_free(btrfs_free_space_cachep, info);
1782                 if (need_resched()) {
1783                         spin_unlock(&block_group->tree_lock);
1784                         cond_resched();
1785                         spin_lock(&block_group->tree_lock);
1786                 }
1787         }
1788
1789         spin_unlock(&block_group->tree_lock);
1790 }
1791
1792 u64 btrfs_find_space_for_alloc(struct btrfs_block_group_cache *block_group,
1793                                u64 offset, u64 bytes, u64 empty_size)
1794 {
1795         struct btrfs_free_space *entry = NULL;
1796         u64 bytes_search = bytes + empty_size;
1797         u64 ret = 0;
1798
1799         spin_lock(&block_group->tree_lock);
1800         entry = find_free_space(block_group, &offset, &bytes_search, 0);
1801         if (!entry)
1802                 goto out;
1803
1804         ret = offset;
1805         if (entry->bitmap) {
1806                 bitmap_clear_bits(block_group, entry, offset, bytes);
1807                 if (!entry->bytes)
1808                         free_bitmap(block_group, entry);
1809         } else {
1810                 unlink_free_space(block_group, entry);
1811                 entry->offset += bytes;
1812                 entry->bytes -= bytes;
1813                 if (!entry->bytes)
1814                         kmem_cache_free(btrfs_free_space_cachep, entry);
1815                 else
1816                         link_free_space(block_group, entry);
1817         }
1818
1819 out:
1820         spin_unlock(&block_group->tree_lock);
1821
1822         return ret;
1823 }
1824
1825 /*
1826  * given a cluster, put all of its extents back into the free space
1827  * cache.  If a block group is passed, this function will only free
1828  * a cluster that belongs to the passed block group.
1829  *
1830  * Otherwise, it'll get a reference on the block group pointed to by the
1831  * cluster and remove the cluster from it.
1832  */
1833 int btrfs_return_cluster_to_free_space(
1834                                struct btrfs_block_group_cache *block_group,
1835                                struct btrfs_free_cluster *cluster)
1836 {
1837         int ret;
1838
1839         /* first, get a safe pointer to the block group */
1840         spin_lock(&cluster->lock);
1841         if (!block_group) {
1842                 block_group = cluster->block_group;
1843                 if (!block_group) {
1844                         spin_unlock(&cluster->lock);
1845                         return 0;
1846                 }
1847         } else if (cluster->block_group != block_group) {
1848                 /* someone else has already freed it don't redo their work */
1849                 spin_unlock(&cluster->lock);
1850                 return 0;
1851         }
1852         atomic_inc(&block_group->count);
1853         spin_unlock(&cluster->lock);
1854
1855         /* now return any extents the cluster had on it */
1856         spin_lock(&block_group->tree_lock);
1857         ret = __btrfs_return_cluster_to_free_space(block_group, cluster);
1858         spin_unlock(&block_group->tree_lock);
1859
1860         /* finally drop our ref */
1861         btrfs_put_block_group(block_group);
1862         return ret;
1863 }
1864
1865 static u64 btrfs_alloc_from_bitmap(struct btrfs_block_group_cache *block_group,
1866                                    struct btrfs_free_cluster *cluster,
1867                                    struct btrfs_free_space *entry,
1868                                    u64 bytes, u64 min_start)
1869 {
1870         int err;
1871         u64 search_start = cluster->window_start;
1872         u64 search_bytes = bytes;
1873         u64 ret = 0;
1874
1875         search_start = min_start;
1876         search_bytes = bytes;
1877
1878         err = search_bitmap(block_group, entry, &search_start,
1879                             &search_bytes);
1880         if (err)
1881                 return 0;
1882
1883         ret = search_start;
1884         bitmap_clear_bits(block_group, entry, ret, bytes);
1885
1886         return ret;
1887 }
1888
1889 /*
1890  * given a cluster, try to allocate 'bytes' from it, returns 0
1891  * if it couldn't find anything suitably large, or a logical disk offset
1892  * if things worked out
1893  */
1894 u64 btrfs_alloc_from_cluster(struct btrfs_block_group_cache *block_group,
1895                              struct btrfs_free_cluster *cluster, u64 bytes,
1896                              u64 min_start)
1897 {
1898         struct btrfs_free_space *entry = NULL;
1899         struct rb_node *node;
1900         u64 ret = 0;
1901
1902         spin_lock(&cluster->lock);
1903         if (bytes > cluster->max_size)
1904                 goto out;
1905
1906         if (cluster->block_group != block_group)
1907                 goto out;
1908
1909         node = rb_first(&cluster->root);
1910         if (!node)
1911                 goto out;
1912
1913         entry = rb_entry(node, struct btrfs_free_space, offset_index);
1914         while(1) {
1915                 if (entry->bytes < bytes ||
1916                     (!entry->bitmap && entry->offset < min_start)) {
1917                         struct rb_node *node;
1918
1919                         node = rb_next(&entry->offset_index);
1920                         if (!node)
1921                                 break;
1922                         entry = rb_entry(node, struct btrfs_free_space,
1923                                          offset_index);
1924                         continue;
1925                 }
1926
1927                 if (entry->bitmap) {
1928                         ret = btrfs_alloc_from_bitmap(block_group,
1929                                                       cluster, entry, bytes,
1930                                                       min_start);
1931                         if (ret == 0) {
1932                                 struct rb_node *node;
1933                                 node = rb_next(&entry->offset_index);
1934                                 if (!node)
1935                                         break;
1936                                 entry = rb_entry(node, struct btrfs_free_space,
1937                                                  offset_index);
1938                                 continue;
1939                         }
1940                 } else {
1941
1942                         ret = entry->offset;
1943
1944                         entry->offset += bytes;
1945                         entry->bytes -= bytes;
1946                 }
1947
1948                 if (entry->bytes == 0)
1949                         rb_erase(&entry->offset_index, &cluster->root);
1950                 break;
1951         }
1952 out:
1953         spin_unlock(&cluster->lock);
1954
1955         if (!ret)
1956                 return 0;
1957
1958         spin_lock(&block_group->tree_lock);
1959
1960         block_group->free_space -= bytes;
1961         if (entry->bytes == 0) {
1962                 block_group->free_extents--;
1963                 if (entry->bitmap) {
1964                         kfree(entry->bitmap);
1965                         block_group->total_bitmaps--;
1966                         recalculate_thresholds(block_group);
1967                 }
1968                 kmem_cache_free(btrfs_free_space_cachep, entry);
1969         }
1970
1971         spin_unlock(&block_group->tree_lock);
1972
1973         return ret;
1974 }
1975
1976 static int btrfs_bitmap_cluster(struct btrfs_block_group_cache *block_group,
1977                                 struct btrfs_free_space *entry,
1978                                 struct btrfs_free_cluster *cluster,
1979                                 u64 offset, u64 bytes, u64 min_bytes)
1980 {
1981         unsigned long next_zero;
1982         unsigned long i;
1983         unsigned long search_bits;
1984         unsigned long total_bits;
1985         unsigned long found_bits;
1986         unsigned long start = 0;
1987         unsigned long total_found = 0;
1988         int ret;
1989         bool found = false;
1990
1991         i = offset_to_bit(entry->offset, block_group->sectorsize,
1992                           max_t(u64, offset, entry->offset));
1993         search_bits = bytes_to_bits(bytes, block_group->sectorsize);
1994         total_bits = bytes_to_bits(min_bytes, block_group->sectorsize);
1995
1996 again:
1997         found_bits = 0;
1998         for (i = find_next_bit(entry->bitmap, BITS_PER_BITMAP, i);
1999              i < BITS_PER_BITMAP;
2000              i = find_next_bit(entry->bitmap, BITS_PER_BITMAP, i + 1)) {
2001                 next_zero = find_next_zero_bit(entry->bitmap,
2002                                                BITS_PER_BITMAP, i);
2003                 if (next_zero - i >= search_bits) {
2004                         found_bits = next_zero - i;
2005                         break;
2006                 }
2007                 i = next_zero;
2008         }
2009
2010         if (!found_bits)
2011                 return -ENOSPC;
2012
2013         if (!found) {
2014                 start = i;
2015                 found = true;
2016         }
2017
2018         total_found += found_bits;
2019
2020         if (cluster->max_size < found_bits * block_group->sectorsize)
2021                 cluster->max_size = found_bits * block_group->sectorsize;
2022
2023         if (total_found < total_bits) {
2024                 i = find_next_bit(entry->bitmap, BITS_PER_BITMAP, next_zero);
2025                 if (i - start > total_bits * 2) {
2026                         total_found = 0;
2027                         cluster->max_size = 0;
2028                         found = false;
2029                 }
2030                 goto again;
2031         }
2032
2033         cluster->window_start = start * block_group->sectorsize +
2034                 entry->offset;
2035         rb_erase(&entry->offset_index, &block_group->free_space_offset);
2036         ret = tree_insert_offset(&cluster->root, entry->offset,
2037                                  &entry->offset_index, 1);
2038         BUG_ON(ret);
2039
2040         return 0;
2041 }
2042
2043 /*
2044  * This searches the block group for just extents to fill the cluster with.
2045  */
2046 static int setup_cluster_no_bitmap(struct btrfs_block_group_cache *block_group,
2047                                    struct btrfs_free_cluster *cluster,
2048                                    u64 offset, u64 bytes, u64 min_bytes)
2049 {
2050         struct btrfs_free_space *first = NULL;
2051         struct btrfs_free_space *entry = NULL;
2052         struct btrfs_free_space *prev = NULL;
2053         struct btrfs_free_space *last;
2054         struct rb_node *node;
2055         u64 window_start;
2056         u64 window_free;
2057         u64 max_extent;
2058         u64 max_gap = 128 * 1024;
2059
2060         entry = tree_search_offset(block_group, offset, 0, 1);
2061         if (!entry)
2062                 return -ENOSPC;
2063
2064         /*
2065          * We don't want bitmaps, so just move along until we find a normal
2066          * extent entry.
2067          */
2068         while (entry->bitmap) {
2069                 node = rb_next(&entry->offset_index);
2070                 if (!node)
2071                         return -ENOSPC;
2072                 entry = rb_entry(node, struct btrfs_free_space, offset_index);
2073         }
2074
2075         window_start = entry->offset;
2076         window_free = entry->bytes;
2077         max_extent = entry->bytes;
2078         first = entry;
2079         last = entry;
2080         prev = entry;
2081
2082         while (window_free <= min_bytes) {
2083                 node = rb_next(&entry->offset_index);
2084                 if (!node)
2085                         return -ENOSPC;
2086                 entry = rb_entry(node, struct btrfs_free_space, offset_index);
2087
2088                 if (entry->bitmap)
2089                         continue;
2090                 /*
2091                  * we haven't filled the empty size and the window is
2092                  * very large.  reset and try again
2093                  */
2094                 if (entry->offset - (prev->offset + prev->bytes) > max_gap ||
2095                     entry->offset - window_start > (min_bytes * 2)) {
2096                         first = entry;
2097                         window_start = entry->offset;
2098                         window_free = entry->bytes;
2099                         last = entry;
2100                         max_extent = entry->bytes;
2101                 } else {
2102                         last = entry;
2103                         window_free += entry->bytes;
2104                         if (entry->bytes > max_extent)
2105                                 max_extent = entry->bytes;
2106                 }
2107                 prev = entry;
2108         }
2109
2110         cluster->window_start = first->offset;
2111
2112         node = &first->offset_index;
2113
2114         /*
2115          * now we've found our entries, pull them out of the free space
2116          * cache and put them into the cluster rbtree
2117          */
2118         do {
2119                 int ret;
2120
2121                 entry = rb_entry(node, struct btrfs_free_space, offset_index);
2122                 node = rb_next(&entry->offset_index);
2123                 if (entry->bitmap)
2124                         continue;
2125
2126                 rb_erase(&entry->offset_index, &block_group->free_space_offset);
2127                 ret = tree_insert_offset(&cluster->root, entry->offset,
2128                                          &entry->offset_index, 0);
2129                 BUG_ON(ret);
2130         } while (node && entry != last);
2131
2132         cluster->max_size = max_extent;
2133
2134         return 0;
2135 }
2136
2137 /*
2138  * This specifically looks for bitmaps that may work in the cluster, we assume
2139  * that we have already failed to find extents that will work.
2140  */
2141 static int setup_cluster_bitmap(struct btrfs_block_group_cache *block_group,
2142                                 struct btrfs_free_cluster *cluster,
2143                                 u64 offset, u64 bytes, u64 min_bytes)
2144 {
2145         struct btrfs_free_space *entry;
2146         struct rb_node *node;
2147         int ret = -ENOSPC;
2148
2149         if (block_group->total_bitmaps == 0)
2150                 return -ENOSPC;
2151
2152         entry = tree_search_offset(block_group,
2153                                    offset_to_bitmap(block_group, offset),
2154                                    0, 1);
2155         if (!entry)
2156                 return -ENOSPC;
2157
2158         node = &entry->offset_index;
2159         do {
2160                 entry = rb_entry(node, struct btrfs_free_space, offset_index);
2161                 node = rb_next(&entry->offset_index);
2162                 if (!entry->bitmap)
2163                         continue;
2164                 if (entry->bytes < min_bytes)
2165                         continue;
2166                 ret = btrfs_bitmap_cluster(block_group, entry, cluster, offset,
2167                                            bytes, min_bytes);
2168         } while (ret && node);
2169
2170         return ret;
2171 }
2172
2173 /*
2174  * here we try to find a cluster of blocks in a block group.  The goal
2175  * is to find at least bytes free and up to empty_size + bytes free.
2176  * We might not find them all in one contiguous area.
2177  *
2178  * returns zero and sets up cluster if things worked out, otherwise
2179  * it returns -enospc
2180  */
2181 int btrfs_find_space_cluster(struct btrfs_trans_handle *trans,
2182                              struct btrfs_root *root,
2183                              struct btrfs_block_group_cache *block_group,
2184                              struct btrfs_free_cluster *cluster,
2185                              u64 offset, u64 bytes, u64 empty_size)
2186 {
2187         u64 min_bytes;
2188         int ret;
2189
2190         /* for metadata, allow allocates with more holes */
2191         if (btrfs_test_opt(root, SSD_SPREAD)) {
2192                 min_bytes = bytes + empty_size;
2193         } else if (block_group->flags & BTRFS_BLOCK_GROUP_METADATA) {
2194                 /*
2195                  * we want to do larger allocations when we are
2196                  * flushing out the delayed refs, it helps prevent
2197                  * making more work as we go along.
2198                  */
2199                 if (trans->transaction->delayed_refs.flushing)
2200                         min_bytes = max(bytes, (bytes + empty_size) >> 1);
2201                 else
2202                         min_bytes = max(bytes, (bytes + empty_size) >> 4);
2203         } else
2204                 min_bytes = max(bytes, (bytes + empty_size) >> 2);
2205
2206         spin_lock(&block_group->tree_lock);
2207
2208         /*
2209          * If we know we don't have enough space to make a cluster don't even
2210          * bother doing all the work to try and find one.
2211          */
2212         if (block_group->free_space < min_bytes) {
2213                 spin_unlock(&block_group->tree_lock);
2214                 return -ENOSPC;
2215         }
2216
2217         spin_lock(&cluster->lock);
2218
2219         /* someone already found a cluster, hooray */
2220         if (cluster->block_group) {
2221                 ret = 0;
2222                 goto out;
2223         }
2224
2225         ret = setup_cluster_no_bitmap(block_group, cluster, offset, bytes,
2226                                       min_bytes);
2227         if (ret)
2228                 ret = setup_cluster_bitmap(block_group, cluster, offset,
2229                                            bytes, min_bytes);
2230
2231         if (!ret) {
2232                 atomic_inc(&block_group->count);
2233                 list_add_tail(&cluster->block_group_list,
2234                               &block_group->cluster_list);
2235                 cluster->block_group = block_group;
2236         }
2237 out:
2238         spin_unlock(&cluster->lock);
2239         spin_unlock(&block_group->tree_lock);
2240
2241         return ret;
2242 }
2243
2244 /*
2245  * simple code to zero out a cluster
2246  */
2247 void btrfs_init_free_cluster(struct btrfs_free_cluster *cluster)
2248 {
2249         spin_lock_init(&cluster->lock);
2250         spin_lock_init(&cluster->refill_lock);
2251         cluster->root = RB_ROOT;
2252         cluster->max_size = 0;
2253         INIT_LIST_HEAD(&cluster->block_group_list);
2254         cluster->block_group = NULL;
2255 }
2256
2257 int btrfs_trim_block_group(struct btrfs_block_group_cache *block_group,
2258                            u64 *trimmed, u64 start, u64 end, u64 minlen)
2259 {
2260         struct btrfs_free_space *entry = NULL;
2261         struct btrfs_fs_info *fs_info = block_group->fs_info;
2262         u64 bytes = 0;
2263         u64 actually_trimmed;
2264         int ret = 0;
2265
2266         *trimmed = 0;
2267
2268         while (start < end) {
2269                 spin_lock(&block_group->tree_lock);
2270
2271                 if (block_group->free_space < minlen) {
2272                         spin_unlock(&block_group->tree_lock);
2273                         break;
2274                 }
2275
2276                 entry = tree_search_offset(block_group, start, 0, 1);
2277                 if (!entry)
2278                         entry = tree_search_offset(block_group,
2279                                                    offset_to_bitmap(block_group,
2280                                                                     start),
2281                                                    1, 1);
2282
2283                 if (!entry || entry->offset >= end) {
2284                         spin_unlock(&block_group->tree_lock);
2285                         break;
2286                 }
2287
2288                 if (entry->bitmap) {
2289                         ret = search_bitmap(block_group, entry, &start, &bytes);
2290                         if (!ret) {
2291                                 if (start >= end) {
2292                                         spin_unlock(&block_group->tree_lock);
2293                                         break;
2294                                 }
2295                                 bytes = min(bytes, end - start);
2296                                 bitmap_clear_bits(block_group, entry,
2297                                                   start, bytes);
2298                                 if (entry->bytes == 0)
2299                                         free_bitmap(block_group, entry);
2300                         } else {
2301                                 start = entry->offset + BITS_PER_BITMAP *
2302                                         block_group->sectorsize;
2303                                 spin_unlock(&block_group->tree_lock);
2304                                 ret = 0;
2305                                 continue;
2306                         }
2307                 } else {
2308                         start = entry->offset;
2309                         bytes = min(entry->bytes, end - start);
2310                         unlink_free_space(block_group, entry);
2311                         kfree(entry);
2312                 }
2313
2314                 spin_unlock(&block_group->tree_lock);
2315
2316                 if (bytes >= minlen) {
2317                         int update_ret;
2318                         update_ret = btrfs_update_reserved_bytes(block_group,
2319                                                                  bytes, 1, 1);
2320
2321                         ret = btrfs_error_discard_extent(fs_info->extent_root,
2322                                                          start,
2323                                                          bytes,
2324                                                          &actually_trimmed);
2325
2326                         btrfs_add_free_space(block_group,
2327                                              start, bytes);
2328                         if (!update_ret)
2329                                 btrfs_update_reserved_bytes(block_group,
2330                                                             bytes, 0, 1);
2331
2332                         if (ret)
2333                                 break;
2334                         *trimmed += actually_trimmed;
2335                 }
2336                 start += bytes;
2337                 bytes = 0;
2338
2339                 if (fatal_signal_pending(current)) {
2340                         ret = -ERESTARTSYS;
2341                         break;
2342                 }
2343
2344                 cond_resched();
2345         }
2346
2347         return ret;
2348 }