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