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