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