Btrfs: two stage dirty block group writeout
[cascardo/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 <linux/ratelimit.h>
24 #include "ctree.h"
25 #include "free-space-cache.h"
26 #include "transaction.h"
27 #include "disk-io.h"
28 #include "extent_io.h"
29 #include "inode-map.h"
30 #include "volumes.h"
31
32 #define BITS_PER_BITMAP         (PAGE_CACHE_SIZE * 8)
33 #define MAX_CACHE_BYTES_PER_GIG (32 * 1024)
34
35 struct btrfs_trim_range {
36         u64 start;
37         u64 bytes;
38         struct list_head list;
39 };
40
41 static int link_free_space(struct btrfs_free_space_ctl *ctl,
42                            struct btrfs_free_space *info);
43 static void unlink_free_space(struct btrfs_free_space_ctl *ctl,
44                               struct btrfs_free_space *info);
45
46 static struct inode *__lookup_free_space_inode(struct btrfs_root *root,
47                                                struct btrfs_path *path,
48                                                u64 offset)
49 {
50         struct btrfs_key key;
51         struct btrfs_key location;
52         struct btrfs_disk_key disk_key;
53         struct btrfs_free_space_header *header;
54         struct extent_buffer *leaf;
55         struct inode *inode = NULL;
56         int ret;
57
58         key.objectid = BTRFS_FREE_SPACE_OBJECTID;
59         key.offset = offset;
60         key.type = 0;
61
62         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
63         if (ret < 0)
64                 return ERR_PTR(ret);
65         if (ret > 0) {
66                 btrfs_release_path(path);
67                 return ERR_PTR(-ENOENT);
68         }
69
70         leaf = path->nodes[0];
71         header = btrfs_item_ptr(leaf, path->slots[0],
72                                 struct btrfs_free_space_header);
73         btrfs_free_space_key(leaf, header, &disk_key);
74         btrfs_disk_key_to_cpu(&location, &disk_key);
75         btrfs_release_path(path);
76
77         inode = btrfs_iget(root->fs_info->sb, &location, root, NULL);
78         if (!inode)
79                 return ERR_PTR(-ENOENT);
80         if (IS_ERR(inode))
81                 return inode;
82         if (is_bad_inode(inode)) {
83                 iput(inode);
84                 return ERR_PTR(-ENOENT);
85         }
86
87         mapping_set_gfp_mask(inode->i_mapping,
88                         mapping_gfp_mask(inode->i_mapping) & ~__GFP_FS);
89
90         return inode;
91 }
92
93 struct inode *lookup_free_space_inode(struct btrfs_root *root,
94                                       struct btrfs_block_group_cache
95                                       *block_group, struct btrfs_path *path)
96 {
97         struct inode *inode = NULL;
98         u32 flags = BTRFS_INODE_NODATASUM | BTRFS_INODE_NODATACOW;
99
100         spin_lock(&block_group->lock);
101         if (block_group->inode)
102                 inode = igrab(block_group->inode);
103         spin_unlock(&block_group->lock);
104         if (inode)
105                 return inode;
106
107         inode = __lookup_free_space_inode(root, path,
108                                           block_group->key.objectid);
109         if (IS_ERR(inode))
110                 return inode;
111
112         spin_lock(&block_group->lock);
113         if (!((BTRFS_I(inode)->flags & flags) == flags)) {
114                 btrfs_info(root->fs_info,
115                         "Old style space inode found, converting.");
116                 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM |
117                         BTRFS_INODE_NODATACOW;
118                 block_group->disk_cache_state = BTRFS_DC_CLEAR;
119         }
120
121         if (!block_group->iref) {
122                 block_group->inode = igrab(inode);
123                 block_group->iref = 1;
124         }
125         spin_unlock(&block_group->lock);
126
127         return inode;
128 }
129
130 static int __create_free_space_inode(struct btrfs_root *root,
131                                      struct btrfs_trans_handle *trans,
132                                      struct btrfs_path *path,
133                                      u64 ino, u64 offset)
134 {
135         struct btrfs_key key;
136         struct btrfs_disk_key disk_key;
137         struct btrfs_free_space_header *header;
138         struct btrfs_inode_item *inode_item;
139         struct extent_buffer *leaf;
140         u64 flags = BTRFS_INODE_NOCOMPRESS | BTRFS_INODE_PREALLOC;
141         int ret;
142
143         ret = btrfs_insert_empty_inode(trans, root, path, ino);
144         if (ret)
145                 return ret;
146
147         /* We inline crc's for the free disk space cache */
148         if (ino != BTRFS_FREE_INO_OBJECTID)
149                 flags |= BTRFS_INODE_NODATASUM | BTRFS_INODE_NODATACOW;
150
151         leaf = path->nodes[0];
152         inode_item = btrfs_item_ptr(leaf, path->slots[0],
153                                     struct btrfs_inode_item);
154         btrfs_item_key(leaf, &disk_key, path->slots[0]);
155         memset_extent_buffer(leaf, 0, (unsigned long)inode_item,
156                              sizeof(*inode_item));
157         btrfs_set_inode_generation(leaf, inode_item, trans->transid);
158         btrfs_set_inode_size(leaf, inode_item, 0);
159         btrfs_set_inode_nbytes(leaf, inode_item, 0);
160         btrfs_set_inode_uid(leaf, inode_item, 0);
161         btrfs_set_inode_gid(leaf, inode_item, 0);
162         btrfs_set_inode_mode(leaf, inode_item, S_IFREG | 0600);
163         btrfs_set_inode_flags(leaf, inode_item, flags);
164         btrfs_set_inode_nlink(leaf, inode_item, 1);
165         btrfs_set_inode_transid(leaf, inode_item, trans->transid);
166         btrfs_set_inode_block_group(leaf, inode_item, offset);
167         btrfs_mark_buffer_dirty(leaf);
168         btrfs_release_path(path);
169
170         key.objectid = BTRFS_FREE_SPACE_OBJECTID;
171         key.offset = offset;
172         key.type = 0;
173         ret = btrfs_insert_empty_item(trans, root, path, &key,
174                                       sizeof(struct btrfs_free_space_header));
175         if (ret < 0) {
176                 btrfs_release_path(path);
177                 return ret;
178         }
179
180         leaf = path->nodes[0];
181         header = btrfs_item_ptr(leaf, path->slots[0],
182                                 struct btrfs_free_space_header);
183         memset_extent_buffer(leaf, 0, (unsigned long)header, sizeof(*header));
184         btrfs_set_free_space_key(leaf, header, &disk_key);
185         btrfs_mark_buffer_dirty(leaf);
186         btrfs_release_path(path);
187
188         return 0;
189 }
190
191 int create_free_space_inode(struct btrfs_root *root,
192                             struct btrfs_trans_handle *trans,
193                             struct btrfs_block_group_cache *block_group,
194                             struct btrfs_path *path)
195 {
196         int ret;
197         u64 ino;
198
199         ret = btrfs_find_free_objectid(root, &ino);
200         if (ret < 0)
201                 return ret;
202
203         return __create_free_space_inode(root, trans, path, ino,
204                                          block_group->key.objectid);
205 }
206
207 int btrfs_check_trunc_cache_free_space(struct btrfs_root *root,
208                                        struct btrfs_block_rsv *rsv)
209 {
210         u64 needed_bytes;
211         int ret;
212
213         /* 1 for slack space, 1 for updating the inode */
214         needed_bytes = btrfs_calc_trunc_metadata_size(root, 1) +
215                 btrfs_calc_trans_metadata_size(root, 1);
216
217         spin_lock(&rsv->lock);
218         if (rsv->reserved < needed_bytes)
219                 ret = -ENOSPC;
220         else
221                 ret = 0;
222         spin_unlock(&rsv->lock);
223         return ret;
224 }
225
226 int btrfs_truncate_free_space_cache(struct btrfs_root *root,
227                                     struct btrfs_trans_handle *trans,
228                                     struct inode *inode)
229 {
230         int ret = 0;
231
232         btrfs_i_size_write(inode, 0);
233         truncate_pagecache(inode, 0);
234
235         /*
236          * We don't need an orphan item because truncating the free space cache
237          * will never be split across transactions.
238          * We don't need to check for -EAGAIN because we're a free space
239          * cache inode
240          */
241         ret = btrfs_truncate_inode_items(trans, root, inode,
242                                          0, BTRFS_EXTENT_DATA_KEY);
243         if (ret) {
244                 btrfs_abort_transaction(trans, root, ret);
245                 return ret;
246         }
247
248         ret = btrfs_update_inode(trans, root, inode);
249         if (ret)
250                 btrfs_abort_transaction(trans, root, ret);
251
252         return ret;
253 }
254
255 static int readahead_cache(struct inode *inode)
256 {
257         struct file_ra_state *ra;
258         unsigned long last_index;
259
260         ra = kzalloc(sizeof(*ra), GFP_NOFS);
261         if (!ra)
262                 return -ENOMEM;
263
264         file_ra_state_init(ra, inode->i_mapping);
265         last_index = (i_size_read(inode) - 1) >> PAGE_CACHE_SHIFT;
266
267         page_cache_sync_readahead(inode->i_mapping, ra, NULL, 0, last_index);
268
269         kfree(ra);
270
271         return 0;
272 }
273
274 static int io_ctl_init(struct btrfs_io_ctl *io_ctl, struct inode *inode,
275                        struct btrfs_root *root, int write)
276 {
277         int num_pages;
278         int check_crcs = 0;
279
280         num_pages = DIV_ROUND_UP(i_size_read(inode), PAGE_CACHE_SIZE);
281
282         if (btrfs_ino(inode) != BTRFS_FREE_INO_OBJECTID)
283                 check_crcs = 1;
284
285         /* Make sure we can fit our crcs into the first page */
286         if (write && check_crcs &&
287             (num_pages * sizeof(u32)) >= PAGE_CACHE_SIZE)
288                 return -ENOSPC;
289
290         memset(io_ctl, 0, sizeof(struct btrfs_io_ctl));
291
292         io_ctl->pages = kcalloc(num_pages, sizeof(struct page *), GFP_NOFS);
293         if (!io_ctl->pages)
294                 return -ENOMEM;
295
296         io_ctl->num_pages = num_pages;
297         io_ctl->root = root;
298         io_ctl->check_crcs = check_crcs;
299         io_ctl->inode = inode;
300
301         return 0;
302 }
303
304 static void io_ctl_free(struct btrfs_io_ctl *io_ctl)
305 {
306         kfree(io_ctl->pages);
307         io_ctl->pages = NULL;
308 }
309
310 static void io_ctl_unmap_page(struct btrfs_io_ctl *io_ctl)
311 {
312         if (io_ctl->cur) {
313                 kunmap(io_ctl->page);
314                 io_ctl->cur = NULL;
315                 io_ctl->orig = NULL;
316         }
317 }
318
319 static void io_ctl_map_page(struct btrfs_io_ctl *io_ctl, int clear)
320 {
321         ASSERT(io_ctl->index < io_ctl->num_pages);
322         io_ctl->page = io_ctl->pages[io_ctl->index++];
323         io_ctl->cur = kmap(io_ctl->page);
324         io_ctl->orig = io_ctl->cur;
325         io_ctl->size = PAGE_CACHE_SIZE;
326         if (clear)
327                 memset(io_ctl->cur, 0, PAGE_CACHE_SIZE);
328 }
329
330 static void io_ctl_drop_pages(struct btrfs_io_ctl *io_ctl)
331 {
332         int i;
333
334         io_ctl_unmap_page(io_ctl);
335
336         for (i = 0; i < io_ctl->num_pages; i++) {
337                 if (io_ctl->pages[i]) {
338                         ClearPageChecked(io_ctl->pages[i]);
339                         unlock_page(io_ctl->pages[i]);
340                         page_cache_release(io_ctl->pages[i]);
341                 }
342         }
343 }
344
345 static int io_ctl_prepare_pages(struct btrfs_io_ctl *io_ctl, struct inode *inode,
346                                 int uptodate)
347 {
348         struct page *page;
349         gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
350         int i;
351
352         for (i = 0; i < io_ctl->num_pages; i++) {
353                 page = find_or_create_page(inode->i_mapping, i, mask);
354                 if (!page) {
355                         io_ctl_drop_pages(io_ctl);
356                         return -ENOMEM;
357                 }
358                 io_ctl->pages[i] = page;
359                 if (uptodate && !PageUptodate(page)) {
360                         btrfs_readpage(NULL, page);
361                         lock_page(page);
362                         if (!PageUptodate(page)) {
363                                 btrfs_err(BTRFS_I(inode)->root->fs_info,
364                                            "error reading free space cache");
365                                 io_ctl_drop_pages(io_ctl);
366                                 return -EIO;
367                         }
368                 }
369         }
370
371         for (i = 0; i < io_ctl->num_pages; i++) {
372                 clear_page_dirty_for_io(io_ctl->pages[i]);
373                 set_page_extent_mapped(io_ctl->pages[i]);
374         }
375
376         return 0;
377 }
378
379 static void io_ctl_set_generation(struct btrfs_io_ctl *io_ctl, u64 generation)
380 {
381         __le64 *val;
382
383         io_ctl_map_page(io_ctl, 1);
384
385         /*
386          * Skip the csum areas.  If we don't check crcs then we just have a
387          * 64bit chunk at the front of the first page.
388          */
389         if (io_ctl->check_crcs) {
390                 io_ctl->cur += (sizeof(u32) * io_ctl->num_pages);
391                 io_ctl->size -= sizeof(u64) + (sizeof(u32) * io_ctl->num_pages);
392         } else {
393                 io_ctl->cur += sizeof(u64);
394                 io_ctl->size -= sizeof(u64) * 2;
395         }
396
397         val = io_ctl->cur;
398         *val = cpu_to_le64(generation);
399         io_ctl->cur += sizeof(u64);
400 }
401
402 static int io_ctl_check_generation(struct btrfs_io_ctl *io_ctl, u64 generation)
403 {
404         __le64 *gen;
405
406         /*
407          * Skip the crc area.  If we don't check crcs then we just have a 64bit
408          * chunk at the front of the first page.
409          */
410         if (io_ctl->check_crcs) {
411                 io_ctl->cur += sizeof(u32) * io_ctl->num_pages;
412                 io_ctl->size -= sizeof(u64) +
413                         (sizeof(u32) * io_ctl->num_pages);
414         } else {
415                 io_ctl->cur += sizeof(u64);
416                 io_ctl->size -= sizeof(u64) * 2;
417         }
418
419         gen = io_ctl->cur;
420         if (le64_to_cpu(*gen) != generation) {
421                 printk_ratelimited(KERN_ERR "BTRFS: space cache generation "
422                                    "(%Lu) does not match inode (%Lu)\n", *gen,
423                                    generation);
424                 io_ctl_unmap_page(io_ctl);
425                 return -EIO;
426         }
427         io_ctl->cur += sizeof(u64);
428         return 0;
429 }
430
431 static void io_ctl_set_crc(struct btrfs_io_ctl *io_ctl, int index)
432 {
433         u32 *tmp;
434         u32 crc = ~(u32)0;
435         unsigned offset = 0;
436
437         if (!io_ctl->check_crcs) {
438                 io_ctl_unmap_page(io_ctl);
439                 return;
440         }
441
442         if (index == 0)
443                 offset = sizeof(u32) * io_ctl->num_pages;
444
445         crc = btrfs_csum_data(io_ctl->orig + offset, crc,
446                               PAGE_CACHE_SIZE - offset);
447         btrfs_csum_final(crc, (char *)&crc);
448         io_ctl_unmap_page(io_ctl);
449         tmp = kmap(io_ctl->pages[0]);
450         tmp += index;
451         *tmp = crc;
452         kunmap(io_ctl->pages[0]);
453 }
454
455 static int io_ctl_check_crc(struct btrfs_io_ctl *io_ctl, int index)
456 {
457         u32 *tmp, val;
458         u32 crc = ~(u32)0;
459         unsigned offset = 0;
460
461         if (!io_ctl->check_crcs) {
462                 io_ctl_map_page(io_ctl, 0);
463                 return 0;
464         }
465
466         if (index == 0)
467                 offset = sizeof(u32) * io_ctl->num_pages;
468
469         tmp = kmap(io_ctl->pages[0]);
470         tmp += index;
471         val = *tmp;
472         kunmap(io_ctl->pages[0]);
473
474         io_ctl_map_page(io_ctl, 0);
475         crc = btrfs_csum_data(io_ctl->orig + offset, crc,
476                               PAGE_CACHE_SIZE - offset);
477         btrfs_csum_final(crc, (char *)&crc);
478         if (val != crc) {
479                 printk_ratelimited(KERN_ERR "BTRFS: csum mismatch on free "
480                                    "space cache\n");
481                 io_ctl_unmap_page(io_ctl);
482                 return -EIO;
483         }
484
485         return 0;
486 }
487
488 static int io_ctl_add_entry(struct btrfs_io_ctl *io_ctl, u64 offset, u64 bytes,
489                             void *bitmap)
490 {
491         struct btrfs_free_space_entry *entry;
492
493         if (!io_ctl->cur)
494                 return -ENOSPC;
495
496         entry = io_ctl->cur;
497         entry->offset = cpu_to_le64(offset);
498         entry->bytes = cpu_to_le64(bytes);
499         entry->type = (bitmap) ? BTRFS_FREE_SPACE_BITMAP :
500                 BTRFS_FREE_SPACE_EXTENT;
501         io_ctl->cur += sizeof(struct btrfs_free_space_entry);
502         io_ctl->size -= sizeof(struct btrfs_free_space_entry);
503
504         if (io_ctl->size >= sizeof(struct btrfs_free_space_entry))
505                 return 0;
506
507         io_ctl_set_crc(io_ctl, io_ctl->index - 1);
508
509         /* No more pages to map */
510         if (io_ctl->index >= io_ctl->num_pages)
511                 return 0;
512
513         /* map the next page */
514         io_ctl_map_page(io_ctl, 1);
515         return 0;
516 }
517
518 static int io_ctl_add_bitmap(struct btrfs_io_ctl *io_ctl, void *bitmap)
519 {
520         if (!io_ctl->cur)
521                 return -ENOSPC;
522
523         /*
524          * If we aren't at the start of the current page, unmap this one and
525          * map the next one if there is any left.
526          */
527         if (io_ctl->cur != io_ctl->orig) {
528                 io_ctl_set_crc(io_ctl, io_ctl->index - 1);
529                 if (io_ctl->index >= io_ctl->num_pages)
530                         return -ENOSPC;
531                 io_ctl_map_page(io_ctl, 0);
532         }
533
534         memcpy(io_ctl->cur, bitmap, PAGE_CACHE_SIZE);
535         io_ctl_set_crc(io_ctl, io_ctl->index - 1);
536         if (io_ctl->index < io_ctl->num_pages)
537                 io_ctl_map_page(io_ctl, 0);
538         return 0;
539 }
540
541 static void io_ctl_zero_remaining_pages(struct btrfs_io_ctl *io_ctl)
542 {
543         /*
544          * If we're not on the boundary we know we've modified the page and we
545          * need to crc the page.
546          */
547         if (io_ctl->cur != io_ctl->orig)
548                 io_ctl_set_crc(io_ctl, io_ctl->index - 1);
549         else
550                 io_ctl_unmap_page(io_ctl);
551
552         while (io_ctl->index < io_ctl->num_pages) {
553                 io_ctl_map_page(io_ctl, 1);
554                 io_ctl_set_crc(io_ctl, io_ctl->index - 1);
555         }
556 }
557
558 static int io_ctl_read_entry(struct btrfs_io_ctl *io_ctl,
559                             struct btrfs_free_space *entry, u8 *type)
560 {
561         struct btrfs_free_space_entry *e;
562         int ret;
563
564         if (!io_ctl->cur) {
565                 ret = io_ctl_check_crc(io_ctl, io_ctl->index);
566                 if (ret)
567                         return ret;
568         }
569
570         e = io_ctl->cur;
571         entry->offset = le64_to_cpu(e->offset);
572         entry->bytes = le64_to_cpu(e->bytes);
573         *type = e->type;
574         io_ctl->cur += sizeof(struct btrfs_free_space_entry);
575         io_ctl->size -= sizeof(struct btrfs_free_space_entry);
576
577         if (io_ctl->size >= sizeof(struct btrfs_free_space_entry))
578                 return 0;
579
580         io_ctl_unmap_page(io_ctl);
581
582         return 0;
583 }
584
585 static int io_ctl_read_bitmap(struct btrfs_io_ctl *io_ctl,
586                               struct btrfs_free_space *entry)
587 {
588         int ret;
589
590         ret = io_ctl_check_crc(io_ctl, io_ctl->index);
591         if (ret)
592                 return ret;
593
594         memcpy(entry->bitmap, io_ctl->cur, PAGE_CACHE_SIZE);
595         io_ctl_unmap_page(io_ctl);
596
597         return 0;
598 }
599
600 /*
601  * Since we attach pinned extents after the fact we can have contiguous sections
602  * of free space that are split up in entries.  This poses a problem with the
603  * tree logging stuff since it could have allocated across what appears to be 2
604  * entries since we would have merged the entries when adding the pinned extents
605  * back to the free space cache.  So run through the space cache that we just
606  * loaded and merge contiguous entries.  This will make the log replay stuff not
607  * blow up and it will make for nicer allocator behavior.
608  */
609 static void merge_space_tree(struct btrfs_free_space_ctl *ctl)
610 {
611         struct btrfs_free_space *e, *prev = NULL;
612         struct rb_node *n;
613
614 again:
615         spin_lock(&ctl->tree_lock);
616         for (n = rb_first(&ctl->free_space_offset); n; n = rb_next(n)) {
617                 e = rb_entry(n, struct btrfs_free_space, offset_index);
618                 if (!prev)
619                         goto next;
620                 if (e->bitmap || prev->bitmap)
621                         goto next;
622                 if (prev->offset + prev->bytes == e->offset) {
623                         unlink_free_space(ctl, prev);
624                         unlink_free_space(ctl, e);
625                         prev->bytes += e->bytes;
626                         kmem_cache_free(btrfs_free_space_cachep, e);
627                         link_free_space(ctl, prev);
628                         prev = NULL;
629                         spin_unlock(&ctl->tree_lock);
630                         goto again;
631                 }
632 next:
633                 prev = e;
634         }
635         spin_unlock(&ctl->tree_lock);
636 }
637
638 static int __load_free_space_cache(struct btrfs_root *root, struct inode *inode,
639                                    struct btrfs_free_space_ctl *ctl,
640                                    struct btrfs_path *path, u64 offset)
641 {
642         struct btrfs_free_space_header *header;
643         struct extent_buffer *leaf;
644         struct btrfs_io_ctl io_ctl;
645         struct btrfs_key key;
646         struct btrfs_free_space *e, *n;
647         LIST_HEAD(bitmaps);
648         u64 num_entries;
649         u64 num_bitmaps;
650         u64 generation;
651         u8 type;
652         int ret = 0;
653
654         /* Nothing in the space cache, goodbye */
655         if (!i_size_read(inode))
656                 return 0;
657
658         key.objectid = BTRFS_FREE_SPACE_OBJECTID;
659         key.offset = offset;
660         key.type = 0;
661
662         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
663         if (ret < 0)
664                 return 0;
665         else if (ret > 0) {
666                 btrfs_release_path(path);
667                 return 0;
668         }
669
670         ret = -1;
671
672         leaf = path->nodes[0];
673         header = btrfs_item_ptr(leaf, path->slots[0],
674                                 struct btrfs_free_space_header);
675         num_entries = btrfs_free_space_entries(leaf, header);
676         num_bitmaps = btrfs_free_space_bitmaps(leaf, header);
677         generation = btrfs_free_space_generation(leaf, header);
678         btrfs_release_path(path);
679
680         if (!BTRFS_I(inode)->generation) {
681                 btrfs_info(root->fs_info,
682                            "The free space cache file (%llu) is invalid. skip it\n",
683                            offset);
684                 return 0;
685         }
686
687         if (BTRFS_I(inode)->generation != generation) {
688                 btrfs_err(root->fs_info,
689                         "free space inode generation (%llu) "
690                         "did not match free space cache generation (%llu)",
691                         BTRFS_I(inode)->generation, generation);
692                 return 0;
693         }
694
695         if (!num_entries)
696                 return 0;
697
698         ret = io_ctl_init(&io_ctl, inode, root, 0);
699         if (ret)
700                 return ret;
701
702         ret = readahead_cache(inode);
703         if (ret)
704                 goto out;
705
706         ret = io_ctl_prepare_pages(&io_ctl, inode, 1);
707         if (ret)
708                 goto out;
709
710         ret = io_ctl_check_crc(&io_ctl, 0);
711         if (ret)
712                 goto free_cache;
713
714         ret = io_ctl_check_generation(&io_ctl, generation);
715         if (ret)
716                 goto free_cache;
717
718         while (num_entries) {
719                 e = kmem_cache_zalloc(btrfs_free_space_cachep,
720                                       GFP_NOFS);
721                 if (!e)
722                         goto free_cache;
723
724                 ret = io_ctl_read_entry(&io_ctl, e, &type);
725                 if (ret) {
726                         kmem_cache_free(btrfs_free_space_cachep, e);
727                         goto free_cache;
728                 }
729
730                 if (!e->bytes) {
731                         kmem_cache_free(btrfs_free_space_cachep, e);
732                         goto free_cache;
733                 }
734
735                 if (type == BTRFS_FREE_SPACE_EXTENT) {
736                         spin_lock(&ctl->tree_lock);
737                         ret = link_free_space(ctl, e);
738                         spin_unlock(&ctl->tree_lock);
739                         if (ret) {
740                                 btrfs_err(root->fs_info,
741                                         "Duplicate entries in free space cache, dumping");
742                                 kmem_cache_free(btrfs_free_space_cachep, e);
743                                 goto free_cache;
744                         }
745                 } else {
746                         ASSERT(num_bitmaps);
747                         num_bitmaps--;
748                         e->bitmap = kzalloc(PAGE_CACHE_SIZE, GFP_NOFS);
749                         if (!e->bitmap) {
750                                 kmem_cache_free(
751                                         btrfs_free_space_cachep, e);
752                                 goto free_cache;
753                         }
754                         spin_lock(&ctl->tree_lock);
755                         ret = link_free_space(ctl, e);
756                         ctl->total_bitmaps++;
757                         ctl->op->recalc_thresholds(ctl);
758                         spin_unlock(&ctl->tree_lock);
759                         if (ret) {
760                                 btrfs_err(root->fs_info,
761                                         "Duplicate entries in free space cache, dumping");
762                                 kmem_cache_free(btrfs_free_space_cachep, e);
763                                 goto free_cache;
764                         }
765                         list_add_tail(&e->list, &bitmaps);
766                 }
767
768                 num_entries--;
769         }
770
771         io_ctl_unmap_page(&io_ctl);
772
773         /*
774          * We add the bitmaps at the end of the entries in order that
775          * the bitmap entries are added to the cache.
776          */
777         list_for_each_entry_safe(e, n, &bitmaps, list) {
778                 list_del_init(&e->list);
779                 ret = io_ctl_read_bitmap(&io_ctl, e);
780                 if (ret)
781                         goto free_cache;
782         }
783
784         io_ctl_drop_pages(&io_ctl);
785         merge_space_tree(ctl);
786         ret = 1;
787 out:
788         io_ctl_free(&io_ctl);
789         return ret;
790 free_cache:
791         io_ctl_drop_pages(&io_ctl);
792         __btrfs_remove_free_space_cache(ctl);
793         goto out;
794 }
795
796 int load_free_space_cache(struct btrfs_fs_info *fs_info,
797                           struct btrfs_block_group_cache *block_group)
798 {
799         struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
800         struct btrfs_root *root = fs_info->tree_root;
801         struct inode *inode;
802         struct btrfs_path *path;
803         int ret = 0;
804         bool matched;
805         u64 used = btrfs_block_group_used(&block_group->item);
806
807         /*
808          * If this block group has been marked to be cleared for one reason or
809          * another then we can't trust the on disk cache, so just return.
810          */
811         spin_lock(&block_group->lock);
812         if (block_group->disk_cache_state != BTRFS_DC_WRITTEN) {
813                 spin_unlock(&block_group->lock);
814                 return 0;
815         }
816         spin_unlock(&block_group->lock);
817
818         path = btrfs_alloc_path();
819         if (!path)
820                 return 0;
821         path->search_commit_root = 1;
822         path->skip_locking = 1;
823
824         inode = lookup_free_space_inode(root, block_group, path);
825         if (IS_ERR(inode)) {
826                 btrfs_free_path(path);
827                 return 0;
828         }
829
830         /* We may have converted the inode and made the cache invalid. */
831         spin_lock(&block_group->lock);
832         if (block_group->disk_cache_state != BTRFS_DC_WRITTEN) {
833                 spin_unlock(&block_group->lock);
834                 btrfs_free_path(path);
835                 goto out;
836         }
837         spin_unlock(&block_group->lock);
838
839         ret = __load_free_space_cache(fs_info->tree_root, inode, ctl,
840                                       path, block_group->key.objectid);
841         btrfs_free_path(path);
842         if (ret <= 0)
843                 goto out;
844
845         spin_lock(&ctl->tree_lock);
846         matched = (ctl->free_space == (block_group->key.offset - used -
847                                        block_group->bytes_super));
848         spin_unlock(&ctl->tree_lock);
849
850         if (!matched) {
851                 __btrfs_remove_free_space_cache(ctl);
852                 btrfs_warn(fs_info, "block group %llu has wrong amount of free space",
853                         block_group->key.objectid);
854                 ret = -1;
855         }
856 out:
857         if (ret < 0) {
858                 /* This cache is bogus, make sure it gets cleared */
859                 spin_lock(&block_group->lock);
860                 block_group->disk_cache_state = BTRFS_DC_CLEAR;
861                 spin_unlock(&block_group->lock);
862                 ret = 0;
863
864                 btrfs_warn(fs_info, "failed to load free space cache for block group %llu, rebuild it now",
865                         block_group->key.objectid);
866         }
867
868         iput(inode);
869         return ret;
870 }
871
872 static noinline_for_stack
873 int write_cache_extent_entries(struct btrfs_io_ctl *io_ctl,
874                               struct btrfs_free_space_ctl *ctl,
875                               struct btrfs_block_group_cache *block_group,
876                               int *entries, int *bitmaps,
877                               struct list_head *bitmap_list)
878 {
879         int ret;
880         struct btrfs_free_cluster *cluster = NULL;
881         struct rb_node *node = rb_first(&ctl->free_space_offset);
882         struct btrfs_trim_range *trim_entry;
883
884         /* Get the cluster for this block_group if it exists */
885         if (block_group && !list_empty(&block_group->cluster_list)) {
886                 cluster = list_entry(block_group->cluster_list.next,
887                                      struct btrfs_free_cluster,
888                                      block_group_list);
889         }
890
891         if (!node && cluster) {
892                 node = rb_first(&cluster->root);
893                 cluster = NULL;
894         }
895
896         /* Write out the extent entries */
897         while (node) {
898                 struct btrfs_free_space *e;
899
900                 e = rb_entry(node, struct btrfs_free_space, offset_index);
901                 *entries += 1;
902
903                 ret = io_ctl_add_entry(io_ctl, e->offset, e->bytes,
904                                        e->bitmap);
905                 if (ret)
906                         goto fail;
907
908                 if (e->bitmap) {
909                         list_add_tail(&e->list, bitmap_list);
910                         *bitmaps += 1;
911                 }
912                 node = rb_next(node);
913                 if (!node && cluster) {
914                         node = rb_first(&cluster->root);
915                         cluster = NULL;
916                 }
917         }
918
919         /*
920          * Make sure we don't miss any range that was removed from our rbtree
921          * because trimming is running. Otherwise after a umount+mount (or crash
922          * after committing the transaction) we would leak free space and get
923          * an inconsistent free space cache report from fsck.
924          */
925         list_for_each_entry(trim_entry, &ctl->trimming_ranges, list) {
926                 ret = io_ctl_add_entry(io_ctl, trim_entry->start,
927                                        trim_entry->bytes, NULL);
928                 if (ret)
929                         goto fail;
930                 *entries += 1;
931         }
932
933         return 0;
934 fail:
935         return -ENOSPC;
936 }
937
938 static noinline_for_stack int
939 update_cache_item(struct btrfs_trans_handle *trans,
940                   struct btrfs_root *root,
941                   struct inode *inode,
942                   struct btrfs_path *path, u64 offset,
943                   int entries, int bitmaps)
944 {
945         struct btrfs_key key;
946         struct btrfs_free_space_header *header;
947         struct extent_buffer *leaf;
948         int ret;
949
950         key.objectid = BTRFS_FREE_SPACE_OBJECTID;
951         key.offset = offset;
952         key.type = 0;
953
954         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
955         if (ret < 0) {
956                 clear_extent_bit(&BTRFS_I(inode)->io_tree, 0, inode->i_size - 1,
957                                  EXTENT_DIRTY | EXTENT_DELALLOC, 0, 0, NULL,
958                                  GFP_NOFS);
959                 goto fail;
960         }
961         leaf = path->nodes[0];
962         if (ret > 0) {
963                 struct btrfs_key found_key;
964                 ASSERT(path->slots[0]);
965                 path->slots[0]--;
966                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
967                 if (found_key.objectid != BTRFS_FREE_SPACE_OBJECTID ||
968                     found_key.offset != offset) {
969                         clear_extent_bit(&BTRFS_I(inode)->io_tree, 0,
970                                          inode->i_size - 1,
971                                          EXTENT_DIRTY | EXTENT_DELALLOC, 0, 0,
972                                          NULL, GFP_NOFS);
973                         btrfs_release_path(path);
974                         goto fail;
975                 }
976         }
977
978         BTRFS_I(inode)->generation = trans->transid;
979         header = btrfs_item_ptr(leaf, path->slots[0],
980                                 struct btrfs_free_space_header);
981         btrfs_set_free_space_entries(leaf, header, entries);
982         btrfs_set_free_space_bitmaps(leaf, header, bitmaps);
983         btrfs_set_free_space_generation(leaf, header, trans->transid);
984         btrfs_mark_buffer_dirty(leaf);
985         btrfs_release_path(path);
986
987         return 0;
988
989 fail:
990         return -1;
991 }
992
993 static noinline_for_stack int
994 write_pinned_extent_entries(struct btrfs_root *root,
995                             struct btrfs_block_group_cache *block_group,
996                             struct btrfs_io_ctl *io_ctl,
997                             int *entries)
998 {
999         u64 start, extent_start, extent_end, len;
1000         struct extent_io_tree *unpin = NULL;
1001         int ret;
1002
1003         if (!block_group)
1004                 return 0;
1005
1006         /*
1007          * We want to add any pinned extents to our free space cache
1008          * so we don't leak the space
1009          *
1010          * We shouldn't have switched the pinned extents yet so this is the
1011          * right one
1012          */
1013         unpin = root->fs_info->pinned_extents;
1014
1015         start = block_group->key.objectid;
1016
1017         while (start < block_group->key.objectid + block_group->key.offset) {
1018                 ret = find_first_extent_bit(unpin, start,
1019                                             &extent_start, &extent_end,
1020                                             EXTENT_DIRTY, NULL);
1021                 if (ret)
1022                         return 0;
1023
1024                 /* This pinned extent is out of our range */
1025                 if (extent_start >= block_group->key.objectid +
1026                     block_group->key.offset)
1027                         return 0;
1028
1029                 extent_start = max(extent_start, start);
1030                 extent_end = min(block_group->key.objectid +
1031                                  block_group->key.offset, extent_end + 1);
1032                 len = extent_end - extent_start;
1033
1034                 *entries += 1;
1035                 ret = io_ctl_add_entry(io_ctl, extent_start, len, NULL);
1036                 if (ret)
1037                         return -ENOSPC;
1038
1039                 start = extent_end;
1040         }
1041
1042         return 0;
1043 }
1044
1045 static noinline_for_stack int
1046 write_bitmap_entries(struct btrfs_io_ctl *io_ctl, struct list_head *bitmap_list)
1047 {
1048         struct list_head *pos, *n;
1049         int ret;
1050
1051         /* Write out the bitmaps */
1052         list_for_each_safe(pos, n, bitmap_list) {
1053                 struct btrfs_free_space *entry =
1054                         list_entry(pos, struct btrfs_free_space, list);
1055
1056                 ret = io_ctl_add_bitmap(io_ctl, entry->bitmap);
1057                 if (ret)
1058                         return -ENOSPC;
1059                 list_del_init(&entry->list);
1060         }
1061
1062         return 0;
1063 }
1064
1065 static int flush_dirty_cache(struct inode *inode)
1066 {
1067         int ret;
1068
1069         ret = btrfs_wait_ordered_range(inode, 0, (u64)-1);
1070         if (ret)
1071                 clear_extent_bit(&BTRFS_I(inode)->io_tree, 0, inode->i_size - 1,
1072                                  EXTENT_DIRTY | EXTENT_DELALLOC, 0, 0, NULL,
1073                                  GFP_NOFS);
1074
1075         return ret;
1076 }
1077
1078 static void noinline_for_stack
1079 cleanup_write_cache_enospc(struct inode *inode,
1080                            struct btrfs_io_ctl *io_ctl,
1081                            struct extent_state **cached_state,
1082                            struct list_head *bitmap_list)
1083 {
1084         struct list_head *pos, *n;
1085
1086         list_for_each_safe(pos, n, bitmap_list) {
1087                 struct btrfs_free_space *entry =
1088                         list_entry(pos, struct btrfs_free_space, list);
1089                 list_del_init(&entry->list);
1090         }
1091         io_ctl_drop_pages(io_ctl);
1092         unlock_extent_cached(&BTRFS_I(inode)->io_tree, 0,
1093                              i_size_read(inode) - 1, cached_state,
1094                              GFP_NOFS);
1095 }
1096
1097 int btrfs_wait_cache_io(struct btrfs_root *root,
1098                         struct btrfs_trans_handle *trans,
1099                         struct btrfs_block_group_cache *block_group,
1100                         struct btrfs_io_ctl *io_ctl,
1101                         struct btrfs_path *path, u64 offset)
1102 {
1103         int ret;
1104         struct inode *inode = io_ctl->inode;
1105
1106         root = root->fs_info->tree_root;
1107
1108         /* Flush the dirty pages in the cache file. */
1109         ret = flush_dirty_cache(inode);
1110         if (ret)
1111                 goto out;
1112
1113         /* Update the cache item to tell everyone this cache file is valid. */
1114         ret = update_cache_item(trans, root, inode, path, offset,
1115                                 io_ctl->entries, io_ctl->bitmaps);
1116 out:
1117         io_ctl_free(io_ctl);
1118         if (ret) {
1119                 invalidate_inode_pages2(inode->i_mapping);
1120                 BTRFS_I(inode)->generation = 0;
1121                 if (block_group) {
1122 #ifdef DEBUG
1123                         btrfs_err(root->fs_info,
1124                                 "failed to write free space cache for block group %llu",
1125                                 block_group->key.objectid);
1126 #endif
1127                 }
1128         }
1129         btrfs_update_inode(trans, root, inode);
1130
1131         if (block_group) {
1132                 spin_lock(&block_group->lock);
1133
1134                 /*
1135                  * only mark this as written if we didn't get put back on
1136                  * the dirty list while waiting for IO.
1137                  */
1138                 if (!ret && list_empty(&block_group->dirty_list))
1139                         block_group->disk_cache_state = BTRFS_DC_WRITTEN;
1140                 else if (ret)
1141                         block_group->disk_cache_state = BTRFS_DC_ERROR;
1142
1143                 spin_unlock(&block_group->lock);
1144                 io_ctl->inode = NULL;
1145                 iput(inode);
1146         }
1147
1148         return ret;
1149
1150 }
1151
1152 /**
1153  * __btrfs_write_out_cache - write out cached info to an inode
1154  * @root - the root the inode belongs to
1155  * @ctl - the free space cache we are going to write out
1156  * @block_group - the block_group for this cache if it belongs to a block_group
1157  * @trans - the trans handle
1158  * @path - the path to use
1159  * @offset - the offset for the key we'll insert
1160  *
1161  * This function writes out a free space cache struct to disk for quick recovery
1162  * on mount.  This will return 0 if it was successfull in writing the cache out,
1163  * and -1 if it was not.
1164  */
1165 static int __btrfs_write_out_cache(struct btrfs_root *root, struct inode *inode,
1166                                    struct btrfs_free_space_ctl *ctl,
1167                                    struct btrfs_block_group_cache *block_group,
1168                                    struct btrfs_io_ctl *io_ctl,
1169                                    struct btrfs_trans_handle *trans,
1170                                    struct btrfs_path *path, u64 offset)
1171 {
1172         struct extent_state *cached_state = NULL;
1173         LIST_HEAD(bitmap_list);
1174         int entries = 0;
1175         int bitmaps = 0;
1176         int ret;
1177         int must_iput = 0;
1178
1179         if (!i_size_read(inode))
1180                 return -1;
1181
1182         WARN_ON(io_ctl->pages);
1183         ret = io_ctl_init(io_ctl, inode, root, 1);
1184         if (ret)
1185                 return -1;
1186
1187         if (block_group && (block_group->flags & BTRFS_BLOCK_GROUP_DATA)) {
1188                 down_write(&block_group->data_rwsem);
1189                 spin_lock(&block_group->lock);
1190                 if (block_group->delalloc_bytes) {
1191                         block_group->disk_cache_state = BTRFS_DC_WRITTEN;
1192                         spin_unlock(&block_group->lock);
1193                         up_write(&block_group->data_rwsem);
1194                         BTRFS_I(inode)->generation = 0;
1195                         ret = 0;
1196                         must_iput = 1;
1197                         goto out;
1198                 }
1199                 spin_unlock(&block_group->lock);
1200         }
1201
1202         /* Lock all pages first so we can lock the extent safely. */
1203         io_ctl_prepare_pages(io_ctl, inode, 0);
1204
1205         lock_extent_bits(&BTRFS_I(inode)->io_tree, 0, i_size_read(inode) - 1,
1206                          0, &cached_state);
1207
1208         io_ctl_set_generation(io_ctl, trans->transid);
1209
1210         mutex_lock(&ctl->cache_writeout_mutex);
1211         /* Write out the extent entries in the free space cache */
1212         ret = write_cache_extent_entries(io_ctl, ctl,
1213                                          block_group, &entries, &bitmaps,
1214                                          &bitmap_list);
1215         if (ret) {
1216                 mutex_unlock(&ctl->cache_writeout_mutex);
1217                 goto out_nospc;
1218         }
1219
1220         /*
1221          * Some spaces that are freed in the current transaction are pinned,
1222          * they will be added into free space cache after the transaction is
1223          * committed, we shouldn't lose them.
1224          */
1225         ret = write_pinned_extent_entries(root, block_group, io_ctl, &entries);
1226         if (ret) {
1227                 mutex_unlock(&ctl->cache_writeout_mutex);
1228                 goto out_nospc;
1229         }
1230
1231         /*
1232          * At last, we write out all the bitmaps and keep cache_writeout_mutex
1233          * locked while doing it because a concurrent trim can be manipulating
1234          * or freeing the bitmap.
1235          */
1236         ret = write_bitmap_entries(io_ctl, &bitmap_list);
1237         mutex_unlock(&ctl->cache_writeout_mutex);
1238         if (ret)
1239                 goto out_nospc;
1240
1241         /* Zero out the rest of the pages just to make sure */
1242         io_ctl_zero_remaining_pages(io_ctl);
1243
1244         /* Everything is written out, now we dirty the pages in the file. */
1245         ret = btrfs_dirty_pages(root, inode, io_ctl->pages, io_ctl->num_pages,
1246                                 0, i_size_read(inode), &cached_state);
1247         if (ret)
1248                 goto out_nospc;
1249
1250         if (block_group && (block_group->flags & BTRFS_BLOCK_GROUP_DATA))
1251                 up_write(&block_group->data_rwsem);
1252         /*
1253          * Release the pages and unlock the extent, we will flush
1254          * them out later
1255          */
1256         io_ctl_drop_pages(io_ctl);
1257
1258         unlock_extent_cached(&BTRFS_I(inode)->io_tree, 0,
1259                              i_size_read(inode) - 1, &cached_state, GFP_NOFS);
1260
1261         /*
1262          * at this point the pages are under IO and we're happy,
1263          * The caller is responsible for waiting on them and updating the
1264          * the cache and the inode
1265          */
1266         io_ctl->entries = entries;
1267         io_ctl->bitmaps = bitmaps;
1268
1269         ret = btrfs_fdatawrite_range(inode, 0, (u64)-1);
1270         if (ret)
1271                 goto out;
1272
1273         return 0;
1274
1275 out:
1276         io_ctl->inode = NULL;
1277         io_ctl_free(io_ctl);
1278         if (ret) {
1279                 invalidate_inode_pages2(inode->i_mapping);
1280                 BTRFS_I(inode)->generation = 0;
1281         }
1282         btrfs_update_inode(trans, root, inode);
1283         if (must_iput)
1284                 iput(inode);
1285         return ret;
1286
1287 out_nospc:
1288         cleanup_write_cache_enospc(inode, io_ctl, &cached_state, &bitmap_list);
1289
1290         if (block_group && (block_group->flags & BTRFS_BLOCK_GROUP_DATA))
1291                 up_write(&block_group->data_rwsem);
1292
1293         goto out;
1294 }
1295
1296 int btrfs_write_out_cache(struct btrfs_root *root,
1297                           struct btrfs_trans_handle *trans,
1298                           struct btrfs_block_group_cache *block_group,
1299                           struct btrfs_path *path)
1300 {
1301         struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
1302         struct inode *inode;
1303         int ret = 0;
1304
1305         root = root->fs_info->tree_root;
1306
1307         spin_lock(&block_group->lock);
1308         if (block_group->disk_cache_state < BTRFS_DC_SETUP) {
1309                 spin_unlock(&block_group->lock);
1310                 return 0;
1311         }
1312
1313         if (block_group->delalloc_bytes) {
1314                 block_group->disk_cache_state = BTRFS_DC_WRITTEN;
1315                 spin_unlock(&block_group->lock);
1316                 return 0;
1317         }
1318         spin_unlock(&block_group->lock);
1319
1320         inode = lookup_free_space_inode(root, block_group, path);
1321         if (IS_ERR(inode))
1322                 return 0;
1323
1324         ret = __btrfs_write_out_cache(root, inode, ctl, block_group,
1325                                       &block_group->io_ctl, trans,
1326                                       path, block_group->key.objectid);
1327         if (ret) {
1328 #ifdef DEBUG
1329                 btrfs_err(root->fs_info,
1330                         "failed to write free space cache for block group %llu",
1331                         block_group->key.objectid);
1332 #endif
1333                 spin_lock(&block_group->lock);
1334                 block_group->disk_cache_state = BTRFS_DC_ERROR;
1335                 spin_unlock(&block_group->lock);
1336
1337                 block_group->io_ctl.inode = NULL;
1338                 iput(inode);
1339         }
1340
1341         /*
1342          * if ret == 0 the caller is expected to call btrfs_wait_cache_io
1343          * to wait for IO and put the inode
1344          */
1345
1346         return ret;
1347 }
1348
1349 static inline unsigned long offset_to_bit(u64 bitmap_start, u32 unit,
1350                                           u64 offset)
1351 {
1352         ASSERT(offset >= bitmap_start);
1353         offset -= bitmap_start;
1354         return (unsigned long)(div_u64(offset, unit));
1355 }
1356
1357 static inline unsigned long bytes_to_bits(u64 bytes, u32 unit)
1358 {
1359         return (unsigned long)(div_u64(bytes, unit));
1360 }
1361
1362 static inline u64 offset_to_bitmap(struct btrfs_free_space_ctl *ctl,
1363                                    u64 offset)
1364 {
1365         u64 bitmap_start;
1366         u32 bytes_per_bitmap;
1367
1368         bytes_per_bitmap = BITS_PER_BITMAP * ctl->unit;
1369         bitmap_start = offset - ctl->start;
1370         bitmap_start = div_u64(bitmap_start, bytes_per_bitmap);
1371         bitmap_start *= bytes_per_bitmap;
1372         bitmap_start += ctl->start;
1373
1374         return bitmap_start;
1375 }
1376
1377 static int tree_insert_offset(struct rb_root *root, u64 offset,
1378                               struct rb_node *node, int bitmap)
1379 {
1380         struct rb_node **p = &root->rb_node;
1381         struct rb_node *parent = NULL;
1382         struct btrfs_free_space *info;
1383
1384         while (*p) {
1385                 parent = *p;
1386                 info = rb_entry(parent, struct btrfs_free_space, offset_index);
1387
1388                 if (offset < info->offset) {
1389                         p = &(*p)->rb_left;
1390                 } else if (offset > info->offset) {
1391                         p = &(*p)->rb_right;
1392                 } else {
1393                         /*
1394                          * we could have a bitmap entry and an extent entry
1395                          * share the same offset.  If this is the case, we want
1396                          * the extent entry to always be found first if we do a
1397                          * linear search through the tree, since we want to have
1398                          * the quickest allocation time, and allocating from an
1399                          * extent is faster than allocating from a bitmap.  So
1400                          * if we're inserting a bitmap and we find an entry at
1401                          * this offset, we want to go right, or after this entry
1402                          * logically.  If we are inserting an extent and we've
1403                          * found a bitmap, we want to go left, or before
1404                          * logically.
1405                          */
1406                         if (bitmap) {
1407                                 if (info->bitmap) {
1408                                         WARN_ON_ONCE(1);
1409                                         return -EEXIST;
1410                                 }
1411                                 p = &(*p)->rb_right;
1412                         } else {
1413                                 if (!info->bitmap) {
1414                                         WARN_ON_ONCE(1);
1415                                         return -EEXIST;
1416                                 }
1417                                 p = &(*p)->rb_left;
1418                         }
1419                 }
1420         }
1421
1422         rb_link_node(node, parent, p);
1423         rb_insert_color(node, root);
1424
1425         return 0;
1426 }
1427
1428 /*
1429  * searches the tree for the given offset.
1430  *
1431  * fuzzy - If this is set, then we are trying to make an allocation, and we just
1432  * want a section that has at least bytes size and comes at or after the given
1433  * offset.
1434  */
1435 static struct btrfs_free_space *
1436 tree_search_offset(struct btrfs_free_space_ctl *ctl,
1437                    u64 offset, int bitmap_only, int fuzzy)
1438 {
1439         struct rb_node *n = ctl->free_space_offset.rb_node;
1440         struct btrfs_free_space *entry, *prev = NULL;
1441
1442         /* find entry that is closest to the 'offset' */
1443         while (1) {
1444                 if (!n) {
1445                         entry = NULL;
1446                         break;
1447                 }
1448
1449                 entry = rb_entry(n, struct btrfs_free_space, offset_index);
1450                 prev = entry;
1451
1452                 if (offset < entry->offset)
1453                         n = n->rb_left;
1454                 else if (offset > entry->offset)
1455                         n = n->rb_right;
1456                 else
1457                         break;
1458         }
1459
1460         if (bitmap_only) {
1461                 if (!entry)
1462                         return NULL;
1463                 if (entry->bitmap)
1464                         return entry;
1465
1466                 /*
1467                  * bitmap entry and extent entry may share same offset,
1468                  * in that case, bitmap entry comes after extent entry.
1469                  */
1470                 n = rb_next(n);
1471                 if (!n)
1472                         return NULL;
1473                 entry = rb_entry(n, struct btrfs_free_space, offset_index);
1474                 if (entry->offset != offset)
1475                         return NULL;
1476
1477                 WARN_ON(!entry->bitmap);
1478                 return entry;
1479         } else if (entry) {
1480                 if (entry->bitmap) {
1481                         /*
1482                          * if previous extent entry covers the offset,
1483                          * we should return it instead of the bitmap entry
1484                          */
1485                         n = rb_prev(&entry->offset_index);
1486                         if (n) {
1487                                 prev = rb_entry(n, struct btrfs_free_space,
1488                                                 offset_index);
1489                                 if (!prev->bitmap &&
1490                                     prev->offset + prev->bytes > offset)
1491                                         entry = prev;
1492                         }
1493                 }
1494                 return entry;
1495         }
1496
1497         if (!prev)
1498                 return NULL;
1499
1500         /* find last entry before the 'offset' */
1501         entry = prev;
1502         if (entry->offset > offset) {
1503                 n = rb_prev(&entry->offset_index);
1504                 if (n) {
1505                         entry = rb_entry(n, struct btrfs_free_space,
1506                                         offset_index);
1507                         ASSERT(entry->offset <= offset);
1508                 } else {
1509                         if (fuzzy)
1510                                 return entry;
1511                         else
1512                                 return NULL;
1513                 }
1514         }
1515
1516         if (entry->bitmap) {
1517                 n = rb_prev(&entry->offset_index);
1518                 if (n) {
1519                         prev = rb_entry(n, struct btrfs_free_space,
1520                                         offset_index);
1521                         if (!prev->bitmap &&
1522                             prev->offset + prev->bytes > offset)
1523                                 return prev;
1524                 }
1525                 if (entry->offset + BITS_PER_BITMAP * ctl->unit > offset)
1526                         return entry;
1527         } else if (entry->offset + entry->bytes > offset)
1528                 return entry;
1529
1530         if (!fuzzy)
1531                 return NULL;
1532
1533         while (1) {
1534                 if (entry->bitmap) {
1535                         if (entry->offset + BITS_PER_BITMAP *
1536                             ctl->unit > offset)
1537                                 break;
1538                 } else {
1539                         if (entry->offset + entry->bytes > offset)
1540                                 break;
1541                 }
1542
1543                 n = rb_next(&entry->offset_index);
1544                 if (!n)
1545                         return NULL;
1546                 entry = rb_entry(n, struct btrfs_free_space, offset_index);
1547         }
1548         return entry;
1549 }
1550
1551 static inline void
1552 __unlink_free_space(struct btrfs_free_space_ctl *ctl,
1553                     struct btrfs_free_space *info)
1554 {
1555         rb_erase(&info->offset_index, &ctl->free_space_offset);
1556         ctl->free_extents--;
1557 }
1558
1559 static void unlink_free_space(struct btrfs_free_space_ctl *ctl,
1560                               struct btrfs_free_space *info)
1561 {
1562         __unlink_free_space(ctl, info);
1563         ctl->free_space -= info->bytes;
1564 }
1565
1566 static int link_free_space(struct btrfs_free_space_ctl *ctl,
1567                            struct btrfs_free_space *info)
1568 {
1569         int ret = 0;
1570
1571         ASSERT(info->bytes || info->bitmap);
1572         ret = tree_insert_offset(&ctl->free_space_offset, info->offset,
1573                                  &info->offset_index, (info->bitmap != NULL));
1574         if (ret)
1575                 return ret;
1576
1577         ctl->free_space += info->bytes;
1578         ctl->free_extents++;
1579         return ret;
1580 }
1581
1582 static void recalculate_thresholds(struct btrfs_free_space_ctl *ctl)
1583 {
1584         struct btrfs_block_group_cache *block_group = ctl->private;
1585         u64 max_bytes;
1586         u64 bitmap_bytes;
1587         u64 extent_bytes;
1588         u64 size = block_group->key.offset;
1589         u32 bytes_per_bg = BITS_PER_BITMAP * ctl->unit;
1590         u32 max_bitmaps = div_u64(size + bytes_per_bg - 1, bytes_per_bg);
1591
1592         max_bitmaps = max_t(u32, max_bitmaps, 1);
1593
1594         ASSERT(ctl->total_bitmaps <= max_bitmaps);
1595
1596         /*
1597          * The goal is to keep the total amount of memory used per 1gb of space
1598          * at or below 32k, so we need to adjust how much memory we allow to be
1599          * used by extent based free space tracking
1600          */
1601         if (size < 1024 * 1024 * 1024)
1602                 max_bytes = MAX_CACHE_BYTES_PER_GIG;
1603         else
1604                 max_bytes = MAX_CACHE_BYTES_PER_GIG *
1605                         div_u64(size, 1024 * 1024 * 1024);
1606
1607         /*
1608          * we want to account for 1 more bitmap than what we have so we can make
1609          * sure we don't go over our overall goal of MAX_CACHE_BYTES_PER_GIG as
1610          * we add more bitmaps.
1611          */
1612         bitmap_bytes = (ctl->total_bitmaps + 1) * PAGE_CACHE_SIZE;
1613
1614         if (bitmap_bytes >= max_bytes) {
1615                 ctl->extents_thresh = 0;
1616                 return;
1617         }
1618
1619         /*
1620          * we want the extent entry threshold to always be at most 1/2 the max
1621          * bytes we can have, or whatever is less than that.
1622          */
1623         extent_bytes = max_bytes - bitmap_bytes;
1624         extent_bytes = min_t(u64, extent_bytes, max_bytes >> 1);
1625
1626         ctl->extents_thresh =
1627                 div_u64(extent_bytes, sizeof(struct btrfs_free_space));
1628 }
1629
1630 static inline void __bitmap_clear_bits(struct btrfs_free_space_ctl *ctl,
1631                                        struct btrfs_free_space *info,
1632                                        u64 offset, u64 bytes)
1633 {
1634         unsigned long start, count;
1635
1636         start = offset_to_bit(info->offset, ctl->unit, offset);
1637         count = bytes_to_bits(bytes, ctl->unit);
1638         ASSERT(start + count <= BITS_PER_BITMAP);
1639
1640         bitmap_clear(info->bitmap, start, count);
1641
1642         info->bytes -= bytes;
1643 }
1644
1645 static void bitmap_clear_bits(struct btrfs_free_space_ctl *ctl,
1646                               struct btrfs_free_space *info, u64 offset,
1647                               u64 bytes)
1648 {
1649         __bitmap_clear_bits(ctl, info, offset, bytes);
1650         ctl->free_space -= bytes;
1651 }
1652
1653 static void bitmap_set_bits(struct btrfs_free_space_ctl *ctl,
1654                             struct btrfs_free_space *info, u64 offset,
1655                             u64 bytes)
1656 {
1657         unsigned long start, count;
1658
1659         start = offset_to_bit(info->offset, ctl->unit, offset);
1660         count = bytes_to_bits(bytes, ctl->unit);
1661         ASSERT(start + count <= BITS_PER_BITMAP);
1662
1663         bitmap_set(info->bitmap, start, count);
1664
1665         info->bytes += bytes;
1666         ctl->free_space += bytes;
1667 }
1668
1669 /*
1670  * If we can not find suitable extent, we will use bytes to record
1671  * the size of the max extent.
1672  */
1673 static int search_bitmap(struct btrfs_free_space_ctl *ctl,
1674                          struct btrfs_free_space *bitmap_info, u64 *offset,
1675                          u64 *bytes)
1676 {
1677         unsigned long found_bits = 0;
1678         unsigned long max_bits = 0;
1679         unsigned long bits, i;
1680         unsigned long next_zero;
1681         unsigned long extent_bits;
1682
1683         i = offset_to_bit(bitmap_info->offset, ctl->unit,
1684                           max_t(u64, *offset, bitmap_info->offset));
1685         bits = bytes_to_bits(*bytes, ctl->unit);
1686
1687         for_each_set_bit_from(i, bitmap_info->bitmap, BITS_PER_BITMAP) {
1688                 next_zero = find_next_zero_bit(bitmap_info->bitmap,
1689                                                BITS_PER_BITMAP, i);
1690                 extent_bits = next_zero - i;
1691                 if (extent_bits >= bits) {
1692                         found_bits = extent_bits;
1693                         break;
1694                 } else if (extent_bits > max_bits) {
1695                         max_bits = extent_bits;
1696                 }
1697                 i = next_zero;
1698         }
1699
1700         if (found_bits) {
1701                 *offset = (u64)(i * ctl->unit) + bitmap_info->offset;
1702                 *bytes = (u64)(found_bits) * ctl->unit;
1703                 return 0;
1704         }
1705
1706         *bytes = (u64)(max_bits) * ctl->unit;
1707         return -1;
1708 }
1709
1710 /* Cache the size of the max extent in bytes */
1711 static struct btrfs_free_space *
1712 find_free_space(struct btrfs_free_space_ctl *ctl, u64 *offset, u64 *bytes,
1713                 unsigned long align, u64 *max_extent_size)
1714 {
1715         struct btrfs_free_space *entry;
1716         struct rb_node *node;
1717         u64 tmp;
1718         u64 align_off;
1719         int ret;
1720
1721         if (!ctl->free_space_offset.rb_node)
1722                 goto out;
1723
1724         entry = tree_search_offset(ctl, offset_to_bitmap(ctl, *offset), 0, 1);
1725         if (!entry)
1726                 goto out;
1727
1728         for (node = &entry->offset_index; node; node = rb_next(node)) {
1729                 entry = rb_entry(node, struct btrfs_free_space, offset_index);
1730                 if (entry->bytes < *bytes) {
1731                         if (entry->bytes > *max_extent_size)
1732                                 *max_extent_size = entry->bytes;
1733                         continue;
1734                 }
1735
1736                 /* make sure the space returned is big enough
1737                  * to match our requested alignment
1738                  */
1739                 if (*bytes >= align) {
1740                         tmp = entry->offset - ctl->start + align - 1;
1741                         tmp = div64_u64(tmp, align);
1742                         tmp = tmp * align + ctl->start;
1743                         align_off = tmp - entry->offset;
1744                 } else {
1745                         align_off = 0;
1746                         tmp = entry->offset;
1747                 }
1748
1749                 if (entry->bytes < *bytes + align_off) {
1750                         if (entry->bytes > *max_extent_size)
1751                                 *max_extent_size = entry->bytes;
1752                         continue;
1753                 }
1754
1755                 if (entry->bitmap) {
1756                         u64 size = *bytes;
1757
1758                         ret = search_bitmap(ctl, entry, &tmp, &size);
1759                         if (!ret) {
1760                                 *offset = tmp;
1761                                 *bytes = size;
1762                                 return entry;
1763                         } else if (size > *max_extent_size) {
1764                                 *max_extent_size = size;
1765                         }
1766                         continue;
1767                 }
1768
1769                 *offset = tmp;
1770                 *bytes = entry->bytes - align_off;
1771                 return entry;
1772         }
1773 out:
1774         return NULL;
1775 }
1776
1777 static void add_new_bitmap(struct btrfs_free_space_ctl *ctl,
1778                            struct btrfs_free_space *info, u64 offset)
1779 {
1780         info->offset = offset_to_bitmap(ctl, offset);
1781         info->bytes = 0;
1782         INIT_LIST_HEAD(&info->list);
1783         link_free_space(ctl, info);
1784         ctl->total_bitmaps++;
1785
1786         ctl->op->recalc_thresholds(ctl);
1787 }
1788
1789 static void free_bitmap(struct btrfs_free_space_ctl *ctl,
1790                         struct btrfs_free_space *bitmap_info)
1791 {
1792         unlink_free_space(ctl, bitmap_info);
1793         kfree(bitmap_info->bitmap);
1794         kmem_cache_free(btrfs_free_space_cachep, bitmap_info);
1795         ctl->total_bitmaps--;
1796         ctl->op->recalc_thresholds(ctl);
1797 }
1798
1799 static noinline int remove_from_bitmap(struct btrfs_free_space_ctl *ctl,
1800                               struct btrfs_free_space *bitmap_info,
1801                               u64 *offset, u64 *bytes)
1802 {
1803         u64 end;
1804         u64 search_start, search_bytes;
1805         int ret;
1806
1807 again:
1808         end = bitmap_info->offset + (u64)(BITS_PER_BITMAP * ctl->unit) - 1;
1809
1810         /*
1811          * We need to search for bits in this bitmap.  We could only cover some
1812          * of the extent in this bitmap thanks to how we add space, so we need
1813          * to search for as much as it as we can and clear that amount, and then
1814          * go searching for the next bit.
1815          */
1816         search_start = *offset;
1817         search_bytes = ctl->unit;
1818         search_bytes = min(search_bytes, end - search_start + 1);
1819         ret = search_bitmap(ctl, bitmap_info, &search_start, &search_bytes);
1820         if (ret < 0 || search_start != *offset)
1821                 return -EINVAL;
1822
1823         /* We may have found more bits than what we need */
1824         search_bytes = min(search_bytes, *bytes);
1825
1826         /* Cannot clear past the end of the bitmap */
1827         search_bytes = min(search_bytes, end - search_start + 1);
1828
1829         bitmap_clear_bits(ctl, bitmap_info, search_start, search_bytes);
1830         *offset += search_bytes;
1831         *bytes -= search_bytes;
1832
1833         if (*bytes) {
1834                 struct rb_node *next = rb_next(&bitmap_info->offset_index);
1835                 if (!bitmap_info->bytes)
1836                         free_bitmap(ctl, bitmap_info);
1837
1838                 /*
1839                  * no entry after this bitmap, but we still have bytes to
1840                  * remove, so something has gone wrong.
1841                  */
1842                 if (!next)
1843                         return -EINVAL;
1844
1845                 bitmap_info = rb_entry(next, struct btrfs_free_space,
1846                                        offset_index);
1847
1848                 /*
1849                  * if the next entry isn't a bitmap we need to return to let the
1850                  * extent stuff do its work.
1851                  */
1852                 if (!bitmap_info->bitmap)
1853                         return -EAGAIN;
1854
1855                 /*
1856                  * Ok the next item is a bitmap, but it may not actually hold
1857                  * the information for the rest of this free space stuff, so
1858                  * look for it, and if we don't find it return so we can try
1859                  * everything over again.
1860                  */
1861                 search_start = *offset;
1862                 search_bytes = ctl->unit;
1863                 ret = search_bitmap(ctl, bitmap_info, &search_start,
1864                                     &search_bytes);
1865                 if (ret < 0 || search_start != *offset)
1866                         return -EAGAIN;
1867
1868                 goto again;
1869         } else if (!bitmap_info->bytes)
1870                 free_bitmap(ctl, bitmap_info);
1871
1872         return 0;
1873 }
1874
1875 static u64 add_bytes_to_bitmap(struct btrfs_free_space_ctl *ctl,
1876                                struct btrfs_free_space *info, u64 offset,
1877                                u64 bytes)
1878 {
1879         u64 bytes_to_set = 0;
1880         u64 end;
1881
1882         end = info->offset + (u64)(BITS_PER_BITMAP * ctl->unit);
1883
1884         bytes_to_set = min(end - offset, bytes);
1885
1886         bitmap_set_bits(ctl, info, offset, bytes_to_set);
1887
1888         return bytes_to_set;
1889
1890 }
1891
1892 static bool use_bitmap(struct btrfs_free_space_ctl *ctl,
1893                       struct btrfs_free_space *info)
1894 {
1895         struct btrfs_block_group_cache *block_group = ctl->private;
1896
1897         /*
1898          * If we are below the extents threshold then we can add this as an
1899          * extent, and don't have to deal with the bitmap
1900          */
1901         if (ctl->free_extents < ctl->extents_thresh) {
1902                 /*
1903                  * If this block group has some small extents we don't want to
1904                  * use up all of our free slots in the cache with them, we want
1905                  * to reserve them to larger extents, however if we have plent
1906                  * of cache left then go ahead an dadd them, no sense in adding
1907                  * the overhead of a bitmap if we don't have to.
1908                  */
1909                 if (info->bytes <= block_group->sectorsize * 4) {
1910                         if (ctl->free_extents * 2 <= ctl->extents_thresh)
1911                                 return false;
1912                 } else {
1913                         return false;
1914                 }
1915         }
1916
1917         /*
1918          * The original block groups from mkfs can be really small, like 8
1919          * megabytes, so don't bother with a bitmap for those entries.  However
1920          * some block groups can be smaller than what a bitmap would cover but
1921          * are still large enough that they could overflow the 32k memory limit,
1922          * so allow those block groups to still be allowed to have a bitmap
1923          * entry.
1924          */
1925         if (((BITS_PER_BITMAP * ctl->unit) >> 1) > block_group->key.offset)
1926                 return false;
1927
1928         return true;
1929 }
1930
1931 static struct btrfs_free_space_op free_space_op = {
1932         .recalc_thresholds      = recalculate_thresholds,
1933         .use_bitmap             = use_bitmap,
1934 };
1935
1936 static int insert_into_bitmap(struct btrfs_free_space_ctl *ctl,
1937                               struct btrfs_free_space *info)
1938 {
1939         struct btrfs_free_space *bitmap_info;
1940         struct btrfs_block_group_cache *block_group = NULL;
1941         int added = 0;
1942         u64 bytes, offset, bytes_added;
1943         int ret;
1944
1945         bytes = info->bytes;
1946         offset = info->offset;
1947
1948         if (!ctl->op->use_bitmap(ctl, info))
1949                 return 0;
1950
1951         if (ctl->op == &free_space_op)
1952                 block_group = ctl->private;
1953 again:
1954         /*
1955          * Since we link bitmaps right into the cluster we need to see if we
1956          * have a cluster here, and if so and it has our bitmap we need to add
1957          * the free space to that bitmap.
1958          */
1959         if (block_group && !list_empty(&block_group->cluster_list)) {
1960                 struct btrfs_free_cluster *cluster;
1961                 struct rb_node *node;
1962                 struct btrfs_free_space *entry;
1963
1964                 cluster = list_entry(block_group->cluster_list.next,
1965                                      struct btrfs_free_cluster,
1966                                      block_group_list);
1967                 spin_lock(&cluster->lock);
1968                 node = rb_first(&cluster->root);
1969                 if (!node) {
1970                         spin_unlock(&cluster->lock);
1971                         goto no_cluster_bitmap;
1972                 }
1973
1974                 entry = rb_entry(node, struct btrfs_free_space, offset_index);
1975                 if (!entry->bitmap) {
1976                         spin_unlock(&cluster->lock);
1977                         goto no_cluster_bitmap;
1978                 }
1979
1980                 if (entry->offset == offset_to_bitmap(ctl, offset)) {
1981                         bytes_added = add_bytes_to_bitmap(ctl, entry,
1982                                                           offset, bytes);
1983                         bytes -= bytes_added;
1984                         offset += bytes_added;
1985                 }
1986                 spin_unlock(&cluster->lock);
1987                 if (!bytes) {
1988                         ret = 1;
1989                         goto out;
1990                 }
1991         }
1992
1993 no_cluster_bitmap:
1994         bitmap_info = tree_search_offset(ctl, offset_to_bitmap(ctl, offset),
1995                                          1, 0);
1996         if (!bitmap_info) {
1997                 ASSERT(added == 0);
1998                 goto new_bitmap;
1999         }
2000
2001         bytes_added = add_bytes_to_bitmap(ctl, bitmap_info, offset, bytes);
2002         bytes -= bytes_added;
2003         offset += bytes_added;
2004         added = 0;
2005
2006         if (!bytes) {
2007                 ret = 1;
2008                 goto out;
2009         } else
2010                 goto again;
2011
2012 new_bitmap:
2013         if (info && info->bitmap) {
2014                 add_new_bitmap(ctl, info, offset);
2015                 added = 1;
2016                 info = NULL;
2017                 goto again;
2018         } else {
2019                 spin_unlock(&ctl->tree_lock);
2020
2021                 /* no pre-allocated info, allocate a new one */
2022                 if (!info) {
2023                         info = kmem_cache_zalloc(btrfs_free_space_cachep,
2024                                                  GFP_NOFS);
2025                         if (!info) {
2026                                 spin_lock(&ctl->tree_lock);
2027                                 ret = -ENOMEM;
2028                                 goto out;
2029                         }
2030                 }
2031
2032                 /* allocate the bitmap */
2033                 info->bitmap = kzalloc(PAGE_CACHE_SIZE, GFP_NOFS);
2034                 spin_lock(&ctl->tree_lock);
2035                 if (!info->bitmap) {
2036                         ret = -ENOMEM;
2037                         goto out;
2038                 }
2039                 goto again;
2040         }
2041
2042 out:
2043         if (info) {
2044                 if (info->bitmap)
2045                         kfree(info->bitmap);
2046                 kmem_cache_free(btrfs_free_space_cachep, info);
2047         }
2048
2049         return ret;
2050 }
2051
2052 static bool try_merge_free_space(struct btrfs_free_space_ctl *ctl,
2053                           struct btrfs_free_space *info, bool update_stat)
2054 {
2055         struct btrfs_free_space *left_info;
2056         struct btrfs_free_space *right_info;
2057         bool merged = false;
2058         u64 offset = info->offset;
2059         u64 bytes = info->bytes;
2060
2061         /*
2062          * first we want to see if there is free space adjacent to the range we
2063          * are adding, if there is remove that struct and add a new one to
2064          * cover the entire range
2065          */
2066         right_info = tree_search_offset(ctl, offset + bytes, 0, 0);
2067         if (right_info && rb_prev(&right_info->offset_index))
2068                 left_info = rb_entry(rb_prev(&right_info->offset_index),
2069                                      struct btrfs_free_space, offset_index);
2070         else
2071                 left_info = tree_search_offset(ctl, offset - 1, 0, 0);
2072
2073         if (right_info && !right_info->bitmap) {
2074                 if (update_stat)
2075                         unlink_free_space(ctl, right_info);
2076                 else
2077                         __unlink_free_space(ctl, right_info);
2078                 info->bytes += right_info->bytes;
2079                 kmem_cache_free(btrfs_free_space_cachep, right_info);
2080                 merged = true;
2081         }
2082
2083         if (left_info && !left_info->bitmap &&
2084             left_info->offset + left_info->bytes == offset) {
2085                 if (update_stat)
2086                         unlink_free_space(ctl, left_info);
2087                 else
2088                         __unlink_free_space(ctl, left_info);
2089                 info->offset = left_info->offset;
2090                 info->bytes += left_info->bytes;
2091                 kmem_cache_free(btrfs_free_space_cachep, left_info);
2092                 merged = true;
2093         }
2094
2095         return merged;
2096 }
2097
2098 static bool steal_from_bitmap_to_end(struct btrfs_free_space_ctl *ctl,
2099                                      struct btrfs_free_space *info,
2100                                      bool update_stat)
2101 {
2102         struct btrfs_free_space *bitmap;
2103         unsigned long i;
2104         unsigned long j;
2105         const u64 end = info->offset + info->bytes;
2106         const u64 bitmap_offset = offset_to_bitmap(ctl, end);
2107         u64 bytes;
2108
2109         bitmap = tree_search_offset(ctl, bitmap_offset, 1, 0);
2110         if (!bitmap)
2111                 return false;
2112
2113         i = offset_to_bit(bitmap->offset, ctl->unit, end);
2114         j = find_next_zero_bit(bitmap->bitmap, BITS_PER_BITMAP, i);
2115         if (j == i)
2116                 return false;
2117         bytes = (j - i) * ctl->unit;
2118         info->bytes += bytes;
2119
2120         if (update_stat)
2121                 bitmap_clear_bits(ctl, bitmap, end, bytes);
2122         else
2123                 __bitmap_clear_bits(ctl, bitmap, end, bytes);
2124
2125         if (!bitmap->bytes)
2126                 free_bitmap(ctl, bitmap);
2127
2128         return true;
2129 }
2130
2131 static bool steal_from_bitmap_to_front(struct btrfs_free_space_ctl *ctl,
2132                                        struct btrfs_free_space *info,
2133                                        bool update_stat)
2134 {
2135         struct btrfs_free_space *bitmap;
2136         u64 bitmap_offset;
2137         unsigned long i;
2138         unsigned long j;
2139         unsigned long prev_j;
2140         u64 bytes;
2141
2142         bitmap_offset = offset_to_bitmap(ctl, info->offset);
2143         /* If we're on a boundary, try the previous logical bitmap. */
2144         if (bitmap_offset == info->offset) {
2145                 if (info->offset == 0)
2146                         return false;
2147                 bitmap_offset = offset_to_bitmap(ctl, info->offset - 1);
2148         }
2149
2150         bitmap = tree_search_offset(ctl, bitmap_offset, 1, 0);
2151         if (!bitmap)
2152                 return false;
2153
2154         i = offset_to_bit(bitmap->offset, ctl->unit, info->offset) - 1;
2155         j = 0;
2156         prev_j = (unsigned long)-1;
2157         for_each_clear_bit_from(j, bitmap->bitmap, BITS_PER_BITMAP) {
2158                 if (j > i)
2159                         break;
2160                 prev_j = j;
2161         }
2162         if (prev_j == i)
2163                 return false;
2164
2165         if (prev_j == (unsigned long)-1)
2166                 bytes = (i + 1) * ctl->unit;
2167         else
2168                 bytes = (i - prev_j) * ctl->unit;
2169
2170         info->offset -= bytes;
2171         info->bytes += bytes;
2172
2173         if (update_stat)
2174                 bitmap_clear_bits(ctl, bitmap, info->offset, bytes);
2175         else
2176                 __bitmap_clear_bits(ctl, bitmap, info->offset, bytes);
2177
2178         if (!bitmap->bytes)
2179                 free_bitmap(ctl, bitmap);
2180
2181         return true;
2182 }
2183
2184 /*
2185  * We prefer always to allocate from extent entries, both for clustered and
2186  * non-clustered allocation requests. So when attempting to add a new extent
2187  * entry, try to see if there's adjacent free space in bitmap entries, and if
2188  * there is, migrate that space from the bitmaps to the extent.
2189  * Like this we get better chances of satisfying space allocation requests
2190  * because we attempt to satisfy them based on a single cache entry, and never
2191  * on 2 or more entries - even if the entries represent a contiguous free space
2192  * region (e.g. 1 extent entry + 1 bitmap entry starting where the extent entry
2193  * ends).
2194  */
2195 static void steal_from_bitmap(struct btrfs_free_space_ctl *ctl,
2196                               struct btrfs_free_space *info,
2197                               bool update_stat)
2198 {
2199         /*
2200          * Only work with disconnected entries, as we can change their offset,
2201          * and must be extent entries.
2202          */
2203         ASSERT(!info->bitmap);
2204         ASSERT(RB_EMPTY_NODE(&info->offset_index));
2205
2206         if (ctl->total_bitmaps > 0) {
2207                 bool stole_end;
2208                 bool stole_front = false;
2209
2210                 stole_end = steal_from_bitmap_to_end(ctl, info, update_stat);
2211                 if (ctl->total_bitmaps > 0)
2212                         stole_front = steal_from_bitmap_to_front(ctl, info,
2213                                                                  update_stat);
2214
2215                 if (stole_end || stole_front)
2216                         try_merge_free_space(ctl, info, update_stat);
2217         }
2218 }
2219
2220 int __btrfs_add_free_space(struct btrfs_free_space_ctl *ctl,
2221                            u64 offset, u64 bytes)
2222 {
2223         struct btrfs_free_space *info;
2224         int ret = 0;
2225
2226         info = kmem_cache_zalloc(btrfs_free_space_cachep, GFP_NOFS);
2227         if (!info)
2228                 return -ENOMEM;
2229
2230         info->offset = offset;
2231         info->bytes = bytes;
2232         RB_CLEAR_NODE(&info->offset_index);
2233
2234         spin_lock(&ctl->tree_lock);
2235
2236         if (try_merge_free_space(ctl, info, true))
2237                 goto link;
2238
2239         /*
2240          * There was no extent directly to the left or right of this new
2241          * extent then we know we're going to have to allocate a new extent, so
2242          * before we do that see if we need to drop this into a bitmap
2243          */
2244         ret = insert_into_bitmap(ctl, info);
2245         if (ret < 0) {
2246                 goto out;
2247         } else if (ret) {
2248                 ret = 0;
2249                 goto out;
2250         }
2251 link:
2252         /*
2253          * Only steal free space from adjacent bitmaps if we're sure we're not
2254          * going to add the new free space to existing bitmap entries - because
2255          * that would mean unnecessary work that would be reverted. Therefore
2256          * attempt to steal space from bitmaps if we're adding an extent entry.
2257          */
2258         steal_from_bitmap(ctl, info, true);
2259
2260         ret = link_free_space(ctl, info);
2261         if (ret)
2262                 kmem_cache_free(btrfs_free_space_cachep, info);
2263 out:
2264         spin_unlock(&ctl->tree_lock);
2265
2266         if (ret) {
2267                 printk(KERN_CRIT "BTRFS: unable to add free space :%d\n", ret);
2268                 ASSERT(ret != -EEXIST);
2269         }
2270
2271         return ret;
2272 }
2273
2274 int btrfs_remove_free_space(struct btrfs_block_group_cache *block_group,
2275                             u64 offset, u64 bytes)
2276 {
2277         struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
2278         struct btrfs_free_space *info;
2279         int ret;
2280         bool re_search = false;
2281
2282         spin_lock(&ctl->tree_lock);
2283
2284 again:
2285         ret = 0;
2286         if (!bytes)
2287                 goto out_lock;
2288
2289         info = tree_search_offset(ctl, offset, 0, 0);
2290         if (!info) {
2291                 /*
2292                  * oops didn't find an extent that matched the space we wanted
2293                  * to remove, look for a bitmap instead
2294                  */
2295                 info = tree_search_offset(ctl, offset_to_bitmap(ctl, offset),
2296                                           1, 0);
2297                 if (!info) {
2298                         /*
2299                          * If we found a partial bit of our free space in a
2300                          * bitmap but then couldn't find the other part this may
2301                          * be a problem, so WARN about it.
2302                          */
2303                         WARN_ON(re_search);
2304                         goto out_lock;
2305                 }
2306         }
2307
2308         re_search = false;
2309         if (!info->bitmap) {
2310                 unlink_free_space(ctl, info);
2311                 if (offset == info->offset) {
2312                         u64 to_free = min(bytes, info->bytes);
2313
2314                         info->bytes -= to_free;
2315                         info->offset += to_free;
2316                         if (info->bytes) {
2317                                 ret = link_free_space(ctl, info);
2318                                 WARN_ON(ret);
2319                         } else {
2320                                 kmem_cache_free(btrfs_free_space_cachep, info);
2321                         }
2322
2323                         offset += to_free;
2324                         bytes -= to_free;
2325                         goto again;
2326                 } else {
2327                         u64 old_end = info->bytes + info->offset;
2328
2329                         info->bytes = offset - info->offset;
2330                         ret = link_free_space(ctl, info);
2331                         WARN_ON(ret);
2332                         if (ret)
2333                                 goto out_lock;
2334
2335                         /* Not enough bytes in this entry to satisfy us */
2336                         if (old_end < offset + bytes) {
2337                                 bytes -= old_end - offset;
2338                                 offset = old_end;
2339                                 goto again;
2340                         } else if (old_end == offset + bytes) {
2341                                 /* all done */
2342                                 goto out_lock;
2343                         }
2344                         spin_unlock(&ctl->tree_lock);
2345
2346                         ret = btrfs_add_free_space(block_group, offset + bytes,
2347                                                    old_end - (offset + bytes));
2348                         WARN_ON(ret);
2349                         goto out;
2350                 }
2351         }
2352
2353         ret = remove_from_bitmap(ctl, info, &offset, &bytes);
2354         if (ret == -EAGAIN) {
2355                 re_search = true;
2356                 goto again;
2357         }
2358 out_lock:
2359         spin_unlock(&ctl->tree_lock);
2360 out:
2361         return ret;
2362 }
2363
2364 void btrfs_dump_free_space(struct btrfs_block_group_cache *block_group,
2365                            u64 bytes)
2366 {
2367         struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
2368         struct btrfs_free_space *info;
2369         struct rb_node *n;
2370         int count = 0;
2371
2372         for (n = rb_first(&ctl->free_space_offset); n; n = rb_next(n)) {
2373                 info = rb_entry(n, struct btrfs_free_space, offset_index);
2374                 if (info->bytes >= bytes && !block_group->ro)
2375                         count++;
2376                 btrfs_crit(block_group->fs_info,
2377                            "entry offset %llu, bytes %llu, bitmap %s",
2378                            info->offset, info->bytes,
2379                        (info->bitmap) ? "yes" : "no");
2380         }
2381         btrfs_info(block_group->fs_info, "block group has cluster?: %s",
2382                list_empty(&block_group->cluster_list) ? "no" : "yes");
2383         btrfs_info(block_group->fs_info,
2384                    "%d blocks of free space at or bigger than bytes is", count);
2385 }
2386
2387 void btrfs_init_free_space_ctl(struct btrfs_block_group_cache *block_group)
2388 {
2389         struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
2390
2391         spin_lock_init(&ctl->tree_lock);
2392         ctl->unit = block_group->sectorsize;
2393         ctl->start = block_group->key.objectid;
2394         ctl->private = block_group;
2395         ctl->op = &free_space_op;
2396         INIT_LIST_HEAD(&ctl->trimming_ranges);
2397         mutex_init(&ctl->cache_writeout_mutex);
2398
2399         /*
2400          * we only want to have 32k of ram per block group for keeping
2401          * track of free space, and if we pass 1/2 of that we want to
2402          * start converting things over to using bitmaps
2403          */
2404         ctl->extents_thresh = ((1024 * 32) / 2) /
2405                                 sizeof(struct btrfs_free_space);
2406 }
2407
2408 /*
2409  * for a given cluster, put all of its extents back into the free
2410  * space cache.  If the block group passed doesn't match the block group
2411  * pointed to by the cluster, someone else raced in and freed the
2412  * cluster already.  In that case, we just return without changing anything
2413  */
2414 static int
2415 __btrfs_return_cluster_to_free_space(
2416                              struct btrfs_block_group_cache *block_group,
2417                              struct btrfs_free_cluster *cluster)
2418 {
2419         struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
2420         struct btrfs_free_space *entry;
2421         struct rb_node *node;
2422
2423         spin_lock(&cluster->lock);
2424         if (cluster->block_group != block_group)
2425                 goto out;
2426
2427         cluster->block_group = NULL;
2428         cluster->window_start = 0;
2429         list_del_init(&cluster->block_group_list);
2430
2431         node = rb_first(&cluster->root);
2432         while (node) {
2433                 bool bitmap;
2434
2435                 entry = rb_entry(node, struct btrfs_free_space, offset_index);
2436                 node = rb_next(&entry->offset_index);
2437                 rb_erase(&entry->offset_index, &cluster->root);
2438                 RB_CLEAR_NODE(&entry->offset_index);
2439
2440                 bitmap = (entry->bitmap != NULL);
2441                 if (!bitmap) {
2442                         try_merge_free_space(ctl, entry, false);
2443                         steal_from_bitmap(ctl, entry, false);
2444                 }
2445                 tree_insert_offset(&ctl->free_space_offset,
2446                                    entry->offset, &entry->offset_index, bitmap);
2447         }
2448         cluster->root = RB_ROOT;
2449
2450 out:
2451         spin_unlock(&cluster->lock);
2452         btrfs_put_block_group(block_group);
2453         return 0;
2454 }
2455
2456 static void __btrfs_remove_free_space_cache_locked(
2457                                 struct btrfs_free_space_ctl *ctl)
2458 {
2459         struct btrfs_free_space *info;
2460         struct rb_node *node;
2461
2462         while ((node = rb_last(&ctl->free_space_offset)) != NULL) {
2463                 info = rb_entry(node, struct btrfs_free_space, offset_index);
2464                 if (!info->bitmap) {
2465                         unlink_free_space(ctl, info);
2466                         kmem_cache_free(btrfs_free_space_cachep, info);
2467                 } else {
2468                         free_bitmap(ctl, info);
2469                 }
2470
2471                 cond_resched_lock(&ctl->tree_lock);
2472         }
2473 }
2474
2475 void __btrfs_remove_free_space_cache(struct btrfs_free_space_ctl *ctl)
2476 {
2477         spin_lock(&ctl->tree_lock);
2478         __btrfs_remove_free_space_cache_locked(ctl);
2479         spin_unlock(&ctl->tree_lock);
2480 }
2481
2482 void btrfs_remove_free_space_cache(struct btrfs_block_group_cache *block_group)
2483 {
2484         struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
2485         struct btrfs_free_cluster *cluster;
2486         struct list_head *head;
2487
2488         spin_lock(&ctl->tree_lock);
2489         while ((head = block_group->cluster_list.next) !=
2490                &block_group->cluster_list) {
2491                 cluster = list_entry(head, struct btrfs_free_cluster,
2492                                      block_group_list);
2493
2494                 WARN_ON(cluster->block_group != block_group);
2495                 __btrfs_return_cluster_to_free_space(block_group, cluster);
2496
2497                 cond_resched_lock(&ctl->tree_lock);
2498         }
2499         __btrfs_remove_free_space_cache_locked(ctl);
2500         spin_unlock(&ctl->tree_lock);
2501
2502 }
2503
2504 u64 btrfs_find_space_for_alloc(struct btrfs_block_group_cache *block_group,
2505                                u64 offset, u64 bytes, u64 empty_size,
2506                                u64 *max_extent_size)
2507 {
2508         struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
2509         struct btrfs_free_space *entry = NULL;
2510         u64 bytes_search = bytes + empty_size;
2511         u64 ret = 0;
2512         u64 align_gap = 0;
2513         u64 align_gap_len = 0;
2514
2515         spin_lock(&ctl->tree_lock);
2516         entry = find_free_space(ctl, &offset, &bytes_search,
2517                                 block_group->full_stripe_len, max_extent_size);
2518         if (!entry)
2519                 goto out;
2520
2521         ret = offset;
2522         if (entry->bitmap) {
2523                 bitmap_clear_bits(ctl, entry, offset, bytes);
2524                 if (!entry->bytes)
2525                         free_bitmap(ctl, entry);
2526         } else {
2527                 unlink_free_space(ctl, entry);
2528                 align_gap_len = offset - entry->offset;
2529                 align_gap = entry->offset;
2530
2531                 entry->offset = offset + bytes;
2532                 WARN_ON(entry->bytes < bytes + align_gap_len);
2533
2534                 entry->bytes -= bytes + align_gap_len;
2535                 if (!entry->bytes)
2536                         kmem_cache_free(btrfs_free_space_cachep, entry);
2537                 else
2538                         link_free_space(ctl, entry);
2539         }
2540 out:
2541         spin_unlock(&ctl->tree_lock);
2542
2543         if (align_gap_len)
2544                 __btrfs_add_free_space(ctl, align_gap, align_gap_len);
2545         return ret;
2546 }
2547
2548 /*
2549  * given a cluster, put all of its extents back into the free space
2550  * cache.  If a block group is passed, this function will only free
2551  * a cluster that belongs to the passed block group.
2552  *
2553  * Otherwise, it'll get a reference on the block group pointed to by the
2554  * cluster and remove the cluster from it.
2555  */
2556 int btrfs_return_cluster_to_free_space(
2557                                struct btrfs_block_group_cache *block_group,
2558                                struct btrfs_free_cluster *cluster)
2559 {
2560         struct btrfs_free_space_ctl *ctl;
2561         int ret;
2562
2563         /* first, get a safe pointer to the block group */
2564         spin_lock(&cluster->lock);
2565         if (!block_group) {
2566                 block_group = cluster->block_group;
2567                 if (!block_group) {
2568                         spin_unlock(&cluster->lock);
2569                         return 0;
2570                 }
2571         } else if (cluster->block_group != block_group) {
2572                 /* someone else has already freed it don't redo their work */
2573                 spin_unlock(&cluster->lock);
2574                 return 0;
2575         }
2576         atomic_inc(&block_group->count);
2577         spin_unlock(&cluster->lock);
2578
2579         ctl = block_group->free_space_ctl;
2580
2581         /* now return any extents the cluster had on it */
2582         spin_lock(&ctl->tree_lock);
2583         ret = __btrfs_return_cluster_to_free_space(block_group, cluster);
2584         spin_unlock(&ctl->tree_lock);
2585
2586         /* finally drop our ref */
2587         btrfs_put_block_group(block_group);
2588         return ret;
2589 }
2590
2591 static u64 btrfs_alloc_from_bitmap(struct btrfs_block_group_cache *block_group,
2592                                    struct btrfs_free_cluster *cluster,
2593                                    struct btrfs_free_space *entry,
2594                                    u64 bytes, u64 min_start,
2595                                    u64 *max_extent_size)
2596 {
2597         struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
2598         int err;
2599         u64 search_start = cluster->window_start;
2600         u64 search_bytes = bytes;
2601         u64 ret = 0;
2602
2603         search_start = min_start;
2604         search_bytes = bytes;
2605
2606         err = search_bitmap(ctl, entry, &search_start, &search_bytes);
2607         if (err) {
2608                 if (search_bytes > *max_extent_size)
2609                         *max_extent_size = search_bytes;
2610                 return 0;
2611         }
2612
2613         ret = search_start;
2614         __bitmap_clear_bits(ctl, entry, ret, bytes);
2615
2616         return ret;
2617 }
2618
2619 /*
2620  * given a cluster, try to allocate 'bytes' from it, returns 0
2621  * if it couldn't find anything suitably large, or a logical disk offset
2622  * if things worked out
2623  */
2624 u64 btrfs_alloc_from_cluster(struct btrfs_block_group_cache *block_group,
2625                              struct btrfs_free_cluster *cluster, u64 bytes,
2626                              u64 min_start, u64 *max_extent_size)
2627 {
2628         struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
2629         struct btrfs_free_space *entry = NULL;
2630         struct rb_node *node;
2631         u64 ret = 0;
2632
2633         spin_lock(&cluster->lock);
2634         if (bytes > cluster->max_size)
2635                 goto out;
2636
2637         if (cluster->block_group != block_group)
2638                 goto out;
2639
2640         node = rb_first(&cluster->root);
2641         if (!node)
2642                 goto out;
2643
2644         entry = rb_entry(node, struct btrfs_free_space, offset_index);
2645         while (1) {
2646                 if (entry->bytes < bytes && entry->bytes > *max_extent_size)
2647                         *max_extent_size = entry->bytes;
2648
2649                 if (entry->bytes < bytes ||
2650                     (!entry->bitmap && entry->offset < min_start)) {
2651                         node = rb_next(&entry->offset_index);
2652                         if (!node)
2653                                 break;
2654                         entry = rb_entry(node, struct btrfs_free_space,
2655                                          offset_index);
2656                         continue;
2657                 }
2658
2659                 if (entry->bitmap) {
2660                         ret = btrfs_alloc_from_bitmap(block_group,
2661                                                       cluster, entry, bytes,
2662                                                       cluster->window_start,
2663                                                       max_extent_size);
2664                         if (ret == 0) {
2665                                 node = rb_next(&entry->offset_index);
2666                                 if (!node)
2667                                         break;
2668                                 entry = rb_entry(node, struct btrfs_free_space,
2669                                                  offset_index);
2670                                 continue;
2671                         }
2672                         cluster->window_start += bytes;
2673                 } else {
2674                         ret = entry->offset;
2675
2676                         entry->offset += bytes;
2677                         entry->bytes -= bytes;
2678                 }
2679
2680                 if (entry->bytes == 0)
2681                         rb_erase(&entry->offset_index, &cluster->root);
2682                 break;
2683         }
2684 out:
2685         spin_unlock(&cluster->lock);
2686
2687         if (!ret)
2688                 return 0;
2689
2690         spin_lock(&ctl->tree_lock);
2691
2692         ctl->free_space -= bytes;
2693         if (entry->bytes == 0) {
2694                 ctl->free_extents--;
2695                 if (entry->bitmap) {
2696                         kfree(entry->bitmap);
2697                         ctl->total_bitmaps--;
2698                         ctl->op->recalc_thresholds(ctl);
2699                 }
2700                 kmem_cache_free(btrfs_free_space_cachep, entry);
2701         }
2702
2703         spin_unlock(&ctl->tree_lock);
2704
2705         return ret;
2706 }
2707
2708 static int btrfs_bitmap_cluster(struct btrfs_block_group_cache *block_group,
2709                                 struct btrfs_free_space *entry,
2710                                 struct btrfs_free_cluster *cluster,
2711                                 u64 offset, u64 bytes,
2712                                 u64 cont1_bytes, u64 min_bytes)
2713 {
2714         struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
2715         unsigned long next_zero;
2716         unsigned long i;
2717         unsigned long want_bits;
2718         unsigned long min_bits;
2719         unsigned long found_bits;
2720         unsigned long start = 0;
2721         unsigned long total_found = 0;
2722         int ret;
2723
2724         i = offset_to_bit(entry->offset, ctl->unit,
2725                           max_t(u64, offset, entry->offset));
2726         want_bits = bytes_to_bits(bytes, ctl->unit);
2727         min_bits = bytes_to_bits(min_bytes, ctl->unit);
2728
2729 again:
2730         found_bits = 0;
2731         for_each_set_bit_from(i, entry->bitmap, BITS_PER_BITMAP) {
2732                 next_zero = find_next_zero_bit(entry->bitmap,
2733                                                BITS_PER_BITMAP, i);
2734                 if (next_zero - i >= min_bits) {
2735                         found_bits = next_zero - i;
2736                         break;
2737                 }
2738                 i = next_zero;
2739         }
2740
2741         if (!found_bits)
2742                 return -ENOSPC;
2743
2744         if (!total_found) {
2745                 start = i;
2746                 cluster->max_size = 0;
2747         }
2748
2749         total_found += found_bits;
2750
2751         if (cluster->max_size < found_bits * ctl->unit)
2752                 cluster->max_size = found_bits * ctl->unit;
2753
2754         if (total_found < want_bits || cluster->max_size < cont1_bytes) {
2755                 i = next_zero + 1;
2756                 goto again;
2757         }
2758
2759         cluster->window_start = start * ctl->unit + entry->offset;
2760         rb_erase(&entry->offset_index, &ctl->free_space_offset);
2761         ret = tree_insert_offset(&cluster->root, entry->offset,
2762                                  &entry->offset_index, 1);
2763         ASSERT(!ret); /* -EEXIST; Logic error */
2764
2765         trace_btrfs_setup_cluster(block_group, cluster,
2766                                   total_found * ctl->unit, 1);
2767         return 0;
2768 }
2769
2770 /*
2771  * This searches the block group for just extents to fill the cluster with.
2772  * Try to find a cluster with at least bytes total bytes, at least one
2773  * extent of cont1_bytes, and other clusters of at least min_bytes.
2774  */
2775 static noinline int
2776 setup_cluster_no_bitmap(struct btrfs_block_group_cache *block_group,
2777                         struct btrfs_free_cluster *cluster,
2778                         struct list_head *bitmaps, u64 offset, u64 bytes,
2779                         u64 cont1_bytes, u64 min_bytes)
2780 {
2781         struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
2782         struct btrfs_free_space *first = NULL;
2783         struct btrfs_free_space *entry = NULL;
2784         struct btrfs_free_space *last;
2785         struct rb_node *node;
2786         u64 window_free;
2787         u64 max_extent;
2788         u64 total_size = 0;
2789
2790         entry = tree_search_offset(ctl, offset, 0, 1);
2791         if (!entry)
2792                 return -ENOSPC;
2793
2794         /*
2795          * We don't want bitmaps, so just move along until we find a normal
2796          * extent entry.
2797          */
2798         while (entry->bitmap || entry->bytes < min_bytes) {
2799                 if (entry->bitmap && list_empty(&entry->list))
2800                         list_add_tail(&entry->list, bitmaps);
2801                 node = rb_next(&entry->offset_index);
2802                 if (!node)
2803                         return -ENOSPC;
2804                 entry = rb_entry(node, struct btrfs_free_space, offset_index);
2805         }
2806
2807         window_free = entry->bytes;
2808         max_extent = entry->bytes;
2809         first = entry;
2810         last = entry;
2811
2812         for (node = rb_next(&entry->offset_index); node;
2813              node = rb_next(&entry->offset_index)) {
2814                 entry = rb_entry(node, struct btrfs_free_space, offset_index);
2815
2816                 if (entry->bitmap) {
2817                         if (list_empty(&entry->list))
2818                                 list_add_tail(&entry->list, bitmaps);
2819                         continue;
2820                 }
2821
2822                 if (entry->bytes < min_bytes)
2823                         continue;
2824
2825                 last = entry;
2826                 window_free += entry->bytes;
2827                 if (entry->bytes > max_extent)
2828                         max_extent = entry->bytes;
2829         }
2830
2831         if (window_free < bytes || max_extent < cont1_bytes)
2832                 return -ENOSPC;
2833
2834         cluster->window_start = first->offset;
2835
2836         node = &first->offset_index;
2837
2838         /*
2839          * now we've found our entries, pull them out of the free space
2840          * cache and put them into the cluster rbtree
2841          */
2842         do {
2843                 int ret;
2844
2845                 entry = rb_entry(node, struct btrfs_free_space, offset_index);
2846                 node = rb_next(&entry->offset_index);
2847                 if (entry->bitmap || entry->bytes < min_bytes)
2848                         continue;
2849
2850                 rb_erase(&entry->offset_index, &ctl->free_space_offset);
2851                 ret = tree_insert_offset(&cluster->root, entry->offset,
2852                                          &entry->offset_index, 0);
2853                 total_size += entry->bytes;
2854                 ASSERT(!ret); /* -EEXIST; Logic error */
2855         } while (node && entry != last);
2856
2857         cluster->max_size = max_extent;
2858         trace_btrfs_setup_cluster(block_group, cluster, total_size, 0);
2859         return 0;
2860 }
2861
2862 /*
2863  * This specifically looks for bitmaps that may work in the cluster, we assume
2864  * that we have already failed to find extents that will work.
2865  */
2866 static noinline int
2867 setup_cluster_bitmap(struct btrfs_block_group_cache *block_group,
2868                      struct btrfs_free_cluster *cluster,
2869                      struct list_head *bitmaps, u64 offset, u64 bytes,
2870                      u64 cont1_bytes, u64 min_bytes)
2871 {
2872         struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
2873         struct btrfs_free_space *entry;
2874         int ret = -ENOSPC;
2875         u64 bitmap_offset = offset_to_bitmap(ctl, offset);
2876
2877         if (ctl->total_bitmaps == 0)
2878                 return -ENOSPC;
2879
2880         /*
2881          * The bitmap that covers offset won't be in the list unless offset
2882          * is just its start offset.
2883          */
2884         entry = list_first_entry(bitmaps, struct btrfs_free_space, list);
2885         if (entry->offset != bitmap_offset) {
2886                 entry = tree_search_offset(ctl, bitmap_offset, 1, 0);
2887                 if (entry && list_empty(&entry->list))
2888                         list_add(&entry->list, bitmaps);
2889         }
2890
2891         list_for_each_entry(entry, bitmaps, list) {
2892                 if (entry->bytes < bytes)
2893                         continue;
2894                 ret = btrfs_bitmap_cluster(block_group, entry, cluster, offset,
2895                                            bytes, cont1_bytes, min_bytes);
2896                 if (!ret)
2897                         return 0;
2898         }
2899
2900         /*
2901          * The bitmaps list has all the bitmaps that record free space
2902          * starting after offset, so no more search is required.
2903          */
2904         return -ENOSPC;
2905 }
2906
2907 /*
2908  * here we try to find a cluster of blocks in a block group.  The goal
2909  * is to find at least bytes+empty_size.
2910  * We might not find them all in one contiguous area.
2911  *
2912  * returns zero and sets up cluster if things worked out, otherwise
2913  * it returns -enospc
2914  */
2915 int btrfs_find_space_cluster(struct btrfs_root *root,
2916                              struct btrfs_block_group_cache *block_group,
2917                              struct btrfs_free_cluster *cluster,
2918                              u64 offset, u64 bytes, u64 empty_size)
2919 {
2920         struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
2921         struct btrfs_free_space *entry, *tmp;
2922         LIST_HEAD(bitmaps);
2923         u64 min_bytes;
2924         u64 cont1_bytes;
2925         int ret;
2926
2927         /*
2928          * Choose the minimum extent size we'll require for this
2929          * cluster.  For SSD_SPREAD, don't allow any fragmentation.
2930          * For metadata, allow allocates with smaller extents.  For
2931          * data, keep it dense.
2932          */
2933         if (btrfs_test_opt(root, SSD_SPREAD)) {
2934                 cont1_bytes = min_bytes = bytes + empty_size;
2935         } else if (block_group->flags & BTRFS_BLOCK_GROUP_METADATA) {
2936                 cont1_bytes = bytes;
2937                 min_bytes = block_group->sectorsize;
2938         } else {
2939                 cont1_bytes = max(bytes, (bytes + empty_size) >> 2);
2940                 min_bytes = block_group->sectorsize;
2941         }
2942
2943         spin_lock(&ctl->tree_lock);
2944
2945         /*
2946          * If we know we don't have enough space to make a cluster don't even
2947          * bother doing all the work to try and find one.
2948          */
2949         if (ctl->free_space < bytes) {
2950                 spin_unlock(&ctl->tree_lock);
2951                 return -ENOSPC;
2952         }
2953
2954         spin_lock(&cluster->lock);
2955
2956         /* someone already found a cluster, hooray */
2957         if (cluster->block_group) {
2958                 ret = 0;
2959                 goto out;
2960         }
2961
2962         trace_btrfs_find_cluster(block_group, offset, bytes, empty_size,
2963                                  min_bytes);
2964
2965         ret = setup_cluster_no_bitmap(block_group, cluster, &bitmaps, offset,
2966                                       bytes + empty_size,
2967                                       cont1_bytes, min_bytes);
2968         if (ret)
2969                 ret = setup_cluster_bitmap(block_group, cluster, &bitmaps,
2970                                            offset, bytes + empty_size,
2971                                            cont1_bytes, min_bytes);
2972
2973         /* Clear our temporary list */
2974         list_for_each_entry_safe(entry, tmp, &bitmaps, list)
2975                 list_del_init(&entry->list);
2976
2977         if (!ret) {
2978                 atomic_inc(&block_group->count);
2979                 list_add_tail(&cluster->block_group_list,
2980                               &block_group->cluster_list);
2981                 cluster->block_group = block_group;
2982         } else {
2983                 trace_btrfs_failed_cluster_setup(block_group);
2984         }
2985 out:
2986         spin_unlock(&cluster->lock);
2987         spin_unlock(&ctl->tree_lock);
2988
2989         return ret;
2990 }
2991
2992 /*
2993  * simple code to zero out a cluster
2994  */
2995 void btrfs_init_free_cluster(struct btrfs_free_cluster *cluster)
2996 {
2997         spin_lock_init(&cluster->lock);
2998         spin_lock_init(&cluster->refill_lock);
2999         cluster->root = RB_ROOT;
3000         cluster->max_size = 0;
3001         INIT_LIST_HEAD(&cluster->block_group_list);
3002         cluster->block_group = NULL;
3003 }
3004
3005 static int do_trimming(struct btrfs_block_group_cache *block_group,
3006                        u64 *total_trimmed, u64 start, u64 bytes,
3007                        u64 reserved_start, u64 reserved_bytes,
3008                        struct btrfs_trim_range *trim_entry)
3009 {
3010         struct btrfs_space_info *space_info = block_group->space_info;
3011         struct btrfs_fs_info *fs_info = block_group->fs_info;
3012         struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
3013         int ret;
3014         int update = 0;
3015         u64 trimmed = 0;
3016
3017         spin_lock(&space_info->lock);
3018         spin_lock(&block_group->lock);
3019         if (!block_group->ro) {
3020                 block_group->reserved += reserved_bytes;
3021                 space_info->bytes_reserved += reserved_bytes;
3022                 update = 1;
3023         }
3024         spin_unlock(&block_group->lock);
3025         spin_unlock(&space_info->lock);
3026
3027         ret = btrfs_discard_extent(fs_info->extent_root,
3028                                    start, bytes, &trimmed);
3029         if (!ret)
3030                 *total_trimmed += trimmed;
3031
3032         mutex_lock(&ctl->cache_writeout_mutex);
3033         btrfs_add_free_space(block_group, reserved_start, reserved_bytes);
3034         list_del(&trim_entry->list);
3035         mutex_unlock(&ctl->cache_writeout_mutex);
3036
3037         if (update) {
3038                 spin_lock(&space_info->lock);
3039                 spin_lock(&block_group->lock);
3040                 if (block_group->ro)
3041                         space_info->bytes_readonly += reserved_bytes;
3042                 block_group->reserved -= reserved_bytes;
3043                 space_info->bytes_reserved -= reserved_bytes;
3044                 spin_unlock(&space_info->lock);
3045                 spin_unlock(&block_group->lock);
3046         }
3047
3048         return ret;
3049 }
3050
3051 static int trim_no_bitmap(struct btrfs_block_group_cache *block_group,
3052                           u64 *total_trimmed, u64 start, u64 end, u64 minlen)
3053 {
3054         struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
3055         struct btrfs_free_space *entry;
3056         struct rb_node *node;
3057         int ret = 0;
3058         u64 extent_start;
3059         u64 extent_bytes;
3060         u64 bytes;
3061
3062         while (start < end) {
3063                 struct btrfs_trim_range trim_entry;
3064
3065                 mutex_lock(&ctl->cache_writeout_mutex);
3066                 spin_lock(&ctl->tree_lock);
3067
3068                 if (ctl->free_space < minlen) {
3069                         spin_unlock(&ctl->tree_lock);
3070                         mutex_unlock(&ctl->cache_writeout_mutex);
3071                         break;
3072                 }
3073
3074                 entry = tree_search_offset(ctl, start, 0, 1);
3075                 if (!entry) {
3076                         spin_unlock(&ctl->tree_lock);
3077                         mutex_unlock(&ctl->cache_writeout_mutex);
3078                         break;
3079                 }
3080
3081                 /* skip bitmaps */
3082                 while (entry->bitmap) {
3083                         node = rb_next(&entry->offset_index);
3084                         if (!node) {
3085                                 spin_unlock(&ctl->tree_lock);
3086                                 mutex_unlock(&ctl->cache_writeout_mutex);
3087                                 goto out;
3088                         }
3089                         entry = rb_entry(node, struct btrfs_free_space,
3090                                          offset_index);
3091                 }
3092
3093                 if (entry->offset >= end) {
3094                         spin_unlock(&ctl->tree_lock);
3095                         mutex_unlock(&ctl->cache_writeout_mutex);
3096                         break;
3097                 }
3098
3099                 extent_start = entry->offset;
3100                 extent_bytes = entry->bytes;
3101                 start = max(start, extent_start);
3102                 bytes = min(extent_start + extent_bytes, end) - start;
3103                 if (bytes < minlen) {
3104                         spin_unlock(&ctl->tree_lock);
3105                         mutex_unlock(&ctl->cache_writeout_mutex);
3106                         goto next;
3107                 }
3108
3109                 unlink_free_space(ctl, entry);
3110                 kmem_cache_free(btrfs_free_space_cachep, entry);
3111
3112                 spin_unlock(&ctl->tree_lock);
3113                 trim_entry.start = extent_start;
3114                 trim_entry.bytes = extent_bytes;
3115                 list_add_tail(&trim_entry.list, &ctl->trimming_ranges);
3116                 mutex_unlock(&ctl->cache_writeout_mutex);
3117
3118                 ret = do_trimming(block_group, total_trimmed, start, bytes,
3119                                   extent_start, extent_bytes, &trim_entry);
3120                 if (ret)
3121                         break;
3122 next:
3123                 start += bytes;
3124
3125                 if (fatal_signal_pending(current)) {
3126                         ret = -ERESTARTSYS;
3127                         break;
3128                 }
3129
3130                 cond_resched();
3131         }
3132 out:
3133         return ret;
3134 }
3135
3136 static int trim_bitmaps(struct btrfs_block_group_cache *block_group,
3137                         u64 *total_trimmed, u64 start, u64 end, u64 minlen)
3138 {
3139         struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
3140         struct btrfs_free_space *entry;
3141         int ret = 0;
3142         int ret2;
3143         u64 bytes;
3144         u64 offset = offset_to_bitmap(ctl, start);
3145
3146         while (offset < end) {
3147                 bool next_bitmap = false;
3148                 struct btrfs_trim_range trim_entry;
3149
3150                 mutex_lock(&ctl->cache_writeout_mutex);
3151                 spin_lock(&ctl->tree_lock);
3152
3153                 if (ctl->free_space < minlen) {
3154                         spin_unlock(&ctl->tree_lock);
3155                         mutex_unlock(&ctl->cache_writeout_mutex);
3156                         break;
3157                 }
3158
3159                 entry = tree_search_offset(ctl, offset, 1, 0);
3160                 if (!entry) {
3161                         spin_unlock(&ctl->tree_lock);
3162                         mutex_unlock(&ctl->cache_writeout_mutex);
3163                         next_bitmap = true;
3164                         goto next;
3165                 }
3166
3167                 bytes = minlen;
3168                 ret2 = search_bitmap(ctl, entry, &start, &bytes);
3169                 if (ret2 || start >= end) {
3170                         spin_unlock(&ctl->tree_lock);
3171                         mutex_unlock(&ctl->cache_writeout_mutex);
3172                         next_bitmap = true;
3173                         goto next;
3174                 }
3175
3176                 bytes = min(bytes, end - start);
3177                 if (bytes < minlen) {
3178                         spin_unlock(&ctl->tree_lock);
3179                         mutex_unlock(&ctl->cache_writeout_mutex);
3180                         goto next;
3181                 }
3182
3183                 bitmap_clear_bits(ctl, entry, start, bytes);
3184                 if (entry->bytes == 0)
3185                         free_bitmap(ctl, entry);
3186
3187                 spin_unlock(&ctl->tree_lock);
3188                 trim_entry.start = start;
3189                 trim_entry.bytes = bytes;
3190                 list_add_tail(&trim_entry.list, &ctl->trimming_ranges);
3191                 mutex_unlock(&ctl->cache_writeout_mutex);
3192
3193                 ret = do_trimming(block_group, total_trimmed, start, bytes,
3194                                   start, bytes, &trim_entry);
3195                 if (ret)
3196                         break;
3197 next:
3198                 if (next_bitmap) {
3199                         offset += BITS_PER_BITMAP * ctl->unit;
3200                 } else {
3201                         start += bytes;
3202                         if (start >= offset + BITS_PER_BITMAP * ctl->unit)
3203                                 offset += BITS_PER_BITMAP * ctl->unit;
3204                 }
3205
3206                 if (fatal_signal_pending(current)) {
3207                         ret = -ERESTARTSYS;
3208                         break;
3209                 }
3210
3211                 cond_resched();
3212         }
3213
3214         return ret;
3215 }
3216
3217 int btrfs_trim_block_group(struct btrfs_block_group_cache *block_group,
3218                            u64 *trimmed, u64 start, u64 end, u64 minlen)
3219 {
3220         int ret;
3221
3222         *trimmed = 0;
3223
3224         spin_lock(&block_group->lock);
3225         if (block_group->removed) {
3226                 spin_unlock(&block_group->lock);
3227                 return 0;
3228         }
3229         atomic_inc(&block_group->trimming);
3230         spin_unlock(&block_group->lock);
3231
3232         ret = trim_no_bitmap(block_group, trimmed, start, end, minlen);
3233         if (ret)
3234                 goto out;
3235
3236         ret = trim_bitmaps(block_group, trimmed, start, end, minlen);
3237 out:
3238         spin_lock(&block_group->lock);
3239         if (atomic_dec_and_test(&block_group->trimming) &&
3240             block_group->removed) {
3241                 struct extent_map_tree *em_tree;
3242                 struct extent_map *em;
3243
3244                 spin_unlock(&block_group->lock);
3245
3246                 lock_chunks(block_group->fs_info->chunk_root);
3247                 em_tree = &block_group->fs_info->mapping_tree.map_tree;
3248                 write_lock(&em_tree->lock);
3249                 em = lookup_extent_mapping(em_tree, block_group->key.objectid,
3250                                            1);
3251                 BUG_ON(!em); /* logic error, can't happen */
3252                 /*
3253                  * remove_extent_mapping() will delete us from the pinned_chunks
3254                  * list, which is protected by the chunk mutex.
3255                  */
3256                 remove_extent_mapping(em_tree, em);
3257                 write_unlock(&em_tree->lock);
3258                 unlock_chunks(block_group->fs_info->chunk_root);
3259
3260                 /* once for us and once for the tree */
3261                 free_extent_map(em);
3262                 free_extent_map(em);
3263
3264                 /*
3265                  * We've left one free space entry and other tasks trimming
3266                  * this block group have left 1 entry each one. Free them.
3267                  */
3268                 __btrfs_remove_free_space_cache(block_group->free_space_ctl);
3269         } else {
3270                 spin_unlock(&block_group->lock);
3271         }
3272
3273         return ret;
3274 }
3275
3276 /*
3277  * Find the left-most item in the cache tree, and then return the
3278  * smallest inode number in the item.
3279  *
3280  * Note: the returned inode number may not be the smallest one in
3281  * the tree, if the left-most item is a bitmap.
3282  */
3283 u64 btrfs_find_ino_for_alloc(struct btrfs_root *fs_root)
3284 {
3285         struct btrfs_free_space_ctl *ctl = fs_root->free_ino_ctl;
3286         struct btrfs_free_space *entry = NULL;
3287         u64 ino = 0;
3288
3289         spin_lock(&ctl->tree_lock);
3290
3291         if (RB_EMPTY_ROOT(&ctl->free_space_offset))
3292                 goto out;
3293
3294         entry = rb_entry(rb_first(&ctl->free_space_offset),
3295                          struct btrfs_free_space, offset_index);
3296
3297         if (!entry->bitmap) {
3298                 ino = entry->offset;
3299
3300                 unlink_free_space(ctl, entry);
3301                 entry->offset++;
3302                 entry->bytes--;
3303                 if (!entry->bytes)
3304                         kmem_cache_free(btrfs_free_space_cachep, entry);
3305                 else
3306                         link_free_space(ctl, entry);
3307         } else {
3308                 u64 offset = 0;
3309                 u64 count = 1;
3310                 int ret;
3311
3312                 ret = search_bitmap(ctl, entry, &offset, &count);
3313                 /* Logic error; Should be empty if it can't find anything */
3314                 ASSERT(!ret);
3315
3316                 ino = offset;
3317                 bitmap_clear_bits(ctl, entry, offset, 1);
3318                 if (entry->bytes == 0)
3319                         free_bitmap(ctl, entry);
3320         }
3321 out:
3322         spin_unlock(&ctl->tree_lock);
3323
3324         return ino;
3325 }
3326
3327 struct inode *lookup_free_ino_inode(struct btrfs_root *root,
3328                                     struct btrfs_path *path)
3329 {
3330         struct inode *inode = NULL;
3331
3332         spin_lock(&root->ino_cache_lock);
3333         if (root->ino_cache_inode)
3334                 inode = igrab(root->ino_cache_inode);
3335         spin_unlock(&root->ino_cache_lock);
3336         if (inode)
3337                 return inode;
3338
3339         inode = __lookup_free_space_inode(root, path, 0);
3340         if (IS_ERR(inode))
3341                 return inode;
3342
3343         spin_lock(&root->ino_cache_lock);
3344         if (!btrfs_fs_closing(root->fs_info))
3345                 root->ino_cache_inode = igrab(inode);
3346         spin_unlock(&root->ino_cache_lock);
3347
3348         return inode;
3349 }
3350
3351 int create_free_ino_inode(struct btrfs_root *root,
3352                           struct btrfs_trans_handle *trans,
3353                           struct btrfs_path *path)
3354 {
3355         return __create_free_space_inode(root, trans, path,
3356                                          BTRFS_FREE_INO_OBJECTID, 0);
3357 }
3358
3359 int load_free_ino_cache(struct btrfs_fs_info *fs_info, struct btrfs_root *root)
3360 {
3361         struct btrfs_free_space_ctl *ctl = root->free_ino_ctl;
3362         struct btrfs_path *path;
3363         struct inode *inode;
3364         int ret = 0;
3365         u64 root_gen = btrfs_root_generation(&root->root_item);
3366
3367         if (!btrfs_test_opt(root, INODE_MAP_CACHE))
3368                 return 0;
3369
3370         /*
3371          * If we're unmounting then just return, since this does a search on the
3372          * normal root and not the commit root and we could deadlock.
3373          */
3374         if (btrfs_fs_closing(fs_info))
3375                 return 0;
3376
3377         path = btrfs_alloc_path();
3378         if (!path)
3379                 return 0;
3380
3381         inode = lookup_free_ino_inode(root, path);
3382         if (IS_ERR(inode))
3383                 goto out;
3384
3385         if (root_gen != BTRFS_I(inode)->generation)
3386                 goto out_put;
3387
3388         ret = __load_free_space_cache(root, inode, ctl, path, 0);
3389
3390         if (ret < 0)
3391                 btrfs_err(fs_info,
3392                         "failed to load free ino cache for root %llu",
3393                         root->root_key.objectid);
3394 out_put:
3395         iput(inode);
3396 out:
3397         btrfs_free_path(path);
3398         return ret;
3399 }
3400
3401 int btrfs_write_out_ino_cache(struct btrfs_root *root,
3402                               struct btrfs_trans_handle *trans,
3403                               struct btrfs_path *path,
3404                               struct inode *inode)
3405 {
3406         struct btrfs_free_space_ctl *ctl = root->free_ino_ctl;
3407         int ret;
3408         struct btrfs_io_ctl io_ctl;
3409
3410         if (!btrfs_test_opt(root, INODE_MAP_CACHE))
3411                 return 0;
3412
3413         ret = __btrfs_write_out_cache(root, inode, ctl, NULL, &io_ctl,
3414                                       trans, path, 0) ||
3415                 btrfs_wait_cache_io(root, trans, NULL, &io_ctl, path, 0);
3416         if (ret) {
3417                 btrfs_delalloc_release_metadata(inode, inode->i_size);
3418 #ifdef DEBUG
3419                 btrfs_err(root->fs_info,
3420                         "failed to write free ino cache for root %llu",
3421                         root->root_key.objectid);
3422 #endif
3423         }
3424
3425         return ret;
3426 }
3427
3428 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
3429 /*
3430  * Use this if you need to make a bitmap or extent entry specifically, it
3431  * doesn't do any of the merging that add_free_space does, this acts a lot like
3432  * how the free space cache loading stuff works, so you can get really weird
3433  * configurations.
3434  */
3435 int test_add_free_space_entry(struct btrfs_block_group_cache *cache,
3436                               u64 offset, u64 bytes, bool bitmap)
3437 {
3438         struct btrfs_free_space_ctl *ctl = cache->free_space_ctl;
3439         struct btrfs_free_space *info = NULL, *bitmap_info;
3440         void *map = NULL;
3441         u64 bytes_added;
3442         int ret;
3443
3444 again:
3445         if (!info) {
3446                 info = kmem_cache_zalloc(btrfs_free_space_cachep, GFP_NOFS);
3447                 if (!info)
3448                         return -ENOMEM;
3449         }
3450
3451         if (!bitmap) {
3452                 spin_lock(&ctl->tree_lock);
3453                 info->offset = offset;
3454                 info->bytes = bytes;
3455                 ret = link_free_space(ctl, info);
3456                 spin_unlock(&ctl->tree_lock);
3457                 if (ret)
3458                         kmem_cache_free(btrfs_free_space_cachep, info);
3459                 return ret;
3460         }
3461
3462         if (!map) {
3463                 map = kzalloc(PAGE_CACHE_SIZE, GFP_NOFS);
3464                 if (!map) {
3465                         kmem_cache_free(btrfs_free_space_cachep, info);
3466                         return -ENOMEM;
3467                 }
3468         }
3469
3470         spin_lock(&ctl->tree_lock);
3471         bitmap_info = tree_search_offset(ctl, offset_to_bitmap(ctl, offset),
3472                                          1, 0);
3473         if (!bitmap_info) {
3474                 info->bitmap = map;
3475                 map = NULL;
3476                 add_new_bitmap(ctl, info, offset);
3477                 bitmap_info = info;
3478                 info = NULL;
3479         }
3480
3481         bytes_added = add_bytes_to_bitmap(ctl, bitmap_info, offset, bytes);
3482         bytes -= bytes_added;
3483         offset += bytes_added;
3484         spin_unlock(&ctl->tree_lock);
3485
3486         if (bytes)
3487                 goto again;
3488
3489         if (info)
3490                 kmem_cache_free(btrfs_free_space_cachep, info);
3491         if (map)
3492                 kfree(map);
3493         return 0;
3494 }
3495
3496 /*
3497  * Checks to see if the given range is in the free space cache.  This is really
3498  * just used to check the absence of space, so if there is free space in the
3499  * range at all we will return 1.
3500  */
3501 int test_check_exists(struct btrfs_block_group_cache *cache,
3502                       u64 offset, u64 bytes)
3503 {
3504         struct btrfs_free_space_ctl *ctl = cache->free_space_ctl;
3505         struct btrfs_free_space *info;
3506         int ret = 0;
3507
3508         spin_lock(&ctl->tree_lock);
3509         info = tree_search_offset(ctl, offset, 0, 0);
3510         if (!info) {
3511                 info = tree_search_offset(ctl, offset_to_bitmap(ctl, offset),
3512                                           1, 0);
3513                 if (!info)
3514                         goto out;
3515         }
3516
3517 have_info:
3518         if (info->bitmap) {
3519                 u64 bit_off, bit_bytes;
3520                 struct rb_node *n;
3521                 struct btrfs_free_space *tmp;
3522
3523                 bit_off = offset;
3524                 bit_bytes = ctl->unit;
3525                 ret = search_bitmap(ctl, info, &bit_off, &bit_bytes);
3526                 if (!ret) {
3527                         if (bit_off == offset) {
3528                                 ret = 1;
3529                                 goto out;
3530                         } else if (bit_off > offset &&
3531                                    offset + bytes > bit_off) {
3532                                 ret = 1;
3533                                 goto out;
3534                         }
3535                 }
3536
3537                 n = rb_prev(&info->offset_index);
3538                 while (n) {
3539                         tmp = rb_entry(n, struct btrfs_free_space,
3540                                        offset_index);
3541                         if (tmp->offset + tmp->bytes < offset)
3542                                 break;
3543                         if (offset + bytes < tmp->offset) {
3544                                 n = rb_prev(&info->offset_index);
3545                                 continue;
3546                         }
3547                         info = tmp;
3548                         goto have_info;
3549                 }
3550
3551                 n = rb_next(&info->offset_index);
3552                 while (n) {
3553                         tmp = rb_entry(n, struct btrfs_free_space,
3554                                        offset_index);
3555                         if (offset + bytes < tmp->offset)
3556                                 break;
3557                         if (tmp->offset + tmp->bytes < offset) {
3558                                 n = rb_next(&info->offset_index);
3559                                 continue;
3560                         }
3561                         info = tmp;
3562                         goto have_info;
3563                 }
3564
3565                 ret = 0;
3566                 goto out;
3567         }
3568
3569         if (info->offset == offset) {
3570                 ret = 1;
3571                 goto out;
3572         }
3573
3574         if (offset > info->offset && offset < info->offset + info->bytes)
3575                 ret = 1;
3576 out:
3577         spin_unlock(&ctl->tree_lock);
3578         return ret;
3579 }
3580 #endif /* CONFIG_BTRFS_FS_RUN_SANITY_TESTS */