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