]> git.proxmox.com Git - mirror_ubuntu-hirsute-kernel.git/blame - fs/btrfs/ctree.c
btrfs: remove unused argument seed from btrfs_find_device
[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
DS
1685 if (oip + key_size <= PAGE_SIZE) {
1686 const unsigned long idx = offset >> PAGE_SHIFT;
1687 char *kaddr = page_address(eb->pages[idx]);
5f39d397 1688
5cd17f34 1689 tmp = (struct btrfs_disk_key *)(kaddr + oip);
5f39d397 1690 } else {
5cd17f34
DS
1691 read_extent_buffer(eb, &unaligned, offset, key_size);
1692 tmp = &unaligned;
5f39d397 1693 }
5cd17f34 1694
be0e5c09
CM
1695 ret = comp_keys(tmp, key);
1696
1697 if (ret < 0)
1698 low = mid + 1;
1699 else if (ret > 0)
1700 high = mid;
1701 else {
1702 *slot = mid;
1703 return 0;
1704 }
1705 }
1706 *slot = low;
1707 return 1;
1708}
1709
97571fd0
CM
1710/*
1711 * simple bin_search frontend that does the right thing for
1712 * leaves vs nodes
1713 */
a74b35ec 1714int btrfs_bin_search(struct extent_buffer *eb, const struct btrfs_key *key,
e3b83361 1715 int *slot)
be0e5c09 1716{
e3b83361 1717 if (btrfs_header_level(eb) == 0)
5f39d397
CM
1718 return generic_bin_search(eb,
1719 offsetof(struct btrfs_leaf, items),
0783fcfc 1720 sizeof(struct btrfs_item),
5f39d397 1721 key, btrfs_header_nritems(eb),
7518a238 1722 slot);
f775738f 1723 else
5f39d397
CM
1724 return generic_bin_search(eb,
1725 offsetof(struct btrfs_node, ptrs),
123abc88 1726 sizeof(struct btrfs_key_ptr),
5f39d397 1727 key, btrfs_header_nritems(eb),
7518a238 1728 slot);
be0e5c09
CM
1729}
1730
f0486c68
YZ
1731static void root_add_used(struct btrfs_root *root, u32 size)
1732{
1733 spin_lock(&root->accounting_lock);
1734 btrfs_set_root_used(&root->root_item,
1735 btrfs_root_used(&root->root_item) + size);
1736 spin_unlock(&root->accounting_lock);
1737}
1738
1739static void root_sub_used(struct btrfs_root *root, u32 size)
1740{
1741 spin_lock(&root->accounting_lock);
1742 btrfs_set_root_used(&root->root_item,
1743 btrfs_root_used(&root->root_item) - size);
1744 spin_unlock(&root->accounting_lock);
1745}
1746
d352ac68
CM
1747/* given a node and slot number, this reads the blocks it points to. The
1748 * extent buffer is returned with a reference taken (but unlocked).
d352ac68 1749 */
4b231ae4
DS
1750struct extent_buffer *btrfs_read_node_slot(struct extent_buffer *parent,
1751 int slot)
bb803951 1752{
ca7a79ad 1753 int level = btrfs_header_level(parent);
416bc658 1754 struct extent_buffer *eb;
581c1760 1755 struct btrfs_key first_key;
416bc658 1756
fb770ae4
LB
1757 if (slot < 0 || slot >= btrfs_header_nritems(parent))
1758 return ERR_PTR(-ENOENT);
ca7a79ad
CM
1759
1760 BUG_ON(level == 0);
1761
581c1760 1762 btrfs_node_key_to_cpu(parent, &first_key, slot);
d0d20b0f 1763 eb = read_tree_block(parent->fs_info, btrfs_node_blockptr(parent, slot),
1b7ec85e 1764 btrfs_header_owner(parent),
581c1760
QW
1765 btrfs_node_ptr_generation(parent, slot),
1766 level - 1, &first_key);
fb770ae4
LB
1767 if (!IS_ERR(eb) && !extent_buffer_uptodate(eb)) {
1768 free_extent_buffer(eb);
1769 eb = ERR_PTR(-EIO);
416bc658
JB
1770 }
1771
1772 return eb;
bb803951
CM
1773}
1774
d352ac68
CM
1775/*
1776 * node level balancing, used to make sure nodes are in proper order for
1777 * item deletion. We balance from the top down, so we have to make sure
1778 * that a deletion won't leave an node completely empty later on.
1779 */
e02119d5 1780static noinline int balance_level(struct btrfs_trans_handle *trans,
98ed5174
CM
1781 struct btrfs_root *root,
1782 struct btrfs_path *path, int level)
bb803951 1783{
0b246afa 1784 struct btrfs_fs_info *fs_info = root->fs_info;
5f39d397
CM
1785 struct extent_buffer *right = NULL;
1786 struct extent_buffer *mid;
1787 struct extent_buffer *left = NULL;
1788 struct extent_buffer *parent = NULL;
bb803951
CM
1789 int ret = 0;
1790 int wret;
1791 int pslot;
bb803951 1792 int orig_slot = path->slots[level];
79f95c82 1793 u64 orig_ptr;
bb803951 1794
98e6b1eb 1795 ASSERT(level > 0);
bb803951 1796
5f39d397 1797 mid = path->nodes[level];
b4ce94de 1798
ac5887c8 1799 WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK);
7bb86316
CM
1800 WARN_ON(btrfs_header_generation(mid) != trans->transid);
1801
1d4f8a0c 1802 orig_ptr = btrfs_node_blockptr(mid, orig_slot);
79f95c82 1803
a05a9bb1 1804 if (level < BTRFS_MAX_LEVEL - 1) {
5f39d397 1805 parent = path->nodes[level + 1];
a05a9bb1
LZ
1806 pslot = path->slots[level + 1];
1807 }
bb803951 1808
40689478
CM
1809 /*
1810 * deal with the case where there is only one pointer in the root
1811 * by promoting the node below to a root
1812 */
5f39d397
CM
1813 if (!parent) {
1814 struct extent_buffer *child;
bb803951 1815
5f39d397 1816 if (btrfs_header_nritems(mid) != 1)
bb803951
CM
1817 return 0;
1818
1819 /* promote the child to a root */
4b231ae4 1820 child = btrfs_read_node_slot(mid, 0);
fb770ae4
LB
1821 if (IS_ERR(child)) {
1822 ret = PTR_ERR(child);
0b246afa 1823 btrfs_handle_fs_error(fs_info, ret, NULL);
305a26af
MF
1824 goto enospc;
1825 }
1826
925baedd 1827 btrfs_tree_lock(child);
9631e4cc
JB
1828 ret = btrfs_cow_block(trans, root, child, mid, 0, &child,
1829 BTRFS_NESTING_COW);
f0486c68
YZ
1830 if (ret) {
1831 btrfs_tree_unlock(child);
1832 free_extent_buffer(child);
1833 goto enospc;
1834 }
2f375ab9 1835
d9d19a01
DS
1836 ret = tree_mod_log_insert_root(root->node, child, 1);
1837 BUG_ON(ret < 0);
240f62c8 1838 rcu_assign_pointer(root->node, child);
925baedd 1839
0b86a832 1840 add_root_to_dirty_list(root);
925baedd 1841 btrfs_tree_unlock(child);
b4ce94de 1842
925baedd 1843 path->locks[level] = 0;
bb803951 1844 path->nodes[level] = NULL;
6a884d7d 1845 btrfs_clean_tree_block(mid);
925baedd 1846 btrfs_tree_unlock(mid);
bb803951 1847 /* once for the path */
5f39d397 1848 free_extent_buffer(mid);
f0486c68
YZ
1849
1850 root_sub_used(root, mid->len);
5581a51a 1851 btrfs_free_tree_block(trans, root, mid, 0, 1);
bb803951 1852 /* once for the root ptr */
3083ee2e 1853 free_extent_buffer_stale(mid);
f0486c68 1854 return 0;
bb803951 1855 }
5f39d397 1856 if (btrfs_header_nritems(mid) >
0b246afa 1857 BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 4)
bb803951
CM
1858 return 0;
1859
4b231ae4 1860 left = btrfs_read_node_slot(parent, pslot - 1);
fb770ae4
LB
1861 if (IS_ERR(left))
1862 left = NULL;
1863
5f39d397 1864 if (left) {
bf77467a 1865 __btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
5f39d397 1866 wret = btrfs_cow_block(trans, root, left,
9631e4cc 1867 parent, pslot - 1, &left,
bf59a5a2 1868 BTRFS_NESTING_LEFT_COW);
54aa1f4d
CM
1869 if (wret) {
1870 ret = wret;
1871 goto enospc;
1872 }
2cc58cf2 1873 }
fb770ae4 1874
4b231ae4 1875 right = btrfs_read_node_slot(parent, pslot + 1);
fb770ae4
LB
1876 if (IS_ERR(right))
1877 right = NULL;
1878
5f39d397 1879 if (right) {
bf77467a 1880 __btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
5f39d397 1881 wret = btrfs_cow_block(trans, root, right,
9631e4cc 1882 parent, pslot + 1, &right,
bf59a5a2 1883 BTRFS_NESTING_RIGHT_COW);
2cc58cf2
CM
1884 if (wret) {
1885 ret = wret;
1886 goto enospc;
1887 }
1888 }
1889
1890 /* first, try to make some room in the middle buffer */
5f39d397
CM
1891 if (left) {
1892 orig_slot += btrfs_header_nritems(left);
d30a668f 1893 wret = push_node_left(trans, left, mid, 1);
79f95c82
CM
1894 if (wret < 0)
1895 ret = wret;
bb803951 1896 }
79f95c82
CM
1897
1898 /*
1899 * then try to empty the right most buffer into the middle
1900 */
5f39d397 1901 if (right) {
d30a668f 1902 wret = push_node_left(trans, mid, right, 1);
54aa1f4d 1903 if (wret < 0 && wret != -ENOSPC)
79f95c82 1904 ret = wret;
5f39d397 1905 if (btrfs_header_nritems(right) == 0) {
6a884d7d 1906 btrfs_clean_tree_block(right);
925baedd 1907 btrfs_tree_unlock(right);
afe5fea7 1908 del_ptr(root, path, level + 1, pslot + 1);
f0486c68 1909 root_sub_used(root, right->len);
5581a51a 1910 btrfs_free_tree_block(trans, root, right, 0, 1);
3083ee2e 1911 free_extent_buffer_stale(right);
f0486c68 1912 right = NULL;
bb803951 1913 } else {
5f39d397
CM
1914 struct btrfs_disk_key right_key;
1915 btrfs_node_key(right, &right_key, 0);
0e82bcfe
DS
1916 ret = tree_mod_log_insert_key(parent, pslot + 1,
1917 MOD_LOG_KEY_REPLACE, GFP_NOFS);
1918 BUG_ON(ret < 0);
5f39d397
CM
1919 btrfs_set_node_key(parent, &right_key, pslot + 1);
1920 btrfs_mark_buffer_dirty(parent);
bb803951
CM
1921 }
1922 }
5f39d397 1923 if (btrfs_header_nritems(mid) == 1) {
79f95c82
CM
1924 /*
1925 * we're not allowed to leave a node with one item in the
1926 * tree during a delete. A deletion from lower in the tree
1927 * could try to delete the only pointer in this node.
1928 * So, pull some keys from the left.
1929 * There has to be a left pointer at this point because
1930 * otherwise we would have pulled some pointers from the
1931 * right
1932 */
305a26af
MF
1933 if (!left) {
1934 ret = -EROFS;
0b246afa 1935 btrfs_handle_fs_error(fs_info, ret, NULL);
305a26af
MF
1936 goto enospc;
1937 }
55d32ed8 1938 wret = balance_node_right(trans, mid, left);
54aa1f4d 1939 if (wret < 0) {
79f95c82 1940 ret = wret;
54aa1f4d
CM
1941 goto enospc;
1942 }
bce4eae9 1943 if (wret == 1) {
d30a668f 1944 wret = push_node_left(trans, left, mid, 1);
bce4eae9
CM
1945 if (wret < 0)
1946 ret = wret;
1947 }
79f95c82
CM
1948 BUG_ON(wret == 1);
1949 }
5f39d397 1950 if (btrfs_header_nritems(mid) == 0) {
6a884d7d 1951 btrfs_clean_tree_block(mid);
925baedd 1952 btrfs_tree_unlock(mid);
afe5fea7 1953 del_ptr(root, path, level + 1, pslot);
f0486c68 1954 root_sub_used(root, mid->len);
5581a51a 1955 btrfs_free_tree_block(trans, root, mid, 0, 1);
3083ee2e 1956 free_extent_buffer_stale(mid);
f0486c68 1957 mid = NULL;
79f95c82
CM
1958 } else {
1959 /* update the parent key to reflect our changes */
5f39d397
CM
1960 struct btrfs_disk_key mid_key;
1961 btrfs_node_key(mid, &mid_key, 0);
0e82bcfe
DS
1962 ret = tree_mod_log_insert_key(parent, pslot,
1963 MOD_LOG_KEY_REPLACE, GFP_NOFS);
1964 BUG_ON(ret < 0);
5f39d397
CM
1965 btrfs_set_node_key(parent, &mid_key, pslot);
1966 btrfs_mark_buffer_dirty(parent);
79f95c82 1967 }
bb803951 1968
79f95c82 1969 /* update the path */
5f39d397
CM
1970 if (left) {
1971 if (btrfs_header_nritems(left) > orig_slot) {
67439dad 1972 atomic_inc(&left->refs);
925baedd 1973 /* left was locked after cow */
5f39d397 1974 path->nodes[level] = left;
bb803951
CM
1975 path->slots[level + 1] -= 1;
1976 path->slots[level] = orig_slot;
925baedd
CM
1977 if (mid) {
1978 btrfs_tree_unlock(mid);
5f39d397 1979 free_extent_buffer(mid);
925baedd 1980 }
bb803951 1981 } else {
5f39d397 1982 orig_slot -= btrfs_header_nritems(left);
bb803951
CM
1983 path->slots[level] = orig_slot;
1984 }
1985 }
79f95c82 1986 /* double check we haven't messed things up */
e20d96d6 1987 if (orig_ptr !=
5f39d397 1988 btrfs_node_blockptr(path->nodes[level], path->slots[level]))
79f95c82 1989 BUG();
54aa1f4d 1990enospc:
925baedd
CM
1991 if (right) {
1992 btrfs_tree_unlock(right);
5f39d397 1993 free_extent_buffer(right);
925baedd
CM
1994 }
1995 if (left) {
1996 if (path->nodes[level] != left)
1997 btrfs_tree_unlock(left);
5f39d397 1998 free_extent_buffer(left);
925baedd 1999 }
bb803951
CM
2000 return ret;
2001}
2002
d352ac68
CM
2003/* Node balancing for insertion. Here we only split or push nodes around
2004 * when they are completely full. This is also done top down, so we
2005 * have to be pessimistic.
2006 */
d397712b 2007static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
98ed5174
CM
2008 struct btrfs_root *root,
2009 struct btrfs_path *path, int level)
e66f709b 2010{
0b246afa 2011 struct btrfs_fs_info *fs_info = root->fs_info;
5f39d397
CM
2012 struct extent_buffer *right = NULL;
2013 struct extent_buffer *mid;
2014 struct extent_buffer *left = NULL;
2015 struct extent_buffer *parent = NULL;
e66f709b
CM
2016 int ret = 0;
2017 int wret;
2018 int pslot;
2019 int orig_slot = path->slots[level];
e66f709b
CM
2020
2021 if (level == 0)
2022 return 1;
2023
5f39d397 2024 mid = path->nodes[level];
7bb86316 2025 WARN_ON(btrfs_header_generation(mid) != trans->transid);
e66f709b 2026
a05a9bb1 2027 if (level < BTRFS_MAX_LEVEL - 1) {
5f39d397 2028 parent = path->nodes[level + 1];
a05a9bb1
LZ
2029 pslot = path->slots[level + 1];
2030 }
e66f709b 2031
5f39d397 2032 if (!parent)
e66f709b 2033 return 1;
e66f709b 2034
4b231ae4 2035 left = btrfs_read_node_slot(parent, pslot - 1);
fb770ae4
LB
2036 if (IS_ERR(left))
2037 left = NULL;
e66f709b
CM
2038
2039 /* first, try to make some room in the middle buffer */
5f39d397 2040 if (left) {
e66f709b 2041 u32 left_nr;
925baedd 2042
bf77467a 2043 __btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
b4ce94de 2044
5f39d397 2045 left_nr = btrfs_header_nritems(left);
0b246afa 2046 if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
33ade1f8
CM
2047 wret = 1;
2048 } else {
5f39d397 2049 ret = btrfs_cow_block(trans, root, left, parent,
9631e4cc 2050 pslot - 1, &left,
bf59a5a2 2051 BTRFS_NESTING_LEFT_COW);
54aa1f4d
CM
2052 if (ret)
2053 wret = 1;
2054 else {
d30a668f 2055 wret = push_node_left(trans, left, mid, 0);
54aa1f4d 2056 }
33ade1f8 2057 }
e66f709b
CM
2058 if (wret < 0)
2059 ret = wret;
2060 if (wret == 0) {
5f39d397 2061 struct btrfs_disk_key disk_key;
e66f709b 2062 orig_slot += left_nr;
5f39d397 2063 btrfs_node_key(mid, &disk_key, 0);
0e82bcfe
DS
2064 ret = tree_mod_log_insert_key(parent, pslot,
2065 MOD_LOG_KEY_REPLACE, GFP_NOFS);
2066 BUG_ON(ret < 0);
5f39d397
CM
2067 btrfs_set_node_key(parent, &disk_key, pslot);
2068 btrfs_mark_buffer_dirty(parent);
2069 if (btrfs_header_nritems(left) > orig_slot) {
2070 path->nodes[level] = left;
e66f709b
CM
2071 path->slots[level + 1] -= 1;
2072 path->slots[level] = orig_slot;
925baedd 2073 btrfs_tree_unlock(mid);
5f39d397 2074 free_extent_buffer(mid);
e66f709b
CM
2075 } else {
2076 orig_slot -=
5f39d397 2077 btrfs_header_nritems(left);
e66f709b 2078 path->slots[level] = orig_slot;
925baedd 2079 btrfs_tree_unlock(left);
5f39d397 2080 free_extent_buffer(left);
e66f709b 2081 }
e66f709b
CM
2082 return 0;
2083 }
925baedd 2084 btrfs_tree_unlock(left);
5f39d397 2085 free_extent_buffer(left);
e66f709b 2086 }
4b231ae4 2087 right = btrfs_read_node_slot(parent, pslot + 1);
fb770ae4
LB
2088 if (IS_ERR(right))
2089 right = NULL;
e66f709b
CM
2090
2091 /*
2092 * then try to empty the right most buffer into the middle
2093 */
5f39d397 2094 if (right) {
33ade1f8 2095 u32 right_nr;
b4ce94de 2096
bf77467a 2097 __btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
b4ce94de 2098
5f39d397 2099 right_nr = btrfs_header_nritems(right);
0b246afa 2100 if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
33ade1f8
CM
2101 wret = 1;
2102 } else {
5f39d397
CM
2103 ret = btrfs_cow_block(trans, root, right,
2104 parent, pslot + 1,
bf59a5a2 2105 &right, BTRFS_NESTING_RIGHT_COW);
54aa1f4d
CM
2106 if (ret)
2107 wret = 1;
2108 else {
55d32ed8 2109 wret = balance_node_right(trans, right, mid);
54aa1f4d 2110 }
33ade1f8 2111 }
e66f709b
CM
2112 if (wret < 0)
2113 ret = wret;
2114 if (wret == 0) {
5f39d397
CM
2115 struct btrfs_disk_key disk_key;
2116
2117 btrfs_node_key(right, &disk_key, 0);
0e82bcfe
DS
2118 ret = tree_mod_log_insert_key(parent, pslot + 1,
2119 MOD_LOG_KEY_REPLACE, GFP_NOFS);
2120 BUG_ON(ret < 0);
5f39d397
CM
2121 btrfs_set_node_key(parent, &disk_key, pslot + 1);
2122 btrfs_mark_buffer_dirty(parent);
2123
2124 if (btrfs_header_nritems(mid) <= orig_slot) {
2125 path->nodes[level] = right;
e66f709b
CM
2126 path->slots[level + 1] += 1;
2127 path->slots[level] = orig_slot -
5f39d397 2128 btrfs_header_nritems(mid);
925baedd 2129 btrfs_tree_unlock(mid);
5f39d397 2130 free_extent_buffer(mid);
e66f709b 2131 } else {
925baedd 2132 btrfs_tree_unlock(right);
5f39d397 2133 free_extent_buffer(right);
e66f709b 2134 }
e66f709b
CM
2135 return 0;
2136 }
925baedd 2137 btrfs_tree_unlock(right);
5f39d397 2138 free_extent_buffer(right);
e66f709b 2139 }
e66f709b
CM
2140 return 1;
2141}
2142
3c69faec 2143/*
d352ac68
CM
2144 * readahead one full node of leaves, finding things that are close
2145 * to the block in 'slot', and triggering ra on them.
3c69faec 2146 */
2ff7e61e 2147static void reada_for_search(struct btrfs_fs_info *fs_info,
c8c42864
CM
2148 struct btrfs_path *path,
2149 int level, int slot, u64 objectid)
3c69faec 2150{
5f39d397 2151 struct extent_buffer *node;
01f46658 2152 struct btrfs_disk_key disk_key;
3c69faec 2153 u32 nritems;
3c69faec 2154 u64 search;
a7175319 2155 u64 target;
6b80053d 2156 u64 nread = 0;
5f39d397 2157 struct extent_buffer *eb;
6b80053d
CM
2158 u32 nr;
2159 u32 blocksize;
2160 u32 nscan = 0;
db94535d 2161
a6b6e75e 2162 if (level != 1)
6702ed49
CM
2163 return;
2164
2165 if (!path->nodes[level])
3c69faec
CM
2166 return;
2167
5f39d397 2168 node = path->nodes[level];
925baedd 2169
3c69faec 2170 search = btrfs_node_blockptr(node, slot);
0b246afa
JM
2171 blocksize = fs_info->nodesize;
2172 eb = find_extent_buffer(fs_info, search);
5f39d397
CM
2173 if (eb) {
2174 free_extent_buffer(eb);
3c69faec
CM
2175 return;
2176 }
2177
a7175319 2178 target = search;
6b80053d 2179
5f39d397 2180 nritems = btrfs_header_nritems(node);
6b80053d 2181 nr = slot;
25b8b936 2182
d397712b 2183 while (1) {
e4058b54 2184 if (path->reada == READA_BACK) {
6b80053d
CM
2185 if (nr == 0)
2186 break;
2187 nr--;
e4058b54 2188 } else if (path->reada == READA_FORWARD) {
6b80053d
CM
2189 nr++;
2190 if (nr >= nritems)
2191 break;
3c69faec 2192 }
e4058b54 2193 if (path->reada == READA_BACK && objectid) {
01f46658
CM
2194 btrfs_node_key(node, &disk_key, nr);
2195 if (btrfs_disk_key_objectid(&disk_key) != objectid)
2196 break;
2197 }
6b80053d 2198 search = btrfs_node_blockptr(node, nr);
a7175319
CM
2199 if ((search <= target && target - search <= 65536) ||
2200 (search > target && search - target <= 65536)) {
bfb484d9 2201 btrfs_readahead_node_child(node, nr);
6b80053d
CM
2202 nread += blocksize;
2203 }
2204 nscan++;
a7175319 2205 if ((nread > 65536 || nscan > 32))
6b80053d 2206 break;
3c69faec
CM
2207 }
2208}
925baedd 2209
bfb484d9 2210static noinline void reada_for_balance(struct btrfs_path *path, int level)
b4ce94de 2211{
bfb484d9 2212 struct extent_buffer *parent;
b4ce94de
CM
2213 int slot;
2214 int nritems;
b4ce94de 2215
8c594ea8 2216 parent = path->nodes[level + 1];
b4ce94de 2217 if (!parent)
0b08851f 2218 return;
b4ce94de
CM
2219
2220 nritems = btrfs_header_nritems(parent);
8c594ea8 2221 slot = path->slots[level + 1];
b4ce94de 2222
bfb484d9
JB
2223 if (slot > 0)
2224 btrfs_readahead_node_child(parent, slot - 1);
2225 if (slot + 1 < nritems)
2226 btrfs_readahead_node_child(parent, slot + 1);
b4ce94de
CM
2227}
2228
2229
d352ac68 2230/*
d397712b
CM
2231 * when we walk down the tree, it is usually safe to unlock the higher layers
2232 * in the tree. The exceptions are when our path goes through slot 0, because
2233 * operations on the tree might require changing key pointers higher up in the
2234 * tree.
d352ac68 2235 *
d397712b
CM
2236 * callers might also have set path->keep_locks, which tells this code to keep
2237 * the lock if the path points to the last slot in the block. This is part of
2238 * walking through the tree, and selecting the next slot in the higher block.
d352ac68 2239 *
d397712b
CM
2240 * lowest_unlock sets the lowest level in the tree we're allowed to unlock. so
2241 * if lowest_unlock is 1, level 0 won't be unlocked
d352ac68 2242 */
e02119d5 2243static noinline void unlock_up(struct btrfs_path *path, int level,
f7c79f30
CM
2244 int lowest_unlock, int min_write_lock_level,
2245 int *write_lock_level)
925baedd
CM
2246{
2247 int i;
2248 int skip_level = level;
051e1b9f 2249 int no_skips = 0;
925baedd
CM
2250 struct extent_buffer *t;
2251
2252 for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2253 if (!path->nodes[i])
2254 break;
2255 if (!path->locks[i])
2256 break;
051e1b9f 2257 if (!no_skips && path->slots[i] == 0) {
925baedd
CM
2258 skip_level = i + 1;
2259 continue;
2260 }
051e1b9f 2261 if (!no_skips && path->keep_locks) {
925baedd
CM
2262 u32 nritems;
2263 t = path->nodes[i];
2264 nritems = btrfs_header_nritems(t);
051e1b9f 2265 if (nritems < 1 || path->slots[i] >= nritems - 1) {
925baedd
CM
2266 skip_level = i + 1;
2267 continue;
2268 }
2269 }
051e1b9f
CM
2270 if (skip_level < i && i >= lowest_unlock)
2271 no_skips = 1;
2272
925baedd 2273 t = path->nodes[i];
d80bb3f9 2274 if (i >= lowest_unlock && i > skip_level) {
bd681513 2275 btrfs_tree_unlock_rw(t, path->locks[i]);
925baedd 2276 path->locks[i] = 0;
f7c79f30
CM
2277 if (write_lock_level &&
2278 i > min_write_lock_level &&
2279 i <= *write_lock_level) {
2280 *write_lock_level = i - 1;
2281 }
925baedd
CM
2282 }
2283 }
2284}
2285
c8c42864
CM
2286/*
2287 * helper function for btrfs_search_slot. The goal is to find a block
2288 * in cache without setting the path to blocking. If we find the block
2289 * we return zero and the path is unchanged.
2290 *
2291 * If we can't find the block, we set the path blocking and do some
2292 * reada. -EAGAIN is returned and the search must be repeated.
2293 */
2294static int
d07b8528
LB
2295read_block_for_search(struct btrfs_root *root, struct btrfs_path *p,
2296 struct extent_buffer **eb_ret, int level, int slot,
cda79c54 2297 const struct btrfs_key *key)
c8c42864 2298{
0b246afa 2299 struct btrfs_fs_info *fs_info = root->fs_info;
c8c42864
CM
2300 u64 blocknr;
2301 u64 gen;
c8c42864 2302 struct extent_buffer *tmp;
581c1760 2303 struct btrfs_key first_key;
76a05b35 2304 int ret;
581c1760 2305 int parent_level;
c8c42864 2306
213ff4b7
NB
2307 blocknr = btrfs_node_blockptr(*eb_ret, slot);
2308 gen = btrfs_node_ptr_generation(*eb_ret, slot);
2309 parent_level = btrfs_header_level(*eb_ret);
2310 btrfs_node_key_to_cpu(*eb_ret, &first_key, slot);
c8c42864 2311
0b246afa 2312 tmp = find_extent_buffer(fs_info, blocknr);
cb44921a 2313 if (tmp) {
b9fab919 2314 /* first we do an atomic uptodate check */
bdf7c00e 2315 if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
448de471
QW
2316 /*
2317 * Do extra check for first_key, eb can be stale due to
2318 * being cached, read from scrub, or have multiple
2319 * parents (shared tree blocks).
2320 */
e064d5e9 2321 if (btrfs_verify_level_key(tmp,
448de471
QW
2322 parent_level - 1, &first_key, gen)) {
2323 free_extent_buffer(tmp);
2324 return -EUCLEAN;
2325 }
bdf7c00e
JB
2326 *eb_ret = tmp;
2327 return 0;
2328 }
2329
bdf7c00e 2330 /* now we're allowed to do a blocking uptodate check */
581c1760 2331 ret = btrfs_read_buffer(tmp, gen, parent_level - 1, &first_key);
bdf7c00e
JB
2332 if (!ret) {
2333 *eb_ret = tmp;
2334 return 0;
cb44921a 2335 }
bdf7c00e
JB
2336 free_extent_buffer(tmp);
2337 btrfs_release_path(p);
2338 return -EIO;
c8c42864
CM
2339 }
2340
2341 /*
2342 * reduce lock contention at high levels
2343 * of the btree by dropping locks before
76a05b35
CM
2344 * we read. Don't release the lock on the current
2345 * level because we need to walk this node to figure
2346 * out which blocks to read.
c8c42864 2347 */
8c594ea8 2348 btrfs_unlock_up_safe(p, level + 1);
8c594ea8 2349
e4058b54 2350 if (p->reada != READA_NONE)
2ff7e61e 2351 reada_for_search(fs_info, p, level, slot, key->objectid);
c8c42864 2352
76a05b35 2353 ret = -EAGAIN;
1b7ec85e
JB
2354 tmp = read_tree_block(fs_info, blocknr, root->root_key.objectid,
2355 gen, parent_level - 1, &first_key);
64c043de 2356 if (!IS_ERR(tmp)) {
76a05b35
CM
2357 /*
2358 * If the read above didn't mark this buffer up to date,
2359 * it will never end up being up to date. Set ret to EIO now
2360 * and give up so that our caller doesn't loop forever
2361 * on our EAGAINs.
2362 */
e6a1d6fd 2363 if (!extent_buffer_uptodate(tmp))
76a05b35 2364 ret = -EIO;
c8c42864 2365 free_extent_buffer(tmp);
c871b0f2
LB
2366 } else {
2367 ret = PTR_ERR(tmp);
76a05b35 2368 }
02a3307a
LB
2369
2370 btrfs_release_path(p);
76a05b35 2371 return ret;
c8c42864
CM
2372}
2373
2374/*
2375 * helper function for btrfs_search_slot. This does all of the checks
2376 * for node-level blocks and does any balancing required based on
2377 * the ins_len.
2378 *
2379 * If no extra work was required, zero is returned. If we had to
2380 * drop the path, -EAGAIN is returned and btrfs_search_slot must
2381 * start over
2382 */
2383static int
2384setup_nodes_for_search(struct btrfs_trans_handle *trans,
2385 struct btrfs_root *root, struct btrfs_path *p,
bd681513
CM
2386 struct extent_buffer *b, int level, int ins_len,
2387 int *write_lock_level)
c8c42864 2388{
0b246afa 2389 struct btrfs_fs_info *fs_info = root->fs_info;
c8c42864 2390 int ret;
0b246afa 2391
c8c42864 2392 if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
0b246afa 2393 BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3) {
c8c42864
CM
2394 int sret;
2395
bd681513
CM
2396 if (*write_lock_level < level + 1) {
2397 *write_lock_level = level + 1;
2398 btrfs_release_path(p);
2399 goto again;
2400 }
2401
bfb484d9 2402 reada_for_balance(p, level);
c8c42864 2403 sret = split_node(trans, root, p, level);
c8c42864
CM
2404
2405 BUG_ON(sret > 0);
2406 if (sret) {
2407 ret = sret;
2408 goto done;
2409 }
2410 b = p->nodes[level];
2411 } else if (ins_len < 0 && btrfs_header_nritems(b) <
0b246afa 2412 BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 2) {
c8c42864
CM
2413 int sret;
2414
bd681513
CM
2415 if (*write_lock_level < level + 1) {
2416 *write_lock_level = level + 1;
2417 btrfs_release_path(p);
2418 goto again;
2419 }
2420
bfb484d9 2421 reada_for_balance(p, level);
c8c42864 2422 sret = balance_level(trans, root, p, level);
c8c42864
CM
2423
2424 if (sret) {
2425 ret = sret;
2426 goto done;
2427 }
2428 b = p->nodes[level];
2429 if (!b) {
b3b4aa74 2430 btrfs_release_path(p);
c8c42864
CM
2431 goto again;
2432 }
2433 BUG_ON(btrfs_header_nritems(b) == 1);
2434 }
2435 return 0;
2436
2437again:
2438 ret = -EAGAIN;
2439done:
2440 return ret;
2441}
2442
381cf658 2443int btrfs_find_item(struct btrfs_root *fs_root, struct btrfs_path *path,
e33d5c3d
KN
2444 u64 iobjectid, u64 ioff, u8 key_type,
2445 struct btrfs_key *found_key)
2446{
2447 int ret;
2448 struct btrfs_key key;
2449 struct extent_buffer *eb;
381cf658
DS
2450
2451 ASSERT(path);
1d4c08e0 2452 ASSERT(found_key);
e33d5c3d
KN
2453
2454 key.type = key_type;
2455 key.objectid = iobjectid;
2456 key.offset = ioff;
2457
2458 ret = btrfs_search_slot(NULL, fs_root, &key, path, 0, 0);
1d4c08e0 2459 if (ret < 0)
e33d5c3d
KN
2460 return ret;
2461
2462 eb = path->nodes[0];
2463 if (ret && path->slots[0] >= btrfs_header_nritems(eb)) {
2464 ret = btrfs_next_leaf(fs_root, path);
2465 if (ret)
2466 return ret;
2467 eb = path->nodes[0];
2468 }
2469
2470 btrfs_item_key_to_cpu(eb, found_key, path->slots[0]);
2471 if (found_key->type != key.type ||
2472 found_key->objectid != key.objectid)
2473 return 1;
2474
2475 return 0;
2476}
2477
1fc28d8e
LB
2478static struct extent_buffer *btrfs_search_slot_get_root(struct btrfs_root *root,
2479 struct btrfs_path *p,
2480 int write_lock_level)
2481{
2482 struct btrfs_fs_info *fs_info = root->fs_info;
2483 struct extent_buffer *b;
2484 int root_lock;
2485 int level = 0;
2486
2487 /* We try very hard to do read locks on the root */
2488 root_lock = BTRFS_READ_LOCK;
2489
2490 if (p->search_commit_root) {
be6821f8
FM
2491 /*
2492 * The commit roots are read only so we always do read locks,
2493 * and we always must hold the commit_root_sem when doing
2494 * searches on them, the only exception is send where we don't
2495 * want to block transaction commits for a long time, so
2496 * we need to clone the commit root in order to avoid races
2497 * with transaction commits that create a snapshot of one of
2498 * the roots used by a send operation.
2499 */
2500 if (p->need_commit_sem) {
1fc28d8e 2501 down_read(&fs_info->commit_root_sem);
be6821f8 2502 b = btrfs_clone_extent_buffer(root->commit_root);
1fc28d8e 2503 up_read(&fs_info->commit_root_sem);
be6821f8
FM
2504 if (!b)
2505 return ERR_PTR(-ENOMEM);
2506
2507 } else {
2508 b = root->commit_root;
67439dad 2509 atomic_inc(&b->refs);
be6821f8
FM
2510 }
2511 level = btrfs_header_level(b);
f9ddfd05
LB
2512 /*
2513 * Ensure that all callers have set skip_locking when
2514 * p->search_commit_root = 1.
2515 */
2516 ASSERT(p->skip_locking == 1);
1fc28d8e
LB
2517
2518 goto out;
2519 }
2520
2521 if (p->skip_locking) {
2522 b = btrfs_root_node(root);
2523 level = btrfs_header_level(b);
2524 goto out;
2525 }
2526
2527 /*
662c653b
LB
2528 * If the level is set to maximum, we can skip trying to get the read
2529 * lock.
1fc28d8e 2530 */
662c653b
LB
2531 if (write_lock_level < BTRFS_MAX_LEVEL) {
2532 /*
2533 * We don't know the level of the root node until we actually
2534 * have it read locked
2535 */
51899412 2536 b = __btrfs_read_lock_root_node(root, p->recurse);
662c653b
LB
2537 level = btrfs_header_level(b);
2538 if (level > write_lock_level)
2539 goto out;
2540
2541 /* Whoops, must trade for write lock */
2542 btrfs_tree_read_unlock(b);
2543 free_extent_buffer(b);
2544 }
1fc28d8e 2545
1fc28d8e
LB
2546 b = btrfs_lock_root_node(root);
2547 root_lock = BTRFS_WRITE_LOCK;
2548
2549 /* The level might have changed, check again */
2550 level = btrfs_header_level(b);
2551
2552out:
2553 p->nodes[level] = b;
2554 if (!p->skip_locking)
2555 p->locks[level] = root_lock;
2556 /*
2557 * Callers are responsible for dropping b's references.
2558 */
2559 return b;
2560}
2561
2562
74123bd7 2563/*
4271ecea
NB
2564 * btrfs_search_slot - look for a key in a tree and perform necessary
2565 * modifications to preserve tree invariants.
74123bd7 2566 *
4271ecea
NB
2567 * @trans: Handle of transaction, used when modifying the tree
2568 * @p: Holds all btree nodes along the search path
2569 * @root: The root node of the tree
2570 * @key: The key we are looking for
2571 * @ins_len: Indicates purpose of search, for inserts it is 1, for
2572 * deletions it's -1. 0 for plain searches
2573 * @cow: boolean should CoW operations be performed. Must always be 1
2574 * when modifying the tree.
97571fd0 2575 *
4271ecea
NB
2576 * If @ins_len > 0, nodes and leaves will be split as we walk down the tree.
2577 * If @ins_len < 0, nodes will be merged as we walk down the tree (if possible)
2578 *
2579 * If @key is found, 0 is returned and you can find the item in the leaf level
2580 * of the path (level 0)
2581 *
2582 * If @key isn't found, 1 is returned and the leaf level of the path (level 0)
2583 * points to the slot where it should be inserted
2584 *
2585 * If an error is encountered while searching the tree a negative error number
2586 * is returned
74123bd7 2587 */
310712b2
OS
2588int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2589 const struct btrfs_key *key, struct btrfs_path *p,
2590 int ins_len, int cow)
be0e5c09 2591{
5f39d397 2592 struct extent_buffer *b;
be0e5c09
CM
2593 int slot;
2594 int ret;
33c66f43 2595 int err;
be0e5c09 2596 int level;
925baedd 2597 int lowest_unlock = 1;
bd681513
CM
2598 /* everything at write_lock_level or lower must be write locked */
2599 int write_lock_level = 0;
9f3a7427 2600 u8 lowest_level = 0;
f7c79f30 2601 int min_write_lock_level;
d7396f07 2602 int prev_cmp;
9f3a7427 2603
6702ed49 2604 lowest_level = p->lowest_level;
323ac95b 2605 WARN_ON(lowest_level && ins_len > 0);
22b0ebda 2606 WARN_ON(p->nodes[0] != NULL);
eb653de1 2607 BUG_ON(!cow && ins_len);
25179201 2608
bd681513 2609 if (ins_len < 0) {
925baedd 2610 lowest_unlock = 2;
65b51a00 2611
bd681513
CM
2612 /* when we are removing items, we might have to go up to level
2613 * two as we update tree pointers Make sure we keep write
2614 * for those levels as well
2615 */
2616 write_lock_level = 2;
2617 } else if (ins_len > 0) {
2618 /*
2619 * for inserting items, make sure we have a write lock on
2620 * level 1 so we can update keys
2621 */
2622 write_lock_level = 1;
2623 }
2624
2625 if (!cow)
2626 write_lock_level = -1;
2627
09a2a8f9 2628 if (cow && (p->keep_locks || p->lowest_level))
bd681513
CM
2629 write_lock_level = BTRFS_MAX_LEVEL;
2630
f7c79f30
CM
2631 min_write_lock_level = write_lock_level;
2632
bb803951 2633again:
d7396f07 2634 prev_cmp = -1;
1fc28d8e 2635 b = btrfs_search_slot_get_root(root, p, write_lock_level);
be6821f8
FM
2636 if (IS_ERR(b)) {
2637 ret = PTR_ERR(b);
2638 goto done;
2639 }
925baedd 2640
eb60ceac 2641 while (b) {
f624d976
QW
2642 int dec = 0;
2643
5f39d397 2644 level = btrfs_header_level(b);
65b51a00 2645
02217ed2 2646 if (cow) {
9ea2c7c9
NB
2647 bool last_level = (level == (BTRFS_MAX_LEVEL - 1));
2648
c8c42864
CM
2649 /*
2650 * if we don't really need to cow this block
2651 * then we don't want to set the path blocking,
2652 * so we test it here
2653 */
64c12921
JM
2654 if (!should_cow_block(trans, root, b)) {
2655 trans->dirty = true;
65b51a00 2656 goto cow_done;
64c12921 2657 }
5d4f98a2 2658
bd681513
CM
2659 /*
2660 * must have write locks on this node and the
2661 * parent
2662 */
5124e00e
JB
2663 if (level > write_lock_level ||
2664 (level + 1 > write_lock_level &&
2665 level + 1 < BTRFS_MAX_LEVEL &&
2666 p->nodes[level + 1])) {
bd681513
CM
2667 write_lock_level = level + 1;
2668 btrfs_release_path(p);
2669 goto again;
2670 }
2671
9ea2c7c9
NB
2672 if (last_level)
2673 err = btrfs_cow_block(trans, root, b, NULL, 0,
9631e4cc
JB
2674 &b,
2675 BTRFS_NESTING_COW);
9ea2c7c9
NB
2676 else
2677 err = btrfs_cow_block(trans, root, b,
2678 p->nodes[level + 1],
9631e4cc
JB
2679 p->slots[level + 1], &b,
2680 BTRFS_NESTING_COW);
33c66f43 2681 if (err) {
33c66f43 2682 ret = err;
65b51a00 2683 goto done;
54aa1f4d 2684 }
02217ed2 2685 }
65b51a00 2686cow_done:
eb60ceac 2687 p->nodes[level] = b;
52398340
LB
2688 /*
2689 * Leave path with blocking locks to avoid massive
2690 * lock context switch, this is made on purpose.
2691 */
b4ce94de
CM
2692
2693 /*
2694 * we have a lock on b and as long as we aren't changing
2695 * the tree, there is no way to for the items in b to change.
2696 * It is safe to drop the lock on our parent before we
2697 * go through the expensive btree search on b.
2698 *
eb653de1
FDBM
2699 * If we're inserting or deleting (ins_len != 0), then we might
2700 * be changing slot zero, which may require changing the parent.
2701 * So, we can't drop the lock until after we know which slot
2702 * we're operating on.
b4ce94de 2703 */
eb653de1
FDBM
2704 if (!ins_len && !p->keep_locks) {
2705 int u = level + 1;
2706
2707 if (u < BTRFS_MAX_LEVEL && p->locks[u]) {
2708 btrfs_tree_unlock_rw(p->nodes[u], p->locks[u]);
2709 p->locks[u] = 0;
2710 }
2711 }
b4ce94de 2712
995e9a16
NB
2713 /*
2714 * If btrfs_bin_search returns an exact match (prev_cmp == 0)
2715 * we can safely assume the target key will always be in slot 0
2716 * on lower levels due to the invariants BTRFS' btree provides,
2717 * namely that a btrfs_key_ptr entry always points to the
2718 * lowest key in the child node, thus we can skip searching
2719 * lower levels
2720 */
2721 if (prev_cmp == 0) {
2722 slot = 0;
2723 ret = 0;
2724 } else {
2725 ret = btrfs_bin_search(b, key, &slot);
2726 prev_cmp = ret;
2727 if (ret < 0)
2728 goto done;
2729 }
b4ce94de 2730
f624d976 2731 if (level == 0) {
be0e5c09 2732 p->slots[level] = slot;
87b29b20 2733 if (ins_len > 0 &&
e902baac 2734 btrfs_leaf_free_space(b) < ins_len) {
bd681513
CM
2735 if (write_lock_level < 1) {
2736 write_lock_level = 1;
2737 btrfs_release_path(p);
2738 goto again;
2739 }
2740
33c66f43
YZ
2741 err = split_leaf(trans, root, key,
2742 p, ins_len, ret == 0);
b4ce94de 2743
33c66f43
YZ
2744 BUG_ON(err > 0);
2745 if (err) {
2746 ret = err;
65b51a00
CM
2747 goto done;
2748 }
5c680ed6 2749 }
459931ec 2750 if (!p->search_for_split)
f7c79f30 2751 unlock_up(p, level, lowest_unlock,
4b6f8e96 2752 min_write_lock_level, NULL);
65b51a00 2753 goto done;
be0e5c09 2754 }
f624d976
QW
2755 if (ret && slot > 0) {
2756 dec = 1;
2757 slot--;
2758 }
2759 p->slots[level] = slot;
2760 err = setup_nodes_for_search(trans, root, p, b, level, ins_len,
2761 &write_lock_level);
2762 if (err == -EAGAIN)
2763 goto again;
2764 if (err) {
2765 ret = err;
2766 goto done;
2767 }
2768 b = p->nodes[level];
2769 slot = p->slots[level];
2770
2771 /*
2772 * Slot 0 is special, if we change the key we have to update
2773 * the parent pointer which means we must have a write lock on
2774 * the parent
2775 */
2776 if (slot == 0 && ins_len && write_lock_level < level + 1) {
2777 write_lock_level = level + 1;
2778 btrfs_release_path(p);
2779 goto again;
2780 }
2781
2782 unlock_up(p, level, lowest_unlock, min_write_lock_level,
2783 &write_lock_level);
2784
2785 if (level == lowest_level) {
2786 if (dec)
2787 p->slots[level]++;
2788 goto done;
2789 }
2790
2791 err = read_block_for_search(root, p, &b, level, slot, key);
2792 if (err == -EAGAIN)
2793 goto again;
2794 if (err) {
2795 ret = err;
2796 goto done;
2797 }
2798
2799 if (!p->skip_locking) {
2800 level = btrfs_header_level(b);
2801 if (level <= write_lock_level) {
ac5887c8 2802 btrfs_tree_lock(b);
f624d976
QW
2803 p->locks[level] = BTRFS_WRITE_LOCK;
2804 } else {
ac5887c8
JB
2805 __btrfs_tree_read_lock(b, BTRFS_NESTING_NORMAL,
2806 p->recurse);
f624d976
QW
2807 p->locks[level] = BTRFS_READ_LOCK;
2808 }
2809 p->nodes[level] = b;
2810 }
be0e5c09 2811 }
65b51a00
CM
2812 ret = 1;
2813done:
5f5bc6b1 2814 if (ret < 0 && !p->skip_release_on_error)
b3b4aa74 2815 btrfs_release_path(p);
65b51a00 2816 return ret;
be0e5c09
CM
2817}
2818
5d9e75c4
JS
2819/*
2820 * Like btrfs_search_slot, this looks for a key in the given tree. It uses the
2821 * current state of the tree together with the operations recorded in the tree
2822 * modification log to search for the key in a previous version of this tree, as
2823 * denoted by the time_seq parameter.
2824 *
2825 * Naturally, there is no support for insert, delete or cow operations.
2826 *
2827 * The resulting path and return value will be set up as if we called
2828 * btrfs_search_slot at that point in time with ins_len and cow both set to 0.
2829 */
310712b2 2830int btrfs_search_old_slot(struct btrfs_root *root, const struct btrfs_key *key,
5d9e75c4
JS
2831 struct btrfs_path *p, u64 time_seq)
2832{
0b246afa 2833 struct btrfs_fs_info *fs_info = root->fs_info;
5d9e75c4
JS
2834 struct extent_buffer *b;
2835 int slot;
2836 int ret;
2837 int err;
2838 int level;
2839 int lowest_unlock = 1;
2840 u8 lowest_level = 0;
2841
2842 lowest_level = p->lowest_level;
2843 WARN_ON(p->nodes[0] != NULL);
2844
2845 if (p->search_commit_root) {
2846 BUG_ON(time_seq);
2847 return btrfs_search_slot(NULL, root, key, p, 0, 0);
2848 }
2849
2850again:
5d9e75c4 2851 b = get_old_root(root, time_seq);
315bed43
NB
2852 if (!b) {
2853 ret = -EIO;
2854 goto done;
2855 }
5d9e75c4 2856 level = btrfs_header_level(b);
5d9e75c4
JS
2857 p->locks[level] = BTRFS_READ_LOCK;
2858
2859 while (b) {
abe9339d
QW
2860 int dec = 0;
2861
5d9e75c4
JS
2862 level = btrfs_header_level(b);
2863 p->nodes[level] = b;
5d9e75c4
JS
2864
2865 /*
2866 * we have a lock on b and as long as we aren't changing
2867 * the tree, there is no way to for the items in b to change.
2868 * It is safe to drop the lock on our parent before we
2869 * go through the expensive btree search on b.
2870 */
2871 btrfs_unlock_up_safe(p, level + 1);
2872
995e9a16 2873 ret = btrfs_bin_search(b, key, &slot);
cbca7d59
FM
2874 if (ret < 0)
2875 goto done;
5d9e75c4 2876
abe9339d 2877 if (level == 0) {
5d9e75c4
JS
2878 p->slots[level] = slot;
2879 unlock_up(p, level, lowest_unlock, 0, NULL);
abe9339d
QW
2880 goto done;
2881 }
5d9e75c4 2882
abe9339d
QW
2883 if (ret && slot > 0) {
2884 dec = 1;
2885 slot--;
2886 }
2887 p->slots[level] = slot;
2888 unlock_up(p, level, lowest_unlock, 0, NULL);
5d9e75c4 2889
abe9339d
QW
2890 if (level == lowest_level) {
2891 if (dec)
2892 p->slots[level]++;
2893 goto done;
2894 }
5d9e75c4 2895
abe9339d
QW
2896 err = read_block_for_search(root, p, &b, level, slot, key);
2897 if (err == -EAGAIN)
2898 goto again;
2899 if (err) {
2900 ret = err;
5d9e75c4
JS
2901 goto done;
2902 }
abe9339d
QW
2903
2904 level = btrfs_header_level(b);
ac5887c8 2905 btrfs_tree_read_lock(b);
abe9339d
QW
2906 b = tree_mod_log_rewind(fs_info, p, b, time_seq);
2907 if (!b) {
2908 ret = -ENOMEM;
2909 goto done;
2910 }
2911 p->locks[level] = BTRFS_READ_LOCK;
2912 p->nodes[level] = b;
5d9e75c4
JS
2913 }
2914 ret = 1;
2915done:
5d9e75c4
JS
2916 if (ret < 0)
2917 btrfs_release_path(p);
2918
2919 return ret;
2920}
2921
2f38b3e1
AJ
2922/*
2923 * helper to use instead of search slot if no exact match is needed but
2924 * instead the next or previous item should be returned.
2925 * When find_higher is true, the next higher item is returned, the next lower
2926 * otherwise.
2927 * When return_any and find_higher are both true, and no higher item is found,
2928 * return the next lower instead.
2929 * When return_any is true and find_higher is false, and no lower item is found,
2930 * return the next higher instead.
2931 * It returns 0 if any item is found, 1 if none is found (tree empty), and
2932 * < 0 on error
2933 */
2934int btrfs_search_slot_for_read(struct btrfs_root *root,
310712b2
OS
2935 const struct btrfs_key *key,
2936 struct btrfs_path *p, int find_higher,
2937 int return_any)
2f38b3e1
AJ
2938{
2939 int ret;
2940 struct extent_buffer *leaf;
2941
2942again:
2943 ret = btrfs_search_slot(NULL, root, key, p, 0, 0);
2944 if (ret <= 0)
2945 return ret;
2946 /*
2947 * a return value of 1 means the path is at the position where the
2948 * item should be inserted. Normally this is the next bigger item,
2949 * but in case the previous item is the last in a leaf, path points
2950 * to the first free slot in the previous leaf, i.e. at an invalid
2951 * item.
2952 */
2953 leaf = p->nodes[0];
2954
2955 if (find_higher) {
2956 if (p->slots[0] >= btrfs_header_nritems(leaf)) {
2957 ret = btrfs_next_leaf(root, p);
2958 if (ret <= 0)
2959 return ret;
2960 if (!return_any)
2961 return 1;
2962 /*
2963 * no higher item found, return the next
2964 * lower instead
2965 */
2966 return_any = 0;
2967 find_higher = 0;
2968 btrfs_release_path(p);
2969 goto again;
2970 }
2971 } else {
e6793769
AJ
2972 if (p->slots[0] == 0) {
2973 ret = btrfs_prev_leaf(root, p);
2974 if (ret < 0)
2975 return ret;
2976 if (!ret) {
23c6bf6a
FDBM
2977 leaf = p->nodes[0];
2978 if (p->slots[0] == btrfs_header_nritems(leaf))
2979 p->slots[0]--;
e6793769 2980 return 0;
2f38b3e1 2981 }
e6793769
AJ
2982 if (!return_any)
2983 return 1;
2984 /*
2985 * no lower item found, return the next
2986 * higher instead
2987 */
2988 return_any = 0;
2989 find_higher = 1;
2990 btrfs_release_path(p);
2991 goto again;
2992 } else {
2f38b3e1
AJ
2993 --p->slots[0];
2994 }
2995 }
2996 return 0;
2997}
2998
74123bd7
CM
2999/*
3000 * adjust the pointers going up the tree, starting at level
3001 * making sure the right key of each node is points to 'key'.
3002 * This is used after shifting pointers to the left, so it stops
3003 * fixing up pointers when a given leaf/node is not in slot 0 of the
3004 * higher levels
aa5d6bed 3005 *
74123bd7 3006 */
b167fa91 3007static void fixup_low_keys(struct btrfs_path *path,
143bede5 3008 struct btrfs_disk_key *key, int level)
be0e5c09
CM
3009{
3010 int i;
5f39d397 3011 struct extent_buffer *t;
0e82bcfe 3012 int ret;
5f39d397 3013
234b63a0 3014 for (i = level; i < BTRFS_MAX_LEVEL; i++) {
be0e5c09 3015 int tslot = path->slots[i];
0e82bcfe 3016
eb60ceac 3017 if (!path->nodes[i])
be0e5c09 3018 break;
5f39d397 3019 t = path->nodes[i];
0e82bcfe
DS
3020 ret = tree_mod_log_insert_key(t, tslot, MOD_LOG_KEY_REPLACE,
3021 GFP_ATOMIC);
3022 BUG_ON(ret < 0);
5f39d397 3023 btrfs_set_node_key(t, key, tslot);
d6025579 3024 btrfs_mark_buffer_dirty(path->nodes[i]);
be0e5c09
CM
3025 if (tslot != 0)
3026 break;
3027 }
3028}
3029
31840ae1
ZY
3030/*
3031 * update item key.
3032 *
3033 * This function isn't completely safe. It's the caller's responsibility
3034 * that the new key won't break the order
3035 */
b7a0365e
DD
3036void btrfs_set_item_key_safe(struct btrfs_fs_info *fs_info,
3037 struct btrfs_path *path,
310712b2 3038 const struct btrfs_key *new_key)
31840ae1
ZY
3039{
3040 struct btrfs_disk_key disk_key;
3041 struct extent_buffer *eb;
3042 int slot;
3043
3044 eb = path->nodes[0];
3045 slot = path->slots[0];
3046 if (slot > 0) {
3047 btrfs_item_key(eb, &disk_key, slot - 1);
7c15d410
QW
3048 if (unlikely(comp_keys(&disk_key, new_key) >= 0)) {
3049 btrfs_crit(fs_info,
3050 "slot %u key (%llu %u %llu) new key (%llu %u %llu)",
3051 slot, btrfs_disk_key_objectid(&disk_key),
3052 btrfs_disk_key_type(&disk_key),
3053 btrfs_disk_key_offset(&disk_key),
3054 new_key->objectid, new_key->type,
3055 new_key->offset);
3056 btrfs_print_leaf(eb);
3057 BUG();
3058 }
31840ae1
ZY
3059 }
3060 if (slot < btrfs_header_nritems(eb) - 1) {
3061 btrfs_item_key(eb, &disk_key, slot + 1);
7c15d410
QW
3062 if (unlikely(comp_keys(&disk_key, new_key) <= 0)) {
3063 btrfs_crit(fs_info,
3064 "slot %u key (%llu %u %llu) new key (%llu %u %llu)",
3065 slot, btrfs_disk_key_objectid(&disk_key),
3066 btrfs_disk_key_type(&disk_key),
3067 btrfs_disk_key_offset(&disk_key),
3068 new_key->objectid, new_key->type,
3069 new_key->offset);
3070 btrfs_print_leaf(eb);
3071 BUG();
3072 }
31840ae1
ZY
3073 }
3074
3075 btrfs_cpu_key_to_disk(&disk_key, new_key);
3076 btrfs_set_item_key(eb, &disk_key, slot);
3077 btrfs_mark_buffer_dirty(eb);
3078 if (slot == 0)
b167fa91 3079 fixup_low_keys(path, &disk_key, 1);
31840ae1
ZY
3080}
3081
d16c702f
QW
3082/*
3083 * Check key order of two sibling extent buffers.
3084 *
3085 * Return true if something is wrong.
3086 * Return false if everything is fine.
3087 *
3088 * Tree-checker only works inside one tree block, thus the following
3089 * corruption can not be detected by tree-checker:
3090 *
3091 * Leaf @left | Leaf @right
3092 * --------------------------------------------------------------
3093 * | 1 | 2 | 3 | 4 | 5 | f6 | | 7 | 8 |
3094 *
3095 * Key f6 in leaf @left itself is valid, but not valid when the next
3096 * key in leaf @right is 7.
3097 * This can only be checked at tree block merge time.
3098 * And since tree checker has ensured all key order in each tree block
3099 * is correct, we only need to bother the last key of @left and the first
3100 * key of @right.
3101 */
3102static bool check_sibling_keys(struct extent_buffer *left,
3103 struct extent_buffer *right)
3104{
3105 struct btrfs_key left_last;
3106 struct btrfs_key right_first;
3107 int level = btrfs_header_level(left);
3108 int nr_left = btrfs_header_nritems(left);
3109 int nr_right = btrfs_header_nritems(right);
3110
3111 /* No key to check in one of the tree blocks */
3112 if (!nr_left || !nr_right)
3113 return false;
3114
3115 if (level) {
3116 btrfs_node_key_to_cpu(left, &left_last, nr_left - 1);
3117 btrfs_node_key_to_cpu(right, &right_first, 0);
3118 } else {
3119 btrfs_item_key_to_cpu(left, &left_last, nr_left - 1);
3120 btrfs_item_key_to_cpu(right, &right_first, 0);
3121 }
3122
3123 if (btrfs_comp_cpu_keys(&left_last, &right_first) >= 0) {
3124 btrfs_crit(left->fs_info,
3125"bad key order, sibling blocks, left last (%llu %u %llu) right first (%llu %u %llu)",
3126 left_last.objectid, left_last.type,
3127 left_last.offset, right_first.objectid,
3128 right_first.type, right_first.offset);
3129 return true;
3130 }
3131 return false;
3132}
3133
74123bd7
CM
3134/*
3135 * try to push data from one node into the next node left in the
79f95c82 3136 * tree.
aa5d6bed
CM
3137 *
3138 * returns 0 if some ptrs were pushed left, < 0 if there was some horrible
3139 * error, and > 0 if there was no room in the left hand block.
74123bd7 3140 */
98ed5174 3141static int push_node_left(struct btrfs_trans_handle *trans,
2ff7e61e 3142 struct extent_buffer *dst,
971a1f66 3143 struct extent_buffer *src, int empty)
be0e5c09 3144{
d30a668f 3145 struct btrfs_fs_info *fs_info = trans->fs_info;
be0e5c09 3146 int push_items = 0;
bb803951
CM
3147 int src_nritems;
3148 int dst_nritems;
aa5d6bed 3149 int ret = 0;
be0e5c09 3150
5f39d397
CM
3151 src_nritems = btrfs_header_nritems(src);
3152 dst_nritems = btrfs_header_nritems(dst);
0b246afa 3153 push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
7bb86316
CM
3154 WARN_ON(btrfs_header_generation(src) != trans->transid);
3155 WARN_ON(btrfs_header_generation(dst) != trans->transid);
54aa1f4d 3156
bce4eae9 3157 if (!empty && src_nritems <= 8)
971a1f66
CM
3158 return 1;
3159
d397712b 3160 if (push_items <= 0)
be0e5c09
CM
3161 return 1;
3162
bce4eae9 3163 if (empty) {
971a1f66 3164 push_items = min(src_nritems, push_items);
bce4eae9
CM
3165 if (push_items < src_nritems) {
3166 /* leave at least 8 pointers in the node if
3167 * we aren't going to empty it
3168 */
3169 if (src_nritems - push_items < 8) {
3170 if (push_items <= 8)
3171 return 1;
3172 push_items -= 8;
3173 }
3174 }
3175 } else
3176 push_items = min(src_nritems - 8, push_items);
79f95c82 3177
d16c702f
QW
3178 /* dst is the left eb, src is the middle eb */
3179 if (check_sibling_keys(dst, src)) {
3180 ret = -EUCLEAN;
3181 btrfs_abort_transaction(trans, ret);
3182 return ret;
3183 }
ed874f0d 3184 ret = tree_mod_log_eb_copy(dst, src, dst_nritems, 0, push_items);
5de865ee 3185 if (ret) {
66642832 3186 btrfs_abort_transaction(trans, ret);
5de865ee
FDBM
3187 return ret;
3188 }
5f39d397
CM
3189 copy_extent_buffer(dst, src,
3190 btrfs_node_key_ptr_offset(dst_nritems),
3191 btrfs_node_key_ptr_offset(0),
d397712b 3192 push_items * sizeof(struct btrfs_key_ptr));
5f39d397 3193
bb803951 3194 if (push_items < src_nritems) {
57911b8b 3195 /*
bf1d3425
DS
3196 * Don't call tree_mod_log_insert_move here, key removal was
3197 * already fully logged by tree_mod_log_eb_copy above.
57911b8b 3198 */
5f39d397
CM
3199 memmove_extent_buffer(src, btrfs_node_key_ptr_offset(0),
3200 btrfs_node_key_ptr_offset(push_items),
3201 (src_nritems - push_items) *
3202 sizeof(struct btrfs_key_ptr));
3203 }
3204 btrfs_set_header_nritems(src, src_nritems - push_items);
3205 btrfs_set_header_nritems(dst, dst_nritems + push_items);
3206 btrfs_mark_buffer_dirty(src);
3207 btrfs_mark_buffer_dirty(dst);
31840ae1 3208
79f95c82
CM
3209 return ret;
3210}
3211
3212/*
3213 * try to push data from one node into the next node right in the
3214 * tree.
3215 *
3216 * returns 0 if some ptrs were pushed, < 0 if there was some horrible
3217 * error, and > 0 if there was no room in the right hand block.
3218 *
3219 * this will only push up to 1/2 the contents of the left node over
3220 */
5f39d397 3221static int balance_node_right(struct btrfs_trans_handle *trans,
5f39d397
CM
3222 struct extent_buffer *dst,
3223 struct extent_buffer *src)
79f95c82 3224{
55d32ed8 3225 struct btrfs_fs_info *fs_info = trans->fs_info;
79f95c82
CM
3226 int push_items = 0;
3227 int max_push;
3228 int src_nritems;
3229 int dst_nritems;
3230 int ret = 0;
79f95c82 3231
7bb86316
CM
3232 WARN_ON(btrfs_header_generation(src) != trans->transid);
3233 WARN_ON(btrfs_header_generation(dst) != trans->transid);
3234
5f39d397
CM
3235 src_nritems = btrfs_header_nritems(src);
3236 dst_nritems = btrfs_header_nritems(dst);
0b246afa 3237 push_items = BTRFS_NODEPTRS_PER_BLOCK(fs_info) - dst_nritems;
d397712b 3238 if (push_items <= 0)
79f95c82 3239 return 1;
bce4eae9 3240
d397712b 3241 if (src_nritems < 4)
bce4eae9 3242 return 1;
79f95c82
CM
3243
3244 max_push = src_nritems / 2 + 1;
3245 /* don't try to empty the node */
d397712b 3246 if (max_push >= src_nritems)
79f95c82 3247 return 1;
252c38f0 3248
79f95c82
CM
3249 if (max_push < push_items)
3250 push_items = max_push;
3251
d16c702f
QW
3252 /* dst is the right eb, src is the middle eb */
3253 if (check_sibling_keys(src, dst)) {
3254 ret = -EUCLEAN;
3255 btrfs_abort_transaction(trans, ret);
3256 return ret;
3257 }
bf1d3425
DS
3258 ret = tree_mod_log_insert_move(dst, push_items, 0, dst_nritems);
3259 BUG_ON(ret < 0);
5f39d397
CM
3260 memmove_extent_buffer(dst, btrfs_node_key_ptr_offset(push_items),
3261 btrfs_node_key_ptr_offset(0),
3262 (dst_nritems) *
3263 sizeof(struct btrfs_key_ptr));
d6025579 3264
ed874f0d
DS
3265 ret = tree_mod_log_eb_copy(dst, src, 0, src_nritems - push_items,
3266 push_items);
5de865ee 3267 if (ret) {
66642832 3268 btrfs_abort_transaction(trans, ret);
5de865ee
FDBM
3269 return ret;
3270 }
5f39d397
CM
3271 copy_extent_buffer(dst, src,
3272 btrfs_node_key_ptr_offset(0),
3273 btrfs_node_key_ptr_offset(src_nritems - push_items),
d397712b 3274 push_items * sizeof(struct btrfs_key_ptr));
79f95c82 3275
5f39d397
CM
3276 btrfs_set_header_nritems(src, src_nritems - push_items);
3277 btrfs_set_header_nritems(dst, dst_nritems + push_items);
79f95c82 3278
5f39d397
CM
3279 btrfs_mark_buffer_dirty(src);
3280 btrfs_mark_buffer_dirty(dst);
31840ae1 3281
aa5d6bed 3282 return ret;
be0e5c09
CM
3283}
3284
97571fd0
CM
3285/*
3286 * helper function to insert a new root level in the tree.
3287 * A new node is allocated, and a single item is inserted to
3288 * point to the existing root
aa5d6bed
CM
3289 *
3290 * returns zero on success or < 0 on failure.
97571fd0 3291 */
d397712b 3292static noinline int insert_new_root(struct btrfs_trans_handle *trans,
5f39d397 3293 struct btrfs_root *root,
fdd99c72 3294 struct btrfs_path *path, int level)
5c680ed6 3295{
0b246afa 3296 struct btrfs_fs_info *fs_info = root->fs_info;
7bb86316 3297 u64 lower_gen;
5f39d397
CM
3298 struct extent_buffer *lower;
3299 struct extent_buffer *c;
925baedd 3300 struct extent_buffer *old;
5f39d397 3301 struct btrfs_disk_key lower_key;
d9d19a01 3302 int ret;
5c680ed6
CM
3303
3304 BUG_ON(path->nodes[level]);
3305 BUG_ON(path->nodes[level-1] != root->node);
3306
7bb86316
CM
3307 lower = path->nodes[level-1];
3308 if (level == 1)
3309 btrfs_item_key(lower, &lower_key, 0);
3310 else
3311 btrfs_node_key(lower, &lower_key, 0);
3312
a6279470 3313 c = alloc_tree_block_no_bg_flush(trans, root, 0, &lower_key, level,
9631e4cc 3314 root->node->start, 0,
cf6f34aa 3315 BTRFS_NESTING_NEW_ROOT);
5f39d397
CM
3316 if (IS_ERR(c))
3317 return PTR_ERR(c);
925baedd 3318
0b246afa 3319 root_add_used(root, fs_info->nodesize);
f0486c68 3320
5f39d397 3321 btrfs_set_header_nritems(c, 1);
5f39d397 3322 btrfs_set_node_key(c, &lower_key, 0);
db94535d 3323 btrfs_set_node_blockptr(c, 0, lower->start);
7bb86316 3324 lower_gen = btrfs_header_generation(lower);
31840ae1 3325 WARN_ON(lower_gen != trans->transid);
7bb86316
CM
3326
3327 btrfs_set_node_ptr_generation(c, 0, lower_gen);
d5719762 3328
5f39d397 3329 btrfs_mark_buffer_dirty(c);
d5719762 3330
925baedd 3331 old = root->node;
d9d19a01
DS
3332 ret = tree_mod_log_insert_root(root->node, c, 0);
3333 BUG_ON(ret < 0);
240f62c8 3334 rcu_assign_pointer(root->node, c);
925baedd
CM
3335
3336 /* the super has an extra ref to root->node */
3337 free_extent_buffer(old);
3338
0b86a832 3339 add_root_to_dirty_list(root);
67439dad 3340 atomic_inc(&c->refs);
5f39d397 3341 path->nodes[level] = c;
ac5887c8 3342 path->locks[level] = BTRFS_WRITE_LOCK;
5c680ed6
CM
3343 path->slots[level] = 0;
3344 return 0;
3345}
3346
74123bd7
CM
3347/*
3348 * worker function to insert a single pointer in a node.
3349 * the node should have enough room for the pointer already
97571fd0 3350 *
74123bd7
CM
3351 * slot and level indicate where you want the key to go, and
3352 * blocknr is the block the key points to.
3353 */
143bede5 3354static void insert_ptr(struct btrfs_trans_handle *trans,
6ad3cf6d 3355 struct btrfs_path *path,
143bede5 3356 struct btrfs_disk_key *key, u64 bytenr,
c3e06965 3357 int slot, int level)
74123bd7 3358{
5f39d397 3359 struct extent_buffer *lower;
74123bd7 3360 int nritems;
f3ea38da 3361 int ret;
5c680ed6
CM
3362
3363 BUG_ON(!path->nodes[level]);
f0486c68 3364 btrfs_assert_tree_locked(path->nodes[level]);
5f39d397
CM
3365 lower = path->nodes[level];
3366 nritems = btrfs_header_nritems(lower);
c293498b 3367 BUG_ON(slot > nritems);
6ad3cf6d 3368 BUG_ON(nritems == BTRFS_NODEPTRS_PER_BLOCK(trans->fs_info));
74123bd7 3369 if (slot != nritems) {
bf1d3425
DS
3370 if (level) {
3371 ret = tree_mod_log_insert_move(lower, slot + 1, slot,
a446a979 3372 nritems - slot);
bf1d3425
DS
3373 BUG_ON(ret < 0);
3374 }
5f39d397
CM
3375 memmove_extent_buffer(lower,
3376 btrfs_node_key_ptr_offset(slot + 1),
3377 btrfs_node_key_ptr_offset(slot),
d6025579 3378 (nritems - slot) * sizeof(struct btrfs_key_ptr));
74123bd7 3379 }
c3e06965 3380 if (level) {
e09c2efe
DS
3381 ret = tree_mod_log_insert_key(lower, slot, MOD_LOG_KEY_ADD,
3382 GFP_NOFS);
f3ea38da
JS
3383 BUG_ON(ret < 0);
3384 }
5f39d397 3385 btrfs_set_node_key(lower, key, slot);
db94535d 3386 btrfs_set_node_blockptr(lower, slot, bytenr);
74493f7a
CM
3387 WARN_ON(trans->transid == 0);
3388 btrfs_set_node_ptr_generation(lower, slot, trans->transid);
5f39d397
CM
3389 btrfs_set_header_nritems(lower, nritems + 1);
3390 btrfs_mark_buffer_dirty(lower);
74123bd7
CM
3391}
3392
97571fd0
CM
3393/*
3394 * split the node at the specified level in path in two.
3395 * The path is corrected to point to the appropriate node after the split
3396 *
3397 * Before splitting this tries to make some room in the node by pushing
3398 * left and right, if either one works, it returns right away.
aa5d6bed
CM
3399 *
3400 * returns 0 on success and < 0 on failure
97571fd0 3401 */
e02119d5
CM
3402static noinline int split_node(struct btrfs_trans_handle *trans,
3403 struct btrfs_root *root,
3404 struct btrfs_path *path, int level)
be0e5c09 3405{
0b246afa 3406 struct btrfs_fs_info *fs_info = root->fs_info;
5f39d397
CM
3407 struct extent_buffer *c;
3408 struct extent_buffer *split;
3409 struct btrfs_disk_key disk_key;
be0e5c09 3410 int mid;
5c680ed6 3411 int ret;
7518a238 3412 u32 c_nritems;
eb60ceac 3413
5f39d397 3414 c = path->nodes[level];
7bb86316 3415 WARN_ON(btrfs_header_generation(c) != trans->transid);
5f39d397 3416 if (c == root->node) {
d9abbf1c 3417 /*
90f8d62e
JS
3418 * trying to split the root, lets make a new one
3419 *
fdd99c72 3420 * tree mod log: We don't log_removal old root in
90f8d62e
JS
3421 * insert_new_root, because that root buffer will be kept as a
3422 * normal node. We are going to log removal of half of the
3423 * elements below with tree_mod_log_eb_copy. We're holding a
3424 * tree lock on the buffer, which is why we cannot race with
3425 * other tree_mod_log users.
d9abbf1c 3426 */
fdd99c72 3427 ret = insert_new_root(trans, root, path, level + 1);
5c680ed6
CM
3428 if (ret)
3429 return ret;
b3612421 3430 } else {
e66f709b 3431 ret = push_nodes_for_insert(trans, root, path, level);
5f39d397
CM
3432 c = path->nodes[level];
3433 if (!ret && btrfs_header_nritems(c) <
0b246afa 3434 BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3)
e66f709b 3435 return 0;
54aa1f4d
CM
3436 if (ret < 0)
3437 return ret;
be0e5c09 3438 }
e66f709b 3439
5f39d397 3440 c_nritems = btrfs_header_nritems(c);
5d4f98a2
YZ
3441 mid = (c_nritems + 1) / 2;
3442 btrfs_node_key(c, &disk_key, mid);
7bb86316 3443
a6279470 3444 split = alloc_tree_block_no_bg_flush(trans, root, 0, &disk_key, level,
4dff97e6 3445 c->start, 0, BTRFS_NESTING_SPLIT);
5f39d397
CM
3446 if (IS_ERR(split))
3447 return PTR_ERR(split);
3448
0b246afa 3449 root_add_used(root, fs_info->nodesize);
bc877d28 3450 ASSERT(btrfs_header_level(c) == level);
54aa1f4d 3451
ed874f0d 3452 ret = tree_mod_log_eb_copy(split, c, 0, mid, c_nritems - mid);
5de865ee 3453 if (ret) {
66642832 3454 btrfs_abort_transaction(trans, ret);
5de865ee
FDBM
3455 return ret;
3456 }
5f39d397
CM
3457 copy_extent_buffer(split, c,
3458 btrfs_node_key_ptr_offset(0),
3459 btrfs_node_key_ptr_offset(mid),
3460 (c_nritems - mid) * sizeof(struct btrfs_key_ptr));
3461 btrfs_set_header_nritems(split, c_nritems - mid);
3462 btrfs_set_header_nritems(c, mid);
aa5d6bed
CM
3463 ret = 0;
3464
5f39d397
CM
3465 btrfs_mark_buffer_dirty(c);
3466 btrfs_mark_buffer_dirty(split);
3467
6ad3cf6d 3468 insert_ptr(trans, path, &disk_key, split->start,
c3e06965 3469 path->slots[level + 1] + 1, level + 1);
aa5d6bed 3470
5de08d7d 3471 if (path->slots[level] >= mid) {
5c680ed6 3472 path->slots[level] -= mid;
925baedd 3473 btrfs_tree_unlock(c);
5f39d397
CM
3474 free_extent_buffer(c);
3475 path->nodes[level] = split;
5c680ed6
CM
3476 path->slots[level + 1] += 1;
3477 } else {
925baedd 3478 btrfs_tree_unlock(split);
5f39d397 3479 free_extent_buffer(split);
be0e5c09 3480 }
aa5d6bed 3481 return ret;
be0e5c09
CM
3482}
3483
74123bd7
CM
3484/*
3485 * how many bytes are required to store the items in a leaf. start
3486 * and nr indicate which items in the leaf to check. This totals up the
3487 * space used both by the item structs and the item data
3488 */
5f39d397 3489static int leaf_space_used(struct extent_buffer *l, int start, int nr)
be0e5c09 3490{
41be1f3b
JB
3491 struct btrfs_item *start_item;
3492 struct btrfs_item *end_item;
be0e5c09 3493 int data_len;
5f39d397 3494 int nritems = btrfs_header_nritems(l);
d4dbff95 3495 int end = min(nritems, start + nr) - 1;
be0e5c09
CM
3496
3497 if (!nr)
3498 return 0;
dd3cc16b
RK
3499 start_item = btrfs_item_nr(start);
3500 end_item = btrfs_item_nr(end);
a31356b9
DS
3501 data_len = btrfs_item_offset(l, start_item) +
3502 btrfs_item_size(l, start_item);
3503 data_len = data_len - btrfs_item_offset(l, end_item);
0783fcfc 3504 data_len += sizeof(struct btrfs_item) * nr;
d4dbff95 3505 WARN_ON(data_len < 0);
be0e5c09
CM
3506 return data_len;
3507}
3508
d4dbff95
CM
3509/*
3510 * The space between the end of the leaf items and
3511 * the start of the leaf data. IOW, how much room
3512 * the leaf has left for both items and data
3513 */
e902baac 3514noinline int btrfs_leaf_free_space(struct extent_buffer *leaf)
d4dbff95 3515{
e902baac 3516 struct btrfs_fs_info *fs_info = leaf->fs_info;
5f39d397
CM
3517 int nritems = btrfs_header_nritems(leaf);
3518 int ret;
0b246afa
JM
3519
3520 ret = BTRFS_LEAF_DATA_SIZE(fs_info) - leaf_space_used(leaf, 0, nritems);
5f39d397 3521 if (ret < 0) {
0b246afa
JM
3522 btrfs_crit(fs_info,
3523 "leaf free space ret %d, leaf data size %lu, used %d nritems %d",
3524 ret,
3525 (unsigned long) BTRFS_LEAF_DATA_SIZE(fs_info),
3526 leaf_space_used(leaf, 0, nritems), nritems);
5f39d397
CM
3527 }
3528 return ret;
d4dbff95
CM
3529}
3530
99d8f83c
CM
3531/*
3532 * min slot controls the lowest index we're willing to push to the
3533 * right. We'll push up to and including min_slot, but no lower
3534 */
f72f0010 3535static noinline int __push_leaf_right(struct btrfs_path *path,
44871b1b
CM
3536 int data_size, int empty,
3537 struct extent_buffer *right,
99d8f83c
CM
3538 int free_space, u32 left_nritems,
3539 u32 min_slot)
00ec4c51 3540{
f72f0010 3541 struct btrfs_fs_info *fs_info = right->fs_info;
5f39d397 3542 struct extent_buffer *left = path->nodes[0];
44871b1b 3543 struct extent_buffer *upper = path->nodes[1];
cfed81a0 3544 struct btrfs_map_token token;
5f39d397 3545 struct btrfs_disk_key disk_key;
00ec4c51 3546 int slot;
34a38218 3547 u32 i;
00ec4c51
CM
3548 int push_space = 0;
3549 int push_items = 0;
0783fcfc 3550 struct btrfs_item *item;
34a38218 3551 u32 nr;
7518a238 3552 u32 right_nritems;
5f39d397 3553 u32 data_end;
db94535d 3554 u32 this_item_size;
00ec4c51 3555
34a38218
CM
3556 if (empty)
3557 nr = 0;
3558 else
99d8f83c 3559 nr = max_t(u32, 1, min_slot);
34a38218 3560
31840ae1 3561 if (path->slots[0] >= left_nritems)
87b29b20 3562 push_space += data_size;
31840ae1 3563
44871b1b 3564 slot = path->slots[1];
34a38218
CM
3565 i = left_nritems - 1;
3566 while (i >= nr) {
dd3cc16b 3567 item = btrfs_item_nr(i);
db94535d 3568
31840ae1
ZY
3569 if (!empty && push_items > 0) {
3570 if (path->slots[0] > i)
3571 break;
3572 if (path->slots[0] == i) {
e902baac
DS
3573 int space = btrfs_leaf_free_space(left);
3574
31840ae1
ZY
3575 if (space + push_space * 2 > free_space)
3576 break;
3577 }
3578 }
3579
00ec4c51 3580 if (path->slots[0] == i)
87b29b20 3581 push_space += data_size;
db94535d 3582
db94535d
CM
3583 this_item_size = btrfs_item_size(left, item);
3584 if (this_item_size + sizeof(*item) + push_space > free_space)
00ec4c51 3585 break;
31840ae1 3586
00ec4c51 3587 push_items++;
db94535d 3588 push_space += this_item_size + sizeof(*item);
34a38218
CM
3589 if (i == 0)
3590 break;
3591 i--;
db94535d 3592 }
5f39d397 3593
925baedd
CM
3594 if (push_items == 0)
3595 goto out_unlock;
5f39d397 3596
6c1500f2 3597 WARN_ON(!empty && push_items == left_nritems);
5f39d397 3598
00ec4c51 3599 /* push left to right */
5f39d397 3600 right_nritems = btrfs_header_nritems(right);
34a38218 3601
5f39d397 3602 push_space = btrfs_item_end_nr(left, left_nritems - push_items);
8f881e8c 3603 push_space -= leaf_data_end(left);
5f39d397 3604
00ec4c51 3605 /* make room in the right data area */
8f881e8c 3606 data_end = leaf_data_end(right);
5f39d397 3607 memmove_extent_buffer(right,
3d9ec8c4
NB
3608 BTRFS_LEAF_DATA_OFFSET + data_end - push_space,
3609 BTRFS_LEAF_DATA_OFFSET + data_end,
0b246afa 3610 BTRFS_LEAF_DATA_SIZE(fs_info) - data_end);
5f39d397 3611
00ec4c51 3612 /* copy from the left data area */
3d9ec8c4 3613 copy_extent_buffer(right, left, BTRFS_LEAF_DATA_OFFSET +
0b246afa 3614 BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
8f881e8c 3615 BTRFS_LEAF_DATA_OFFSET + leaf_data_end(left),
d6025579 3616 push_space);
5f39d397
CM
3617
3618 memmove_extent_buffer(right, btrfs_item_nr_offset(push_items),
3619 btrfs_item_nr_offset(0),
3620 right_nritems * sizeof(struct btrfs_item));
3621
00ec4c51 3622 /* copy the items from left to right */
5f39d397
CM
3623 copy_extent_buffer(right, left, btrfs_item_nr_offset(0),
3624 btrfs_item_nr_offset(left_nritems - push_items),
3625 push_items * sizeof(struct btrfs_item));
00ec4c51
CM
3626
3627 /* update the item pointers */
c82f823c 3628 btrfs_init_map_token(&token, right);
7518a238 3629 right_nritems += push_items;
5f39d397 3630 btrfs_set_header_nritems(right, right_nritems);
0b246afa 3631 push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
7518a238 3632 for (i = 0; i < right_nritems; i++) {
dd3cc16b 3633 item = btrfs_item_nr(i);
cc4c13d5
DS
3634 push_space -= btrfs_token_item_size(&token, item);
3635 btrfs_set_token_item_offset(&token, item, push_space);
db94535d
CM
3636 }
3637
7518a238 3638 left_nritems -= push_items;
5f39d397 3639 btrfs_set_header_nritems(left, left_nritems);
00ec4c51 3640
34a38218
CM
3641 if (left_nritems)
3642 btrfs_mark_buffer_dirty(left);
f0486c68 3643 else
6a884d7d 3644 btrfs_clean_tree_block(left);
f0486c68 3645
5f39d397 3646 btrfs_mark_buffer_dirty(right);
a429e513 3647
5f39d397
CM
3648 btrfs_item_key(right, &disk_key, 0);
3649 btrfs_set_node_key(upper, &disk_key, slot + 1);
d6025579 3650 btrfs_mark_buffer_dirty(upper);
02217ed2 3651
00ec4c51 3652 /* then fixup the leaf pointer in the path */
7518a238
CM
3653 if (path->slots[0] >= left_nritems) {
3654 path->slots[0] -= left_nritems;
925baedd 3655 if (btrfs_header_nritems(path->nodes[0]) == 0)
6a884d7d 3656 btrfs_clean_tree_block(path->nodes[0]);
925baedd 3657 btrfs_tree_unlock(path->nodes[0]);
5f39d397
CM
3658 free_extent_buffer(path->nodes[0]);
3659 path->nodes[0] = right;
00ec4c51
CM
3660 path->slots[1] += 1;
3661 } else {
925baedd 3662 btrfs_tree_unlock(right);
5f39d397 3663 free_extent_buffer(right);
00ec4c51
CM
3664 }
3665 return 0;
925baedd
CM
3666
3667out_unlock:
3668 btrfs_tree_unlock(right);
3669 free_extent_buffer(right);
3670 return 1;
00ec4c51 3671}
925baedd 3672
44871b1b
CM
3673/*
3674 * push some data in the path leaf to the right, trying to free up at
3675 * least data_size bytes. returns zero if the push worked, nonzero otherwise
3676 *
3677 * returns 1 if the push failed because the other node didn't have enough
3678 * room, 0 if everything worked out and < 0 if there were major errors.
99d8f83c
CM
3679 *
3680 * this will push starting from min_slot to the end of the leaf. It won't
3681 * push any slot lower than min_slot
44871b1b
CM
3682 */
3683static int push_leaf_right(struct btrfs_trans_handle *trans, struct btrfs_root
99d8f83c
CM
3684 *root, struct btrfs_path *path,
3685 int min_data_size, int data_size,
3686 int empty, u32 min_slot)
44871b1b
CM
3687{
3688 struct extent_buffer *left = path->nodes[0];
3689 struct extent_buffer *right;
3690 struct extent_buffer *upper;
3691 int slot;
3692 int free_space;
3693 u32 left_nritems;
3694 int ret;
3695
3696 if (!path->nodes[1])
3697 return 1;
3698
3699 slot = path->slots[1];
3700 upper = path->nodes[1];
3701 if (slot >= btrfs_header_nritems(upper) - 1)
3702 return 1;
3703
3704 btrfs_assert_tree_locked(path->nodes[1]);
3705
4b231ae4 3706 right = btrfs_read_node_slot(upper, slot + 1);
fb770ae4
LB
3707 /*
3708 * slot + 1 is not valid or we fail to read the right node,
3709 * no big deal, just return.
3710 */
3711 if (IS_ERR(right))
91ca338d
TI
3712 return 1;
3713
bf77467a 3714 __btrfs_tree_lock(right, BTRFS_NESTING_RIGHT);
44871b1b 3715
e902baac 3716 free_space = btrfs_leaf_free_space(right);
44871b1b
CM
3717 if (free_space < data_size)
3718 goto out_unlock;
3719
3720 /* cow and double check */
3721 ret = btrfs_cow_block(trans, root, right, upper,
bf59a5a2 3722 slot + 1, &right, BTRFS_NESTING_RIGHT_COW);
44871b1b
CM
3723 if (ret)
3724 goto out_unlock;
3725
e902baac 3726 free_space = btrfs_leaf_free_space(right);
44871b1b
CM
3727 if (free_space < data_size)
3728 goto out_unlock;
3729
3730 left_nritems = btrfs_header_nritems(left);
3731 if (left_nritems == 0)
3732 goto out_unlock;
3733
d16c702f
QW
3734 if (check_sibling_keys(left, right)) {
3735 ret = -EUCLEAN;
3736 btrfs_tree_unlock(right);
3737 free_extent_buffer(right);
3738 return ret;
3739 }
2ef1fed2
FDBM
3740 if (path->slots[0] == left_nritems && !empty) {
3741 /* Key greater than all keys in the leaf, right neighbor has
3742 * enough room for it and we're not emptying our leaf to delete
3743 * it, therefore use right neighbor to insert the new item and
52042d8e 3744 * no need to touch/dirty our left leaf. */
2ef1fed2
FDBM
3745 btrfs_tree_unlock(left);
3746 free_extent_buffer(left);
3747 path->nodes[0] = right;
3748 path->slots[0] = 0;
3749 path->slots[1]++;
3750 return 0;
3751 }
3752
f72f0010 3753 return __push_leaf_right(path, min_data_size, empty,
99d8f83c 3754 right, free_space, left_nritems, min_slot);
44871b1b
CM
3755out_unlock:
3756 btrfs_tree_unlock(right);
3757 free_extent_buffer(right);
3758 return 1;
3759}
3760
74123bd7
CM
3761/*
3762 * push some data in the path leaf to the left, trying to free up at
3763 * least data_size bytes. returns zero if the push worked, nonzero otherwise
99d8f83c
CM
3764 *
3765 * max_slot can put a limit on how far into the leaf we'll push items. The
3766 * item at 'max_slot' won't be touched. Use (u32)-1 to make us do all the
3767 * items
74123bd7 3768 */
8087c193 3769static noinline int __push_leaf_left(struct btrfs_path *path, int data_size,
44871b1b 3770 int empty, struct extent_buffer *left,
99d8f83c
CM
3771 int free_space, u32 right_nritems,
3772 u32 max_slot)
be0e5c09 3773{
8087c193 3774 struct btrfs_fs_info *fs_info = left->fs_info;
5f39d397
CM
3775 struct btrfs_disk_key disk_key;
3776 struct extent_buffer *right = path->nodes[0];
be0e5c09 3777 int i;
be0e5c09
CM
3778 int push_space = 0;
3779 int push_items = 0;
0783fcfc 3780 struct btrfs_item *item;
7518a238 3781 u32 old_left_nritems;
34a38218 3782 u32 nr;
aa5d6bed 3783 int ret = 0;
db94535d
CM
3784 u32 this_item_size;
3785 u32 old_left_item_size;
cfed81a0
CM
3786 struct btrfs_map_token token;
3787
34a38218 3788 if (empty)
99d8f83c 3789 nr = min(right_nritems, max_slot);
34a38218 3790 else
99d8f83c 3791 nr = min(right_nritems - 1, max_slot);
34a38218
CM
3792
3793 for (i = 0; i < nr; i++) {
dd3cc16b 3794 item = btrfs_item_nr(i);
db94535d 3795
31840ae1
ZY
3796 if (!empty && push_items > 0) {
3797 if (path->slots[0] < i)
3798 break;
3799 if (path->slots[0] == i) {
e902baac
DS
3800 int space = btrfs_leaf_free_space(right);
3801
31840ae1
ZY
3802 if (space + push_space * 2 > free_space)
3803 break;
3804 }
3805 }
3806
be0e5c09 3807 if (path->slots[0] == i)
87b29b20 3808 push_space += data_size;
db94535d
CM
3809
3810 this_item_size = btrfs_item_size(right, item);
3811 if (this_item_size + sizeof(*item) + push_space > free_space)
be0e5c09 3812 break;
db94535d 3813
be0e5c09 3814 push_items++;
db94535d
CM
3815 push_space += this_item_size + sizeof(*item);
3816 }
3817
be0e5c09 3818 if (push_items == 0) {
925baedd
CM
3819 ret = 1;
3820 goto out;
be0e5c09 3821 }
fae7f21c 3822 WARN_ON(!empty && push_items == btrfs_header_nritems(right));
5f39d397 3823
be0e5c09 3824 /* push data from right to left */
5f39d397
CM
3825 copy_extent_buffer(left, right,
3826 btrfs_item_nr_offset(btrfs_header_nritems(left)),
3827 btrfs_item_nr_offset(0),
3828 push_items * sizeof(struct btrfs_item));
3829
0b246afa 3830 push_space = BTRFS_LEAF_DATA_SIZE(fs_info) -
d397712b 3831 btrfs_item_offset_nr(right, push_items - 1);
5f39d397 3832
3d9ec8c4 3833 copy_extent_buffer(left, right, BTRFS_LEAF_DATA_OFFSET +
8f881e8c 3834 leaf_data_end(left) - push_space,
3d9ec8c4 3835 BTRFS_LEAF_DATA_OFFSET +
5f39d397 3836 btrfs_item_offset_nr(right, push_items - 1),
d6025579 3837 push_space);
5f39d397 3838 old_left_nritems = btrfs_header_nritems(left);
87b29b20 3839 BUG_ON(old_left_nritems <= 0);
eb60ceac 3840
c82f823c 3841 btrfs_init_map_token(&token, left);
db94535d 3842 old_left_item_size = btrfs_item_offset_nr(left, old_left_nritems - 1);
0783fcfc 3843 for (i = old_left_nritems; i < old_left_nritems + push_items; i++) {
5f39d397 3844 u32 ioff;
db94535d 3845
dd3cc16b 3846 item = btrfs_item_nr(i);
db94535d 3847
cc4c13d5
DS
3848 ioff = btrfs_token_item_offset(&token, item);
3849 btrfs_set_token_item_offset(&token, item,
3850 ioff - (BTRFS_LEAF_DATA_SIZE(fs_info) - old_left_item_size));
be0e5c09 3851 }
5f39d397 3852 btrfs_set_header_nritems(left, old_left_nritems + push_items);
be0e5c09
CM
3853
3854 /* fixup right node */
31b1a2bd
JL
3855 if (push_items > right_nritems)
3856 WARN(1, KERN_CRIT "push items %d nr %u\n", push_items,
d397712b 3857 right_nritems);
34a38218
CM
3858
3859 if (push_items < right_nritems) {
3860 push_space = btrfs_item_offset_nr(right, push_items - 1) -
8f881e8c 3861 leaf_data_end(right);
3d9ec8c4 3862 memmove_extent_buffer(right, BTRFS_LEAF_DATA_OFFSET +
0b246afa 3863 BTRFS_LEAF_DATA_SIZE(fs_info) - push_space,
3d9ec8c4 3864 BTRFS_LEAF_DATA_OFFSET +
8f881e8c 3865 leaf_data_end(right), push_space);
34a38218
CM
3866
3867 memmove_extent_buffer(right, btrfs_item_nr_offset(0),
5f39d397
CM
3868 btrfs_item_nr_offset(push_items),
3869 (btrfs_header_nritems(right) - push_items) *
3870 sizeof(struct btrfs_item));
34a38218 3871 }
c82f823c
DS
3872
3873 btrfs_init_map_token(&token, right);
eef1c494
Y
3874 right_nritems -= push_items;
3875 btrfs_set_header_nritems(right, right_nritems);
0b246afa 3876 push_space = BTRFS_LEAF_DATA_SIZE(fs_info);
5f39d397 3877 for (i = 0; i < right_nritems; i++) {
dd3cc16b 3878 item = btrfs_item_nr(i);
db94535d 3879
cc4c13d5
DS
3880 push_space = push_space - btrfs_token_item_size(&token, item);
3881 btrfs_set_token_item_offset(&token, item, push_space);
db94535d 3882 }
eb60ceac 3883
5f39d397 3884 btrfs_mark_buffer_dirty(left);
34a38218
CM
3885 if (right_nritems)
3886 btrfs_mark_buffer_dirty(right);
f0486c68 3887 else
6a884d7d 3888 btrfs_clean_tree_block(right);
098f59c2 3889
5f39d397 3890 btrfs_item_key(right, &disk_key, 0);
b167fa91 3891 fixup_low_keys(path, &disk_key, 1);
be0e5c09
CM
3892
3893 /* then fixup the leaf pointer in the path */
3894 if (path->slots[0] < push_items) {
3895 path->slots[0] += old_left_nritems;
925baedd 3896 btrfs_tree_unlock(path->nodes[0]);
5f39d397
CM
3897 free_extent_buffer(path->nodes[0]);
3898 path->nodes[0] = left;
be0e5c09
CM
3899 path->slots[1] -= 1;
3900 } else {
925baedd 3901 btrfs_tree_unlock(left);
5f39d397 3902 free_extent_buffer(left);
be0e5c09
CM
3903 path->slots[0] -= push_items;
3904 }
eb60ceac 3905 BUG_ON(path->slots[0] < 0);
aa5d6bed 3906 return ret;
925baedd
CM
3907out:
3908 btrfs_tree_unlock(left);
3909 free_extent_buffer(left);
3910 return ret;
be0e5c09
CM
3911}
3912
44871b1b
CM
3913/*
3914 * push some data in the path leaf to the left, trying to free up at
3915 * least data_size bytes. returns zero if the push worked, nonzero otherwise
99d8f83c
CM
3916 *
3917 * max_slot can put a limit on how far into the leaf we'll push items. The
3918 * item at 'max_slot' won't be touched. Use (u32)-1 to make us push all the
3919 * items
44871b1b
CM
3920 */
3921static int push_leaf_left(struct btrfs_trans_handle *trans, struct btrfs_root
99d8f83c
CM
3922 *root, struct btrfs_path *path, int min_data_size,
3923 int data_size, int empty, u32 max_slot)
44871b1b
CM
3924{
3925 struct extent_buffer *right = path->nodes[0];
3926 struct extent_buffer *left;
3927 int slot;
3928 int free_space;
3929 u32 right_nritems;
3930 int ret = 0;
3931
3932 slot = path->slots[1];
3933 if (slot == 0)
3934 return 1;
3935 if (!path->nodes[1])
3936 return 1;
3937
3938 right_nritems = btrfs_header_nritems(right);
3939 if (right_nritems == 0)
3940 return 1;
3941
3942 btrfs_assert_tree_locked(path->nodes[1]);
3943
4b231ae4 3944 left = btrfs_read_node_slot(path->nodes[1], slot - 1);
fb770ae4
LB
3945 /*
3946 * slot - 1 is not valid or we fail to read the left node,
3947 * no big deal, just return.
3948 */
3949 if (IS_ERR(left))
91ca338d
TI
3950 return 1;
3951
bf77467a 3952 __btrfs_tree_lock(left, BTRFS_NESTING_LEFT);
44871b1b 3953
e902baac 3954 free_space = btrfs_leaf_free_space(left);
44871b1b
CM
3955 if (free_space < data_size) {
3956 ret = 1;
3957 goto out;
3958 }
3959
3960 /* cow and double check */
3961 ret = btrfs_cow_block(trans, root, left,
9631e4cc 3962 path->nodes[1], slot - 1, &left,
bf59a5a2 3963 BTRFS_NESTING_LEFT_COW);
44871b1b
CM
3964 if (ret) {
3965 /* we hit -ENOSPC, but it isn't fatal here */
79787eaa
JM
3966 if (ret == -ENOSPC)
3967 ret = 1;
44871b1b
CM
3968 goto out;
3969 }
3970
e902baac 3971 free_space = btrfs_leaf_free_space(left);
44871b1b
CM
3972 if (free_space < data_size) {
3973 ret = 1;
3974 goto out;
3975 }
3976
d16c702f
QW
3977 if (check_sibling_keys(left, right)) {
3978 ret = -EUCLEAN;
3979 goto out;
3980 }
8087c193 3981 return __push_leaf_left(path, min_data_size,
99d8f83c
CM
3982 empty, left, free_space, right_nritems,
3983 max_slot);
44871b1b
CM
3984out:
3985 btrfs_tree_unlock(left);
3986 free_extent_buffer(left);
3987 return ret;
3988}
3989
3990/*
3991 * split the path's leaf in two, making sure there is at least data_size
3992 * available for the resulting leaf level of the path.
44871b1b 3993 */
143bede5 3994static noinline void copy_for_split(struct btrfs_trans_handle *trans,
143bede5
JM
3995 struct btrfs_path *path,
3996 struct extent_buffer *l,
3997 struct extent_buffer *right,
3998 int slot, int mid, int nritems)
44871b1b 3999{
94f94ad9 4000 struct btrfs_fs_info *fs_info = trans->fs_info;
44871b1b
CM
4001 int data_copy_size;
4002 int rt_data_off;
4003 int i;
44871b1b 4004 struct btrfs_disk_key disk_key;
cfed81a0
CM
4005 struct btrfs_map_token token;
4006
44871b1b
CM
4007 nritems = nritems - mid;
4008 btrfs_set_header_nritems(right, nritems);
8f881e8c 4009 data_copy_size = btrfs_item_end_nr(l, mid) - leaf_data_end(l);
44871b1b
CM
4010
4011 copy_extent_buffer(right, l, btrfs_item_nr_offset(0),
4012 btrfs_item_nr_offset(mid),
4013 nritems * sizeof(struct btrfs_item));
4014
4015 copy_extent_buffer(right, l,
3d9ec8c4
NB
4016 BTRFS_LEAF_DATA_OFFSET + BTRFS_LEAF_DATA_SIZE(fs_info) -
4017 data_copy_size, BTRFS_LEAF_DATA_OFFSET +
8f881e8c 4018 leaf_data_end(l), data_copy_size);
44871b1b 4019
0b246afa 4020 rt_data_off = BTRFS_LEAF_DATA_SIZE(fs_info) - btrfs_item_end_nr(l, mid);
44871b1b 4021
c82f823c 4022 btrfs_init_map_token(&token, right);
44871b1b 4023 for (i = 0; i < nritems; i++) {
dd3cc16b 4024 struct btrfs_item *item = btrfs_item_nr(i);
44871b1b
CM
4025 u32 ioff;
4026
cc4c13d5
DS
4027 ioff = btrfs_token_item_offset(&token, item);
4028 btrfs_set_token_item_offset(&token, item, ioff + rt_data_off);
44871b1b
CM
4029 }
4030
44871b1b 4031 btrfs_set_header_nritems(l, mid);
44871b1b 4032 btrfs_item_key(right, &disk_key, 0);
6ad3cf6d 4033 insert_ptr(trans, path, &disk_key, right->start, path->slots[1] + 1, 1);
44871b1b
CM
4034
4035 btrfs_mark_buffer_dirty(right);
4036 btrfs_mark_buffer_dirty(l);
4037 BUG_ON(path->slots[0] != slot);
4038
44871b1b
CM
4039 if (mid <= slot) {
4040 btrfs_tree_unlock(path->nodes[0]);
4041 free_extent_buffer(path->nodes[0]);
4042 path->nodes[0] = right;
4043 path->slots[0] -= mid;
4044 path->slots[1] += 1;
4045 } else {
4046 btrfs_tree_unlock(right);
4047 free_extent_buffer(right);
4048 }
4049
4050 BUG_ON(path->slots[0] < 0);
44871b1b
CM
4051}
4052
99d8f83c
CM
4053/*
4054 * double splits happen when we need to insert a big item in the middle
4055 * of a leaf. A double split can leave us with 3 mostly empty leaves:
4056 * leaf: [ slots 0 - N] [ our target ] [ N + 1 - total in leaf ]
4057 * A B C
4058 *
4059 * We avoid this by trying to push the items on either side of our target
4060 * into the adjacent leaves. If all goes well we can avoid the double split
4061 * completely.
4062 */
4063static noinline int push_for_double_split(struct btrfs_trans_handle *trans,
4064 struct btrfs_root *root,
4065 struct btrfs_path *path,
4066 int data_size)
4067{
4068 int ret;
4069 int progress = 0;
4070 int slot;
4071 u32 nritems;
5a4267ca 4072 int space_needed = data_size;
99d8f83c
CM
4073
4074 slot = path->slots[0];
5a4267ca 4075 if (slot < btrfs_header_nritems(path->nodes[0]))
e902baac 4076 space_needed -= btrfs_leaf_free_space(path->nodes[0]);
99d8f83c
CM
4077
4078 /*
4079 * try to push all the items after our slot into the
4080 * right leaf
4081 */
5a4267ca 4082 ret = push_leaf_right(trans, root, path, 1, space_needed, 0, slot);
99d8f83c
CM
4083 if (ret < 0)
4084 return ret;
4085
4086 if (ret == 0)
4087 progress++;
4088
4089 nritems = btrfs_header_nritems(path->nodes[0]);
4090 /*
4091 * our goal is to get our slot at the start or end of a leaf. If
4092 * we've done so we're done
4093 */
4094 if (path->slots[0] == 0 || path->slots[0] == nritems)
4095 return 0;
4096
e902baac 4097 if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
99d8f83c
CM
4098 return 0;
4099
4100 /* try to push all the items before our slot into the next leaf */
4101 slot = path->slots[0];
263d3995
FM
4102 space_needed = data_size;
4103 if (slot > 0)
e902baac 4104 space_needed -= btrfs_leaf_free_space(path->nodes[0]);
5a4267ca 4105 ret = push_leaf_left(trans, root, path, 1, space_needed, 0, slot);
99d8f83c
CM
4106 if (ret < 0)
4107 return ret;
4108
4109 if (ret == 0)
4110 progress++;
4111
4112 if (progress)
4113 return 0;
4114 return 1;
4115}
4116
74123bd7
CM
4117/*
4118 * split the path's leaf in two, making sure there is at least data_size
4119 * available for the resulting leaf level of the path.
aa5d6bed
CM
4120 *
4121 * returns 0 if all went well and < 0 on failure.
74123bd7 4122 */
e02119d5
CM
4123static noinline int split_leaf(struct btrfs_trans_handle *trans,
4124 struct btrfs_root *root,
310712b2 4125 const struct btrfs_key *ins_key,
e02119d5
CM
4126 struct btrfs_path *path, int data_size,
4127 int extend)
be0e5c09 4128{
5d4f98a2 4129 struct btrfs_disk_key disk_key;
5f39d397 4130 struct extent_buffer *l;
7518a238 4131 u32 nritems;
eb60ceac
CM
4132 int mid;
4133 int slot;
5f39d397 4134 struct extent_buffer *right;
b7a0365e 4135 struct btrfs_fs_info *fs_info = root->fs_info;
d4dbff95 4136 int ret = 0;
aa5d6bed 4137 int wret;
5d4f98a2 4138 int split;
cc0c5538 4139 int num_doubles = 0;
99d8f83c 4140 int tried_avoid_double = 0;
aa5d6bed 4141
a5719521
YZ
4142 l = path->nodes[0];
4143 slot = path->slots[0];
4144 if (extend && data_size + btrfs_item_size_nr(l, slot) +
0b246afa 4145 sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(fs_info))
a5719521
YZ
4146 return -EOVERFLOW;
4147
40689478 4148 /* first try to make some room by pushing left and right */
33157e05 4149 if (data_size && path->nodes[1]) {
5a4267ca
FDBM
4150 int space_needed = data_size;
4151
4152 if (slot < btrfs_header_nritems(l))
e902baac 4153 space_needed -= btrfs_leaf_free_space(l);
5a4267ca
FDBM
4154
4155 wret = push_leaf_right(trans, root, path, space_needed,
4156 space_needed, 0, 0);
d397712b 4157 if (wret < 0)
eaee50e8 4158 return wret;
3685f791 4159 if (wret) {
263d3995
FM
4160 space_needed = data_size;
4161 if (slot > 0)
e902baac 4162 space_needed -= btrfs_leaf_free_space(l);
5a4267ca
FDBM
4163 wret = push_leaf_left(trans, root, path, space_needed,
4164 space_needed, 0, (u32)-1);
3685f791
CM
4165 if (wret < 0)
4166 return wret;
4167 }
4168 l = path->nodes[0];
aa5d6bed 4169
3685f791 4170 /* did the pushes work? */
e902baac 4171 if (btrfs_leaf_free_space(l) >= data_size)
3685f791 4172 return 0;
3326d1b0 4173 }
aa5d6bed 4174
5c680ed6 4175 if (!path->nodes[1]) {
fdd99c72 4176 ret = insert_new_root(trans, root, path, 1);
5c680ed6
CM
4177 if (ret)
4178 return ret;
4179 }
cc0c5538 4180again:
5d4f98a2 4181 split = 1;
cc0c5538 4182 l = path->nodes[0];
eb60ceac 4183 slot = path->slots[0];
5f39d397 4184 nritems = btrfs_header_nritems(l);
d397712b 4185 mid = (nritems + 1) / 2;
54aa1f4d 4186
5d4f98a2
YZ
4187 if (mid <= slot) {
4188 if (nritems == 1 ||
4189 leaf_space_used(l, mid, nritems - mid) + data_size >
0b246afa 4190 BTRFS_LEAF_DATA_SIZE(fs_info)) {
5d4f98a2
YZ
4191 if (slot >= nritems) {
4192 split = 0;
4193 } else {
4194 mid = slot;
4195 if (mid != nritems &&
4196 leaf_space_used(l, mid, nritems - mid) +
0b246afa 4197 data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
99d8f83c
CM
4198 if (data_size && !tried_avoid_double)
4199 goto push_for_double;
5d4f98a2
YZ
4200 split = 2;
4201 }
4202 }
4203 }
4204 } else {
4205 if (leaf_space_used(l, 0, mid) + data_size >
0b246afa 4206 BTRFS_LEAF_DATA_SIZE(fs_info)) {
5d4f98a2
YZ
4207 if (!extend && data_size && slot == 0) {
4208 split = 0;
4209 } else if ((extend || !data_size) && slot == 0) {
4210 mid = 1;
4211 } else {
4212 mid = slot;
4213 if (mid != nritems &&
4214 leaf_space_used(l, mid, nritems - mid) +
0b246afa 4215 data_size > BTRFS_LEAF_DATA_SIZE(fs_info)) {
99d8f83c
CM
4216 if (data_size && !tried_avoid_double)
4217 goto push_for_double;
67871254 4218 split = 2;
5d4f98a2
YZ
4219 }
4220 }
4221 }
4222 }
4223
4224 if (split == 0)
4225 btrfs_cpu_key_to_disk(&disk_key, ins_key);
4226 else
4227 btrfs_item_key(l, &disk_key, mid);
4228
ca9d473a
JB
4229 /*
4230 * We have to about BTRFS_NESTING_NEW_ROOT here if we've done a double
4231 * split, because we're only allowed to have MAX_LOCKDEP_SUBCLASSES
4232 * subclasses, which is 8 at the time of this patch, and we've maxed it
4233 * out. In the future we could add a
4234 * BTRFS_NESTING_SPLIT_THE_SPLITTENING if we need to, but for now just
4235 * use BTRFS_NESTING_NEW_ROOT.
4236 */
a6279470 4237 right = alloc_tree_block_no_bg_flush(trans, root, 0, &disk_key, 0,
ca9d473a
JB
4238 l->start, 0, num_doubles ?
4239 BTRFS_NESTING_NEW_ROOT :
4240 BTRFS_NESTING_SPLIT);
f0486c68 4241 if (IS_ERR(right))
5f39d397 4242 return PTR_ERR(right);
f0486c68 4243
0b246afa 4244 root_add_used(root, fs_info->nodesize);
5f39d397 4245
5d4f98a2
YZ
4246 if (split == 0) {
4247 if (mid <= slot) {
4248 btrfs_set_header_nritems(right, 0);
6ad3cf6d 4249 insert_ptr(trans, path, &disk_key,
2ff7e61e 4250 right->start, path->slots[1] + 1, 1);
5d4f98a2
YZ
4251 btrfs_tree_unlock(path->nodes[0]);
4252 free_extent_buffer(path->nodes[0]);
4253 path->nodes[0] = right;
4254 path->slots[0] = 0;
4255 path->slots[1] += 1;
4256 } else {
4257 btrfs_set_header_nritems(right, 0);
6ad3cf6d 4258 insert_ptr(trans, path, &disk_key,
2ff7e61e 4259 right->start, path->slots[1], 1);
5d4f98a2
YZ
4260 btrfs_tree_unlock(path->nodes[0]);
4261 free_extent_buffer(path->nodes[0]);
4262 path->nodes[0] = right;
4263 path->slots[0] = 0;
143bede5 4264 if (path->slots[1] == 0)
b167fa91 4265 fixup_low_keys(path, &disk_key, 1);
d4dbff95 4266 }
196e0249
LB
4267 /*
4268 * We create a new leaf 'right' for the required ins_len and
4269 * we'll do btrfs_mark_buffer_dirty() on this leaf after copying
4270 * the content of ins_len to 'right'.
4271 */
5d4f98a2 4272 return ret;
d4dbff95 4273 }
74123bd7 4274
94f94ad9 4275 copy_for_split(trans, path, l, right, slot, mid, nritems);
31840ae1 4276
5d4f98a2 4277 if (split == 2) {
cc0c5538
CM
4278 BUG_ON(num_doubles != 0);
4279 num_doubles++;
4280 goto again;
a429e513 4281 }
44871b1b 4282
143bede5 4283 return 0;
99d8f83c
CM
4284
4285push_for_double:
4286 push_for_double_split(trans, root, path, data_size);
4287 tried_avoid_double = 1;
e902baac 4288 if (btrfs_leaf_free_space(path->nodes[0]) >= data_size)
99d8f83c
CM
4289 return 0;
4290 goto again;
be0e5c09
CM
4291}
4292
ad48fd75
YZ
4293static noinline int setup_leaf_for_split(struct btrfs_trans_handle *trans,
4294 struct btrfs_root *root,
4295 struct btrfs_path *path, int ins_len)
459931ec 4296{
ad48fd75 4297 struct btrfs_key key;
459931ec 4298 struct extent_buffer *leaf;
ad48fd75
YZ
4299 struct btrfs_file_extent_item *fi;
4300 u64 extent_len = 0;
4301 u32 item_size;
4302 int ret;
459931ec
CM
4303
4304 leaf = path->nodes[0];
ad48fd75
YZ
4305 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4306
4307 BUG_ON(key.type != BTRFS_EXTENT_DATA_KEY &&
4308 key.type != BTRFS_EXTENT_CSUM_KEY);
4309
e902baac 4310 if (btrfs_leaf_free_space(leaf) >= ins_len)
ad48fd75 4311 return 0;
459931ec
CM
4312
4313 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
ad48fd75
YZ
4314 if (key.type == BTRFS_EXTENT_DATA_KEY) {
4315 fi = btrfs_item_ptr(leaf, path->slots[0],
4316 struct btrfs_file_extent_item);
4317 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
4318 }
b3b4aa74 4319 btrfs_release_path(path);
459931ec 4320
459931ec 4321 path->keep_locks = 1;
ad48fd75
YZ
4322 path->search_for_split = 1;
4323 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
459931ec 4324 path->search_for_split = 0;
a8df6fe6
FM
4325 if (ret > 0)
4326 ret = -EAGAIN;
ad48fd75
YZ
4327 if (ret < 0)
4328 goto err;
459931ec 4329
ad48fd75
YZ
4330 ret = -EAGAIN;
4331 leaf = path->nodes[0];
a8df6fe6
FM
4332 /* if our item isn't there, return now */
4333 if (item_size != btrfs_item_size_nr(leaf, path->slots[0]))
ad48fd75
YZ
4334 goto err;
4335
109f6aef 4336 /* the leaf has changed, it now has room. return now */
e902baac 4337 if (btrfs_leaf_free_space(path->nodes[0]) >= ins_len)
109f6aef
CM
4338 goto err;
4339
ad48fd75
YZ
4340 if (key.type == BTRFS_EXTENT_DATA_KEY) {
4341 fi = btrfs_item_ptr(leaf, path->slots[0],
4342 struct btrfs_file_extent_item);
4343 if (extent_len != btrfs_file_extent_num_bytes(leaf, fi))
4344 goto err;
459931ec
CM
4345 }
4346
ad48fd75 4347 ret = split_leaf(trans, root, &key, path, ins_len, 1);
f0486c68
YZ
4348 if (ret)
4349 goto err;
459931ec 4350
ad48fd75 4351 path->keep_locks = 0;
b9473439 4352 btrfs_unlock_up_safe(path, 1);
ad48fd75
YZ
4353 return 0;
4354err:
4355 path->keep_locks = 0;
4356 return ret;
4357}
4358
25263cd7 4359static noinline int split_item(struct btrfs_path *path,
310712b2 4360 const struct btrfs_key *new_key,
ad48fd75
YZ
4361 unsigned long split_offset)
4362{
4363 struct extent_buffer *leaf;
4364 struct btrfs_item *item;
4365 struct btrfs_item *new_item;
4366 int slot;
4367 char *buf;
4368 u32 nritems;
4369 u32 item_size;
4370 u32 orig_offset;
4371 struct btrfs_disk_key disk_key;
4372
b9473439 4373 leaf = path->nodes[0];
e902baac 4374 BUG_ON(btrfs_leaf_free_space(leaf) < sizeof(struct btrfs_item));
b9473439 4375
dd3cc16b 4376 item = btrfs_item_nr(path->slots[0]);
459931ec
CM
4377 orig_offset = btrfs_item_offset(leaf, item);
4378 item_size = btrfs_item_size(leaf, item);
4379
459931ec 4380 buf = kmalloc(item_size, GFP_NOFS);
ad48fd75
YZ
4381 if (!buf)
4382 return -ENOMEM;
4383
459931ec
CM
4384 read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf,
4385 path->slots[0]), item_size);
459931ec 4386
ad48fd75 4387 slot = path->slots[0] + 1;
459931ec 4388 nritems = btrfs_header_nritems(leaf);
459931ec
CM
4389 if (slot != nritems) {
4390 /* shift the items */
4391 memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + 1),
ad48fd75
YZ
4392 btrfs_item_nr_offset(slot),
4393 (nritems - slot) * sizeof(struct btrfs_item));
459931ec
CM
4394 }
4395
4396 btrfs_cpu_key_to_disk(&disk_key, new_key);
4397 btrfs_set_item_key(leaf, &disk_key, slot);
4398
dd3cc16b 4399 new_item = btrfs_item_nr(slot);
459931ec
CM
4400
4401 btrfs_set_item_offset(leaf, new_item, orig_offset);
4402 btrfs_set_item_size(leaf, new_item, item_size - split_offset);
4403
4404 btrfs_set_item_offset(leaf, item,
4405 orig_offset + item_size - split_offset);
4406 btrfs_set_item_size(leaf, item, split_offset);
4407
4408 btrfs_set_header_nritems(leaf, nritems + 1);
4409
4410 /* write the data for the start of the original item */
4411 write_extent_buffer(leaf, buf,
4412 btrfs_item_ptr_offset(leaf, path->slots[0]),
4413 split_offset);
4414
4415 /* write the data for the new item */
4416 write_extent_buffer(leaf, buf + split_offset,
4417 btrfs_item_ptr_offset(leaf, slot),
4418 item_size - split_offset);
4419 btrfs_mark_buffer_dirty(leaf);
4420
e902baac 4421 BUG_ON(btrfs_leaf_free_space(leaf) < 0);
459931ec 4422 kfree(buf);
ad48fd75
YZ
4423 return 0;
4424}
4425
4426/*
4427 * This function splits a single item into two items,
4428 * giving 'new_key' to the new item and splitting the
4429 * old one at split_offset (from the start of the item).
4430 *
4431 * The path may be released by this operation. After
4432 * the split, the path is pointing to the old item. The
4433 * new item is going to be in the same node as the old one.
4434 *
4435 * Note, the item being split must be smaller enough to live alone on
4436 * a tree block with room for one extra struct btrfs_item
4437 *
4438 * This allows us to split the item in place, keeping a lock on the
4439 * leaf the entire time.
4440 */
4441int btrfs_split_item(struct btrfs_trans_handle *trans,
4442 struct btrfs_root *root,
4443 struct btrfs_path *path,
310712b2 4444 const struct btrfs_key *new_key,
ad48fd75
YZ
4445 unsigned long split_offset)
4446{
4447 int ret;
4448 ret = setup_leaf_for_split(trans, root, path,
4449 sizeof(struct btrfs_item));
4450 if (ret)
4451 return ret;
4452
25263cd7 4453 ret = split_item(path, new_key, split_offset);
459931ec
CM
4454 return ret;
4455}
4456
ad48fd75
YZ
4457/*
4458 * This function duplicate a item, giving 'new_key' to the new item.
4459 * It guarantees both items live in the same tree leaf and the new item
4460 * is contiguous with the original item.
4461 *
4462 * This allows us to split file extent in place, keeping a lock on the
4463 * leaf the entire time.
4464 */
4465int btrfs_duplicate_item(struct btrfs_trans_handle *trans,
4466 struct btrfs_root *root,
4467 struct btrfs_path *path,
310712b2 4468 const struct btrfs_key *new_key)
ad48fd75
YZ
4469{
4470 struct extent_buffer *leaf;
4471 int ret;
4472 u32 item_size;
4473
4474 leaf = path->nodes[0];
4475 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
4476 ret = setup_leaf_for_split(trans, root, path,
4477 item_size + sizeof(struct btrfs_item));
4478 if (ret)
4479 return ret;
4480
4481 path->slots[0]++;
fc0d82e1 4482 setup_items_for_insert(root, path, new_key, &item_size, 1);
ad48fd75
YZ
4483 leaf = path->nodes[0];
4484 memcpy_extent_buffer(leaf,
4485 btrfs_item_ptr_offset(leaf, path->slots[0]),
4486 btrfs_item_ptr_offset(leaf, path->slots[0] - 1),
4487 item_size);
4488 return 0;
4489}
4490
d352ac68
CM
4491/*
4492 * make the item pointed to by the path smaller. new_size indicates
4493 * how small to make it, and from_end tells us if we just chop bytes
4494 * off the end of the item or if we shift the item to chop bytes off
4495 * the front.
4496 */
78ac4f9e 4497void btrfs_truncate_item(struct btrfs_path *path, u32 new_size, int from_end)
b18c6685 4498{
b18c6685 4499 int slot;
5f39d397
CM
4500 struct extent_buffer *leaf;
4501 struct btrfs_item *item;
b18c6685
CM
4502 u32 nritems;
4503 unsigned int data_end;
4504 unsigned int old_data_start;
4505 unsigned int old_size;
4506 unsigned int size_diff;
4507 int i;
cfed81a0
CM
4508 struct btrfs_map_token token;
4509
5f39d397 4510 leaf = path->nodes[0];
179e29e4
CM
4511 slot = path->slots[0];
4512
4513 old_size = btrfs_item_size_nr(leaf, slot);
4514 if (old_size == new_size)
143bede5 4515 return;
b18c6685 4516
5f39d397 4517 nritems = btrfs_header_nritems(leaf);
8f881e8c 4518 data_end = leaf_data_end(leaf);
b18c6685 4519
5f39d397 4520 old_data_start = btrfs_item_offset_nr(leaf, slot);
179e29e4 4521
b18c6685
CM
4522 size_diff = old_size - new_size;
4523
4524 BUG_ON(slot < 0);
4525 BUG_ON(slot >= nritems);
4526
4527 /*
4528 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4529 */
4530 /* first correct the data pointers */
c82f823c 4531 btrfs_init_map_token(&token, leaf);
b18c6685 4532 for (i = slot; i < nritems; i++) {
5f39d397 4533 u32 ioff;
dd3cc16b 4534 item = btrfs_item_nr(i);
db94535d 4535
cc4c13d5
DS
4536 ioff = btrfs_token_item_offset(&token, item);
4537 btrfs_set_token_item_offset(&token, item, ioff + size_diff);
b18c6685 4538 }
db94535d 4539
b18c6685 4540 /* shift the data */
179e29e4 4541 if (from_end) {
3d9ec8c4
NB
4542 memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
4543 data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
179e29e4
CM
4544 data_end, old_data_start + new_size - data_end);
4545 } else {
4546 struct btrfs_disk_key disk_key;
4547 u64 offset;
4548
4549 btrfs_item_key(leaf, &disk_key, slot);
4550
4551 if (btrfs_disk_key_type(&disk_key) == BTRFS_EXTENT_DATA_KEY) {
4552 unsigned long ptr;
4553 struct btrfs_file_extent_item *fi;
4554
4555 fi = btrfs_item_ptr(leaf, slot,
4556 struct btrfs_file_extent_item);
4557 fi = (struct btrfs_file_extent_item *)(
4558 (unsigned long)fi - size_diff);
4559
4560 if (btrfs_file_extent_type(leaf, fi) ==
4561 BTRFS_FILE_EXTENT_INLINE) {
4562 ptr = btrfs_item_ptr_offset(leaf, slot);
4563 memmove_extent_buffer(leaf, ptr,
d397712b 4564 (unsigned long)fi,
7ec20afb 4565 BTRFS_FILE_EXTENT_INLINE_DATA_START);
179e29e4
CM
4566 }
4567 }
4568
3d9ec8c4
NB
4569 memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
4570 data_end + size_diff, BTRFS_LEAF_DATA_OFFSET +
179e29e4
CM
4571 data_end, old_data_start - data_end);
4572
4573 offset = btrfs_disk_key_offset(&disk_key);
4574 btrfs_set_disk_key_offset(&disk_key, offset + size_diff);
4575 btrfs_set_item_key(leaf, &disk_key, slot);
4576 if (slot == 0)
b167fa91 4577 fixup_low_keys(path, &disk_key, 1);
179e29e4 4578 }
5f39d397 4579
dd3cc16b 4580 item = btrfs_item_nr(slot);
5f39d397
CM
4581 btrfs_set_item_size(leaf, item, new_size);
4582 btrfs_mark_buffer_dirty(leaf);
b18c6685 4583
e902baac 4584 if (btrfs_leaf_free_space(leaf) < 0) {
a4f78750 4585 btrfs_print_leaf(leaf);
b18c6685 4586 BUG();
5f39d397 4587 }
b18c6685
CM
4588}
4589
d352ac68 4590/*
8f69dbd2 4591 * make the item pointed to by the path bigger, data_size is the added size.
d352ac68 4592 */
c71dd880 4593void btrfs_extend_item(struct btrfs_path *path, u32 data_size)
6567e837 4594{
6567e837 4595 int slot;
5f39d397
CM
4596 struct extent_buffer *leaf;
4597 struct btrfs_item *item;
6567e837
CM
4598 u32 nritems;
4599 unsigned int data_end;
4600 unsigned int old_data;
4601 unsigned int old_size;
4602 int i;
cfed81a0
CM
4603 struct btrfs_map_token token;
4604
5f39d397 4605 leaf = path->nodes[0];
6567e837 4606
5f39d397 4607 nritems = btrfs_header_nritems(leaf);
8f881e8c 4608 data_end = leaf_data_end(leaf);
6567e837 4609
e902baac 4610 if (btrfs_leaf_free_space(leaf) < data_size) {
a4f78750 4611 btrfs_print_leaf(leaf);
6567e837 4612 BUG();
5f39d397 4613 }
6567e837 4614 slot = path->slots[0];
5f39d397 4615 old_data = btrfs_item_end_nr(leaf, slot);
6567e837
CM
4616
4617 BUG_ON(slot < 0);
3326d1b0 4618 if (slot >= nritems) {
a4f78750 4619 btrfs_print_leaf(leaf);
c71dd880 4620 btrfs_crit(leaf->fs_info, "slot %d too large, nritems %d",
0b246afa 4621 slot, nritems);
290342f6 4622 BUG();
3326d1b0 4623 }
6567e837
CM
4624
4625 /*
4626 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4627 */
4628 /* first correct the data pointers */
c82f823c 4629 btrfs_init_map_token(&token, leaf);
6567e837 4630 for (i = slot; i < nritems; i++) {
5f39d397 4631 u32 ioff;
dd3cc16b 4632 item = btrfs_item_nr(i);
db94535d 4633
cc4c13d5
DS
4634 ioff = btrfs_token_item_offset(&token, item);
4635 btrfs_set_token_item_offset(&token, item, ioff - data_size);
6567e837 4636 }
5f39d397 4637
6567e837 4638 /* shift the data */
3d9ec8c4
NB
4639 memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
4640 data_end - data_size, BTRFS_LEAF_DATA_OFFSET +
6567e837 4641 data_end, old_data - data_end);
5f39d397 4642
6567e837 4643 data_end = old_data;
5f39d397 4644 old_size = btrfs_item_size_nr(leaf, slot);
dd3cc16b 4645 item = btrfs_item_nr(slot);
5f39d397
CM
4646 btrfs_set_item_size(leaf, item, old_size + data_size);
4647 btrfs_mark_buffer_dirty(leaf);
6567e837 4648
e902baac 4649 if (btrfs_leaf_free_space(leaf) < 0) {
a4f78750 4650 btrfs_print_leaf(leaf);
6567e837 4651 BUG();
5f39d397 4652 }
6567e837
CM
4653}
4654
da9ffb24
NB
4655/**
4656 * setup_items_for_insert - Helper called before inserting one or more items
4657 * to a leaf. Main purpose is to save stack depth by doing the bulk of the work
4658 * in a function that doesn't call btrfs_search_slot
4659 *
4660 * @root: root we are inserting items to
4661 * @path: points to the leaf/slot where we are going to insert new items
4662 * @cpu_key: array of keys for items to be inserted
4663 * @data_size: size of the body of each item we are going to insert
4664 * @nr: size of @cpu_key/@data_size arrays
74123bd7 4665 */
afe5fea7 4666void setup_items_for_insert(struct btrfs_root *root, struct btrfs_path *path,
310712b2 4667 const struct btrfs_key *cpu_key, u32 *data_size,
fc0d82e1 4668 int nr)
be0e5c09 4669{
0b246afa 4670 struct btrfs_fs_info *fs_info = root->fs_info;
5f39d397 4671 struct btrfs_item *item;
9c58309d 4672 int i;
7518a238 4673 u32 nritems;
be0e5c09 4674 unsigned int data_end;
e2fa7227 4675 struct btrfs_disk_key disk_key;
44871b1b
CM
4676 struct extent_buffer *leaf;
4677 int slot;
cfed81a0 4678 struct btrfs_map_token token;
fc0d82e1
NB
4679 u32 total_size;
4680 u32 total_data = 0;
4681
4682 for (i = 0; i < nr; i++)
4683 total_data += data_size[i];
4684 total_size = total_data + (nr * sizeof(struct btrfs_item));
cfed81a0 4685
24cdc847
FM
4686 if (path->slots[0] == 0) {
4687 btrfs_cpu_key_to_disk(&disk_key, cpu_key);
b167fa91 4688 fixup_low_keys(path, &disk_key, 1);
24cdc847
FM
4689 }
4690 btrfs_unlock_up_safe(path, 1);
4691
5f39d397 4692 leaf = path->nodes[0];
44871b1b 4693 slot = path->slots[0];
74123bd7 4694
5f39d397 4695 nritems = btrfs_header_nritems(leaf);
8f881e8c 4696 data_end = leaf_data_end(leaf);
eb60ceac 4697
e902baac 4698 if (btrfs_leaf_free_space(leaf) < total_size) {
a4f78750 4699 btrfs_print_leaf(leaf);
0b246afa 4700 btrfs_crit(fs_info, "not enough freespace need %u have %d",
e902baac 4701 total_size, btrfs_leaf_free_space(leaf));
be0e5c09 4702 BUG();
d4dbff95 4703 }
5f39d397 4704
c82f823c 4705 btrfs_init_map_token(&token, leaf);
be0e5c09 4706 if (slot != nritems) {
5f39d397 4707 unsigned int old_data = btrfs_item_end_nr(leaf, slot);
be0e5c09 4708
5f39d397 4709 if (old_data < data_end) {
a4f78750 4710 btrfs_print_leaf(leaf);
7269ddd2
NB
4711 btrfs_crit(fs_info,
4712 "item at slot %d with data offset %u beyond data end of leaf %u",
5d163e0e 4713 slot, old_data, data_end);
290342f6 4714 BUG();
5f39d397 4715 }
be0e5c09
CM
4716 /*
4717 * item0..itemN ... dataN.offset..dataN.size .. data0.size
4718 */
4719 /* first correct the data pointers */
0783fcfc 4720 for (i = slot; i < nritems; i++) {
5f39d397 4721 u32 ioff;
db94535d 4722
62e85577 4723 item = btrfs_item_nr(i);
cc4c13d5
DS
4724 ioff = btrfs_token_item_offset(&token, item);
4725 btrfs_set_token_item_offset(&token, item,
4726 ioff - total_data);
0783fcfc 4727 }
be0e5c09 4728 /* shift the items */
9c58309d 4729 memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot + nr),
5f39d397 4730 btrfs_item_nr_offset(slot),
d6025579 4731 (nritems - slot) * sizeof(struct btrfs_item));
be0e5c09
CM
4732
4733 /* shift the data */
3d9ec8c4
NB
4734 memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
4735 data_end - total_data, BTRFS_LEAF_DATA_OFFSET +
d6025579 4736 data_end, old_data - data_end);
be0e5c09
CM
4737 data_end = old_data;
4738 }
5f39d397 4739
62e2749e 4740 /* setup the item for the new data */
9c58309d
CM
4741 for (i = 0; i < nr; i++) {
4742 btrfs_cpu_key_to_disk(&disk_key, cpu_key + i);
4743 btrfs_set_item_key(leaf, &disk_key, slot + i);
dd3cc16b 4744 item = btrfs_item_nr(slot + i);
9c58309d 4745 data_end -= data_size[i];
fc0716c2 4746 btrfs_set_token_item_offset(&token, item, data_end);
cc4c13d5 4747 btrfs_set_token_item_size(&token, item, data_size[i]);
9c58309d 4748 }
44871b1b 4749
9c58309d 4750 btrfs_set_header_nritems(leaf, nritems + nr);
b9473439 4751 btrfs_mark_buffer_dirty(leaf);
aa5d6bed 4752
e902baac 4753 if (btrfs_leaf_free_space(leaf) < 0) {
a4f78750 4754 btrfs_print_leaf(leaf);
be0e5c09 4755 BUG();
5f39d397 4756 }
44871b1b
CM
4757}
4758
4759/*
4760 * Given a key and some data, insert items into the tree.
4761 * This does all the path init required, making room in the tree if needed.
4762 */
4763int btrfs_insert_empty_items(struct btrfs_trans_handle *trans,
4764 struct btrfs_root *root,
4765 struct btrfs_path *path,
310712b2 4766 const struct btrfs_key *cpu_key, u32 *data_size,
44871b1b
CM
4767 int nr)
4768{
44871b1b
CM
4769 int ret = 0;
4770 int slot;
4771 int i;
4772 u32 total_size = 0;
4773 u32 total_data = 0;
4774
4775 for (i = 0; i < nr; i++)
4776 total_data += data_size[i];
4777
4778 total_size = total_data + (nr * sizeof(struct btrfs_item));
4779 ret = btrfs_search_slot(trans, root, cpu_key, path, total_size, 1);
4780 if (ret == 0)
4781 return -EEXIST;
4782 if (ret < 0)
143bede5 4783 return ret;
44871b1b 4784
44871b1b
CM
4785 slot = path->slots[0];
4786 BUG_ON(slot < 0);
4787
fc0d82e1 4788 setup_items_for_insert(root, path, cpu_key, data_size, nr);
143bede5 4789 return 0;
62e2749e
CM
4790}
4791
4792/*
4793 * Given a key and some data, insert an item into the tree.
4794 * This does all the path init required, making room in the tree if needed.
4795 */
310712b2
OS
4796int btrfs_insert_item(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4797 const struct btrfs_key *cpu_key, void *data,
4798 u32 data_size)
62e2749e
CM
4799{
4800 int ret = 0;
2c90e5d6 4801 struct btrfs_path *path;
5f39d397
CM
4802 struct extent_buffer *leaf;
4803 unsigned long ptr;
62e2749e 4804
2c90e5d6 4805 path = btrfs_alloc_path();
db5b493a
TI
4806 if (!path)
4807 return -ENOMEM;
2c90e5d6 4808 ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size);
62e2749e 4809 if (!ret) {
5f39d397
CM
4810 leaf = path->nodes[0];
4811 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
4812 write_extent_buffer(leaf, data, ptr, data_size);
4813 btrfs_mark_buffer_dirty(leaf);
62e2749e 4814 }
2c90e5d6 4815 btrfs_free_path(path);
aa5d6bed 4816 return ret;
be0e5c09
CM
4817}
4818
74123bd7 4819/*
5de08d7d 4820 * delete the pointer from a given node.
74123bd7 4821 *
d352ac68
CM
4822 * the tree should have been previously balanced so the deletion does not
4823 * empty a node.
74123bd7 4824 */
afe5fea7
TI
4825static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
4826 int level, int slot)
be0e5c09 4827{
5f39d397 4828 struct extent_buffer *parent = path->nodes[level];
7518a238 4829 u32 nritems;
f3ea38da 4830 int ret;
be0e5c09 4831
5f39d397 4832 nritems = btrfs_header_nritems(parent);
d397712b 4833 if (slot != nritems - 1) {
bf1d3425
DS
4834 if (level) {
4835 ret = tree_mod_log_insert_move(parent, slot, slot + 1,
a446a979 4836 nritems - slot - 1);
bf1d3425
DS
4837 BUG_ON(ret < 0);
4838 }
5f39d397
CM
4839 memmove_extent_buffer(parent,
4840 btrfs_node_key_ptr_offset(slot),
4841 btrfs_node_key_ptr_offset(slot + 1),
d6025579
CM
4842 sizeof(struct btrfs_key_ptr) *
4843 (nritems - slot - 1));
57ba86c0 4844 } else if (level) {
e09c2efe
DS
4845 ret = tree_mod_log_insert_key(parent, slot, MOD_LOG_KEY_REMOVE,
4846 GFP_NOFS);
57ba86c0 4847 BUG_ON(ret < 0);
bb803951 4848 }
f3ea38da 4849
7518a238 4850 nritems--;
5f39d397 4851 btrfs_set_header_nritems(parent, nritems);
7518a238 4852 if (nritems == 0 && parent == root->node) {
5f39d397 4853 BUG_ON(btrfs_header_level(root->node) != 1);
bb803951 4854 /* just turn the root into a leaf and break */
5f39d397 4855 btrfs_set_header_level(root->node, 0);
bb803951 4856 } else if (slot == 0) {
5f39d397
CM
4857 struct btrfs_disk_key disk_key;
4858
4859 btrfs_node_key(parent, &disk_key, 0);
b167fa91 4860 fixup_low_keys(path, &disk_key, level + 1);
be0e5c09 4861 }
d6025579 4862 btrfs_mark_buffer_dirty(parent);
be0e5c09
CM
4863}
4864
323ac95b
CM
4865/*
4866 * a helper function to delete the leaf pointed to by path->slots[1] and
5d4f98a2 4867 * path->nodes[1].
323ac95b
CM
4868 *
4869 * This deletes the pointer in path->nodes[1] and frees the leaf
4870 * block extent. zero is returned if it all worked out, < 0 otherwise.
4871 *
4872 * The path must have already been setup for deleting the leaf, including
4873 * all the proper balancing. path->nodes[1] must be locked.
4874 */
143bede5
JM
4875static noinline void btrfs_del_leaf(struct btrfs_trans_handle *trans,
4876 struct btrfs_root *root,
4877 struct btrfs_path *path,
4878 struct extent_buffer *leaf)
323ac95b 4879{
5d4f98a2 4880 WARN_ON(btrfs_header_generation(leaf) != trans->transid);
afe5fea7 4881 del_ptr(root, path, 1, path->slots[1]);
323ac95b 4882
4d081c41
CM
4883 /*
4884 * btrfs_free_extent is expensive, we want to make sure we
4885 * aren't holding any locks when we call it
4886 */
4887 btrfs_unlock_up_safe(path, 0);
4888
f0486c68
YZ
4889 root_sub_used(root, leaf->len);
4890
67439dad 4891 atomic_inc(&leaf->refs);
5581a51a 4892 btrfs_free_tree_block(trans, root, leaf, 0, 1);
3083ee2e 4893 free_extent_buffer_stale(leaf);
323ac95b 4894}
74123bd7
CM
4895/*
4896 * delete the item at the leaf level in path. If that empties
4897 * the leaf, remove it from the tree
4898 */
85e21bac
CM
4899int btrfs_del_items(struct btrfs_trans_handle *trans, struct btrfs_root *root,
4900 struct btrfs_path *path, int slot, int nr)
be0e5c09 4901{
0b246afa 4902 struct btrfs_fs_info *fs_info = root->fs_info;
5f39d397
CM
4903 struct extent_buffer *leaf;
4904 struct btrfs_item *item;
ce0eac2a
AM
4905 u32 last_off;
4906 u32 dsize = 0;
aa5d6bed
CM
4907 int ret = 0;
4908 int wret;
85e21bac 4909 int i;
7518a238 4910 u32 nritems;
be0e5c09 4911
5f39d397 4912 leaf = path->nodes[0];
85e21bac
CM
4913 last_off = btrfs_item_offset_nr(leaf, slot + nr - 1);
4914
4915 for (i = 0; i < nr; i++)
4916 dsize += btrfs_item_size_nr(leaf, slot + i);
4917
5f39d397 4918 nritems = btrfs_header_nritems(leaf);
be0e5c09 4919
85e21bac 4920 if (slot + nr != nritems) {
8f881e8c 4921 int data_end = leaf_data_end(leaf);
c82f823c 4922 struct btrfs_map_token token;
5f39d397 4923
3d9ec8c4 4924 memmove_extent_buffer(leaf, BTRFS_LEAF_DATA_OFFSET +
d6025579 4925 data_end + dsize,
3d9ec8c4 4926 BTRFS_LEAF_DATA_OFFSET + data_end,
85e21bac 4927 last_off - data_end);
5f39d397 4928
c82f823c 4929 btrfs_init_map_token(&token, leaf);
85e21bac 4930 for (i = slot + nr; i < nritems; i++) {
5f39d397 4931 u32 ioff;
db94535d 4932
dd3cc16b 4933 item = btrfs_item_nr(i);
cc4c13d5
DS
4934 ioff = btrfs_token_item_offset(&token, item);
4935 btrfs_set_token_item_offset(&token, item, ioff + dsize);
0783fcfc 4936 }
db94535d 4937
5f39d397 4938 memmove_extent_buffer(leaf, btrfs_item_nr_offset(slot),
85e21bac 4939 btrfs_item_nr_offset(slot + nr),
d6025579 4940 sizeof(struct btrfs_item) *
85e21bac 4941 (nritems - slot - nr));
be0e5c09 4942 }
85e21bac
CM
4943 btrfs_set_header_nritems(leaf, nritems - nr);
4944 nritems -= nr;
5f39d397 4945
74123bd7 4946 /* delete the leaf if we've emptied it */
7518a238 4947 if (nritems == 0) {
5f39d397
CM
4948 if (leaf == root->node) {
4949 btrfs_set_header_level(leaf, 0);
9a8dd150 4950 } else {
6a884d7d 4951 btrfs_clean_tree_block(leaf);
143bede5 4952 btrfs_del_leaf(trans, root, path, leaf);
9a8dd150 4953 }
be0e5c09 4954 } else {
7518a238 4955 int used = leaf_space_used(leaf, 0, nritems);
aa5d6bed 4956 if (slot == 0) {
5f39d397
CM
4957 struct btrfs_disk_key disk_key;
4958
4959 btrfs_item_key(leaf, &disk_key, 0);
b167fa91 4960 fixup_low_keys(path, &disk_key, 1);
aa5d6bed 4961 }
aa5d6bed 4962
74123bd7 4963 /* delete the leaf if it is mostly empty */
0b246afa 4964 if (used < BTRFS_LEAF_DATA_SIZE(fs_info) / 3) {
be0e5c09
CM
4965 /* push_leaf_left fixes the path.
4966 * make sure the path still points to our leaf
4967 * for possible call to del_ptr below
4968 */
4920c9ac 4969 slot = path->slots[1];
67439dad 4970 atomic_inc(&leaf->refs);
5f39d397 4971
99d8f83c
CM
4972 wret = push_leaf_left(trans, root, path, 1, 1,
4973 1, (u32)-1);
54aa1f4d 4974 if (wret < 0 && wret != -ENOSPC)
aa5d6bed 4975 ret = wret;
5f39d397
CM
4976
4977 if (path->nodes[0] == leaf &&
4978 btrfs_header_nritems(leaf)) {
99d8f83c
CM
4979 wret = push_leaf_right(trans, root, path, 1,
4980 1, 1, 0);
54aa1f4d 4981 if (wret < 0 && wret != -ENOSPC)
aa5d6bed
CM
4982 ret = wret;
4983 }
5f39d397
CM
4984
4985 if (btrfs_header_nritems(leaf) == 0) {
323ac95b 4986 path->slots[1] = slot;
143bede5 4987 btrfs_del_leaf(trans, root, path, leaf);
5f39d397 4988 free_extent_buffer(leaf);
143bede5 4989 ret = 0;
5de08d7d 4990 } else {
925baedd
CM
4991 /* if we're still in the path, make sure
4992 * we're dirty. Otherwise, one of the
4993 * push_leaf functions must have already
4994 * dirtied this buffer
4995 */
4996 if (path->nodes[0] == leaf)
4997 btrfs_mark_buffer_dirty(leaf);
5f39d397 4998 free_extent_buffer(leaf);
be0e5c09 4999 }
d5719762 5000 } else {
5f39d397 5001 btrfs_mark_buffer_dirty(leaf);
be0e5c09
CM
5002 }
5003 }
aa5d6bed 5004 return ret;
be0e5c09
CM
5005}
5006
7bb86316 5007/*
925baedd 5008 * search the tree again to find a leaf with lesser keys
7bb86316
CM
5009 * returns 0 if it found something or 1 if there are no lesser leaves.
5010 * returns < 0 on io errors.
d352ac68
CM
5011 *
5012 * This may release the path, and so you may lose any locks held at the
5013 * time you call it.
7bb86316 5014 */
16e7549f 5015int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
7bb86316 5016{
925baedd
CM
5017 struct btrfs_key key;
5018 struct btrfs_disk_key found_key;
5019 int ret;
7bb86316 5020
925baedd 5021 btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
7bb86316 5022
e8b0d724 5023 if (key.offset > 0) {
925baedd 5024 key.offset--;
e8b0d724 5025 } else if (key.type > 0) {
925baedd 5026 key.type--;
e8b0d724
FDBM
5027 key.offset = (u64)-1;
5028 } else if (key.objectid > 0) {
925baedd 5029 key.objectid--;
e8b0d724
FDBM
5030 key.type = (u8)-1;
5031 key.offset = (u64)-1;
5032 } else {
925baedd 5033 return 1;
e8b0d724 5034 }
7bb86316 5035
b3b4aa74 5036 btrfs_release_path(path);
925baedd
CM
5037 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5038 if (ret < 0)
5039 return ret;
5040 btrfs_item_key(path->nodes[0], &found_key, 0);
5041 ret = comp_keys(&found_key, &key);
337c6f68
FM
5042 /*
5043 * We might have had an item with the previous key in the tree right
5044 * before we released our path. And after we released our path, that
5045 * item might have been pushed to the first slot (0) of the leaf we
5046 * were holding due to a tree balance. Alternatively, an item with the
5047 * previous key can exist as the only element of a leaf (big fat item).
5048 * Therefore account for these 2 cases, so that our callers (like
5049 * btrfs_previous_item) don't miss an existing item with a key matching
5050 * the previous key we computed above.
5051 */
5052 if (ret <= 0)
925baedd
CM
5053 return 0;
5054 return 1;
7bb86316
CM
5055}
5056
3f157a2f
CM
5057/*
5058 * A helper function to walk down the tree starting at min_key, and looking
de78b51a
ES
5059 * for nodes or leaves that are have a minimum transaction id.
5060 * This is used by the btree defrag code, and tree logging
3f157a2f
CM
5061 *
5062 * This does not cow, but it does stuff the starting key it finds back
5063 * into min_key, so you can call btrfs_search_slot with cow=1 on the
5064 * key and get a writable path.
5065 *
3f157a2f
CM
5066 * This honors path->lowest_level to prevent descent past a given level
5067 * of the tree.
5068 *
d352ac68
CM
5069 * min_trans indicates the oldest transaction that you are interested
5070 * in walking through. Any nodes or leaves older than min_trans are
5071 * skipped over (without reading them).
5072 *
3f157a2f
CM
5073 * returns zero if something useful was found, < 0 on error and 1 if there
5074 * was nothing in the tree that matched the search criteria.
5075 */
5076int btrfs_search_forward(struct btrfs_root *root, struct btrfs_key *min_key,
de78b51a 5077 struct btrfs_path *path,
3f157a2f
CM
5078 u64 min_trans)
5079{
5080 struct extent_buffer *cur;
5081 struct btrfs_key found_key;
5082 int slot;
9652480b 5083 int sret;
3f157a2f
CM
5084 u32 nritems;
5085 int level;
5086 int ret = 1;
f98de9b9 5087 int keep_locks = path->keep_locks;
3f157a2f 5088
f98de9b9 5089 path->keep_locks = 1;
3f157a2f 5090again:
bd681513 5091 cur = btrfs_read_lock_root_node(root);
3f157a2f 5092 level = btrfs_header_level(cur);
e02119d5 5093 WARN_ON(path->nodes[level]);
3f157a2f 5094 path->nodes[level] = cur;
bd681513 5095 path->locks[level] = BTRFS_READ_LOCK;
3f157a2f
CM
5096
5097 if (btrfs_header_generation(cur) < min_trans) {
5098 ret = 1;
5099 goto out;
5100 }
d397712b 5101 while (1) {
3f157a2f
CM
5102 nritems = btrfs_header_nritems(cur);
5103 level = btrfs_header_level(cur);
e3b83361 5104 sret = btrfs_bin_search(cur, min_key, &slot);
cbca7d59
FM
5105 if (sret < 0) {
5106 ret = sret;
5107 goto out;
5108 }
3f157a2f 5109
323ac95b
CM
5110 /* at the lowest level, we're done, setup the path and exit */
5111 if (level == path->lowest_level) {
e02119d5
CM
5112 if (slot >= nritems)
5113 goto find_next_key;
3f157a2f
CM
5114 ret = 0;
5115 path->slots[level] = slot;
5116 btrfs_item_key_to_cpu(cur, &found_key, slot);
5117 goto out;
5118 }
9652480b
Y
5119 if (sret && slot > 0)
5120 slot--;
3f157a2f 5121 /*
de78b51a 5122 * check this node pointer against the min_trans parameters.
260db43c 5123 * If it is too old, skip to the next one.
3f157a2f 5124 */
d397712b 5125 while (slot < nritems) {
3f157a2f 5126 u64 gen;
e02119d5 5127
3f157a2f
CM
5128 gen = btrfs_node_ptr_generation(cur, slot);
5129 if (gen < min_trans) {
5130 slot++;
5131 continue;
5132 }
de78b51a 5133 break;
3f157a2f 5134 }
e02119d5 5135find_next_key:
3f157a2f
CM
5136 /*
5137 * we didn't find a candidate key in this node, walk forward
5138 * and find another one
5139 */
5140 if (slot >= nritems) {
e02119d5
CM
5141 path->slots[level] = slot;
5142 sret = btrfs_find_next_key(root, path, min_key, level,
de78b51a 5143 min_trans);
e02119d5 5144 if (sret == 0) {
b3b4aa74 5145 btrfs_release_path(path);
3f157a2f
CM
5146 goto again;
5147 } else {
5148 goto out;
5149 }
5150 }
5151 /* save our key for returning back */
5152 btrfs_node_key_to_cpu(cur, &found_key, slot);
5153 path->slots[level] = slot;
5154 if (level == path->lowest_level) {
5155 ret = 0;
3f157a2f
CM
5156 goto out;
5157 }
4b231ae4 5158 cur = btrfs_read_node_slot(cur, slot);
fb770ae4
LB
5159 if (IS_ERR(cur)) {
5160 ret = PTR_ERR(cur);
5161 goto out;
5162 }
3f157a2f 5163
bd681513 5164 btrfs_tree_read_lock(cur);
b4ce94de 5165
bd681513 5166 path->locks[level - 1] = BTRFS_READ_LOCK;
3f157a2f 5167 path->nodes[level - 1] = cur;
f7c79f30 5168 unlock_up(path, level, 1, 0, NULL);
3f157a2f
CM
5169 }
5170out:
f98de9b9
FM
5171 path->keep_locks = keep_locks;
5172 if (ret == 0) {
5173 btrfs_unlock_up_safe(path, path->lowest_level + 1);
3f157a2f 5174 memcpy(min_key, &found_key, sizeof(found_key));
f98de9b9 5175 }
3f157a2f
CM
5176 return ret;
5177}
5178
5179/*
5180 * this is similar to btrfs_next_leaf, but does not try to preserve
5181 * and fixup the path. It looks for and returns the next key in the
de78b51a 5182 * tree based on the current path and the min_trans parameters.
3f157a2f
CM
5183 *
5184 * 0 is returned if another key is found, < 0 if there are any errors
5185 * and 1 is returned if there are no higher keys in the tree
5186 *
5187 * path->keep_locks should be set to 1 on the search made before
5188 * calling this function.
5189 */
e7a84565 5190int btrfs_find_next_key(struct btrfs_root *root, struct btrfs_path *path,
de78b51a 5191 struct btrfs_key *key, int level, u64 min_trans)
e7a84565 5192{
e7a84565
CM
5193 int slot;
5194 struct extent_buffer *c;
5195
6a9fb468 5196 WARN_ON(!path->keep_locks && !path->skip_locking);
d397712b 5197 while (level < BTRFS_MAX_LEVEL) {
e7a84565
CM
5198 if (!path->nodes[level])
5199 return 1;
5200
5201 slot = path->slots[level] + 1;
5202 c = path->nodes[level];
3f157a2f 5203next:
e7a84565 5204 if (slot >= btrfs_header_nritems(c)) {
33c66f43
YZ
5205 int ret;
5206 int orig_lowest;
5207 struct btrfs_key cur_key;
5208 if (level + 1 >= BTRFS_MAX_LEVEL ||
5209 !path->nodes[level + 1])
e7a84565 5210 return 1;
33c66f43 5211
6a9fb468 5212 if (path->locks[level + 1] || path->skip_locking) {
33c66f43
YZ
5213 level++;
5214 continue;
5215 }
5216
5217 slot = btrfs_header_nritems(c) - 1;
5218 if (level == 0)
5219 btrfs_item_key_to_cpu(c, &cur_key, slot);
5220 else
5221 btrfs_node_key_to_cpu(c, &cur_key, slot);
5222
5223 orig_lowest = path->lowest_level;
b3b4aa74 5224 btrfs_release_path(path);
33c66f43
YZ
5225 path->lowest_level = level;
5226 ret = btrfs_search_slot(NULL, root, &cur_key, path,
5227 0, 0);
5228 path->lowest_level = orig_lowest;
5229 if (ret < 0)
5230 return ret;
5231
5232 c = path->nodes[level];
5233 slot = path->slots[level];
5234 if (ret == 0)
5235 slot++;
5236 goto next;
e7a84565 5237 }
33c66f43 5238
e7a84565
CM
5239 if (level == 0)
5240 btrfs_item_key_to_cpu(c, key, slot);
3f157a2f 5241 else {
3f157a2f
CM
5242 u64 gen = btrfs_node_ptr_generation(c, slot);
5243
3f157a2f
CM
5244 if (gen < min_trans) {
5245 slot++;
5246 goto next;
5247 }
e7a84565 5248 btrfs_node_key_to_cpu(c, key, slot);
3f157a2f 5249 }
e7a84565
CM
5250 return 0;
5251 }
5252 return 1;
5253}
5254
97571fd0 5255/*
925baedd 5256 * search the tree again to find a leaf with greater keys
0f70abe2
CM
5257 * returns 0 if it found something or 1 if there are no greater leaves.
5258 * returns < 0 on io errors.
97571fd0 5259 */
234b63a0 5260int btrfs_next_leaf(struct btrfs_root *root, struct btrfs_path *path)
3d7806ec
JS
5261{
5262 return btrfs_next_old_leaf(root, path, 0);
5263}
5264
5265int btrfs_next_old_leaf(struct btrfs_root *root, struct btrfs_path *path,
5266 u64 time_seq)
d97e63b6
CM
5267{
5268 int slot;
8e73f275 5269 int level;
5f39d397 5270 struct extent_buffer *c;
8e73f275 5271 struct extent_buffer *next;
925baedd
CM
5272 struct btrfs_key key;
5273 u32 nritems;
5274 int ret;
bd681513 5275 int next_rw_lock = 0;
925baedd
CM
5276
5277 nritems = btrfs_header_nritems(path->nodes[0]);
d397712b 5278 if (nritems == 0)
925baedd 5279 return 1;
925baedd 5280
8e73f275
CM
5281 btrfs_item_key_to_cpu(path->nodes[0], &key, nritems - 1);
5282again:
5283 level = 1;
5284 next = NULL;
bd681513 5285 next_rw_lock = 0;
b3b4aa74 5286 btrfs_release_path(path);
8e73f275 5287
a2135011 5288 path->keep_locks = 1;
8e73f275 5289
3d7806ec
JS
5290 if (time_seq)
5291 ret = btrfs_search_old_slot(root, &key, path, time_seq);
5292 else
5293 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
925baedd
CM
5294 path->keep_locks = 0;
5295
5296 if (ret < 0)
5297 return ret;
5298
a2135011 5299 nritems = btrfs_header_nritems(path->nodes[0]);
168fd7d2
CM
5300 /*
5301 * by releasing the path above we dropped all our locks. A balance
5302 * could have added more items next to the key that used to be
5303 * at the very end of the block. So, check again here and
5304 * advance the path if there are now more items available.
5305 */
a2135011 5306 if (nritems > 0 && path->slots[0] < nritems - 1) {
e457afec
YZ
5307 if (ret == 0)
5308 path->slots[0]++;
8e73f275 5309 ret = 0;
925baedd
CM
5310 goto done;
5311 }
0b43e04f
LB
5312 /*
5313 * So the above check misses one case:
5314 * - after releasing the path above, someone has removed the item that
5315 * used to be at the very end of the block, and balance between leafs
5316 * gets another one with bigger key.offset to replace it.
5317 *
5318 * This one should be returned as well, or we can get leaf corruption
5319 * later(esp. in __btrfs_drop_extents()).
5320 *
5321 * And a bit more explanation about this check,
5322 * with ret > 0, the key isn't found, the path points to the slot
5323 * where it should be inserted, so the path->slots[0] item must be the
5324 * bigger one.
5325 */
5326 if (nritems > 0 && ret > 0 && path->slots[0] == nritems - 1) {
5327 ret = 0;
5328 goto done;
5329 }
d97e63b6 5330
d397712b 5331 while (level < BTRFS_MAX_LEVEL) {
8e73f275
CM
5332 if (!path->nodes[level]) {
5333 ret = 1;
5334 goto done;
5335 }
5f39d397 5336
d97e63b6
CM
5337 slot = path->slots[level] + 1;
5338 c = path->nodes[level];
5f39d397 5339 if (slot >= btrfs_header_nritems(c)) {
d97e63b6 5340 level++;
8e73f275
CM
5341 if (level == BTRFS_MAX_LEVEL) {
5342 ret = 1;
5343 goto done;
5344 }
d97e63b6
CM
5345 continue;
5346 }
5f39d397 5347
925baedd 5348 if (next) {
bd681513 5349 btrfs_tree_unlock_rw(next, next_rw_lock);
5f39d397 5350 free_extent_buffer(next);
925baedd 5351 }
5f39d397 5352
8e73f275 5353 next = c;
bd681513 5354 next_rw_lock = path->locks[level];
d07b8528 5355 ret = read_block_for_search(root, path, &next, level,
cda79c54 5356 slot, &key);
8e73f275
CM
5357 if (ret == -EAGAIN)
5358 goto again;
5f39d397 5359
76a05b35 5360 if (ret < 0) {
b3b4aa74 5361 btrfs_release_path(path);
76a05b35
CM
5362 goto done;
5363 }
5364
5cd57b2c 5365 if (!path->skip_locking) {
bd681513 5366 ret = btrfs_try_tree_read_lock(next);
d42244a0
JS
5367 if (!ret && time_seq) {
5368 /*
5369 * If we don't get the lock, we may be racing
5370 * with push_leaf_left, holding that lock while
5371 * itself waiting for the leaf we've currently
5372 * locked. To solve this situation, we give up
5373 * on our lock and cycle.
5374 */
cf538830 5375 free_extent_buffer(next);
d42244a0
JS
5376 btrfs_release_path(path);
5377 cond_resched();
5378 goto again;
5379 }
8e73f275 5380 if (!ret) {
fd7ba1c1 5381 __btrfs_tree_read_lock(next,
bf77467a 5382 BTRFS_NESTING_RIGHT,
fd7ba1c1 5383 path->recurse);
8e73f275 5384 }
31533fb2 5385 next_rw_lock = BTRFS_READ_LOCK;
5cd57b2c 5386 }
d97e63b6
CM
5387 break;
5388 }
5389 path->slots[level] = slot;
d397712b 5390 while (1) {
d97e63b6
CM
5391 level--;
5392 c = path->nodes[level];
925baedd 5393 if (path->locks[level])
bd681513 5394 btrfs_tree_unlock_rw(c, path->locks[level]);
8e73f275 5395
5f39d397 5396 free_extent_buffer(c);
d97e63b6
CM
5397 path->nodes[level] = next;
5398 path->slots[level] = 0;
a74a4b97 5399 if (!path->skip_locking)
bd681513 5400 path->locks[level] = next_rw_lock;
d97e63b6
CM
5401 if (!level)
5402 break;
b4ce94de 5403
d07b8528 5404 ret = read_block_for_search(root, path, &next, level,
cda79c54 5405 0, &key);
8e73f275
CM
5406 if (ret == -EAGAIN)
5407 goto again;
5408
76a05b35 5409 if (ret < 0) {
b3b4aa74 5410 btrfs_release_path(path);
76a05b35
CM
5411 goto done;
5412 }
5413
5cd57b2c 5414 if (!path->skip_locking) {
ac5887c8
JB
5415 __btrfs_tree_read_lock(next, BTRFS_NESTING_RIGHT,
5416 path->recurse);
31533fb2 5417 next_rw_lock = BTRFS_READ_LOCK;
5cd57b2c 5418 }
d97e63b6 5419 }
8e73f275 5420 ret = 0;
925baedd 5421done:
f7c79f30 5422 unlock_up(path, 0, 1, 0, NULL);
8e73f275
CM
5423
5424 return ret;
d97e63b6 5425}
0b86a832 5426
3f157a2f
CM
5427/*
5428 * this uses btrfs_prev_leaf to walk backwards in the tree, and keeps
5429 * searching until it gets past min_objectid or finds an item of 'type'
5430 *
5431 * returns 0 if something is found, 1 if nothing was found and < 0 on error
5432 */
0b86a832
CM
5433int btrfs_previous_item(struct btrfs_root *root,
5434 struct btrfs_path *path, u64 min_objectid,
5435 int type)
5436{
5437 struct btrfs_key found_key;
5438 struct extent_buffer *leaf;
e02119d5 5439 u32 nritems;
0b86a832
CM
5440 int ret;
5441
d397712b 5442 while (1) {
0b86a832
CM
5443 if (path->slots[0] == 0) {
5444 ret = btrfs_prev_leaf(root, path);
5445 if (ret != 0)
5446 return ret;
5447 } else {
5448 path->slots[0]--;
5449 }
5450 leaf = path->nodes[0];
e02119d5
CM
5451 nritems = btrfs_header_nritems(leaf);
5452 if (nritems == 0)
5453 return 1;
5454 if (path->slots[0] == nritems)
5455 path->slots[0]--;
5456
0b86a832 5457 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
e02119d5
CM
5458 if (found_key.objectid < min_objectid)
5459 break;
0a4eefbb
YZ
5460 if (found_key.type == type)
5461 return 0;
e02119d5
CM
5462 if (found_key.objectid == min_objectid &&
5463 found_key.type < type)
5464 break;
0b86a832
CM
5465 }
5466 return 1;
5467}
ade2e0b3
WS
5468
5469/*
5470 * search in extent tree to find a previous Metadata/Data extent item with
5471 * min objecitd.
5472 *
5473 * returns 0 if something is found, 1 if nothing was found and < 0 on error
5474 */
5475int btrfs_previous_extent_item(struct btrfs_root *root,
5476 struct btrfs_path *path, u64 min_objectid)
5477{
5478 struct btrfs_key found_key;
5479 struct extent_buffer *leaf;
5480 u32 nritems;
5481 int ret;
5482
5483 while (1) {
5484 if (path->slots[0] == 0) {
ade2e0b3
WS
5485 ret = btrfs_prev_leaf(root, path);
5486 if (ret != 0)
5487 return ret;
5488 } else {
5489 path->slots[0]--;
5490 }
5491 leaf = path->nodes[0];
5492 nritems = btrfs_header_nritems(leaf);
5493 if (nritems == 0)
5494 return 1;
5495 if (path->slots[0] == nritems)
5496 path->slots[0]--;
5497
5498 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5499 if (found_key.objectid < min_objectid)
5500 break;
5501 if (found_key.type == BTRFS_EXTENT_ITEM_KEY ||
5502 found_key.type == BTRFS_METADATA_ITEM_KEY)
5503 return 0;
5504 if (found_key.objectid == min_objectid &&
5505 found_key.type < BTRFS_EXTENT_ITEM_KEY)
5506 break;
5507 }
5508 return 1;
5509}