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