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