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