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