Btrfs: tree mod log's old roots could still be part of the tree
[linux-block.git] / fs / btrfs / ctree.c
CommitLineData
6cbd5570 1/*
d352ac68 2 * Copyright (C) 2007,2008 Oracle. All rights reserved.
6cbd5570
CM
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
a6b6e75e 19#include <linux/sched.h>
5a0e3ad6 20#include <linux/slab.h>
bd989ba3 21#include <linux/rbtree.h>
eb60ceac
CM
22#include "ctree.h"
23#include "disk-io.h"
7f5c1516 24#include "transaction.h"
5f39d397 25#include "print-tree.h"
925baedd 26#include "locking.h"
9a8dd150 27
e089f05c
CM
28static int split_node(struct btrfs_trans_handle *trans, struct btrfs_root
29 *root, struct btrfs_path *path, int level);
30static int split_leaf(struct btrfs_trans_handle *trans, struct btrfs_root
d4dbff95 31 *root, struct btrfs_key *ins_key,
cc0c5538 32 struct btrfs_path *path, int data_size, int extend);
5f39d397
CM
33static int push_node_left(struct btrfs_trans_handle *trans,
34 struct btrfs_root *root, struct extent_buffer *dst,
971a1f66 35 struct extent_buffer *src, int empty);
5f39d397
CM
36static int balance_node_right(struct btrfs_trans_handle *trans,
37 struct btrfs_root *root,
38 struct extent_buffer *dst_buf,
39 struct extent_buffer *src_buf);
143bede5 40static void del_ptr(struct btrfs_trans_handle *trans, struct btrfs_root *root,
f3ea38da
JS
41 struct btrfs_path *path, int level, int slot,
42 int tree_mod_log);
f230475e
JS
43static void tree_mod_log_free_eb(struct btrfs_fs_info *fs_info,
44 struct extent_buffer *eb);
45struct extent_buffer *read_old_tree_block(struct btrfs_root *root, u64 bytenr,
46 u32 blocksize, u64 parent_transid,
47 u64 time_seq);
48struct extent_buffer *btrfs_find_old_tree_block(struct btrfs_root *root,
49 u64 bytenr, u32 blocksize,
50 u64 time_seq);
d97e63b6 51
df24a2b9 52struct btrfs_path *btrfs_alloc_path(void)
2c90e5d6 53{
df24a2b9 54 struct btrfs_path *path;
e00f7308 55 path = kmem_cache_zalloc(btrfs_path_cachep, GFP_NOFS);
df24a2b9 56 return path;
2c90e5d6
CM
57}
58
b4ce94de
CM
59/*
60 * set all locked nodes in the path to blocking locks. This should
61 * be done before scheduling
62 */
63noinline void btrfs_set_path_blocking(struct btrfs_path *p)
64{
65 int i;
66 for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
bd681513
CM
67 if (!p->nodes[i] || !p->locks[i])
68 continue;
69 btrfs_set_lock_blocking_rw(p->nodes[i], p->locks[i]);
70 if (p->locks[i] == BTRFS_READ_LOCK)
71 p->locks[i] = BTRFS_READ_LOCK_BLOCKING;
72 else if (p->locks[i] == BTRFS_WRITE_LOCK)
73 p->locks[i] = BTRFS_WRITE_LOCK_BLOCKING;
b4ce94de
CM
74 }
75}
76
77/*
78 * reset all the locked nodes in the patch to spinning locks.
4008c04a
CM
79 *
80 * held is used to keep lockdep happy, when lockdep is enabled
81 * we set held to a blocking lock before we go around and
82 * retake all the spinlocks in the path. You can safely use NULL
83 * for held
b4ce94de 84 */
4008c04a 85noinline void btrfs_clear_path_blocking(struct btrfs_path *p,
bd681513 86 struct extent_buffer *held, int held_rw)
b4ce94de
CM
87{
88 int i;
4008c04a
CM
89
90#ifdef CONFIG_DEBUG_LOCK_ALLOC
91 /* lockdep really cares that we take all of these spinlocks
92 * in the right order. If any of the locks in the path are not
93 * currently blocking, it is going to complain. So, make really
94 * really sure by forcing the path to blocking before we clear
95 * the path blocking.
96 */
bd681513
CM
97 if (held) {
98 btrfs_set_lock_blocking_rw(held, held_rw);
99 if (held_rw == BTRFS_WRITE_LOCK)
100 held_rw = BTRFS_WRITE_LOCK_BLOCKING;
101 else if (held_rw == BTRFS_READ_LOCK)
102 held_rw = BTRFS_READ_LOCK_BLOCKING;
103 }
4008c04a
CM
104 btrfs_set_path_blocking(p);
105#endif
106
107 for (i = BTRFS_MAX_LEVEL - 1; i >= 0; i--) {
bd681513
CM
108 if (p->nodes[i] && p->locks[i]) {
109 btrfs_clear_lock_blocking_rw(p->nodes[i], p->locks[i]);
110 if (p->locks[i] == BTRFS_WRITE_LOCK_BLOCKING)
111 p->locks[i] = BTRFS_WRITE_LOCK;
112 else if (p->locks[i] == BTRFS_READ_LOCK_BLOCKING)
113 p->locks[i] = BTRFS_READ_LOCK;
114 }
b4ce94de 115 }
4008c04a
CM
116
117#ifdef CONFIG_DEBUG_LOCK_ALLOC
118 if (held)
bd681513 119 btrfs_clear_lock_blocking_rw(held, held_rw);
4008c04a 120#endif
b4ce94de
CM
121}
122
d352ac68 123/* this also releases the path */
df24a2b9 124void btrfs_free_path(struct btrfs_path *p)
be0e5c09 125{
ff175d57
JJ
126 if (!p)
127 return;
b3b4aa74 128 btrfs_release_path(p);
df24a2b9 129 kmem_cache_free(btrfs_path_cachep, p);
be0e5c09
CM
130}
131
d352ac68
CM
132/*
133 * path release drops references on the extent buffers in the path
134 * and it drops any locks held by this path
135 *
136 * It is safe to call this on paths that no locks or extent buffers held.
137 */
b3b4aa74 138noinline void btrfs_release_path(struct btrfs_path *p)
eb60ceac
CM
139{
140 int i;
a2135011 141
234b63a0 142 for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
3f157a2f 143 p->slots[i] = 0;
eb60ceac 144 if (!p->nodes[i])
925baedd
CM
145 continue;
146 if (p->locks[i]) {
bd681513 147 btrfs_tree_unlock_rw(p->nodes[i], p->locks[i]);
925baedd
CM
148 p->locks[i] = 0;
149 }
5f39d397 150 free_extent_buffer(p->nodes[i]);
3f157a2f 151 p->nodes[i] = NULL;
eb60ceac
CM
152 }
153}
154
d352ac68
CM
155/*
156 * safely gets a reference on the root node of a tree. A lock
157 * is not taken, so a concurrent writer may put a different node
158 * at the root of the tree. See btrfs_lock_root_node for the
159 * looping required.
160 *
161 * The extent buffer returned by this has a reference taken, so
162 * it won't disappear. It may stop being the root of the tree
163 * at any time because there are no locks held.
164 */
925baedd
CM
165struct extent_buffer *btrfs_root_node(struct btrfs_root *root)
166{
167 struct extent_buffer *eb;
240f62c8 168
3083ee2e
JB
169 while (1) {
170 rcu_read_lock();
171 eb = rcu_dereference(root->node);
172
173 /*
174 * RCU really hurts here, we could free up the root node because
175 * it was cow'ed but we may not get the new root node yet so do
176 * the inc_not_zero dance and if it doesn't work then
177 * synchronize_rcu and try again.
178 */
179 if (atomic_inc_not_zero(&eb->refs)) {
180 rcu_read_unlock();
181 break;
182 }
183 rcu_read_unlock();
184 synchronize_rcu();
185 }
925baedd
CM
186 return eb;
187}
188
d352ac68
CM
189/* loop around taking references on and locking the root node of the
190 * tree until you end up with a lock on the root. A locked buffer
191 * is returned, with a reference held.
192 */
925baedd
CM
193struct extent_buffer *btrfs_lock_root_node(struct btrfs_root *root)
194{
195 struct extent_buffer *eb;
196
d397712b 197 while (1) {
925baedd
CM
198 eb = btrfs_root_node(root);
199 btrfs_tree_lock(eb);
240f62c8 200 if (eb == root->node)
925baedd 201 break;
925baedd
CM
202 btrfs_tree_unlock(eb);
203 free_extent_buffer(eb);
204 }
205 return eb;
206}
207
bd681513
CM
208/* loop around taking references on and locking the root node of the
209 * tree until you end up with a lock on the root. A locked buffer
210 * is returned, with a reference held.
211 */
212struct extent_buffer *btrfs_read_lock_root_node(struct btrfs_root *root)
213{
214 struct extent_buffer *eb;
215
216 while (1) {
217 eb = btrfs_root_node(root);
218 btrfs_tree_read_lock(eb);
219 if (eb == root->node)
220 break;
221 btrfs_tree_read_unlock(eb);
222 free_extent_buffer(eb);
223 }
224 return eb;
225}
226
d352ac68
CM
227/* cowonly root (everything not a reference counted cow subvolume), just get
228 * put onto a simple dirty list. transaction.c walks this to make sure they
229 * get properly updated on disk.
230 */
0b86a832
CM
231static void add_root_to_dirty_list(struct btrfs_root *root)
232{
e5846fc6 233 spin_lock(&root->fs_info->trans_lock);
0b86a832
CM
234 if (root->track_dirty && list_empty(&root->dirty_list)) {
235 list_add(&root->dirty_list,
236 &root->fs_info->dirty_cowonly_roots);
237 }
e5846fc6 238 spin_unlock(&root->fs_info->trans_lock);
0b86a832
CM
239}
240
d352ac68
CM
241/*
242 * used by snapshot creation to make a copy of a root for a tree with
243 * a given objectid. The buffer with the new root node is returned in
244 * cow_ret, and this func returns zero on success or a negative error code.
245 */
be20aa9d
CM
246int btrfs_copy_root(struct btrfs_trans_handle *trans,
247 struct btrfs_root *root,
248 struct extent_buffer *buf,
249 struct extent_buffer **cow_ret, u64 new_root_objectid)
250{
251 struct extent_buffer *cow;
be20aa9d
CM
252 int ret = 0;
253 int level;
5d4f98a2 254 struct btrfs_disk_key disk_key;
be20aa9d
CM
255
256 WARN_ON(root->ref_cows && trans->transid !=
257 root->fs_info->running_transaction->transid);
258 WARN_ON(root->ref_cows && trans->transid != root->last_trans);
259
260 level = btrfs_header_level(buf);
5d4f98a2
YZ
261 if (level == 0)
262 btrfs_item_key(buf, &disk_key, 0);
263 else
264 btrfs_node_key(buf, &disk_key, 0);
31840ae1 265
5d4f98a2
YZ
266 cow = btrfs_alloc_free_block(trans, root, buf->len, 0,
267 new_root_objectid, &disk_key, level,
5581a51a 268 buf->start, 0);
5d4f98a2 269 if (IS_ERR(cow))
be20aa9d
CM
270 return PTR_ERR(cow);
271
272 copy_extent_buffer(cow, buf, 0, 0, cow->len);
273 btrfs_set_header_bytenr(cow, cow->start);
274 btrfs_set_header_generation(cow, trans->transid);
5d4f98a2
YZ
275 btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
276 btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
277 BTRFS_HEADER_FLAG_RELOC);
278 if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
279 btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
280 else
281 btrfs_set_header_owner(cow, new_root_objectid);
be20aa9d 282
2b82032c
YZ
283 write_extent_buffer(cow, root->fs_info->fsid,
284 (unsigned long)btrfs_header_fsid(cow),
285 BTRFS_FSID_SIZE);
286
be20aa9d 287 WARN_ON(btrfs_header_generation(buf) > trans->transid);
5d4f98a2 288 if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
66d7e7f0 289 ret = btrfs_inc_ref(trans, root, cow, 1, 1);
5d4f98a2 290 else
66d7e7f0 291 ret = btrfs_inc_ref(trans, root, cow, 0, 1);
4aec2b52 292
be20aa9d
CM
293 if (ret)
294 return ret;
295
296 btrfs_mark_buffer_dirty(cow);
297 *cow_ret = cow;
298 return 0;
299}
300
bd989ba3
JS
301enum mod_log_op {
302 MOD_LOG_KEY_REPLACE,
303 MOD_LOG_KEY_ADD,
304 MOD_LOG_KEY_REMOVE,
305 MOD_LOG_KEY_REMOVE_WHILE_FREEING,
306 MOD_LOG_KEY_REMOVE_WHILE_MOVING,
307 MOD_LOG_MOVE_KEYS,
308 MOD_LOG_ROOT_REPLACE,
309};
310
311struct tree_mod_move {
312 int dst_slot;
313 int nr_items;
314};
315
316struct tree_mod_root {
317 u64 logical;
318 u8 level;
319};
320
321struct tree_mod_elem {
322 struct rb_node node;
323 u64 index; /* shifted logical */
097b8a7c 324 u64 seq;
bd989ba3
JS
325 enum mod_log_op op;
326
327 /* this is used for MOD_LOG_KEY_* and MOD_LOG_MOVE_KEYS operations */
328 int slot;
329
330 /* this is used for MOD_LOG_KEY* and MOD_LOG_ROOT_REPLACE */
331 u64 generation;
332
333 /* those are used for op == MOD_LOG_KEY_{REPLACE,REMOVE} */
334 struct btrfs_disk_key key;
335 u64 blockptr;
336
337 /* this is used for op == MOD_LOG_MOVE_KEYS */
338 struct tree_mod_move move;
339
340 /* this is used for op == MOD_LOG_ROOT_REPLACE */
341 struct tree_mod_root old_root;
342};
343
097b8a7c 344static inline void tree_mod_log_read_lock(struct btrfs_fs_info *fs_info)
bd989ba3 345{
097b8a7c 346 read_lock(&fs_info->tree_mod_log_lock);
bd989ba3
JS
347}
348
097b8a7c
JS
349static inline void tree_mod_log_read_unlock(struct btrfs_fs_info *fs_info)
350{
351 read_unlock(&fs_info->tree_mod_log_lock);
352}
353
354static inline void tree_mod_log_write_lock(struct btrfs_fs_info *fs_info)
355{
356 write_lock(&fs_info->tree_mod_log_lock);
357}
358
359static inline void tree_mod_log_write_unlock(struct btrfs_fs_info *fs_info)
360{
361 write_unlock(&fs_info->tree_mod_log_lock);
362}
363
364/*
365 * This adds a new blocker to the tree mod log's blocker list if the @elem
366 * passed does not already have a sequence number set. So when a caller expects
367 * to record tree modifications, it should ensure to set elem->seq to zero
368 * before calling btrfs_get_tree_mod_seq.
369 * Returns a fresh, unused tree log modification sequence number, even if no new
370 * blocker was added.
371 */
372u64 btrfs_get_tree_mod_seq(struct btrfs_fs_info *fs_info,
373 struct seq_list *elem)
bd989ba3 374{
097b8a7c
JS
375 u64 seq;
376
377 tree_mod_log_write_lock(fs_info);
bd989ba3 378 spin_lock(&fs_info->tree_mod_seq_lock);
097b8a7c
JS
379 if (!elem->seq) {
380 elem->seq = btrfs_inc_tree_mod_seq(fs_info);
381 list_add_tail(&elem->list, &fs_info->tree_mod_seq_list);
382 }
383 seq = btrfs_inc_tree_mod_seq(fs_info);
bd989ba3 384 spin_unlock(&fs_info->tree_mod_seq_lock);
097b8a7c
JS
385 tree_mod_log_write_unlock(fs_info);
386
387 return seq;
bd989ba3
JS
388}
389
390void btrfs_put_tree_mod_seq(struct btrfs_fs_info *fs_info,
391 struct seq_list *elem)
392{
393 struct rb_root *tm_root;
394 struct rb_node *node;
395 struct rb_node *next;
396 struct seq_list *cur_elem;
397 struct tree_mod_elem *tm;
398 u64 min_seq = (u64)-1;
399 u64 seq_putting = elem->seq;
400
401 if (!seq_putting)
402 return;
403
bd989ba3
JS
404 spin_lock(&fs_info->tree_mod_seq_lock);
405 list_del(&elem->list);
097b8a7c 406 elem->seq = 0;
bd989ba3
JS
407
408 list_for_each_entry(cur_elem, &fs_info->tree_mod_seq_list, list) {
097b8a7c 409 if (cur_elem->seq < min_seq) {
bd989ba3
JS
410 if (seq_putting > cur_elem->seq) {
411 /*
412 * blocker with lower sequence number exists, we
413 * cannot remove anything from the log
414 */
097b8a7c
JS
415 spin_unlock(&fs_info->tree_mod_seq_lock);
416 return;
bd989ba3
JS
417 }
418 min_seq = cur_elem->seq;
419 }
420 }
097b8a7c
JS
421 spin_unlock(&fs_info->tree_mod_seq_lock);
422
bd989ba3
JS
423 /*
424 * anything that's lower than the lowest existing (read: blocked)
425 * sequence number can be removed from the tree.
426 */
097b8a7c 427 tree_mod_log_write_lock(fs_info);
bd989ba3
JS
428 tm_root = &fs_info->tree_mod_log;
429 for (node = rb_first(tm_root); node; node = next) {
430 next = rb_next(node);
431 tm = container_of(node, struct tree_mod_elem, node);
097b8a7c 432 if (tm->seq > min_seq)
bd989ba3
JS
433 continue;
434 rb_erase(node, tm_root);
bd989ba3
JS
435 kfree(tm);
436 }
097b8a7c 437 tree_mod_log_write_unlock(fs_info);
bd989ba3
JS
438}
439
440/*
441 * key order of the log:
442 * index -> sequence
443 *
444 * the index is the shifted logical of the *new* root node for root replace
445 * operations, or the shifted logical of the affected block for all other
446 * operations.
447 */
448static noinline int
449__tree_mod_log_insert(struct btrfs_fs_info *fs_info, struct tree_mod_elem *tm)
450{
451 struct rb_root *tm_root;
452 struct rb_node **new;
453 struct rb_node *parent = NULL;
454 struct tree_mod_elem *cur;
bd989ba3 455
097b8a7c 456 BUG_ON(!tm || !tm->seq);
bd989ba3 457
bd989ba3
JS
458 tm_root = &fs_info->tree_mod_log;
459 new = &tm_root->rb_node;
460 while (*new) {
461 cur = container_of(*new, struct tree_mod_elem, node);
462 parent = *new;
463 if (cur->index < tm->index)
464 new = &((*new)->rb_left);
465 else if (cur->index > tm->index)
466 new = &((*new)->rb_right);
097b8a7c 467 else if (cur->seq < tm->seq)
bd989ba3 468 new = &((*new)->rb_left);
097b8a7c 469 else if (cur->seq > tm->seq)
bd989ba3
JS
470 new = &((*new)->rb_right);
471 else {
472 kfree(tm);
097b8a7c 473 return -EEXIST;
bd989ba3
JS
474 }
475 }
476
477 rb_link_node(&tm->node, parent, new);
478 rb_insert_color(&tm->node, tm_root);
097b8a7c 479 return 0;
bd989ba3
JS
480}
481
097b8a7c
JS
482/*
483 * Determines if logging can be omitted. Returns 1 if it can. Otherwise, it
484 * returns zero with the tree_mod_log_lock acquired. The caller must hold
485 * this until all tree mod log insertions are recorded in the rb tree and then
486 * call tree_mod_log_write_unlock() to release.
487 */
e9b7fd4d
JS
488static inline int tree_mod_dont_log(struct btrfs_fs_info *fs_info,
489 struct extent_buffer *eb) {
490 smp_mb();
491 if (list_empty(&(fs_info)->tree_mod_seq_list))
492 return 1;
097b8a7c
JS
493 if (eb && btrfs_header_level(eb) == 0)
494 return 1;
495
496 tree_mod_log_write_lock(fs_info);
497 if (list_empty(&fs_info->tree_mod_seq_list)) {
498 /*
499 * someone emptied the list while we were waiting for the lock.
500 * we must not add to the list when no blocker exists.
501 */
502 tree_mod_log_write_unlock(fs_info);
e9b7fd4d 503 return 1;
097b8a7c
JS
504 }
505
e9b7fd4d
JS
506 return 0;
507}
508
3310c36e 509/*
097b8a7c 510 * This allocates memory and gets a tree modification sequence number.
3310c36e 511 *
097b8a7c
JS
512 * Returns <0 on error.
513 * Returns >0 (the added sequence number) on success.
3310c36e 514 */
926dd8a6
JS
515static inline int tree_mod_alloc(struct btrfs_fs_info *fs_info, gfp_t flags,
516 struct tree_mod_elem **tm_ret)
bd989ba3
JS
517{
518 struct tree_mod_elem *tm;
bd989ba3 519
097b8a7c
JS
520 /*
521 * once we switch from spin locks to something different, we should
522 * honor the flags parameter here.
523 */
524 tm = *tm_ret = kzalloc(sizeof(*tm), GFP_ATOMIC);
bd989ba3
JS
525 if (!tm)
526 return -ENOMEM;
527
097b8a7c
JS
528 tm->seq = btrfs_inc_tree_mod_seq(fs_info);
529 return tm->seq;
bd989ba3
JS
530}
531
097b8a7c
JS
532static inline int
533__tree_mod_log_insert_key(struct btrfs_fs_info *fs_info,
534 struct extent_buffer *eb, int slot,
535 enum mod_log_op op, gfp_t flags)
bd989ba3 536{
bd989ba3 537 int ret;
097b8a7c 538 struct tree_mod_elem *tm;
bd989ba3
JS
539
540 ret = tree_mod_alloc(fs_info, flags, &tm);
097b8a7c 541 if (ret < 0)
bd989ba3
JS
542 return ret;
543
544 tm->index = eb->start >> PAGE_CACHE_SHIFT;
545 if (op != MOD_LOG_KEY_ADD) {
546 btrfs_node_key(eb, &tm->key, slot);
547 tm->blockptr = btrfs_node_blockptr(eb, slot);
548 }
549 tm->op = op;
550 tm->slot = slot;
551 tm->generation = btrfs_node_ptr_generation(eb, slot);
552
097b8a7c
JS
553 return __tree_mod_log_insert(fs_info, tm);
554}
555
556static noinline int
557tree_mod_log_insert_key_mask(struct btrfs_fs_info *fs_info,
558 struct extent_buffer *eb, int slot,
559 enum mod_log_op op, gfp_t flags)
560{
561 int ret;
562
563 if (tree_mod_dont_log(fs_info, eb))
564 return 0;
565
566 ret = __tree_mod_log_insert_key(fs_info, eb, slot, op, flags);
567
568 tree_mod_log_write_unlock(fs_info);
3310c36e 569 return ret;
bd989ba3
JS
570}
571
572static noinline int
573tree_mod_log_insert_key(struct btrfs_fs_info *fs_info, struct extent_buffer *eb,
574 int slot, enum mod_log_op op)
575{
576 return tree_mod_log_insert_key_mask(fs_info, eb, slot, op, GFP_NOFS);
577}
578
097b8a7c
JS
579static noinline int
580tree_mod_log_insert_key_locked(struct btrfs_fs_info *fs_info,
581 struct extent_buffer *eb, int slot,
582 enum mod_log_op op)
583{
584 return __tree_mod_log_insert_key(fs_info, eb, slot, op, GFP_NOFS);
585}
586
bd989ba3
JS
587static noinline int
588tree_mod_log_insert_move(struct btrfs_fs_info *fs_info,
589 struct extent_buffer *eb, int dst_slot, int src_slot,
590 int nr_items, gfp_t flags)
591{
592 struct tree_mod_elem *tm;
593 int ret;
594 int i;
595
f395694c
JS
596 if (tree_mod_dont_log(fs_info, eb))
597 return 0;
bd989ba3
JS
598
599 for (i = 0; i + dst_slot < src_slot && i < nr_items; i++) {
097b8a7c 600 ret = tree_mod_log_insert_key_locked(fs_info, eb, i + dst_slot,
bd989ba3
JS
601 MOD_LOG_KEY_REMOVE_WHILE_MOVING);
602 BUG_ON(ret < 0);
603 }
604
f395694c 605 ret = tree_mod_alloc(fs_info, flags, &tm);
097b8a7c
JS
606 if (ret < 0)
607 goto out;
f395694c 608
bd989ba3
JS
609 tm->index = eb->start >> PAGE_CACHE_SHIFT;
610 tm->slot = src_slot;
611 tm->move.dst_slot = dst_slot;
612 tm->move.nr_items = nr_items;
613 tm->op = MOD_LOG_MOVE_KEYS;
614
3310c36e 615 ret = __tree_mod_log_insert(fs_info, tm);
097b8a7c
JS
616out:
617 tree_mod_log_write_unlock(fs_info);
3310c36e 618 return ret;
bd989ba3
JS
619}
620
097b8a7c
JS
621static inline void
622__tree_mod_log_free_eb(struct btrfs_fs_info *fs_info, struct extent_buffer *eb)
623{
624 int i;
625 u32 nritems;
626 int ret;
627
b12a3b1e
CM
628 if (btrfs_header_level(eb) == 0)
629 return;
630
097b8a7c
JS
631 nritems = btrfs_header_nritems(eb);
632 for (i = nritems - 1; i >= 0; i--) {
633 ret = tree_mod_log_insert_key_locked(fs_info, eb, i,
634 MOD_LOG_KEY_REMOVE_WHILE_FREEING);
635 BUG_ON(ret < 0);
636 }
637}
638
bd989ba3
JS
639static noinline int
640tree_mod_log_insert_root(struct btrfs_fs_info *fs_info,
641 struct extent_buffer *old_root,
642 struct extent_buffer *new_root, gfp_t flags)
643{
644 struct tree_mod_elem *tm;
645 int ret;
646
097b8a7c
JS
647 if (tree_mod_dont_log(fs_info, NULL))
648 return 0;
649
bd989ba3 650 ret = tree_mod_alloc(fs_info, flags, &tm);
097b8a7c
JS
651 if (ret < 0)
652 goto out;
bd989ba3
JS
653
654 tm->index = new_root->start >> PAGE_CACHE_SHIFT;
655 tm->old_root.logical = old_root->start;
656 tm->old_root.level = btrfs_header_level(old_root);
657 tm->generation = btrfs_header_generation(old_root);
658 tm->op = MOD_LOG_ROOT_REPLACE;
659
3310c36e 660 ret = __tree_mod_log_insert(fs_info, tm);
097b8a7c
JS
661out:
662 tree_mod_log_write_unlock(fs_info);
3310c36e 663 return ret;
bd989ba3
JS
664}
665
666static struct tree_mod_elem *
667__tree_mod_log_search(struct btrfs_fs_info *fs_info, u64 start, u64 min_seq,
668 int smallest)
669{
670 struct rb_root *tm_root;
671 struct rb_node *node;
672 struct tree_mod_elem *cur = NULL;
673 struct tree_mod_elem *found = NULL;
674 u64 index = start >> PAGE_CACHE_SHIFT;
675
097b8a7c 676 tree_mod_log_read_lock(fs_info);
bd989ba3
JS
677 tm_root = &fs_info->tree_mod_log;
678 node = tm_root->rb_node;
679 while (node) {
680 cur = container_of(node, struct tree_mod_elem, node);
681 if (cur->index < index) {
682 node = node->rb_left;
683 } else if (cur->index > index) {
684 node = node->rb_right;
097b8a7c 685 } else if (cur->seq < min_seq) {
bd989ba3
JS
686 node = node->rb_left;
687 } else if (!smallest) {
688 /* we want the node with the highest seq */
689 if (found)
097b8a7c 690 BUG_ON(found->seq > cur->seq);
bd989ba3
JS
691 found = cur;
692 node = node->rb_left;
097b8a7c 693 } else if (cur->seq > min_seq) {
bd989ba3
JS
694 /* we want the node with the smallest seq */
695 if (found)
097b8a7c 696 BUG_ON(found->seq < cur->seq);
bd989ba3
JS
697 found = cur;
698 node = node->rb_right;
699 } else {
700 found = cur;
701 break;
702 }
703 }
097b8a7c 704 tree_mod_log_read_unlock(fs_info);
bd989ba3
JS
705
706 return found;
707}
708
709/*
710 * this returns the element from the log with the smallest time sequence
711 * value that's in the log (the oldest log item). any element with a time
712 * sequence lower than min_seq will be ignored.
713 */
714static struct tree_mod_elem *
715tree_mod_log_search_oldest(struct btrfs_fs_info *fs_info, u64 start,
716 u64 min_seq)
717{
718 return __tree_mod_log_search(fs_info, start, min_seq, 1);
719}
720
721/*
722 * this returns the element from the log with the largest time sequence
723 * value that's in the log (the most recent log item). any element with
724 * a time sequence lower than min_seq will be ignored.
725 */
726static struct tree_mod_elem *
727tree_mod_log_search(struct btrfs_fs_info *fs_info, u64 start, u64 min_seq)
728{
729 return __tree_mod_log_search(fs_info, start, min_seq, 0);
730}
731
097b8a7c 732static noinline void
bd989ba3
JS
733tree_mod_log_eb_copy(struct btrfs_fs_info *fs_info, struct extent_buffer *dst,
734 struct extent_buffer *src, unsigned long dst_offset,
735 unsigned long src_offset, int nr_items)
736{
737 int ret;
738 int i;
739
e9b7fd4d 740 if (tree_mod_dont_log(fs_info, NULL))
bd989ba3
JS
741 return;
742
097b8a7c
JS
743 if (btrfs_header_level(dst) == 0 && btrfs_header_level(src) == 0) {
744 tree_mod_log_write_unlock(fs_info);
bd989ba3 745 return;
097b8a7c 746 }
bd989ba3 747
bd989ba3 748 for (i = 0; i < nr_items; i++) {
097b8a7c
JS
749 ret = tree_mod_log_insert_key_locked(fs_info, src,
750 i + src_offset,
751 MOD_LOG_KEY_REMOVE);
bd989ba3 752 BUG_ON(ret < 0);
097b8a7c
JS
753 ret = tree_mod_log_insert_key_locked(fs_info, dst,
754 i + dst_offset,
755 MOD_LOG_KEY_ADD);
bd989ba3
JS
756 BUG_ON(ret < 0);
757 }
097b8a7c
JS
758
759 tree_mod_log_write_unlock(fs_info);
bd989ba3
JS
760}
761
762static inline void
763tree_mod_log_eb_move(struct btrfs_fs_info *fs_info, struct extent_buffer *dst,
764 int dst_offset, int src_offset, int nr_items)
765{
766 int ret;
767 ret = tree_mod_log_insert_move(fs_info, dst, dst_offset, src_offset,
768 nr_items, GFP_NOFS);
769 BUG_ON(ret < 0);
770}
771
097b8a7c 772static noinline void
bd989ba3
JS
773tree_mod_log_set_node_key(struct btrfs_fs_info *fs_info,
774 struct extent_buffer *eb,
775 struct btrfs_disk_key *disk_key, int slot, int atomic)
776{
777 int ret;
778
779 ret = tree_mod_log_insert_key_mask(fs_info, eb, slot,
780 MOD_LOG_KEY_REPLACE,
781 atomic ? GFP_ATOMIC : GFP_NOFS);
782 BUG_ON(ret < 0);
783}
784
097b8a7c
JS
785static noinline void
786tree_mod_log_free_eb(struct btrfs_fs_info *fs_info, struct extent_buffer *eb)
bd989ba3 787{
e9b7fd4d 788 if (tree_mod_dont_log(fs_info, eb))
bd989ba3
JS
789 return;
790
097b8a7c
JS
791 __tree_mod_log_free_eb(fs_info, eb);
792
793 tree_mod_log_write_unlock(fs_info);
bd989ba3
JS
794}
795
097b8a7c 796static noinline void
bd989ba3
JS
797tree_mod_log_set_root_pointer(struct btrfs_root *root,
798 struct extent_buffer *new_root_node)
799{
800 int ret;
bd989ba3
JS
801 ret = tree_mod_log_insert_root(root->fs_info, root->node,
802 new_root_node, GFP_NOFS);
803 BUG_ON(ret < 0);
804}
805
5d4f98a2
YZ
806/*
807 * check if the tree block can be shared by multiple trees
808 */
809int btrfs_block_can_be_shared(struct btrfs_root *root,
810 struct extent_buffer *buf)
811{
812 /*
813 * Tree blocks not in refernece counted trees and tree roots
814 * are never shared. If a block was allocated after the last
815 * snapshot and the block was not allocated by tree relocation,
816 * we know the block is not shared.
817 */
818 if (root->ref_cows &&
819 buf != root->node && buf != root->commit_root &&
820 (btrfs_header_generation(buf) <=
821 btrfs_root_last_snapshot(&root->root_item) ||
822 btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)))
823 return 1;
824#ifdef BTRFS_COMPAT_EXTENT_TREE_V0
825 if (root->ref_cows &&
826 btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
827 return 1;
828#endif
829 return 0;
830}
831
832static noinline int update_ref_for_cow(struct btrfs_trans_handle *trans,
833 struct btrfs_root *root,
834 struct extent_buffer *buf,
f0486c68
YZ
835 struct extent_buffer *cow,
836 int *last_ref)
5d4f98a2
YZ
837{
838 u64 refs;
839 u64 owner;
840 u64 flags;
841 u64 new_flags = 0;
842 int ret;
843
844 /*
845 * Backrefs update rules:
846 *
847 * Always use full backrefs for extent pointers in tree block
848 * allocated by tree relocation.
849 *
850 * If a shared tree block is no longer referenced by its owner
851 * tree (btrfs_header_owner(buf) == root->root_key.objectid),
852 * use full backrefs for extent pointers in tree block.
853 *
854 * If a tree block is been relocating
855 * (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID),
856 * use full backrefs for extent pointers in tree block.
857 * The reason for this is some operations (such as drop tree)
858 * are only allowed for blocks use full backrefs.
859 */
860
861 if (btrfs_block_can_be_shared(root, buf)) {
862 ret = btrfs_lookup_extent_info(trans, root, buf->start,
863 buf->len, &refs, &flags);
be1a5564
MF
864 if (ret)
865 return ret;
e5df9573
MF
866 if (refs == 0) {
867 ret = -EROFS;
868 btrfs_std_error(root->fs_info, ret);
869 return ret;
870 }
5d4f98a2
YZ
871 } else {
872 refs = 1;
873 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
874 btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
875 flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
876 else
877 flags = 0;
878 }
879
880 owner = btrfs_header_owner(buf);
881 BUG_ON(owner == BTRFS_TREE_RELOC_OBJECTID &&
882 !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
883
884 if (refs > 1) {
885 if ((owner == root->root_key.objectid ||
886 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) &&
887 !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
66d7e7f0 888 ret = btrfs_inc_ref(trans, root, buf, 1, 1);
79787eaa 889 BUG_ON(ret); /* -ENOMEM */
5d4f98a2
YZ
890
891 if (root->root_key.objectid ==
892 BTRFS_TREE_RELOC_OBJECTID) {
66d7e7f0 893 ret = btrfs_dec_ref(trans, root, buf, 0, 1);
79787eaa 894 BUG_ON(ret); /* -ENOMEM */
66d7e7f0 895 ret = btrfs_inc_ref(trans, root, cow, 1, 1);
79787eaa 896 BUG_ON(ret); /* -ENOMEM */
5d4f98a2
YZ
897 }
898 new_flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
899 } else {
900
901 if (root->root_key.objectid ==
902 BTRFS_TREE_RELOC_OBJECTID)
66d7e7f0 903 ret = btrfs_inc_ref(trans, root, cow, 1, 1);
5d4f98a2 904 else
66d7e7f0 905 ret = btrfs_inc_ref(trans, root, cow, 0, 1);
79787eaa 906 BUG_ON(ret); /* -ENOMEM */
5d4f98a2
YZ
907 }
908 if (new_flags != 0) {
909 ret = btrfs_set_disk_extent_flags(trans, root,
910 buf->start,
911 buf->len,
912 new_flags, 0);
be1a5564
MF
913 if (ret)
914 return ret;
5d4f98a2
YZ
915 }
916 } else {
917 if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
918 if (root->root_key.objectid ==
919 BTRFS_TREE_RELOC_OBJECTID)
66d7e7f0 920 ret = btrfs_inc_ref(trans, root, cow, 1, 1);
5d4f98a2 921 else
66d7e7f0 922 ret = btrfs_inc_ref(trans, root, cow, 0, 1);
79787eaa 923 BUG_ON(ret); /* -ENOMEM */
66d7e7f0 924 ret = btrfs_dec_ref(trans, root, buf, 1, 1);
79787eaa 925 BUG_ON(ret); /* -ENOMEM */
5d4f98a2 926 }
ba1bfbd5 927 tree_mod_log_free_eb(root->fs_info, buf);
5d4f98a2 928 clean_tree_block(trans, root, buf);
f0486c68 929 *last_ref = 1;
5d4f98a2
YZ
930 }
931 return 0;
932}
933
d352ac68 934/*
d397712b
CM
935 * does the dirty work in cow of a single block. The parent block (if
936 * supplied) is updated to point to the new cow copy. The new buffer is marked
937 * dirty and returned locked. If you modify the block it needs to be marked
938 * dirty again.
d352ac68
CM
939 *
940 * search_start -- an allocation hint for the new block
941 *
d397712b
CM
942 * empty_size -- a hint that you plan on doing more cow. This is the size in
943 * bytes the allocator should try to find free next to the block it returns.
944 * This is just a hint and may be ignored by the allocator.
d352ac68 945 */
d397712b 946static noinline int __btrfs_cow_block(struct btrfs_trans_handle *trans,
5f39d397
CM
947 struct btrfs_root *root,
948 struct extent_buffer *buf,
949 struct extent_buffer *parent, int parent_slot,
950 struct extent_buffer **cow_ret,
9fa8cfe7 951 u64 search_start, u64 empty_size)
02217ed2 952{
5d4f98a2 953 struct btrfs_disk_key disk_key;
5f39d397 954 struct extent_buffer *cow;
be1a5564 955 int level, ret;
f0486c68 956 int last_ref = 0;
925baedd 957 int unlock_orig = 0;
5d4f98a2 958 u64 parent_start;
7bb86316 959
925baedd
CM
960 if (*cow_ret == buf)
961 unlock_orig = 1;
962
b9447ef8 963 btrfs_assert_tree_locked(buf);
925baedd 964
7bb86316
CM
965 WARN_ON(root->ref_cows && trans->transid !=
966 root->fs_info->running_transaction->transid);
6702ed49 967 WARN_ON(root->ref_cows && trans->transid != root->last_trans);
5f39d397 968
7bb86316 969 level = btrfs_header_level(buf);
31840ae1 970
5d4f98a2
YZ
971 if (level == 0)
972 btrfs_item_key(buf, &disk_key, 0);
973 else
974 btrfs_node_key(buf, &disk_key, 0);
975
976 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) {
977 if (parent)
978 parent_start = parent->start;
979 else
980 parent_start = 0;
981 } else
982 parent_start = 0;
983
984 cow = btrfs_alloc_free_block(trans, root, buf->len, parent_start,
985 root->root_key.objectid, &disk_key,
5581a51a 986 level, search_start, empty_size);
54aa1f4d
CM
987 if (IS_ERR(cow))
988 return PTR_ERR(cow);
6702ed49 989
b4ce94de
CM
990 /* cow is set to blocking by btrfs_init_new_buffer */
991
5f39d397 992 copy_extent_buffer(cow, buf, 0, 0, cow->len);
db94535d 993 btrfs_set_header_bytenr(cow, cow->start);
5f39d397 994 btrfs_set_header_generation(cow, trans->transid);
5d4f98a2
YZ
995 btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
996 btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
997 BTRFS_HEADER_FLAG_RELOC);
998 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
999 btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
1000 else
1001 btrfs_set_header_owner(cow, root->root_key.objectid);
6702ed49 1002
2b82032c
YZ
1003 write_extent_buffer(cow, root->fs_info->fsid,
1004 (unsigned long)btrfs_header_fsid(cow),
1005 BTRFS_FSID_SIZE);
1006
be1a5564 1007 ret = update_ref_for_cow(trans, root, buf, cow, &last_ref);
b68dc2a9 1008 if (ret) {
79787eaa 1009 btrfs_abort_transaction(trans, root, ret);
b68dc2a9
MF
1010 return ret;
1011 }
1a40e23b 1012
3fd0a558
YZ
1013 if (root->ref_cows)
1014 btrfs_reloc_cow_block(trans, root, buf, cow);
1015
02217ed2 1016 if (buf == root->node) {
925baedd 1017 WARN_ON(parent && parent != buf);
5d4f98a2
YZ
1018 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
1019 btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
1020 parent_start = buf->start;
1021 else
1022 parent_start = 0;
925baedd 1023
5f39d397 1024 extent_buffer_get(cow);
f230475e 1025 tree_mod_log_set_root_pointer(root, cow);
240f62c8 1026 rcu_assign_pointer(root->node, cow);
925baedd 1027
f0486c68 1028 btrfs_free_tree_block(trans, root, buf, parent_start,
5581a51a 1029 last_ref);
5f39d397 1030 free_extent_buffer(buf);
0b86a832 1031 add_root_to_dirty_list(root);
02217ed2 1032 } else {
5d4f98a2
YZ
1033 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
1034 parent_start = parent->start;
1035 else
1036 parent_start = 0;
1037
1038 WARN_ON(trans->transid != btrfs_header_generation(parent));
f230475e
JS
1039 tree_mod_log_insert_key(root->fs_info, parent, parent_slot,
1040 MOD_LOG_KEY_REPLACE);
5f39d397 1041 btrfs_set_node_blockptr(parent, parent_slot,
db94535d 1042 cow->start);
74493f7a
CM
1043 btrfs_set_node_ptr_generation(parent, parent_slot,
1044 trans->transid);
d6025579 1045 btrfs_mark_buffer_dirty(parent);
f0486c68 1046 btrfs_free_tree_block(trans, root, buf, parent_start,
5581a51a 1047 last_ref);
02217ed2 1048 }
925baedd
CM
1049 if (unlock_orig)
1050 btrfs_tree_unlock(buf);
3083ee2e 1051 free_extent_buffer_stale(buf);
ccd467d6 1052 btrfs_mark_buffer_dirty(cow);
2c90e5d6 1053 *cow_ret = cow;
02217ed2
CM
1054 return 0;
1055}
1056
5d9e75c4
JS
1057/*
1058 * returns the logical address of the oldest predecessor of the given root.
1059 * entries older than time_seq are ignored.
1060 */
1061static struct tree_mod_elem *
1062__tree_mod_log_oldest_root(struct btrfs_fs_info *fs_info,
1063 struct btrfs_root *root, u64 time_seq)
1064{
1065 struct tree_mod_elem *tm;
1066 struct tree_mod_elem *found = NULL;
1067 u64 root_logical = root->node->start;
1068 int looped = 0;
1069
1070 if (!time_seq)
1071 return 0;
1072
1073 /*
1074 * the very last operation that's logged for a root is the replacement
1075 * operation (if it is replaced at all). this has the index of the *new*
1076 * root, making it the very first operation that's logged for this root.
1077 */
1078 while (1) {
1079 tm = tree_mod_log_search_oldest(fs_info, root_logical,
1080 time_seq);
1081 if (!looped && !tm)
1082 return 0;
1083 /*
28da9fb4
JS
1084 * if there are no tree operation for the oldest root, we simply
1085 * return it. this should only happen if that (old) root is at
1086 * level 0.
5d9e75c4 1087 */
28da9fb4
JS
1088 if (!tm)
1089 break;
5d9e75c4 1090
28da9fb4
JS
1091 /*
1092 * if there's an operation that's not a root replacement, we
1093 * found the oldest version of our root. normally, we'll find a
1094 * MOD_LOG_KEY_REMOVE_WHILE_FREEING operation here.
1095 */
5d9e75c4
JS
1096 if (tm->op != MOD_LOG_ROOT_REPLACE)
1097 break;
1098
1099 found = tm;
1100 root_logical = tm->old_root.logical;
1101 BUG_ON(root_logical == root->node->start);
1102 looped = 1;
1103 }
1104
a95236d9
JS
1105 /* if there's no old root to return, return what we found instead */
1106 if (!found)
1107 found = tm;
1108
5d9e75c4
JS
1109 return found;
1110}
1111
1112/*
1113 * tm is a pointer to the first operation to rewind within eb. then, all
1114 * previous operations will be rewinded (until we reach something older than
1115 * time_seq).
1116 */
1117static void
1118__tree_mod_log_rewind(struct extent_buffer *eb, u64 time_seq,
1119 struct tree_mod_elem *first_tm)
1120{
1121 u32 n;
1122 struct rb_node *next;
1123 struct tree_mod_elem *tm = first_tm;
1124 unsigned long o_dst;
1125 unsigned long o_src;
1126 unsigned long p_size = sizeof(struct btrfs_key_ptr);
1127
1128 n = btrfs_header_nritems(eb);
097b8a7c 1129 while (tm && tm->seq >= time_seq) {
5d9e75c4
JS
1130 /*
1131 * all the operations are recorded with the operator used for
1132 * the modification. as we're going backwards, we do the
1133 * opposite of each operation here.
1134 */
1135 switch (tm->op) {
1136 case MOD_LOG_KEY_REMOVE_WHILE_FREEING:
1137 BUG_ON(tm->slot < n);
1138 case MOD_LOG_KEY_REMOVE_WHILE_MOVING:
1139 case MOD_LOG_KEY_REMOVE:
1140 btrfs_set_node_key(eb, &tm->key, tm->slot);
1141 btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
1142 btrfs_set_node_ptr_generation(eb, tm->slot,
1143 tm->generation);
1144 n++;
1145 break;
1146 case MOD_LOG_KEY_REPLACE:
1147 BUG_ON(tm->slot >= n);
1148 btrfs_set_node_key(eb, &tm->key, tm->slot);
1149 btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
1150 btrfs_set_node_ptr_generation(eb, tm->slot,
1151 tm->generation);
1152 break;
1153 case MOD_LOG_KEY_ADD:
19956c7e 1154 /* if a move operation is needed it's in the log */
5d9e75c4
JS
1155 n--;
1156 break;
1157 case MOD_LOG_MOVE_KEYS:
c3193108
JS
1158 o_dst = btrfs_node_key_ptr_offset(tm->slot);
1159 o_src = btrfs_node_key_ptr_offset(tm->move.dst_slot);
1160 memmove_extent_buffer(eb, o_dst, o_src,
5d9e75c4
JS
1161 tm->move.nr_items * p_size);
1162 break;
1163 case MOD_LOG_ROOT_REPLACE:
1164 /*
1165 * this operation is special. for roots, this must be
1166 * handled explicitly before rewinding.
1167 * for non-roots, this operation may exist if the node
1168 * was a root: root A -> child B; then A gets empty and
1169 * B is promoted to the new root. in the mod log, we'll
1170 * have a root-replace operation for B, a tree block
1171 * that is no root. we simply ignore that operation.
1172 */
1173 break;
1174 }
1175 next = rb_next(&tm->node);
1176 if (!next)
1177 break;
1178 tm = container_of(next, struct tree_mod_elem, node);
1179 if (tm->index != first_tm->index)
1180 break;
1181 }
1182 btrfs_set_header_nritems(eb, n);
1183}
1184
1185static struct extent_buffer *
1186tree_mod_log_rewind(struct btrfs_fs_info *fs_info, struct extent_buffer *eb,
1187 u64 time_seq)
1188{
1189 struct extent_buffer *eb_rewin;
1190 struct tree_mod_elem *tm;
1191
1192 if (!time_seq)
1193 return eb;
1194
1195 if (btrfs_header_level(eb) == 0)
1196 return eb;
1197
1198 tm = tree_mod_log_search(fs_info, eb->start, time_seq);
1199 if (!tm)
1200 return eb;
1201
1202 if (tm->op == MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
1203 BUG_ON(tm->slot != 0);
1204 eb_rewin = alloc_dummy_extent_buffer(eb->start,
1205 fs_info->tree_root->nodesize);
1206 BUG_ON(!eb_rewin);
1207 btrfs_set_header_bytenr(eb_rewin, eb->start);
1208 btrfs_set_header_backref_rev(eb_rewin,
1209 btrfs_header_backref_rev(eb));
1210 btrfs_set_header_owner(eb_rewin, btrfs_header_owner(eb));
c3193108 1211 btrfs_set_header_level(eb_rewin, btrfs_header_level(eb));
5d9e75c4
JS
1212 } else {
1213 eb_rewin = btrfs_clone_extent_buffer(eb);
1214 BUG_ON(!eb_rewin);
1215 }
1216
1217 extent_buffer_get(eb_rewin);
1218 free_extent_buffer(eb);
1219
1220 __tree_mod_log_rewind(eb_rewin, time_seq, tm);
57911b8b
JS
1221 WARN_ON(btrfs_header_nritems(eb_rewin) >
1222 BTRFS_NODEPTRS_PER_BLOCK(fs_info->fs_root));
5d9e75c4
JS
1223
1224 return eb_rewin;
1225}
1226
8ba97a15
JS
1227/*
1228 * get_old_root() rewinds the state of @root's root node to the given @time_seq
1229 * value. If there are no changes, the current root->root_node is returned. If
1230 * anything changed in between, there's a fresh buffer allocated on which the
1231 * rewind operations are done. In any case, the returned buffer is read locked.
1232 * Returns NULL on error (with no locks held).
1233 */
5d9e75c4
JS
1234static inline struct extent_buffer *
1235get_old_root(struct btrfs_root *root, u64 time_seq)
1236{
1237 struct tree_mod_elem *tm;
1238 struct extent_buffer *eb;
a95236d9 1239 struct tree_mod_root *old_root = NULL;
4325edd0 1240 u64 old_generation = 0;
a95236d9 1241 u64 logical;
834328a8 1242 u32 blocksize;
5d9e75c4 1243
8ba97a15 1244 eb = btrfs_read_lock_root_node(root);
5d9e75c4
JS
1245 tm = __tree_mod_log_oldest_root(root->fs_info, root, time_seq);
1246 if (!tm)
1247 return root->node;
1248
a95236d9
JS
1249 if (tm->op == MOD_LOG_ROOT_REPLACE) {
1250 old_root = &tm->old_root;
1251 old_generation = tm->generation;
1252 logical = old_root->logical;
1253 } else {
1254 logical = root->node->start;
1255 }
5d9e75c4 1256
a95236d9 1257 tm = tree_mod_log_search(root->fs_info, logical, time_seq);
834328a8
JS
1258 if (old_root && tm && tm->op != MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
1259 btrfs_tree_read_unlock(root->node);
1260 free_extent_buffer(root->node);
1261 blocksize = btrfs_level_size(root, old_root->level);
1262 eb = read_tree_block(root, logical, blocksize, 0);
1263 if (!eb) {
1264 pr_warn("btrfs: failed to read tree block %llu from get_old_root\n",
1265 logical);
1266 WARN_ON(1);
1267 } else {
1268 eb = btrfs_clone_extent_buffer(eb);
1269 }
1270 } else if (old_root) {
1271 btrfs_tree_read_unlock(root->node);
1272 free_extent_buffer(root->node);
28da9fb4 1273 eb = alloc_dummy_extent_buffer(logical, root->nodesize);
834328a8 1274 } else {
a95236d9 1275 eb = btrfs_clone_extent_buffer(root->node);
834328a8
JS
1276 btrfs_tree_read_unlock(root->node);
1277 free_extent_buffer(root->node);
1278 }
1279
8ba97a15
JS
1280 if (!eb)
1281 return NULL;
1282 btrfs_tree_read_lock(eb);
a95236d9 1283 if (old_root) {
5d9e75c4
JS
1284 btrfs_set_header_bytenr(eb, eb->start);
1285 btrfs_set_header_backref_rev(eb, BTRFS_MIXED_BACKREF_REV);
1286 btrfs_set_header_owner(eb, root->root_key.objectid);
a95236d9
JS
1287 btrfs_set_header_level(eb, old_root->level);
1288 btrfs_set_header_generation(eb, old_generation);
5d9e75c4 1289 }
28da9fb4
JS
1290 if (tm)
1291 __tree_mod_log_rewind(eb, time_seq, tm);
1292 else
1293 WARN_ON(btrfs_header_level(eb) != 0);
8ba97a15 1294 extent_buffer_get(eb);
57911b8b 1295 WARN_ON(btrfs_header_nritems(eb) > BTRFS_NODEPTRS_PER_BLOCK(root));
5d9e75c4
JS
1296
1297 return eb;
1298}
1299
5d4f98a2
YZ
1300static inline int should_cow_block(struct btrfs_trans_handle *trans,
1301 struct btrfs_root *root,
1302 struct extent_buffer *buf)
1303{
f1ebcc74
LB
1304 /* ensure we can see the force_cow */
1305 smp_rmb();
1306
1307 /*
1308 * We do not need to cow a block if
1309 * 1) this block is not created or changed in this transaction;
1310 * 2) this block does not belong to TREE_RELOC tree;
1311 * 3) the root is not forced COW.
1312 *
1313 * What is forced COW:
1314 * when we create snapshot during commiting the transaction,
1315 * after we've finished coping src root, we must COW the shared
1316 * block to ensure the metadata consistency.
1317 */
5d4f98a2
YZ
1318 if (btrfs_header_generation(buf) == trans->transid &&
1319 !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
1320 !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
f1ebcc74
LB
1321 btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
1322 !root->force_cow)
5d4f98a2
YZ
1323 return 0;
1324 return 1;
1325}
1326
d352ac68
CM
1327/*
1328 * cows a single block, see __btrfs_cow_block for the real work.
1329 * This version of it has extra checks so that a block isn't cow'd more than
1330 * once per transaction, as long as it hasn't been written yet
1331 */
d397712b 1332noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
5f39d397
CM
1333 struct btrfs_root *root, struct extent_buffer *buf,
1334 struct extent_buffer *parent, int parent_slot,
9fa8cfe7 1335 struct extent_buffer **cow_ret)
6702ed49
CM
1336{
1337 u64 search_start;
f510cfec 1338 int ret;
dc17ff8f 1339
6702ed49 1340 if (trans->transaction != root->fs_info->running_transaction) {
d397712b
CM
1341 printk(KERN_CRIT "trans %llu running %llu\n",
1342 (unsigned long long)trans->transid,
1343 (unsigned long long)
6702ed49
CM
1344 root->fs_info->running_transaction->transid);
1345 WARN_ON(1);
1346 }
1347 if (trans->transid != root->fs_info->generation) {
d397712b
CM
1348 printk(KERN_CRIT "trans %llu running %llu\n",
1349 (unsigned long long)trans->transid,
1350 (unsigned long long)root->fs_info->generation);
6702ed49
CM
1351 WARN_ON(1);
1352 }
dc17ff8f 1353
5d4f98a2 1354 if (!should_cow_block(trans, root, buf)) {
6702ed49
CM
1355 *cow_ret = buf;
1356 return 0;
1357 }
c487685d 1358
0b86a832 1359 search_start = buf->start & ~((u64)(1024 * 1024 * 1024) - 1);
b4ce94de
CM
1360
1361 if (parent)
1362 btrfs_set_lock_blocking(parent);
1363 btrfs_set_lock_blocking(buf);
1364
f510cfec 1365 ret = __btrfs_cow_block(trans, root, buf, parent,
9fa8cfe7 1366 parent_slot, cow_ret, search_start, 0);
1abe9b8a 1367
1368 trace_btrfs_cow_block(root, buf, *cow_ret);
1369
f510cfec 1370 return ret;
6702ed49
CM
1371}
1372
d352ac68
CM
1373/*
1374 * helper function for defrag to decide if two blocks pointed to by a
1375 * node are actually close by
1376 */
6b80053d 1377static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
6702ed49 1378{
6b80053d 1379 if (blocknr < other && other - (blocknr + blocksize) < 32768)
6702ed49 1380 return 1;
6b80053d 1381 if (blocknr > other && blocknr - (other + blocksize) < 32768)
6702ed49
CM
1382 return 1;
1383 return 0;
1384}
1385
081e9573
CM
1386/*
1387 * compare two keys in a memcmp fashion
1388 */
1389static int comp_keys(struct btrfs_disk_key *disk, struct btrfs_key *k2)
1390{
1391 struct btrfs_key k1;
1392
1393 btrfs_disk_key_to_cpu(&k1, disk);
1394
20736aba 1395 return btrfs_comp_cpu_keys(&k1, k2);
081e9573
CM
1396}
1397
f3465ca4
JB
1398/*
1399 * same as comp_keys only with two btrfs_key's
1400 */
5d4f98a2 1401int btrfs_comp_cpu_keys(struct btrfs_key *k1, struct btrfs_key *k2)
f3465ca4
JB
1402{
1403 if (k1->objectid > k2->objectid)
1404 return 1;
1405 if (k1->objectid < k2->objectid)
1406 return -1;
1407 if (k1->type > k2->type)
1408 return 1;
1409 if (k1->type < k2->type)
1410 return -1;
1411 if (k1->offset > k2->offset)
1412 return 1;
1413 if (k1->offset < k2->offset)
1414 return -1;
1415 return 0;
1416}
081e9573 1417
d352ac68
CM
1418/*
1419 * this is used by the defrag code to go through all the
1420 * leaves pointed to by a node and reallocate them so that
1421 * disk order is close to key order
1422 */
6702ed49 1423int btrfs_realloc_node(struct btrfs_trans_handle *trans,
5f39d397 1424 struct btrfs_root *root, struct extent_buffer *parent,
a6b6e75e
CM
1425 int start_slot, int cache_only, u64 *last_ret,
1426 struct btrfs_key *progress)
6702ed49 1427{
6b80053d 1428 struct extent_buffer *cur;
6702ed49 1429 u64 blocknr;
ca7a79ad 1430 u64 gen;
e9d0b13b
CM
1431 u64 search_start = *last_ret;
1432 u64 last_block = 0;
6702ed49
CM
1433 u64 other;
1434 u32 parent_nritems;
6702ed49
CM
1435 int end_slot;
1436 int i;
1437 int err = 0;
f2183bde 1438 int parent_level;
6b80053d
CM
1439 int uptodate;
1440 u32 blocksize;
081e9573
CM
1441 int progress_passed = 0;
1442 struct btrfs_disk_key disk_key;
6702ed49 1443
5708b959
CM
1444 parent_level = btrfs_header_level(parent);
1445 if (cache_only && parent_level != 1)
1446 return 0;
1447
d397712b 1448 if (trans->transaction != root->fs_info->running_transaction)
6702ed49 1449 WARN_ON(1);
d397712b 1450 if (trans->transid != root->fs_info->generation)
6702ed49 1451 WARN_ON(1);
86479a04 1452
6b80053d 1453 parent_nritems = btrfs_header_nritems(parent);
6b80053d 1454 blocksize = btrfs_level_size(root, parent_level - 1);
6702ed49
CM
1455 end_slot = parent_nritems;
1456
1457 if (parent_nritems == 1)
1458 return 0;
1459
b4ce94de
CM
1460 btrfs_set_lock_blocking(parent);
1461
6702ed49
CM
1462 for (i = start_slot; i < end_slot; i++) {
1463 int close = 1;
a6b6e75e 1464
081e9573
CM
1465 btrfs_node_key(parent, &disk_key, i);
1466 if (!progress_passed && comp_keys(&disk_key, progress) < 0)
1467 continue;
1468
1469 progress_passed = 1;
6b80053d 1470 blocknr = btrfs_node_blockptr(parent, i);
ca7a79ad 1471 gen = btrfs_node_ptr_generation(parent, i);
e9d0b13b
CM
1472 if (last_block == 0)
1473 last_block = blocknr;
5708b959 1474
6702ed49 1475 if (i > 0) {
6b80053d
CM
1476 other = btrfs_node_blockptr(parent, i - 1);
1477 close = close_blocks(blocknr, other, blocksize);
6702ed49 1478 }
0ef3e66b 1479 if (!close && i < end_slot - 2) {
6b80053d
CM
1480 other = btrfs_node_blockptr(parent, i + 1);
1481 close = close_blocks(blocknr, other, blocksize);
6702ed49 1482 }
e9d0b13b
CM
1483 if (close) {
1484 last_block = blocknr;
6702ed49 1485 continue;
e9d0b13b 1486 }
6702ed49 1487
6b80053d
CM
1488 cur = btrfs_find_tree_block(root, blocknr, blocksize);
1489 if (cur)
b9fab919 1490 uptodate = btrfs_buffer_uptodate(cur, gen, 0);
6b80053d
CM
1491 else
1492 uptodate = 0;
5708b959 1493 if (!cur || !uptodate) {
6702ed49 1494 if (cache_only) {
6b80053d 1495 free_extent_buffer(cur);
6702ed49
CM
1496 continue;
1497 }
6b80053d
CM
1498 if (!cur) {
1499 cur = read_tree_block(root, blocknr,
ca7a79ad 1500 blocksize, gen);
97d9a8a4
TI
1501 if (!cur)
1502 return -EIO;
6b80053d 1503 } else if (!uptodate) {
018642a1
TI
1504 err = btrfs_read_buffer(cur, gen);
1505 if (err) {
1506 free_extent_buffer(cur);
1507 return err;
1508 }
f2183bde 1509 }
6702ed49 1510 }
e9d0b13b 1511 if (search_start == 0)
6b80053d 1512 search_start = last_block;
e9d0b13b 1513
e7a84565 1514 btrfs_tree_lock(cur);
b4ce94de 1515 btrfs_set_lock_blocking(cur);
6b80053d 1516 err = __btrfs_cow_block(trans, root, cur, parent, i,
e7a84565 1517 &cur, search_start,
6b80053d 1518 min(16 * blocksize,
9fa8cfe7 1519 (end_slot - i) * blocksize));
252c38f0 1520 if (err) {
e7a84565 1521 btrfs_tree_unlock(cur);
6b80053d 1522 free_extent_buffer(cur);
6702ed49 1523 break;
252c38f0 1524 }
e7a84565
CM
1525 search_start = cur->start;
1526 last_block = cur->start;
f2183bde 1527 *last_ret = search_start;
e7a84565
CM
1528 btrfs_tree_unlock(cur);
1529 free_extent_buffer(cur);
6702ed49
CM
1530 }
1531 return err;
1532}
1533
74123bd7
CM
1534/*
1535 * The leaf data grows from end-to-front in the node.
1536 * this returns the address of the start of the last item,
1537 * which is the stop of the leaf data stack
1538 */
123abc88 1539static inline unsigned int leaf_data_end(struct btrfs_root *root,
5f39d397 1540 struct extent_buffer *leaf)
be0e5c09 1541{
5f39d397 1542 u32 nr = btrfs_header_nritems(leaf);
be0e5c09 1543 if (nr == 0)
123abc88 1544 return BTRFS_LEAF_DATA_SIZE(root);
5f39d397 1545 return btrfs_item_offset_nr(leaf, nr - 1);
be0e5c09
CM
1546}
1547
aa5d6bed 1548
74123bd7 1549/*
5f39d397
CM
1550 * search for key in the extent_buffer. The items start at offset p,
1551 * and they are item_size apart. There are 'max' items in p.
1552 *
74123bd7
CM
1553 * the slot in the array is returned via slot, and it points to
1554 * the place where you would insert key if it is not found in
1555 * the array.
1556 *
1557 * slot may point to max if the key is bigger than all of the keys
1558 */
e02119d5
CM
1559static noinline int generic_bin_search(struct extent_buffer *eb,
1560 unsigned long p,
1561 int item_size, struct btrfs_key *key,
1562 int max, int *slot)
be0e5c09
CM
1563{
1564 int low = 0;
1565 int high = max;
1566 int mid;
1567 int ret;
479965d6 1568 struct btrfs_disk_key *tmp = NULL;
5f39d397
CM
1569 struct btrfs_disk_key unaligned;
1570 unsigned long offset;
5f39d397
CM
1571 char *kaddr = NULL;
1572 unsigned long map_start = 0;
1573 unsigned long map_len = 0;
479965d6 1574 int err;
be0e5c09 1575
d397712b 1576 while (low < high) {
be0e5c09 1577 mid = (low + high) / 2;
5f39d397
CM
1578 offset = p + mid * item_size;
1579
a6591715 1580 if (!kaddr || offset < map_start ||
5f39d397
CM
1581 (offset + sizeof(struct btrfs_disk_key)) >
1582 map_start + map_len) {
934d375b
CM
1583
1584 err = map_private_extent_buffer(eb, offset,
479965d6 1585 sizeof(struct btrfs_disk_key),
a6591715 1586 &kaddr, &map_start, &map_len);
479965d6
CM
1587
1588 if (!err) {
1589 tmp = (struct btrfs_disk_key *)(kaddr + offset -
1590 map_start);
1591 } else {
1592 read_extent_buffer(eb, &unaligned,
1593 offset, sizeof(unaligned));
1594 tmp = &unaligned;
1595 }
5f39d397 1596
5f39d397
CM
1597 } else {
1598 tmp = (struct btrfs_disk_key *)(kaddr + offset -
1599 map_start);
1600 }
be0e5c09
CM
1601 ret = comp_keys(tmp, key);
1602
1603 if (ret < 0)
1604 low = mid + 1;
1605 else if (ret > 0)
1606 high = mid;
1607 else {
1608 *slot = mid;
1609 return 0;
1610 }
1611 }
1612 *slot = low;
1613 return 1;
1614}
1615
97571fd0
CM
1616/*
1617 * simple bin_search frontend that does the right thing for
1618 * leaves vs nodes
1619 */
5f39d397
CM
1620static int bin_search(struct extent_buffer *eb, struct btrfs_key *key,
1621 int level, int *slot)
be0e5c09 1622{
f775738f 1623 if (level == 0)
5f39d397
CM
1624 return generic_bin_search(eb,
1625 offsetof(struct btrfs_leaf, items),
0783fcfc 1626 sizeof(struct btrfs_item),
5f39d397 1627 key, btrfs_header_nritems(eb),
7518a238 1628 slot);
f775738f 1629 else
5f39d397
CM
1630 return generic_bin_search(eb,
1631 offsetof(struct btrfs_node, ptrs),
123abc88 1632 sizeof(struct btrfs_key_ptr),
5f39d397 1633 key, btrfs_header_nritems(eb),
7518a238 1634 slot);
be0e5c09
CM
1635}
1636
5d4f98a2
YZ
1637int btrfs_bin_search(struct extent_buffer *eb, struct btrfs_key *key,
1638 int level, int *slot)
1639{
1640 return bin_search(eb, key, level, slot);
1641}
1642
f0486c68
YZ
1643static void root_add_used(struct btrfs_root *root, u32 size)
1644{
1645 spin_lock(&root->accounting_lock);
1646 btrfs_set_root_used(&root->root_item,
1647 btrfs_root_used(&root->root_item) + size);
1648 spin_unlock(&root->accounting_lock);
1649}
1650
1651static void root_sub_used(struct btrfs_root *root, u32 size)
1652{
1653 spin_lock(&root->accounting_lock);
1654 btrfs_set_root_used(&root->root_item,
1655 btrfs_root_used(&root->root_item) - size);
1656 spin_unlock(&root->accounting_lock);
1657}
1658
d352ac68
CM
1659/* given a node and slot number, this reads the blocks it points to. The
1660 * extent buffer is returned with a reference taken (but unlocked).
1661 * NULL is returned on error.
1662 */
e02119d5 1663static noinline struct extent_buffer *read_node_slot(struct btrfs_root *root,
5f39d397 1664 struct extent_buffer *parent, int slot)
bb803951 1665{
ca7a79ad 1666 int level = btrfs_header_level(parent);
bb803951
CM
1667 if (slot < 0)
1668 return NULL;
5f39d397 1669 if (slot >= btrfs_header_nritems(parent))
bb803951 1670 return NULL;
ca7a79ad
CM
1671
1672 BUG_ON(level == 0);
1673
db94535d 1674 return read_tree_block(root, btrfs_node_blockptr(parent, slot),
ca7a79ad
CM
1675 btrfs_level_size(root, level - 1),
1676 btrfs_node_ptr_generation(parent, slot));
bb803951
CM
1677}
1678
d352ac68
CM
1679/*
1680 * node level balancing, used to make sure nodes are in proper order for
1681 * item deletion. We balance from the top down, so we have to make sure
1682 * that a deletion won't leave an node completely empty later on.
1683 */
e02119d5 1684static noinline int balance_level(struct btrfs_trans_handle *trans,
98ed5174
CM
1685 struct btrfs_root *root,
1686 struct btrfs_path *path, int level)
bb803951 1687{
5f39d397
CM
1688 struct extent_buffer *right = NULL;
1689 struct extent_buffer *mid;
1690 struct extent_buffer *left = NULL;
1691 struct extent_buffer *parent = NULL;
bb803951
CM
1692 int ret = 0;
1693 int wret;
1694 int pslot;
bb803951 1695 int orig_slot = path->slots[level];
79f95c82 1696 u64 orig_ptr;
bb803951
CM
1697
1698 if (level == 0)
1699 return 0;
1700
5f39d397 1701 mid = path->nodes[level];
b4ce94de 1702
bd681513
CM
1703 WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK &&
1704 path->locks[level] != BTRFS_WRITE_LOCK_BLOCKING);
7bb86316
CM
1705 WARN_ON(btrfs_header_generation(mid) != trans->transid);
1706
1d4f8a0c 1707 orig_ptr = btrfs_node_blockptr(mid, orig_slot);
79f95c82 1708
a05a9bb1 1709 if (level < BTRFS_MAX_LEVEL - 1) {
5f39d397 1710 parent = path->nodes[level + 1];
a05a9bb1
LZ
1711 pslot = path->slots[level + 1];
1712 }
bb803951 1713
40689478
CM
1714 /*
1715 * deal with the case where there is only one pointer in the root
1716 * by promoting the node below to a root
1717 */
5f39d397
CM
1718 if (!parent) {
1719 struct extent_buffer *child;
bb803951 1720
5f39d397 1721 if (btrfs_header_nritems(mid) != 1)
bb803951
CM
1722 return 0;
1723
1724 /* promote the child to a root */
5f39d397 1725 child = read_node_slot(root, mid, 0);
305a26af
MF
1726 if (!child) {
1727 ret = -EROFS;
1728 btrfs_std_error(root->fs_info, ret);
1729 goto enospc;
1730 }
1731
925baedd 1732 btrfs_tree_lock(child);
b4ce94de 1733 btrfs_set_lock_blocking(child);
9fa8cfe7 1734 ret = btrfs_cow_block(trans, root, child, mid, 0, &child);
f0486c68
YZ
1735 if (ret) {
1736 btrfs_tree_unlock(child);
1737 free_extent_buffer(child);
1738 goto enospc;
1739 }
2f375ab9 1740
ba1bfbd5 1741 tree_mod_log_free_eb(root->fs_info, root->node);
f230475e 1742 tree_mod_log_set_root_pointer(root, child);
240f62c8 1743 rcu_assign_pointer(root->node, child);
925baedd 1744
0b86a832 1745 add_root_to_dirty_list(root);
925baedd 1746 btrfs_tree_unlock(child);
b4ce94de 1747
925baedd 1748 path->locks[level] = 0;
bb803951 1749 path->nodes[level] = NULL;
5f39d397 1750 clean_tree_block(trans, root, mid);
925baedd 1751 btrfs_tree_unlock(mid);
bb803951 1752 /* once for the path */
5f39d397 1753 free_extent_buffer(mid);
f0486c68
YZ
1754
1755 root_sub_used(root, mid->len);
5581a51a 1756 btrfs_free_tree_block(trans, root, mid, 0, 1);
bb803951 1757 /* once for the root ptr */
3083ee2e 1758 free_extent_buffer_stale(mid);
f0486c68 1759 return 0;
bb803951 1760 }
5f39d397 1761 if (btrfs_header_nritems(mid) >
123abc88 1762 BTRFS_NODEPTRS_PER_BLOCK(root) / 4)
bb803951
CM
1763 return 0;
1764
5f39d397
CM
1765 left = read_node_slot(root, parent, pslot - 1);
1766 if (left) {
925baedd 1767 btrfs_tree_lock(left);
b4ce94de 1768 btrfs_set_lock_blocking(left);
5f39d397 1769 wret = btrfs_cow_block(trans, root, left,
9fa8cfe7 1770 parent, pslot - 1, &left);
54aa1f4d
CM
1771 if (wret) {
1772 ret = wret;
1773 goto enospc;
1774 }
2cc58cf2 1775 }
5f39d397
CM
1776 right = read_node_slot(root, parent, pslot + 1);
1777 if (right) {
925baedd 1778 btrfs_tree_lock(right);
b4ce94de 1779 btrfs_set_lock_blocking(right);
5f39d397 1780 wret = btrfs_cow_block(trans, root, right,
9fa8cfe7 1781 parent, pslot + 1, &right);
2cc58cf2
CM
1782 if (wret) {
1783 ret = wret;
1784 goto enospc;
1785 }
1786 }
1787
1788 /* first, try to make some room in the middle buffer */
5f39d397
CM
1789 if (left) {
1790 orig_slot += btrfs_header_nritems(left);
bce4eae9 1791 wret = push_node_left(trans, root, left, mid, 1);
79f95c82
CM
1792 if (wret < 0)
1793 ret = wret;
bb803951 1794 }
79f95c82
CM
1795
1796 /*
1797 * then try to empty the right most buffer into the middle
1798 */
5f39d397 1799 if (right) {
971a1f66 1800 wret = push_node_left(trans, root, mid, right, 1);
54aa1f4d 1801 if (wret < 0 && wret != -ENOSPC)
79f95c82 1802 ret = wret;
5f39d397 1803 if (btrfs_header_nritems(right) == 0) {
5f39d397 1804 clean_tree_block(trans, root, right);
925baedd 1805 btrfs_tree_unlock(right);
f3ea38da 1806 del_ptr(trans, root, path, level + 1, pslot + 1, 1);
f0486c68 1807 root_sub_used(root, right->len);
5581a51a 1808 btrfs_free_tree_block(trans, root, right, 0, 1);
3083ee2e 1809 free_extent_buffer_stale(right);
f0486c68 1810 right = NULL;
bb803951 1811 } else {
5f39d397
CM
1812 struct btrfs_disk_key right_key;
1813 btrfs_node_key(right, &right_key, 0);
f230475e
JS
1814 tree_mod_log_set_node_key(root->fs_info, parent,
1815 &right_key, pslot + 1, 0);
5f39d397
CM
1816 btrfs_set_node_key(parent, &right_key, pslot + 1);
1817 btrfs_mark_buffer_dirty(parent);
bb803951
CM
1818 }
1819 }
5f39d397 1820 if (btrfs_header_nritems(mid) == 1) {
79f95c82
CM
1821 /*
1822 * we're not allowed to leave a node with one item in the
1823 * tree during a delete. A deletion from lower in the tree
1824 * could try to delete the only pointer in this node.
1825 * So, pull some keys from the left.
1826 * There has to be a left pointer at this point because
1827 * otherwise we would have pulled some pointers from the
1828 * right
1829 */
305a26af
MF
1830 if (!left) {
1831 ret = -EROFS;
1832 btrfs_std_error(root->fs_info, ret);
1833 goto enospc;
1834 }
5f39d397 1835 wret = balance_node_right(trans, root, mid, left);
54aa1f4d 1836 if (wret < 0) {
79f95c82 1837 ret = wret;
54aa1f4d
CM
1838 goto enospc;
1839 }
bce4eae9
CM
1840 if (wret == 1) {
1841 wret = push_node_left(trans, root, left, mid, 1);
1842 if (wret < 0)
1843 ret = wret;
1844 }
79f95c82
CM
1845 BUG_ON(wret == 1);
1846 }
5f39d397 1847 if (btrfs_header_nritems(mid) == 0) {
5f39d397 1848 clean_tree_block(trans, root, mid);
925baedd 1849 btrfs_tree_unlock(mid);
f3ea38da 1850 del_ptr(trans, root, path, level + 1, pslot, 1);
f0486c68 1851 root_sub_used(root, mid->len);
5581a51a 1852 btrfs_free_tree_block(trans, root, mid, 0, 1);
3083ee2e 1853 free_extent_buffer_stale(mid);
f0486c68 1854 mid = NULL;
79f95c82
CM
1855 } else {
1856 /* update the parent key to reflect our changes */
5f39d397
CM
1857 struct btrfs_disk_key mid_key;
1858 btrfs_node_key(mid, &mid_key, 0);
f230475e
JS
1859 tree_mod_log_set_node_key(root->fs_info, parent, &mid_key,
1860 pslot, 0);
5f39d397
CM
1861 btrfs_set_node_key(parent, &mid_key, pslot);
1862 btrfs_mark_buffer_dirty(parent);
79f95c82 1863 }
bb803951 1864
79f95c82 1865 /* update the path */
5f39d397
CM
1866 if (left) {
1867 if (btrfs_header_nritems(left) > orig_slot) {
1868 extent_buffer_get(left);
925baedd 1869 /* left was locked after cow */
5f39d397 1870 path->nodes[level] = left;
bb803951
CM
1871 path->slots[level + 1] -= 1;
1872 path->slots[level] = orig_slot;
925baedd
CM
1873 if (mid) {
1874 btrfs_tree_unlock(mid);
5f39d397 1875 free_extent_buffer(mid);
925baedd 1876 }
bb803951 1877 } else {
5f39d397 1878 orig_slot -= btrfs_header_nritems(left);
bb803951
CM
1879 path->slots[level] = orig_slot;
1880 }
1881 }
79f95c82 1882 /* double check we haven't messed things up */
e20d96d6 1883 if (orig_ptr !=
5f39d397 1884 btrfs_node_blockptr(path->nodes[level], path->slots[level]))
79f95c82 1885 BUG();
54aa1f4d 1886enospc:
925baedd
CM
1887 if (right) {
1888 btrfs_tree_unlock(right);
5f39d397 1889 free_extent_buffer(right);
925baedd
CM
1890 }
1891 if (left) {
1892 if (path->nodes[level] != left)
1893 btrfs_tree_unlock(left);
5f39d397 1894 free_extent_buffer(left);
925baedd 1895 }
bb803951
CM
1896 return ret;
1897}
1898
d352ac68
CM
1899/* Node balancing for insertion. Here we only split or push nodes around
1900 * when they are completely full. This is also done top down, so we
1901 * have to be pessimistic.
1902 */
d397712b 1903static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
98ed5174
CM
1904 struct btrfs_root *root,
1905 struct btrfs_path *path, int level)
e66f709b 1906{
5f39d397
CM
1907 struct extent_buffer *right = NULL;
1908 struct extent_buffer *mid;
1909 struct extent_buffer *left = NULL;
1910 struct extent_buffer *parent = NULL;
e66f709b
CM
1911 int ret = 0;
1912 int wret;
1913 int pslot;
1914 int orig_slot = path->slots[level];
e66f709b
CM
1915
1916 if (level == 0)
1917 return 1;
1918
5f39d397 1919 mid = path->nodes[level];
7bb86316 1920 WARN_ON(btrfs_header_generation(mid) != trans->transid);
e66f709b 1921
a05a9bb1 1922 if (level < BTRFS_MAX_LEVEL - 1) {
5f39d397 1923 parent = path->nodes[level + 1];
a05a9bb1
LZ
1924 pslot = path->slots[level + 1];
1925 }
e66f709b 1926
5f39d397 1927 if (!parent)
e66f709b 1928 return 1;
e66f709b 1929
5f39d397 1930 left = read_node_slot(root, parent, pslot - 1);
e66f709b
CM
1931
1932 /* first, try to make some room in the middle buffer */
5f39d397 1933 if (left) {
e66f709b 1934 u32 left_nr;
925baedd
CM
1935
1936 btrfs_tree_lock(left);
b4ce94de
CM
1937 btrfs_set_lock_blocking(left);
1938
5f39d397 1939 left_nr = btrfs_header_nritems(left);
33ade1f8
CM
1940 if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(root) - 1) {
1941 wret = 1;
1942 } else {
5f39d397 1943 ret = btrfs_cow_block(trans, root, left, parent,
9fa8cfe7 1944 pslot - 1, &left);
54aa1f4d
CM
1945 if (ret)
1946 wret = 1;
1947 else {
54aa1f4d 1948 wret = push_node_left(trans, root,
971a1f66 1949 left, mid, 0);
54aa1f4d 1950 }
33ade1f8 1951 }
e66f709b
CM
1952 if (wret < 0)
1953 ret = wret;
1954 if (wret == 0) {
5f39d397 1955 struct btrfs_disk_key disk_key;
e66f709b 1956 orig_slot += left_nr;
5f39d397 1957 btrfs_node_key(mid, &disk_key, 0);
f230475e
JS
1958 tree_mod_log_set_node_key(root->fs_info, parent,
1959 &disk_key, pslot, 0);
5f39d397
CM
1960 btrfs_set_node_key(parent, &disk_key, pslot);
1961 btrfs_mark_buffer_dirty(parent);
1962 if (btrfs_header_nritems(left) > orig_slot) {
1963 path->nodes[level] = left;
e66f709b
CM
1964 path->slots[level + 1] -= 1;
1965 path->slots[level] = orig_slot;
925baedd 1966 btrfs_tree_unlock(mid);
5f39d397 1967 free_extent_buffer(mid);
e66f709b
CM
1968 } else {
1969 orig_slot -=
5f39d397 1970 btrfs_header_nritems(left);
e66f709b 1971 path->slots[level] = orig_slot;
925baedd 1972 btrfs_tree_unlock(left);
5f39d397 1973 free_extent_buffer(left);
e66f709b 1974 }
e66f709b
CM
1975 return 0;
1976 }
925baedd 1977 btrfs_tree_unlock(left);
5f39d397 1978 free_extent_buffer(left);
e66f709b 1979 }
925baedd 1980 right = read_node_slot(root, parent, pslot + 1);
e66f709b
CM
1981
1982 /*
1983 * then try to empty the right most buffer into the middle
1984 */
5f39d397 1985 if (right) {
33ade1f8 1986 u32 right_nr;
b4ce94de 1987
925baedd 1988 btrfs_tree_lock(right);
b4ce94de
CM
1989 btrfs_set_lock_blocking(right);
1990
5f39d397 1991 right_nr = btrfs_header_nritems(right);
33ade1f8
CM
1992 if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(root) - 1) {
1993 wret = 1;
1994 } else {
5f39d397
CM
1995 ret = btrfs_cow_block(trans, root, right,
1996 parent, pslot + 1,
9fa8cfe7 1997 &right);
54aa1f4d
CM
1998 if (ret)
1999 wret = 1;
2000 else {
54aa1f4d 2001 wret = balance_node_right(trans, root,
5f39d397 2002 right, mid);
54aa1f4d 2003 }
33ade1f8 2004 }
e66f709b
CM
2005 if (wret < 0)
2006 ret = wret;
2007 if (wret == 0) {
5f39d397
CM
2008 struct btrfs_disk_key disk_key;
2009
2010 btrfs_node_key(right, &disk_key, 0);
f230475e
JS
2011 tree_mod_log_set_node_key(root->fs_info, parent,
2012 &disk_key, pslot + 1, 0);
5f39d397
CM
2013 btrfs_set_node_key(parent, &disk_key, pslot + 1);
2014 btrfs_mark_buffer_dirty(parent);
2015
2016 if (btrfs_header_nritems(mid) <= orig_slot) {
2017 path->nodes[level] = right;
e66f709b
CM
2018 path->slots[level + 1] += 1;
2019 path->slots[level] = orig_slot -
5f39d397 2020 btrfs_header_nritems(mid);
925baedd 2021 btrfs_tree_unlock(mid);
5f39d397 2022 free_extent_buffer(mid);
e66f709b 2023 } else {
925baedd 2024 btrfs_tree_unlock(right);
5f39d397 2025 free_extent_buffer(right);
e66f709b 2026 }
e66f709b
CM
2027 return 0;
2028 }
925baedd 2029 btrfs_tree_unlock(right);
5f39d397 2030 free_extent_buffer(right);
e66f709b 2031 }
e66f709b
CM
2032 return 1;
2033}
2034
3c69faec 2035/*
d352ac68
CM
2036 * readahead one full node of leaves, finding things that are close
2037 * to the block in 'slot', and triggering ra on them.
3c69faec 2038 */
c8c42864
CM
2039static void reada_for_search(struct btrfs_root *root,
2040 struct btrfs_path *path,
2041 int level, int slot, u64 objectid)
3c69faec 2042{
5f39d397 2043 struct extent_buffer *node;
01f46658 2044 struct btrfs_disk_key disk_key;
3c69faec 2045 u32 nritems;
3c69faec 2046 u64 search;
a7175319 2047 u64 target;
6b80053d 2048 u64 nread = 0;
cb25c2ea 2049 u64 gen;
3c69faec 2050 int direction = path->reada;
5f39d397 2051 struct extent_buffer *eb;
6b80053d
CM
2052 u32 nr;
2053 u32 blocksize;
2054 u32 nscan = 0;
db94535d 2055
a6b6e75e 2056 if (level != 1)
6702ed49
CM
2057 return;
2058
2059 if (!path->nodes[level])
3c69faec
CM
2060 return;
2061
5f39d397 2062 node = path->nodes[level];
925baedd 2063
3c69faec 2064 search = btrfs_node_blockptr(node, slot);
6b80053d
CM
2065 blocksize = btrfs_level_size(root, level - 1);
2066 eb = btrfs_find_tree_block(root, search, blocksize);
5f39d397
CM
2067 if (eb) {
2068 free_extent_buffer(eb);
3c69faec
CM
2069 return;
2070 }
2071
a7175319 2072 target = search;
6b80053d 2073
5f39d397 2074 nritems = btrfs_header_nritems(node);
6b80053d 2075 nr = slot;
25b8b936 2076
d397712b 2077 while (1) {
6b80053d
CM
2078 if (direction < 0) {
2079 if (nr == 0)
2080 break;
2081 nr--;
2082 } else if (direction > 0) {
2083 nr++;
2084 if (nr >= nritems)
2085 break;
3c69faec 2086 }
01f46658
CM
2087 if (path->reada < 0 && objectid) {
2088 btrfs_node_key(node, &disk_key, nr);
2089 if (btrfs_disk_key_objectid(&disk_key) != objectid)
2090 break;
2091 }
6b80053d 2092 search = btrfs_node_blockptr(node, nr);
a7175319
CM
2093 if ((search <= target && target - search <= 65536) ||
2094 (search > target && search - target <= 65536)) {
cb25c2ea 2095 gen = btrfs_node_ptr_generation(node, nr);
cb25c2ea 2096 readahead_tree_block(root, search, blocksize, gen);
6b80053d
CM
2097 nread += blocksize;
2098 }
2099 nscan++;
a7175319 2100 if ((nread > 65536 || nscan > 32))
6b80053d 2101 break;
3c69faec
CM
2102 }
2103}
925baedd 2104
b4ce94de
CM
2105/*
2106 * returns -EAGAIN if it had to drop the path, or zero if everything was in
2107 * cache
2108 */
2109static noinline int reada_for_balance(struct btrfs_root *root,
2110 struct btrfs_path *path, int level)
2111{
2112 int slot;
2113 int nritems;
2114 struct extent_buffer *parent;
2115 struct extent_buffer *eb;
2116 u64 gen;
2117 u64 block1 = 0;
2118 u64 block2 = 0;
2119 int ret = 0;
2120 int blocksize;
2121
8c594ea8 2122 parent = path->nodes[level + 1];
b4ce94de
CM
2123 if (!parent)
2124 return 0;
2125
2126 nritems = btrfs_header_nritems(parent);
8c594ea8 2127 slot = path->slots[level + 1];
b4ce94de
CM
2128 blocksize = btrfs_level_size(root, level);
2129
2130 if (slot > 0) {
2131 block1 = btrfs_node_blockptr(parent, slot - 1);
2132 gen = btrfs_node_ptr_generation(parent, slot - 1);
2133 eb = btrfs_find_tree_block(root, block1, blocksize);
b9fab919
CM
2134 /*
2135 * if we get -eagain from btrfs_buffer_uptodate, we
2136 * don't want to return eagain here. That will loop
2137 * forever
2138 */
2139 if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
b4ce94de
CM
2140 block1 = 0;
2141 free_extent_buffer(eb);
2142 }
8c594ea8 2143 if (slot + 1 < nritems) {
b4ce94de
CM
2144 block2 = btrfs_node_blockptr(parent, slot + 1);
2145 gen = btrfs_node_ptr_generation(parent, slot + 1);
2146 eb = btrfs_find_tree_block(root, block2, blocksize);
b9fab919 2147 if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
b4ce94de
CM
2148 block2 = 0;
2149 free_extent_buffer(eb);
2150 }
2151 if (block1 || block2) {
2152 ret = -EAGAIN;
8c594ea8
CM
2153
2154 /* release the whole path */
b3b4aa74 2155 btrfs_release_path(path);
8c594ea8
CM
2156
2157 /* read the blocks */
b4ce94de
CM
2158 if (block1)
2159 readahead_tree_block(root, block1, blocksize, 0);
2160 if (block2)
2161 readahead_tree_block(root, block2, blocksize, 0);
2162
2163 if (block1) {
2164 eb = read_tree_block(root, block1, blocksize, 0);
2165 free_extent_buffer(eb);
2166 }
8c594ea8 2167 if (block2) {
b4ce94de
CM
2168 eb = read_tree_block(root, block2, blocksize, 0);
2169 free_extent_buffer(eb);
2170 }
2171 }
2172 return ret;
2173}
2174
2175
d352ac68 2176/*
d397712b
CM
2177 * when we walk down the tree, it is usually safe to unlock the higher layers
2178 * in the tree. The exceptions are when our path goes through slot 0, because
2179 * operations on the tree might require changing key pointers higher up in the
2180 * tree.
d352ac68 2181 *
d397712b
CM
2182 * callers might also have set path->keep_locks, which tells this code to keep
2183 * the lock if the path points to the last slot in the block. This is part of
2184 * walking through the tree, and selecting the next slot in the higher block.
d352ac68 2185 *
d397712b
CM
2186 * lowest_unlock sets the lowest level in the tree we're allowed to unlock. so
2187 * if lowest_unlock is 1, level 0 won't be unlocked
d352ac68 2188 */
e02119d5 2189static noinline void unlock_up(struct btrfs_path *path, int level,
f7c79f30
CM
2190 int lowest_unlock, int min_write_lock_level,
2191 int *write_lock_level)
925baedd
CM
2192{
2193 int i;
2194 int skip_level = level;
051e1b9f 2195 int no_skips = 0;
925baedd
CM
2196 struct extent_buffer *t;
2197
2198 for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2199 if (!path->nodes[i])
2200 break;
2201 if (!path->locks[i])
2202 break;
051e1b9f 2203 if (!no_skips && path->slots[i] == 0) {
925baedd
CM
2204 skip_level = i + 1;
2205 continue;
2206 }
051e1b9f 2207 if (!no_skips && path->keep_locks) {
925baedd
CM
2208 u32 nritems;
2209 t = path->nodes[i];
2210 nritems = btrfs_header_nritems(t);
051e1b9f 2211 if (nritems < 1 || path->slots[i] >= nritems - 1) {
925baedd
CM
2212 skip_level = i + 1;
2213 continue;
2214 }
2215 }
051e1b9f
CM
2216 if (skip_level < i && i >= lowest_unlock)
2217 no_skips = 1;
2218
925baedd
CM
2219 t = path->nodes[i];
2220 if (i >= lowest_unlock && i > skip_level && path->locks[i]) {
bd681513 2221 btrfs_tree_unlock_rw(t, path->locks[i]);
925baedd 2222 path->locks[i] = 0;
f7c79f30
CM
2223 if (write_lock_level &&
2224 i > min_write_lock_level &&
2225 i <= *write_lock_level) {
2226 *write_lock_level = i - 1;
2227 }
925baedd
CM
2228 }
2229 }
2230}
2231
b4ce94de
CM
2232/*
2233 * This releases any locks held in the path starting at level and
2234 * going all the way up to the root.
2235 *
2236 * btrfs_search_slot will keep the lock held on higher nodes in a few
2237 * corner cases, such as COW of the block at slot zero in the node. This
2238 * ignores those rules, and it should only be called when there are no
2239 * more updates to be done higher up in the tree.
2240 */
2241noinline void btrfs_unlock_up_safe(struct btrfs_path *path, int level)
2242{
2243 int i;
2244
5d4f98a2 2245 if (path->keep_locks)
b4ce94de
CM
2246 return;
2247
2248 for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2249 if (!path->nodes[i])
12f4dacc 2250 continue;
b4ce94de 2251 if (!path->locks[i])
12f4dacc 2252 continue;
bd681513 2253 btrfs_tree_unlock_rw(path->nodes[i], path->locks[i]);
b4ce94de
CM
2254 path->locks[i] = 0;
2255 }
2256}
2257
c8c42864
CM
2258/*
2259 * helper function for btrfs_search_slot. The goal is to find a block
2260 * in cache without setting the path to blocking. If we find the block
2261 * we return zero and the path is unchanged.
2262 *
2263 * If we can't find the block, we set the path blocking and do some
2264 * reada. -EAGAIN is returned and the search must be repeated.
2265 */
2266static int
2267read_block_for_search(struct btrfs_trans_handle *trans,
2268 struct btrfs_root *root, struct btrfs_path *p,
2269 struct extent_buffer **eb_ret, int level, int slot,
5d9e75c4 2270 struct btrfs_key *key, u64 time_seq)
c8c42864
CM
2271{
2272 u64 blocknr;
2273 u64 gen;
2274 u32 blocksize;
2275 struct extent_buffer *b = *eb_ret;
2276 struct extent_buffer *tmp;
76a05b35 2277 int ret;
c8c42864
CM
2278
2279 blocknr = btrfs_node_blockptr(b, slot);
2280 gen = btrfs_node_ptr_generation(b, slot);
2281 blocksize = btrfs_level_size(root, level - 1);
2282
2283 tmp = btrfs_find_tree_block(root, blocknr, blocksize);
cb44921a 2284 if (tmp) {
b9fab919
CM
2285 /* first we do an atomic uptodate check */
2286 if (btrfs_buffer_uptodate(tmp, 0, 1) > 0) {
2287 if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
cb44921a
CM
2288 /*
2289 * we found an up to date block without
2290 * sleeping, return
2291 * right away
2292 */
2293 *eb_ret = tmp;
2294 return 0;
2295 }
2296 /* the pages were up to date, but we failed
2297 * the generation number check. Do a full
2298 * read for the generation number that is correct.
2299 * We must do this without dropping locks so
2300 * we can trust our generation number
2301 */
2302 free_extent_buffer(tmp);
bd681513
CM
2303 btrfs_set_path_blocking(p);
2304
b9fab919 2305 /* now we're allowed to do a blocking uptodate check */
cb44921a 2306 tmp = read_tree_block(root, blocknr, blocksize, gen);
b9fab919 2307 if (tmp && btrfs_buffer_uptodate(tmp, gen, 0) > 0) {
cb44921a
CM
2308 *eb_ret = tmp;
2309 return 0;
2310 }
2311 free_extent_buffer(tmp);
b3b4aa74 2312 btrfs_release_path(p);
cb44921a
CM
2313 return -EIO;
2314 }
c8c42864
CM
2315 }
2316
2317 /*
2318 * reduce lock contention at high levels
2319 * of the btree by dropping locks before
76a05b35
CM
2320 * we read. Don't release the lock on the current
2321 * level because we need to walk this node to figure
2322 * out which blocks to read.
c8c42864 2323 */
8c594ea8
CM
2324 btrfs_unlock_up_safe(p, level + 1);
2325 btrfs_set_path_blocking(p);
2326
cb44921a 2327 free_extent_buffer(tmp);
c8c42864
CM
2328 if (p->reada)
2329 reada_for_search(root, p, level, slot, key->objectid);
2330
b3b4aa74 2331 btrfs_release_path(p);
76a05b35
CM
2332
2333 ret = -EAGAIN;
5bdd3536 2334 tmp = read_tree_block(root, blocknr, blocksize, 0);
76a05b35
CM
2335 if (tmp) {
2336 /*
2337 * If the read above didn't mark this buffer up to date,
2338 * it will never end up being up to date. Set ret to EIO now
2339 * and give up so that our caller doesn't loop forever
2340 * on our EAGAINs.
2341 */
b9fab919 2342 if (!btrfs_buffer_uptodate(tmp, 0, 0))
76a05b35 2343 ret = -EIO;
c8c42864 2344 free_extent_buffer(tmp);
76a05b35
CM
2345 }
2346 return ret;
c8c42864
CM
2347}
2348
2349/*
2350 * helper function for btrfs_search_slot. This does all of the checks
2351 * for node-level blocks and does any balancing required based on
2352 * the ins_len.
2353 *
2354 * If no extra work was required, zero is returned. If we had to
2355 * drop the path, -EAGAIN is returned and btrfs_search_slot must
2356 * start over
2357 */
2358static int
2359setup_nodes_for_search(struct btrfs_trans_handle *trans,
2360 struct btrfs_root *root, struct btrfs_path *p,
bd681513
CM
2361 struct extent_buffer *b, int level, int ins_len,
2362 int *write_lock_level)
c8c42864
CM
2363{
2364 int ret;
2365 if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
2366 BTRFS_NODEPTRS_PER_BLOCK(root) - 3) {
2367 int sret;
2368
bd681513
CM
2369 if (*write_lock_level < level + 1) {
2370 *write_lock_level = level + 1;
2371 btrfs_release_path(p);
2372 goto again;
2373 }
2374
c8c42864
CM
2375 sret = reada_for_balance(root, p, level);
2376 if (sret)
2377 goto again;
2378
2379 btrfs_set_path_blocking(p);
2380 sret = split_node(trans, root, p, level);
bd681513 2381 btrfs_clear_path_blocking(p, NULL, 0);
c8c42864
CM
2382
2383 BUG_ON(sret > 0);
2384 if (sret) {
2385 ret = sret;
2386 goto done;
2387 }
2388 b = p->nodes[level];
2389 } else if (ins_len < 0 && btrfs_header_nritems(b) <
cfbb9308 2390 BTRFS_NODEPTRS_PER_BLOCK(root) / 2) {
c8c42864
CM
2391 int sret;
2392
bd681513
CM
2393 if (*write_lock_level < level + 1) {
2394 *write_lock_level = level + 1;
2395 btrfs_release_path(p);
2396 goto again;
2397 }
2398
c8c42864
CM
2399 sret = reada_for_balance(root, p, level);
2400 if (sret)
2401 goto again;
2402
2403 btrfs_set_path_blocking(p);
2404 sret = balance_level(trans, root, p, level);
bd681513 2405 btrfs_clear_path_blocking(p, NULL, 0);
c8c42864
CM
2406
2407 if (sret) {
2408 ret = sret;
2409 goto done;
2410 }
2411 b = p->nodes[level];
2412 if (!b) {
b3b4aa74 2413 btrfs_release_path(p);
c8c42864
CM
2414 goto again;
2415 }
2416 BUG_ON(btrfs_header_nritems(b) == 1);
2417 }
2418 return 0;
2419
2420again:
2421 ret = -EAGAIN;
2422done:
2423 return ret;
2424}
2425
74123bd7
CM
2426/*
2427 * look for key in the tree. path is filled in with nodes along the way
2428 * if key is found, we return zero and you can find the item in the leaf
2429 * level of the path (level 0)
2430 *
2431 * If the key isn't found, the path points to the slot where it should
aa5d6bed
CM
2432 * be inserted, and 1 is returned. If there are other errors during the
2433 * search a negative error number is returned.
97571fd0
CM
2434 *
2435 * if ins_len > 0, nodes and leaves will be split as we walk down the
2436 * tree. if ins_len < 0, nodes will be merged as we walk down the tree (if
2437 * possible)
74123bd7 2438 */
e089f05c
CM
2439int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root
2440 *root, struct btrfs_key *key, struct btrfs_path *p, int
2441 ins_len, int cow)
be0e5c09 2442{
5f39d397 2443 struct extent_buffer *b;
be0e5c09
CM
2444 int slot;
2445 int ret;
33c66f43 2446 int err;
be0e5c09 2447 int level;
925baedd 2448 int lowest_unlock = 1;
bd681513
CM
2449 int root_lock;
2450 /* everything at write_lock_level or lower must be write locked */
2451 int write_lock_level = 0;
9f3a7427 2452 u8 lowest_level = 0;
f7c79f30 2453 int min_write_lock_level;
9f3a7427 2454
6702ed49 2455 lowest_level = p->lowest_level;
323ac95b 2456 WARN_ON(lowest_level && ins_len > 0);
22b0ebda 2457 WARN_ON(p->nodes[0] != NULL);
25179201 2458
bd681513 2459 if (ins_len < 0) {
925baedd 2460 lowest_unlock = 2;
65b51a00 2461
bd681513
CM
2462 /* when we are removing items, we might have to go up to level
2463 * two as we update tree pointers Make sure we keep write
2464 * for those levels as well
2465 */
2466 write_lock_level = 2;
2467 } else if (ins_len > 0) {
2468 /*
2469 * for inserting items, make sure we have a write lock on
2470 * level 1 so we can update keys
2471 */
2472 write_lock_level = 1;
2473 }
2474
2475 if (!cow)
2476 write_lock_level = -1;
2477
2478 if (cow && (p->keep_locks || p->lowest_level))
2479 write_lock_level = BTRFS_MAX_LEVEL;
2480
f7c79f30
CM
2481 min_write_lock_level = write_lock_level;
2482
bb803951 2483again:
bd681513
CM
2484 /*
2485 * we try very hard to do read locks on the root
2486 */
2487 root_lock = BTRFS_READ_LOCK;
2488 level = 0;
5d4f98a2 2489 if (p->search_commit_root) {
bd681513
CM
2490 /*
2491 * the commit roots are read only
2492 * so we always do read locks
2493 */
5d4f98a2
YZ
2494 b = root->commit_root;
2495 extent_buffer_get(b);
bd681513 2496 level = btrfs_header_level(b);
5d4f98a2 2497 if (!p->skip_locking)
bd681513 2498 btrfs_tree_read_lock(b);
5d4f98a2 2499 } else {
bd681513 2500 if (p->skip_locking) {
5d4f98a2 2501 b = btrfs_root_node(root);
bd681513
CM
2502 level = btrfs_header_level(b);
2503 } else {
2504 /* we don't know the level of the root node
2505 * until we actually have it read locked
2506 */
2507 b = btrfs_read_lock_root_node(root);
2508 level = btrfs_header_level(b);
2509 if (level <= write_lock_level) {
2510 /* whoops, must trade for write lock */
2511 btrfs_tree_read_unlock(b);
2512 free_extent_buffer(b);
2513 b = btrfs_lock_root_node(root);
2514 root_lock = BTRFS_WRITE_LOCK;
2515
2516 /* the level might have changed, check again */
2517 level = btrfs_header_level(b);
2518 }
2519 }
5d4f98a2 2520 }
bd681513
CM
2521 p->nodes[level] = b;
2522 if (!p->skip_locking)
2523 p->locks[level] = root_lock;
925baedd 2524
eb60ceac 2525 while (b) {
5f39d397 2526 level = btrfs_header_level(b);
65b51a00
CM
2527
2528 /*
2529 * setup the path here so we can release it under lock
2530 * contention with the cow code
2531 */
02217ed2 2532 if (cow) {
c8c42864
CM
2533 /*
2534 * if we don't really need to cow this block
2535 * then we don't want to set the path blocking,
2536 * so we test it here
2537 */
5d4f98a2 2538 if (!should_cow_block(trans, root, b))
65b51a00 2539 goto cow_done;
5d4f98a2 2540
b4ce94de
CM
2541 btrfs_set_path_blocking(p);
2542
bd681513
CM
2543 /*
2544 * must have write locks on this node and the
2545 * parent
2546 */
2547 if (level + 1 > write_lock_level) {
2548 write_lock_level = level + 1;
2549 btrfs_release_path(p);
2550 goto again;
2551 }
2552
33c66f43
YZ
2553 err = btrfs_cow_block(trans, root, b,
2554 p->nodes[level + 1],
2555 p->slots[level + 1], &b);
2556 if (err) {
33c66f43 2557 ret = err;
65b51a00 2558 goto done;
54aa1f4d 2559 }
02217ed2 2560 }
65b51a00 2561cow_done:
02217ed2 2562 BUG_ON(!cow && ins_len);
65b51a00 2563
eb60ceac 2564 p->nodes[level] = b;
bd681513 2565 btrfs_clear_path_blocking(p, NULL, 0);
b4ce94de
CM
2566
2567 /*
2568 * we have a lock on b and as long as we aren't changing
2569 * the tree, there is no way to for the items in b to change.
2570 * It is safe to drop the lock on our parent before we
2571 * go through the expensive btree search on b.
2572 *
2573 * If cow is true, then we might be changing slot zero,
2574 * which may require changing the parent. So, we can't
2575 * drop the lock until after we know which slot we're
2576 * operating on.
2577 */
2578 if (!cow)
2579 btrfs_unlock_up_safe(p, level + 1);
2580
5f39d397 2581 ret = bin_search(b, key, level, &slot);
b4ce94de 2582
5f39d397 2583 if (level != 0) {
33c66f43
YZ
2584 int dec = 0;
2585 if (ret && slot > 0) {
2586 dec = 1;
be0e5c09 2587 slot -= 1;
33c66f43 2588 }
be0e5c09 2589 p->slots[level] = slot;
33c66f43 2590 err = setup_nodes_for_search(trans, root, p, b, level,
bd681513 2591 ins_len, &write_lock_level);
33c66f43 2592 if (err == -EAGAIN)
c8c42864 2593 goto again;
33c66f43
YZ
2594 if (err) {
2595 ret = err;
c8c42864 2596 goto done;
33c66f43 2597 }
c8c42864
CM
2598 b = p->nodes[level];
2599 slot = p->slots[level];
b4ce94de 2600
bd681513
CM
2601 /*
2602 * slot 0 is special, if we change the key
2603 * we have to update the parent pointer
2604 * which means we must have a write lock
2605 * on the parent
2606 */
2607 if (slot == 0 && cow &&
2608 write_lock_level < level + 1) {
2609 write_lock_level = level + 1;
2610 btrfs_release_path(p);
2611 goto again;
2612 }
2613
f7c79f30
CM
2614 unlock_up(p, level, lowest_unlock,
2615 min_write_lock_level, &write_lock_level);
f9efa9c7 2616
925baedd 2617 if (level == lowest_level) {
33c66f43
YZ
2618 if (dec)
2619 p->slots[level]++;
5b21f2ed 2620 goto done;
925baedd 2621 }
ca7a79ad 2622
33c66f43 2623 err = read_block_for_search(trans, root, p,
5d9e75c4 2624 &b, level, slot, key, 0);
33c66f43 2625 if (err == -EAGAIN)
c8c42864 2626 goto again;
33c66f43
YZ
2627 if (err) {
2628 ret = err;
76a05b35 2629 goto done;
33c66f43 2630 }
76a05b35 2631
b4ce94de 2632 if (!p->skip_locking) {
bd681513
CM
2633 level = btrfs_header_level(b);
2634 if (level <= write_lock_level) {
2635 err = btrfs_try_tree_write_lock(b);
2636 if (!err) {
2637 btrfs_set_path_blocking(p);
2638 btrfs_tree_lock(b);
2639 btrfs_clear_path_blocking(p, b,
2640 BTRFS_WRITE_LOCK);
2641 }
2642 p->locks[level] = BTRFS_WRITE_LOCK;
2643 } else {
2644 err = btrfs_try_tree_read_lock(b);
2645 if (!err) {
2646 btrfs_set_path_blocking(p);
2647 btrfs_tree_read_lock(b);
2648 btrfs_clear_path_blocking(p, b,
2649 BTRFS_READ_LOCK);
2650 }
2651 p->locks[level] = BTRFS_READ_LOCK;
b4ce94de 2652 }
bd681513 2653 p->nodes[level] = b;
b4ce94de 2654 }
be0e5c09
CM
2655 } else {
2656 p->slots[level] = slot;
87b29b20
YZ
2657 if (ins_len > 0 &&
2658 btrfs_leaf_free_space(root, b) < ins_len) {
bd681513
CM
2659 if (write_lock_level < 1) {
2660 write_lock_level = 1;
2661 btrfs_release_path(p);
2662 goto again;
2663 }
2664
b4ce94de 2665 btrfs_set_path_blocking(p);
33c66f43
YZ
2666 err = split_leaf(trans, root, key,
2667 p, ins_len, ret == 0);
bd681513 2668 btrfs_clear_path_blocking(p, NULL, 0);
b4ce94de 2669
33c66f43
YZ
2670 BUG_ON(err > 0);
2671 if (err) {
2672 ret = err;
65b51a00
CM
2673 goto done;
2674 }
5c680ed6 2675 }
459931ec 2676 if (!p->search_for_split)
f7c79f30
CM
2677 unlock_up(p, level, lowest_unlock,
2678 min_write_lock_level, &write_lock_level);
65b51a00 2679 goto done;
be0e5c09
CM
2680 }
2681 }
65b51a00
CM
2682 ret = 1;
2683done:
b4ce94de
CM
2684 /*
2685 * we don't really know what they plan on doing with the path
2686 * from here on, so for now just mark it as blocking
2687 */
b9473439
CM
2688 if (!p->leave_spinning)
2689 btrfs_set_path_blocking(p);
76a05b35 2690 if (ret < 0)
b3b4aa74 2691 btrfs_release_path(p);
65b51a00 2692 return ret;
be0e5c09
CM
2693}
2694
5d9e75c4
JS
2695/*
2696 * Like btrfs_search_slot, this looks for a key in the given tree. It uses the
2697 * current state of the tree together with the operations recorded in the tree
2698 * modification log to search for the key in a previous version of this tree, as
2699 * denoted by the time_seq parameter.
2700 *
2701 * Naturally, there is no support for insert, delete or cow operations.
2702 *
2703 * The resulting path and return value will be set up as if we called
2704 * btrfs_search_slot at that point in time with ins_len and cow both set to 0.
2705 */
2706int btrfs_search_old_slot(struct btrfs_root *root, struct btrfs_key *key,
2707 struct btrfs_path *p, u64 time_seq)
2708{
2709 struct extent_buffer *b;
2710 int slot;
2711 int ret;
2712 int err;
2713 int level;
2714 int lowest_unlock = 1;
2715 u8 lowest_level = 0;
2716
2717 lowest_level = p->lowest_level;
2718 WARN_ON(p->nodes[0] != NULL);
2719
2720 if (p->search_commit_root) {
2721 BUG_ON(time_seq);
2722 return btrfs_search_slot(NULL, root, key, p, 0, 0);
2723 }
2724
2725again:
5d9e75c4 2726 b = get_old_root(root, time_seq);
5d9e75c4 2727 level = btrfs_header_level(b);
5d9e75c4
JS
2728 p->locks[level] = BTRFS_READ_LOCK;
2729
2730 while (b) {
2731 level = btrfs_header_level(b);
2732 p->nodes[level] = b;
2733 btrfs_clear_path_blocking(p, NULL, 0);
2734
2735 /*
2736 * we have a lock on b and as long as we aren't changing
2737 * the tree, there is no way to for the items in b to change.
2738 * It is safe to drop the lock on our parent before we
2739 * go through the expensive btree search on b.
2740 */
2741 btrfs_unlock_up_safe(p, level + 1);
2742
2743 ret = bin_search(b, key, level, &slot);
2744
2745 if (level != 0) {
2746 int dec = 0;
2747 if (ret && slot > 0) {
2748 dec = 1;
2749 slot -= 1;
2750 }
2751 p->slots[level] = slot;
2752 unlock_up(p, level, lowest_unlock, 0, NULL);
2753
2754 if (level == lowest_level) {
2755 if (dec)
2756 p->slots[level]++;
2757 goto done;
2758 }
2759
2760 err = read_block_for_search(NULL, root, p, &b, level,
2761 slot, key, time_seq);
2762 if (err == -EAGAIN)
2763 goto again;
2764 if (err) {
2765 ret = err;
2766 goto done;
2767 }
2768
2769 level = btrfs_header_level(b);
2770 err = btrfs_try_tree_read_lock(b);
2771 if (!err) {
2772 btrfs_set_path_blocking(p);
2773 btrfs_tree_read_lock(b);
2774 btrfs_clear_path_blocking(p, b,
2775 BTRFS_READ_LOCK);
2776 }
2777 p->locks[level] = BTRFS_READ_LOCK;
2778 p->nodes[level] = b;
2779 b = tree_mod_log_rewind(root->fs_info, b, time_seq);
2780 if (b != p->nodes[level]) {
2781 btrfs_tree_unlock_rw(p->nodes[level],
2782 p->locks[level]);
2783 p->locks[level] = 0;
2784 p->nodes[level] = b;
2785 }
2786 } else {
2787 p->slots[level] = slot;
2788 unlock_up(p, level, lowest_unlock, 0, NULL);
2789 goto done;
2790 }
2791 }
2792 ret = 1;
2793done:
2794 if (!p->leave_spinning)
2795 btrfs_set_path_blocking(p);
2796 if (ret < 0)
2797 btrfs_release_path(p);
2798
2799 return ret;
2800}
2801
2f38b3e1
AJ
2802/*
2803 * helper to use instead of search slot if no exact match is needed but
2804 * instead the next or previous item should be returned.
2805 * When find_higher is true, the next higher item is returned, the next lower
2806 * otherwise.
2807 * When return_any and find_higher are both true, and no higher item is found,
2808 * return the next lower instead.
2809 * When return_any is true and find_higher is false, and no lower item is found,
2810 * return the next higher instead.
2811 * It returns 0 if any item is found, 1 if none is found (tree empty), and
2812 * < 0 on error
2813 */
2814int btrfs_search_slot_for_read(struct btrfs_root *root,
2815 struct btrfs_key *key, struct btrfs_path *p,
2816 int find_higher, int return_any)
2817{
2818 int ret;
2819 struct extent_buffer *leaf;
2820
2821again:
2822 ret = btrfs_search_slot(NULL, root, key, p, 0, 0);
2823 if (ret <= 0)
2824 return ret;
2825 /*
2826 * a return value of 1 means the path is at the position where the
2827 * item should be inserted. Normally this is the next bigger item,
2828 * but in case the previous item is the last in a leaf, path points
2829 * to the first free slot in the previous leaf, i.e. at an invalid
2830 * item.
2831 */
2832 leaf = p->nodes[0];
2833
2834 if (find_higher) {
2835 if (p->slots[0] >= btrfs_header_nritems(leaf)) {
2836 ret = btrfs_next_leaf(root, p);
2837 if (ret <= 0)
2838 return ret;
2839 if (!return_any)
2840 return 1;
2841 /*
2842 * no higher item found, return the next
2843 * lower instead
2844 */
2845 return_any = 0;
2846 find_higher = 0;
2847 btrfs_release_path(p);
2848 goto again;
2849 }
2850 } else {
e6793769
AJ
2851 if (p->slots[0] == 0) {
2852 ret = btrfs_prev_leaf(root, p);
2853 if (ret < 0)
2854 return ret;
2855 if (!ret) {
2856 p->slots[0] = btrfs_header_nritems(leaf) - 1;
2857 return 0;
2f38b3e1 2858 }
e6793769
AJ
2859 if (!return_any)
2860 return 1;
2861 /*
2862 * no lower item found, return the next
2863 * higher instead
2864 */
2865 return_any = 0;
2866 find_higher = 1;
2867 btrfs_release_path(p);
2868 goto again;
2869 } else {
2f38b3e1
AJ
2870 --p->slots[0];
2871 }
2872 }
2873 return 0;
2874}
2875
74123bd7
CM
2876/*
2877 * adjust the pointers going up the tree, starting at level
2878 * making sure the right key of each node is points to 'key'.
2879 * This is used after shifting pointers to the left, so it stops
2880 * fixing up pointers when a given leaf/node is not in slot 0 of the
2881 * higher levels
aa5d6bed 2882 *
74123bd7 2883 */
143bede5
JM
2884static void fixup_low_keys(struct btrfs_trans_handle *trans,
2885 struct btrfs_root *root, struct btrfs_path *path,
2886 struct btrfs_disk_key *key, int level)
be0e5c09
CM
2887{
2888 int i;
5f39d397
CM
2889 struct extent_buffer *t;
2890
234b63a0 2891 for (i = level; i < BTRFS_MAX_LEVEL; i++) {
be0e5c09 2892 int tslot = path->slots[i];
eb60ceac 2893 if (!path->nodes[i])
be0e5c09 2894 break;
5f39d397 2895 t = path->nodes[i];
f230475e 2896 tree_mod_log_set_node_key(root->fs_info, t, key, tslot, 1);
5f39d397 2897 btrfs_set_node_key(t, key, tslot);
d6025579 2898 btrfs_mark_buffer_dirty(path->nodes[i]);
be0e5c09
CM
2899 if (tslot != 0)
2900 break;
2901 }
2902}
2903
31840ae1
ZY
2904/*
2905 * update item key.
2906 *
2907 * This function isn't completely safe. It's the caller's responsibility
2908 * that the new key won't break the order
2909 */
143bede5
JM
2910void btrfs_set_item_key_safe(struct btrfs_trans_handle *trans,
2911 struct btrfs_root *root, struct btrfs_path *path,
2912 struct btrfs_key *new_key)
31840ae1
ZY
2913{
2914 struct btrfs_disk_key disk_key;
2915 struct extent_buffer *eb;
2916 int slot;
2917
2918 eb = path->nodes[0];
2919 slot = path->slots[0];
2920 if (slot > 0) {
2921 btrfs_item_key(eb, &disk_key, slot - 1);
143bede5 2922 BUG_ON(comp_keys(&disk_key, new_key) >= 0);
31840ae1
ZY
2923 }
2924 if (slot < btrfs_header_nritems(eb) - 1) {
2925 btrfs_item_key(eb, &disk_key, slot + 1);
143bede5 2926 BUG_ON(comp_keys(&disk_key, new_key) <= 0);
31840ae1
ZY
2927 }
2928
2929 btrfs_cpu_key_to_disk(&disk_key, new_key);
2930 btrfs_set_item_key(eb, &disk_key, slot);
2931 btrfs_mark_buffer_dirty(eb);
2932 if (slot == 0)
2933 fixup_low_keys(trans, root, path, &disk_key, 1);
31840ae1
ZY
2934}
2935
74123bd7
CM
2936/*
2937 * try to push data from one node into the next node left in the
79f95c82 2938 * tree.
aa5d6bed
CM
2939 *
2940 * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
2941 * error, and > 0 if there was no room in the left hand block.
74123bd7 2942 */
98ed5174
CM
2943static int push_node_left(struct btrfs_trans_handle *trans,
2944 struct btrfs_root *root, struct extent_buffer *dst,
971a1f66 2945 struct extent_buffer *src, int empty)
be0e5c09 2946{
be0e5c09 2947 int push_items = 0;
bb803951
CM
2948 int src_nritems;
2949 int dst_nritems;
aa5d6bed 2950 int ret = 0;
be0e5c09 2951
5f39d397
CM
2952 src_nritems = btrfs_header_nritems(src);
2953 dst_nritems = btrfs_header_nritems(dst);
123abc88 2954 push_items = BTRFS_NODEPTRS_PER_BLOCK(root) - dst_nritems;
7bb86316
CM
2955 WARN_ON(btrfs_header_generation(src) != trans->transid);
2956 WARN_ON(btrfs_header_generation(dst) != trans->transid);
54aa1f4d 2957
bce4eae9 2958 if (!empty && src_nritems <= 8)
971a1f66
CM
2959 return 1;
2960
d397712b 2961 if (push_items <= 0)
be0e5c09
CM
2962 return 1;
2963
bce4eae9 2964 if (empty) {
971a1f66 2965 push_items = min(src_nritems, push_items);
bce4eae9
CM
2966 if (push_items < src_nritems) {
2967 /* leave at least 8 pointers in the node if
2968 * we aren't going to empty it
2969 */
2970 if (src_nritems - push_items < 8) {
2971 if (push_items <= 8)
2972 return 1;
2973 push_items -= 8;
2974 }
2975 }
2976 } else
2977 push_items = min(src_nritems - 8, push_items);
79f95c82 2978
f230475e
JS
2979 tree_mod_log_eb_copy(root->fs_info, dst, src, dst_nritems, 0,
2980 push_items);
5f39d397
CM
2981 copy_extent_buffer(dst, src,
2982 btrfs_node_key_ptr_offset(dst_nritems),
2983 btrfs_node_key_ptr_offset(0),
d397712b 2984 push_items * sizeof(struct btrfs_key_ptr));
5f39d397 2985
bb803951 2986 if (push_items < src_nritems) {
57911b8b
JS
2987 /*
2988 * don't call tree_mod_log_eb_move here, key removal was already
2989 * fully logged by tree_mod_log_eb_copy above.
2990 */
5f39d397
CM
2991 memmove_extent_buffer(src, btrfs_node_key_ptr_offset(0),
2992 btrfs_node_key_ptr_offset(push_items),
2993 (src_nritems - push_items) *
2994 sizeof(struct btrfs_key_ptr));
2995 }
2996 btrfs_set_header_nritems(src, src_nritems - push_items);
2997 btrfs_set_header_nritems(dst, dst_nritems + push_items);
2998 btrfs_mark_buffer_dirty(src);
2999 btrfs_mark_buffer_dirty(dst);
31840ae1 3000
79f95c82
CM
3001 return ret;
3002}
3003
3004/*
3005 * try to push data from one node into the next node right in the
3006 * tree.
3007 *
3008 * returns 0 if some ptrs were pushed, < 0 if there was some horrible
3009 * error, and > 0 if there was no room in the right hand block.
3010 *
3011 * this will only push up to 1/2 the contents of the left node over
3012 */
5f39d397
CM
3013static int balance_node_right(struct btrfs_trans_handle *trans,
3014 struct btrfs_root *root,
3015 struct extent_buffer *dst,
3016 struct extent_buffer *src)
79f95c82 3017{
79f95c82
CM
3018 int push_items = 0;
3019 int max_push;
3020 int src_nritems;
3021 int dst_nritems;
3022 int ret = 0;
79f95c82 3023
7bb86316
CM
3024 WARN_ON(btrfs_header_generation(src) != trans->transid);
3025 WARN_ON(btrfs_header_generation(dst) != trans->transid);
3026
5f39d397
CM
3027 src_nritems = btrfs_header_nritems(src);
3028 dst_nritems = btrfs_header_nritems(dst);
123abc88 3029 push_items = BTRFS_NODEPTRS_PER_BLOCK(root) - dst_nritems;
d397712b 3030 if (push_items <= 0)
79f95c82 3031 return 1;
bce4eae9 3032
d397712b 3033 if (src_nritems < 4)
bce4eae9 3034 return 1;
79f95c82
CM
3035
3036 max_push = src_nritems / 2 + 1;
3037 /* don't try to empty the node */
d397712b 3038 if (max_push >= src_nritems)
79f95c82 3039 return 1;
252c38f0 3040
79f95c82
CM
3041 if (max_push < push_items)
3042 push_items = max_push;
3043
f230475e 3044 tree_mod_log_eb_move(root->fs_info, dst, push_items, 0, dst_nritems);
5f39d397
CM
3045 memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(push_items),
3046 btrfs_node_key_ptr_offset(0),
3047 (dst_nritems) *
3048 sizeof(struct btrfs_key_ptr));
d6025579 3049
f230475e
JS
3050 tree_mod_log_eb_copy(root->fs_info, dst, src, 0,
3051 src_nritems - push_items, push_items);
5f39d397
CM
3052 copy_extent_buffer(dst, src,
3053 btrfs_node_key_ptr_offset(0),
3054 btrfs_node_key_ptr_offset(src_nritems - push_items),
d397712b 3055 push_items * sizeof(struct btrfs_key_ptr));
79f95c82 3056
5f39d397
CM
3057 btrfs_set_header_nritems(src, src_nritems - push_items);
3058 btrfs_set_header_nritems(dst, dst_nritems + push_items);
79f95c82 3059
5f39d397
CM
3060 btrfs_mark_buffer_dirty(src);
3061 btrfs_mark_buffer_dirty(dst);
31840ae1 3062
aa5d6bed 3063 return ret;
be0e5c09
CM
3064}
3065
97571fd0
CM
3066/*
3067 * helper function to insert a new root level in the tree.
3068 * A new node is allocated, and a single item is inserted to
3069 * point to the existing root
aa5d6bed
CM
3070 *
3071 * returns zero on success or < 0 on failure.
97571fd0 3072 */
d397712b 3073static noinline int insert_new_root(struct btrfs_trans_handle *trans,
5f39d397
CM
3074 struct btrfs_root *root,
3075 struct btrfs_path *path, int level)
5c680ed6 3076{
7bb86316 3077 u64 lower_gen;
5f39d397
CM
3078 struct extent_buffer *lower;
3079 struct extent_buffer *c;
925baedd 3080 struct extent_buffer *old;
5f39d397 3081 struct btrfs_disk_key lower_key;
5c680ed6
CM
3082
3083 BUG_ON(path->nodes[level]);
3084 BUG_ON(path->nodes[level-1] != root->node);
3085
7bb86316
CM
3086 lower = path->nodes[level-1];
3087 if (level == 1)
3088 btrfs_item_key(lower, &lower_key, 0);
3089 else
3090 btrfs_node_key(lower, &lower_key, 0);
3091
31840ae1 3092 c = btrfs_alloc_free_block(trans, root, root->nodesize, 0,
5d4f98a2 3093 root->root_key.objectid, &lower_key,
5581a51a 3094 level, root->node->start, 0);
5f39d397
CM
3095 if (IS_ERR(c))
3096 return PTR_ERR(c);
925baedd 3097
f0486c68
YZ
3098 root_add_used(root, root->nodesize);
3099
5d4f98a2 3100 memset_extent_buffer(c, 0, 0, sizeof(struct btrfs_header));
5f39d397
CM
3101 btrfs_set_header_nritems(c, 1);
3102 btrfs_set_header_level(c, level);
db94535d 3103 btrfs_set_header_bytenr(c, c->start);
5f39d397 3104 btrfs_set_header_generation(c, trans->transid);
5d4f98a2 3105 btrfs_set_header_backref_rev(c, BTRFS_MIXED_BACKREF_REV);
5f39d397 3106 btrfs_set_header_owner(c, root->root_key.objectid);
5f39d397
CM
3107
3108 write_extent_buffer(c, root->fs_info->fsid,
3109 (unsigned long)btrfs_header_fsid(c),
3110 BTRFS_FSID_SIZE);
e17cade2
CM
3111
3112 write_extent_buffer(c, root->fs_info->chunk_tree_uuid,
3113 (unsigned long)btrfs_header_chunk_tree_uuid(c),
3114 BTRFS_UUID_SIZE);
3115
5f39d397 3116 btrfs_set_node_key(c, &lower_key, 0);
db94535d 3117 btrfs_set_node_blockptr(c, 0, lower->start);
7bb86316 3118 lower_gen = btrfs_header_generation(lower);
31840ae1 3119 WARN_ON(lower_gen != trans->transid);
7bb86316
CM
3120
3121 btrfs_set_node_ptr_generation(c, 0, lower_gen);
d5719762 3122
5f39d397 3123 btrfs_mark_buffer_dirty(c);
d5719762 3124
925baedd 3125 old = root->node;
f230475e 3126 tree_mod_log_set_root_pointer(root, c);
240f62c8 3127 rcu_assign_pointer(root->node, c);
925baedd
CM
3128
3129 /* the super has an extra ref to root->node */
3130 free_extent_buffer(old);
3131
0b86a832 3132 add_root_to_dirty_list(root);
5f39d397
CM
3133 extent_buffer_get(c);
3134 path->nodes[level] = c;
bd681513 3135 path->locks[level] = BTRFS_WRITE_LOCK;
5c680ed6
CM
3136 path->slots[level] = 0;
3137 return 0;
3138}
3139
74123bd7
CM
3140/*
3141 * worker function to insert a single pointer in a node.
3142 * the node should have enough room for the pointer already
97571fd0 3143 *
74123bd7
CM
3144 * slot and level indicate where you want the key to go, and
3145 * blocknr is the block the key points to.
3146 */
143bede5
JM
3147static void insert_ptr(struct btrfs_trans_handle *trans,
3148 struct btrfs_root *root, struct btrfs_path *path,
3149 struct btrfs_disk_key *key, u64 bytenr,
c3e06965 3150 int slot, int level)
74123bd7 3151{
5f39d397 3152 struct extent_buffer *lower;
74123bd7 3153 int nritems;
f3ea38da 3154 int ret;
5c680ed6
CM
3155
3156 BUG_ON(!path->nodes[level]);
f0486c68 3157 btrfs_assert_tree_locked(path->nodes[level]);
5f39d397
CM
3158 lower = path->nodes[level];
3159 nritems = btrfs_header_nritems(lower);
c293498b 3160 BUG_ON(slot > nritems);
143bede5 3161 BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(root));
74123bd7 3162 if (slot != nritems) {
c3e06965 3163 if (level)
f3ea38da
JS
3164 tree_mod_log_eb_move(root->fs_info, lower, slot + 1,
3165 slot, nritems - slot);
5f39d397
CM
3166 memmove_extent_buffer(lower,
3167 btrfs_node_key_ptr_offset(slot + 1),
3168 btrfs_node_key_ptr_offset(slot),
d6025579 3169 (nritems - slot) * sizeof(struct btrfs_key_ptr));
74123bd7 3170 }
c3e06965 3171 if (level) {
f3ea38da
JS
3172 ret = tree_mod_log_insert_key(root->fs_info, lower, slot,
3173 MOD_LOG_KEY_ADD);
3174 BUG_ON(ret < 0);
3175 }
5f39d397 3176 btrfs_set_node_key(lower, key, slot);
db94535d 3177 btrfs_set_node_blockptr(lower, slot, bytenr);
74493f7a
CM
3178 WARN_ON(trans->transid == 0);
3179 btrfs_set_node_ptr_generation(lower, slot, trans->transid);
5f39d397
CM
3180 btrfs_set_header_nritems(lower, nritems + 1);
3181 btrfs_mark_buffer_dirty(lower);
74123bd7
CM
3182}
3183
97571fd0
CM
3184/*
3185 * split the node at the specified level in path in two.
3186 * The path is corrected to point to the appropriate node after the split
3187 *
3188 * Before splitting this tries to make some room in the node by pushing
3189 * left and right, if either one works, it returns right away.
aa5d6bed
CM
3190 *
3191 * returns 0 on success and < 0 on failure
97571fd0 3192 */
e02119d5
CM
3193static noinline int split_node(struct btrfs_trans_handle *trans,
3194 struct btrfs_root *root,
3195 struct btrfs_path *path, int level)
be0e5c09 3196{
5f39d397
CM
3197 struct extent_buffer *c;
3198 struct extent_buffer *split;
3199 struct btrfs_disk_key disk_key;
be0e5c09 3200 int mid;
5c680ed6 3201 int ret;
7518a238 3202 u32 c_nritems;
eb60ceac 3203
5f39d397 3204 c = path->nodes[level];
7bb86316 3205 WARN_ON(btrfs_header_generation(c) != trans->transid);
5f39d397 3206 if (c == root->node) {
5c680ed6 3207 /* trying to split the root, lets make a new one */
e089f05c 3208 ret = insert_new_root(trans, root, path, level + 1);
5c680ed6
CM
3209 if (ret)
3210 return ret;
b3612421 3211 } else {
e66f709b 3212 ret = push_nodes_for_insert(trans, root, path, level);
5f39d397
CM
3213 c = path->nodes[level];
3214 if (!ret && btrfs_header_nritems(c) <
c448acf0 3215 BTRFS_NODEPTRS_PER_BLOCK(root) - 3)
e66f709b 3216 return 0;
54aa1f4d
CM
3217 if (ret < 0)
3218 return ret;
be0e5c09 3219 }
e66f709b 3220
5f39d397 3221 c_nritems = btrfs_header_nritems(c);
5d4f98a2
YZ
3222 mid = (c_nritems + 1) / 2;
3223 btrfs_node_key(c, &disk_key, mid);
7bb86316 3224
5d4f98a2 3225 split = btrfs_alloc_free_block(trans, root, root->nodesize, 0,
31840ae1 3226 root->root_key.objectid,
5581a51a 3227 &disk_key, level, c->start, 0);
5f39d397
CM
3228 if (IS_ERR(split))
3229 return PTR_ERR(split);
3230
f0486c68
YZ
3231 root_add_used(root, root->nodesize);
3232
5d4f98a2 3233 memset_extent_buffer(split, 0, 0, sizeof(struct btrfs_header));
5f39d397 3234 btrfs_set_header_level(split, btrfs_header_level(c));
db94535d 3235 btrfs_set_header_bytenr(split, split->start);
5f39d397 3236 btrfs_set_header_generation(split, trans->transid);
5d4f98a2 3237 btrfs_set_header_backref_rev(split, BTRFS_MIXED_BACKREF_REV);
5f39d397
CM
3238 btrfs_set_header_owner(split, root->root_key.objectid);
3239 write_extent_buffer(split, root->fs_info->fsid,
3240 (unsigned long)btrfs_header_fsid(split),
3241 BTRFS_FSID_SIZE);
e17cade2
CM
3242 write_extent_buffer(split, root->fs_info->chunk_tree_uuid,
3243 (unsigned long)btrfs_header_chunk_tree_uuid(split),
3244 BTRFS_UUID_SIZE);
54aa1f4d 3245
f230475e 3246 tree_mod_log_eb_copy(root->fs_info, split, c, 0, mid, c_nritems - mid);
5f39d397
CM
3247 copy_extent_buffer(split, c,
3248 btrfs_node_key_ptr_offset(0),
3249 btrfs_node_key_ptr_offset(mid),
3250 (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
3251 btrfs_set_header_nritems(split, c_nritems - mid);
3252 btrfs_set_header_nritems(c, mid);
aa5d6bed
CM
3253 ret = 0;
3254
5f39d397
CM
3255 btrfs_mark_buffer_dirty(c);
3256 btrfs_mark_buffer_dirty(split);
3257
143bede5 3258 insert_ptr(trans, root, path, &disk_key, split->start,
c3e06965 3259 path->slots[level + 1] + 1, level + 1);
aa5d6bed 3260
5de08d7d 3261 if (path->slots[level] >= mid) {
5c680ed6 3262 path->slots[level] -= mid;
925baedd 3263 btrfs_tree_unlock(c);
5f39d397
CM
3264 free_extent_buffer(c);
3265 path->nodes[level] = split;
5c680ed6
CM
3266 path->slots[level + 1] += 1;
3267 } else {
925baedd 3268 btrfs_tree_unlock(split);
5f39d397 3269 free_extent_buffer(split);
be0e5c09 3270 }
aa5d6bed 3271 return ret;
be0e5c09
CM
3272}
3273
74123bd7
CM
3274/*
3275 * how many bytes are required to store the items in a leaf. start
3276 * and nr indicate which items in the leaf to check. This totals up the
3277 * space used both by the item structs and the item data
3278 */
5f39d397 3279static int leaf_space_used(struct extent_buffer *l, int start, int nr)
be0e5c09
CM
3280{
3281 int data_len;
5f39d397 3282 int nritems = btrfs_header_nritems(l);
d4dbff95 3283 int end = min(nritems, start + nr) - 1;
be0e5c09
CM
3284
3285 if (!nr)
3286 return 0;
5f39d397
CM
3287 data_len = btrfs_item_end_nr(l, start);
3288 data_len = data_len - btrfs_item_offset_nr(l, end);
0783fcfc 3289 data_len += sizeof(struct btrfs_item) * nr;
d4dbff95 3290 WARN_ON(data_len < 0);
be0e5c09
CM
3291 return data_len;
3292}
3293
d4dbff95
CM
3294/*
3295 * The space between the end of the leaf items and
3296 * the start of the leaf data. IOW, how much room
3297 * the leaf has left for both items and data
3298 */
d397712b 3299noinline int btrfs_leaf_free_space(struct btrfs_root *root,
e02119d5 3300 struct extent_buffer *leaf)
d4dbff95 3301{
5f39d397
CM
3302 int nritems = btrfs_header_nritems(leaf);
3303 int ret;
3304 ret = BTRFS_LEAF_DATA_SIZE(root) - leaf_space_used(leaf, 0, nritems);
3305 if (ret < 0) {
d397712b
CM
3306 printk(KERN_CRIT "leaf free space ret %d, leaf data size %lu, "
3307 "used %d nritems %d\n",
ae2f5411 3308 ret, (unsigned long) BTRFS_LEAF_DATA_SIZE(root),
5f39d397
CM
3309 leaf_space_used(leaf, 0, nritems), nritems);
3310 }
3311 return ret;
d4dbff95
CM
3312}
3313
99d8f83c
CM
3314/*
3315 * min slot controls the lowest index we're willing to push to the
3316 * right. We'll push up to and including min_slot, but no lower
3317 */
44871b1b
CM
3318static noinline int __push_leaf_right(struct btrfs_trans_handle *trans,
3319 struct btrfs_root *root,
3320 struct btrfs_path *path,
3321 int data_size, int empty,
3322 struct extent_buffer *right,
99d8f83c
CM
3323 int free_space, u32 left_nritems,
3324 u32 min_slot)
00ec4c51 3325{
5f39d397 3326 struct extent_buffer *left = path->nodes[0];
44871b1b 3327 struct extent_buffer *upper = path->nodes[1];
cfed81a0 3328 struct btrfs_map_token token;
5f39d397 3329 struct btrfs_disk_key disk_key;
00ec4c51 3330 int slot;
34a38218 3331 u32 i;
00ec4c51
CM
3332 int push_space = 0;
3333 int push_items = 0;
0783fcfc 3334 struct btrfs_item *item;
34a38218 3335 u32 nr;
7518a238 3336 u32 right_nritems;
5f39d397 3337 u32 data_end;
db94535d 3338 u32 this_item_size;
00ec4c51 3339
cfed81a0
CM
3340 btrfs_init_map_token(&token);
3341
34a38218
CM
3342 if (empty)
3343 nr = 0;
3344 else
99d8f83c 3345 nr = max_t(u32, 1, min_slot);
34a38218 3346
31840ae1 3347 if (path->slots[0] >= left_nritems)
87b29b20 3348 push_space += data_size;
31840ae1 3349
44871b1b 3350 slot = path->slots[1];
34a38218
CM
3351 i = left_nritems - 1;
3352 while (i >= nr) {
5f39d397 3353 item = btrfs_item_nr(left, i);
db94535d 3354
31840ae1
ZY
3355 if (!empty && push_items > 0) {
3356 if (path->slots[0] > i)
3357 break;
3358 if (path->slots[0] == i) {
3359 int space = btrfs_leaf_free_space(root, left);
3360 if (space + push_space * 2 > free_space)
3361 break;
3362 }
3363 }
3364
00ec4c51 3365 if (path->slots[0] == i)
87b29b20 3366 push_space += data_size;
db94535d 3367
db94535d
CM
3368 this_item_size = btrfs_item_size(left, item);
3369 if (this_item_size + sizeof(*item) + push_space > free_space)
00ec4c51 3370 break;
31840ae1 3371
00ec4c51 3372 push_items++;
db94535d 3373 push_space += this_item_size + sizeof(*item);
34a38218
CM
3374 if (i == 0)
3375 break;
3376 i--;
db94535d 3377 }
5f39d397 3378
925baedd
CM
3379 if (push_items == 0)
3380 goto out_unlock;
5f39d397 3381
34a38218 3382 if (!empty && push_items == left_nritems)
a429e513 3383 WARN_ON(1);
5f39d397 3384
00ec4c51 3385 /* push left to right */
5f39d397 3386 right_nritems = btrfs_header_nritems(right);
34a38218 3387
5f39d397 3388 push_space = btrfs_item_end_nr(left, left_nritems - push_items);
123abc88 3389 push_space -= leaf_data_end(root, left);
5f39d397 3390
00ec4c51 3391 /* make room in the right data area */
5f39d397
CM
3392 data_end = leaf_data_end(root, right);
3393 memmove_extent_buffer(right,
3394 btrfs_leaf_data(right) + data_end - push_space,
3395 btrfs_leaf_data(right) + data_end,
3396 BTRFS_LEAF_DATA_SIZE(root) - data_end);
3397
00ec4c51 3398 /* copy from the left data area */
5f39d397 3399 copy_extent_buffer(right, left, btrfs_leaf_data(right) +
d6025579
CM
3400 BTRFS_LEAF_DATA_SIZE(root) - push_space,
3401 btrfs_leaf_data(left) + leaf_data_end(root, left),
3402 push_space);
5f39d397
CM
3403
3404 memmove_extent_buffer(right, btrfs_item_nr_offset(push_items),
3405 btrfs_item_nr_offset(0),
3406 right_nritems * sizeof(struct btrfs_item));
3407
00ec4c51 3408 /* copy the items from left to right */
5f39d397
CM
3409 copy_extent_buffer(right, left, btrfs_item_nr_offset(0),
3410 btrfs_item_nr_offset(left_nritems - push_items),
3411 push_items * sizeof(struct btrfs_item));
00ec4c51
CM
3412
3413 /* update the item pointers */
7518a238 3414 right_nritems += push_items;
5f39d397 3415 btrfs_set_header_nritems(right, right_nritems);
123abc88 3416 push_space = BTRFS_LEAF_DATA_SIZE(root);
7518a238 3417 for (i = 0; i < right_nritems; i++) {
5f39d397 3418 item = btrfs_item_nr(right, i);
cfed81a0
CM
3419 push_space -= btrfs_token_item_size(right, item, &token);
3420 btrfs_set_token_item_offset(right, item, push_space, &token);
db94535d
CM
3421 }
3422
7518a238 3423 left_nritems -= push_items;
5f39d397 3424 btrfs_set_header_nritems(left, left_nritems);
00ec4c51 3425
34a38218
CM
3426 if (left_nritems)
3427 btrfs_mark_buffer_dirty(left);
f0486c68
YZ
3428 else
3429 clean_tree_block(trans, root, left);
3430
5f39d397 3431 btrfs_mark_buffer_dirty(right);
a429e513 3432
5f39d397
CM
3433 btrfs_item_key(right, &disk_key, 0);
3434 btrfs_set_node_key(upper, &disk_key, slot + 1);
d6025579 3435 btrfs_mark_buffer_dirty(upper);
02217ed2 3436
00ec4c51 3437 /* then fixup the leaf pointer in the path */
7518a238
CM
3438 if (path->slots[0] >= left_nritems) {
3439 path->slots[0] -= left_nritems;
925baedd
CM
3440 if (btrfs_header_nritems(path->nodes[0]) == 0)
3441 clean_tree_block(trans, root, path->nodes[0]);
3442 btrfs_tree_unlock(path->nodes[0]);
5f39d397
CM
3443 free_extent_buffer(path->nodes[0]);
3444 path->nodes[0] = right;
00ec4c51
CM
3445 path->slots[1] += 1;
3446 } else {
925baedd 3447 btrfs_tree_unlock(right);
5f39d397 3448 free_extent_buffer(right);
00ec4c51
CM
3449 }
3450 return 0;
925baedd
CM
3451
3452out_unlock:
3453 btrfs_tree_unlock(right);
3454 free_extent_buffer(right);
3455 return 1;
00ec4c51 3456}
925baedd 3457
44871b1b
CM
3458/*
3459 * push some data in the path leaf to the right, trying to free up at
3460 * least data_size bytes. returns zero if the push worked, nonzero otherwise
3461 *
3462 * returns 1 if the push failed because the other node didn't have enough
3463 * room, 0 if everything worked out and < 0 if there were major errors.
99d8f83c
CM
3464 *
3465 * this will push starting from min_slot to the end of the leaf. It won't
3466 * push any slot lower than min_slot
44871b1b
CM
3467 */
3468static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
99d8f83c
CM
3469 *root, struct btrfs_path *path,
3470 int min_data_size, int data_size,
3471 int empty, u32 min_slot)
44871b1b
CM
3472{
3473 struct extent_buffer *left = path->nodes[0];
3474 struct extent_buffer *right;
3475 struct extent_buffer *upper;
3476 int slot;
3477 int free_space;
3478 u32 left_nritems;
3479 int ret;
3480
3481 if (!path->nodes[1])
3482 return 1;
3483
3484 slot = path->slots[1];
3485 upper = path->nodes[1];
3486 if (slot >= btrfs_header_nritems(upper) - 1)
3487 return 1;
3488
3489 btrfs_assert_tree_locked(path->nodes[1]);
3490
3491 right = read_node_slot(root, upper, slot + 1);
91ca338d
TI
3492 if (right == NULL)
3493 return 1;
3494
44871b1b
CM
3495 btrfs_tree_lock(right);
3496 btrfs_set_lock_blocking(right);
3497
3498 free_space = btrfs_leaf_free_space(root, right);
3499 if (free_space < data_size)
3500 goto out_unlock;
3501
3502 /* cow and double check */
3503 ret = btrfs_cow_block(trans, root, right, upper,
3504 slot + 1, &right);
3505 if (ret)
3506 goto out_unlock;
3507
3508 free_space = btrfs_leaf_free_space(root, right);
3509 if (free_space < data_size)
3510 goto out_unlock;
3511
3512 left_nritems = btrfs_header_nritems(left);
3513 if (left_nritems == 0)
3514 goto out_unlock;
3515
99d8f83c
CM
3516 return __push_leaf_right(trans, root, path, min_data_size, empty,
3517 right, free_space, left_nritems, min_slot);
44871b1b
CM
3518out_unlock:
3519 btrfs_tree_unlock(right);
3520 free_extent_buffer(right);
3521 return 1;
3522}
3523
74123bd7
CM
3524/*
3525 * push some data in the path leaf to the left, trying to free up at
3526 * least data_size bytes. returns zero if the push worked, nonzero otherwise
99d8f83c
CM
3527 *
3528 * max_slot can put a limit on how far into the leaf we'll push items. The
3529 * item at 'max_slot' won't be touched. Use (u32)-1 to make us do all the
3530 * items
74123bd7 3531 */
44871b1b
CM
3532static noinline int __push_leaf_left(struct btrfs_trans_handle *trans,
3533 struct btrfs_root *root,
3534 struct btrfs_path *path, int data_size,
3535 int empty, struct extent_buffer *left,
99d8f83c
CM
3536 int free_space, u32 right_nritems,
3537 u32 max_slot)
be0e5c09 3538{
5f39d397
CM
3539 struct btrfs_disk_key disk_key;
3540 struct extent_buffer *right = path->nodes[0];
be0e5c09 3541 int i;
be0e5c09
CM
3542 int push_space = 0;
3543 int push_items = 0;
0783fcfc 3544 struct btrfs_item *item;
7518a238 3545 u32 old_left_nritems;
34a38218 3546 u32 nr;
aa5d6bed 3547 int ret = 0;
db94535d
CM
3548 u32 this_item_size;
3549 u32 old_left_item_size;
cfed81a0
CM
3550 struct btrfs_map_token token;
3551
3552 btrfs_init_map_token(&token);
be0e5c09 3553
34a38218 3554 if (empty)
99d8f83c 3555 nr = min(right_nritems, max_slot);
34a38218 3556 else
99d8f83c 3557 nr = min(right_nritems - 1, max_slot);
34a38218
CM
3558
3559 for (i = 0; i < nr; i++) {
5f39d397 3560 item = btrfs_item_nr(right, i);
db94535d 3561
31840ae1
ZY
3562 if (!empty && push_items > 0) {
3563 if (path->slots[0] < i)
3564 break;
3565 if (path->slots[0] == i) {
3566 int space = btrfs_leaf_free_space(root, right);
3567 if (space + push_space * 2 > free_space)
3568 break;
3569 }
3570 }
3571
be0e5c09 3572 if (path->slots[0] == i)
87b29b20 3573 push_space += data_size;
db94535d
CM
3574
3575 this_item_size = btrfs_item_size(right, item);
3576 if (this_item_size + sizeof(*item) + push_space > free_space)
be0e5c09 3577 break;
db94535d 3578
be0e5c09 3579 push_items++;
db94535d
CM
3580 push_space += this_item_size + sizeof(*item);
3581 }
3582
be0e5c09 3583 if (push_items == 0) {
925baedd
CM
3584 ret = 1;
3585 goto out;
be0e5c09 3586 }
34a38218 3587 if (!empty && push_items == btrfs_header_nritems(right))
a429e513 3588 WARN_ON(1);
5f39d397 3589
be0e5c09 3590 /* push data from right to left */
5f39d397
CM
3591 copy_extent_buffer(left, right,
3592 btrfs_item_nr_offset(btrfs_header_nritems(left)),
3593 btrfs_item_nr_offset(0),
3594 push_items * sizeof(struct btrfs_item));
3595
123abc88 3596 push_space = BTRFS_LEAF_DATA_SIZE(root) -
d397712b 3597 btrfs_item_offset_nr(right, push_items - 1);
5f39d397
CM
3598
3599 copy_extent_buffer(left, right, btrfs_leaf_data(left) +
d6025579
CM
3600 leaf_data_end(root, left) - push_space,
3601 btrfs_leaf_data(right) +
5f39d397 3602 btrfs_item_offset_nr(right, push_items - 1),
d6025579 3603 push_space);
5f39d397 3604 old_left_nritems = btrfs_header_nritems(left);
87b29b20 3605 BUG_ON(old_left_nritems <= 0);
eb60ceac 3606
db94535d 3607 old_left_item_size = btrfs_item_offset_nr(left, old_left_nritems - 1);
0783fcfc 3608 for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
5f39d397 3609 u32 ioff;
db94535d 3610
5f39d397 3611 item = btrfs_item_nr(left, i);
db94535d 3612
cfed81a0
CM
3613 ioff = btrfs_token_item_offset(left, item, &token);
3614 btrfs_set_token_item_offset(left, item,
3615 ioff - (BTRFS_LEAF_DATA_SIZE(root) - old_left_item_size),
3616 &token);
be0e5c09 3617 }
5f39d397 3618 btrfs_set_header_nritems(left, old_left_nritems + push_items);
be0e5c09
CM
3619
3620 /* fixup right node */
34a38218 3621 if (push_items > right_nritems) {
d397712b
CM
3622 printk(KERN_CRIT "push items %d nr %u\n", push_items,
3623 right_nritems);
34a38218
CM
3624 WARN_ON(1);
3625 }
3626
3627 if (push_items < right_nritems) {
3628 push_space = btrfs_item_offset_nr(right, push_items - 1) -
3629 leaf_data_end(root, right);
3630 memmove_extent_buffer(right, btrfs_leaf_data(right) +
3631 BTRFS_LEAF_DATA_SIZE(root) - push_space,
3632 btrfs_leaf_data(right) +
3633 leaf_data_end(root, right), push_space);
3634
3635 memmove_extent_buffer(right, btrfs_item_nr_offset(0),
5f39d397
CM
3636 btrfs_item_nr_offset(push_items),
3637 (btrfs_header_nritems(right) - push_items) *
3638 sizeof(struct btrfs_item));
34a38218 3639 }
eef1c494
Y
3640 right_nritems -= push_items;
3641 btrfs_set_header_nritems(right, right_nritems);
123abc88 3642 push_space = BTRFS_LEAF_DATA_SIZE(root);
5f39d397
CM
3643 for (i = 0; i < right_nritems; i++) {
3644 item = btrfs_item_nr(right, i);
db94535d 3645
cfed81a0
CM
3646 push_space = push_space - btrfs_token_item_size(right,
3647 item, &token);
3648 btrfs_set_token_item_offset(right, item, push_space, &token);
db94535d 3649 }
eb60ceac 3650
5f39d397 3651 btrfs_mark_buffer_dirty(left);
34a38218
CM
3652 if (right_nritems)
3653 btrfs_mark_buffer_dirty(right);
f0486c68
YZ
3654 else
3655 clean_tree_block(trans, root, right);
098f59c2 3656
5f39d397 3657 btrfs_item_key(right, &disk_key, 0);
143bede5 3658 fixup_low_keys(trans, root, path, &disk_key, 1);
be0e5c09
CM
3659
3660 /* then fixup the leaf pointer in the path */
3661 if (path->slots[0] < push_items) {
3662 path->slots[0] += old_left_nritems;
925baedd 3663 btrfs_tree_unlock(path->nodes[0]);
5f39d397
CM
3664 free_extent_buffer(path->nodes[0]);
3665 path->nodes[0] = left;
be0e5c09
CM
3666 path->slots[1] -= 1;
3667 } else {
925baedd 3668 btrfs_tree_unlock(left);
5f39d397 3669 free_extent_buffer(left);
be0e5c09
CM
3670 path->slots[0] -= push_items;
3671 }
eb60ceac 3672 BUG_ON(path->slots[0] < 0);
aa5d6bed 3673 return ret;
925baedd
CM
3674out:
3675 btrfs_tree_unlock(left);
3676 free_extent_buffer(left);
3677 return ret;
be0e5c09
CM
3678}
3679
44871b1b
CM
3680/*
3681 * push some data in the path leaf to the left, trying to free up at
3682 * least data_size bytes. returns zero if the push worked, nonzero otherwise
99d8f83c
CM
3683 *
3684 * max_slot can put a limit on how far into the leaf we'll push items. The
3685 * item at 'max_slot' won't be touched. Use (u32)-1 to make us push all the
3686 * items
44871b1b
CM
3687 */
3688static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
99d8f83c
CM
3689 *root, struct btrfs_path *path, int min_data_size,
3690 int data_size, int empty, u32 max_slot)
44871b1b
CM
3691{
3692 struct extent_buffer *right = path->nodes[0];
3693 struct extent_buffer *left;
3694 int slot;
3695 int free_space;
3696 u32 right_nritems;
3697 int ret = 0;
3698
3699 slot = path->slots[1];
3700 if (slot == 0)
3701 return 1;
3702 if (!path->nodes[1])
3703 return 1;
3704
3705 right_nritems = btrfs_header_nritems(right);
3706 if (right_nritems == 0)
3707 return 1;
3708
3709 btrfs_assert_tree_locked(path->nodes[1]);
3710
3711 left = read_node_slot(root, path->nodes[1], slot - 1);
91ca338d
TI
3712 if (left == NULL)
3713 return 1;
3714
44871b1b
CM
3715 btrfs_tree_lock(left);
3716 btrfs_set_lock_blocking(left);
3717
3718 free_space = btrfs_leaf_free_space(root, left);
3719 if (free_space < data_size) {
3720 ret = 1;
3721 goto out;
3722 }
3723
3724 /* cow and double check */
3725 ret = btrfs_cow_block(trans, root, left,
3726 path->nodes[1], slot - 1, &left);
3727 if (ret) {
3728 /* we hit -ENOSPC, but it isn't fatal here */
79787eaa
JM
3729 if (ret == -ENOSPC)
3730 ret = 1;
44871b1b
CM
3731 goto out;
3732 }
3733
3734 free_space = btrfs_leaf_free_space(root, left);
3735 if (free_space < data_size) {
3736 ret = 1;
3737 goto out;
3738 }
3739
99d8f83c
CM
3740 return __push_leaf_left(trans, root, path, min_data_size,
3741 empty, left, free_space, right_nritems,
3742 max_slot);
44871b1b
CM
3743out:
3744 btrfs_tree_unlock(left);
3745 free_extent_buffer(left);
3746 return ret;
3747}
3748
3749/*
3750 * split the path's leaf in two, making sure there is at least data_size
3751 * available for the resulting leaf level of the path.
44871b1b 3752 */
143bede5
JM
3753static noinline void copy_for_split(struct btrfs_trans_handle *trans,
3754 struct btrfs_root *root,
3755 struct btrfs_path *path,
3756 struct extent_buffer *l,
3757 struct extent_buffer *right,
3758 int slot, int mid, int nritems)
44871b1b
CM
3759{
3760 int data_copy_size;
3761 int rt_data_off;
3762 int i;
44871b1b 3763 struct btrfs_disk_key disk_key;
cfed81a0
CM
3764 struct btrfs_map_token token;
3765
3766 btrfs_init_map_token(&token);
44871b1b
CM
3767
3768 nritems = nritems - mid;
3769 btrfs_set_header_nritems(right, nritems);
3770 data_copy_size = btrfs_item_end_nr(l, mid) - leaf_data_end(root, l);
3771
3772 copy_extent_buffer(right, l, btrfs_item_nr_offset(0),
3773 btrfs_item_nr_offset(mid),
3774 nritems * sizeof(struct btrfs_item));
3775
3776 copy_extent_buffer(right, l,
3777 btrfs_leaf_data(right) + BTRFS_LEAF_DATA_SIZE(root) -
3778 data_copy_size, btrfs_leaf_data(l) +
3779 leaf_data_end(root, l), data_copy_size);
3780
3781 rt_data_off = BTRFS_LEAF_DATA_SIZE(root) -
3782 btrfs_item_end_nr(l, mid);
3783
3784 for (i = 0; i < nritems; i++) {
3785 struct btrfs_item *item = btrfs_item_nr(right, i);
3786 u32 ioff;
3787
cfed81a0
CM
3788 ioff = btrfs_token_item_offset(right, item, &token);
3789 btrfs_set_token_item_offset(right, item,
3790 ioff + rt_data_off, &token);
44871b1b
CM
3791 }
3792
44871b1b 3793 btrfs_set_header_nritems(l, mid);
44871b1b 3794 btrfs_item_key(right, &disk_key, 0);
143bede5 3795 insert_ptr(trans, root, path, &disk_key, right->start,
c3e06965 3796 path->slots[1] + 1, 1);
44871b1b
CM
3797
3798 btrfs_mark_buffer_dirty(right);
3799 btrfs_mark_buffer_dirty(l);
3800 BUG_ON(path->slots[0] != slot);
3801
44871b1b
CM
3802 if (mid <= slot) {
3803 btrfs_tree_unlock(path->nodes[0]);
3804 free_extent_buffer(path->nodes[0]);
3805 path->nodes[0] = right;
3806 path->slots[0] -= mid;
3807 path->slots[1] += 1;
3808 } else {
3809 btrfs_tree_unlock(right);
3810 free_extent_buffer(right);
3811 }
3812
3813 BUG_ON(path->slots[0] < 0);
44871b1b
CM
3814}
3815
99d8f83c
CM
3816/*
3817 * double splits happen when we need to insert a big item in the middle
3818 * of a leaf. A double split can leave us with 3 mostly empty leaves:
3819 * leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
3820 * A B C
3821 *
3822 * We avoid this by trying to push the items on either side of our target
3823 * into the adjacent leaves. If all goes well we can avoid the double split
3824 * completely.
3825 */
3826static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
3827 struct btrfs_root *root,
3828 struct btrfs_path *path,
3829 int data_size)
3830{
3831 int ret;
3832 int progress = 0;
3833 int slot;
3834 u32 nritems;
3835
3836 slot = path->slots[0];
3837
3838 /*
3839 * try to push all the items after our slot into the
3840 * right leaf
3841 */
3842 ret = push_leaf_right(trans, root, path, 1, data_size, 0, slot);
3843 if (ret < 0)
3844 return ret;
3845
3846 if (ret == 0)
3847 progress++;
3848
3849 nritems = btrfs_header_nritems(path->nodes[0]);
3850 /*
3851 * our goal is to get our slot at the start or end of a leaf. If
3852 * we've done so we're done
3853 */
3854 if (path->slots[0] == 0 || path->slots[0] == nritems)
3855 return 0;
3856
3857 if (btrfs_leaf_free_space(root, path->nodes[0]) >= data_size)
3858 return 0;
3859
3860 /* try to push all the items before our slot into the next leaf */
3861 slot = path->slots[0];
3862 ret = push_leaf_left(trans, root, path, 1, data_size, 0, slot);
3863 if (ret < 0)
3864 return ret;
3865
3866 if (ret == 0)
3867 progress++;
3868
3869 if (progress)
3870 return 0;
3871 return 1;
3872}
3873
74123bd7
CM
3874/*
3875 * split the path's leaf in two, making sure there is at least data_size
3876 * available for the resulting leaf level of the path.
aa5d6bed
CM
3877 *
3878 * returns 0 if all went well and < 0 on failure.
74123bd7 3879 */
e02119d5
CM
3880static noinline int split_leaf(struct btrfs_trans_handle *trans,
3881 struct btrfs_root *root,
3882 struct btrfs_key *ins_key,
3883 struct btrfs_path *path, int data_size,
3884 int extend)
be0e5c09 3885{
5d4f98a2 3886 struct btrfs_disk_key disk_key;
5f39d397 3887 struct extent_buffer *l;
7518a238 3888 u32 nritems;
eb60ceac
CM
3889 int mid;
3890 int slot;
5f39d397 3891 struct extent_buffer *right;
d4dbff95 3892 int ret = 0;
aa5d6bed 3893 int wret;
5d4f98a2 3894 int split;
cc0c5538 3895 int num_doubles = 0;
99d8f83c 3896 int tried_avoid_double = 0;
aa5d6bed 3897
a5719521
YZ
3898 l = path->nodes[0];
3899 slot = path->slots[0];
3900 if (extend && data_size + btrfs_item_size_nr(l, slot) +
3901 sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(root))
3902 return -EOVERFLOW;
3903
40689478 3904 /* first try to make some room by pushing left and right */
99d8f83c
CM
3905 if (data_size) {
3906 wret = push_leaf_right(trans, root, path, data_size,
3907 data_size, 0, 0);
d397712b 3908 if (wret < 0)
eaee50e8 3909 return wret;
3685f791 3910 if (wret) {
99d8f83c
CM
3911 wret = push_leaf_left(trans, root, path, data_size,
3912 data_size, 0, (u32)-1);
3685f791
CM
3913 if (wret < 0)
3914 return wret;
3915 }
3916 l = path->nodes[0];
aa5d6bed 3917
3685f791 3918 /* did the pushes work? */
87b29b20 3919 if (btrfs_leaf_free_space(root, l) >= data_size)
3685f791 3920 return 0;
3326d1b0 3921 }
aa5d6bed 3922
5c680ed6 3923 if (!path->nodes[1]) {
e089f05c 3924 ret = insert_new_root(trans, root, path, 1);
5c680ed6
CM
3925 if (ret)
3926 return ret;
3927 }
cc0c5538 3928again:
5d4f98a2 3929 split = 1;
cc0c5538 3930 l = path->nodes[0];
eb60ceac 3931 slot = path->slots[0];
5f39d397 3932 nritems = btrfs_header_nritems(l);
d397712b 3933 mid = (nritems + 1) / 2;
54aa1f4d 3934
5d4f98a2
YZ
3935 if (mid <= slot) {
3936 if (nritems == 1 ||
3937 leaf_space_used(l, mid, nritems - mid) + data_size >
3938 BTRFS_LEAF_DATA_SIZE(root)) {
3939 if (slot >= nritems) {
3940 split = 0;
3941 } else {
3942 mid = slot;
3943 if (mid != nritems &&
3944 leaf_space_used(l, mid, nritems - mid) +
3945 data_size > BTRFS_LEAF_DATA_SIZE(root)) {
99d8f83c
CM
3946 if (data_size && !tried_avoid_double)
3947 goto push_for_double;
5d4f98a2
YZ
3948 split = 2;
3949 }
3950 }
3951 }
3952 } else {
3953 if (leaf_space_used(l, 0, mid) + data_size >
3954 BTRFS_LEAF_DATA_SIZE(root)) {
3955 if (!extend && data_size && slot == 0) {
3956 split = 0;
3957 } else if ((extend || !data_size) && slot == 0) {
3958 mid = 1;
3959 } else {
3960 mid = slot;
3961 if (mid != nritems &&
3962 leaf_space_used(l, mid, nritems - mid) +
3963 data_size > BTRFS_LEAF_DATA_SIZE(root)) {
99d8f83c
CM
3964 if (data_size && !tried_avoid_double)
3965 goto push_for_double;
5d4f98a2
YZ
3966 split = 2 ;
3967 }
3968 }
3969 }
3970 }
3971
3972 if (split == 0)
3973 btrfs_cpu_key_to_disk(&disk_key, ins_key);
3974 else
3975 btrfs_item_key(l, &disk_key, mid);
3976
3977 right = btrfs_alloc_free_block(trans, root, root->leafsize, 0,
31840ae1 3978 root->root_key.objectid,
5581a51a 3979 &disk_key, 0, l->start, 0);
f0486c68 3980 if (IS_ERR(right))
5f39d397 3981 return PTR_ERR(right);
f0486c68
YZ
3982
3983 root_add_used(root, root->leafsize);
5f39d397
CM
3984
3985 memset_extent_buffer(right, 0, 0, sizeof(struct btrfs_header));
db94535d 3986 btrfs_set_header_bytenr(right, right->start);
5f39d397 3987 btrfs_set_header_generation(right, trans->transid);
5d4f98a2 3988 btrfs_set_header_backref_rev(right, BTRFS_MIXED_BACKREF_REV);
5f39d397
CM
3989 btrfs_set_header_owner(right, root->root_key.objectid);
3990 btrfs_set_header_level(right, 0);
3991 write_extent_buffer(right, root->fs_info->fsid,
3992 (unsigned long)btrfs_header_fsid(right),
3993 BTRFS_FSID_SIZE);
e17cade2
CM
3994
3995 write_extent_buffer(right, root->fs_info->chunk_tree_uuid,
3996 (unsigned long)btrfs_header_chunk_tree_uuid(right),
3997 BTRFS_UUID_SIZE);
44871b1b 3998
5d4f98a2
YZ
3999 if (split == 0) {
4000 if (mid <= slot) {
4001 btrfs_set_header_nritems(right, 0);
143bede5 4002 insert_ptr(trans, root, path, &disk_key, right->start,
c3e06965 4003 path->slots[1] + 1, 1);
5d4f98a2
YZ
4004 btrfs_tree_unlock(path->nodes[0]);
4005 free_extent_buffer(path->nodes[0]);
4006 path->nodes[0] = right;
4007 path->slots[0] = 0;
4008 path->slots[1] += 1;
4009 } else {
4010 btrfs_set_header_nritems(right, 0);
143bede5 4011 insert_ptr(trans, root, path, &disk_key, right->start,
c3e06965 4012 path->slots[1], 1);
5d4f98a2
YZ
4013 btrfs_tree_unlock(path->nodes[0]);
4014 free_extent_buffer(path->nodes[0]);
4015 path->nodes[0] = right;
4016 path->slots[0] = 0;
143bede5
JM
4017 if (path->slots[1] == 0)
4018 fixup_low_keys(trans, root, path,
4019 &disk_key, 1);
d4dbff95 4020 }
5d4f98a2
YZ
4021 btrfs_mark_buffer_dirty(right);
4022 return ret;
d4dbff95 4023 }
74123bd7 4024
143bede5 4025 copy_for_split(trans, root, path, l, right, slot, mid, nritems);
31840ae1 4026
5d4f98a2 4027 if (split == 2) {
cc0c5538
CM
4028 BUG_ON(num_doubles != 0);
4029 num_doubles++;
4030 goto again;
a429e513 4031 }
44871b1b 4032
143bede5 4033 return 0;
99d8f83c
CM
4034
4035push_for_double:
4036 push_for_double_split(trans, root, path, data_size);
4037 tried_avoid_double = 1;
4038 if (btrfs_leaf_free_space(root, path->nodes[0]) >= data_size)
4039 return 0;
4040 goto again;
be0e5c09
CM
4041}
4042
ad48fd75
YZ
4043static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
4044 struct btrfs_root *root,
4045 struct btrfs_path *path, int ins_len)
459931ec 4046{
ad48fd75 4047 struct btrfs_key key;
459931ec 4048 struct extent_buffer *leaf;
ad48fd75
YZ
4049 struct btrfs_file_extent_item *fi;
4050 u64 extent_len = 0;
4051 u32 item_size;
4052 int ret;
459931ec
CM
4053
4054 leaf = path->nodes[0];
ad48fd75
YZ
4055 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4056
4057 BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
4058 key.type != BTRFS_EXTENT_CSUM_KEY);
4059
4060 if (btrfs_leaf_free_space(root, leaf) >= ins_len)
4061 return 0;
459931ec
CM
4062
4063 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
ad48fd75
YZ
4064 if (key.type == BTRFS_EXTENT_DATA_KEY) {
4065 fi = btrfs_item_ptr(leaf, path->slots[0],
4066 struct btrfs_file_extent_item);
4067 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
4068 }
b3b4aa74 4069 btrfs_release_path(path);
459931ec 4070
459931ec 4071 path->keep_locks = 1;
ad48fd75
YZ
4072 path->search_for_split = 1;
4073 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
459931ec 4074 path->search_for_split = 0;
ad48fd75
YZ
4075 if (ret < 0)
4076 goto err;
459931ec 4077
ad48fd75
YZ
4078 ret = -EAGAIN;
4079 leaf = path->nodes[0];
459931ec 4080 /* if our item isn't there or got smaller, return now */
ad48fd75
YZ
4081 if (ret > 0 || item_size != btrfs_item_size_nr(leaf, path->slots[0]))
4082 goto err;
4083
109f6aef
CM
4084 /* the leaf has changed, it now has room. return now */
4085 if (btrfs_leaf_free_space(root, path->nodes[0]) >= ins_len)
4086 goto err;
4087
ad48fd75
YZ
4088 if (key.type == BTRFS_EXTENT_DATA_KEY) {
4089 fi = btrfs_item_ptr(leaf, path->slots[0],
4090 struct btrfs_file_extent_item);
4091 if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
4092 goto err;
459931ec
CM
4093 }
4094
b9473439 4095 btrfs_set_path_blocking(path);
ad48fd75 4096 ret = split_leaf(trans, root, &key, path, ins_len, 1);
f0486c68
YZ
4097 if (ret)
4098 goto err;
459931ec 4099
ad48fd75 4100 path->keep_locks = 0;
b9473439 4101 btrfs_unlock_up_safe(path, 1);
ad48fd75
YZ
4102 return 0;
4103err:
4104 path->keep_locks = 0;
4105 return ret;
4106}
4107
4108static noinline int split_item(struct btrfs_trans_handle *trans,
4109 struct btrfs_root *root,
4110 struct btrfs_path *path,
4111 struct btrfs_key *new_key,
4112 unsigned long split_offset)
4113{
4114 struct extent_buffer *leaf;
4115 struct btrfs_item *item;
4116 struct btrfs_item *new_item;
4117 int slot;
4118 char *buf;
4119 u32 nritems;
4120 u32 item_size;
4121 u32 orig_offset;
4122 struct btrfs_disk_key disk_key;
4123
b9473439
CM
4124 leaf = path->nodes[0];
4125 BUG_ON(btrfs_leaf_free_space(root, leaf) < sizeof(struct btrfs_item));
4126
b4ce94de
CM
4127 btrfs_set_path_blocking(path);
4128
459931ec
CM
4129 item = btrfs_item_nr(leaf, path->slots[0]);
4130 orig_offset = btrfs_item_offset(leaf, item);
4131 item_size = btrfs_item_size(leaf, item);
4132
459931ec 4133 buf = kmalloc(item_size, GFP_NOFS);
ad48fd75
YZ
4134 if (!buf)
4135 return -ENOMEM;
4136
459931ec
CM
4137 read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
4138 path->slots[0]), item_size);
459931ec 4139
ad48fd75 4140 slot = path->slots[0] + 1;
459931ec 4141 nritems = btrfs_header_nritems(leaf);
459931ec
CM
4142 if (slot != nritems) {
4143 /* shift the items */
4144 memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + 1),
ad48fd75
YZ
4145 btrfs_item_nr_offset(slot),
4146 (nritems - slot) * sizeof(struct btrfs_item));
459931ec
CM
4147 }
4148
4149 btrfs_cpu_key_to_disk(&disk_key, new_key);
4150 btrfs_set_item_key(leaf, &disk_key, slot);
4151
4152 new_item = btrfs_item_nr(leaf, slot);
4153
4154 btrfs_set_item_offset(leaf, new_item, orig_offset);
4155 btrfs_set_item_size(leaf, new_item, item_size - split_offset);
4156
4157 btrfs_set_item_offset(leaf, item,
4158 orig_offset + item_size - split_offset);
4159 btrfs_set_item_size(leaf, item, split_offset);
4160
4161 btrfs_set_header_nritems(leaf, nritems + 1);
4162
4163 /* write the data for the start of the original item */
4164 write_extent_buffer(leaf, buf,
4165 btrfs_item_ptr_offset(leaf, path->slots[0]),
4166 split_offset);
4167
4168 /* write the data for the new item */
4169 write_extent_buffer(leaf, buf + split_offset,
4170 btrfs_item_ptr_offset(leaf, slot),
4171 item_size - split_offset);
4172 btrfs_mark_buffer_dirty(leaf);
4173
ad48fd75 4174 BUG_ON(btrfs_leaf_free_space(root, leaf) < 0);
459931ec 4175 kfree(buf);
ad48fd75
YZ
4176 return 0;
4177}
4178
4179/*
4180 * This function splits a single item into two items,
4181 * giving 'new_key' to the new item and splitting the
4182 * old one at split_offset (from the start of the item).
4183 *
4184 * The path may be released by this operation. After
4185 * the split, the path is pointing to the old item. The
4186 * new item is going to be in the same node as the old one.
4187 *
4188 * Note, the item being split must be smaller enough to live alone on
4189 * a tree block with room for one extra struct btrfs_item
4190 *
4191 * This allows us to split the item in place, keeping a lock on the
4192 * leaf the entire time.
4193 */
4194int btrfs_split_item(struct btrfs_trans_handle *trans,
4195 struct btrfs_root *root,
4196 struct btrfs_path *path,
4197 struct btrfs_key *new_key,
4198 unsigned long split_offset)
4199{
4200 int ret;
4201 ret = setup_leaf_for_split(trans, root, path,
4202 sizeof(struct btrfs_item));
4203 if (ret)
4204 return ret;
4205
4206 ret = split_item(trans, root, path, new_key, split_offset);
459931ec
CM
4207 return ret;
4208}
4209
ad48fd75
YZ
4210/*
4211 * This function duplicate a item, giving 'new_key' to the new item.
4212 * It guarantees both items live in the same tree leaf and the new item
4213 * is contiguous with the original item.
4214 *
4215 * This allows us to split file extent in place, keeping a lock on the
4216 * leaf the entire time.
4217 */
4218int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
4219 struct btrfs_root *root,
4220 struct btrfs_path *path,
4221 struct btrfs_key *new_key)
4222{
4223 struct extent_buffer *leaf;
4224 int ret;
4225 u32 item_size;
4226
4227 leaf = path->nodes[0];
4228 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
4229 ret = setup_leaf_for_split(trans, root, path,
4230 item_size + sizeof(struct btrfs_item));
4231 if (ret)
4232 return ret;
4233
4234 path->slots[0]++;
143bede5
JM
4235 setup_items_for_insert(trans, root, path, new_key, &item_size,
4236 item_size, item_size +
4237 sizeof(struct btrfs_item), 1);
ad48fd75
YZ
4238 leaf = path->nodes[0];
4239 memcpy_extent_buffer(leaf,
4240 btrfs_item_ptr_offset(leaf, path->slots[0]),
4241 btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
4242 item_size);
4243 return 0;
4244}
4245
d352ac68
CM
4246/*
4247 * make the item pointed to by the path smaller. new_size indicates
4248 * how small to make it, and from_end tells us if we just chop bytes
4249 * off the end of the item or if we shift the item to chop bytes off
4250 * the front.
4251 */
143bede5
JM
4252void btrfs_truncate_item(struct btrfs_trans_handle *trans,
4253 struct btrfs_root *root,
4254 struct btrfs_path *path,
4255 u32 new_size, int from_end)
b18c6685 4256{
b18c6685 4257 int slot;
5f39d397
CM
4258 struct extent_buffer *leaf;
4259 struct btrfs_item *item;
b18c6685
CM
4260 u32 nritems;
4261 unsigned int data_end;
4262 unsigned int old_data_start;
4263 unsigned int old_size;
4264 unsigned int size_diff;
4265 int i;
cfed81a0
CM
4266 struct btrfs_map_token token;
4267
4268 btrfs_init_map_token(&token);
b18c6685 4269
5f39d397 4270 leaf = path->nodes[0];
179e29e4
CM
4271 slot = path->slots[0];
4272
4273 old_size = btrfs_item_size_nr(leaf, slot);
4274 if (old_size == new_size)
143bede5 4275 return;
b18c6685 4276
5f39d397 4277 nritems = btrfs_header_nritems(leaf);
b18c6685
CM
4278 data_end = leaf_data_end(root, leaf);
4279
5f39d397 4280 old_data_start = btrfs_item_offset_nr(leaf, slot);
179e29e4 4281
b18c6685
CM
4282 size_diff = old_size - new_size;
4283
4284 BUG_ON(slot < 0);
4285 BUG_ON(slot >= nritems);
4286
4287 /*
4288 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4289 */
4290 /* first correct the data pointers */
4291 for (i = slot; i < nritems; i++) {
5f39d397
CM
4292 u32 ioff;
4293 item = btrfs_item_nr(leaf, i);
db94535d 4294
cfed81a0
CM
4295 ioff = btrfs_token_item_offset(leaf, item, &token);
4296 btrfs_set_token_item_offset(leaf, item,
4297 ioff + size_diff, &token);
b18c6685 4298 }
db94535d 4299
b18c6685 4300 /* shift the data */
179e29e4
CM
4301 if (from_end) {
4302 memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
4303 data_end + size_diff, btrfs_leaf_data(leaf) +
4304 data_end, old_data_start + new_size - data_end);
4305 } else {
4306 struct btrfs_disk_key disk_key;
4307 u64 offset;
4308
4309 btrfs_item_key(leaf, &disk_key, slot);
4310
4311 if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
4312 unsigned long ptr;
4313 struct btrfs_file_extent_item *fi;
4314
4315 fi = btrfs_item_ptr(leaf, slot,
4316 struct btrfs_file_extent_item);
4317 fi = (struct btrfs_file_extent_item *)(
4318 (unsigned long)fi - size_diff);
4319
4320 if (btrfs_file_extent_type(leaf, fi) ==
4321 BTRFS_FILE_EXTENT_INLINE) {
4322 ptr = btrfs_item_ptr_offset(leaf, slot);
4323 memmove_extent_buffer(leaf, ptr,
d397712b
CM
4324 (unsigned long)fi,
4325 offsetof(struct btrfs_file_extent_item,
179e29e4
CM
4326 disk_bytenr));
4327 }
4328 }
4329
4330 memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
4331 data_end + size_diff, btrfs_leaf_data(leaf) +
4332 data_end, old_data_start - data_end);
4333
4334 offset = btrfs_disk_key_offset(&disk_key);
4335 btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
4336 btrfs_set_item_key(leaf, &disk_key, slot);
4337 if (slot == 0)
4338 fixup_low_keys(trans, root, path, &disk_key, 1);
4339 }
5f39d397
CM
4340
4341 item = btrfs_item_nr(leaf, slot);
4342 btrfs_set_item_size(leaf, item, new_size);
4343 btrfs_mark_buffer_dirty(leaf);
b18c6685 4344
5f39d397
CM
4345 if (btrfs_leaf_free_space(root, leaf) < 0) {
4346 btrfs_print_leaf(root, leaf);
b18c6685 4347 BUG();
5f39d397 4348 }
b18c6685
CM
4349}
4350
d352ac68
CM
4351/*
4352 * make the item pointed to by the path bigger, data_size is the new size.
4353 */
143bede5
JM
4354void btrfs_extend_item(struct btrfs_trans_handle *trans,
4355 struct btrfs_root *root, struct btrfs_path *path,
4356 u32 data_size)
6567e837 4357{
6567e837 4358 int slot;
5f39d397
CM
4359 struct extent_buffer *leaf;
4360 struct btrfs_item *item;
6567e837
CM
4361 u32 nritems;
4362 unsigned int data_end;
4363 unsigned int old_data;
4364 unsigned int old_size;
4365 int i;
cfed81a0
CM
4366 struct btrfs_map_token token;
4367
4368 btrfs_init_map_token(&token);
6567e837 4369
5f39d397 4370 leaf = path->nodes[0];
6567e837 4371
5f39d397 4372 nritems = btrfs_header_nritems(leaf);
6567e837
CM
4373 data_end = leaf_data_end(root, leaf);
4374
5f39d397
CM
4375 if (btrfs_leaf_free_space(root, leaf) < data_size) {
4376 btrfs_print_leaf(root, leaf);
6567e837 4377 BUG();
5f39d397 4378 }
6567e837 4379 slot = path->slots[0];
5f39d397 4380 old_data = btrfs_item_end_nr(leaf, slot);
6567e837
CM
4381
4382 BUG_ON(slot < 0);
3326d1b0
CM
4383 if (slot >= nritems) {
4384 btrfs_print_leaf(root, leaf);
d397712b
CM
4385 printk(KERN_CRIT "slot %d too large, nritems %d\n",
4386 slot, nritems);
3326d1b0
CM
4387 BUG_ON(1);
4388 }
6567e837
CM
4389
4390 /*
4391 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4392 */
4393 /* first correct the data pointers */
4394 for (i = slot; i < nritems; i++) {
5f39d397
CM
4395 u32 ioff;
4396 item = btrfs_item_nr(leaf, i);
db94535d 4397
cfed81a0
CM
4398 ioff = btrfs_token_item_offset(leaf, item, &token);
4399 btrfs_set_token_item_offset(leaf, item,
4400 ioff - data_size, &token);
6567e837 4401 }
5f39d397 4402
6567e837 4403 /* shift the data */
5f39d397 4404 memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
6567e837
CM
4405 data_end - data_size, btrfs_leaf_data(leaf) +
4406 data_end, old_data - data_end);
5f39d397 4407
6567e837 4408 data_end = old_data;
5f39d397
CM
4409 old_size = btrfs_item_size_nr(leaf, slot);
4410 item = btrfs_item_nr(leaf, slot);
4411 btrfs_set_item_size(leaf, item, old_size + data_size);
4412 btrfs_mark_buffer_dirty(leaf);
6567e837 4413
5f39d397
CM
4414 if (btrfs_leaf_free_space(root, leaf) < 0) {
4415 btrfs_print_leaf(root, leaf);
6567e837 4416 BUG();
5f39d397 4417 }
6567e837
CM
4418}
4419
74123bd7 4420/*
44871b1b
CM
4421 * this is a helper for btrfs_insert_empty_items, the main goal here is
4422 * to save stack depth by doing the bulk of the work in a function
4423 * that doesn't call btrfs_search_slot
74123bd7 4424 */
143bede5
JM
4425void setup_items_for_insert(struct btrfs_trans_handle *trans,
4426 struct btrfs_root *root, struct btrfs_path *path,
4427 struct btrfs_key *cpu_key, u32 *data_size,
4428 u32 total_data, u32 total_size, int nr)
be0e5c09 4429{
5f39d397 4430 struct btrfs_item *item;
9c58309d 4431 int i;
7518a238 4432 u32 nritems;
be0e5c09 4433 unsigned int data_end;
e2fa7227 4434 struct btrfs_disk_key disk_key;
44871b1b
CM
4435 struct extent_buffer *leaf;
4436 int slot;
cfed81a0
CM
4437 struct btrfs_map_token token;
4438
4439 btrfs_init_map_token(&token);
e2fa7227 4440
5f39d397 4441 leaf = path->nodes[0];
44871b1b 4442 slot = path->slots[0];
74123bd7 4443
5f39d397 4444 nritems = btrfs_header_nritems(leaf);
123abc88 4445 data_end = leaf_data_end(root, leaf);
eb60ceac 4446
f25956cc 4447 if (btrfs_leaf_free_space(root, leaf) < total_size) {
3326d1b0 4448 btrfs_print_leaf(root, leaf);
d397712b 4449 printk(KERN_CRIT "not enough freespace need %u have %d\n",
9c58309d 4450 total_size, btrfs_leaf_free_space(root, leaf));
be0e5c09 4451 BUG();
d4dbff95 4452 }
5f39d397 4453
be0e5c09 4454 if (slot != nritems) {
5f39d397 4455 unsigned int old_data = btrfs_item_end_nr(leaf, slot);
be0e5c09 4456
5f39d397
CM
4457 if (old_data < data_end) {
4458 btrfs_print_leaf(root, leaf);
d397712b 4459 printk(KERN_CRIT "slot %d old_data %d data_end %d\n",
5f39d397
CM
4460 slot, old_data, data_end);
4461 BUG_ON(1);
4462 }
be0e5c09
CM
4463 /*
4464 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4465 */
4466 /* first correct the data pointers */
0783fcfc 4467 for (i = slot; i < nritems; i++) {
5f39d397 4468 u32 ioff;
db94535d 4469
5f39d397 4470 item = btrfs_item_nr(leaf, i);
cfed81a0
CM
4471 ioff = btrfs_token_item_offset(leaf, item, &token);
4472 btrfs_set_token_item_offset(leaf, item,
4473 ioff - total_data, &token);
0783fcfc 4474 }
be0e5c09 4475 /* shift the items */
9c58309d 4476 memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + nr),
5f39d397 4477 btrfs_item_nr_offset(slot),
d6025579 4478 (nritems - slot) * sizeof(struct btrfs_item));
be0e5c09
CM
4479
4480 /* shift the data */
5f39d397 4481 memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
9c58309d 4482 data_end - total_data, btrfs_leaf_data(leaf) +
d6025579 4483 data_end, old_data - data_end);
be0e5c09
CM
4484 data_end = old_data;
4485 }
5f39d397 4486
62e2749e 4487 /* setup the item for the new data */
9c58309d
CM
4488 for (i = 0; i < nr; i++) {
4489 btrfs_cpu_key_to_disk(&disk_key, cpu_key + i);
4490 btrfs_set_item_key(leaf, &disk_key, slot + i);
4491 item = btrfs_item_nr(leaf, slot + i);
cfed81a0
CM
4492 btrfs_set_token_item_offset(leaf, item,
4493 data_end - data_size[i], &token);
9c58309d 4494 data_end -= data_size[i];
cfed81a0 4495 btrfs_set_token_item_size(leaf, item, data_size[i], &token);
9c58309d 4496 }
44871b1b 4497
9c58309d 4498 btrfs_set_header_nritems(leaf, nritems + nr);
aa5d6bed 4499
5a01a2e3
CM
4500 if (slot == 0) {
4501 btrfs_cpu_key_to_disk(&disk_key, cpu_key);
143bede5 4502 fixup_low_keys(trans, root, path, &disk_key, 1);
5a01a2e3 4503 }
b9473439
CM
4504 btrfs_unlock_up_safe(path, 1);
4505 btrfs_mark_buffer_dirty(leaf);
aa5d6bed 4506
5f39d397
CM
4507 if (btrfs_leaf_free_space(root, leaf) < 0) {
4508 btrfs_print_leaf(root, leaf);
be0e5c09 4509 BUG();
5f39d397 4510 }
44871b1b
CM
4511}
4512
4513/*
4514 * Given a key and some data, insert items into the tree.
4515 * This does all the path init required, making room in the tree if needed.
4516 */
4517int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
4518 struct btrfs_root *root,
4519 struct btrfs_path *path,
4520 struct btrfs_key *cpu_key, u32 *data_size,
4521 int nr)
4522{
44871b1b
CM
4523 int ret = 0;
4524 int slot;
4525 int i;
4526 u32 total_size = 0;
4527 u32 total_data = 0;
4528
4529 for (i = 0; i < nr; i++)
4530 total_data += data_size[i];
4531
4532 total_size = total_data + (nr * sizeof(struct btrfs_item));
4533 ret = btrfs_search_slot(trans, root, cpu_key, path, total_size, 1);
4534 if (ret == 0)
4535 return -EEXIST;
4536 if (ret < 0)
143bede5 4537 return ret;
44871b1b 4538
44871b1b
CM
4539 slot = path->slots[0];
4540 BUG_ON(slot < 0);
4541
143bede5 4542 setup_items_for_insert(trans, root, path, cpu_key, data_size,
44871b1b 4543 total_data, total_size, nr);
143bede5 4544 return 0;
62e2749e
CM
4545}
4546
4547/*
4548 * Given a key and some data, insert an item into the tree.
4549 * This does all the path init required, making room in the tree if needed.
4550 */
e089f05c
CM
4551int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root
4552 *root, struct btrfs_key *cpu_key, void *data, u32
4553 data_size)
62e2749e
CM
4554{
4555 int ret = 0;
2c90e5d6 4556 struct btrfs_path *path;
5f39d397
CM
4557 struct extent_buffer *leaf;
4558 unsigned long ptr;
62e2749e 4559
2c90e5d6 4560 path = btrfs_alloc_path();
db5b493a
TI
4561 if (!path)
4562 return -ENOMEM;
2c90e5d6 4563 ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
62e2749e 4564 if (!ret) {
5f39d397
CM
4565 leaf = path->nodes[0];
4566 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
4567 write_extent_buffer(leaf, data, ptr, data_size);
4568 btrfs_mark_buffer_dirty(leaf);
62e2749e 4569 }
2c90e5d6 4570 btrfs_free_path(path);
aa5d6bed 4571 return ret;
be0e5c09
CM
4572}
4573
74123bd7 4574/*
5de08d7d 4575 * delete the pointer from a given node.
74123bd7 4576 *
d352ac68
CM
4577 * the tree should have been previously balanced so the deletion does not
4578 * empty a node.
74123bd7 4579 */
143bede5 4580static void del_ptr(struct btrfs_trans_handle *trans, struct btrfs_root *root,
f3ea38da
JS
4581 struct btrfs_path *path, int level, int slot,
4582 int tree_mod_log)
be0e5c09 4583{
5f39d397 4584 struct extent_buffer *parent = path->nodes[level];
7518a238 4585 u32 nritems;
f3ea38da 4586 int ret;
be0e5c09 4587
5f39d397 4588 nritems = btrfs_header_nritems(parent);
d397712b 4589 if (slot != nritems - 1) {
f3ea38da
JS
4590 if (tree_mod_log && level)
4591 tree_mod_log_eb_move(root->fs_info, parent, slot,
4592 slot + 1, nritems - slot - 1);
5f39d397
CM
4593 memmove_extent_buffer(parent,
4594 btrfs_node_key_ptr_offset(slot),
4595 btrfs_node_key_ptr_offset(slot + 1),
d6025579
CM
4596 sizeof(struct btrfs_key_ptr) *
4597 (nritems - slot - 1));
f395694c 4598 } else if (tree_mod_log && level) {
f3ea38da
JS
4599 ret = tree_mod_log_insert_key(root->fs_info, parent, slot,
4600 MOD_LOG_KEY_REMOVE);
4601 BUG_ON(ret < 0);
bb803951 4602 }
f3ea38da 4603
7518a238 4604 nritems--;
5f39d397 4605 btrfs_set_header_nritems(parent, nritems);
7518a238 4606 if (nritems == 0 && parent == root->node) {
5f39d397 4607 BUG_ON(btrfs_header_level(root->node) != 1);
bb803951 4608 /* just turn the root into a leaf and break */
5f39d397 4609 btrfs_set_header_level(root->node, 0);
bb803951 4610 } else if (slot == 0) {
5f39d397
CM
4611 struct btrfs_disk_key disk_key;
4612
4613 btrfs_node_key(parent, &disk_key, 0);
143bede5 4614 fixup_low_keys(trans, root, path, &disk_key, level + 1);
be0e5c09 4615 }
d6025579 4616 btrfs_mark_buffer_dirty(parent);
be0e5c09
CM
4617}
4618
323ac95b
CM
4619/*
4620 * a helper function to delete the leaf pointed to by path->slots[1] and
5d4f98a2 4621 * path->nodes[1].
323ac95b
CM
4622 *
4623 * This deletes the pointer in path->nodes[1] and frees the leaf
4624 * block extent. zero is returned if it all worked out, < 0 otherwise.
4625 *
4626 * The path must have already been setup for deleting the leaf, including
4627 * all the proper balancing. path->nodes[1] must be locked.
4628 */
143bede5
JM
4629static noinline void btrfs_del_leaf(struct btrfs_trans_handle *trans,
4630 struct btrfs_root *root,
4631 struct btrfs_path *path,
4632 struct extent_buffer *leaf)
323ac95b 4633{
5d4f98a2 4634 WARN_ON(btrfs_header_generation(leaf) != trans->transid);
f3ea38da 4635 del_ptr(trans, root, path, 1, path->slots[1], 1);
323ac95b 4636
4d081c41
CM
4637 /*
4638 * btrfs_free_extent is expensive, we want to make sure we
4639 * aren't holding any locks when we call it
4640 */
4641 btrfs_unlock_up_safe(path, 0);
4642
f0486c68
YZ
4643 root_sub_used(root, leaf->len);
4644
3083ee2e 4645 extent_buffer_get(leaf);
5581a51a 4646 btrfs_free_tree_block(trans, root, leaf, 0, 1);
3083ee2e 4647 free_extent_buffer_stale(leaf);
323ac95b 4648}
74123bd7
CM
4649/*
4650 * delete the item at the leaf level in path. If that empties
4651 * the leaf, remove it from the tree
4652 */
85e21bac
CM
4653int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4654 struct btrfs_path *path, int slot, int nr)
be0e5c09 4655{
5f39d397
CM
4656 struct extent_buffer *leaf;
4657 struct btrfs_item *item;
85e21bac
CM
4658 int last_off;
4659 int dsize = 0;
aa5d6bed
CM
4660 int ret = 0;
4661 int wret;
85e21bac 4662 int i;
7518a238 4663 u32 nritems;
cfed81a0
CM
4664 struct btrfs_map_token token;
4665
4666 btrfs_init_map_token(&token);
be0e5c09 4667
5f39d397 4668 leaf = path->nodes[0];
85e21bac
CM
4669 last_off = btrfs_item_offset_nr(leaf, slot + nr - 1);
4670
4671 for (i = 0; i < nr; i++)
4672 dsize += btrfs_item_size_nr(leaf, slot + i);
4673
5f39d397 4674 nritems = btrfs_header_nritems(leaf);
be0e5c09 4675
85e21bac 4676 if (slot + nr != nritems) {
123abc88 4677 int data_end = leaf_data_end(root, leaf);
5f39d397
CM
4678
4679 memmove_extent_buffer(leaf, btrfs_leaf_data(leaf) +
d6025579
CM
4680 data_end + dsize,
4681 btrfs_leaf_data(leaf) + data_end,
85e21bac 4682 last_off - data_end);
5f39d397 4683
85e21bac 4684 for (i = slot + nr; i < nritems; i++) {
5f39d397 4685 u32 ioff;
db94535d 4686
5f39d397 4687 item = btrfs_item_nr(leaf, i);
cfed81a0
CM
4688 ioff = btrfs_token_item_offset(leaf, item, &token);
4689 btrfs_set_token_item_offset(leaf, item,
4690 ioff + dsize, &token);
0783fcfc 4691 }
db94535d 4692
5f39d397 4693 memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot),
85e21bac 4694 btrfs_item_nr_offset(slot + nr),
d6025579 4695 sizeof(struct btrfs_item) *
85e21bac 4696 (nritems - slot - nr));
be0e5c09 4697 }
85e21bac
CM
4698 btrfs_set_header_nritems(leaf, nritems - nr);
4699 nritems -= nr;
5f39d397 4700
74123bd7 4701 /* delete the leaf if we've emptied it */
7518a238 4702 if (nritems == 0) {
5f39d397
CM
4703 if (leaf == root->node) {
4704 btrfs_set_header_level(leaf, 0);
9a8dd150 4705 } else {
f0486c68
YZ
4706 btrfs_set_path_blocking(path);
4707 clean_tree_block(trans, root, leaf);
143bede5 4708 btrfs_del_leaf(trans, root, path, leaf);
9a8dd150 4709 }
be0e5c09 4710 } else {
7518a238 4711 int used = leaf_space_used(leaf, 0, nritems);
aa5d6bed 4712 if (slot == 0) {
5f39d397
CM
4713 struct btrfs_disk_key disk_key;
4714
4715 btrfs_item_key(leaf, &disk_key, 0);
143bede5 4716 fixup_low_keys(trans, root, path, &disk_key, 1);
aa5d6bed 4717 }
aa5d6bed 4718
74123bd7 4719 /* delete the leaf if it is mostly empty */
d717aa1d 4720 if (used < BTRFS_LEAF_DATA_SIZE(root) / 3) {
be0e5c09
CM
4721 /* push_leaf_left fixes the path.
4722 * make sure the path still points to our leaf
4723 * for possible call to del_ptr below
4724 */
4920c9ac 4725 slot = path->slots[1];
5f39d397
CM
4726 extent_buffer_get(leaf);
4727
b9473439 4728 btrfs_set_path_blocking(path);
99d8f83c
CM
4729 wret = push_leaf_left(trans, root, path, 1, 1,
4730 1, (u32)-1);
54aa1f4d 4731 if (wret < 0 && wret != -ENOSPC)
aa5d6bed 4732 ret = wret;
5f39d397
CM
4733
4734 if (path->nodes[0] == leaf &&
4735 btrfs_header_nritems(leaf)) {
99d8f83c
CM
4736 wret = push_leaf_right(trans, root, path, 1,
4737 1, 1, 0);
54aa1f4d 4738 if (wret < 0 && wret != -ENOSPC)
aa5d6bed
CM
4739 ret = wret;
4740 }
5f39d397
CM
4741
4742 if (btrfs_header_nritems(leaf) == 0) {
323ac95b 4743 path->slots[1] = slot;
143bede5 4744 btrfs_del_leaf(trans, root, path, leaf);
5f39d397 4745 free_extent_buffer(leaf);
143bede5 4746 ret = 0;
5de08d7d 4747 } else {
925baedd
CM
4748 /* if we're still in the path, make sure
4749 * we're dirty. Otherwise, one of the
4750 * push_leaf functions must have already
4751 * dirtied this buffer
4752 */
4753 if (path->nodes[0] == leaf)
4754 btrfs_mark_buffer_dirty(leaf);
5f39d397 4755 free_extent_buffer(leaf);
be0e5c09 4756 }
d5719762 4757 } else {
5f39d397 4758 btrfs_mark_buffer_dirty(leaf);
be0e5c09
CM
4759 }
4760 }
aa5d6bed 4761 return ret;
be0e5c09
CM
4762}
4763
7bb86316 4764/*
925baedd 4765 * search the tree again to find a leaf with lesser keys
7bb86316
CM
4766 * returns 0 if it found something or 1 if there are no lesser leaves.
4767 * returns < 0 on io errors.
d352ac68
CM
4768 *
4769 * This may release the path, and so you may lose any locks held at the
4770 * time you call it.
7bb86316
CM
4771 */
4772int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
4773{
925baedd
CM
4774 struct btrfs_key key;
4775 struct btrfs_disk_key found_key;
4776 int ret;
7bb86316 4777
925baedd 4778 btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
7bb86316 4779
925baedd
CM
4780 if (key.offset > 0)
4781 key.offset--;
4782 else if (key.type > 0)
4783 key.type--;
4784 else if (key.objectid > 0)
4785 key.objectid--;
4786 else
4787 return 1;
7bb86316 4788
b3b4aa74 4789 btrfs_release_path(path);
925baedd
CM
4790 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4791 if (ret < 0)
4792 return ret;
4793 btrfs_item_key(path->nodes[0], &found_key, 0);
4794 ret = comp_keys(&found_key, &key);
4795 if (ret < 0)
4796 return 0;
4797 return 1;
7bb86316
CM
4798}
4799
3f157a2f
CM
4800/*
4801 * A helper function to walk down the tree starting at min_key, and looking
4802 * for nodes or leaves that are either in cache or have a minimum
d352ac68 4803 * transaction id. This is used by the btree defrag code, and tree logging
3f157a2f
CM
4804 *
4805 * This does not cow, but it does stuff the starting key it finds back
4806 * into min_key, so you can call btrfs_search_slot with cow=1 on the
4807 * key and get a writable path.
4808 *
4809 * This does lock as it descends, and path->keep_locks should be set
4810 * to 1 by the caller.
4811 *
4812 * This honors path->lowest_level to prevent descent past a given level
4813 * of the tree.
4814 *
d352ac68
CM
4815 * min_trans indicates the oldest transaction that you are interested
4816 * in walking through. Any nodes or leaves older than min_trans are
4817 * skipped over (without reading them).
4818 *
3f157a2f
CM
4819 * returns zero if something useful was found, < 0 on error and 1 if there
4820 * was nothing in the tree that matched the search criteria.
4821 */
4822int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
e02119d5 4823 struct btrfs_key *max_key,
3f157a2f
CM
4824 struct btrfs_path *path, int cache_only,
4825 u64 min_trans)
4826{
4827 struct extent_buffer *cur;
4828 struct btrfs_key found_key;
4829 int slot;
9652480b 4830 int sret;
3f157a2f
CM
4831 u32 nritems;
4832 int level;
4833 int ret = 1;
4834
934d375b 4835 WARN_ON(!path->keep_locks);
3f157a2f 4836again:
bd681513 4837 cur = btrfs_read_lock_root_node(root);
3f157a2f 4838 level = btrfs_header_level(cur);
e02119d5 4839 WARN_ON(path->nodes[level]);
3f157a2f 4840 path->nodes[level] = cur;
bd681513 4841 path->locks[level] = BTRFS_READ_LOCK;
3f157a2f
CM
4842
4843 if (btrfs_header_generation(cur) < min_trans) {
4844 ret = 1;
4845 goto out;
4846 }
d397712b 4847 while (1) {
3f157a2f
CM
4848 nritems = btrfs_header_nritems(cur);
4849 level = btrfs_header_level(cur);
9652480b 4850 sret = bin_search(cur, min_key, level, &slot);
3f157a2f 4851
323ac95b
CM
4852 /* at the lowest level, we're done, setup the path and exit */
4853 if (level == path->lowest_level) {
e02119d5
CM
4854 if (slot >= nritems)
4855 goto find_next_key;
3f157a2f
CM
4856 ret = 0;
4857 path->slots[level] = slot;
4858 btrfs_item_key_to_cpu(cur, &found_key, slot);
4859 goto out;
4860 }
9652480b
Y
4861 if (sret && slot > 0)
4862 slot--;
3f157a2f
CM
4863 /*
4864 * check this node pointer against the cache_only and
4865 * min_trans parameters. If it isn't in cache or is too
4866 * old, skip to the next one.
4867 */
d397712b 4868 while (slot < nritems) {
3f157a2f
CM
4869 u64 blockptr;
4870 u64 gen;
4871 struct extent_buffer *tmp;
e02119d5
CM
4872 struct btrfs_disk_key disk_key;
4873
3f157a2f
CM
4874 blockptr = btrfs_node_blockptr(cur, slot);
4875 gen = btrfs_node_ptr_generation(cur, slot);
4876 if (gen < min_trans) {
4877 slot++;
4878 continue;
4879 }
4880 if (!cache_only)
4881 break;
4882
e02119d5
CM
4883 if (max_key) {
4884 btrfs_node_key(cur, &disk_key, slot);
4885 if (comp_keys(&disk_key, max_key) >= 0) {
4886 ret = 1;
4887 goto out;
4888 }
4889 }
4890
3f157a2f
CM
4891 tmp = btrfs_find_tree_block(root, blockptr,
4892 btrfs_level_size(root, level - 1));
4893
b9fab919 4894 if (tmp && btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
3f157a2f
CM
4895 free_extent_buffer(tmp);
4896 break;
4897 }
4898 if (tmp)
4899 free_extent_buffer(tmp);
4900 slot++;
4901 }
e02119d5 4902find_next_key:
3f157a2f
CM
4903 /*
4904 * we didn't find a candidate key in this node, walk forward
4905 * and find another one
4906 */
4907 if (slot >= nritems) {
e02119d5 4908 path->slots[level] = slot;
b4ce94de 4909 btrfs_set_path_blocking(path);
e02119d5 4910 sret = btrfs_find_next_key(root, path, min_key, level,
3f157a2f 4911 cache_only, min_trans);
e02119d5 4912 if (sret == 0) {
b3b4aa74 4913 btrfs_release_path(path);
3f157a2f
CM
4914 goto again;
4915 } else {
4916 goto out;
4917 }
4918 }
4919 /* save our key for returning back */
4920 btrfs_node_key_to_cpu(cur, &found_key, slot);
4921 path->slots[level] = slot;
4922 if (level == path->lowest_level) {
4923 ret = 0;
f7c79f30 4924 unlock_up(path, level, 1, 0, NULL);
3f157a2f
CM
4925 goto out;
4926 }
b4ce94de 4927 btrfs_set_path_blocking(path);
3f157a2f 4928 cur = read_node_slot(root, cur, slot);
79787eaa 4929 BUG_ON(!cur); /* -ENOMEM */
3f157a2f 4930
bd681513 4931 btrfs_tree_read_lock(cur);
b4ce94de 4932
bd681513 4933 path->locks[level - 1] = BTRFS_READ_LOCK;
3f157a2f 4934 path->nodes[level - 1] = cur;
f7c79f30 4935 unlock_up(path, level, 1, 0, NULL);
bd681513 4936 btrfs_clear_path_blocking(path, NULL, 0);
3f157a2f
CM
4937 }
4938out:
4939 if (ret == 0)
4940 memcpy(min_key, &found_key, sizeof(found_key));
b4ce94de 4941 btrfs_set_path_blocking(path);
3f157a2f
CM
4942 return ret;
4943}
4944
7069830a
AB
4945static void tree_move_down(struct btrfs_root *root,
4946 struct btrfs_path *path,
4947 int *level, int root_level)
4948{
74dd17fb 4949 BUG_ON(*level == 0);
7069830a
AB
4950 path->nodes[*level - 1] = read_node_slot(root, path->nodes[*level],
4951 path->slots[*level]);
4952 path->slots[*level - 1] = 0;
4953 (*level)--;
4954}
4955
4956static int tree_move_next_or_upnext(struct btrfs_root *root,
4957 struct btrfs_path *path,
4958 int *level, int root_level)
4959{
4960 int ret = 0;
4961 int nritems;
4962 nritems = btrfs_header_nritems(path->nodes[*level]);
4963
4964 path->slots[*level]++;
4965
74dd17fb 4966 while (path->slots[*level] >= nritems) {
7069830a
AB
4967 if (*level == root_level)
4968 return -1;
4969
4970 /* move upnext */
4971 path->slots[*level] = 0;
4972 free_extent_buffer(path->nodes[*level]);
4973 path->nodes[*level] = NULL;
4974 (*level)++;
4975 path->slots[*level]++;
4976
4977 nritems = btrfs_header_nritems(path->nodes[*level]);
4978 ret = 1;
4979 }
4980 return ret;
4981}
4982
4983/*
4984 * Returns 1 if it had to move up and next. 0 is returned if it moved only next
4985 * or down.
4986 */
4987static int tree_advance(struct btrfs_root *root,
4988 struct btrfs_path *path,
4989 int *level, int root_level,
4990 int allow_down,
4991 struct btrfs_key *key)
4992{
4993 int ret;
4994
4995 if (*level == 0 || !allow_down) {
4996 ret = tree_move_next_or_upnext(root, path, level, root_level);
4997 } else {
4998 tree_move_down(root, path, level, root_level);
4999 ret = 0;
5000 }
5001 if (ret >= 0) {
5002 if (*level == 0)
5003 btrfs_item_key_to_cpu(path->nodes[*level], key,
5004 path->slots[*level]);
5005 else
5006 btrfs_node_key_to_cpu(path->nodes[*level], key,
5007 path->slots[*level]);
5008 }
5009 return ret;
5010}
5011
5012static int tree_compare_item(struct btrfs_root *left_root,
5013 struct btrfs_path *left_path,
5014 struct btrfs_path *right_path,
5015 char *tmp_buf)
5016{
5017 int cmp;
5018 int len1, len2;
5019 unsigned long off1, off2;
5020
5021 len1 = btrfs_item_size_nr(left_path->nodes[0], left_path->slots[0]);
5022 len2 = btrfs_item_size_nr(right_path->nodes[0], right_path->slots[0]);
5023 if (len1 != len2)
5024 return 1;
5025
5026 off1 = btrfs_item_ptr_offset(left_path->nodes[0], left_path->slots[0]);
5027 off2 = btrfs_item_ptr_offset(right_path->nodes[0],
5028 right_path->slots[0]);
5029
5030 read_extent_buffer(left_path->nodes[0], tmp_buf, off1, len1);
5031
5032 cmp = memcmp_extent_buffer(right_path->nodes[0], tmp_buf, off2, len1);
5033 if (cmp)
5034 return 1;
5035 return 0;
5036}
5037
5038#define ADVANCE 1
5039#define ADVANCE_ONLY_NEXT -1
5040
5041/*
5042 * This function compares two trees and calls the provided callback for
5043 * every changed/new/deleted item it finds.
5044 * If shared tree blocks are encountered, whole subtrees are skipped, making
5045 * the compare pretty fast on snapshotted subvolumes.
5046 *
5047 * This currently works on commit roots only. As commit roots are read only,
5048 * we don't do any locking. The commit roots are protected with transactions.
5049 * Transactions are ended and rejoined when a commit is tried in between.
5050 *
5051 * This function checks for modifications done to the trees while comparing.
5052 * If it detects a change, it aborts immediately.
5053 */
5054int btrfs_compare_trees(struct btrfs_root *left_root,
5055 struct btrfs_root *right_root,
5056 btrfs_changed_cb_t changed_cb, void *ctx)
5057{
5058 int ret;
5059 int cmp;
5060 struct btrfs_trans_handle *trans = NULL;
5061 struct btrfs_path *left_path = NULL;
5062 struct btrfs_path *right_path = NULL;
5063 struct btrfs_key left_key;
5064 struct btrfs_key right_key;
5065 char *tmp_buf = NULL;
5066 int left_root_level;
5067 int right_root_level;
5068 int left_level;
5069 int right_level;
5070 int left_end_reached;
5071 int right_end_reached;
5072 int advance_left;
5073 int advance_right;
5074 u64 left_blockptr;
5075 u64 right_blockptr;
5076 u64 left_start_ctransid;
5077 u64 right_start_ctransid;
5078 u64 ctransid;
5079
5080 left_path = btrfs_alloc_path();
5081 if (!left_path) {
5082 ret = -ENOMEM;
5083 goto out;
5084 }
5085 right_path = btrfs_alloc_path();
5086 if (!right_path) {
5087 ret = -ENOMEM;
5088 goto out;
5089 }
5090
5091 tmp_buf = kmalloc(left_root->leafsize, GFP_NOFS);
5092 if (!tmp_buf) {
5093 ret = -ENOMEM;
5094 goto out;
5095 }
5096
5097 left_path->search_commit_root = 1;
5098 left_path->skip_locking = 1;
5099 right_path->search_commit_root = 1;
5100 right_path->skip_locking = 1;
5101
5102 spin_lock(&left_root->root_times_lock);
5103 left_start_ctransid = btrfs_root_ctransid(&left_root->root_item);
5104 spin_unlock(&left_root->root_times_lock);
5105
5106 spin_lock(&right_root->root_times_lock);
5107 right_start_ctransid = btrfs_root_ctransid(&right_root->root_item);
5108 spin_unlock(&right_root->root_times_lock);
5109
5110 trans = btrfs_join_transaction(left_root);
5111 if (IS_ERR(trans)) {
5112 ret = PTR_ERR(trans);
5113 trans = NULL;
5114 goto out;
5115 }
5116
5117 /*
5118 * Strategy: Go to the first items of both trees. Then do
5119 *
5120 * If both trees are at level 0
5121 * Compare keys of current items
5122 * If left < right treat left item as new, advance left tree
5123 * and repeat
5124 * If left > right treat right item as deleted, advance right tree
5125 * and repeat
5126 * If left == right do deep compare of items, treat as changed if
5127 * needed, advance both trees and repeat
5128 * If both trees are at the same level but not at level 0
5129 * Compare keys of current nodes/leafs
5130 * If left < right advance left tree and repeat
5131 * If left > right advance right tree and repeat
5132 * If left == right compare blockptrs of the next nodes/leafs
5133 * If they match advance both trees but stay at the same level
5134 * and repeat
5135 * If they don't match advance both trees while allowing to go
5136 * deeper and repeat
5137 * If tree levels are different
5138 * Advance the tree that needs it and repeat
5139 *
5140 * Advancing a tree means:
5141 * If we are at level 0, try to go to the next slot. If that's not
5142 * possible, go one level up and repeat. Stop when we found a level
5143 * where we could go to the next slot. We may at this point be on a
5144 * node or a leaf.
5145 *
5146 * If we are not at level 0 and not on shared tree blocks, go one
5147 * level deeper.
5148 *
5149 * If we are not at level 0 and on shared tree blocks, go one slot to
5150 * the right if possible or go up and right.
5151 */
5152
5153 left_level = btrfs_header_level(left_root->commit_root);
5154 left_root_level = left_level;
5155 left_path->nodes[left_level] = left_root->commit_root;
5156 extent_buffer_get(left_path->nodes[left_level]);
5157
5158 right_level = btrfs_header_level(right_root->commit_root);
5159 right_root_level = right_level;
5160 right_path->nodes[right_level] = right_root->commit_root;
5161 extent_buffer_get(right_path->nodes[right_level]);
5162
5163 if (left_level == 0)
5164 btrfs_item_key_to_cpu(left_path->nodes[left_level],
5165 &left_key, left_path->slots[left_level]);
5166 else
5167 btrfs_node_key_to_cpu(left_path->nodes[left_level],
5168 &left_key, left_path->slots[left_level]);
5169 if (right_level == 0)
5170 btrfs_item_key_to_cpu(right_path->nodes[right_level],
5171 &right_key, right_path->slots[right_level]);
5172 else
5173 btrfs_node_key_to_cpu(right_path->nodes[right_level],
5174 &right_key, right_path->slots[right_level]);
5175
5176 left_end_reached = right_end_reached = 0;
5177 advance_left = advance_right = 0;
5178
5179 while (1) {
5180 /*
5181 * We need to make sure the transaction does not get committed
5182 * while we do anything on commit roots. This means, we need to
5183 * join and leave transactions for every item that we process.
5184 */
5185 if (trans && btrfs_should_end_transaction(trans, left_root)) {
5186 btrfs_release_path(left_path);
5187 btrfs_release_path(right_path);
5188
5189 ret = btrfs_end_transaction(trans, left_root);
5190 trans = NULL;
5191 if (ret < 0)
5192 goto out;
5193 }
5194 /* now rejoin the transaction */
5195 if (!trans) {
5196 trans = btrfs_join_transaction(left_root);
5197 if (IS_ERR(trans)) {
5198 ret = PTR_ERR(trans);
5199 trans = NULL;
5200 goto out;
5201 }
5202
5203 spin_lock(&left_root->root_times_lock);
5204 ctransid = btrfs_root_ctransid(&left_root->root_item);
5205 spin_unlock(&left_root->root_times_lock);
5206 if (ctransid != left_start_ctransid)
5207 left_start_ctransid = 0;
5208
5209 spin_lock(&right_root->root_times_lock);
5210 ctransid = btrfs_root_ctransid(&right_root->root_item);
5211 spin_unlock(&right_root->root_times_lock);
5212 if (ctransid != right_start_ctransid)
5213 right_start_ctransid = 0;
5214
5215 if (!left_start_ctransid || !right_start_ctransid) {
5216 WARN(1, KERN_WARNING
5217 "btrfs: btrfs_compare_tree detected "
5218 "a change in one of the trees while "
5219 "iterating. This is probably a "
5220 "bug.\n");
5221 ret = -EIO;
5222 goto out;
5223 }
5224
5225 /*
5226 * the commit root may have changed, so start again
5227 * where we stopped
5228 */
5229 left_path->lowest_level = left_level;
5230 right_path->lowest_level = right_level;
5231 ret = btrfs_search_slot(NULL, left_root,
5232 &left_key, left_path, 0, 0);
5233 if (ret < 0)
5234 goto out;
5235 ret = btrfs_search_slot(NULL, right_root,
5236 &right_key, right_path, 0, 0);
5237 if (ret < 0)
5238 goto out;
5239 }
5240
5241 if (advance_left && !left_end_reached) {
5242 ret = tree_advance(left_root, left_path, &left_level,
5243 left_root_level,
5244 advance_left != ADVANCE_ONLY_NEXT,
5245 &left_key);
5246 if (ret < 0)
5247 left_end_reached = ADVANCE;
5248 advance_left = 0;
5249 }
5250 if (advance_right && !right_end_reached) {
5251 ret = tree_advance(right_root, right_path, &right_level,
5252 right_root_level,
5253 advance_right != ADVANCE_ONLY_NEXT,
5254 &right_key);
5255 if (ret < 0)
5256 right_end_reached = ADVANCE;
5257 advance_right = 0;
5258 }
5259
5260 if (left_end_reached && right_end_reached) {
5261 ret = 0;
5262 goto out;
5263 } else if (left_end_reached) {
5264 if (right_level == 0) {
5265 ret = changed_cb(left_root, right_root,
5266 left_path, right_path,
5267 &right_key,
5268 BTRFS_COMPARE_TREE_DELETED,
5269 ctx);
5270 if (ret < 0)
5271 goto out;
5272 }
5273 advance_right = ADVANCE;
5274 continue;
5275 } else if (right_end_reached) {
5276 if (left_level == 0) {
5277 ret = changed_cb(left_root, right_root,
5278 left_path, right_path,
5279 &left_key,
5280 BTRFS_COMPARE_TREE_NEW,
5281 ctx);
5282 if (ret < 0)
5283 goto out;
5284 }
5285 advance_left = ADVANCE;
5286 continue;
5287 }
5288
5289 if (left_level == 0 && right_level == 0) {
5290 cmp = btrfs_comp_cpu_keys(&left_key, &right_key);
5291 if (cmp < 0) {
5292 ret = changed_cb(left_root, right_root,
5293 left_path, right_path,
5294 &left_key,
5295 BTRFS_COMPARE_TREE_NEW,
5296 ctx);
5297 if (ret < 0)
5298 goto out;
5299 advance_left = ADVANCE;
5300 } else if (cmp > 0) {
5301 ret = changed_cb(left_root, right_root,
5302 left_path, right_path,
5303 &right_key,
5304 BTRFS_COMPARE_TREE_DELETED,
5305 ctx);
5306 if (ret < 0)
5307 goto out;
5308 advance_right = ADVANCE;
5309 } else {
74dd17fb 5310 WARN_ON(!extent_buffer_uptodate(left_path->nodes[0]));
7069830a
AB
5311 ret = tree_compare_item(left_root, left_path,
5312 right_path, tmp_buf);
5313 if (ret) {
74dd17fb 5314 WARN_ON(!extent_buffer_uptodate(left_path->nodes[0]));
7069830a
AB
5315 ret = changed_cb(left_root, right_root,
5316 left_path, right_path,
5317 &left_key,
5318 BTRFS_COMPARE_TREE_CHANGED,
5319 ctx);
5320 if (ret < 0)
5321 goto out;
5322 }
5323 advance_left = ADVANCE;
5324 advance_right = ADVANCE;
5325 }
5326 } else if (left_level == right_level) {
5327 cmp = btrfs_comp_cpu_keys(&left_key, &right_key);
5328 if (cmp < 0) {
5329 advance_left = ADVANCE;
5330 } else if (cmp > 0) {
5331 advance_right = ADVANCE;
5332 } else {
5333 left_blockptr = btrfs_node_blockptr(
5334 left_path->nodes[left_level],
5335 left_path->slots[left_level]);
5336 right_blockptr = btrfs_node_blockptr(
5337 right_path->nodes[right_level],
5338 right_path->slots[right_level]);
5339 if (left_blockptr == right_blockptr) {
5340 /*
5341 * As we're on a shared block, don't
5342 * allow to go deeper.
5343 */
5344 advance_left = ADVANCE_ONLY_NEXT;
5345 advance_right = ADVANCE_ONLY_NEXT;
5346 } else {
5347 advance_left = ADVANCE;
5348 advance_right = ADVANCE;
5349 }
5350 }
5351 } else if (left_level < right_level) {
5352 advance_right = ADVANCE;
5353 } else {
5354 advance_left = ADVANCE;
5355 }
5356 }
5357
5358out:
5359 btrfs_free_path(left_path);
5360 btrfs_free_path(right_path);
5361 kfree(tmp_buf);
5362
5363 if (trans) {
5364 if (!ret)
5365 ret = btrfs_end_transaction(trans, left_root);
5366 else
5367 btrfs_end_transaction(trans, left_root);
5368 }
5369
5370 return ret;
5371}
5372
3f157a2f
CM
5373/*
5374 * this is similar to btrfs_next_leaf, but does not try to preserve
5375 * and fixup the path. It looks for and returns the next key in the
5376 * tree based on the current path and the cache_only and min_trans
5377 * parameters.
5378 *
5379 * 0 is returned if another key is found, < 0 if there are any errors
5380 * and 1 is returned if there are no higher keys in the tree
5381 *
5382 * path->keep_locks should be set to 1 on the search made before
5383 * calling this function.
5384 */
e7a84565 5385int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
33c66f43 5386 struct btrfs_key *key, int level,
3f157a2f 5387 int cache_only, u64 min_trans)
e7a84565 5388{
e7a84565
CM
5389 int slot;
5390 struct extent_buffer *c;
5391
934d375b 5392 WARN_ON(!path->keep_locks);
d397712b 5393 while (level < BTRFS_MAX_LEVEL) {
e7a84565
CM
5394 if (!path->nodes[level])
5395 return 1;
5396
5397 slot = path->slots[level] + 1;
5398 c = path->nodes[level];
3f157a2f 5399next:
e7a84565 5400 if (slot >= btrfs_header_nritems(c)) {
33c66f43
YZ
5401 int ret;
5402 int orig_lowest;
5403 struct btrfs_key cur_key;
5404 if (level + 1 >= BTRFS_MAX_LEVEL ||
5405 !path->nodes[level + 1])
e7a84565 5406 return 1;
33c66f43
YZ
5407
5408 if (path->locks[level + 1]) {
5409 level++;
5410 continue;
5411 }
5412
5413 slot = btrfs_header_nritems(c) - 1;
5414 if (level == 0)
5415 btrfs_item_key_to_cpu(c, &cur_key, slot);
5416 else
5417 btrfs_node_key_to_cpu(c, &cur_key, slot);
5418
5419 orig_lowest = path->lowest_level;
b3b4aa74 5420 btrfs_release_path(path);
33c66f43
YZ
5421 path->lowest_level = level;
5422 ret = btrfs_search_slot(NULL, root, &cur_key, path,
5423 0, 0);
5424 path->lowest_level = orig_lowest;
5425 if (ret < 0)
5426 return ret;
5427
5428 c = path->nodes[level];
5429 slot = path->slots[level];
5430 if (ret == 0)
5431 slot++;
5432 goto next;
e7a84565 5433 }
33c66f43 5434
e7a84565
CM
5435 if (level == 0)
5436 btrfs_item_key_to_cpu(c, key, slot);
3f157a2f
CM
5437 else {
5438 u64 blockptr = btrfs_node_blockptr(c, slot);
5439 u64 gen = btrfs_node_ptr_generation(c, slot);
5440
5441 if (cache_only) {
5442 struct extent_buffer *cur;
5443 cur = btrfs_find_tree_block(root, blockptr,
5444 btrfs_level_size(root, level - 1));
b9fab919
CM
5445 if (!cur ||
5446 btrfs_buffer_uptodate(cur, gen, 1) <= 0) {
3f157a2f
CM
5447 slot++;
5448 if (cur)
5449 free_extent_buffer(cur);
5450 goto next;
5451 }
5452 free_extent_buffer(cur);
5453 }
5454 if (gen < min_trans) {
5455 slot++;
5456 goto next;
5457 }
e7a84565 5458 btrfs_node_key_to_cpu(c, key, slot);
3f157a2f 5459 }
e7a84565
CM
5460 return 0;
5461 }
5462 return 1;
5463}
5464
97571fd0 5465/*
925baedd 5466 * search the tree again to find a leaf with greater keys
0f70abe2
CM
5467 * returns 0 if it found something or 1 if there are no greater leaves.
5468 * returns < 0 on io errors.
97571fd0 5469 */
234b63a0 5470int btrfs_next_leaf(struct btrfs_root *root, struct btrfs_path *path)
3d7806ec
JS
5471{
5472 return btrfs_next_old_leaf(root, path, 0);
5473}
5474
5475int btrfs_next_old_leaf(struct btrfs_root *root, struct btrfs_path *path,
5476 u64 time_seq)
d97e63b6
CM
5477{
5478 int slot;
8e73f275 5479 int level;
5f39d397 5480 struct extent_buffer *c;
8e73f275 5481 struct extent_buffer *next;
925baedd
CM
5482 struct btrfs_key key;
5483 u32 nritems;
5484 int ret;
8e73f275 5485 int old_spinning = path->leave_spinning;
bd681513 5486 int next_rw_lock = 0;
925baedd
CM
5487
5488 nritems = btrfs_header_nritems(path->nodes[0]);
d397712b 5489 if (nritems == 0)
925baedd 5490 return 1;
925baedd 5491
8e73f275
CM
5492 btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
5493again:
5494 level = 1;
5495 next = NULL;
bd681513 5496 next_rw_lock = 0;
b3b4aa74 5497 btrfs_release_path(path);
8e73f275 5498
a2135011 5499 path->keep_locks = 1;
31533fb2 5500 path->leave_spinning = 1;
8e73f275 5501
3d7806ec
JS
5502 if (time_seq)
5503 ret = btrfs_search_old_slot(root, &key, path, time_seq);
5504 else
5505 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
925baedd
CM
5506 path->keep_locks = 0;
5507
5508 if (ret < 0)
5509 return ret;
5510
a2135011 5511 nritems = btrfs_header_nritems(path->nodes[0]);
168fd7d2
CM
5512 /*
5513 * by releasing the path above we dropped all our locks. A balance
5514 * could have added more items next to the key that used to be
5515 * at the very end of the block. So, check again here and
5516 * advance the path if there are now more items available.
5517 */
a2135011 5518 if (nritems > 0 && path->slots[0] < nritems - 1) {
e457afec
YZ
5519 if (ret == 0)
5520 path->slots[0]++;
8e73f275 5521 ret = 0;
925baedd
CM
5522 goto done;
5523 }
d97e63b6 5524
d397712b 5525 while (level < BTRFS_MAX_LEVEL) {
8e73f275
CM
5526 if (!path->nodes[level]) {
5527 ret = 1;
5528 goto done;
5529 }
5f39d397 5530
d97e63b6
CM
5531 slot = path->slots[level] + 1;
5532 c = path->nodes[level];
5f39d397 5533 if (slot >= btrfs_header_nritems(c)) {
d97e63b6 5534 level++;
8e73f275
CM
5535 if (level == BTRFS_MAX_LEVEL) {
5536 ret = 1;
5537 goto done;
5538 }
d97e63b6
CM
5539 continue;
5540 }
5f39d397 5541
925baedd 5542 if (next) {
bd681513 5543 btrfs_tree_unlock_rw(next, next_rw_lock);
5f39d397 5544 free_extent_buffer(next);
925baedd 5545 }
5f39d397 5546
8e73f275 5547 next = c;
bd681513 5548 next_rw_lock = path->locks[level];
8e73f275 5549 ret = read_block_for_search(NULL, root, path, &next, level,
5d9e75c4 5550 slot, &key, 0);
8e73f275
CM
5551 if (ret == -EAGAIN)
5552 goto again;
5f39d397 5553
76a05b35 5554 if (ret < 0) {
b3b4aa74 5555 btrfs_release_path(path);
76a05b35
CM
5556 goto done;
5557 }
5558
5cd57b2c 5559 if (!path->skip_locking) {
bd681513 5560 ret = btrfs_try_tree_read_lock(next);
d42244a0
JS
5561 if (!ret && time_seq) {
5562 /*
5563 * If we don't get the lock, we may be racing
5564 * with push_leaf_left, holding that lock while
5565 * itself waiting for the leaf we've currently
5566 * locked. To solve this situation, we give up
5567 * on our lock and cycle.
5568 */
cf538830 5569 free_extent_buffer(next);
d42244a0
JS
5570 btrfs_release_path(path);
5571 cond_resched();
5572 goto again;
5573 }
8e73f275
CM
5574 if (!ret) {
5575 btrfs_set_path_blocking(path);
bd681513 5576 btrfs_tree_read_lock(next);
31533fb2 5577 btrfs_clear_path_blocking(path, next,
bd681513 5578 BTRFS_READ_LOCK);
8e73f275 5579 }
31533fb2 5580 next_rw_lock = BTRFS_READ_LOCK;
5cd57b2c 5581 }
d97e63b6
CM
5582 break;
5583 }
5584 path->slots[level] = slot;
d397712b 5585 while (1) {
d97e63b6
CM
5586 level--;
5587 c = path->nodes[level];
925baedd 5588 if (path->locks[level])
bd681513 5589 btrfs_tree_unlock_rw(c, path->locks[level]);
8e73f275 5590
5f39d397 5591 free_extent_buffer(c);
d97e63b6
CM
5592 path->nodes[level] = next;
5593 path->slots[level] = 0;
a74a4b97 5594 if (!path->skip_locking)
bd681513 5595 path->locks[level] = next_rw_lock;
d97e63b6
CM
5596 if (!level)
5597 break;
b4ce94de 5598
8e73f275 5599 ret = read_block_for_search(NULL, root, path, &next, level,
5d9e75c4 5600 0, &key, 0);
8e73f275
CM
5601 if (ret == -EAGAIN)
5602 goto again;
5603
76a05b35 5604 if (ret < 0) {
b3b4aa74 5605 btrfs_release_path(path);
76a05b35
CM
5606 goto done;
5607 }
5608
5cd57b2c 5609 if (!path->skip_locking) {
bd681513 5610 ret = btrfs_try_tree_read_lock(next);
8e73f275
CM
5611 if (!ret) {
5612 btrfs_set_path_blocking(path);
bd681513 5613 btrfs_tree_read_lock(next);
31533fb2 5614 btrfs_clear_path_blocking(path, next,
bd681513
CM
5615 BTRFS_READ_LOCK);
5616 }
31533fb2 5617 next_rw_lock = BTRFS_READ_LOCK;
5cd57b2c 5618 }
d97e63b6 5619 }
8e73f275 5620 ret = 0;
925baedd 5621done:
f7c79f30 5622 unlock_up(path, 0, 1, 0, NULL);
8e73f275
CM
5623 path->leave_spinning = old_spinning;
5624 if (!old_spinning)
5625 btrfs_set_path_blocking(path);
5626
5627 return ret;
d97e63b6 5628}
0b86a832 5629
3f157a2f
CM
5630/*
5631 * this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
5632 * searching until it gets past min_objectid or finds an item of 'type'
5633 *
5634 * returns 0 if something is found, 1 if nothing was found and < 0 on error
5635 */
0b86a832
CM
5636int btrfs_previous_item(struct btrfs_root *root,
5637 struct btrfs_path *path, u64 min_objectid,
5638 int type)
5639{
5640 struct btrfs_key found_key;
5641 struct extent_buffer *leaf;
e02119d5 5642 u32 nritems;
0b86a832
CM
5643 int ret;
5644
d397712b 5645 while (1) {
0b86a832 5646 if (path->slots[0] == 0) {
b4ce94de 5647 btrfs_set_path_blocking(path);
0b86a832
CM
5648 ret = btrfs_prev_leaf(root, path);
5649 if (ret != 0)
5650 return ret;
5651 } else {
5652 path->slots[0]--;
5653 }
5654 leaf = path->nodes[0];
e02119d5
CM
5655 nritems = btrfs_header_nritems(leaf);
5656 if (nritems == 0)
5657 return 1;
5658 if (path->slots[0] == nritems)
5659 path->slots[0]--;
5660
0b86a832 5661 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
e02119d5
CM
5662 if (found_key.objectid < min_objectid)
5663 break;
0a4eefbb
YZ
5664 if (found_key.type == type)
5665 return 0;
e02119d5
CM
5666 if (found_key.objectid == min_objectid &&
5667 found_key.type < type)
5668 break;
0b86a832
CM
5669 }
5670 return 1;
5671}