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