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