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