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