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