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