xref: /openbmc/linux/fs/btrfs/free-space-tree.c (revision be709d48)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2015 Facebook.  All rights reserved.
4  */
5 
6 #include <linux/kernel.h>
7 #include <linux/sched/mm.h>
8 #include "ctree.h"
9 #include "disk-io.h"
10 #include "locking.h"
11 #include "free-space-tree.h"
12 #include "transaction.h"
13 
14 static int __add_block_group_free_space(struct btrfs_trans_handle *trans,
15 					struct btrfs_block_group_cache *block_group,
16 					struct btrfs_path *path);
17 
18 void set_free_space_tree_thresholds(struct btrfs_block_group_cache *cache)
19 {
20 	u32 bitmap_range;
21 	size_t bitmap_size;
22 	u64 num_bitmaps, total_bitmap_size;
23 
24 	/*
25 	 * We convert to bitmaps when the disk space required for using extents
26 	 * exceeds that required for using bitmaps.
27 	 */
28 	bitmap_range = cache->fs_info->sectorsize * BTRFS_FREE_SPACE_BITMAP_BITS;
29 	num_bitmaps = div_u64(cache->key.offset + bitmap_range - 1,
30 			      bitmap_range);
31 	bitmap_size = sizeof(struct btrfs_item) + BTRFS_FREE_SPACE_BITMAP_SIZE;
32 	total_bitmap_size = num_bitmaps * bitmap_size;
33 	cache->bitmap_high_thresh = div_u64(total_bitmap_size,
34 					    sizeof(struct btrfs_item));
35 
36 	/*
37 	 * We allow for a small buffer between the high threshold and low
38 	 * threshold to avoid thrashing back and forth between the two formats.
39 	 */
40 	if (cache->bitmap_high_thresh > 100)
41 		cache->bitmap_low_thresh = cache->bitmap_high_thresh - 100;
42 	else
43 		cache->bitmap_low_thresh = 0;
44 }
45 
46 static int add_new_free_space_info(struct btrfs_trans_handle *trans,
47 				   struct btrfs_block_group_cache *block_group,
48 				   struct btrfs_path *path)
49 {
50 	struct btrfs_root *root = trans->fs_info->free_space_root;
51 	struct btrfs_free_space_info *info;
52 	struct btrfs_key key;
53 	struct extent_buffer *leaf;
54 	int ret;
55 
56 	key.objectid = block_group->key.objectid;
57 	key.type = BTRFS_FREE_SPACE_INFO_KEY;
58 	key.offset = block_group->key.offset;
59 
60 	ret = btrfs_insert_empty_item(trans, root, path, &key, sizeof(*info));
61 	if (ret)
62 		goto out;
63 
64 	leaf = path->nodes[0];
65 	info = btrfs_item_ptr(leaf, path->slots[0],
66 			      struct btrfs_free_space_info);
67 	btrfs_set_free_space_extent_count(leaf, info, 0);
68 	btrfs_set_free_space_flags(leaf, info, 0);
69 	btrfs_mark_buffer_dirty(leaf);
70 
71 	ret = 0;
72 out:
73 	btrfs_release_path(path);
74 	return ret;
75 }
76 
77 EXPORT_FOR_TESTS
78 struct btrfs_free_space_info *search_free_space_info(
79 		struct btrfs_trans_handle *trans, struct btrfs_fs_info *fs_info,
80 		struct btrfs_block_group_cache *block_group,
81 		struct btrfs_path *path, int cow)
82 {
83 	struct btrfs_root *root = fs_info->free_space_root;
84 	struct btrfs_key key;
85 	int ret;
86 
87 	key.objectid = block_group->key.objectid;
88 	key.type = BTRFS_FREE_SPACE_INFO_KEY;
89 	key.offset = block_group->key.offset;
90 
91 	ret = btrfs_search_slot(trans, root, &key, path, 0, cow);
92 	if (ret < 0)
93 		return ERR_PTR(ret);
94 	if (ret != 0) {
95 		btrfs_warn(fs_info, "missing free space info for %llu",
96 			   block_group->key.objectid);
97 		ASSERT(0);
98 		return ERR_PTR(-ENOENT);
99 	}
100 
101 	return btrfs_item_ptr(path->nodes[0], path->slots[0],
102 			      struct btrfs_free_space_info);
103 }
104 
105 /*
106  * btrfs_search_slot() but we're looking for the greatest key less than the
107  * passed key.
108  */
109 static int btrfs_search_prev_slot(struct btrfs_trans_handle *trans,
110 				  struct btrfs_root *root,
111 				  struct btrfs_key *key, struct btrfs_path *p,
112 				  int ins_len, int cow)
113 {
114 	int ret;
115 
116 	ret = btrfs_search_slot(trans, root, key, p, ins_len, cow);
117 	if (ret < 0)
118 		return ret;
119 
120 	if (ret == 0) {
121 		ASSERT(0);
122 		return -EIO;
123 	}
124 
125 	if (p->slots[0] == 0) {
126 		ASSERT(0);
127 		return -EIO;
128 	}
129 	p->slots[0]--;
130 
131 	return 0;
132 }
133 
134 static inline u32 free_space_bitmap_size(u64 size, u32 sectorsize)
135 {
136 	return DIV_ROUND_UP((u32)div_u64(size, sectorsize), BITS_PER_BYTE);
137 }
138 
139 static unsigned long *alloc_bitmap(u32 bitmap_size)
140 {
141 	unsigned long *ret;
142 	unsigned int nofs_flag;
143 	u32 bitmap_rounded_size = round_up(bitmap_size, sizeof(unsigned long));
144 
145 	/*
146 	 * GFP_NOFS doesn't work with kvmalloc(), but we really can't recurse
147 	 * into the filesystem as the free space bitmap can be modified in the
148 	 * critical section of a transaction commit.
149 	 *
150 	 * TODO: push the memalloc_nofs_{save,restore}() to the caller where we
151 	 * know that recursion is unsafe.
152 	 */
153 	nofs_flag = memalloc_nofs_save();
154 	ret = kvzalloc(bitmap_rounded_size, GFP_KERNEL);
155 	memalloc_nofs_restore(nofs_flag);
156 	return ret;
157 }
158 
159 static void le_bitmap_set(unsigned long *map, unsigned int start, int len)
160 {
161 	u8 *p = ((u8 *)map) + BIT_BYTE(start);
162 	const unsigned int size = start + len;
163 	int bits_to_set = BITS_PER_BYTE - (start % BITS_PER_BYTE);
164 	u8 mask_to_set = BITMAP_FIRST_BYTE_MASK(start);
165 
166 	while (len - bits_to_set >= 0) {
167 		*p |= mask_to_set;
168 		len -= bits_to_set;
169 		bits_to_set = BITS_PER_BYTE;
170 		mask_to_set = ~0;
171 		p++;
172 	}
173 	if (len) {
174 		mask_to_set &= BITMAP_LAST_BYTE_MASK(size);
175 		*p |= mask_to_set;
176 	}
177 }
178 
179 EXPORT_FOR_TESTS
180 int convert_free_space_to_bitmaps(struct btrfs_trans_handle *trans,
181 				  struct btrfs_block_group_cache *block_group,
182 				  struct btrfs_path *path)
183 {
184 	struct btrfs_fs_info *fs_info = trans->fs_info;
185 	struct btrfs_root *root = fs_info->free_space_root;
186 	struct btrfs_free_space_info *info;
187 	struct btrfs_key key, found_key;
188 	struct extent_buffer *leaf;
189 	unsigned long *bitmap;
190 	char *bitmap_cursor;
191 	u64 start, end;
192 	u64 bitmap_range, i;
193 	u32 bitmap_size, flags, expected_extent_count;
194 	u32 extent_count = 0;
195 	int done = 0, nr;
196 	int ret;
197 
198 	bitmap_size = free_space_bitmap_size(block_group->key.offset,
199 					     fs_info->sectorsize);
200 	bitmap = alloc_bitmap(bitmap_size);
201 	if (!bitmap) {
202 		ret = -ENOMEM;
203 		goto out;
204 	}
205 
206 	start = block_group->key.objectid;
207 	end = block_group->key.objectid + block_group->key.offset;
208 
209 	key.objectid = end - 1;
210 	key.type = (u8)-1;
211 	key.offset = (u64)-1;
212 
213 	while (!done) {
214 		ret = btrfs_search_prev_slot(trans, root, &key, path, -1, 1);
215 		if (ret)
216 			goto out;
217 
218 		leaf = path->nodes[0];
219 		nr = 0;
220 		path->slots[0]++;
221 		while (path->slots[0] > 0) {
222 			btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0] - 1);
223 
224 			if (found_key.type == BTRFS_FREE_SPACE_INFO_KEY) {
225 				ASSERT(found_key.objectid == block_group->key.objectid);
226 				ASSERT(found_key.offset == block_group->key.offset);
227 				done = 1;
228 				break;
229 			} else if (found_key.type == BTRFS_FREE_SPACE_EXTENT_KEY) {
230 				u64 first, last;
231 
232 				ASSERT(found_key.objectid >= start);
233 				ASSERT(found_key.objectid < end);
234 				ASSERT(found_key.objectid + found_key.offset <= end);
235 
236 				first = div_u64(found_key.objectid - start,
237 						fs_info->sectorsize);
238 				last = div_u64(found_key.objectid + found_key.offset - start,
239 					       fs_info->sectorsize);
240 				le_bitmap_set(bitmap, first, last - first);
241 
242 				extent_count++;
243 				nr++;
244 				path->slots[0]--;
245 			} else {
246 				ASSERT(0);
247 			}
248 		}
249 
250 		ret = btrfs_del_items(trans, root, path, path->slots[0], nr);
251 		if (ret)
252 			goto out;
253 		btrfs_release_path(path);
254 	}
255 
256 	info = search_free_space_info(trans, fs_info, block_group, path, 1);
257 	if (IS_ERR(info)) {
258 		ret = PTR_ERR(info);
259 		goto out;
260 	}
261 	leaf = path->nodes[0];
262 	flags = btrfs_free_space_flags(leaf, info);
263 	flags |= BTRFS_FREE_SPACE_USING_BITMAPS;
264 	btrfs_set_free_space_flags(leaf, info, flags);
265 	expected_extent_count = btrfs_free_space_extent_count(leaf, info);
266 	btrfs_mark_buffer_dirty(leaf);
267 	btrfs_release_path(path);
268 
269 	if (extent_count != expected_extent_count) {
270 		btrfs_err(fs_info,
271 			  "incorrect extent count for %llu; counted %u, expected %u",
272 			  block_group->key.objectid, extent_count,
273 			  expected_extent_count);
274 		ASSERT(0);
275 		ret = -EIO;
276 		goto out;
277 	}
278 
279 	bitmap_cursor = (char *)bitmap;
280 	bitmap_range = fs_info->sectorsize * BTRFS_FREE_SPACE_BITMAP_BITS;
281 	i = start;
282 	while (i < end) {
283 		unsigned long ptr;
284 		u64 extent_size;
285 		u32 data_size;
286 
287 		extent_size = min(end - i, bitmap_range);
288 		data_size = free_space_bitmap_size(extent_size,
289 						   fs_info->sectorsize);
290 
291 		key.objectid = i;
292 		key.type = BTRFS_FREE_SPACE_BITMAP_KEY;
293 		key.offset = extent_size;
294 
295 		ret = btrfs_insert_empty_item(trans, root, path, &key,
296 					      data_size);
297 		if (ret)
298 			goto out;
299 
300 		leaf = path->nodes[0];
301 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
302 		write_extent_buffer(leaf, bitmap_cursor, ptr,
303 				    data_size);
304 		btrfs_mark_buffer_dirty(leaf);
305 		btrfs_release_path(path);
306 
307 		i += extent_size;
308 		bitmap_cursor += data_size;
309 	}
310 
311 	ret = 0;
312 out:
313 	kvfree(bitmap);
314 	if (ret)
315 		btrfs_abort_transaction(trans, ret);
316 	return ret;
317 }
318 
319 EXPORT_FOR_TESTS
320 int convert_free_space_to_extents(struct btrfs_trans_handle *trans,
321 				  struct btrfs_block_group_cache *block_group,
322 				  struct btrfs_path *path)
323 {
324 	struct btrfs_fs_info *fs_info = trans->fs_info;
325 	struct btrfs_root *root = fs_info->free_space_root;
326 	struct btrfs_free_space_info *info;
327 	struct btrfs_key key, found_key;
328 	struct extent_buffer *leaf;
329 	unsigned long *bitmap;
330 	u64 start, end;
331 	u32 bitmap_size, flags, expected_extent_count;
332 	unsigned long nrbits, start_bit, end_bit;
333 	u32 extent_count = 0;
334 	int done = 0, nr;
335 	int ret;
336 
337 	bitmap_size = free_space_bitmap_size(block_group->key.offset,
338 					     fs_info->sectorsize);
339 	bitmap = alloc_bitmap(bitmap_size);
340 	if (!bitmap) {
341 		ret = -ENOMEM;
342 		goto out;
343 	}
344 
345 	start = block_group->key.objectid;
346 	end = block_group->key.objectid + block_group->key.offset;
347 
348 	key.objectid = end - 1;
349 	key.type = (u8)-1;
350 	key.offset = (u64)-1;
351 
352 	while (!done) {
353 		ret = btrfs_search_prev_slot(trans, root, &key, path, -1, 1);
354 		if (ret)
355 			goto out;
356 
357 		leaf = path->nodes[0];
358 		nr = 0;
359 		path->slots[0]++;
360 		while (path->slots[0] > 0) {
361 			btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0] - 1);
362 
363 			if (found_key.type == BTRFS_FREE_SPACE_INFO_KEY) {
364 				ASSERT(found_key.objectid == block_group->key.objectid);
365 				ASSERT(found_key.offset == block_group->key.offset);
366 				done = 1;
367 				break;
368 			} else if (found_key.type == BTRFS_FREE_SPACE_BITMAP_KEY) {
369 				unsigned long ptr;
370 				char *bitmap_cursor;
371 				u32 bitmap_pos, data_size;
372 
373 				ASSERT(found_key.objectid >= start);
374 				ASSERT(found_key.objectid < end);
375 				ASSERT(found_key.objectid + found_key.offset <= end);
376 
377 				bitmap_pos = div_u64(found_key.objectid - start,
378 						     fs_info->sectorsize *
379 						     BITS_PER_BYTE);
380 				bitmap_cursor = ((char *)bitmap) + bitmap_pos;
381 				data_size = free_space_bitmap_size(found_key.offset,
382 								   fs_info->sectorsize);
383 
384 				ptr = btrfs_item_ptr_offset(leaf, path->slots[0] - 1);
385 				read_extent_buffer(leaf, bitmap_cursor, ptr,
386 						   data_size);
387 
388 				nr++;
389 				path->slots[0]--;
390 			} else {
391 				ASSERT(0);
392 			}
393 		}
394 
395 		ret = btrfs_del_items(trans, root, path, path->slots[0], nr);
396 		if (ret)
397 			goto out;
398 		btrfs_release_path(path);
399 	}
400 
401 	info = search_free_space_info(trans, fs_info, block_group, path, 1);
402 	if (IS_ERR(info)) {
403 		ret = PTR_ERR(info);
404 		goto out;
405 	}
406 	leaf = path->nodes[0];
407 	flags = btrfs_free_space_flags(leaf, info);
408 	flags &= ~BTRFS_FREE_SPACE_USING_BITMAPS;
409 	btrfs_set_free_space_flags(leaf, info, flags);
410 	expected_extent_count = btrfs_free_space_extent_count(leaf, info);
411 	btrfs_mark_buffer_dirty(leaf);
412 	btrfs_release_path(path);
413 
414 	nrbits = div_u64(block_group->key.offset, block_group->fs_info->sectorsize);
415 	start_bit = find_next_bit_le(bitmap, nrbits, 0);
416 
417 	while (start_bit < nrbits) {
418 		end_bit = find_next_zero_bit_le(bitmap, nrbits, start_bit);
419 		ASSERT(start_bit < end_bit);
420 
421 		key.objectid = start + start_bit * block_group->fs_info->sectorsize;
422 		key.type = BTRFS_FREE_SPACE_EXTENT_KEY;
423 		key.offset = (end_bit - start_bit) * block_group->fs_info->sectorsize;
424 
425 		ret = btrfs_insert_empty_item(trans, root, path, &key, 0);
426 		if (ret)
427 			goto out;
428 		btrfs_release_path(path);
429 
430 		extent_count++;
431 
432 		start_bit = find_next_bit_le(bitmap, nrbits, end_bit);
433 	}
434 
435 	if (extent_count != expected_extent_count) {
436 		btrfs_err(fs_info,
437 			  "incorrect extent count for %llu; counted %u, expected %u",
438 			  block_group->key.objectid, extent_count,
439 			  expected_extent_count);
440 		ASSERT(0);
441 		ret = -EIO;
442 		goto out;
443 	}
444 
445 	ret = 0;
446 out:
447 	kvfree(bitmap);
448 	if (ret)
449 		btrfs_abort_transaction(trans, ret);
450 	return ret;
451 }
452 
453 static int update_free_space_extent_count(struct btrfs_trans_handle *trans,
454 					  struct btrfs_block_group_cache *block_group,
455 					  struct btrfs_path *path,
456 					  int new_extents)
457 {
458 	struct btrfs_free_space_info *info;
459 	u32 flags;
460 	u32 extent_count;
461 	int ret = 0;
462 
463 	if (new_extents == 0)
464 		return 0;
465 
466 	info = search_free_space_info(trans, trans->fs_info, block_group, path,
467 				      1);
468 	if (IS_ERR(info)) {
469 		ret = PTR_ERR(info);
470 		goto out;
471 	}
472 	flags = btrfs_free_space_flags(path->nodes[0], info);
473 	extent_count = btrfs_free_space_extent_count(path->nodes[0], info);
474 
475 	extent_count += new_extents;
476 	btrfs_set_free_space_extent_count(path->nodes[0], info, extent_count);
477 	btrfs_mark_buffer_dirty(path->nodes[0]);
478 	btrfs_release_path(path);
479 
480 	if (!(flags & BTRFS_FREE_SPACE_USING_BITMAPS) &&
481 	    extent_count > block_group->bitmap_high_thresh) {
482 		ret = convert_free_space_to_bitmaps(trans, block_group, path);
483 	} else if ((flags & BTRFS_FREE_SPACE_USING_BITMAPS) &&
484 		   extent_count < block_group->bitmap_low_thresh) {
485 		ret = convert_free_space_to_extents(trans, block_group, path);
486 	}
487 
488 out:
489 	return ret;
490 }
491 
492 EXPORT_FOR_TESTS
493 int free_space_test_bit(struct btrfs_block_group_cache *block_group,
494 			struct btrfs_path *path, u64 offset)
495 {
496 	struct extent_buffer *leaf;
497 	struct btrfs_key key;
498 	u64 found_start, found_end;
499 	unsigned long ptr, i;
500 
501 	leaf = path->nodes[0];
502 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
503 	ASSERT(key.type == BTRFS_FREE_SPACE_BITMAP_KEY);
504 
505 	found_start = key.objectid;
506 	found_end = key.objectid + key.offset;
507 	ASSERT(offset >= found_start && offset < found_end);
508 
509 	ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
510 	i = div_u64(offset - found_start,
511 		    block_group->fs_info->sectorsize);
512 	return !!extent_buffer_test_bit(leaf, ptr, i);
513 }
514 
515 static void free_space_set_bits(struct btrfs_block_group_cache *block_group,
516 				struct btrfs_path *path, u64 *start, u64 *size,
517 				int bit)
518 {
519 	struct btrfs_fs_info *fs_info = block_group->fs_info;
520 	struct extent_buffer *leaf;
521 	struct btrfs_key key;
522 	u64 end = *start + *size;
523 	u64 found_start, found_end;
524 	unsigned long ptr, first, last;
525 
526 	leaf = path->nodes[0];
527 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
528 	ASSERT(key.type == BTRFS_FREE_SPACE_BITMAP_KEY);
529 
530 	found_start = key.objectid;
531 	found_end = key.objectid + key.offset;
532 	ASSERT(*start >= found_start && *start < found_end);
533 	ASSERT(end > found_start);
534 
535 	if (end > found_end)
536 		end = found_end;
537 
538 	ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
539 	first = div_u64(*start - found_start, fs_info->sectorsize);
540 	last = div_u64(end - found_start, fs_info->sectorsize);
541 	if (bit)
542 		extent_buffer_bitmap_set(leaf, ptr, first, last - first);
543 	else
544 		extent_buffer_bitmap_clear(leaf, ptr, first, last - first);
545 	btrfs_mark_buffer_dirty(leaf);
546 
547 	*size -= end - *start;
548 	*start = end;
549 }
550 
551 /*
552  * We can't use btrfs_next_item() in modify_free_space_bitmap() because
553  * btrfs_next_leaf() doesn't get the path for writing. We can forgo the fancy
554  * tree walking in btrfs_next_leaf() anyways because we know exactly what we're
555  * looking for.
556  */
557 static int free_space_next_bitmap(struct btrfs_trans_handle *trans,
558 				  struct btrfs_root *root, struct btrfs_path *p)
559 {
560 	struct btrfs_key key;
561 
562 	if (p->slots[0] + 1 < btrfs_header_nritems(p->nodes[0])) {
563 		p->slots[0]++;
564 		return 0;
565 	}
566 
567 	btrfs_item_key_to_cpu(p->nodes[0], &key, p->slots[0]);
568 	btrfs_release_path(p);
569 
570 	key.objectid += key.offset;
571 	key.type = (u8)-1;
572 	key.offset = (u64)-1;
573 
574 	return btrfs_search_prev_slot(trans, root, &key, p, 0, 1);
575 }
576 
577 /*
578  * If remove is 1, then we are removing free space, thus clearing bits in the
579  * bitmap. If remove is 0, then we are adding free space, thus setting bits in
580  * the bitmap.
581  */
582 static int modify_free_space_bitmap(struct btrfs_trans_handle *trans,
583 				    struct btrfs_block_group_cache *block_group,
584 				    struct btrfs_path *path,
585 				    u64 start, u64 size, int remove)
586 {
587 	struct btrfs_root *root = block_group->fs_info->free_space_root;
588 	struct btrfs_key key;
589 	u64 end = start + size;
590 	u64 cur_start, cur_size;
591 	int prev_bit, next_bit;
592 	int new_extents;
593 	int ret;
594 
595 	/*
596 	 * Read the bit for the block immediately before the extent of space if
597 	 * that block is within the block group.
598 	 */
599 	if (start > block_group->key.objectid) {
600 		u64 prev_block = start - block_group->fs_info->sectorsize;
601 
602 		key.objectid = prev_block;
603 		key.type = (u8)-1;
604 		key.offset = (u64)-1;
605 
606 		ret = btrfs_search_prev_slot(trans, root, &key, path, 0, 1);
607 		if (ret)
608 			goto out;
609 
610 		prev_bit = free_space_test_bit(block_group, path, prev_block);
611 
612 		/* The previous block may have been in the previous bitmap. */
613 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
614 		if (start >= key.objectid + key.offset) {
615 			ret = free_space_next_bitmap(trans, root, path);
616 			if (ret)
617 				goto out;
618 		}
619 	} else {
620 		key.objectid = start;
621 		key.type = (u8)-1;
622 		key.offset = (u64)-1;
623 
624 		ret = btrfs_search_prev_slot(trans, root, &key, path, 0, 1);
625 		if (ret)
626 			goto out;
627 
628 		prev_bit = -1;
629 	}
630 
631 	/*
632 	 * Iterate over all of the bitmaps overlapped by the extent of space,
633 	 * clearing/setting bits as required.
634 	 */
635 	cur_start = start;
636 	cur_size = size;
637 	while (1) {
638 		free_space_set_bits(block_group, path, &cur_start, &cur_size,
639 				    !remove);
640 		if (cur_size == 0)
641 			break;
642 		ret = free_space_next_bitmap(trans, root, path);
643 		if (ret)
644 			goto out;
645 	}
646 
647 	/*
648 	 * Read the bit for the block immediately after the extent of space if
649 	 * that block is within the block group.
650 	 */
651 	if (end < block_group->key.objectid + block_group->key.offset) {
652 		/* The next block may be in the next bitmap. */
653 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
654 		if (end >= key.objectid + key.offset) {
655 			ret = free_space_next_bitmap(trans, root, path);
656 			if (ret)
657 				goto out;
658 		}
659 
660 		next_bit = free_space_test_bit(block_group, path, end);
661 	} else {
662 		next_bit = -1;
663 	}
664 
665 	if (remove) {
666 		new_extents = -1;
667 		if (prev_bit == 1) {
668 			/* Leftover on the left. */
669 			new_extents++;
670 		}
671 		if (next_bit == 1) {
672 			/* Leftover on the right. */
673 			new_extents++;
674 		}
675 	} else {
676 		new_extents = 1;
677 		if (prev_bit == 1) {
678 			/* Merging with neighbor on the left. */
679 			new_extents--;
680 		}
681 		if (next_bit == 1) {
682 			/* Merging with neighbor on the right. */
683 			new_extents--;
684 		}
685 	}
686 
687 	btrfs_release_path(path);
688 	ret = update_free_space_extent_count(trans, block_group, path,
689 					     new_extents);
690 
691 out:
692 	return ret;
693 }
694 
695 static int remove_free_space_extent(struct btrfs_trans_handle *trans,
696 				    struct btrfs_block_group_cache *block_group,
697 				    struct btrfs_path *path,
698 				    u64 start, u64 size)
699 {
700 	struct btrfs_root *root = trans->fs_info->free_space_root;
701 	struct btrfs_key key;
702 	u64 found_start, found_end;
703 	u64 end = start + size;
704 	int new_extents = -1;
705 	int ret;
706 
707 	key.objectid = start;
708 	key.type = (u8)-1;
709 	key.offset = (u64)-1;
710 
711 	ret = btrfs_search_prev_slot(trans, root, &key, path, -1, 1);
712 	if (ret)
713 		goto out;
714 
715 	btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
716 
717 	ASSERT(key.type == BTRFS_FREE_SPACE_EXTENT_KEY);
718 
719 	found_start = key.objectid;
720 	found_end = key.objectid + key.offset;
721 	ASSERT(start >= found_start && end <= found_end);
722 
723 	/*
724 	 * Okay, now that we've found the free space extent which contains the
725 	 * free space that we are removing, there are four cases:
726 	 *
727 	 * 1. We're using the whole extent: delete the key we found and
728 	 * decrement the free space extent count.
729 	 * 2. We are using part of the extent starting at the beginning: delete
730 	 * the key we found and insert a new key representing the leftover at
731 	 * the end. There is no net change in the number of extents.
732 	 * 3. We are using part of the extent ending at the end: delete the key
733 	 * we found and insert a new key representing the leftover at the
734 	 * beginning. There is no net change in the number of extents.
735 	 * 4. We are using part of the extent in the middle: delete the key we
736 	 * found and insert two new keys representing the leftovers on each
737 	 * side. Where we used to have one extent, we now have two, so increment
738 	 * the extent count. We may need to convert the block group to bitmaps
739 	 * as a result.
740 	 */
741 
742 	/* Delete the existing key (cases 1-4). */
743 	ret = btrfs_del_item(trans, root, path);
744 	if (ret)
745 		goto out;
746 
747 	/* Add a key for leftovers at the beginning (cases 3 and 4). */
748 	if (start > found_start) {
749 		key.objectid = found_start;
750 		key.type = BTRFS_FREE_SPACE_EXTENT_KEY;
751 		key.offset = start - found_start;
752 
753 		btrfs_release_path(path);
754 		ret = btrfs_insert_empty_item(trans, root, path, &key, 0);
755 		if (ret)
756 			goto out;
757 		new_extents++;
758 	}
759 
760 	/* Add a key for leftovers at the end (cases 2 and 4). */
761 	if (end < found_end) {
762 		key.objectid = end;
763 		key.type = BTRFS_FREE_SPACE_EXTENT_KEY;
764 		key.offset = found_end - end;
765 
766 		btrfs_release_path(path);
767 		ret = btrfs_insert_empty_item(trans, root, path, &key, 0);
768 		if (ret)
769 			goto out;
770 		new_extents++;
771 	}
772 
773 	btrfs_release_path(path);
774 	ret = update_free_space_extent_count(trans, block_group, path,
775 					     new_extents);
776 
777 out:
778 	return ret;
779 }
780 
781 EXPORT_FOR_TESTS
782 int __remove_from_free_space_tree(struct btrfs_trans_handle *trans,
783 				  struct btrfs_block_group_cache *block_group,
784 				  struct btrfs_path *path, u64 start, u64 size)
785 {
786 	struct btrfs_free_space_info *info;
787 	u32 flags;
788 	int ret;
789 
790 	if (block_group->needs_free_space) {
791 		ret = __add_block_group_free_space(trans, block_group, path);
792 		if (ret)
793 			return ret;
794 	}
795 
796 	info = search_free_space_info(NULL, trans->fs_info, block_group, path,
797 				      0);
798 	if (IS_ERR(info))
799 		return PTR_ERR(info);
800 	flags = btrfs_free_space_flags(path->nodes[0], info);
801 	btrfs_release_path(path);
802 
803 	if (flags & BTRFS_FREE_SPACE_USING_BITMAPS) {
804 		return modify_free_space_bitmap(trans, block_group, path,
805 						start, size, 1);
806 	} else {
807 		return remove_free_space_extent(trans, block_group, path,
808 						start, size);
809 	}
810 }
811 
812 int remove_from_free_space_tree(struct btrfs_trans_handle *trans,
813 				u64 start, u64 size)
814 {
815 	struct btrfs_block_group_cache *block_group;
816 	struct btrfs_path *path;
817 	int ret;
818 
819 	if (!btrfs_fs_compat_ro(trans->fs_info, FREE_SPACE_TREE))
820 		return 0;
821 
822 	path = btrfs_alloc_path();
823 	if (!path) {
824 		ret = -ENOMEM;
825 		goto out;
826 	}
827 
828 	block_group = btrfs_lookup_block_group(trans->fs_info, start);
829 	if (!block_group) {
830 		ASSERT(0);
831 		ret = -ENOENT;
832 		goto out;
833 	}
834 
835 	mutex_lock(&block_group->free_space_lock);
836 	ret = __remove_from_free_space_tree(trans, block_group, path, start,
837 					    size);
838 	mutex_unlock(&block_group->free_space_lock);
839 
840 	btrfs_put_block_group(block_group);
841 out:
842 	btrfs_free_path(path);
843 	if (ret)
844 		btrfs_abort_transaction(trans, ret);
845 	return ret;
846 }
847 
848 static int add_free_space_extent(struct btrfs_trans_handle *trans,
849 				 struct btrfs_block_group_cache *block_group,
850 				 struct btrfs_path *path,
851 				 u64 start, u64 size)
852 {
853 	struct btrfs_root *root = trans->fs_info->free_space_root;
854 	struct btrfs_key key, new_key;
855 	u64 found_start, found_end;
856 	u64 end = start + size;
857 	int new_extents = 1;
858 	int ret;
859 
860 	/*
861 	 * We are adding a new extent of free space, but we need to merge
862 	 * extents. There are four cases here:
863 	 *
864 	 * 1. The new extent does not have any immediate neighbors to merge
865 	 * with: add the new key and increment the free space extent count. We
866 	 * may need to convert the block group to bitmaps as a result.
867 	 * 2. The new extent has an immediate neighbor before it: remove the
868 	 * previous key and insert a new key combining both of them. There is no
869 	 * net change in the number of extents.
870 	 * 3. The new extent has an immediate neighbor after it: remove the next
871 	 * key and insert a new key combining both of them. There is no net
872 	 * change in the number of extents.
873 	 * 4. The new extent has immediate neighbors on both sides: remove both
874 	 * of the keys and insert a new key combining all of them. Where we used
875 	 * to have two extents, we now have one, so decrement the extent count.
876 	 */
877 
878 	new_key.objectid = start;
879 	new_key.type = BTRFS_FREE_SPACE_EXTENT_KEY;
880 	new_key.offset = size;
881 
882 	/* Search for a neighbor on the left. */
883 	if (start == block_group->key.objectid)
884 		goto right;
885 	key.objectid = start - 1;
886 	key.type = (u8)-1;
887 	key.offset = (u64)-1;
888 
889 	ret = btrfs_search_prev_slot(trans, root, &key, path, -1, 1);
890 	if (ret)
891 		goto out;
892 
893 	btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
894 
895 	if (key.type != BTRFS_FREE_SPACE_EXTENT_KEY) {
896 		ASSERT(key.type == BTRFS_FREE_SPACE_INFO_KEY);
897 		btrfs_release_path(path);
898 		goto right;
899 	}
900 
901 	found_start = key.objectid;
902 	found_end = key.objectid + key.offset;
903 	ASSERT(found_start >= block_group->key.objectid &&
904 	       found_end > block_group->key.objectid);
905 	ASSERT(found_start < start && found_end <= start);
906 
907 	/*
908 	 * Delete the neighbor on the left and absorb it into the new key (cases
909 	 * 2 and 4).
910 	 */
911 	if (found_end == start) {
912 		ret = btrfs_del_item(trans, root, path);
913 		if (ret)
914 			goto out;
915 		new_key.objectid = found_start;
916 		new_key.offset += key.offset;
917 		new_extents--;
918 	}
919 	btrfs_release_path(path);
920 
921 right:
922 	/* Search for a neighbor on the right. */
923 	if (end == block_group->key.objectid + block_group->key.offset)
924 		goto insert;
925 	key.objectid = end;
926 	key.type = (u8)-1;
927 	key.offset = (u64)-1;
928 
929 	ret = btrfs_search_prev_slot(trans, root, &key, path, -1, 1);
930 	if (ret)
931 		goto out;
932 
933 	btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
934 
935 	if (key.type != BTRFS_FREE_SPACE_EXTENT_KEY) {
936 		ASSERT(key.type == BTRFS_FREE_SPACE_INFO_KEY);
937 		btrfs_release_path(path);
938 		goto insert;
939 	}
940 
941 	found_start = key.objectid;
942 	found_end = key.objectid + key.offset;
943 	ASSERT(found_start >= block_group->key.objectid &&
944 	       found_end > block_group->key.objectid);
945 	ASSERT((found_start < start && found_end <= start) ||
946 	       (found_start >= end && found_end > end));
947 
948 	/*
949 	 * Delete the neighbor on the right and absorb it into the new key
950 	 * (cases 3 and 4).
951 	 */
952 	if (found_start == end) {
953 		ret = btrfs_del_item(trans, root, path);
954 		if (ret)
955 			goto out;
956 		new_key.offset += key.offset;
957 		new_extents--;
958 	}
959 	btrfs_release_path(path);
960 
961 insert:
962 	/* Insert the new key (cases 1-4). */
963 	ret = btrfs_insert_empty_item(trans, root, path, &new_key, 0);
964 	if (ret)
965 		goto out;
966 
967 	btrfs_release_path(path);
968 	ret = update_free_space_extent_count(trans, block_group, path,
969 					     new_extents);
970 
971 out:
972 	return ret;
973 }
974 
975 EXPORT_FOR_TESTS
976 int __add_to_free_space_tree(struct btrfs_trans_handle *trans,
977 			     struct btrfs_block_group_cache *block_group,
978 			     struct btrfs_path *path, u64 start, u64 size)
979 {
980 	struct btrfs_fs_info *fs_info = trans->fs_info;
981 	struct btrfs_free_space_info *info;
982 	u32 flags;
983 	int ret;
984 
985 	if (block_group->needs_free_space) {
986 		ret = __add_block_group_free_space(trans, block_group, path);
987 		if (ret)
988 			return ret;
989 	}
990 
991 	info = search_free_space_info(NULL, fs_info, block_group, path, 0);
992 	if (IS_ERR(info))
993 		return PTR_ERR(info);
994 	flags = btrfs_free_space_flags(path->nodes[0], info);
995 	btrfs_release_path(path);
996 
997 	if (flags & BTRFS_FREE_SPACE_USING_BITMAPS) {
998 		return modify_free_space_bitmap(trans, block_group, path,
999 						start, size, 0);
1000 	} else {
1001 		return add_free_space_extent(trans, block_group, path, start,
1002 					     size);
1003 	}
1004 }
1005 
1006 int add_to_free_space_tree(struct btrfs_trans_handle *trans,
1007 			   u64 start, u64 size)
1008 {
1009 	struct btrfs_block_group_cache *block_group;
1010 	struct btrfs_path *path;
1011 	int ret;
1012 
1013 	if (!btrfs_fs_compat_ro(trans->fs_info, FREE_SPACE_TREE))
1014 		return 0;
1015 
1016 	path = btrfs_alloc_path();
1017 	if (!path) {
1018 		ret = -ENOMEM;
1019 		goto out;
1020 	}
1021 
1022 	block_group = btrfs_lookup_block_group(trans->fs_info, start);
1023 	if (!block_group) {
1024 		ASSERT(0);
1025 		ret = -ENOENT;
1026 		goto out;
1027 	}
1028 
1029 	mutex_lock(&block_group->free_space_lock);
1030 	ret = __add_to_free_space_tree(trans, block_group, path, start, size);
1031 	mutex_unlock(&block_group->free_space_lock);
1032 
1033 	btrfs_put_block_group(block_group);
1034 out:
1035 	btrfs_free_path(path);
1036 	if (ret)
1037 		btrfs_abort_transaction(trans, ret);
1038 	return ret;
1039 }
1040 
1041 /*
1042  * Populate the free space tree by walking the extent tree. Operations on the
1043  * extent tree that happen as a result of writes to the free space tree will go
1044  * through the normal add/remove hooks.
1045  */
1046 static int populate_free_space_tree(struct btrfs_trans_handle *trans,
1047 				    struct btrfs_block_group_cache *block_group)
1048 {
1049 	struct btrfs_root *extent_root = trans->fs_info->extent_root;
1050 	struct btrfs_path *path, *path2;
1051 	struct btrfs_key key;
1052 	u64 start, end;
1053 	int ret;
1054 
1055 	path = btrfs_alloc_path();
1056 	if (!path)
1057 		return -ENOMEM;
1058 	path->reada = READA_FORWARD;
1059 
1060 	path2 = btrfs_alloc_path();
1061 	if (!path2) {
1062 		btrfs_free_path(path);
1063 		return -ENOMEM;
1064 	}
1065 
1066 	ret = add_new_free_space_info(trans, block_group, path2);
1067 	if (ret)
1068 		goto out;
1069 
1070 	mutex_lock(&block_group->free_space_lock);
1071 
1072 	/*
1073 	 * Iterate through all of the extent and metadata items in this block
1074 	 * group, adding the free space between them and the free space at the
1075 	 * end. Note that EXTENT_ITEM and METADATA_ITEM are less than
1076 	 * BLOCK_GROUP_ITEM, so an extent may precede the block group that it's
1077 	 * contained in.
1078 	 */
1079 	key.objectid = block_group->key.objectid;
1080 	key.type = BTRFS_EXTENT_ITEM_KEY;
1081 	key.offset = 0;
1082 
1083 	ret = btrfs_search_slot_for_read(extent_root, &key, path, 1, 0);
1084 	if (ret < 0)
1085 		goto out_locked;
1086 	ASSERT(ret == 0);
1087 
1088 	start = block_group->key.objectid;
1089 	end = block_group->key.objectid + block_group->key.offset;
1090 	while (1) {
1091 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1092 
1093 		if (key.type == BTRFS_EXTENT_ITEM_KEY ||
1094 		    key.type == BTRFS_METADATA_ITEM_KEY) {
1095 			if (key.objectid >= end)
1096 				break;
1097 
1098 			if (start < key.objectid) {
1099 				ret = __add_to_free_space_tree(trans,
1100 							       block_group,
1101 							       path2, start,
1102 							       key.objectid -
1103 							       start);
1104 				if (ret)
1105 					goto out_locked;
1106 			}
1107 			start = key.objectid;
1108 			if (key.type == BTRFS_METADATA_ITEM_KEY)
1109 				start += trans->fs_info->nodesize;
1110 			else
1111 				start += key.offset;
1112 		} else if (key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
1113 			if (key.objectid != block_group->key.objectid)
1114 				break;
1115 		}
1116 
1117 		ret = btrfs_next_item(extent_root, path);
1118 		if (ret < 0)
1119 			goto out_locked;
1120 		if (ret)
1121 			break;
1122 	}
1123 	if (start < end) {
1124 		ret = __add_to_free_space_tree(trans, block_group, path2,
1125 					       start, end - start);
1126 		if (ret)
1127 			goto out_locked;
1128 	}
1129 
1130 	ret = 0;
1131 out_locked:
1132 	mutex_unlock(&block_group->free_space_lock);
1133 out:
1134 	btrfs_free_path(path2);
1135 	btrfs_free_path(path);
1136 	return ret;
1137 }
1138 
1139 int btrfs_create_free_space_tree(struct btrfs_fs_info *fs_info)
1140 {
1141 	struct btrfs_trans_handle *trans;
1142 	struct btrfs_root *tree_root = fs_info->tree_root;
1143 	struct btrfs_root *free_space_root;
1144 	struct btrfs_block_group_cache *block_group;
1145 	struct rb_node *node;
1146 	int ret;
1147 
1148 	trans = btrfs_start_transaction(tree_root, 0);
1149 	if (IS_ERR(trans))
1150 		return PTR_ERR(trans);
1151 
1152 	set_bit(BTRFS_FS_CREATING_FREE_SPACE_TREE, &fs_info->flags);
1153 	free_space_root = btrfs_create_tree(trans, fs_info,
1154 					    BTRFS_FREE_SPACE_TREE_OBJECTID);
1155 	if (IS_ERR(free_space_root)) {
1156 		ret = PTR_ERR(free_space_root);
1157 		goto abort;
1158 	}
1159 	fs_info->free_space_root = free_space_root;
1160 
1161 	node = rb_first(&fs_info->block_group_cache_tree);
1162 	while (node) {
1163 		block_group = rb_entry(node, struct btrfs_block_group_cache,
1164 				       cache_node);
1165 		ret = populate_free_space_tree(trans, block_group);
1166 		if (ret)
1167 			goto abort;
1168 		node = rb_next(node);
1169 	}
1170 
1171 	btrfs_set_fs_compat_ro(fs_info, FREE_SPACE_TREE);
1172 	btrfs_set_fs_compat_ro(fs_info, FREE_SPACE_TREE_VALID);
1173 	clear_bit(BTRFS_FS_CREATING_FREE_SPACE_TREE, &fs_info->flags);
1174 
1175 	return btrfs_commit_transaction(trans);
1176 
1177 abort:
1178 	clear_bit(BTRFS_FS_CREATING_FREE_SPACE_TREE, &fs_info->flags);
1179 	btrfs_abort_transaction(trans, ret);
1180 	btrfs_end_transaction(trans);
1181 	return ret;
1182 }
1183 
1184 static int clear_free_space_tree(struct btrfs_trans_handle *trans,
1185 				 struct btrfs_root *root)
1186 {
1187 	struct btrfs_path *path;
1188 	struct btrfs_key key;
1189 	int nr;
1190 	int ret;
1191 
1192 	path = btrfs_alloc_path();
1193 	if (!path)
1194 		return -ENOMEM;
1195 
1196 	path->leave_spinning = 1;
1197 
1198 	key.objectid = 0;
1199 	key.type = 0;
1200 	key.offset = 0;
1201 
1202 	while (1) {
1203 		ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1204 		if (ret < 0)
1205 			goto out;
1206 
1207 		nr = btrfs_header_nritems(path->nodes[0]);
1208 		if (!nr)
1209 			break;
1210 
1211 		path->slots[0] = 0;
1212 		ret = btrfs_del_items(trans, root, path, 0, nr);
1213 		if (ret)
1214 			goto out;
1215 
1216 		btrfs_release_path(path);
1217 	}
1218 
1219 	ret = 0;
1220 out:
1221 	btrfs_free_path(path);
1222 	return ret;
1223 }
1224 
1225 int btrfs_clear_free_space_tree(struct btrfs_fs_info *fs_info)
1226 {
1227 	struct btrfs_trans_handle *trans;
1228 	struct btrfs_root *tree_root = fs_info->tree_root;
1229 	struct btrfs_root *free_space_root = fs_info->free_space_root;
1230 	int ret;
1231 
1232 	trans = btrfs_start_transaction(tree_root, 0);
1233 	if (IS_ERR(trans))
1234 		return PTR_ERR(trans);
1235 
1236 	btrfs_clear_fs_compat_ro(fs_info, FREE_SPACE_TREE);
1237 	btrfs_clear_fs_compat_ro(fs_info, FREE_SPACE_TREE_VALID);
1238 	fs_info->free_space_root = NULL;
1239 
1240 	ret = clear_free_space_tree(trans, free_space_root);
1241 	if (ret)
1242 		goto abort;
1243 
1244 	ret = btrfs_del_root(trans, &free_space_root->root_key);
1245 	if (ret)
1246 		goto abort;
1247 
1248 	list_del(&free_space_root->dirty_list);
1249 
1250 	btrfs_tree_lock(free_space_root->node);
1251 	clean_tree_block(fs_info, free_space_root->node);
1252 	btrfs_tree_unlock(free_space_root->node);
1253 	btrfs_free_tree_block(trans, free_space_root, free_space_root->node,
1254 			      0, 1);
1255 
1256 	free_extent_buffer(free_space_root->node);
1257 	free_extent_buffer(free_space_root->commit_root);
1258 	kfree(free_space_root);
1259 
1260 	return btrfs_commit_transaction(trans);
1261 
1262 abort:
1263 	btrfs_abort_transaction(trans, ret);
1264 	btrfs_end_transaction(trans);
1265 	return ret;
1266 }
1267 
1268 static int __add_block_group_free_space(struct btrfs_trans_handle *trans,
1269 					struct btrfs_block_group_cache *block_group,
1270 					struct btrfs_path *path)
1271 {
1272 	int ret;
1273 
1274 	block_group->needs_free_space = 0;
1275 
1276 	ret = add_new_free_space_info(trans, block_group, path);
1277 	if (ret)
1278 		return ret;
1279 
1280 	return __add_to_free_space_tree(trans, block_group, path,
1281 					block_group->key.objectid,
1282 					block_group->key.offset);
1283 }
1284 
1285 int add_block_group_free_space(struct btrfs_trans_handle *trans,
1286 			       struct btrfs_block_group_cache *block_group)
1287 {
1288 	struct btrfs_fs_info *fs_info = trans->fs_info;
1289 	struct btrfs_path *path = NULL;
1290 	int ret = 0;
1291 
1292 	if (!btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE))
1293 		return 0;
1294 
1295 	mutex_lock(&block_group->free_space_lock);
1296 	if (!block_group->needs_free_space)
1297 		goto out;
1298 
1299 	path = btrfs_alloc_path();
1300 	if (!path) {
1301 		ret = -ENOMEM;
1302 		goto out;
1303 	}
1304 
1305 	ret = __add_block_group_free_space(trans, block_group, path);
1306 
1307 out:
1308 	btrfs_free_path(path);
1309 	mutex_unlock(&block_group->free_space_lock);
1310 	if (ret)
1311 		btrfs_abort_transaction(trans, ret);
1312 	return ret;
1313 }
1314 
1315 int remove_block_group_free_space(struct btrfs_trans_handle *trans,
1316 				  struct btrfs_block_group_cache *block_group)
1317 {
1318 	struct btrfs_root *root = trans->fs_info->free_space_root;
1319 	struct btrfs_path *path;
1320 	struct btrfs_key key, found_key;
1321 	struct extent_buffer *leaf;
1322 	u64 start, end;
1323 	int done = 0, nr;
1324 	int ret;
1325 
1326 	if (!btrfs_fs_compat_ro(trans->fs_info, FREE_SPACE_TREE))
1327 		return 0;
1328 
1329 	if (block_group->needs_free_space) {
1330 		/* We never added this block group to the free space tree. */
1331 		return 0;
1332 	}
1333 
1334 	path = btrfs_alloc_path();
1335 	if (!path) {
1336 		ret = -ENOMEM;
1337 		goto out;
1338 	}
1339 
1340 	start = block_group->key.objectid;
1341 	end = block_group->key.objectid + block_group->key.offset;
1342 
1343 	key.objectid = end - 1;
1344 	key.type = (u8)-1;
1345 	key.offset = (u64)-1;
1346 
1347 	while (!done) {
1348 		ret = btrfs_search_prev_slot(trans, root, &key, path, -1, 1);
1349 		if (ret)
1350 			goto out;
1351 
1352 		leaf = path->nodes[0];
1353 		nr = 0;
1354 		path->slots[0]++;
1355 		while (path->slots[0] > 0) {
1356 			btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0] - 1);
1357 
1358 			if (found_key.type == BTRFS_FREE_SPACE_INFO_KEY) {
1359 				ASSERT(found_key.objectid == block_group->key.objectid);
1360 				ASSERT(found_key.offset == block_group->key.offset);
1361 				done = 1;
1362 				nr++;
1363 				path->slots[0]--;
1364 				break;
1365 			} else if (found_key.type == BTRFS_FREE_SPACE_EXTENT_KEY ||
1366 				   found_key.type == BTRFS_FREE_SPACE_BITMAP_KEY) {
1367 				ASSERT(found_key.objectid >= start);
1368 				ASSERT(found_key.objectid < end);
1369 				ASSERT(found_key.objectid + found_key.offset <= end);
1370 				nr++;
1371 				path->slots[0]--;
1372 			} else {
1373 				ASSERT(0);
1374 			}
1375 		}
1376 
1377 		ret = btrfs_del_items(trans, root, path, path->slots[0], nr);
1378 		if (ret)
1379 			goto out;
1380 		btrfs_release_path(path);
1381 	}
1382 
1383 	ret = 0;
1384 out:
1385 	btrfs_free_path(path);
1386 	if (ret)
1387 		btrfs_abort_transaction(trans, ret);
1388 	return ret;
1389 }
1390 
1391 static int load_free_space_bitmaps(struct btrfs_caching_control *caching_ctl,
1392 				   struct btrfs_path *path,
1393 				   u32 expected_extent_count)
1394 {
1395 	struct btrfs_block_group_cache *block_group;
1396 	struct btrfs_fs_info *fs_info;
1397 	struct btrfs_root *root;
1398 	struct btrfs_key key;
1399 	int prev_bit = 0, bit;
1400 	/* Initialize to silence GCC. */
1401 	u64 extent_start = 0;
1402 	u64 end, offset;
1403 	u64 total_found = 0;
1404 	u32 extent_count = 0;
1405 	int ret;
1406 
1407 	block_group = caching_ctl->block_group;
1408 	fs_info = block_group->fs_info;
1409 	root = fs_info->free_space_root;
1410 
1411 	end = block_group->key.objectid + block_group->key.offset;
1412 
1413 	while (1) {
1414 		ret = btrfs_next_item(root, path);
1415 		if (ret < 0)
1416 			goto out;
1417 		if (ret)
1418 			break;
1419 
1420 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1421 
1422 		if (key.type == BTRFS_FREE_SPACE_INFO_KEY)
1423 			break;
1424 
1425 		ASSERT(key.type == BTRFS_FREE_SPACE_BITMAP_KEY);
1426 		ASSERT(key.objectid < end && key.objectid + key.offset <= end);
1427 
1428 		caching_ctl->progress = key.objectid;
1429 
1430 		offset = key.objectid;
1431 		while (offset < key.objectid + key.offset) {
1432 			bit = free_space_test_bit(block_group, path, offset);
1433 			if (prev_bit == 0 && bit == 1) {
1434 				extent_start = offset;
1435 			} else if (prev_bit == 1 && bit == 0) {
1436 				total_found += add_new_free_space(block_group,
1437 								  extent_start,
1438 								  offset);
1439 				if (total_found > CACHING_CTL_WAKE_UP) {
1440 					total_found = 0;
1441 					wake_up(&caching_ctl->wait);
1442 				}
1443 				extent_count++;
1444 			}
1445 			prev_bit = bit;
1446 			offset += fs_info->sectorsize;
1447 		}
1448 	}
1449 	if (prev_bit == 1) {
1450 		total_found += add_new_free_space(block_group, extent_start,
1451 						  end);
1452 		extent_count++;
1453 	}
1454 
1455 	if (extent_count != expected_extent_count) {
1456 		btrfs_err(fs_info,
1457 			  "incorrect extent count for %llu; counted %u, expected %u",
1458 			  block_group->key.objectid, extent_count,
1459 			  expected_extent_count);
1460 		ASSERT(0);
1461 		ret = -EIO;
1462 		goto out;
1463 	}
1464 
1465 	caching_ctl->progress = (u64)-1;
1466 
1467 	ret = 0;
1468 out:
1469 	return ret;
1470 }
1471 
1472 static int load_free_space_extents(struct btrfs_caching_control *caching_ctl,
1473 				   struct btrfs_path *path,
1474 				   u32 expected_extent_count)
1475 {
1476 	struct btrfs_block_group_cache *block_group;
1477 	struct btrfs_fs_info *fs_info;
1478 	struct btrfs_root *root;
1479 	struct btrfs_key key;
1480 	u64 end;
1481 	u64 total_found = 0;
1482 	u32 extent_count = 0;
1483 	int ret;
1484 
1485 	block_group = caching_ctl->block_group;
1486 	fs_info = block_group->fs_info;
1487 	root = fs_info->free_space_root;
1488 
1489 	end = block_group->key.objectid + block_group->key.offset;
1490 
1491 	while (1) {
1492 		ret = btrfs_next_item(root, path);
1493 		if (ret < 0)
1494 			goto out;
1495 		if (ret)
1496 			break;
1497 
1498 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1499 
1500 		if (key.type == BTRFS_FREE_SPACE_INFO_KEY)
1501 			break;
1502 
1503 		ASSERT(key.type == BTRFS_FREE_SPACE_EXTENT_KEY);
1504 		ASSERT(key.objectid < end && key.objectid + key.offset <= end);
1505 
1506 		caching_ctl->progress = key.objectid;
1507 
1508 		total_found += add_new_free_space(block_group, key.objectid,
1509 						  key.objectid + key.offset);
1510 		if (total_found > CACHING_CTL_WAKE_UP) {
1511 			total_found = 0;
1512 			wake_up(&caching_ctl->wait);
1513 		}
1514 		extent_count++;
1515 	}
1516 
1517 	if (extent_count != expected_extent_count) {
1518 		btrfs_err(fs_info,
1519 			  "incorrect extent count for %llu; counted %u, expected %u",
1520 			  block_group->key.objectid, extent_count,
1521 			  expected_extent_count);
1522 		ASSERT(0);
1523 		ret = -EIO;
1524 		goto out;
1525 	}
1526 
1527 	caching_ctl->progress = (u64)-1;
1528 
1529 	ret = 0;
1530 out:
1531 	return ret;
1532 }
1533 
1534 int load_free_space_tree(struct btrfs_caching_control *caching_ctl)
1535 {
1536 	struct btrfs_block_group_cache *block_group;
1537 	struct btrfs_fs_info *fs_info;
1538 	struct btrfs_free_space_info *info;
1539 	struct btrfs_path *path;
1540 	u32 extent_count, flags;
1541 	int ret;
1542 
1543 	block_group = caching_ctl->block_group;
1544 	fs_info = block_group->fs_info;
1545 
1546 	path = btrfs_alloc_path();
1547 	if (!path)
1548 		return -ENOMEM;
1549 
1550 	/*
1551 	 * Just like caching_thread() doesn't want to deadlock on the extent
1552 	 * tree, we don't want to deadlock on the free space tree.
1553 	 */
1554 	path->skip_locking = 1;
1555 	path->search_commit_root = 1;
1556 	path->reada = READA_FORWARD;
1557 
1558 	info = search_free_space_info(NULL, fs_info, block_group, path, 0);
1559 	if (IS_ERR(info)) {
1560 		ret = PTR_ERR(info);
1561 		goto out;
1562 	}
1563 	extent_count = btrfs_free_space_extent_count(path->nodes[0], info);
1564 	flags = btrfs_free_space_flags(path->nodes[0], info);
1565 
1566 	/*
1567 	 * We left path pointing to the free space info item, so now
1568 	 * load_free_space_foo can just iterate through the free space tree from
1569 	 * there.
1570 	 */
1571 	if (flags & BTRFS_FREE_SPACE_USING_BITMAPS)
1572 		ret = load_free_space_bitmaps(caching_ctl, path, extent_count);
1573 	else
1574 		ret = load_free_space_extents(caching_ctl, path, extent_count);
1575 
1576 out:
1577 	btrfs_free_path(path);
1578 	return ret;
1579 }
1580