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