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