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