1 /*
2  * Copyright (C) 2007,2008 Oracle.  All rights reserved.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public
6  * License v2 as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public
14  * License along with this program; if not, write to the
15  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16  * Boston, MA 021110-1307, USA.
17  */
18 
19 #include <linux/sched.h>
20 #include <linux/slab.h>
21 #include "ctree.h"
22 #include "disk-io.h"
23 #include "transaction.h"
24 #include "print-tree.h"
25 #include "locking.h"
26 
27 static int split_node(struct btrfs_trans_handle *trans, struct btrfs_root
28 		      *root, struct btrfs_path *path, int level);
29 static int split_leaf(struct btrfs_trans_handle *trans, struct btrfs_root
30 		      *root, struct btrfs_key *ins_key,
31 		      struct btrfs_path *path, int data_size, int extend);
32 static int push_node_left(struct btrfs_trans_handle *trans,
33 			  struct btrfs_root *root, struct extent_buffer *dst,
34 			  struct extent_buffer *src, int empty);
35 static int balance_node_right(struct btrfs_trans_handle *trans,
36 			      struct btrfs_root *root,
37 			      struct extent_buffer *dst_buf,
38 			      struct extent_buffer *src_buf);
39 static void del_ptr(struct btrfs_trans_handle *trans, struct btrfs_root *root,
40 		   struct btrfs_path *path, int level, int slot);
41 
btrfs_alloc_path(void)42 struct btrfs_path *btrfs_alloc_path(void)
43 {
44 	struct btrfs_path *path;
45 	path = kmem_cache_zalloc(btrfs_path_cachep, GFP_NOFS);
46 	return path;
47 }
48 
49 /*
50  * set all locked nodes in the path to blocking locks.  This should
51  * be done before scheduling
52  */
btrfs_set_path_blocking(struct btrfs_path * p)53 noinline void btrfs_set_path_blocking(struct btrfs_path *p)
54 {
55 	int i;
56 	for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
57 		if (!p->nodes[i] || !p->locks[i])
58 			continue;
59 		btrfs_set_lock_blocking_rw(p->nodes[i], p->locks[i]);
60 		if (p->locks[i] == BTRFS_READ_LOCK)
61 			p->locks[i] = BTRFS_READ_LOCK_BLOCKING;
62 		else if (p->locks[i] == BTRFS_WRITE_LOCK)
63 			p->locks[i] = BTRFS_WRITE_LOCK_BLOCKING;
64 	}
65 }
66 
67 /*
68  * reset all the locked nodes in the patch to spinning locks.
69  *
70  * held is used to keep lockdep happy, when lockdep is enabled
71  * we set held to a blocking lock before we go around and
72  * retake all the spinlocks in the path.  You can safely use NULL
73  * for held
74  */
btrfs_clear_path_blocking(struct btrfs_path * p,struct extent_buffer * held,int held_rw)75 noinline void btrfs_clear_path_blocking(struct btrfs_path *p,
76 					struct extent_buffer *held, int held_rw)
77 {
78 	int i;
79 
80 #ifdef CONFIG_DEBUG_LOCK_ALLOC
81 	/* lockdep really cares that we take all of these spinlocks
82 	 * in the right order.  If any of the locks in the path are not
83 	 * currently blocking, it is going to complain.  So, make really
84 	 * really sure by forcing the path to blocking before we clear
85 	 * the path blocking.
86 	 */
87 	if (held) {
88 		btrfs_set_lock_blocking_rw(held, held_rw);
89 		if (held_rw == BTRFS_WRITE_LOCK)
90 			held_rw = BTRFS_WRITE_LOCK_BLOCKING;
91 		else if (held_rw == BTRFS_READ_LOCK)
92 			held_rw = BTRFS_READ_LOCK_BLOCKING;
93 	}
94 	btrfs_set_path_blocking(p);
95 #endif
96 
97 	for (i = BTRFS_MAX_LEVEL - 1; i >= 0; i--) {
98 		if (p->nodes[i] && p->locks[i]) {
99 			btrfs_clear_lock_blocking_rw(p->nodes[i], p->locks[i]);
100 			if (p->locks[i] == BTRFS_WRITE_LOCK_BLOCKING)
101 				p->locks[i] = BTRFS_WRITE_LOCK;
102 			else if (p->locks[i] == BTRFS_READ_LOCK_BLOCKING)
103 				p->locks[i] = BTRFS_READ_LOCK;
104 		}
105 	}
106 
107 #ifdef CONFIG_DEBUG_LOCK_ALLOC
108 	if (held)
109 		btrfs_clear_lock_blocking_rw(held, held_rw);
110 #endif
111 }
112 
113 /* this also releases the path */
btrfs_free_path(struct btrfs_path * p)114 void btrfs_free_path(struct btrfs_path *p)
115 {
116 	if (!p)
117 		return;
118 	btrfs_release_path(p);
119 	kmem_cache_free(btrfs_path_cachep, p);
120 }
121 
122 /*
123  * path release drops references on the extent buffers in the path
124  * and it drops any locks held by this path
125  *
126  * It is safe to call this on paths that no locks or extent buffers held.
127  */
btrfs_release_path(struct btrfs_path * p)128 noinline void btrfs_release_path(struct btrfs_path *p)
129 {
130 	int i;
131 
132 	for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
133 		p->slots[i] = 0;
134 		if (!p->nodes[i])
135 			continue;
136 		if (p->locks[i]) {
137 			btrfs_tree_unlock_rw(p->nodes[i], p->locks[i]);
138 			p->locks[i] = 0;
139 		}
140 		free_extent_buffer(p->nodes[i]);
141 		p->nodes[i] = NULL;
142 	}
143 }
144 
145 /*
146  * safely gets a reference on the root node of a tree.  A lock
147  * is not taken, so a concurrent writer may put a different node
148  * at the root of the tree.  See btrfs_lock_root_node for the
149  * looping required.
150  *
151  * The extent buffer returned by this has a reference taken, so
152  * it won't disappear.  It may stop being the root of the tree
153  * at any time because there are no locks held.
154  */
btrfs_root_node(struct btrfs_root * root)155 struct extent_buffer *btrfs_root_node(struct btrfs_root *root)
156 {
157 	struct extent_buffer *eb;
158 
159 	while (1) {
160 		rcu_read_lock();
161 		eb = rcu_dereference(root->node);
162 
163 		/*
164 		 * RCU really hurts here, we could free up the root node because
165 		 * it was cow'ed but we may not get the new root node yet so do
166 		 * the inc_not_zero dance and if it doesn't work then
167 		 * synchronize_rcu and try again.
168 		 */
169 		if (atomic_inc_not_zero(&eb->refs)) {
170 			rcu_read_unlock();
171 			break;
172 		}
173 		rcu_read_unlock();
174 		synchronize_rcu();
175 	}
176 	return eb;
177 }
178 
179 /* loop around taking references on and locking the root node of the
180  * tree until you end up with a lock on the root.  A locked buffer
181  * is returned, with a reference held.
182  */
btrfs_lock_root_node(struct btrfs_root * root)183 struct extent_buffer *btrfs_lock_root_node(struct btrfs_root *root)
184 {
185 	struct extent_buffer *eb;
186 
187 	while (1) {
188 		eb = btrfs_root_node(root);
189 		btrfs_tree_lock(eb);
190 		if (eb == root->node)
191 			break;
192 		btrfs_tree_unlock(eb);
193 		free_extent_buffer(eb);
194 	}
195 	return eb;
196 }
197 
198 /* loop around taking references on and locking the root node of the
199  * tree until you end up with a lock on the root.  A locked buffer
200  * is returned, with a reference held.
201  */
btrfs_read_lock_root_node(struct btrfs_root * root)202 struct extent_buffer *btrfs_read_lock_root_node(struct btrfs_root *root)
203 {
204 	struct extent_buffer *eb;
205 
206 	while (1) {
207 		eb = btrfs_root_node(root);
208 		btrfs_tree_read_lock(eb);
209 		if (eb == root->node)
210 			break;
211 		btrfs_tree_read_unlock(eb);
212 		free_extent_buffer(eb);
213 	}
214 	return eb;
215 }
216 
217 /* cowonly root (everything not a reference counted cow subvolume), just get
218  * put onto a simple dirty list.  transaction.c walks this to make sure they
219  * get properly updated on disk.
220  */
add_root_to_dirty_list(struct btrfs_root * root)221 static void add_root_to_dirty_list(struct btrfs_root *root)
222 {
223 	spin_lock(&root->fs_info->trans_lock);
224 	if (root->track_dirty && list_empty(&root->dirty_list)) {
225 		list_add(&root->dirty_list,
226 			 &root->fs_info->dirty_cowonly_roots);
227 	}
228 	spin_unlock(&root->fs_info->trans_lock);
229 }
230 
231 /*
232  * used by snapshot creation to make a copy of a root for a tree with
233  * a given objectid.  The buffer with the new root node is returned in
234  * cow_ret, and this func returns zero on success or a negative error code.
235  */
btrfs_copy_root(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct extent_buffer * buf,struct extent_buffer ** cow_ret,u64 new_root_objectid)236 int btrfs_copy_root(struct btrfs_trans_handle *trans,
237 		      struct btrfs_root *root,
238 		      struct extent_buffer *buf,
239 		      struct extent_buffer **cow_ret, u64 new_root_objectid)
240 {
241 	struct extent_buffer *cow;
242 	int ret = 0;
243 	int level;
244 	struct btrfs_disk_key disk_key;
245 
246 	WARN_ON(root->ref_cows && trans->transid !=
247 		root->fs_info->running_transaction->transid);
248 	WARN_ON(root->ref_cows && trans->transid != root->last_trans);
249 
250 	level = btrfs_header_level(buf);
251 	if (level == 0)
252 		btrfs_item_key(buf, &disk_key, 0);
253 	else
254 		btrfs_node_key(buf, &disk_key, 0);
255 
256 	cow = btrfs_alloc_free_block(trans, root, buf->len, 0,
257 				     new_root_objectid, &disk_key, level,
258 				     buf->start, 0, 1);
259 	if (IS_ERR(cow))
260 		return PTR_ERR(cow);
261 
262 	copy_extent_buffer(cow, buf, 0, 0, cow->len);
263 	btrfs_set_header_bytenr(cow, cow->start);
264 	btrfs_set_header_generation(cow, trans->transid);
265 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
266 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
267 				     BTRFS_HEADER_FLAG_RELOC);
268 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
269 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
270 	else
271 		btrfs_set_header_owner(cow, new_root_objectid);
272 
273 	write_extent_buffer(cow, root->fs_info->fsid,
274 			    (unsigned long)btrfs_header_fsid(cow),
275 			    BTRFS_FSID_SIZE);
276 
277 	WARN_ON(btrfs_header_generation(buf) > trans->transid);
278 	if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
279 		ret = btrfs_inc_ref(trans, root, cow, 1, 1);
280 	else
281 		ret = btrfs_inc_ref(trans, root, cow, 0, 1);
282 
283 	if (ret)
284 		return ret;
285 
286 	btrfs_mark_buffer_dirty(cow);
287 	*cow_ret = cow;
288 	return 0;
289 }
290 
291 /*
292  * check if the tree block can be shared by multiple trees
293  */
btrfs_block_can_be_shared(struct btrfs_root * root,struct extent_buffer * buf)294 int btrfs_block_can_be_shared(struct btrfs_root *root,
295 			      struct extent_buffer *buf)
296 {
297 	/*
298 	 * Tree blocks not in refernece counted trees and tree roots
299 	 * are never shared. If a block was allocated after the last
300 	 * snapshot and the block was not allocated by tree relocation,
301 	 * we know the block is not shared.
302 	 */
303 	if (root->ref_cows &&
304 	    buf != root->node && buf != root->commit_root &&
305 	    (btrfs_header_generation(buf) <=
306 	     btrfs_root_last_snapshot(&root->root_item) ||
307 	     btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)))
308 		return 1;
309 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
310 	if (root->ref_cows &&
311 	    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
312 		return 1;
313 #endif
314 	return 0;
315 }
316 
update_ref_for_cow(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct extent_buffer * buf,struct extent_buffer * cow,int * last_ref)317 static noinline int update_ref_for_cow(struct btrfs_trans_handle *trans,
318 				       struct btrfs_root *root,
319 				       struct extent_buffer *buf,
320 				       struct extent_buffer *cow,
321 				       int *last_ref)
322 {
323 	u64 refs;
324 	u64 owner;
325 	u64 flags;
326 	u64 new_flags = 0;
327 	int ret;
328 
329 	/*
330 	 * Backrefs update rules:
331 	 *
332 	 * Always use full backrefs for extent pointers in tree block
333 	 * allocated by tree relocation.
334 	 *
335 	 * If a shared tree block is no longer referenced by its owner
336 	 * tree (btrfs_header_owner(buf) == root->root_key.objectid),
337 	 * use full backrefs for extent pointers in tree block.
338 	 *
339 	 * If a tree block is been relocating
340 	 * (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID),
341 	 * use full backrefs for extent pointers in tree block.
342 	 * The reason for this is some operations (such as drop tree)
343 	 * are only allowed for blocks use full backrefs.
344 	 */
345 
346 	if (btrfs_block_can_be_shared(root, buf)) {
347 		ret = btrfs_lookup_extent_info(trans, root, buf->start,
348 					       buf->len, &refs, &flags);
349 		if (ret)
350 			return ret;
351 		if (refs == 0) {
352 			ret = -EROFS;
353 			btrfs_std_error(root->fs_info, ret);
354 			return ret;
355 		}
356 	} else {
357 		refs = 1;
358 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
359 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
360 			flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
361 		else
362 			flags = 0;
363 	}
364 
365 	owner = btrfs_header_owner(buf);
366 	BUG_ON(owner == BTRFS_TREE_RELOC_OBJECTID &&
367 	       !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
368 
369 	if (refs > 1) {
370 		if ((owner == root->root_key.objectid ||
371 		     root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) &&
372 		    !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
373 			ret = btrfs_inc_ref(trans, root, buf, 1, 1);
374 			BUG_ON(ret); /* -ENOMEM */
375 
376 			if (root->root_key.objectid ==
377 			    BTRFS_TREE_RELOC_OBJECTID) {
378 				ret = btrfs_dec_ref(trans, root, buf, 0, 1);
379 				BUG_ON(ret); /* -ENOMEM */
380 				ret = btrfs_inc_ref(trans, root, cow, 1, 1);
381 				BUG_ON(ret); /* -ENOMEM */
382 			}
383 			new_flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
384 		} else {
385 
386 			if (root->root_key.objectid ==
387 			    BTRFS_TREE_RELOC_OBJECTID)
388 				ret = btrfs_inc_ref(trans, root, cow, 1, 1);
389 			else
390 				ret = btrfs_inc_ref(trans, root, cow, 0, 1);
391 			BUG_ON(ret); /* -ENOMEM */
392 		}
393 		if (new_flags != 0) {
394 			ret = btrfs_set_disk_extent_flags(trans, root,
395 							  buf->start,
396 							  buf->len,
397 							  new_flags, 0);
398 			if (ret)
399 				return ret;
400 		}
401 	} else {
402 		if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
403 			if (root->root_key.objectid ==
404 			    BTRFS_TREE_RELOC_OBJECTID)
405 				ret = btrfs_inc_ref(trans, root, cow, 1, 1);
406 			else
407 				ret = btrfs_inc_ref(trans, root, cow, 0, 1);
408 			BUG_ON(ret); /* -ENOMEM */
409 			ret = btrfs_dec_ref(trans, root, buf, 1, 1);
410 			BUG_ON(ret); /* -ENOMEM */
411 		}
412 		clean_tree_block(trans, root, buf);
413 		*last_ref = 1;
414 	}
415 	return 0;
416 }
417 
418 /*
419  * does the dirty work in cow of a single block.  The parent block (if
420  * supplied) is updated to point to the new cow copy.  The new buffer is marked
421  * dirty and returned locked.  If you modify the block it needs to be marked
422  * dirty again.
423  *
424  * search_start -- an allocation hint for the new block
425  *
426  * empty_size -- a hint that you plan on doing more cow.  This is the size in
427  * bytes the allocator should try to find free next to the block it returns.
428  * This is just a hint and may be ignored by the allocator.
429  */
__btrfs_cow_block(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct extent_buffer * buf,struct extent_buffer * parent,int parent_slot,struct extent_buffer ** cow_ret,u64 search_start,u64 empty_size)430 static noinline int __btrfs_cow_block(struct btrfs_trans_handle *trans,
431 			     struct btrfs_root *root,
432 			     struct extent_buffer *buf,
433 			     struct extent_buffer *parent, int parent_slot,
434 			     struct extent_buffer **cow_ret,
435 			     u64 search_start, u64 empty_size)
436 {
437 	struct btrfs_disk_key disk_key;
438 	struct extent_buffer *cow;
439 	int level, ret;
440 	int last_ref = 0;
441 	int unlock_orig = 0;
442 	u64 parent_start;
443 
444 	if (*cow_ret == buf)
445 		unlock_orig = 1;
446 
447 	btrfs_assert_tree_locked(buf);
448 
449 	WARN_ON(root->ref_cows && trans->transid !=
450 		root->fs_info->running_transaction->transid);
451 	WARN_ON(root->ref_cows && trans->transid != root->last_trans);
452 
453 	level = btrfs_header_level(buf);
454 
455 	if (level == 0)
456 		btrfs_item_key(buf, &disk_key, 0);
457 	else
458 		btrfs_node_key(buf, &disk_key, 0);
459 
460 	if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) {
461 		if (parent)
462 			parent_start = parent->start;
463 		else
464 			parent_start = 0;
465 	} else
466 		parent_start = 0;
467 
468 	cow = btrfs_alloc_free_block(trans, root, buf->len, parent_start,
469 				     root->root_key.objectid, &disk_key,
470 				     level, search_start, empty_size, 1);
471 	if (IS_ERR(cow))
472 		return PTR_ERR(cow);
473 
474 	/* cow is set to blocking by btrfs_init_new_buffer */
475 
476 	copy_extent_buffer(cow, buf, 0, 0, cow->len);
477 	btrfs_set_header_bytenr(cow, cow->start);
478 	btrfs_set_header_generation(cow, trans->transid);
479 	btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
480 	btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
481 				     BTRFS_HEADER_FLAG_RELOC);
482 	if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
483 		btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
484 	else
485 		btrfs_set_header_owner(cow, root->root_key.objectid);
486 
487 	write_extent_buffer(cow, root->fs_info->fsid,
488 			    (unsigned long)btrfs_header_fsid(cow),
489 			    BTRFS_FSID_SIZE);
490 
491 	ret = update_ref_for_cow(trans, root, buf, cow, &last_ref);
492 	if (ret) {
493 		btrfs_abort_transaction(trans, root, ret);
494 		return ret;
495 	}
496 
497 	if (root->ref_cows)
498 		btrfs_reloc_cow_block(trans, root, buf, cow);
499 
500 	if (buf == root->node) {
501 		WARN_ON(parent && parent != buf);
502 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
503 		    btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
504 			parent_start = buf->start;
505 		else
506 			parent_start = 0;
507 
508 		extent_buffer_get(cow);
509 		rcu_assign_pointer(root->node, cow);
510 
511 		btrfs_free_tree_block(trans, root, buf, parent_start,
512 				      last_ref, 1);
513 		free_extent_buffer(buf);
514 		add_root_to_dirty_list(root);
515 	} else {
516 		if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
517 			parent_start = parent->start;
518 		else
519 			parent_start = 0;
520 
521 		WARN_ON(trans->transid != btrfs_header_generation(parent));
522 		btrfs_set_node_blockptr(parent, parent_slot,
523 					cow->start);
524 		btrfs_set_node_ptr_generation(parent, parent_slot,
525 					      trans->transid);
526 		btrfs_mark_buffer_dirty(parent);
527 		btrfs_free_tree_block(trans, root, buf, parent_start,
528 				      last_ref, 1);
529 	}
530 	if (unlock_orig)
531 		btrfs_tree_unlock(buf);
532 	free_extent_buffer_stale(buf);
533 	btrfs_mark_buffer_dirty(cow);
534 	*cow_ret = cow;
535 	return 0;
536 }
537 
should_cow_block(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct extent_buffer * buf)538 static inline int should_cow_block(struct btrfs_trans_handle *trans,
539 				   struct btrfs_root *root,
540 				   struct extent_buffer *buf)
541 {
542 	/* ensure we can see the force_cow */
543 	smp_rmb();
544 
545 	/*
546 	 * We do not need to cow a block if
547 	 * 1) this block is not created or changed in this transaction;
548 	 * 2) this block does not belong to TREE_RELOC tree;
549 	 * 3) the root is not forced COW.
550 	 *
551 	 * What is forced COW:
552 	 *    when we create snapshot during commiting the transaction,
553 	 *    after we've finished coping src root, we must COW the shared
554 	 *    block to ensure the metadata consistency.
555 	 */
556 	if (btrfs_header_generation(buf) == trans->transid &&
557 	    !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
558 	    !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
559 	      btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
560 	    !root->force_cow)
561 		return 0;
562 	return 1;
563 }
564 
565 /*
566  * cows a single block, see __btrfs_cow_block for the real work.
567  * This version of it has extra checks so that a block isn't cow'd more than
568  * once per transaction, as long as it hasn't been written yet
569  */
btrfs_cow_block(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct extent_buffer * buf,struct extent_buffer * parent,int parent_slot,struct extent_buffer ** cow_ret)570 noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
571 		    struct btrfs_root *root, struct extent_buffer *buf,
572 		    struct extent_buffer *parent, int parent_slot,
573 		    struct extent_buffer **cow_ret)
574 {
575 	u64 search_start;
576 	int ret;
577 
578 	if (trans->transaction != root->fs_info->running_transaction) {
579 		printk(KERN_CRIT "trans %llu running %llu\n",
580 		       (unsigned long long)trans->transid,
581 		       (unsigned long long)
582 		       root->fs_info->running_transaction->transid);
583 		WARN_ON(1);
584 	}
585 	if (trans->transid != root->fs_info->generation) {
586 		printk(KERN_CRIT "trans %llu running %llu\n",
587 		       (unsigned long long)trans->transid,
588 		       (unsigned long long)root->fs_info->generation);
589 		WARN_ON(1);
590 	}
591 
592 	if (!should_cow_block(trans, root, buf)) {
593 		*cow_ret = buf;
594 		return 0;
595 	}
596 
597 	search_start = buf->start & ~((u64)(1024 * 1024 * 1024) - 1);
598 
599 	if (parent)
600 		btrfs_set_lock_blocking(parent);
601 	btrfs_set_lock_blocking(buf);
602 
603 	ret = __btrfs_cow_block(trans, root, buf, parent,
604 				 parent_slot, cow_ret, search_start, 0);
605 
606 	trace_btrfs_cow_block(root, buf, *cow_ret);
607 
608 	return ret;
609 }
610 
611 /*
612  * helper function for defrag to decide if two blocks pointed to by a
613  * node are actually close by
614  */
close_blocks(u64 blocknr,u64 other,u32 blocksize)615 static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
616 {
617 	if (blocknr < other && other - (blocknr + blocksize) < 32768)
618 		return 1;
619 	if (blocknr > other && blocknr - (other + blocksize) < 32768)
620 		return 1;
621 	return 0;
622 }
623 
624 /*
625  * compare two keys in a memcmp fashion
626  */
comp_keys(struct btrfs_disk_key * disk,struct btrfs_key * k2)627 static int comp_keys(struct btrfs_disk_key *disk, struct btrfs_key *k2)
628 {
629 	struct btrfs_key k1;
630 
631 	btrfs_disk_key_to_cpu(&k1, disk);
632 
633 	return btrfs_comp_cpu_keys(&k1, k2);
634 }
635 
636 /*
637  * same as comp_keys only with two btrfs_key's
638  */
btrfs_comp_cpu_keys(struct btrfs_key * k1,struct btrfs_key * k2)639 int btrfs_comp_cpu_keys(struct btrfs_key *k1, struct btrfs_key *k2)
640 {
641 	if (k1->objectid > k2->objectid)
642 		return 1;
643 	if (k1->objectid < k2->objectid)
644 		return -1;
645 	if (k1->type > k2->type)
646 		return 1;
647 	if (k1->type < k2->type)
648 		return -1;
649 	if (k1->offset > k2->offset)
650 		return 1;
651 	if (k1->offset < k2->offset)
652 		return -1;
653 	return 0;
654 }
655 
656 /*
657  * this is used by the defrag code to go through all the
658  * leaves pointed to by a node and reallocate them so that
659  * disk order is close to key order
660  */
btrfs_realloc_node(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct extent_buffer * parent,int start_slot,int cache_only,u64 * last_ret,struct btrfs_key * progress)661 int btrfs_realloc_node(struct btrfs_trans_handle *trans,
662 		       struct btrfs_root *root, struct extent_buffer *parent,
663 		       int start_slot, int cache_only, u64 *last_ret,
664 		       struct btrfs_key *progress)
665 {
666 	struct extent_buffer *cur;
667 	u64 blocknr;
668 	u64 gen;
669 	u64 search_start = *last_ret;
670 	u64 last_block = 0;
671 	u64 other;
672 	u32 parent_nritems;
673 	int end_slot;
674 	int i;
675 	int err = 0;
676 	int parent_level;
677 	int uptodate;
678 	u32 blocksize;
679 	int progress_passed = 0;
680 	struct btrfs_disk_key disk_key;
681 
682 	parent_level = btrfs_header_level(parent);
683 	if (cache_only && parent_level != 1)
684 		return 0;
685 
686 	if (trans->transaction != root->fs_info->running_transaction)
687 		WARN_ON(1);
688 	if (trans->transid != root->fs_info->generation)
689 		WARN_ON(1);
690 
691 	parent_nritems = btrfs_header_nritems(parent);
692 	blocksize = btrfs_level_size(root, parent_level - 1);
693 	end_slot = parent_nritems;
694 
695 	if (parent_nritems == 1)
696 		return 0;
697 
698 	btrfs_set_lock_blocking(parent);
699 
700 	for (i = start_slot; i < end_slot; i++) {
701 		int close = 1;
702 
703 		btrfs_node_key(parent, &disk_key, i);
704 		if (!progress_passed && comp_keys(&disk_key, progress) < 0)
705 			continue;
706 
707 		progress_passed = 1;
708 		blocknr = btrfs_node_blockptr(parent, i);
709 		gen = btrfs_node_ptr_generation(parent, i);
710 		if (last_block == 0)
711 			last_block = blocknr;
712 
713 		if (i > 0) {
714 			other = btrfs_node_blockptr(parent, i - 1);
715 			close = close_blocks(blocknr, other, blocksize);
716 		}
717 		if (!close && i < end_slot - 2) {
718 			other = btrfs_node_blockptr(parent, i + 1);
719 			close = close_blocks(blocknr, other, blocksize);
720 		}
721 		if (close) {
722 			last_block = blocknr;
723 			continue;
724 		}
725 
726 		cur = btrfs_find_tree_block(root, blocknr, blocksize);
727 		if (cur)
728 			uptodate = btrfs_buffer_uptodate(cur, gen, 0);
729 		else
730 			uptodate = 0;
731 		if (!cur || !uptodate) {
732 			if (cache_only) {
733 				free_extent_buffer(cur);
734 				continue;
735 			}
736 			if (!cur) {
737 				cur = read_tree_block(root, blocknr,
738 							 blocksize, gen);
739 				if (!cur)
740 					return -EIO;
741 			} else if (!uptodate) {
742 				btrfs_read_buffer(cur, gen);
743 			}
744 		}
745 		if (search_start == 0)
746 			search_start = last_block;
747 
748 		btrfs_tree_lock(cur);
749 		btrfs_set_lock_blocking(cur);
750 		err = __btrfs_cow_block(trans, root, cur, parent, i,
751 					&cur, search_start,
752 					min(16 * blocksize,
753 					    (end_slot - i) * blocksize));
754 		if (err) {
755 			btrfs_tree_unlock(cur);
756 			free_extent_buffer(cur);
757 			break;
758 		}
759 		search_start = cur->start;
760 		last_block = cur->start;
761 		*last_ret = search_start;
762 		btrfs_tree_unlock(cur);
763 		free_extent_buffer(cur);
764 	}
765 	return err;
766 }
767 
768 /*
769  * The leaf data grows from end-to-front in the node.
770  * this returns the address of the start of the last item,
771  * which is the stop of the leaf data stack
772  */
leaf_data_end(struct btrfs_root * root,struct extent_buffer * leaf)773 static inline unsigned int leaf_data_end(struct btrfs_root *root,
774 					 struct extent_buffer *leaf)
775 {
776 	u32 nr = btrfs_header_nritems(leaf);
777 	if (nr == 0)
778 		return BTRFS_LEAF_DATA_SIZE(root);
779 	return btrfs_item_offset_nr(leaf, nr - 1);
780 }
781 
782 
783 /*
784  * search for key in the extent_buffer.  The items start at offset p,
785  * and they are item_size apart.  There are 'max' items in p.
786  *
787  * the slot in the array is returned via slot, and it points to
788  * the place where you would insert key if it is not found in
789  * the array.
790  *
791  * slot may point to max if the key is bigger than all of the keys
792  */
generic_bin_search(struct extent_buffer * eb,unsigned long p,int item_size,struct btrfs_key * key,int max,int * slot)793 static noinline int generic_bin_search(struct extent_buffer *eb,
794 				       unsigned long p,
795 				       int item_size, struct btrfs_key *key,
796 				       int max, int *slot)
797 {
798 	int low = 0;
799 	int high = max;
800 	int mid;
801 	int ret;
802 	struct btrfs_disk_key *tmp = NULL;
803 	struct btrfs_disk_key unaligned;
804 	unsigned long offset;
805 	char *kaddr = NULL;
806 	unsigned long map_start = 0;
807 	unsigned long map_len = 0;
808 	int err;
809 
810 	while (low < high) {
811 		mid = (low + high) / 2;
812 		offset = p + mid * item_size;
813 
814 		if (!kaddr || offset < map_start ||
815 		    (offset + sizeof(struct btrfs_disk_key)) >
816 		    map_start + map_len) {
817 
818 			err = map_private_extent_buffer(eb, offset,
819 						sizeof(struct btrfs_disk_key),
820 						&kaddr, &map_start, &map_len);
821 
822 			if (!err) {
823 				tmp = (struct btrfs_disk_key *)(kaddr + offset -
824 							map_start);
825 			} else {
826 				read_extent_buffer(eb, &unaligned,
827 						   offset, sizeof(unaligned));
828 				tmp = &unaligned;
829 			}
830 
831 		} else {
832 			tmp = (struct btrfs_disk_key *)(kaddr + offset -
833 							map_start);
834 		}
835 		ret = comp_keys(tmp, key);
836 
837 		if (ret < 0)
838 			low = mid + 1;
839 		else if (ret > 0)
840 			high = mid;
841 		else {
842 			*slot = mid;
843 			return 0;
844 		}
845 	}
846 	*slot = low;
847 	return 1;
848 }
849 
850 /*
851  * simple bin_search frontend that does the right thing for
852  * leaves vs nodes
853  */
bin_search(struct extent_buffer * eb,struct btrfs_key * key,int level,int * slot)854 static int bin_search(struct extent_buffer *eb, struct btrfs_key *key,
855 		      int level, int *slot)
856 {
857 	if (level == 0) {
858 		return generic_bin_search(eb,
859 					  offsetof(struct btrfs_leaf, items),
860 					  sizeof(struct btrfs_item),
861 					  key, btrfs_header_nritems(eb),
862 					  slot);
863 	} else {
864 		return generic_bin_search(eb,
865 					  offsetof(struct btrfs_node, ptrs),
866 					  sizeof(struct btrfs_key_ptr),
867 					  key, btrfs_header_nritems(eb),
868 					  slot);
869 	}
870 	return -1;
871 }
872 
btrfs_bin_search(struct extent_buffer * eb,struct btrfs_key * key,int level,int * slot)873 int btrfs_bin_search(struct extent_buffer *eb, struct btrfs_key *key,
874 		     int level, int *slot)
875 {
876 	return bin_search(eb, key, level, slot);
877 }
878 
root_add_used(struct btrfs_root * root,u32 size)879 static void root_add_used(struct btrfs_root *root, u32 size)
880 {
881 	spin_lock(&root->accounting_lock);
882 	btrfs_set_root_used(&root->root_item,
883 			    btrfs_root_used(&root->root_item) + size);
884 	spin_unlock(&root->accounting_lock);
885 }
886 
root_sub_used(struct btrfs_root * root,u32 size)887 static void root_sub_used(struct btrfs_root *root, u32 size)
888 {
889 	spin_lock(&root->accounting_lock);
890 	btrfs_set_root_used(&root->root_item,
891 			    btrfs_root_used(&root->root_item) - size);
892 	spin_unlock(&root->accounting_lock);
893 }
894 
895 /* given a node and slot number, this reads the blocks it points to.  The
896  * extent buffer is returned with a reference taken (but unlocked).
897  * NULL is returned on error.
898  */
read_node_slot(struct btrfs_root * root,struct extent_buffer * parent,int slot)899 static noinline struct extent_buffer *read_node_slot(struct btrfs_root *root,
900 				   struct extent_buffer *parent, int slot)
901 {
902 	int level = btrfs_header_level(parent);
903 	if (slot < 0)
904 		return NULL;
905 	if (slot >= btrfs_header_nritems(parent))
906 		return NULL;
907 
908 	BUG_ON(level == 0);
909 
910 	return read_tree_block(root, btrfs_node_blockptr(parent, slot),
911 		       btrfs_level_size(root, level - 1),
912 		       btrfs_node_ptr_generation(parent, slot));
913 }
914 
915 /*
916  * node level balancing, used to make sure nodes are in proper order for
917  * item deletion.  We balance from the top down, so we have to make sure
918  * that a deletion won't leave an node completely empty later on.
919  */
balance_level(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_path * path,int level)920 static noinline int balance_level(struct btrfs_trans_handle *trans,
921 			 struct btrfs_root *root,
922 			 struct btrfs_path *path, int level)
923 {
924 	struct extent_buffer *right = NULL;
925 	struct extent_buffer *mid;
926 	struct extent_buffer *left = NULL;
927 	struct extent_buffer *parent = NULL;
928 	int ret = 0;
929 	int wret;
930 	int pslot;
931 	int orig_slot = path->slots[level];
932 	u64 orig_ptr;
933 
934 	if (level == 0)
935 		return 0;
936 
937 	mid = path->nodes[level];
938 
939 	WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK &&
940 		path->locks[level] != BTRFS_WRITE_LOCK_BLOCKING);
941 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
942 
943 	orig_ptr = btrfs_node_blockptr(mid, orig_slot);
944 
945 	if (level < BTRFS_MAX_LEVEL - 1) {
946 		parent = path->nodes[level + 1];
947 		pslot = path->slots[level + 1];
948 	}
949 
950 	/*
951 	 * deal with the case where there is only one pointer in the root
952 	 * by promoting the node below to a root
953 	 */
954 	if (!parent) {
955 		struct extent_buffer *child;
956 
957 		if (btrfs_header_nritems(mid) != 1)
958 			return 0;
959 
960 		/* promote the child to a root */
961 		child = read_node_slot(root, mid, 0);
962 		if (!child) {
963 			ret = -EROFS;
964 			btrfs_std_error(root->fs_info, ret);
965 			goto enospc;
966 		}
967 
968 		btrfs_tree_lock(child);
969 		btrfs_set_lock_blocking(child);
970 		ret = btrfs_cow_block(trans, root, child, mid, 0, &child);
971 		if (ret) {
972 			btrfs_tree_unlock(child);
973 			free_extent_buffer(child);
974 			goto enospc;
975 		}
976 
977 		rcu_assign_pointer(root->node, child);
978 
979 		add_root_to_dirty_list(root);
980 		btrfs_tree_unlock(child);
981 
982 		path->locks[level] = 0;
983 		path->nodes[level] = NULL;
984 		clean_tree_block(trans, root, mid);
985 		btrfs_tree_unlock(mid);
986 		/* once for the path */
987 		free_extent_buffer(mid);
988 
989 		root_sub_used(root, mid->len);
990 		btrfs_free_tree_block(trans, root, mid, 0, 1, 0);
991 		/* once for the root ptr */
992 		free_extent_buffer_stale(mid);
993 		return 0;
994 	}
995 	if (btrfs_header_nritems(mid) >
996 	    BTRFS_NODEPTRS_PER_BLOCK(root) / 4)
997 		return 0;
998 
999 	btrfs_header_nritems(mid);
1000 
1001 	left = read_node_slot(root, parent, pslot - 1);
1002 	if (left) {
1003 		btrfs_tree_lock(left);
1004 		btrfs_set_lock_blocking(left);
1005 		wret = btrfs_cow_block(trans, root, left,
1006 				       parent, pslot - 1, &left);
1007 		if (wret) {
1008 			ret = wret;
1009 			goto enospc;
1010 		}
1011 	}
1012 	right = read_node_slot(root, parent, pslot + 1);
1013 	if (right) {
1014 		btrfs_tree_lock(right);
1015 		btrfs_set_lock_blocking(right);
1016 		wret = btrfs_cow_block(trans, root, right,
1017 				       parent, pslot + 1, &right);
1018 		if (wret) {
1019 			ret = wret;
1020 			goto enospc;
1021 		}
1022 	}
1023 
1024 	/* first, try to make some room in the middle buffer */
1025 	if (left) {
1026 		orig_slot += btrfs_header_nritems(left);
1027 		wret = push_node_left(trans, root, left, mid, 1);
1028 		if (wret < 0)
1029 			ret = wret;
1030 		btrfs_header_nritems(mid);
1031 	}
1032 
1033 	/*
1034 	 * then try to empty the right most buffer into the middle
1035 	 */
1036 	if (right) {
1037 		wret = push_node_left(trans, root, mid, right, 1);
1038 		if (wret < 0 && wret != -ENOSPC)
1039 			ret = wret;
1040 		if (btrfs_header_nritems(right) == 0) {
1041 			clean_tree_block(trans, root, right);
1042 			btrfs_tree_unlock(right);
1043 			del_ptr(trans, root, path, level + 1, pslot + 1);
1044 			root_sub_used(root, right->len);
1045 			btrfs_free_tree_block(trans, root, right, 0, 1, 0);
1046 			free_extent_buffer_stale(right);
1047 			right = NULL;
1048 		} else {
1049 			struct btrfs_disk_key right_key;
1050 			btrfs_node_key(right, &right_key, 0);
1051 			btrfs_set_node_key(parent, &right_key, pslot + 1);
1052 			btrfs_mark_buffer_dirty(parent);
1053 		}
1054 	}
1055 	if (btrfs_header_nritems(mid) == 1) {
1056 		/*
1057 		 * we're not allowed to leave a node with one item in the
1058 		 * tree during a delete.  A deletion from lower in the tree
1059 		 * could try to delete the only pointer in this node.
1060 		 * So, pull some keys from the left.
1061 		 * There has to be a left pointer at this point because
1062 		 * otherwise we would have pulled some pointers from the
1063 		 * right
1064 		 */
1065 		if (!left) {
1066 			ret = -EROFS;
1067 			btrfs_std_error(root->fs_info, ret);
1068 			goto enospc;
1069 		}
1070 		wret = balance_node_right(trans, root, mid, left);
1071 		if (wret < 0) {
1072 			ret = wret;
1073 			goto enospc;
1074 		}
1075 		if (wret == 1) {
1076 			wret = push_node_left(trans, root, left, mid, 1);
1077 			if (wret < 0)
1078 				ret = wret;
1079 		}
1080 		BUG_ON(wret == 1);
1081 	}
1082 	if (btrfs_header_nritems(mid) == 0) {
1083 		clean_tree_block(trans, root, mid);
1084 		btrfs_tree_unlock(mid);
1085 		del_ptr(trans, root, path, level + 1, pslot);
1086 		root_sub_used(root, mid->len);
1087 		btrfs_free_tree_block(trans, root, mid, 0, 1, 0);
1088 		free_extent_buffer_stale(mid);
1089 		mid = NULL;
1090 	} else {
1091 		/* update the parent key to reflect our changes */
1092 		struct btrfs_disk_key mid_key;
1093 		btrfs_node_key(mid, &mid_key, 0);
1094 		btrfs_set_node_key(parent, &mid_key, pslot);
1095 		btrfs_mark_buffer_dirty(parent);
1096 	}
1097 
1098 	/* update the path */
1099 	if (left) {
1100 		if (btrfs_header_nritems(left) > orig_slot) {
1101 			extent_buffer_get(left);
1102 			/* left was locked after cow */
1103 			path->nodes[level] = left;
1104 			path->slots[level + 1] -= 1;
1105 			path->slots[level] = orig_slot;
1106 			if (mid) {
1107 				btrfs_tree_unlock(mid);
1108 				free_extent_buffer(mid);
1109 			}
1110 		} else {
1111 			orig_slot -= btrfs_header_nritems(left);
1112 			path->slots[level] = orig_slot;
1113 		}
1114 	}
1115 	/* double check we haven't messed things up */
1116 	if (orig_ptr !=
1117 	    btrfs_node_blockptr(path->nodes[level], path->slots[level]))
1118 		BUG();
1119 enospc:
1120 	if (right) {
1121 		btrfs_tree_unlock(right);
1122 		free_extent_buffer(right);
1123 	}
1124 	if (left) {
1125 		if (path->nodes[level] != left)
1126 			btrfs_tree_unlock(left);
1127 		free_extent_buffer(left);
1128 	}
1129 	return ret;
1130 }
1131 
1132 /* Node balancing for insertion.  Here we only split or push nodes around
1133  * when they are completely full.  This is also done top down, so we
1134  * have to be pessimistic.
1135  */
push_nodes_for_insert(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_path * path,int level)1136 static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
1137 					  struct btrfs_root *root,
1138 					  struct btrfs_path *path, int level)
1139 {
1140 	struct extent_buffer *right = NULL;
1141 	struct extent_buffer *mid;
1142 	struct extent_buffer *left = NULL;
1143 	struct extent_buffer *parent = NULL;
1144 	int ret = 0;
1145 	int wret;
1146 	int pslot;
1147 	int orig_slot = path->slots[level];
1148 
1149 	if (level == 0)
1150 		return 1;
1151 
1152 	mid = path->nodes[level];
1153 	WARN_ON(btrfs_header_generation(mid) != trans->transid);
1154 
1155 	if (level < BTRFS_MAX_LEVEL - 1) {
1156 		parent = path->nodes[level + 1];
1157 		pslot = path->slots[level + 1];
1158 	}
1159 
1160 	if (!parent)
1161 		return 1;
1162 
1163 	left = read_node_slot(root, parent, pslot - 1);
1164 
1165 	/* first, try to make some room in the middle buffer */
1166 	if (left) {
1167 		u32 left_nr;
1168 
1169 		btrfs_tree_lock(left);
1170 		btrfs_set_lock_blocking(left);
1171 
1172 		left_nr = btrfs_header_nritems(left);
1173 		if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(root) - 1) {
1174 			wret = 1;
1175 		} else {
1176 			ret = btrfs_cow_block(trans, root, left, parent,
1177 					      pslot - 1, &left);
1178 			if (ret)
1179 				wret = 1;
1180 			else {
1181 				wret = push_node_left(trans, root,
1182 						      left, mid, 0);
1183 			}
1184 		}
1185 		if (wret < 0)
1186 			ret = wret;
1187 		if (wret == 0) {
1188 			struct btrfs_disk_key disk_key;
1189 			orig_slot += left_nr;
1190 			btrfs_node_key(mid, &disk_key, 0);
1191 			btrfs_set_node_key(parent, &disk_key, pslot);
1192 			btrfs_mark_buffer_dirty(parent);
1193 			if (btrfs_header_nritems(left) > orig_slot) {
1194 				path->nodes[level] = left;
1195 				path->slots[level + 1] -= 1;
1196 				path->slots[level] = orig_slot;
1197 				btrfs_tree_unlock(mid);
1198 				free_extent_buffer(mid);
1199 			} else {
1200 				orig_slot -=
1201 					btrfs_header_nritems(left);
1202 				path->slots[level] = orig_slot;
1203 				btrfs_tree_unlock(left);
1204 				free_extent_buffer(left);
1205 			}
1206 			return 0;
1207 		}
1208 		btrfs_tree_unlock(left);
1209 		free_extent_buffer(left);
1210 	}
1211 	right = read_node_slot(root, parent, pslot + 1);
1212 
1213 	/*
1214 	 * then try to empty the right most buffer into the middle
1215 	 */
1216 	if (right) {
1217 		u32 right_nr;
1218 
1219 		btrfs_tree_lock(right);
1220 		btrfs_set_lock_blocking(right);
1221 
1222 		right_nr = btrfs_header_nritems(right);
1223 		if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(root) - 1) {
1224 			wret = 1;
1225 		} else {
1226 			ret = btrfs_cow_block(trans, root, right,
1227 					      parent, pslot + 1,
1228 					      &right);
1229 			if (ret)
1230 				wret = 1;
1231 			else {
1232 				wret = balance_node_right(trans, root,
1233 							  right, mid);
1234 			}
1235 		}
1236 		if (wret < 0)
1237 			ret = wret;
1238 		if (wret == 0) {
1239 			struct btrfs_disk_key disk_key;
1240 
1241 			btrfs_node_key(right, &disk_key, 0);
1242 			btrfs_set_node_key(parent, &disk_key, pslot + 1);
1243 			btrfs_mark_buffer_dirty(parent);
1244 
1245 			if (btrfs_header_nritems(mid) <= orig_slot) {
1246 				path->nodes[level] = right;
1247 				path->slots[level + 1] += 1;
1248 				path->slots[level] = orig_slot -
1249 					btrfs_header_nritems(mid);
1250 				btrfs_tree_unlock(mid);
1251 				free_extent_buffer(mid);
1252 			} else {
1253 				btrfs_tree_unlock(right);
1254 				free_extent_buffer(right);
1255 			}
1256 			return 0;
1257 		}
1258 		btrfs_tree_unlock(right);
1259 		free_extent_buffer(right);
1260 	}
1261 	return 1;
1262 }
1263 
1264 /*
1265  * readahead one full node of leaves, finding things that are close
1266  * to the block in 'slot', and triggering ra on them.
1267  */
reada_for_search(struct btrfs_root * root,struct btrfs_path * path,int level,int slot,u64 objectid)1268 static void reada_for_search(struct btrfs_root *root,
1269 			     struct btrfs_path *path,
1270 			     int level, int slot, u64 objectid)
1271 {
1272 	struct extent_buffer *node;
1273 	struct btrfs_disk_key disk_key;
1274 	u32 nritems;
1275 	u64 search;
1276 	u64 target;
1277 	u64 nread = 0;
1278 	u64 gen;
1279 	int direction = path->reada;
1280 	struct extent_buffer *eb;
1281 	u32 nr;
1282 	u32 blocksize;
1283 	u32 nscan = 0;
1284 
1285 	if (level != 1)
1286 		return;
1287 
1288 	if (!path->nodes[level])
1289 		return;
1290 
1291 	node = path->nodes[level];
1292 
1293 	search = btrfs_node_blockptr(node, slot);
1294 	blocksize = btrfs_level_size(root, level - 1);
1295 	eb = btrfs_find_tree_block(root, search, blocksize);
1296 	if (eb) {
1297 		free_extent_buffer(eb);
1298 		return;
1299 	}
1300 
1301 	target = search;
1302 
1303 	nritems = btrfs_header_nritems(node);
1304 	nr = slot;
1305 
1306 	while (1) {
1307 		if (direction < 0) {
1308 			if (nr == 0)
1309 				break;
1310 			nr--;
1311 		} else if (direction > 0) {
1312 			nr++;
1313 			if (nr >= nritems)
1314 				break;
1315 		}
1316 		if (path->reada < 0 && objectid) {
1317 			btrfs_node_key(node, &disk_key, nr);
1318 			if (btrfs_disk_key_objectid(&disk_key) != objectid)
1319 				break;
1320 		}
1321 		search = btrfs_node_blockptr(node, nr);
1322 		if ((search <= target && target - search <= 65536) ||
1323 		    (search > target && search - target <= 65536)) {
1324 			gen = btrfs_node_ptr_generation(node, nr);
1325 			readahead_tree_block(root, search, blocksize, gen);
1326 			nread += blocksize;
1327 		}
1328 		nscan++;
1329 		if ((nread > 65536 || nscan > 32))
1330 			break;
1331 	}
1332 }
1333 
1334 /*
1335  * returns -EAGAIN if it had to drop the path, or zero if everything was in
1336  * cache
1337  */
reada_for_balance(struct btrfs_root * root,struct btrfs_path * path,int level)1338 static noinline int reada_for_balance(struct btrfs_root *root,
1339 				      struct btrfs_path *path, int level)
1340 {
1341 	int slot;
1342 	int nritems;
1343 	struct extent_buffer *parent;
1344 	struct extent_buffer *eb;
1345 	u64 gen;
1346 	u64 block1 = 0;
1347 	u64 block2 = 0;
1348 	int ret = 0;
1349 	int blocksize;
1350 
1351 	parent = path->nodes[level + 1];
1352 	if (!parent)
1353 		return 0;
1354 
1355 	nritems = btrfs_header_nritems(parent);
1356 	slot = path->slots[level + 1];
1357 	blocksize = btrfs_level_size(root, level);
1358 
1359 	if (slot > 0) {
1360 		block1 = btrfs_node_blockptr(parent, slot - 1);
1361 		gen = btrfs_node_ptr_generation(parent, slot - 1);
1362 		eb = btrfs_find_tree_block(root, block1, blocksize);
1363 		/*
1364 		 * if we get -eagain from btrfs_buffer_uptodate, we
1365 		 * don't want to return eagain here.  That will loop
1366 		 * forever
1367 		 */
1368 		if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
1369 			block1 = 0;
1370 		free_extent_buffer(eb);
1371 	}
1372 	if (slot + 1 < nritems) {
1373 		block2 = btrfs_node_blockptr(parent, slot + 1);
1374 		gen = btrfs_node_ptr_generation(parent, slot + 1);
1375 		eb = btrfs_find_tree_block(root, block2, blocksize);
1376 		if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
1377 			block2 = 0;
1378 		free_extent_buffer(eb);
1379 	}
1380 	if (block1 || block2) {
1381 		ret = -EAGAIN;
1382 
1383 		/* release the whole path */
1384 		btrfs_release_path(path);
1385 
1386 		/* read the blocks */
1387 		if (block1)
1388 			readahead_tree_block(root, block1, blocksize, 0);
1389 		if (block2)
1390 			readahead_tree_block(root, block2, blocksize, 0);
1391 
1392 		if (block1) {
1393 			eb = read_tree_block(root, block1, blocksize, 0);
1394 			free_extent_buffer(eb);
1395 		}
1396 		if (block2) {
1397 			eb = read_tree_block(root, block2, blocksize, 0);
1398 			free_extent_buffer(eb);
1399 		}
1400 	}
1401 	return ret;
1402 }
1403 
1404 
1405 /*
1406  * when we walk down the tree, it is usually safe to unlock the higher layers
1407  * in the tree.  The exceptions are when our path goes through slot 0, because
1408  * operations on the tree might require changing key pointers higher up in the
1409  * tree.
1410  *
1411  * callers might also have set path->keep_locks, which tells this code to keep
1412  * the lock if the path points to the last slot in the block.  This is part of
1413  * walking through the tree, and selecting the next slot in the higher block.
1414  *
1415  * lowest_unlock sets the lowest level in the tree we're allowed to unlock.  so
1416  * if lowest_unlock is 1, level 0 won't be unlocked
1417  */
unlock_up(struct btrfs_path * path,int level,int lowest_unlock,int min_write_lock_level,int * write_lock_level)1418 static noinline void unlock_up(struct btrfs_path *path, int level,
1419 			       int lowest_unlock, int min_write_lock_level,
1420 			       int *write_lock_level)
1421 {
1422 	int i;
1423 	int skip_level = level;
1424 	int no_skips = 0;
1425 	struct extent_buffer *t;
1426 
1427 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
1428 		if (!path->nodes[i])
1429 			break;
1430 		if (!path->locks[i])
1431 			break;
1432 		if (!no_skips && path->slots[i] == 0) {
1433 			skip_level = i + 1;
1434 			continue;
1435 		}
1436 		if (!no_skips && path->keep_locks) {
1437 			u32 nritems;
1438 			t = path->nodes[i];
1439 			nritems = btrfs_header_nritems(t);
1440 			if (nritems < 1 || path->slots[i] >= nritems - 1) {
1441 				skip_level = i + 1;
1442 				continue;
1443 			}
1444 		}
1445 		if (skip_level < i && i >= lowest_unlock)
1446 			no_skips = 1;
1447 
1448 		t = path->nodes[i];
1449 		if (i >= lowest_unlock && i > skip_level && path->locks[i]) {
1450 			btrfs_tree_unlock_rw(t, path->locks[i]);
1451 			path->locks[i] = 0;
1452 			if (write_lock_level &&
1453 			    i > min_write_lock_level &&
1454 			    i <= *write_lock_level) {
1455 				*write_lock_level = i - 1;
1456 			}
1457 		}
1458 	}
1459 }
1460 
1461 /*
1462  * This releases any locks held in the path starting at level and
1463  * going all the way up to the root.
1464  *
1465  * btrfs_search_slot will keep the lock held on higher nodes in a few
1466  * corner cases, such as COW of the block at slot zero in the node.  This
1467  * ignores those rules, and it should only be called when there are no
1468  * more updates to be done higher up in the tree.
1469  */
btrfs_unlock_up_safe(struct btrfs_path * path,int level)1470 noinline void btrfs_unlock_up_safe(struct btrfs_path *path, int level)
1471 {
1472 	int i;
1473 
1474 	if (path->keep_locks)
1475 		return;
1476 
1477 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
1478 		if (!path->nodes[i])
1479 			continue;
1480 		if (!path->locks[i])
1481 			continue;
1482 		btrfs_tree_unlock_rw(path->nodes[i], path->locks[i]);
1483 		path->locks[i] = 0;
1484 	}
1485 }
1486 
1487 /*
1488  * helper function for btrfs_search_slot.  The goal is to find a block
1489  * in cache without setting the path to blocking.  If we find the block
1490  * we return zero and the path is unchanged.
1491  *
1492  * If we can't find the block, we set the path blocking and do some
1493  * reada.  -EAGAIN is returned and the search must be repeated.
1494  */
1495 static int
read_block_for_search(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_path * p,struct extent_buffer ** eb_ret,int level,int slot,struct btrfs_key * key)1496 read_block_for_search(struct btrfs_trans_handle *trans,
1497 		       struct btrfs_root *root, struct btrfs_path *p,
1498 		       struct extent_buffer **eb_ret, int level, int slot,
1499 		       struct btrfs_key *key)
1500 {
1501 	u64 blocknr;
1502 	u64 gen;
1503 	u32 blocksize;
1504 	struct extent_buffer *b = *eb_ret;
1505 	struct extent_buffer *tmp;
1506 	int ret;
1507 
1508 	blocknr = btrfs_node_blockptr(b, slot);
1509 	gen = btrfs_node_ptr_generation(b, slot);
1510 	blocksize = btrfs_level_size(root, level - 1);
1511 
1512 	tmp = btrfs_find_tree_block(root, blocknr, blocksize);
1513 	if (tmp) {
1514 		/* first we do an atomic uptodate check */
1515 		if (btrfs_buffer_uptodate(tmp, 0, 1) > 0) {
1516 			if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
1517 				/*
1518 				 * we found an up to date block without
1519 				 * sleeping, return
1520 				 * right away
1521 				 */
1522 				*eb_ret = tmp;
1523 				return 0;
1524 			}
1525 			/* the pages were up to date, but we failed
1526 			 * the generation number check.  Do a full
1527 			 * read for the generation number that is correct.
1528 			 * We must do this without dropping locks so
1529 			 * we can trust our generation number
1530 			 */
1531 			free_extent_buffer(tmp);
1532 			btrfs_set_path_blocking(p);
1533 
1534 			/* now we're allowed to do a blocking uptodate check */
1535 			tmp = read_tree_block(root, blocknr, blocksize, gen);
1536 			if (tmp && btrfs_buffer_uptodate(tmp, gen, 0) > 0) {
1537 				*eb_ret = tmp;
1538 				return 0;
1539 			}
1540 			free_extent_buffer(tmp);
1541 			btrfs_release_path(p);
1542 			return -EIO;
1543 		}
1544 	}
1545 
1546 	/*
1547 	 * reduce lock contention at high levels
1548 	 * of the btree by dropping locks before
1549 	 * we read.  Don't release the lock on the current
1550 	 * level because we need to walk this node to figure
1551 	 * out which blocks to read.
1552 	 */
1553 	btrfs_unlock_up_safe(p, level + 1);
1554 	btrfs_set_path_blocking(p);
1555 
1556 	free_extent_buffer(tmp);
1557 	if (p->reada)
1558 		reada_for_search(root, p, level, slot, key->objectid);
1559 
1560 	btrfs_release_path(p);
1561 
1562 	ret = -EAGAIN;
1563 	tmp = read_tree_block(root, blocknr, blocksize, 0);
1564 	if (tmp) {
1565 		/*
1566 		 * If the read above didn't mark this buffer up to date,
1567 		 * it will never end up being up to date.  Set ret to EIO now
1568 		 * and give up so that our caller doesn't loop forever
1569 		 * on our EAGAINs.
1570 		 */
1571 		if (!btrfs_buffer_uptodate(tmp, 0, 0))
1572 			ret = -EIO;
1573 		free_extent_buffer(tmp);
1574 	}
1575 	return ret;
1576 }
1577 
1578 /*
1579  * helper function for btrfs_search_slot.  This does all of the checks
1580  * for node-level blocks and does any balancing required based on
1581  * the ins_len.
1582  *
1583  * If no extra work was required, zero is returned.  If we had to
1584  * drop the path, -EAGAIN is returned and btrfs_search_slot must
1585  * start over
1586  */
1587 static int
setup_nodes_for_search(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_path * p,struct extent_buffer * b,int level,int ins_len,int * write_lock_level)1588 setup_nodes_for_search(struct btrfs_trans_handle *trans,
1589 		       struct btrfs_root *root, struct btrfs_path *p,
1590 		       struct extent_buffer *b, int level, int ins_len,
1591 		       int *write_lock_level)
1592 {
1593 	int ret;
1594 	if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
1595 	    BTRFS_NODEPTRS_PER_BLOCK(root) - 3) {
1596 		int sret;
1597 
1598 		if (*write_lock_level < level + 1) {
1599 			*write_lock_level = level + 1;
1600 			btrfs_release_path(p);
1601 			goto again;
1602 		}
1603 
1604 		sret = reada_for_balance(root, p, level);
1605 		if (sret)
1606 			goto again;
1607 
1608 		btrfs_set_path_blocking(p);
1609 		sret = split_node(trans, root, p, level);
1610 		btrfs_clear_path_blocking(p, NULL, 0);
1611 
1612 		BUG_ON(sret > 0);
1613 		if (sret) {
1614 			ret = sret;
1615 			goto done;
1616 		}
1617 		b = p->nodes[level];
1618 	} else if (ins_len < 0 && btrfs_header_nritems(b) <
1619 		   BTRFS_NODEPTRS_PER_BLOCK(root) / 2) {
1620 		int sret;
1621 
1622 		if (*write_lock_level < level + 1) {
1623 			*write_lock_level = level + 1;
1624 			btrfs_release_path(p);
1625 			goto again;
1626 		}
1627 
1628 		sret = reada_for_balance(root, p, level);
1629 		if (sret)
1630 			goto again;
1631 
1632 		btrfs_set_path_blocking(p);
1633 		sret = balance_level(trans, root, p, level);
1634 		btrfs_clear_path_blocking(p, NULL, 0);
1635 
1636 		if (sret) {
1637 			ret = sret;
1638 			goto done;
1639 		}
1640 		b = p->nodes[level];
1641 		if (!b) {
1642 			btrfs_release_path(p);
1643 			goto again;
1644 		}
1645 		BUG_ON(btrfs_header_nritems(b) == 1);
1646 	}
1647 	return 0;
1648 
1649 again:
1650 	ret = -EAGAIN;
1651 done:
1652 	return ret;
1653 }
1654 
1655 /*
1656  * look for key in the tree.  path is filled in with nodes along the way
1657  * if key is found, we return zero and you can find the item in the leaf
1658  * level of the path (level 0)
1659  *
1660  * If the key isn't found, the path points to the slot where it should
1661  * be inserted, and 1 is returned.  If there are other errors during the
1662  * search a negative error number is returned.
1663  *
1664  * if ins_len > 0, nodes and leaves will be split as we walk down the
1665  * tree.  if ins_len < 0, nodes will be merged as we walk down the tree (if
1666  * possible)
1667  */
btrfs_search_slot(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_key * key,struct btrfs_path * p,int ins_len,int cow)1668 int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root
1669 		      *root, struct btrfs_key *key, struct btrfs_path *p, int
1670 		      ins_len, int cow)
1671 {
1672 	struct extent_buffer *b;
1673 	int slot;
1674 	int ret;
1675 	int err;
1676 	int level;
1677 	int lowest_unlock = 1;
1678 	int root_lock;
1679 	/* everything at write_lock_level or lower must be write locked */
1680 	int write_lock_level = 0;
1681 	u8 lowest_level = 0;
1682 	int min_write_lock_level;
1683 
1684 	lowest_level = p->lowest_level;
1685 	WARN_ON(lowest_level && ins_len > 0);
1686 	WARN_ON(p->nodes[0] != NULL);
1687 
1688 	if (ins_len < 0) {
1689 		lowest_unlock = 2;
1690 
1691 		/* when we are removing items, we might have to go up to level
1692 		 * two as we update tree pointers  Make sure we keep write
1693 		 * for those levels as well
1694 		 */
1695 		write_lock_level = 2;
1696 	} else if (ins_len > 0) {
1697 		/*
1698 		 * for inserting items, make sure we have a write lock on
1699 		 * level 1 so we can update keys
1700 		 */
1701 		write_lock_level = 1;
1702 	}
1703 
1704 	if (!cow)
1705 		write_lock_level = -1;
1706 
1707 	if (cow && (p->keep_locks || p->lowest_level))
1708 		write_lock_level = BTRFS_MAX_LEVEL;
1709 
1710 	min_write_lock_level = write_lock_level;
1711 
1712 again:
1713 	/*
1714 	 * we try very hard to do read locks on the root
1715 	 */
1716 	root_lock = BTRFS_READ_LOCK;
1717 	level = 0;
1718 	if (p->search_commit_root) {
1719 		/*
1720 		 * the commit roots are read only
1721 		 * so we always do read locks
1722 		 */
1723 		b = root->commit_root;
1724 		extent_buffer_get(b);
1725 		level = btrfs_header_level(b);
1726 		if (!p->skip_locking)
1727 			btrfs_tree_read_lock(b);
1728 	} else {
1729 		if (p->skip_locking) {
1730 			b = btrfs_root_node(root);
1731 			level = btrfs_header_level(b);
1732 		} else {
1733 			/* we don't know the level of the root node
1734 			 * until we actually have it read locked
1735 			 */
1736 			b = btrfs_read_lock_root_node(root);
1737 			level = btrfs_header_level(b);
1738 			if (level <= write_lock_level) {
1739 				/* whoops, must trade for write lock */
1740 				btrfs_tree_read_unlock(b);
1741 				free_extent_buffer(b);
1742 				b = btrfs_lock_root_node(root);
1743 				root_lock = BTRFS_WRITE_LOCK;
1744 
1745 				/* the level might have changed, check again */
1746 				level = btrfs_header_level(b);
1747 			}
1748 		}
1749 	}
1750 	p->nodes[level] = b;
1751 	if (!p->skip_locking)
1752 		p->locks[level] = root_lock;
1753 
1754 	while (b) {
1755 		level = btrfs_header_level(b);
1756 
1757 		/*
1758 		 * setup the path here so we can release it under lock
1759 		 * contention with the cow code
1760 		 */
1761 		if (cow) {
1762 			/*
1763 			 * if we don't really need to cow this block
1764 			 * then we don't want to set the path blocking,
1765 			 * so we test it here
1766 			 */
1767 			if (!should_cow_block(trans, root, b))
1768 				goto cow_done;
1769 
1770 			btrfs_set_path_blocking(p);
1771 
1772 			/*
1773 			 * must have write locks on this node and the
1774 			 * parent
1775 			 */
1776 			if (level + 1 > write_lock_level) {
1777 				write_lock_level = level + 1;
1778 				btrfs_release_path(p);
1779 				goto again;
1780 			}
1781 
1782 			err = btrfs_cow_block(trans, root, b,
1783 					      p->nodes[level + 1],
1784 					      p->slots[level + 1], &b);
1785 			if (err) {
1786 				ret = err;
1787 				goto done;
1788 			}
1789 		}
1790 cow_done:
1791 		BUG_ON(!cow && ins_len);
1792 
1793 		p->nodes[level] = b;
1794 		btrfs_clear_path_blocking(p, NULL, 0);
1795 
1796 		/*
1797 		 * we have a lock on b and as long as we aren't changing
1798 		 * the tree, there is no way to for the items in b to change.
1799 		 * It is safe to drop the lock on our parent before we
1800 		 * go through the expensive btree search on b.
1801 		 *
1802 		 * If cow is true, then we might be changing slot zero,
1803 		 * which may require changing the parent.  So, we can't
1804 		 * drop the lock until after we know which slot we're
1805 		 * operating on.
1806 		 */
1807 		if (!cow)
1808 			btrfs_unlock_up_safe(p, level + 1);
1809 
1810 		ret = bin_search(b, key, level, &slot);
1811 
1812 		if (level != 0) {
1813 			int dec = 0;
1814 			if (ret && slot > 0) {
1815 				dec = 1;
1816 				slot -= 1;
1817 			}
1818 			p->slots[level] = slot;
1819 			err = setup_nodes_for_search(trans, root, p, b, level,
1820 					     ins_len, &write_lock_level);
1821 			if (err == -EAGAIN)
1822 				goto again;
1823 			if (err) {
1824 				ret = err;
1825 				goto done;
1826 			}
1827 			b = p->nodes[level];
1828 			slot = p->slots[level];
1829 
1830 			/*
1831 			 * slot 0 is special, if we change the key
1832 			 * we have to update the parent pointer
1833 			 * which means we must have a write lock
1834 			 * on the parent
1835 			 */
1836 			if (slot == 0 && cow &&
1837 			    write_lock_level < level + 1) {
1838 				write_lock_level = level + 1;
1839 				btrfs_release_path(p);
1840 				goto again;
1841 			}
1842 
1843 			unlock_up(p, level, lowest_unlock,
1844 				  min_write_lock_level, &write_lock_level);
1845 
1846 			if (level == lowest_level) {
1847 				if (dec)
1848 					p->slots[level]++;
1849 				goto done;
1850 			}
1851 
1852 			err = read_block_for_search(trans, root, p,
1853 						    &b, level, slot, key);
1854 			if (err == -EAGAIN)
1855 				goto again;
1856 			if (err) {
1857 				ret = err;
1858 				goto done;
1859 			}
1860 
1861 			if (!p->skip_locking) {
1862 				level = btrfs_header_level(b);
1863 				if (level <= write_lock_level) {
1864 					err = btrfs_try_tree_write_lock(b);
1865 					if (!err) {
1866 						btrfs_set_path_blocking(p);
1867 						btrfs_tree_lock(b);
1868 						btrfs_clear_path_blocking(p, b,
1869 								  BTRFS_WRITE_LOCK);
1870 					}
1871 					p->locks[level] = BTRFS_WRITE_LOCK;
1872 				} else {
1873 					err = btrfs_try_tree_read_lock(b);
1874 					if (!err) {
1875 						btrfs_set_path_blocking(p);
1876 						btrfs_tree_read_lock(b);
1877 						btrfs_clear_path_blocking(p, b,
1878 								  BTRFS_READ_LOCK);
1879 					}
1880 					p->locks[level] = BTRFS_READ_LOCK;
1881 				}
1882 				p->nodes[level] = b;
1883 			}
1884 		} else {
1885 			p->slots[level] = slot;
1886 			if (ins_len > 0 &&
1887 			    btrfs_leaf_free_space(root, b) < ins_len) {
1888 				if (write_lock_level < 1) {
1889 					write_lock_level = 1;
1890 					btrfs_release_path(p);
1891 					goto again;
1892 				}
1893 
1894 				btrfs_set_path_blocking(p);
1895 				err = split_leaf(trans, root, key,
1896 						 p, ins_len, ret == 0);
1897 				btrfs_clear_path_blocking(p, NULL, 0);
1898 
1899 				BUG_ON(err > 0);
1900 				if (err) {
1901 					ret = err;
1902 					goto done;
1903 				}
1904 			}
1905 			if (!p->search_for_split)
1906 				unlock_up(p, level, lowest_unlock,
1907 					  min_write_lock_level, &write_lock_level);
1908 			goto done;
1909 		}
1910 	}
1911 	ret = 1;
1912 done:
1913 	/*
1914 	 * we don't really know what they plan on doing with the path
1915 	 * from here on, so for now just mark it as blocking
1916 	 */
1917 	if (!p->leave_spinning)
1918 		btrfs_set_path_blocking(p);
1919 	if (ret < 0)
1920 		btrfs_release_path(p);
1921 	return ret;
1922 }
1923 
1924 /*
1925  * adjust the pointers going up the tree, starting at level
1926  * making sure the right key of each node is points to 'key'.
1927  * This is used after shifting pointers to the left, so it stops
1928  * fixing up pointers when a given leaf/node is not in slot 0 of the
1929  * higher levels
1930  *
1931  */
fixup_low_keys(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_path * path,struct btrfs_disk_key * key,int level)1932 static void fixup_low_keys(struct btrfs_trans_handle *trans,
1933 			   struct btrfs_root *root, struct btrfs_path *path,
1934 			   struct btrfs_disk_key *key, int level)
1935 {
1936 	int i;
1937 	struct extent_buffer *t;
1938 
1939 	for (i = level; i < BTRFS_MAX_LEVEL; i++) {
1940 		int tslot = path->slots[i];
1941 		if (!path->nodes[i])
1942 			break;
1943 		t = path->nodes[i];
1944 		btrfs_set_node_key(t, key, tslot);
1945 		btrfs_mark_buffer_dirty(path->nodes[i]);
1946 		if (tslot != 0)
1947 			break;
1948 	}
1949 }
1950 
1951 /*
1952  * update item key.
1953  *
1954  * This function isn't completely safe. It's the caller's responsibility
1955  * that the new key won't break the order
1956  */
btrfs_set_item_key_safe(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_path * path,struct btrfs_key * new_key)1957 void btrfs_set_item_key_safe(struct btrfs_trans_handle *trans,
1958 			     struct btrfs_root *root, struct btrfs_path *path,
1959 			     struct btrfs_key *new_key)
1960 {
1961 	struct btrfs_disk_key disk_key;
1962 	struct extent_buffer *eb;
1963 	int slot;
1964 
1965 	eb = path->nodes[0];
1966 	slot = path->slots[0];
1967 	if (slot > 0) {
1968 		btrfs_item_key(eb, &disk_key, slot - 1);
1969 		BUG_ON(comp_keys(&disk_key, new_key) >= 0);
1970 	}
1971 	if (slot < btrfs_header_nritems(eb) - 1) {
1972 		btrfs_item_key(eb, &disk_key, slot + 1);
1973 		BUG_ON(comp_keys(&disk_key, new_key) <= 0);
1974 	}
1975 
1976 	btrfs_cpu_key_to_disk(&disk_key, new_key);
1977 	btrfs_set_item_key(eb, &disk_key, slot);
1978 	btrfs_mark_buffer_dirty(eb);
1979 	if (slot == 0)
1980 		fixup_low_keys(trans, root, path, &disk_key, 1);
1981 }
1982 
1983 /*
1984  * try to push data from one node into the next node left in the
1985  * tree.
1986  *
1987  * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
1988  * error, and > 0 if there was no room in the left hand block.
1989  */
push_node_left(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct extent_buffer * dst,struct extent_buffer * src,int empty)1990 static int push_node_left(struct btrfs_trans_handle *trans,
1991 			  struct btrfs_root *root, struct extent_buffer *dst,
1992 			  struct extent_buffer *src, int empty)
1993 {
1994 	int push_items = 0;
1995 	int src_nritems;
1996 	int dst_nritems;
1997 	int ret = 0;
1998 
1999 	src_nritems = btrfs_header_nritems(src);
2000 	dst_nritems = btrfs_header_nritems(dst);
2001 	push_items = BTRFS_NODEPTRS_PER_BLOCK(root) - dst_nritems;
2002 	WARN_ON(btrfs_header_generation(src) != trans->transid);
2003 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
2004 
2005 	if (!empty && src_nritems <= 8)
2006 		return 1;
2007 
2008 	if (push_items <= 0)
2009 		return 1;
2010 
2011 	if (empty) {
2012 		push_items = min(src_nritems, push_items);
2013 		if (push_items < src_nritems) {
2014 			/* leave at least 8 pointers in the node if
2015 			 * we aren't going to empty it
2016 			 */
2017 			if (src_nritems - push_items < 8) {
2018 				if (push_items <= 8)
2019 					return 1;
2020 				push_items -= 8;
2021 			}
2022 		}
2023 	} else
2024 		push_items = min(src_nritems - 8, push_items);
2025 
2026 	copy_extent_buffer(dst, src,
2027 			   btrfs_node_key_ptr_offset(dst_nritems),
2028 			   btrfs_node_key_ptr_offset(0),
2029 			   push_items * sizeof(struct btrfs_key_ptr));
2030 
2031 	if (push_items < src_nritems) {
2032 		memmove_extent_buffer(src, btrfs_node_key_ptr_offset(0),
2033 				      btrfs_node_key_ptr_offset(push_items),
2034 				      (src_nritems - push_items) *
2035 				      sizeof(struct btrfs_key_ptr));
2036 	}
2037 	btrfs_set_header_nritems(src, src_nritems - push_items);
2038 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
2039 	btrfs_mark_buffer_dirty(src);
2040 	btrfs_mark_buffer_dirty(dst);
2041 
2042 	return ret;
2043 }
2044 
2045 /*
2046  * try to push data from one node into the next node right in the
2047  * tree.
2048  *
2049  * returns 0 if some ptrs were pushed, < 0 if there was some horrible
2050  * error, and > 0 if there was no room in the right hand block.
2051  *
2052  * this will  only push up to 1/2 the contents of the left node over
2053  */
balance_node_right(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct extent_buffer * dst,struct extent_buffer * src)2054 static int balance_node_right(struct btrfs_trans_handle *trans,
2055 			      struct btrfs_root *root,
2056 			      struct extent_buffer *dst,
2057 			      struct extent_buffer *src)
2058 {
2059 	int push_items = 0;
2060 	int max_push;
2061 	int src_nritems;
2062 	int dst_nritems;
2063 	int ret = 0;
2064 
2065 	WARN_ON(btrfs_header_generation(src) != trans->transid);
2066 	WARN_ON(btrfs_header_generation(dst) != trans->transid);
2067 
2068 	src_nritems = btrfs_header_nritems(src);
2069 	dst_nritems = btrfs_header_nritems(dst);
2070 	push_items = BTRFS_NODEPTRS_PER_BLOCK(root) - dst_nritems;
2071 	if (push_items <= 0)
2072 		return 1;
2073 
2074 	if (src_nritems < 4)
2075 		return 1;
2076 
2077 	max_push = src_nritems / 2 + 1;
2078 	/* don't try to empty the node */
2079 	if (max_push >= src_nritems)
2080 		return 1;
2081 
2082 	if (max_push < push_items)
2083 		push_items = max_push;
2084 
2085 	memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(push_items),
2086 				      btrfs_node_key_ptr_offset(0),
2087 				      (dst_nritems) *
2088 				      sizeof(struct btrfs_key_ptr));
2089 
2090 	copy_extent_buffer(dst, src,
2091 			   btrfs_node_key_ptr_offset(0),
2092 			   btrfs_node_key_ptr_offset(src_nritems - push_items),
2093 			   push_items * sizeof(struct btrfs_key_ptr));
2094 
2095 	btrfs_set_header_nritems(src, src_nritems - push_items);
2096 	btrfs_set_header_nritems(dst, dst_nritems + push_items);
2097 
2098 	btrfs_mark_buffer_dirty(src);
2099 	btrfs_mark_buffer_dirty(dst);
2100 
2101 	return ret;
2102 }
2103 
2104 /*
2105  * helper function to insert a new root level in the tree.
2106  * A new node is allocated, and a single item is inserted to
2107  * point to the existing root
2108  *
2109  * returns zero on success or < 0 on failure.
2110  */
insert_new_root(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_path * path,int level)2111 static noinline int insert_new_root(struct btrfs_trans_handle *trans,
2112 			   struct btrfs_root *root,
2113 			   struct btrfs_path *path, int level)
2114 {
2115 	u64 lower_gen;
2116 	struct extent_buffer *lower;
2117 	struct extent_buffer *c;
2118 	struct extent_buffer *old;
2119 	struct btrfs_disk_key lower_key;
2120 
2121 	BUG_ON(path->nodes[level]);
2122 	BUG_ON(path->nodes[level-1] != root->node);
2123 
2124 	lower = path->nodes[level-1];
2125 	if (level == 1)
2126 		btrfs_item_key(lower, &lower_key, 0);
2127 	else
2128 		btrfs_node_key(lower, &lower_key, 0);
2129 
2130 	c = btrfs_alloc_free_block(trans, root, root->nodesize, 0,
2131 				   root->root_key.objectid, &lower_key,
2132 				   level, root->node->start, 0, 0);
2133 	if (IS_ERR(c))
2134 		return PTR_ERR(c);
2135 
2136 	root_add_used(root, root->nodesize);
2137 
2138 	memset_extent_buffer(c, 0, 0, sizeof(struct btrfs_header));
2139 	btrfs_set_header_nritems(c, 1);
2140 	btrfs_set_header_level(c, level);
2141 	btrfs_set_header_bytenr(c, c->start);
2142 	btrfs_set_header_generation(c, trans->transid);
2143 	btrfs_set_header_backref_rev(c, BTRFS_MIXED_BACKREF_REV);
2144 	btrfs_set_header_owner(c, root->root_key.objectid);
2145 
2146 	write_extent_buffer(c, root->fs_info->fsid,
2147 			    (unsigned long)btrfs_header_fsid(c),
2148 			    BTRFS_FSID_SIZE);
2149 
2150 	write_extent_buffer(c, root->fs_info->chunk_tree_uuid,
2151 			    (unsigned long)btrfs_header_chunk_tree_uuid(c),
2152 			    BTRFS_UUID_SIZE);
2153 
2154 	btrfs_set_node_key(c, &lower_key, 0);
2155 	btrfs_set_node_blockptr(c, 0, lower->start);
2156 	lower_gen = btrfs_header_generation(lower);
2157 	WARN_ON(lower_gen != trans->transid);
2158 
2159 	btrfs_set_node_ptr_generation(c, 0, lower_gen);
2160 
2161 	btrfs_mark_buffer_dirty(c);
2162 
2163 	old = root->node;
2164 	rcu_assign_pointer(root->node, c);
2165 
2166 	/* the super has an extra ref to root->node */
2167 	free_extent_buffer(old);
2168 
2169 	add_root_to_dirty_list(root);
2170 	extent_buffer_get(c);
2171 	path->nodes[level] = c;
2172 	path->locks[level] = BTRFS_WRITE_LOCK;
2173 	path->slots[level] = 0;
2174 	return 0;
2175 }
2176 
2177 /*
2178  * worker function to insert a single pointer in a node.
2179  * the node should have enough room for the pointer already
2180  *
2181  * slot and level indicate where you want the key to go, and
2182  * blocknr is the block the key points to.
2183  */
insert_ptr(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_path * path,struct btrfs_disk_key * key,u64 bytenr,int slot,int level)2184 static void insert_ptr(struct btrfs_trans_handle *trans,
2185 		       struct btrfs_root *root, struct btrfs_path *path,
2186 		       struct btrfs_disk_key *key, u64 bytenr,
2187 		       int slot, int level)
2188 {
2189 	struct extent_buffer *lower;
2190 	int nritems;
2191 
2192 	BUG_ON(!path->nodes[level]);
2193 	btrfs_assert_tree_locked(path->nodes[level]);
2194 	lower = path->nodes[level];
2195 	nritems = btrfs_header_nritems(lower);
2196 	BUG_ON(slot > nritems);
2197 	BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(root));
2198 	if (slot != nritems) {
2199 		memmove_extent_buffer(lower,
2200 			      btrfs_node_key_ptr_offset(slot + 1),
2201 			      btrfs_node_key_ptr_offset(slot),
2202 			      (nritems - slot) * sizeof(struct btrfs_key_ptr));
2203 	}
2204 	btrfs_set_node_key(lower, key, slot);
2205 	btrfs_set_node_blockptr(lower, slot, bytenr);
2206 	WARN_ON(trans->transid == 0);
2207 	btrfs_set_node_ptr_generation(lower, slot, trans->transid);
2208 	btrfs_set_header_nritems(lower, nritems + 1);
2209 	btrfs_mark_buffer_dirty(lower);
2210 }
2211 
2212 /*
2213  * split the node at the specified level in path in two.
2214  * The path is corrected to point to the appropriate node after the split
2215  *
2216  * Before splitting this tries to make some room in the node by pushing
2217  * left and right, if either one works, it returns right away.
2218  *
2219  * returns 0 on success and < 0 on failure
2220  */
split_node(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_path * path,int level)2221 static noinline int split_node(struct btrfs_trans_handle *trans,
2222 			       struct btrfs_root *root,
2223 			       struct btrfs_path *path, int level)
2224 {
2225 	struct extent_buffer *c;
2226 	struct extent_buffer *split;
2227 	struct btrfs_disk_key disk_key;
2228 	int mid;
2229 	int ret;
2230 	u32 c_nritems;
2231 
2232 	c = path->nodes[level];
2233 	WARN_ON(btrfs_header_generation(c) != trans->transid);
2234 	if (c == root->node) {
2235 		/* trying to split the root, lets make a new one */
2236 		ret = insert_new_root(trans, root, path, level + 1);
2237 		if (ret)
2238 			return ret;
2239 	} else {
2240 		ret = push_nodes_for_insert(trans, root, path, level);
2241 		c = path->nodes[level];
2242 		if (!ret && btrfs_header_nritems(c) <
2243 		    BTRFS_NODEPTRS_PER_BLOCK(root) - 3)
2244 			return 0;
2245 		if (ret < 0)
2246 			return ret;
2247 	}
2248 
2249 	c_nritems = btrfs_header_nritems(c);
2250 	mid = (c_nritems + 1) / 2;
2251 	btrfs_node_key(c, &disk_key, mid);
2252 
2253 	split = btrfs_alloc_free_block(trans, root, root->nodesize, 0,
2254 					root->root_key.objectid,
2255 					&disk_key, level, c->start, 0, 0);
2256 	if (IS_ERR(split))
2257 		return PTR_ERR(split);
2258 
2259 	root_add_used(root, root->nodesize);
2260 
2261 	memset_extent_buffer(split, 0, 0, sizeof(struct btrfs_header));
2262 	btrfs_set_header_level(split, btrfs_header_level(c));
2263 	btrfs_set_header_bytenr(split, split->start);
2264 	btrfs_set_header_generation(split, trans->transid);
2265 	btrfs_set_header_backref_rev(split, BTRFS_MIXED_BACKREF_REV);
2266 	btrfs_set_header_owner(split, root->root_key.objectid);
2267 	write_extent_buffer(split, root->fs_info->fsid,
2268 			    (unsigned long)btrfs_header_fsid(split),
2269 			    BTRFS_FSID_SIZE);
2270 	write_extent_buffer(split, root->fs_info->chunk_tree_uuid,
2271 			    (unsigned long)btrfs_header_chunk_tree_uuid(split),
2272 			    BTRFS_UUID_SIZE);
2273 
2274 
2275 	copy_extent_buffer(split, c,
2276 			   btrfs_node_key_ptr_offset(0),
2277 			   btrfs_node_key_ptr_offset(mid),
2278 			   (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
2279 	btrfs_set_header_nritems(split, c_nritems - mid);
2280 	btrfs_set_header_nritems(c, mid);
2281 	ret = 0;
2282 
2283 	btrfs_mark_buffer_dirty(c);
2284 	btrfs_mark_buffer_dirty(split);
2285 
2286 	insert_ptr(trans, root, path, &disk_key, split->start,
2287 		   path->slots[level + 1] + 1, level + 1);
2288 
2289 	if (path->slots[level] >= mid) {
2290 		path->slots[level] -= mid;
2291 		btrfs_tree_unlock(c);
2292 		free_extent_buffer(c);
2293 		path->nodes[level] = split;
2294 		path->slots[level + 1] += 1;
2295 	} else {
2296 		btrfs_tree_unlock(split);
2297 		free_extent_buffer(split);
2298 	}
2299 	return ret;
2300 }
2301 
2302 /*
2303  * how many bytes are required to store the items in a leaf.  start
2304  * and nr indicate which items in the leaf to check.  This totals up the
2305  * space used both by the item structs and the item data
2306  */
leaf_space_used(struct extent_buffer * l,int start,int nr)2307 static int leaf_space_used(struct extent_buffer *l, int start, int nr)
2308 {
2309 	int data_len;
2310 	int nritems = btrfs_header_nritems(l);
2311 	int end = min(nritems, start + nr) - 1;
2312 
2313 	if (!nr)
2314 		return 0;
2315 	data_len = btrfs_item_end_nr(l, start);
2316 	data_len = data_len - btrfs_item_offset_nr(l, end);
2317 	data_len += sizeof(struct btrfs_item) * nr;
2318 	WARN_ON(data_len < 0);
2319 	return data_len;
2320 }
2321 
2322 /*
2323  * The space between the end of the leaf items and
2324  * the start of the leaf data.  IOW, how much room
2325  * the leaf has left for both items and data
2326  */
btrfs_leaf_free_space(struct btrfs_root * root,struct extent_buffer * leaf)2327 noinline int btrfs_leaf_free_space(struct btrfs_root *root,
2328 				   struct extent_buffer *leaf)
2329 {
2330 	int nritems = btrfs_header_nritems(leaf);
2331 	int ret;
2332 	ret = BTRFS_LEAF_DATA_SIZE(root) - leaf_space_used(leaf, 0, nritems);
2333 	if (ret < 0) {
2334 		printk(KERN_CRIT "leaf free space ret %d, leaf data size %lu, "
2335 		       "used %d nritems %d\n",
2336 		       ret, (unsigned long) BTRFS_LEAF_DATA_SIZE(root),
2337 		       leaf_space_used(leaf, 0, nritems), nritems);
2338 	}
2339 	return ret;
2340 }
2341 
2342 /*
2343  * min slot controls the lowest index we're willing to push to the
2344  * right.  We'll push up to and including min_slot, but no lower
2345  */
__push_leaf_right(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_path * path,int data_size,int empty,struct extent_buffer * right,int free_space,u32 left_nritems,u32 min_slot)2346 static noinline int __push_leaf_right(struct btrfs_trans_handle *trans,
2347 				      struct btrfs_root *root,
2348 				      struct btrfs_path *path,
2349 				      int data_size, int empty,
2350 				      struct extent_buffer *right,
2351 				      int free_space, u32 left_nritems,
2352 				      u32 min_slot)
2353 {
2354 	struct extent_buffer *left = path->nodes[0];
2355 	struct extent_buffer *upper = path->nodes[1];
2356 	struct btrfs_map_token token;
2357 	struct btrfs_disk_key disk_key;
2358 	int slot;
2359 	u32 i;
2360 	int push_space = 0;
2361 	int push_items = 0;
2362 	struct btrfs_item *item;
2363 	u32 nr;
2364 	u32 right_nritems;
2365 	u32 data_end;
2366 	u32 this_item_size;
2367 
2368 	btrfs_init_map_token(&token);
2369 
2370 	if (empty)
2371 		nr = 0;
2372 	else
2373 		nr = max_t(u32, 1, min_slot);
2374 
2375 	if (path->slots[0] >= left_nritems)
2376 		push_space += data_size;
2377 
2378 	slot = path->slots[1];
2379 	i = left_nritems - 1;
2380 	while (i >= nr) {
2381 		item = btrfs_item_nr(left, i);
2382 
2383 		if (!empty && push_items > 0) {
2384 			if (path->slots[0] > i)
2385 				break;
2386 			if (path->slots[0] == i) {
2387 				int space = btrfs_leaf_free_space(root, left);
2388 				if (space + push_space * 2 > free_space)
2389 					break;
2390 			}
2391 		}
2392 
2393 		if (path->slots[0] == i)
2394 			push_space += data_size;
2395 
2396 		this_item_size = btrfs_item_size(left, item);
2397 		if (this_item_size + sizeof(*item) + push_space > free_space)
2398 			break;
2399 
2400 		push_items++;
2401 		push_space += this_item_size + sizeof(*item);
2402 		if (i == 0)
2403 			break;
2404 		i--;
2405 	}
2406 
2407 	if (push_items == 0)
2408 		goto out_unlock;
2409 
2410 	if (!empty && push_items == left_nritems)
2411 		WARN_ON(1);
2412 
2413 	/* push left to right */
2414 	right_nritems = btrfs_header_nritems(right);
2415 
2416 	push_space = btrfs_item_end_nr(left, left_nritems - push_items);
2417 	push_space -= leaf_data_end(root, left);
2418 
2419 	/* make room in the right data area */
2420 	data_end = leaf_data_end(root, right);
2421 	memmove_extent_buffer(right,
2422 			      btrfs_leaf_data(right) + data_end - push_space,
2423 			      btrfs_leaf_data(right) + data_end,
2424 			      BTRFS_LEAF_DATA_SIZE(root) - data_end);
2425 
2426 	/* copy from the left data area */
2427 	copy_extent_buffer(right, left, btrfs_leaf_data(right) +
2428 		     BTRFS_LEAF_DATA_SIZE(root) - push_space,
2429 		     btrfs_leaf_data(left) + leaf_data_end(root, left),
2430 		     push_space);
2431 
2432 	memmove_extent_buffer(right, btrfs_item_nr_offset(push_items),
2433 			      btrfs_item_nr_offset(0),
2434 			      right_nritems * sizeof(struct btrfs_item));
2435 
2436 	/* copy the items from left to right */
2437 	copy_extent_buffer(right, left, btrfs_item_nr_offset(0),
2438 		   btrfs_item_nr_offset(left_nritems - push_items),
2439 		   push_items * sizeof(struct btrfs_item));
2440 
2441 	/* update the item pointers */
2442 	right_nritems += push_items;
2443 	btrfs_set_header_nritems(right, right_nritems);
2444 	push_space = BTRFS_LEAF_DATA_SIZE(root);
2445 	for (i = 0; i < right_nritems; i++) {
2446 		item = btrfs_item_nr(right, i);
2447 		push_space -= btrfs_token_item_size(right, item, &token);
2448 		btrfs_set_token_item_offset(right, item, push_space, &token);
2449 	}
2450 
2451 	left_nritems -= push_items;
2452 	btrfs_set_header_nritems(left, left_nritems);
2453 
2454 	if (left_nritems)
2455 		btrfs_mark_buffer_dirty(left);
2456 	else
2457 		clean_tree_block(trans, root, left);
2458 
2459 	btrfs_mark_buffer_dirty(right);
2460 
2461 	btrfs_item_key(right, &disk_key, 0);
2462 	btrfs_set_node_key(upper, &disk_key, slot + 1);
2463 	btrfs_mark_buffer_dirty(upper);
2464 
2465 	/* then fixup the leaf pointer in the path */
2466 	if (path->slots[0] >= left_nritems) {
2467 		path->slots[0] -= left_nritems;
2468 		if (btrfs_header_nritems(path->nodes[0]) == 0)
2469 			clean_tree_block(trans, root, path->nodes[0]);
2470 		btrfs_tree_unlock(path->nodes[0]);
2471 		free_extent_buffer(path->nodes[0]);
2472 		path->nodes[0] = right;
2473 		path->slots[1] += 1;
2474 	} else {
2475 		btrfs_tree_unlock(right);
2476 		free_extent_buffer(right);
2477 	}
2478 	return 0;
2479 
2480 out_unlock:
2481 	btrfs_tree_unlock(right);
2482 	free_extent_buffer(right);
2483 	return 1;
2484 }
2485 
2486 /*
2487  * push some data in the path leaf to the right, trying to free up at
2488  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
2489  *
2490  * returns 1 if the push failed because the other node didn't have enough
2491  * room, 0 if everything worked out and < 0 if there were major errors.
2492  *
2493  * this will push starting from min_slot to the end of the leaf.  It won't
2494  * push any slot lower than min_slot
2495  */
push_leaf_right(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_path * path,int min_data_size,int data_size,int empty,u32 min_slot)2496 static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
2497 			   *root, struct btrfs_path *path,
2498 			   int min_data_size, int data_size,
2499 			   int empty, u32 min_slot)
2500 {
2501 	struct extent_buffer *left = path->nodes[0];
2502 	struct extent_buffer *right;
2503 	struct extent_buffer *upper;
2504 	int slot;
2505 	int free_space;
2506 	u32 left_nritems;
2507 	int ret;
2508 
2509 	if (!path->nodes[1])
2510 		return 1;
2511 
2512 	slot = path->slots[1];
2513 	upper = path->nodes[1];
2514 	if (slot >= btrfs_header_nritems(upper) - 1)
2515 		return 1;
2516 
2517 	btrfs_assert_tree_locked(path->nodes[1]);
2518 
2519 	right = read_node_slot(root, upper, slot + 1);
2520 	if (right == NULL)
2521 		return 1;
2522 
2523 	btrfs_tree_lock(right);
2524 	btrfs_set_lock_blocking(right);
2525 
2526 	free_space = btrfs_leaf_free_space(root, right);
2527 	if (free_space < data_size)
2528 		goto out_unlock;
2529 
2530 	/* cow and double check */
2531 	ret = btrfs_cow_block(trans, root, right, upper,
2532 			      slot + 1, &right);
2533 	if (ret)
2534 		goto out_unlock;
2535 
2536 	free_space = btrfs_leaf_free_space(root, right);
2537 	if (free_space < data_size)
2538 		goto out_unlock;
2539 
2540 	left_nritems = btrfs_header_nritems(left);
2541 	if (left_nritems == 0)
2542 		goto out_unlock;
2543 
2544 	return __push_leaf_right(trans, root, path, min_data_size, empty,
2545 				right, free_space, left_nritems, min_slot);
2546 out_unlock:
2547 	btrfs_tree_unlock(right);
2548 	free_extent_buffer(right);
2549 	return 1;
2550 }
2551 
2552 /*
2553  * push some data in the path leaf to the left, trying to free up at
2554  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
2555  *
2556  * max_slot can put a limit on how far into the leaf we'll push items.  The
2557  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us do all the
2558  * items
2559  */
__push_leaf_left(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_path * path,int data_size,int empty,struct extent_buffer * left,int free_space,u32 right_nritems,u32 max_slot)2560 static noinline int __push_leaf_left(struct btrfs_trans_handle *trans,
2561 				     struct btrfs_root *root,
2562 				     struct btrfs_path *path, int data_size,
2563 				     int empty, struct extent_buffer *left,
2564 				     int free_space, u32 right_nritems,
2565 				     u32 max_slot)
2566 {
2567 	struct btrfs_disk_key disk_key;
2568 	struct extent_buffer *right = path->nodes[0];
2569 	int i;
2570 	int push_space = 0;
2571 	int push_items = 0;
2572 	struct btrfs_item *item;
2573 	u32 old_left_nritems;
2574 	u32 nr;
2575 	int ret = 0;
2576 	u32 this_item_size;
2577 	u32 old_left_item_size;
2578 	struct btrfs_map_token token;
2579 
2580 	btrfs_init_map_token(&token);
2581 
2582 	if (empty)
2583 		nr = min(right_nritems, max_slot);
2584 	else
2585 		nr = min(right_nritems - 1, max_slot);
2586 
2587 	for (i = 0; i < nr; i++) {
2588 		item = btrfs_item_nr(right, i);
2589 
2590 		if (!empty && push_items > 0) {
2591 			if (path->slots[0] < i)
2592 				break;
2593 			if (path->slots[0] == i) {
2594 				int space = btrfs_leaf_free_space(root, right);
2595 				if (space + push_space * 2 > free_space)
2596 					break;
2597 			}
2598 		}
2599 
2600 		if (path->slots[0] == i)
2601 			push_space += data_size;
2602 
2603 		this_item_size = btrfs_item_size(right, item);
2604 		if (this_item_size + sizeof(*item) + push_space > free_space)
2605 			break;
2606 
2607 		push_items++;
2608 		push_space += this_item_size + sizeof(*item);
2609 	}
2610 
2611 	if (push_items == 0) {
2612 		ret = 1;
2613 		goto out;
2614 	}
2615 	if (!empty && push_items == btrfs_header_nritems(right))
2616 		WARN_ON(1);
2617 
2618 	/* push data from right to left */
2619 	copy_extent_buffer(left, right,
2620 			   btrfs_item_nr_offset(btrfs_header_nritems(left)),
2621 			   btrfs_item_nr_offset(0),
2622 			   push_items * sizeof(struct btrfs_item));
2623 
2624 	push_space = BTRFS_LEAF_DATA_SIZE(root) -
2625 		     btrfs_item_offset_nr(right, push_items - 1);
2626 
2627 	copy_extent_buffer(left, right, btrfs_leaf_data(left) +
2628 		     leaf_data_end(root, left) - push_space,
2629 		     btrfs_leaf_data(right) +
2630 		     btrfs_item_offset_nr(right, push_items - 1),
2631 		     push_space);
2632 	old_left_nritems = btrfs_header_nritems(left);
2633 	BUG_ON(old_left_nritems <= 0);
2634 
2635 	old_left_item_size = btrfs_item_offset_nr(left, old_left_nritems - 1);
2636 	for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
2637 		u32 ioff;
2638 
2639 		item = btrfs_item_nr(left, i);
2640 
2641 		ioff = btrfs_token_item_offset(left, item, &token);
2642 		btrfs_set_token_item_offset(left, item,
2643 		      ioff - (BTRFS_LEAF_DATA_SIZE(root) - old_left_item_size),
2644 		      &token);
2645 	}
2646 	btrfs_set_header_nritems(left, old_left_nritems + push_items);
2647 
2648 	/* fixup right node */
2649 	if (push_items > right_nritems) {
2650 		printk(KERN_CRIT "push items %d nr %u\n", push_items,
2651 		       right_nritems);
2652 		WARN_ON(1);
2653 	}
2654 
2655 	if (push_items < right_nritems) {
2656 		push_space = btrfs_item_offset_nr(right, push_items - 1) -
2657 						  leaf_data_end(root, right);
2658 		memmove_extent_buffer(right, btrfs_leaf_data(right) +
2659 				      BTRFS_LEAF_DATA_SIZE(root) - push_space,
2660 				      btrfs_leaf_data(right) +
2661 				      leaf_data_end(root, right), push_space);
2662 
2663 		memmove_extent_buffer(right, btrfs_item_nr_offset(0),
2664 			      btrfs_item_nr_offset(push_items),
2665 			     (btrfs_header_nritems(right) - push_items) *
2666 			     sizeof(struct btrfs_item));
2667 	}
2668 	right_nritems -= push_items;
2669 	btrfs_set_header_nritems(right, right_nritems);
2670 	push_space = BTRFS_LEAF_DATA_SIZE(root);
2671 	for (i = 0; i < right_nritems; i++) {
2672 		item = btrfs_item_nr(right, i);
2673 
2674 		push_space = push_space - btrfs_token_item_size(right,
2675 								item, &token);
2676 		btrfs_set_token_item_offset(right, item, push_space, &token);
2677 	}
2678 
2679 	btrfs_mark_buffer_dirty(left);
2680 	if (right_nritems)
2681 		btrfs_mark_buffer_dirty(right);
2682 	else
2683 		clean_tree_block(trans, root, right);
2684 
2685 	btrfs_item_key(right, &disk_key, 0);
2686 	fixup_low_keys(trans, root, path, &disk_key, 1);
2687 
2688 	/* then fixup the leaf pointer in the path */
2689 	if (path->slots[0] < push_items) {
2690 		path->slots[0] += old_left_nritems;
2691 		btrfs_tree_unlock(path->nodes[0]);
2692 		free_extent_buffer(path->nodes[0]);
2693 		path->nodes[0] = left;
2694 		path->slots[1] -= 1;
2695 	} else {
2696 		btrfs_tree_unlock(left);
2697 		free_extent_buffer(left);
2698 		path->slots[0] -= push_items;
2699 	}
2700 	BUG_ON(path->slots[0] < 0);
2701 	return ret;
2702 out:
2703 	btrfs_tree_unlock(left);
2704 	free_extent_buffer(left);
2705 	return ret;
2706 }
2707 
2708 /*
2709  * push some data in the path leaf to the left, trying to free up at
2710  * least data_size bytes.  returns zero if the push worked, nonzero otherwise
2711  *
2712  * max_slot can put a limit on how far into the leaf we'll push items.  The
2713  * item at 'max_slot' won't be touched.  Use (u32)-1 to make us push all the
2714  * items
2715  */
push_leaf_left(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_path * path,int min_data_size,int data_size,int empty,u32 max_slot)2716 static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
2717 			  *root, struct btrfs_path *path, int min_data_size,
2718 			  int data_size, int empty, u32 max_slot)
2719 {
2720 	struct extent_buffer *right = path->nodes[0];
2721 	struct extent_buffer *left;
2722 	int slot;
2723 	int free_space;
2724 	u32 right_nritems;
2725 	int ret = 0;
2726 
2727 	slot = path->slots[1];
2728 	if (slot == 0)
2729 		return 1;
2730 	if (!path->nodes[1])
2731 		return 1;
2732 
2733 	right_nritems = btrfs_header_nritems(right);
2734 	if (right_nritems == 0)
2735 		return 1;
2736 
2737 	btrfs_assert_tree_locked(path->nodes[1]);
2738 
2739 	left = read_node_slot(root, path->nodes[1], slot - 1);
2740 	if (left == NULL)
2741 		return 1;
2742 
2743 	btrfs_tree_lock(left);
2744 	btrfs_set_lock_blocking(left);
2745 
2746 	free_space = btrfs_leaf_free_space(root, left);
2747 	if (free_space < data_size) {
2748 		ret = 1;
2749 		goto out;
2750 	}
2751 
2752 	/* cow and double check */
2753 	ret = btrfs_cow_block(trans, root, left,
2754 			      path->nodes[1], slot - 1, &left);
2755 	if (ret) {
2756 		/* we hit -ENOSPC, but it isn't fatal here */
2757 		if (ret == -ENOSPC)
2758 			ret = 1;
2759 		goto out;
2760 	}
2761 
2762 	free_space = btrfs_leaf_free_space(root, left);
2763 	if (free_space < data_size) {
2764 		ret = 1;
2765 		goto out;
2766 	}
2767 
2768 	return __push_leaf_left(trans, root, path, min_data_size,
2769 			       empty, left, free_space, right_nritems,
2770 			       max_slot);
2771 out:
2772 	btrfs_tree_unlock(left);
2773 	free_extent_buffer(left);
2774 	return ret;
2775 }
2776 
2777 /*
2778  * split the path's leaf in two, making sure there is at least data_size
2779  * available for the resulting leaf level of the path.
2780  */
copy_for_split(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_path * path,struct extent_buffer * l,struct extent_buffer * right,int slot,int mid,int nritems)2781 static noinline void copy_for_split(struct btrfs_trans_handle *trans,
2782 				    struct btrfs_root *root,
2783 				    struct btrfs_path *path,
2784 				    struct extent_buffer *l,
2785 				    struct extent_buffer *right,
2786 				    int slot, int mid, int nritems)
2787 {
2788 	int data_copy_size;
2789 	int rt_data_off;
2790 	int i;
2791 	struct btrfs_disk_key disk_key;
2792 	struct btrfs_map_token token;
2793 
2794 	btrfs_init_map_token(&token);
2795 
2796 	nritems = nritems - mid;
2797 	btrfs_set_header_nritems(right, nritems);
2798 	data_copy_size = btrfs_item_end_nr(l, mid) - leaf_data_end(root, l);
2799 
2800 	copy_extent_buffer(right, l, btrfs_item_nr_offset(0),
2801 			   btrfs_item_nr_offset(mid),
2802 			   nritems * sizeof(struct btrfs_item));
2803 
2804 	copy_extent_buffer(right, l,
2805 		     btrfs_leaf_data(right) + BTRFS_LEAF_DATA_SIZE(root) -
2806 		     data_copy_size, btrfs_leaf_data(l) +
2807 		     leaf_data_end(root, l), data_copy_size);
2808 
2809 	rt_data_off = BTRFS_LEAF_DATA_SIZE(root) -
2810 		      btrfs_item_end_nr(l, mid);
2811 
2812 	for (i = 0; i < nritems; i++) {
2813 		struct btrfs_item *item = btrfs_item_nr(right, i);
2814 		u32 ioff;
2815 
2816 		ioff = btrfs_token_item_offset(right, item, &token);
2817 		btrfs_set_token_item_offset(right, item,
2818 					    ioff + rt_data_off, &token);
2819 	}
2820 
2821 	btrfs_set_header_nritems(l, mid);
2822 	btrfs_item_key(right, &disk_key, 0);
2823 	insert_ptr(trans, root, path, &disk_key, right->start,
2824 		   path->slots[1] + 1, 1);
2825 
2826 	btrfs_mark_buffer_dirty(right);
2827 	btrfs_mark_buffer_dirty(l);
2828 	BUG_ON(path->slots[0] != slot);
2829 
2830 	if (mid <= slot) {
2831 		btrfs_tree_unlock(path->nodes[0]);
2832 		free_extent_buffer(path->nodes[0]);
2833 		path->nodes[0] = right;
2834 		path->slots[0] -= mid;
2835 		path->slots[1] += 1;
2836 	} else {
2837 		btrfs_tree_unlock(right);
2838 		free_extent_buffer(right);
2839 	}
2840 
2841 	BUG_ON(path->slots[0] < 0);
2842 }
2843 
2844 /*
2845  * double splits happen when we need to insert a big item in the middle
2846  * of a leaf.  A double split can leave us with 3 mostly empty leaves:
2847  * leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
2848  *          A                 B                 C
2849  *
2850  * We avoid this by trying to push the items on either side of our target
2851  * into the adjacent leaves.  If all goes well we can avoid the double split
2852  * completely.
2853  */
push_for_double_split(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_path * path,int data_size)2854 static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
2855 					  struct btrfs_root *root,
2856 					  struct btrfs_path *path,
2857 					  int data_size)
2858 {
2859 	int ret;
2860 	int progress = 0;
2861 	int slot;
2862 	u32 nritems;
2863 
2864 	slot = path->slots[0];
2865 
2866 	/*
2867 	 * try to push all the items after our slot into the
2868 	 * right leaf
2869 	 */
2870 	ret = push_leaf_right(trans, root, path, 1, data_size, 0, slot);
2871 	if (ret < 0)
2872 		return ret;
2873 
2874 	if (ret == 0)
2875 		progress++;
2876 
2877 	nritems = btrfs_header_nritems(path->nodes[0]);
2878 	/*
2879 	 * our goal is to get our slot at the start or end of a leaf.  If
2880 	 * we've done so we're done
2881 	 */
2882 	if (path->slots[0] == 0 || path->slots[0] == nritems)
2883 		return 0;
2884 
2885 	if (btrfs_leaf_free_space(root, path->nodes[0]) >= data_size)
2886 		return 0;
2887 
2888 	/* try to push all the items before our slot into the next leaf */
2889 	slot = path->slots[0];
2890 	ret = push_leaf_left(trans, root, path, 1, data_size, 0, slot);
2891 	if (ret < 0)
2892 		return ret;
2893 
2894 	if (ret == 0)
2895 		progress++;
2896 
2897 	if (progress)
2898 		return 0;
2899 	return 1;
2900 }
2901 
2902 /*
2903  * split the path's leaf in two, making sure there is at least data_size
2904  * available for the resulting leaf level of the path.
2905  *
2906  * returns 0 if all went well and < 0 on failure.
2907  */
split_leaf(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_key * ins_key,struct btrfs_path * path,int data_size,int extend)2908 static noinline int split_leaf(struct btrfs_trans_handle *trans,
2909 			       struct btrfs_root *root,
2910 			       struct btrfs_key *ins_key,
2911 			       struct btrfs_path *path, int data_size,
2912 			       int extend)
2913 {
2914 	struct btrfs_disk_key disk_key;
2915 	struct extent_buffer *l;
2916 	u32 nritems;
2917 	int mid;
2918 	int slot;
2919 	struct extent_buffer *right;
2920 	int ret = 0;
2921 	int wret;
2922 	int split;
2923 	int num_doubles = 0;
2924 	int tried_avoid_double = 0;
2925 
2926 	l = path->nodes[0];
2927 	slot = path->slots[0];
2928 	if (extend && data_size + btrfs_item_size_nr(l, slot) +
2929 	    sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(root))
2930 		return -EOVERFLOW;
2931 
2932 	/* first try to make some room by pushing left and right */
2933 	if (data_size) {
2934 		wret = push_leaf_right(trans, root, path, data_size,
2935 				       data_size, 0, 0);
2936 		if (wret < 0)
2937 			return wret;
2938 		if (wret) {
2939 			wret = push_leaf_left(trans, root, path, data_size,
2940 					      data_size, 0, (u32)-1);
2941 			if (wret < 0)
2942 				return wret;
2943 		}
2944 		l = path->nodes[0];
2945 
2946 		/* did the pushes work? */
2947 		if (btrfs_leaf_free_space(root, l) >= data_size)
2948 			return 0;
2949 	}
2950 
2951 	if (!path->nodes[1]) {
2952 		ret = insert_new_root(trans, root, path, 1);
2953 		if (ret)
2954 			return ret;
2955 	}
2956 again:
2957 	split = 1;
2958 	l = path->nodes[0];
2959 	slot = path->slots[0];
2960 	nritems = btrfs_header_nritems(l);
2961 	mid = (nritems + 1) / 2;
2962 
2963 	if (mid <= slot) {
2964 		if (nritems == 1 ||
2965 		    leaf_space_used(l, mid, nritems - mid) + data_size >
2966 			BTRFS_LEAF_DATA_SIZE(root)) {
2967 			if (slot >= nritems) {
2968 				split = 0;
2969 			} else {
2970 				mid = slot;
2971 				if (mid != nritems &&
2972 				    leaf_space_used(l, mid, nritems - mid) +
2973 				    data_size > BTRFS_LEAF_DATA_SIZE(root)) {
2974 					if (data_size && !tried_avoid_double)
2975 						goto push_for_double;
2976 					split = 2;
2977 				}
2978 			}
2979 		}
2980 	} else {
2981 		if (leaf_space_used(l, 0, mid) + data_size >
2982 			BTRFS_LEAF_DATA_SIZE(root)) {
2983 			if (!extend && data_size && slot == 0) {
2984 				split = 0;
2985 			} else if ((extend || !data_size) && slot == 0) {
2986 				mid = 1;
2987 			} else {
2988 				mid = slot;
2989 				if (mid != nritems &&
2990 				    leaf_space_used(l, mid, nritems - mid) +
2991 				    data_size > BTRFS_LEAF_DATA_SIZE(root)) {
2992 					if (data_size && !tried_avoid_double)
2993 						goto push_for_double;
2994 					split = 2 ;
2995 				}
2996 			}
2997 		}
2998 	}
2999 
3000 	if (split == 0)
3001 		btrfs_cpu_key_to_disk(&disk_key, ins_key);
3002 	else
3003 		btrfs_item_key(l, &disk_key, mid);
3004 
3005 	right = btrfs_alloc_free_block(trans, root, root->leafsize, 0,
3006 					root->root_key.objectid,
3007 					&disk_key, 0, l->start, 0, 0);
3008 	if (IS_ERR(right))
3009 		return PTR_ERR(right);
3010 
3011 	root_add_used(root, root->leafsize);
3012 
3013 	memset_extent_buffer(right, 0, 0, sizeof(struct btrfs_header));
3014 	btrfs_set_header_bytenr(right, right->start);
3015 	btrfs_set_header_generation(right, trans->transid);
3016 	btrfs_set_header_backref_rev(right, BTRFS_MIXED_BACKREF_REV);
3017 	btrfs_set_header_owner(right, root->root_key.objectid);
3018 	btrfs_set_header_level(right, 0);
3019 	write_extent_buffer(right, root->fs_info->fsid,
3020 			    (unsigned long)btrfs_header_fsid(right),
3021 			    BTRFS_FSID_SIZE);
3022 
3023 	write_extent_buffer(right, root->fs_info->chunk_tree_uuid,
3024 			    (unsigned long)btrfs_header_chunk_tree_uuid(right),
3025 			    BTRFS_UUID_SIZE);
3026 
3027 	if (split == 0) {
3028 		if (mid <= slot) {
3029 			btrfs_set_header_nritems(right, 0);
3030 			insert_ptr(trans, root, path, &disk_key, right->start,
3031 				   path->slots[1] + 1, 1);
3032 			btrfs_tree_unlock(path->nodes[0]);
3033 			free_extent_buffer(path->nodes[0]);
3034 			path->nodes[0] = right;
3035 			path->slots[0] = 0;
3036 			path->slots[1] += 1;
3037 		} else {
3038 			btrfs_set_header_nritems(right, 0);
3039 			insert_ptr(trans, root, path, &disk_key, right->start,
3040 					  path->slots[1], 1);
3041 			btrfs_tree_unlock(path->nodes[0]);
3042 			free_extent_buffer(path->nodes[0]);
3043 			path->nodes[0] = right;
3044 			path->slots[0] = 0;
3045 			if (path->slots[1] == 0)
3046 				fixup_low_keys(trans, root, path,
3047 					       &disk_key, 1);
3048 		}
3049 		btrfs_mark_buffer_dirty(right);
3050 		return ret;
3051 	}
3052 
3053 	copy_for_split(trans, root, path, l, right, slot, mid, nritems);
3054 
3055 	if (split == 2) {
3056 		BUG_ON(num_doubles != 0);
3057 		num_doubles++;
3058 		goto again;
3059 	}
3060 
3061 	return 0;
3062 
3063 push_for_double:
3064 	push_for_double_split(trans, root, path, data_size);
3065 	tried_avoid_double = 1;
3066 	if (btrfs_leaf_free_space(root, path->nodes[0]) >= data_size)
3067 		return 0;
3068 	goto again;
3069 }
3070 
setup_leaf_for_split(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_path * path,int ins_len)3071 static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
3072 					 struct btrfs_root *root,
3073 					 struct btrfs_path *path, int ins_len)
3074 {
3075 	struct btrfs_key key;
3076 	struct extent_buffer *leaf;
3077 	struct btrfs_file_extent_item *fi;
3078 	u64 extent_len = 0;
3079 	u32 item_size;
3080 	int ret;
3081 
3082 	leaf = path->nodes[0];
3083 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3084 
3085 	BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
3086 	       key.type != BTRFS_EXTENT_CSUM_KEY);
3087 
3088 	if (btrfs_leaf_free_space(root, leaf) >= ins_len)
3089 		return 0;
3090 
3091 	item_size = btrfs_item_size_nr(leaf, path->slots[0]);
3092 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
3093 		fi = btrfs_item_ptr(leaf, path->slots[0],
3094 				    struct btrfs_file_extent_item);
3095 		extent_len = btrfs_file_extent_num_bytes(leaf, fi);
3096 	}
3097 	btrfs_release_path(path);
3098 
3099 	path->keep_locks = 1;
3100 	path->search_for_split = 1;
3101 	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
3102 	path->search_for_split = 0;
3103 	if (ret < 0)
3104 		goto err;
3105 
3106 	ret = -EAGAIN;
3107 	leaf = path->nodes[0];
3108 	/* if our item isn't there or got smaller, return now */
3109 	if (ret > 0 || item_size != btrfs_item_size_nr(leaf, path->slots[0]))
3110 		goto err;
3111 
3112 	/* the leaf has  changed, it now has room.  return now */
3113 	if (btrfs_leaf_free_space(root, path->nodes[0]) >= ins_len)
3114 		goto err;
3115 
3116 	if (key.type == BTRFS_EXTENT_DATA_KEY) {
3117 		fi = btrfs_item_ptr(leaf, path->slots[0],
3118 				    struct btrfs_file_extent_item);
3119 		if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
3120 			goto err;
3121 	}
3122 
3123 	btrfs_set_path_blocking(path);
3124 	ret = split_leaf(trans, root, &key, path, ins_len, 1);
3125 	if (ret)
3126 		goto err;
3127 
3128 	path->keep_locks = 0;
3129 	btrfs_unlock_up_safe(path, 1);
3130 	return 0;
3131 err:
3132 	path->keep_locks = 0;
3133 	return ret;
3134 }
3135 
split_item(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_path * path,struct btrfs_key * new_key,unsigned long split_offset)3136 static noinline int split_item(struct btrfs_trans_handle *trans,
3137 			       struct btrfs_root *root,
3138 			       struct btrfs_path *path,
3139 			       struct btrfs_key *new_key,
3140 			       unsigned long split_offset)
3141 {
3142 	struct extent_buffer *leaf;
3143 	struct btrfs_item *item;
3144 	struct btrfs_item *new_item;
3145 	int slot;
3146 	char *buf;
3147 	u32 nritems;
3148 	u32 item_size;
3149 	u32 orig_offset;
3150 	struct btrfs_disk_key disk_key;
3151 
3152 	leaf = path->nodes[0];
3153 	BUG_ON(btrfs_leaf_free_space(root, leaf) < sizeof(struct btrfs_item));
3154 
3155 	btrfs_set_path_blocking(path);
3156 
3157 	item = btrfs_item_nr(leaf, path->slots[0]);
3158 	orig_offset = btrfs_item_offset(leaf, item);
3159 	item_size = btrfs_item_size(leaf, item);
3160 
3161 	buf = kmalloc(item_size, GFP_NOFS);
3162 	if (!buf)
3163 		return -ENOMEM;
3164 
3165 	read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
3166 			    path->slots[0]), item_size);
3167 
3168 	slot = path->slots[0] + 1;
3169 	nritems = btrfs_header_nritems(leaf);
3170 	if (slot != nritems) {
3171 		/* shift the items */
3172 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + 1),
3173 				btrfs_item_nr_offset(slot),
3174 				(nritems - slot) * sizeof(struct btrfs_item));
3175 	}
3176 
3177 	btrfs_cpu_key_to_disk(&disk_key, new_key);
3178 	btrfs_set_item_key(leaf, &disk_key, slot);
3179 
3180 	new_item = btrfs_item_nr(leaf, slot);
3181 
3182 	btrfs_set_item_offset(leaf, new_item, orig_offset);
3183 	btrfs_set_item_size(leaf, new_item, item_size - split_offset);
3184 
3185 	btrfs_set_item_offset(leaf, item,
3186 			      orig_offset + item_size - split_offset);
3187 	btrfs_set_item_size(leaf, item, split_offset);
3188 
3189 	btrfs_set_header_nritems(leaf, nritems + 1);
3190 
3191 	/* write the data for the start of the original item */
3192 	write_extent_buffer(leaf, buf,
3193 			    btrfs_item_ptr_offset(leaf, path->slots[0]),
3194 			    split_offset);
3195 
3196 	/* write the data for the new item */
3197 	write_extent_buffer(leaf, buf + split_offset,
3198 			    btrfs_item_ptr_offset(leaf, slot),
3199 			    item_size - split_offset);
3200 	btrfs_mark_buffer_dirty(leaf);
3201 
3202 	BUG_ON(btrfs_leaf_free_space(root, leaf) < 0);
3203 	kfree(buf);
3204 	return 0;
3205 }
3206 
3207 /*
3208  * This function splits a single item into two items,
3209  * giving 'new_key' to the new item and splitting the
3210  * old one at split_offset (from the start of the item).
3211  *
3212  * The path may be released by this operation.  After
3213  * the split, the path is pointing to the old item.  The
3214  * new item is going to be in the same node as the old one.
3215  *
3216  * Note, the item being split must be smaller enough to live alone on
3217  * a tree block with room for one extra struct btrfs_item
3218  *
3219  * This allows us to split the item in place, keeping a lock on the
3220  * leaf the entire time.
3221  */
btrfs_split_item(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_path * path,struct btrfs_key * new_key,unsigned long split_offset)3222 int btrfs_split_item(struct btrfs_trans_handle *trans,
3223 		     struct btrfs_root *root,
3224 		     struct btrfs_path *path,
3225 		     struct btrfs_key *new_key,
3226 		     unsigned long split_offset)
3227 {
3228 	int ret;
3229 	ret = setup_leaf_for_split(trans, root, path,
3230 				   sizeof(struct btrfs_item));
3231 	if (ret)
3232 		return ret;
3233 
3234 	ret = split_item(trans, root, path, new_key, split_offset);
3235 	return ret;
3236 }
3237 
3238 /*
3239  * This function duplicate a item, giving 'new_key' to the new item.
3240  * It guarantees both items live in the same tree leaf and the new item
3241  * is contiguous with the original item.
3242  *
3243  * This allows us to split file extent in place, keeping a lock on the
3244  * leaf the entire time.
3245  */
btrfs_duplicate_item(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_path * path,struct btrfs_key * new_key)3246 int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
3247 			 struct btrfs_root *root,
3248 			 struct btrfs_path *path,
3249 			 struct btrfs_key *new_key)
3250 {
3251 	struct extent_buffer *leaf;
3252 	int ret;
3253 	u32 item_size;
3254 
3255 	leaf = path->nodes[0];
3256 	item_size = btrfs_item_size_nr(leaf, path->slots[0]);
3257 	ret = setup_leaf_for_split(trans, root, path,
3258 				   item_size + sizeof(struct btrfs_item));
3259 	if (ret)
3260 		return ret;
3261 
3262 	path->slots[0]++;
3263 	setup_items_for_insert(trans, root, path, new_key, &item_size,
3264 			       item_size, item_size +
3265 			       sizeof(struct btrfs_item), 1);
3266 	leaf = path->nodes[0];
3267 	memcpy_extent_buffer(leaf,
3268 			     btrfs_item_ptr_offset(leaf, path->slots[0]),
3269 			     btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
3270 			     item_size);
3271 	return 0;
3272 }
3273 
3274 /*
3275  * make the item pointed to by the path smaller.  new_size indicates
3276  * how small to make it, and from_end tells us if we just chop bytes
3277  * off the end of the item or if we shift the item to chop bytes off
3278  * the front.
3279  */
btrfs_truncate_item(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_path * path,u32 new_size,int from_end)3280 void btrfs_truncate_item(struct btrfs_trans_handle *trans,
3281 			 struct btrfs_root *root,
3282 			 struct btrfs_path *path,
3283 			 u32 new_size, int from_end)
3284 {
3285 	int slot;
3286 	struct extent_buffer *leaf;
3287 	struct btrfs_item *item;
3288 	u32 nritems;
3289 	unsigned int data_end;
3290 	unsigned int old_data_start;
3291 	unsigned int old_size;
3292 	unsigned int size_diff;
3293 	int i;
3294 	struct btrfs_map_token token;
3295 
3296 	btrfs_init_map_token(&token);
3297 
3298 	leaf = path->nodes[0];
3299 	slot = path->slots[0];
3300 
3301 	old_size = btrfs_item_size_nr(leaf, slot);
3302 	if (old_size == new_size)
3303 		return;
3304 
3305 	nritems = btrfs_header_nritems(leaf);
3306 	data_end = leaf_data_end(root, leaf);
3307 
3308 	old_data_start = btrfs_item_offset_nr(leaf, slot);
3309 
3310 	size_diff = old_size - new_size;
3311 
3312 	BUG_ON(slot < 0);
3313 	BUG_ON(slot >= nritems);
3314 
3315 	/*
3316 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
3317 	 */
3318 	/* first correct the data pointers */
3319 	for (i = slot; i < nritems; i++) {
3320 		u32 ioff;
3321 		item = btrfs_item_nr(leaf, i);
3322 
3323 		ioff = btrfs_token_item_offset(leaf, item, &token);
3324 		btrfs_set_token_item_offset(leaf, item,
3325 					    ioff + size_diff, &token);
3326 	}
3327 
3328 	/* shift the data */
3329 	if (from_end) {
3330 		memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
3331 			      data_end + size_diff, btrfs_leaf_data(leaf) +
3332 			      data_end, old_data_start + new_size - data_end);
3333 	} else {
3334 		struct btrfs_disk_key disk_key;
3335 		u64 offset;
3336 
3337 		btrfs_item_key(leaf, &disk_key, slot);
3338 
3339 		if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
3340 			unsigned long ptr;
3341 			struct btrfs_file_extent_item *fi;
3342 
3343 			fi = btrfs_item_ptr(leaf, slot,
3344 					    struct btrfs_file_extent_item);
3345 			fi = (struct btrfs_file_extent_item *)(
3346 			     (unsigned long)fi - size_diff);
3347 
3348 			if (btrfs_file_extent_type(leaf, fi) ==
3349 			    BTRFS_FILE_EXTENT_INLINE) {
3350 				ptr = btrfs_item_ptr_offset(leaf, slot);
3351 				memmove_extent_buffer(leaf, ptr,
3352 				      (unsigned long)fi,
3353 				      offsetof(struct btrfs_file_extent_item,
3354 						 disk_bytenr));
3355 			}
3356 		}
3357 
3358 		memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
3359 			      data_end + size_diff, btrfs_leaf_data(leaf) +
3360 			      data_end, old_data_start - data_end);
3361 
3362 		offset = btrfs_disk_key_offset(&disk_key);
3363 		btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
3364 		btrfs_set_item_key(leaf, &disk_key, slot);
3365 		if (slot == 0)
3366 			fixup_low_keys(trans, root, path, &disk_key, 1);
3367 	}
3368 
3369 	item = btrfs_item_nr(leaf, slot);
3370 	btrfs_set_item_size(leaf, item, new_size);
3371 	btrfs_mark_buffer_dirty(leaf);
3372 
3373 	if (btrfs_leaf_free_space(root, leaf) < 0) {
3374 		btrfs_print_leaf(root, leaf);
3375 		BUG();
3376 	}
3377 }
3378 
3379 /*
3380  * make the item pointed to by the path bigger, data_size is the new size.
3381  */
btrfs_extend_item(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_path * path,u32 data_size)3382 void btrfs_extend_item(struct btrfs_trans_handle *trans,
3383 		       struct btrfs_root *root, struct btrfs_path *path,
3384 		       u32 data_size)
3385 {
3386 	int slot;
3387 	struct extent_buffer *leaf;
3388 	struct btrfs_item *item;
3389 	u32 nritems;
3390 	unsigned int data_end;
3391 	unsigned int old_data;
3392 	unsigned int old_size;
3393 	int i;
3394 	struct btrfs_map_token token;
3395 
3396 	btrfs_init_map_token(&token);
3397 
3398 	leaf = path->nodes[0];
3399 
3400 	nritems = btrfs_header_nritems(leaf);
3401 	data_end = leaf_data_end(root, leaf);
3402 
3403 	if (btrfs_leaf_free_space(root, leaf) < data_size) {
3404 		btrfs_print_leaf(root, leaf);
3405 		BUG();
3406 	}
3407 	slot = path->slots[0];
3408 	old_data = btrfs_item_end_nr(leaf, slot);
3409 
3410 	BUG_ON(slot < 0);
3411 	if (slot >= nritems) {
3412 		btrfs_print_leaf(root, leaf);
3413 		printk(KERN_CRIT "slot %d too large, nritems %d\n",
3414 		       slot, nritems);
3415 		BUG_ON(1);
3416 	}
3417 
3418 	/*
3419 	 * item0..itemN ... dataN.offset..dataN.size .. data0.size
3420 	 */
3421 	/* first correct the data pointers */
3422 	for (i = slot; i < nritems; i++) {
3423 		u32 ioff;
3424 		item = btrfs_item_nr(leaf, i);
3425 
3426 		ioff = btrfs_token_item_offset(leaf, item, &token);
3427 		btrfs_set_token_item_offset(leaf, item,
3428 					    ioff - data_size, &token);
3429 	}
3430 
3431 	/* shift the data */
3432 	memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
3433 		      data_end - data_size, btrfs_leaf_data(leaf) +
3434 		      data_end, old_data - data_end);
3435 
3436 	data_end = old_data;
3437 	old_size = btrfs_item_size_nr(leaf, slot);
3438 	item = btrfs_item_nr(leaf, slot);
3439 	btrfs_set_item_size(leaf, item, old_size + data_size);
3440 	btrfs_mark_buffer_dirty(leaf);
3441 
3442 	if (btrfs_leaf_free_space(root, leaf) < 0) {
3443 		btrfs_print_leaf(root, leaf);
3444 		BUG();
3445 	}
3446 }
3447 
3448 /*
3449  * Given a key and some data, insert items into the tree.
3450  * This does all the path init required, making room in the tree if needed.
3451  * Returns the number of keys that were inserted.
3452  */
btrfs_insert_some_items(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_path * path,struct btrfs_key * cpu_key,u32 * data_size,int nr)3453 int btrfs_insert_some_items(struct btrfs_trans_handle *trans,
3454 			    struct btrfs_root *root,
3455 			    struct btrfs_path *path,
3456 			    struct btrfs_key *cpu_key, u32 *data_size,
3457 			    int nr)
3458 {
3459 	struct extent_buffer *leaf;
3460 	struct btrfs_item *item;
3461 	int ret = 0;
3462 	int slot;
3463 	int i;
3464 	u32 nritems;
3465 	u32 total_data = 0;
3466 	u32 total_size = 0;
3467 	unsigned int data_end;
3468 	struct btrfs_disk_key disk_key;
3469 	struct btrfs_key found_key;
3470 	struct btrfs_map_token token;
3471 
3472 	btrfs_init_map_token(&token);
3473 
3474 	for (i = 0; i < nr; i++) {
3475 		if (total_size + data_size[i] + sizeof(struct btrfs_item) >
3476 		    BTRFS_LEAF_DATA_SIZE(root)) {
3477 			break;
3478 			nr = i;
3479 		}
3480 		total_data += data_size[i];
3481 		total_size += data_size[i] + sizeof(struct btrfs_item);
3482 	}
3483 	BUG_ON(nr == 0);
3484 
3485 	ret = btrfs_search_slot(trans, root, cpu_key, path, total_size, 1);
3486 	if (ret == 0)
3487 		return -EEXIST;
3488 	if (ret < 0)
3489 		goto out;
3490 
3491 	leaf = path->nodes[0];
3492 
3493 	nritems = btrfs_header_nritems(leaf);
3494 	data_end = leaf_data_end(root, leaf);
3495 
3496 	if (btrfs_leaf_free_space(root, leaf) < total_size) {
3497 		for (i = nr; i >= 0; i--) {
3498 			total_data -= data_size[i];
3499 			total_size -= data_size[i] + sizeof(struct btrfs_item);
3500 			if (total_size < btrfs_leaf_free_space(root, leaf))
3501 				break;
3502 		}
3503 		nr = i;
3504 	}
3505 
3506 	slot = path->slots[0];
3507 	BUG_ON(slot < 0);
3508 
3509 	if (slot != nritems) {
3510 		unsigned int old_data = btrfs_item_end_nr(leaf, slot);
3511 
3512 		item = btrfs_item_nr(leaf, slot);
3513 		btrfs_item_key_to_cpu(leaf, &found_key, slot);
3514 
3515 		/* figure out how many keys we can insert in here */
3516 		total_data = data_size[0];
3517 		for (i = 1; i < nr; i++) {
3518 			if (btrfs_comp_cpu_keys(&found_key, cpu_key + i) <= 0)
3519 				break;
3520 			total_data += data_size[i];
3521 		}
3522 		nr = i;
3523 
3524 		if (old_data < data_end) {
3525 			btrfs_print_leaf(root, leaf);
3526 			printk(KERN_CRIT "slot %d old_data %d data_end %d\n",
3527 			       slot, old_data, data_end);
3528 			BUG_ON(1);
3529 		}
3530 		/*
3531 		 * item0..itemN ... dataN.offset..dataN.size .. data0.size
3532 		 */
3533 		/* first correct the data pointers */
3534 		for (i = slot; i < nritems; i++) {
3535 			u32 ioff;
3536 
3537 			item = btrfs_item_nr(leaf, i);
3538 			ioff = btrfs_token_item_offset(leaf, item, &token);
3539 			btrfs_set_token_item_offset(leaf, item,
3540 						    ioff - total_data, &token);
3541 		}
3542 		/* shift the items */
3543 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + nr),
3544 			      btrfs_item_nr_offset(slot),
3545 			      (nritems - slot) * sizeof(struct btrfs_item));
3546 
3547 		/* shift the data */
3548 		memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
3549 			      data_end - total_data, btrfs_leaf_data(leaf) +
3550 			      data_end, old_data - data_end);
3551 		data_end = old_data;
3552 	} else {
3553 		/*
3554 		 * this sucks but it has to be done, if we are inserting at
3555 		 * the end of the leaf only insert 1 of the items, since we
3556 		 * have no way of knowing whats on the next leaf and we'd have
3557 		 * to drop our current locks to figure it out
3558 		 */
3559 		nr = 1;
3560 	}
3561 
3562 	/* setup the item for the new data */
3563 	for (i = 0; i < nr; i++) {
3564 		btrfs_cpu_key_to_disk(&disk_key, cpu_key + i);
3565 		btrfs_set_item_key(leaf, &disk_key, slot + i);
3566 		item = btrfs_item_nr(leaf, slot + i);
3567 		btrfs_set_token_item_offset(leaf, item,
3568 					    data_end - data_size[i], &token);
3569 		data_end -= data_size[i];
3570 		btrfs_set_token_item_size(leaf, item, data_size[i], &token);
3571 	}
3572 	btrfs_set_header_nritems(leaf, nritems + nr);
3573 	btrfs_mark_buffer_dirty(leaf);
3574 
3575 	ret = 0;
3576 	if (slot == 0) {
3577 		btrfs_cpu_key_to_disk(&disk_key, cpu_key);
3578 		fixup_low_keys(trans, root, path, &disk_key, 1);
3579 	}
3580 
3581 	if (btrfs_leaf_free_space(root, leaf) < 0) {
3582 		btrfs_print_leaf(root, leaf);
3583 		BUG();
3584 	}
3585 out:
3586 	if (!ret)
3587 		ret = nr;
3588 	return ret;
3589 }
3590 
3591 /*
3592  * this is a helper for btrfs_insert_empty_items, the main goal here is
3593  * to save stack depth by doing the bulk of the work in a function
3594  * that doesn't call btrfs_search_slot
3595  */
setup_items_for_insert(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_path * path,struct btrfs_key * cpu_key,u32 * data_size,u32 total_data,u32 total_size,int nr)3596 void setup_items_for_insert(struct btrfs_trans_handle *trans,
3597 			    struct btrfs_root *root, struct btrfs_path *path,
3598 			    struct btrfs_key *cpu_key, u32 *data_size,
3599 			    u32 total_data, u32 total_size, int nr)
3600 {
3601 	struct btrfs_item *item;
3602 	int i;
3603 	u32 nritems;
3604 	unsigned int data_end;
3605 	struct btrfs_disk_key disk_key;
3606 	struct extent_buffer *leaf;
3607 	int slot;
3608 	struct btrfs_map_token token;
3609 
3610 	btrfs_init_map_token(&token);
3611 
3612 	leaf = path->nodes[0];
3613 	slot = path->slots[0];
3614 
3615 	nritems = btrfs_header_nritems(leaf);
3616 	data_end = leaf_data_end(root, leaf);
3617 
3618 	if (btrfs_leaf_free_space(root, leaf) < total_size) {
3619 		btrfs_print_leaf(root, leaf);
3620 		printk(KERN_CRIT "not enough freespace need %u have %d\n",
3621 		       total_size, btrfs_leaf_free_space(root, leaf));
3622 		BUG();
3623 	}
3624 
3625 	if (slot != nritems) {
3626 		unsigned int old_data = btrfs_item_end_nr(leaf, slot);
3627 
3628 		if (old_data < data_end) {
3629 			btrfs_print_leaf(root, leaf);
3630 			printk(KERN_CRIT "slot %d old_data %d data_end %d\n",
3631 			       slot, old_data, data_end);
3632 			BUG_ON(1);
3633 		}
3634 		/*
3635 		 * item0..itemN ... dataN.offset..dataN.size .. data0.size
3636 		 */
3637 		/* first correct the data pointers */
3638 		for (i = slot; i < nritems; i++) {
3639 			u32 ioff;
3640 
3641 			item = btrfs_item_nr(leaf, i);
3642 			ioff = btrfs_token_item_offset(leaf, item, &token);
3643 			btrfs_set_token_item_offset(leaf, item,
3644 						    ioff - total_data, &token);
3645 		}
3646 		/* shift the items */
3647 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + nr),
3648 			      btrfs_item_nr_offset(slot),
3649 			      (nritems - slot) * sizeof(struct btrfs_item));
3650 
3651 		/* shift the data */
3652 		memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
3653 			      data_end - total_data, btrfs_leaf_data(leaf) +
3654 			      data_end, old_data - data_end);
3655 		data_end = old_data;
3656 	}
3657 
3658 	/* setup the item for the new data */
3659 	for (i = 0; i < nr; i++) {
3660 		btrfs_cpu_key_to_disk(&disk_key, cpu_key + i);
3661 		btrfs_set_item_key(leaf, &disk_key, slot + i);
3662 		item = btrfs_item_nr(leaf, slot + i);
3663 		btrfs_set_token_item_offset(leaf, item,
3664 					    data_end - data_size[i], &token);
3665 		data_end -= data_size[i];
3666 		btrfs_set_token_item_size(leaf, item, data_size[i], &token);
3667 	}
3668 
3669 	btrfs_set_header_nritems(leaf, nritems + nr);
3670 
3671 	if (slot == 0) {
3672 		btrfs_cpu_key_to_disk(&disk_key, cpu_key);
3673 		fixup_low_keys(trans, root, path, &disk_key, 1);
3674 	}
3675 	btrfs_unlock_up_safe(path, 1);
3676 	btrfs_mark_buffer_dirty(leaf);
3677 
3678 	if (btrfs_leaf_free_space(root, leaf) < 0) {
3679 		btrfs_print_leaf(root, leaf);
3680 		BUG();
3681 	}
3682 }
3683 
3684 /*
3685  * Given a key and some data, insert items into the tree.
3686  * This does all the path init required, making room in the tree if needed.
3687  */
btrfs_insert_empty_items(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_path * path,struct btrfs_key * cpu_key,u32 * data_size,int nr)3688 int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
3689 			    struct btrfs_root *root,
3690 			    struct btrfs_path *path,
3691 			    struct btrfs_key *cpu_key, u32 *data_size,
3692 			    int nr)
3693 {
3694 	int ret = 0;
3695 	int slot;
3696 	int i;
3697 	u32 total_size = 0;
3698 	u32 total_data = 0;
3699 
3700 	for (i = 0; i < nr; i++)
3701 		total_data += data_size[i];
3702 
3703 	total_size = total_data + (nr * sizeof(struct btrfs_item));
3704 	ret = btrfs_search_slot(trans, root, cpu_key, path, total_size, 1);
3705 	if (ret == 0)
3706 		return -EEXIST;
3707 	if (ret < 0)
3708 		return ret;
3709 
3710 	slot = path->slots[0];
3711 	BUG_ON(slot < 0);
3712 
3713 	setup_items_for_insert(trans, root, path, cpu_key, data_size,
3714 			       total_data, total_size, nr);
3715 	return 0;
3716 }
3717 
3718 /*
3719  * Given a key and some data, insert an item into the tree.
3720  * This does all the path init required, making room in the tree if needed.
3721  */
btrfs_insert_item(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_key * cpu_key,void * data,u32 data_size)3722 int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root
3723 		      *root, struct btrfs_key *cpu_key, void *data, u32
3724 		      data_size)
3725 {
3726 	int ret = 0;
3727 	struct btrfs_path *path;
3728 	struct extent_buffer *leaf;
3729 	unsigned long ptr;
3730 
3731 	path = btrfs_alloc_path();
3732 	if (!path)
3733 		return -ENOMEM;
3734 	ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
3735 	if (!ret) {
3736 		leaf = path->nodes[0];
3737 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3738 		write_extent_buffer(leaf, data, ptr, data_size);
3739 		btrfs_mark_buffer_dirty(leaf);
3740 	}
3741 	btrfs_free_path(path);
3742 	return ret;
3743 }
3744 
3745 /*
3746  * delete the pointer from a given node.
3747  *
3748  * the tree should have been previously balanced so the deletion does not
3749  * empty a node.
3750  */
del_ptr(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_path * path,int level,int slot)3751 static void del_ptr(struct btrfs_trans_handle *trans, struct btrfs_root *root,
3752 		    struct btrfs_path *path, int level, int slot)
3753 {
3754 	struct extent_buffer *parent = path->nodes[level];
3755 	u32 nritems;
3756 
3757 	nritems = btrfs_header_nritems(parent);
3758 	if (slot != nritems - 1) {
3759 		memmove_extent_buffer(parent,
3760 			      btrfs_node_key_ptr_offset(slot),
3761 			      btrfs_node_key_ptr_offset(slot + 1),
3762 			      sizeof(struct btrfs_key_ptr) *
3763 			      (nritems - slot - 1));
3764 	}
3765 	nritems--;
3766 	btrfs_set_header_nritems(parent, nritems);
3767 	if (nritems == 0 && parent == root->node) {
3768 		BUG_ON(btrfs_header_level(root->node) != 1);
3769 		/* just turn the root into a leaf and break */
3770 		btrfs_set_header_level(root->node, 0);
3771 	} else if (slot == 0) {
3772 		struct btrfs_disk_key disk_key;
3773 
3774 		btrfs_node_key(parent, &disk_key, 0);
3775 		fixup_low_keys(trans, root, path, &disk_key, level + 1);
3776 	}
3777 	btrfs_mark_buffer_dirty(parent);
3778 }
3779 
3780 /*
3781  * a helper function to delete the leaf pointed to by path->slots[1] and
3782  * path->nodes[1].
3783  *
3784  * This deletes the pointer in path->nodes[1] and frees the leaf
3785  * block extent.  zero is returned if it all worked out, < 0 otherwise.
3786  *
3787  * The path must have already been setup for deleting the leaf, including
3788  * all the proper balancing.  path->nodes[1] must be locked.
3789  */
btrfs_del_leaf(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_path * path,struct extent_buffer * leaf)3790 static noinline void btrfs_del_leaf(struct btrfs_trans_handle *trans,
3791 				    struct btrfs_root *root,
3792 				    struct btrfs_path *path,
3793 				    struct extent_buffer *leaf)
3794 {
3795 	WARN_ON(btrfs_header_generation(leaf) != trans->transid);
3796 	del_ptr(trans, root, path, 1, path->slots[1]);
3797 
3798 	/*
3799 	 * btrfs_free_extent is expensive, we want to make sure we
3800 	 * aren't holding any locks when we call it
3801 	 */
3802 	btrfs_unlock_up_safe(path, 0);
3803 
3804 	root_sub_used(root, leaf->len);
3805 
3806 	extent_buffer_get(leaf);
3807 	btrfs_free_tree_block(trans, root, leaf, 0, 1, 0);
3808 	free_extent_buffer_stale(leaf);
3809 }
3810 /*
3811  * delete the item at the leaf level in path.  If that empties
3812  * the leaf, remove it from the tree
3813  */
btrfs_del_items(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_path * path,int slot,int nr)3814 int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
3815 		    struct btrfs_path *path, int slot, int nr)
3816 {
3817 	struct extent_buffer *leaf;
3818 	struct btrfs_item *item;
3819 	int last_off;
3820 	int dsize = 0;
3821 	int ret = 0;
3822 	int wret;
3823 	int i;
3824 	u32 nritems;
3825 	struct btrfs_map_token token;
3826 
3827 	btrfs_init_map_token(&token);
3828 
3829 	leaf = path->nodes[0];
3830 	last_off = btrfs_item_offset_nr(leaf, slot + nr - 1);
3831 
3832 	for (i = 0; i < nr; i++)
3833 		dsize += btrfs_item_size_nr(leaf, slot + i);
3834 
3835 	nritems = btrfs_header_nritems(leaf);
3836 
3837 	if (slot + nr != nritems) {
3838 		int data_end = leaf_data_end(root, leaf);
3839 
3840 		memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
3841 			      data_end + dsize,
3842 			      btrfs_leaf_data(leaf) + data_end,
3843 			      last_off - data_end);
3844 
3845 		for (i = slot + nr; i < nritems; i++) {
3846 			u32 ioff;
3847 
3848 			item = btrfs_item_nr(leaf, i);
3849 			ioff = btrfs_token_item_offset(leaf, item, &token);
3850 			btrfs_set_token_item_offset(leaf, item,
3851 						    ioff + dsize, &token);
3852 		}
3853 
3854 		memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot),
3855 			      btrfs_item_nr_offset(slot + nr),
3856 			      sizeof(struct btrfs_item) *
3857 			      (nritems - slot - nr));
3858 	}
3859 	btrfs_set_header_nritems(leaf, nritems - nr);
3860 	nritems -= nr;
3861 
3862 	/* delete the leaf if we've emptied it */
3863 	if (nritems == 0) {
3864 		if (leaf == root->node) {
3865 			btrfs_set_header_level(leaf, 0);
3866 		} else {
3867 			btrfs_set_path_blocking(path);
3868 			clean_tree_block(trans, root, leaf);
3869 			btrfs_del_leaf(trans, root, path, leaf);
3870 		}
3871 	} else {
3872 		int used = leaf_space_used(leaf, 0, nritems);
3873 		if (slot == 0) {
3874 			struct btrfs_disk_key disk_key;
3875 
3876 			btrfs_item_key(leaf, &disk_key, 0);
3877 			fixup_low_keys(trans, root, path, &disk_key, 1);
3878 		}
3879 
3880 		/* delete the leaf if it is mostly empty */
3881 		if (used < BTRFS_LEAF_DATA_SIZE(root) / 3) {
3882 			/* push_leaf_left fixes the path.
3883 			 * make sure the path still points to our leaf
3884 			 * for possible call to del_ptr below
3885 			 */
3886 			slot = path->slots[1];
3887 			extent_buffer_get(leaf);
3888 
3889 			btrfs_set_path_blocking(path);
3890 			wret = push_leaf_left(trans, root, path, 1, 1,
3891 					      1, (u32)-1);
3892 			if (wret < 0 && wret != -ENOSPC)
3893 				ret = wret;
3894 
3895 			if (path->nodes[0] == leaf &&
3896 			    btrfs_header_nritems(leaf)) {
3897 				wret = push_leaf_right(trans, root, path, 1,
3898 						       1, 1, 0);
3899 				if (wret < 0 && wret != -ENOSPC)
3900 					ret = wret;
3901 			}
3902 
3903 			if (btrfs_header_nritems(leaf) == 0) {
3904 				path->slots[1] = slot;
3905 				btrfs_del_leaf(trans, root, path, leaf);
3906 				free_extent_buffer(leaf);
3907 				ret = 0;
3908 			} else {
3909 				/* if we're still in the path, make sure
3910 				 * we're dirty.  Otherwise, one of the
3911 				 * push_leaf functions must have already
3912 				 * dirtied this buffer
3913 				 */
3914 				if (path->nodes[0] == leaf)
3915 					btrfs_mark_buffer_dirty(leaf);
3916 				free_extent_buffer(leaf);
3917 			}
3918 		} else {
3919 			btrfs_mark_buffer_dirty(leaf);
3920 		}
3921 	}
3922 	return ret;
3923 }
3924 
3925 /*
3926  * search the tree again to find a leaf with lesser keys
3927  * returns 0 if it found something or 1 if there are no lesser leaves.
3928  * returns < 0 on io errors.
3929  *
3930  * This may release the path, and so you may lose any locks held at the
3931  * time you call it.
3932  */
btrfs_prev_leaf(struct btrfs_root * root,struct btrfs_path * path)3933 int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
3934 {
3935 	struct btrfs_key key;
3936 	struct btrfs_disk_key found_key;
3937 	int ret;
3938 
3939 	btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
3940 
3941 	if (key.offset > 0)
3942 		key.offset--;
3943 	else if (key.type > 0)
3944 		key.type--;
3945 	else if (key.objectid > 0)
3946 		key.objectid--;
3947 	else
3948 		return 1;
3949 
3950 	btrfs_release_path(path);
3951 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3952 	if (ret < 0)
3953 		return ret;
3954 	btrfs_item_key(path->nodes[0], &found_key, 0);
3955 	ret = comp_keys(&found_key, &key);
3956 	if (ret < 0)
3957 		return 0;
3958 	return 1;
3959 }
3960 
3961 /*
3962  * A helper function to walk down the tree starting at min_key, and looking
3963  * for nodes or leaves that are either in cache or have a minimum
3964  * transaction id.  This is used by the btree defrag code, and tree logging
3965  *
3966  * This does not cow, but it does stuff the starting key it finds back
3967  * into min_key, so you can call btrfs_search_slot with cow=1 on the
3968  * key and get a writable path.
3969  *
3970  * This does lock as it descends, and path->keep_locks should be set
3971  * to 1 by the caller.
3972  *
3973  * This honors path->lowest_level to prevent descent past a given level
3974  * of the tree.
3975  *
3976  * min_trans indicates the oldest transaction that you are interested
3977  * in walking through.  Any nodes or leaves older than min_trans are
3978  * skipped over (without reading them).
3979  *
3980  * returns zero if something useful was found, < 0 on error and 1 if there
3981  * was nothing in the tree that matched the search criteria.
3982  */
btrfs_search_forward(struct btrfs_root * root,struct btrfs_key * min_key,struct btrfs_key * max_key,struct btrfs_path * path,int cache_only,u64 min_trans)3983 int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
3984 			 struct btrfs_key *max_key,
3985 			 struct btrfs_path *path, int cache_only,
3986 			 u64 min_trans)
3987 {
3988 	struct extent_buffer *cur;
3989 	struct btrfs_key found_key;
3990 	int slot;
3991 	int sret;
3992 	u32 nritems;
3993 	int level;
3994 	int ret = 1;
3995 
3996 	WARN_ON(!path->keep_locks);
3997 again:
3998 	cur = btrfs_read_lock_root_node(root);
3999 	level = btrfs_header_level(cur);
4000 	WARN_ON(path->nodes[level]);
4001 	path->nodes[level] = cur;
4002 	path->locks[level] = BTRFS_READ_LOCK;
4003 
4004 	if (btrfs_header_generation(cur) < min_trans) {
4005 		ret = 1;
4006 		goto out;
4007 	}
4008 	while (1) {
4009 		nritems = btrfs_header_nritems(cur);
4010 		level = btrfs_header_level(cur);
4011 		sret = bin_search(cur, min_key, level, &slot);
4012 
4013 		/* at the lowest level, we're done, setup the path and exit */
4014 		if (level == path->lowest_level) {
4015 			if (slot >= nritems)
4016 				goto find_next_key;
4017 			ret = 0;
4018 			path->slots[level] = slot;
4019 			btrfs_item_key_to_cpu(cur, &found_key, slot);
4020 			goto out;
4021 		}
4022 		if (sret && slot > 0)
4023 			slot--;
4024 		/*
4025 		 * check this node pointer against the cache_only and
4026 		 * min_trans parameters.  If it isn't in cache or is too
4027 		 * old, skip to the next one.
4028 		 */
4029 		while (slot < nritems) {
4030 			u64 blockptr;
4031 			u64 gen;
4032 			struct extent_buffer *tmp;
4033 			struct btrfs_disk_key disk_key;
4034 
4035 			blockptr = btrfs_node_blockptr(cur, slot);
4036 			gen = btrfs_node_ptr_generation(cur, slot);
4037 			if (gen < min_trans) {
4038 				slot++;
4039 				continue;
4040 			}
4041 			if (!cache_only)
4042 				break;
4043 
4044 			if (max_key) {
4045 				btrfs_node_key(cur, &disk_key, slot);
4046 				if (comp_keys(&disk_key, max_key) >= 0) {
4047 					ret = 1;
4048 					goto out;
4049 				}
4050 			}
4051 
4052 			tmp = btrfs_find_tree_block(root, blockptr,
4053 					    btrfs_level_size(root, level - 1));
4054 
4055 			if (tmp && btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
4056 				free_extent_buffer(tmp);
4057 				break;
4058 			}
4059 			if (tmp)
4060 				free_extent_buffer(tmp);
4061 			slot++;
4062 		}
4063 find_next_key:
4064 		/*
4065 		 * we didn't find a candidate key in this node, walk forward
4066 		 * and find another one
4067 		 */
4068 		if (slot >= nritems) {
4069 			path->slots[level] = slot;
4070 			btrfs_set_path_blocking(path);
4071 			sret = btrfs_find_next_key(root, path, min_key, level,
4072 						  cache_only, min_trans);
4073 			if (sret == 0) {
4074 				btrfs_release_path(path);
4075 				goto again;
4076 			} else {
4077 				goto out;
4078 			}
4079 		}
4080 		/* save our key for returning back */
4081 		btrfs_node_key_to_cpu(cur, &found_key, slot);
4082 		path->slots[level] = slot;
4083 		if (level == path->lowest_level) {
4084 			ret = 0;
4085 			unlock_up(path, level, 1, 0, NULL);
4086 			goto out;
4087 		}
4088 		btrfs_set_path_blocking(path);
4089 		cur = read_node_slot(root, cur, slot);
4090 		BUG_ON(!cur); /* -ENOMEM */
4091 
4092 		btrfs_tree_read_lock(cur);
4093 
4094 		path->locks[level - 1] = BTRFS_READ_LOCK;
4095 		path->nodes[level - 1] = cur;
4096 		unlock_up(path, level, 1, 0, NULL);
4097 		btrfs_clear_path_blocking(path, NULL, 0);
4098 	}
4099 out:
4100 	if (ret == 0)
4101 		memcpy(min_key, &found_key, sizeof(found_key));
4102 	btrfs_set_path_blocking(path);
4103 	return ret;
4104 }
4105 
4106 /*
4107  * this is similar to btrfs_next_leaf, but does not try to preserve
4108  * and fixup the path.  It looks for and returns the next key in the
4109  * tree based on the current path and the cache_only and min_trans
4110  * parameters.
4111  *
4112  * 0 is returned if another key is found, < 0 if there are any errors
4113  * and 1 is returned if there are no higher keys in the tree
4114  *
4115  * path->keep_locks should be set to 1 on the search made before
4116  * calling this function.
4117  */
btrfs_find_next_key(struct btrfs_root * root,struct btrfs_path * path,struct btrfs_key * key,int level,int cache_only,u64 min_trans)4118 int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
4119 			struct btrfs_key *key, int level,
4120 			int cache_only, u64 min_trans)
4121 {
4122 	int slot;
4123 	struct extent_buffer *c;
4124 
4125 	WARN_ON(!path->keep_locks);
4126 	while (level < BTRFS_MAX_LEVEL) {
4127 		if (!path->nodes[level])
4128 			return 1;
4129 
4130 		slot = path->slots[level] + 1;
4131 		c = path->nodes[level];
4132 next:
4133 		if (slot >= btrfs_header_nritems(c)) {
4134 			int ret;
4135 			int orig_lowest;
4136 			struct btrfs_key cur_key;
4137 			if (level + 1 >= BTRFS_MAX_LEVEL ||
4138 			    !path->nodes[level + 1])
4139 				return 1;
4140 
4141 			if (path->locks[level + 1]) {
4142 				level++;
4143 				continue;
4144 			}
4145 
4146 			slot = btrfs_header_nritems(c) - 1;
4147 			if (level == 0)
4148 				btrfs_item_key_to_cpu(c, &cur_key, slot);
4149 			else
4150 				btrfs_node_key_to_cpu(c, &cur_key, slot);
4151 
4152 			orig_lowest = path->lowest_level;
4153 			btrfs_release_path(path);
4154 			path->lowest_level = level;
4155 			ret = btrfs_search_slot(NULL, root, &cur_key, path,
4156 						0, 0);
4157 			path->lowest_level = orig_lowest;
4158 			if (ret < 0)
4159 				return ret;
4160 
4161 			c = path->nodes[level];
4162 			slot = path->slots[level];
4163 			if (ret == 0)
4164 				slot++;
4165 			goto next;
4166 		}
4167 
4168 		if (level == 0)
4169 			btrfs_item_key_to_cpu(c, key, slot);
4170 		else {
4171 			u64 blockptr = btrfs_node_blockptr(c, slot);
4172 			u64 gen = btrfs_node_ptr_generation(c, slot);
4173 
4174 			if (cache_only) {
4175 				struct extent_buffer *cur;
4176 				cur = btrfs_find_tree_block(root, blockptr,
4177 					    btrfs_level_size(root, level - 1));
4178 				if (!cur ||
4179 				    btrfs_buffer_uptodate(cur, gen, 1) <= 0) {
4180 					slot++;
4181 					if (cur)
4182 						free_extent_buffer(cur);
4183 					goto next;
4184 				}
4185 				free_extent_buffer(cur);
4186 			}
4187 			if (gen < min_trans) {
4188 				slot++;
4189 				goto next;
4190 			}
4191 			btrfs_node_key_to_cpu(c, key, slot);
4192 		}
4193 		return 0;
4194 	}
4195 	return 1;
4196 }
4197 
4198 /*
4199  * search the tree again to find a leaf with greater keys
4200  * returns 0 if it found something or 1 if there are no greater leaves.
4201  * returns < 0 on io errors.
4202  */
btrfs_next_leaf(struct btrfs_root * root,struct btrfs_path * path)4203 int btrfs_next_leaf(struct btrfs_root *root, struct btrfs_path *path)
4204 {
4205 	int slot;
4206 	int level;
4207 	struct extent_buffer *c;
4208 	struct extent_buffer *next;
4209 	struct btrfs_key key;
4210 	u32 nritems;
4211 	int ret;
4212 	int old_spinning = path->leave_spinning;
4213 	int next_rw_lock = 0;
4214 
4215 	nritems = btrfs_header_nritems(path->nodes[0]);
4216 	if (nritems == 0)
4217 		return 1;
4218 
4219 	btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
4220 again:
4221 	level = 1;
4222 	next = NULL;
4223 	next_rw_lock = 0;
4224 	btrfs_release_path(path);
4225 
4226 	path->keep_locks = 1;
4227 	path->leave_spinning = 1;
4228 
4229 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4230 	path->keep_locks = 0;
4231 
4232 	if (ret < 0)
4233 		return ret;
4234 
4235 	nritems = btrfs_header_nritems(path->nodes[0]);
4236 	/*
4237 	 * by releasing the path above we dropped all our locks.  A balance
4238 	 * could have added more items next to the key that used to be
4239 	 * at the very end of the block.  So, check again here and
4240 	 * advance the path if there are now more items available.
4241 	 */
4242 	if (nritems > 0 && path->slots[0] < nritems - 1) {
4243 		if (ret == 0)
4244 			path->slots[0]++;
4245 		ret = 0;
4246 		goto done;
4247 	}
4248 
4249 	while (level < BTRFS_MAX_LEVEL) {
4250 		if (!path->nodes[level]) {
4251 			ret = 1;
4252 			goto done;
4253 		}
4254 
4255 		slot = path->slots[level] + 1;
4256 		c = path->nodes[level];
4257 		if (slot >= btrfs_header_nritems(c)) {
4258 			level++;
4259 			if (level == BTRFS_MAX_LEVEL) {
4260 				ret = 1;
4261 				goto done;
4262 			}
4263 			continue;
4264 		}
4265 
4266 		if (next) {
4267 			btrfs_tree_unlock_rw(next, next_rw_lock);
4268 			free_extent_buffer(next);
4269 		}
4270 
4271 		next = c;
4272 		next_rw_lock = path->locks[level];
4273 		ret = read_block_for_search(NULL, root, path, &next, level,
4274 					    slot, &key);
4275 		if (ret == -EAGAIN)
4276 			goto again;
4277 
4278 		if (ret < 0) {
4279 			btrfs_release_path(path);
4280 			goto done;
4281 		}
4282 
4283 		if (!path->skip_locking) {
4284 			ret = btrfs_try_tree_read_lock(next);
4285 			if (!ret) {
4286 				btrfs_set_path_blocking(path);
4287 				btrfs_tree_read_lock(next);
4288 				btrfs_clear_path_blocking(path, next,
4289 							  BTRFS_READ_LOCK);
4290 			}
4291 			next_rw_lock = BTRFS_READ_LOCK;
4292 		}
4293 		break;
4294 	}
4295 	path->slots[level] = slot;
4296 	while (1) {
4297 		level--;
4298 		c = path->nodes[level];
4299 		if (path->locks[level])
4300 			btrfs_tree_unlock_rw(c, path->locks[level]);
4301 
4302 		free_extent_buffer(c);
4303 		path->nodes[level] = next;
4304 		path->slots[level] = 0;
4305 		if (!path->skip_locking)
4306 			path->locks[level] = next_rw_lock;
4307 		if (!level)
4308 			break;
4309 
4310 		ret = read_block_for_search(NULL, root, path, &next, level,
4311 					    0, &key);
4312 		if (ret == -EAGAIN)
4313 			goto again;
4314 
4315 		if (ret < 0) {
4316 			btrfs_release_path(path);
4317 			goto done;
4318 		}
4319 
4320 		if (!path->skip_locking) {
4321 			ret = btrfs_try_tree_read_lock(next);
4322 			if (!ret) {
4323 				btrfs_set_path_blocking(path);
4324 				btrfs_tree_read_lock(next);
4325 				btrfs_clear_path_blocking(path, next,
4326 							  BTRFS_READ_LOCK);
4327 			}
4328 			next_rw_lock = BTRFS_READ_LOCK;
4329 		}
4330 	}
4331 	ret = 0;
4332 done:
4333 	unlock_up(path, 0, 1, 0, NULL);
4334 	path->leave_spinning = old_spinning;
4335 	if (!old_spinning)
4336 		btrfs_set_path_blocking(path);
4337 
4338 	return ret;
4339 }
4340 
4341 /*
4342  * this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
4343  * searching until it gets past min_objectid or finds an item of 'type'
4344  *
4345  * returns 0 if something is found, 1 if nothing was found and < 0 on error
4346  */
btrfs_previous_item(struct btrfs_root * root,struct btrfs_path * path,u64 min_objectid,int type)4347 int btrfs_previous_item(struct btrfs_root *root,
4348 			struct btrfs_path *path, u64 min_objectid,
4349 			int type)
4350 {
4351 	struct btrfs_key found_key;
4352 	struct extent_buffer *leaf;
4353 	u32 nritems;
4354 	int ret;
4355 
4356 	while (1) {
4357 		if (path->slots[0] == 0) {
4358 			btrfs_set_path_blocking(path);
4359 			ret = btrfs_prev_leaf(root, path);
4360 			if (ret != 0)
4361 				return ret;
4362 		} else {
4363 			path->slots[0]--;
4364 		}
4365 		leaf = path->nodes[0];
4366 		nritems = btrfs_header_nritems(leaf);
4367 		if (nritems == 0)
4368 			return 1;
4369 		if (path->slots[0] == nritems)
4370 			path->slots[0]--;
4371 
4372 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4373 		if (found_key.objectid < min_objectid)
4374 			break;
4375 		if (found_key.type == type)
4376 			return 0;
4377 		if (found_key.objectid == min_objectid &&
4378 		    found_key.type < type)
4379 			break;
4380 	}
4381 	return 1;
4382 }
4383