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