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