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