btrfs: drop fs_info parameter from tree_mod_log_insert_move
[sfrench/cifs-2.6.git] / fs / btrfs / ctree.c
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 <linux/mm.h>
23 #include "ctree.h"
24 #include "disk-io.h"
25 #include "transaction.h"
26 #include "print-tree.h"
27 #include "locking.h"
28
29 static int split_node(struct btrfs_trans_handle *trans, struct btrfs_root
30                       *root, struct btrfs_path *path, int level);
31 static int split_leaf(struct btrfs_trans_handle *trans, struct btrfs_root *root,
32                       const struct btrfs_key *ins_key, struct btrfs_path *path,
33                       int data_size, int extend);
34 static int push_node_left(struct btrfs_trans_handle *trans,
35                           struct btrfs_fs_info *fs_info,
36                           struct extent_buffer *dst,
37                           struct extent_buffer *src, int empty);
38 static int balance_node_right(struct btrfs_trans_handle *trans,
39                               struct btrfs_fs_info *fs_info,
40                               struct extent_buffer *dst_buf,
41                               struct extent_buffer *src_buf);
42 static void del_ptr(struct btrfs_root *root, struct btrfs_path *path,
43                     int level, int slot);
44 static int tree_mod_log_free_eb(struct btrfs_fs_info *fs_info,
45                                  struct extent_buffer *eb);
46
47 struct btrfs_path *btrfs_alloc_path(void)
48 {
49         return kmem_cache_zalloc(btrfs_path_cachep, GFP_NOFS);
50 }
51
52 /*
53  * set all locked nodes in the path to blocking locks.  This should
54  * be done before scheduling
55  */
56 noinline 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  */
78 noinline void btrfs_clear_path_blocking(struct btrfs_path *p,
79                                         struct extent_buffer *held, int held_rw)
80 {
81         int i;
82
83         if (held) {
84                 btrfs_set_lock_blocking_rw(held, held_rw);
85                 if (held_rw == BTRFS_WRITE_LOCK)
86                         held_rw = BTRFS_WRITE_LOCK_BLOCKING;
87                 else if (held_rw == BTRFS_READ_LOCK)
88                         held_rw = BTRFS_READ_LOCK_BLOCKING;
89         }
90         btrfs_set_path_blocking(p);
91
92         for (i = BTRFS_MAX_LEVEL - 1; i >= 0; i--) {
93                 if (p->nodes[i] && p->locks[i]) {
94                         btrfs_clear_lock_blocking_rw(p->nodes[i], p->locks[i]);
95                         if (p->locks[i] == BTRFS_WRITE_LOCK_BLOCKING)
96                                 p->locks[i] = BTRFS_WRITE_LOCK;
97                         else if (p->locks[i] == BTRFS_READ_LOCK_BLOCKING)
98                                 p->locks[i] = BTRFS_READ_LOCK;
99                 }
100         }
101
102         if (held)
103                 btrfs_clear_lock_blocking_rw(held, held_rw);
104 }
105
106 /* this also releases the path */
107 void btrfs_free_path(struct btrfs_path *p)
108 {
109         if (!p)
110                 return;
111         btrfs_release_path(p);
112         kmem_cache_free(btrfs_path_cachep, p);
113 }
114
115 /*
116  * path release drops references on the extent buffers in the path
117  * and it drops any locks held by this path
118  *
119  * It is safe to call this on paths that no locks or extent buffers held.
120  */
121 noinline void btrfs_release_path(struct btrfs_path *p)
122 {
123         int i;
124
125         for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
126                 p->slots[i] = 0;
127                 if (!p->nodes[i])
128                         continue;
129                 if (p->locks[i]) {
130                         btrfs_tree_unlock_rw(p->nodes[i], p->locks[i]);
131                         p->locks[i] = 0;
132                 }
133                 free_extent_buffer(p->nodes[i]);
134                 p->nodes[i] = NULL;
135         }
136 }
137
138 /*
139  * safely gets a reference on the root node of a tree.  A lock
140  * is not taken, so a concurrent writer may put a different node
141  * at the root of the tree.  See btrfs_lock_root_node for the
142  * looping required.
143  *
144  * The extent buffer returned by this has a reference taken, so
145  * it won't disappear.  It may stop being the root of the tree
146  * at any time because there are no locks held.
147  */
148 struct extent_buffer *btrfs_root_node(struct btrfs_root *root)
149 {
150         struct extent_buffer *eb;
151
152         while (1) {
153                 rcu_read_lock();
154                 eb = rcu_dereference(root->node);
155
156                 /*
157                  * RCU really hurts here, we could free up the root node because
158                  * it was COWed but we may not get the new root node yet so do
159                  * the inc_not_zero dance and if it doesn't work then
160                  * synchronize_rcu and try again.
161                  */
162                 if (atomic_inc_not_zero(&eb->refs)) {
163                         rcu_read_unlock();
164                         break;
165                 }
166                 rcu_read_unlock();
167                 synchronize_rcu();
168         }
169         return eb;
170 }
171
172 /* loop around taking references on and locking the root node of the
173  * tree until you end up with a lock on the root.  A locked buffer
174  * is returned, with a reference held.
175  */
176 struct extent_buffer *btrfs_lock_root_node(struct btrfs_root *root)
177 {
178         struct extent_buffer *eb;
179
180         while (1) {
181                 eb = btrfs_root_node(root);
182                 btrfs_tree_lock(eb);
183                 if (eb == root->node)
184                         break;
185                 btrfs_tree_unlock(eb);
186                 free_extent_buffer(eb);
187         }
188         return eb;
189 }
190
191 /* loop around taking references on and locking the root node of the
192  * tree until you end up with a lock on the root.  A locked buffer
193  * is returned, with a reference held.
194  */
195 struct extent_buffer *btrfs_read_lock_root_node(struct btrfs_root *root)
196 {
197         struct extent_buffer *eb;
198
199         while (1) {
200                 eb = btrfs_root_node(root);
201                 btrfs_tree_read_lock(eb);
202                 if (eb == root->node)
203                         break;
204                 btrfs_tree_read_unlock(eb);
205                 free_extent_buffer(eb);
206         }
207         return eb;
208 }
209
210 /* cowonly root (everything not a reference counted cow subvolume), just get
211  * put onto a simple dirty list.  transaction.c walks this to make sure they
212  * get properly updated on disk.
213  */
214 static void add_root_to_dirty_list(struct btrfs_root *root)
215 {
216         struct btrfs_fs_info *fs_info = root->fs_info;
217
218         if (test_bit(BTRFS_ROOT_DIRTY, &root->state) ||
219             !test_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state))
220                 return;
221
222         spin_lock(&fs_info->trans_lock);
223         if (!test_and_set_bit(BTRFS_ROOT_DIRTY, &root->state)) {
224                 /* Want the extent tree to be the last on the list */
225                 if (root->objectid == BTRFS_EXTENT_TREE_OBJECTID)
226                         list_move_tail(&root->dirty_list,
227                                        &fs_info->dirty_cowonly_roots);
228                 else
229                         list_move(&root->dirty_list,
230                                   &fs_info->dirty_cowonly_roots);
231         }
232         spin_unlock(&fs_info->trans_lock);
233 }
234
235 /*
236  * used by snapshot creation to make a copy of a root for a tree with
237  * a given objectid.  The buffer with the new root node is returned in
238  * cow_ret, and this func returns zero on success or a negative error code.
239  */
240 int btrfs_copy_root(struct btrfs_trans_handle *trans,
241                       struct btrfs_root *root,
242                       struct extent_buffer *buf,
243                       struct extent_buffer **cow_ret, u64 new_root_objectid)
244 {
245         struct btrfs_fs_info *fs_info = root->fs_info;
246         struct extent_buffer *cow;
247         int ret = 0;
248         int level;
249         struct btrfs_disk_key disk_key;
250
251         WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
252                 trans->transid != fs_info->running_transaction->transid);
253         WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
254                 trans->transid != root->last_trans);
255
256         level = btrfs_header_level(buf);
257         if (level == 0)
258                 btrfs_item_key(buf, &disk_key, 0);
259         else
260                 btrfs_node_key(buf, &disk_key, 0);
261
262         cow = btrfs_alloc_tree_block(trans, root, 0, new_root_objectid,
263                         &disk_key, level, buf->start, 0);
264         if (IS_ERR(cow))
265                 return PTR_ERR(cow);
266
267         copy_extent_buffer_full(cow, buf);
268         btrfs_set_header_bytenr(cow, cow->start);
269         btrfs_set_header_generation(cow, trans->transid);
270         btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
271         btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
272                                      BTRFS_HEADER_FLAG_RELOC);
273         if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
274                 btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
275         else
276                 btrfs_set_header_owner(cow, new_root_objectid);
277
278         write_extent_buffer_fsid(cow, fs_info->fsid);
279
280         WARN_ON(btrfs_header_generation(buf) > trans->transid);
281         if (new_root_objectid == BTRFS_TREE_RELOC_OBJECTID)
282                 ret = btrfs_inc_ref(trans, root, cow, 1);
283         else
284                 ret = btrfs_inc_ref(trans, root, cow, 0);
285
286         if (ret)
287                 return ret;
288
289         btrfs_mark_buffer_dirty(cow);
290         *cow_ret = cow;
291         return 0;
292 }
293
294 enum mod_log_op {
295         MOD_LOG_KEY_REPLACE,
296         MOD_LOG_KEY_ADD,
297         MOD_LOG_KEY_REMOVE,
298         MOD_LOG_KEY_REMOVE_WHILE_FREEING,
299         MOD_LOG_KEY_REMOVE_WHILE_MOVING,
300         MOD_LOG_MOVE_KEYS,
301         MOD_LOG_ROOT_REPLACE,
302 };
303
304 struct tree_mod_move {
305         int dst_slot;
306         int nr_items;
307 };
308
309 struct tree_mod_root {
310         u64 logical;
311         u8 level;
312 };
313
314 struct tree_mod_elem {
315         struct rb_node node;
316         u64 logical;
317         u64 seq;
318         enum mod_log_op op;
319
320         /* this is used for MOD_LOG_KEY_* and MOD_LOG_MOVE_KEYS operations */
321         int slot;
322
323         /* this is used for MOD_LOG_KEY* and MOD_LOG_ROOT_REPLACE */
324         u64 generation;
325
326         /* those are used for op == MOD_LOG_KEY_{REPLACE,REMOVE} */
327         struct btrfs_disk_key key;
328         u64 blockptr;
329
330         /* this is used for op == MOD_LOG_MOVE_KEYS */
331         struct tree_mod_move move;
332
333         /* this is used for op == MOD_LOG_ROOT_REPLACE */
334         struct tree_mod_root old_root;
335 };
336
337 static inline void tree_mod_log_read_lock(struct btrfs_fs_info *fs_info)
338 {
339         read_lock(&fs_info->tree_mod_log_lock);
340 }
341
342 static inline void tree_mod_log_read_unlock(struct btrfs_fs_info *fs_info)
343 {
344         read_unlock(&fs_info->tree_mod_log_lock);
345 }
346
347 static inline void tree_mod_log_write_lock(struct btrfs_fs_info *fs_info)
348 {
349         write_lock(&fs_info->tree_mod_log_lock);
350 }
351
352 static inline void tree_mod_log_write_unlock(struct btrfs_fs_info *fs_info)
353 {
354         write_unlock(&fs_info->tree_mod_log_lock);
355 }
356
357 /*
358  * Pull a new tree mod seq number for our operation.
359  */
360 static inline u64 btrfs_inc_tree_mod_seq(struct btrfs_fs_info *fs_info)
361 {
362         return atomic64_inc_return(&fs_info->tree_mod_seq);
363 }
364
365 /*
366  * This adds a new blocker to the tree mod log's blocker list if the @elem
367  * passed does not already have a sequence number set. So when a caller expects
368  * to record tree modifications, it should ensure to set elem->seq to zero
369  * before calling btrfs_get_tree_mod_seq.
370  * Returns a fresh, unused tree log modification sequence number, even if no new
371  * blocker was added.
372  */
373 u64 btrfs_get_tree_mod_seq(struct btrfs_fs_info *fs_info,
374                            struct seq_list *elem)
375 {
376         tree_mod_log_write_lock(fs_info);
377         spin_lock(&fs_info->tree_mod_seq_lock);
378         if (!elem->seq) {
379                 elem->seq = btrfs_inc_tree_mod_seq(fs_info);
380                 list_add_tail(&elem->list, &fs_info->tree_mod_seq_list);
381         }
382         spin_unlock(&fs_info->tree_mod_seq_lock);
383         tree_mod_log_write_unlock(fs_info);
384
385         return elem->seq;
386 }
387
388 void btrfs_put_tree_mod_seq(struct btrfs_fs_info *fs_info,
389                             struct seq_list *elem)
390 {
391         struct rb_root *tm_root;
392         struct rb_node *node;
393         struct rb_node *next;
394         struct seq_list *cur_elem;
395         struct tree_mod_elem *tm;
396         u64 min_seq = (u64)-1;
397         u64 seq_putting = elem->seq;
398
399         if (!seq_putting)
400                 return;
401
402         spin_lock(&fs_info->tree_mod_seq_lock);
403         list_del(&elem->list);
404         elem->seq = 0;
405
406         list_for_each_entry(cur_elem, &fs_info->tree_mod_seq_list, list) {
407                 if (cur_elem->seq < min_seq) {
408                         if (seq_putting > cur_elem->seq) {
409                                 /*
410                                  * blocker with lower sequence number exists, we
411                                  * cannot remove anything from the log
412                                  */
413                                 spin_unlock(&fs_info->tree_mod_seq_lock);
414                                 return;
415                         }
416                         min_seq = cur_elem->seq;
417                 }
418         }
419         spin_unlock(&fs_info->tree_mod_seq_lock);
420
421         /*
422          * anything that's lower than the lowest existing (read: blocked)
423          * sequence number can be removed from the tree.
424          */
425         tree_mod_log_write_lock(fs_info);
426         tm_root = &fs_info->tree_mod_log;
427         for (node = rb_first(tm_root); node; node = next) {
428                 next = rb_next(node);
429                 tm = rb_entry(node, struct tree_mod_elem, node);
430                 if (tm->seq > min_seq)
431                         continue;
432                 rb_erase(node, tm_root);
433                 kfree(tm);
434         }
435         tree_mod_log_write_unlock(fs_info);
436 }
437
438 /*
439  * key order of the log:
440  *       node/leaf start address -> sequence
441  *
442  * The 'start address' is the logical address of the *new* root node
443  * for root replace operations, or the logical address of the affected
444  * block for all other operations.
445  *
446  * Note: must be called with write lock (tree_mod_log_write_lock).
447  */
448 static noinline int
449 __tree_mod_log_insert(struct btrfs_fs_info *fs_info, struct tree_mod_elem *tm)
450 {
451         struct rb_root *tm_root;
452         struct rb_node **new;
453         struct rb_node *parent = NULL;
454         struct tree_mod_elem *cur;
455
456         tm->seq = btrfs_inc_tree_mod_seq(fs_info);
457
458         tm_root = &fs_info->tree_mod_log;
459         new = &tm_root->rb_node;
460         while (*new) {
461                 cur = rb_entry(*new, struct tree_mod_elem, node);
462                 parent = *new;
463                 if (cur->logical < tm->logical)
464                         new = &((*new)->rb_left);
465                 else if (cur->logical > tm->logical)
466                         new = &((*new)->rb_right);
467                 else if (cur->seq < tm->seq)
468                         new = &((*new)->rb_left);
469                 else if (cur->seq > tm->seq)
470                         new = &((*new)->rb_right);
471                 else
472                         return -EEXIST;
473         }
474
475         rb_link_node(&tm->node, parent, new);
476         rb_insert_color(&tm->node, tm_root);
477         return 0;
478 }
479
480 /*
481  * Determines if logging can be omitted. Returns 1 if it can. Otherwise, it
482  * returns zero with the tree_mod_log_lock acquired. The caller must hold
483  * this until all tree mod log insertions are recorded in the rb tree and then
484  * call tree_mod_log_write_unlock() to release.
485  */
486 static inline int tree_mod_dont_log(struct btrfs_fs_info *fs_info,
487                                     struct extent_buffer *eb) {
488         smp_mb();
489         if (list_empty(&(fs_info)->tree_mod_seq_list))
490                 return 1;
491         if (eb && btrfs_header_level(eb) == 0)
492                 return 1;
493
494         tree_mod_log_write_lock(fs_info);
495         if (list_empty(&(fs_info)->tree_mod_seq_list)) {
496                 tree_mod_log_write_unlock(fs_info);
497                 return 1;
498         }
499
500         return 0;
501 }
502
503 /* Similar to tree_mod_dont_log, but doesn't acquire any locks. */
504 static inline int tree_mod_need_log(const struct btrfs_fs_info *fs_info,
505                                     struct extent_buffer *eb)
506 {
507         smp_mb();
508         if (list_empty(&(fs_info)->tree_mod_seq_list))
509                 return 0;
510         if (eb && btrfs_header_level(eb) == 0)
511                 return 0;
512
513         return 1;
514 }
515
516 static struct tree_mod_elem *
517 alloc_tree_mod_elem(struct extent_buffer *eb, int slot,
518                     enum mod_log_op op, gfp_t flags)
519 {
520         struct tree_mod_elem *tm;
521
522         tm = kzalloc(sizeof(*tm), flags);
523         if (!tm)
524                 return NULL;
525
526         tm->logical = eb->start;
527         if (op != MOD_LOG_KEY_ADD) {
528                 btrfs_node_key(eb, &tm->key, slot);
529                 tm->blockptr = btrfs_node_blockptr(eb, slot);
530         }
531         tm->op = op;
532         tm->slot = slot;
533         tm->generation = btrfs_node_ptr_generation(eb, slot);
534         RB_CLEAR_NODE(&tm->node);
535
536         return tm;
537 }
538
539 static noinline int
540 tree_mod_log_insert_key(struct btrfs_fs_info *fs_info,
541                         struct extent_buffer *eb, int slot,
542                         enum mod_log_op op, gfp_t flags)
543 {
544         struct tree_mod_elem *tm;
545         int ret;
546
547         if (!tree_mod_need_log(fs_info, eb))
548                 return 0;
549
550         tm = alloc_tree_mod_elem(eb, slot, op, flags);
551         if (!tm)
552                 return -ENOMEM;
553
554         if (tree_mod_dont_log(fs_info, eb)) {
555                 kfree(tm);
556                 return 0;
557         }
558
559         ret = __tree_mod_log_insert(fs_info, tm);
560         tree_mod_log_write_unlock(fs_info);
561         if (ret)
562                 kfree(tm);
563
564         return ret;
565 }
566
567 static noinline int tree_mod_log_insert_move(struct extent_buffer *eb,
568                 int dst_slot, int src_slot, int nr_items)
569 {
570         struct tree_mod_elem *tm = NULL;
571         struct tree_mod_elem **tm_list = NULL;
572         int ret = 0;
573         int i;
574         int locked = 0;
575
576         if (!tree_mod_need_log(eb->fs_info, eb))
577                 return 0;
578
579         tm_list = kcalloc(nr_items, sizeof(struct tree_mod_elem *), GFP_NOFS);
580         if (!tm_list)
581                 return -ENOMEM;
582
583         tm = kzalloc(sizeof(*tm), GFP_NOFS);
584         if (!tm) {
585                 ret = -ENOMEM;
586                 goto free_tms;
587         }
588
589         tm->logical = eb->start;
590         tm->slot = src_slot;
591         tm->move.dst_slot = dst_slot;
592         tm->move.nr_items = nr_items;
593         tm->op = MOD_LOG_MOVE_KEYS;
594
595         for (i = 0; i + dst_slot < src_slot && i < nr_items; i++) {
596                 tm_list[i] = alloc_tree_mod_elem(eb, i + dst_slot,
597                     MOD_LOG_KEY_REMOVE_WHILE_MOVING, GFP_NOFS);
598                 if (!tm_list[i]) {
599                         ret = -ENOMEM;
600                         goto free_tms;
601                 }
602         }
603
604         if (tree_mod_dont_log(eb->fs_info, eb))
605                 goto free_tms;
606         locked = 1;
607
608         /*
609          * When we override something during the move, we log these removals.
610          * This can only happen when we move towards the beginning of the
611          * buffer, i.e. dst_slot < src_slot.
612          */
613         for (i = 0; i + dst_slot < src_slot && i < nr_items; i++) {
614                 ret = __tree_mod_log_insert(eb->fs_info, tm_list[i]);
615                 if (ret)
616                         goto free_tms;
617         }
618
619         ret = __tree_mod_log_insert(eb->fs_info, tm);
620         if (ret)
621                 goto free_tms;
622         tree_mod_log_write_unlock(eb->fs_info);
623         kfree(tm_list);
624
625         return 0;
626 free_tms:
627         for (i = 0; i < nr_items; i++) {
628                 if (tm_list[i] && !RB_EMPTY_NODE(&tm_list[i]->node))
629                         rb_erase(&tm_list[i]->node, &eb->fs_info->tree_mod_log);
630                 kfree(tm_list[i]);
631         }
632         if (locked)
633                 tree_mod_log_write_unlock(eb->fs_info);
634         kfree(tm_list);
635         kfree(tm);
636
637         return ret;
638 }
639
640 static inline int
641 __tree_mod_log_free_eb(struct btrfs_fs_info *fs_info,
642                        struct tree_mod_elem **tm_list,
643                        int nritems)
644 {
645         int i, j;
646         int ret;
647
648         for (i = nritems - 1; i >= 0; i--) {
649                 ret = __tree_mod_log_insert(fs_info, tm_list[i]);
650                 if (ret) {
651                         for (j = nritems - 1; j > i; j--)
652                                 rb_erase(&tm_list[j]->node,
653                                          &fs_info->tree_mod_log);
654                         return ret;
655                 }
656         }
657
658         return 0;
659 }
660
661 static noinline int
662 tree_mod_log_insert_root(struct btrfs_fs_info *fs_info,
663                          struct extent_buffer *old_root,
664                          struct extent_buffer *new_root,
665                          int log_removal)
666 {
667         struct tree_mod_elem *tm = NULL;
668         struct tree_mod_elem **tm_list = NULL;
669         int nritems = 0;
670         int ret = 0;
671         int i;
672
673         if (!tree_mod_need_log(fs_info, NULL))
674                 return 0;
675
676         if (log_removal && btrfs_header_level(old_root) > 0) {
677                 nritems = btrfs_header_nritems(old_root);
678                 tm_list = kcalloc(nritems, sizeof(struct tree_mod_elem *),
679                                   GFP_NOFS);
680                 if (!tm_list) {
681                         ret = -ENOMEM;
682                         goto free_tms;
683                 }
684                 for (i = 0; i < nritems; i++) {
685                         tm_list[i] = alloc_tree_mod_elem(old_root, i,
686                             MOD_LOG_KEY_REMOVE_WHILE_FREEING, GFP_NOFS);
687                         if (!tm_list[i]) {
688                                 ret = -ENOMEM;
689                                 goto free_tms;
690                         }
691                 }
692         }
693
694         tm = kzalloc(sizeof(*tm), GFP_NOFS);
695         if (!tm) {
696                 ret = -ENOMEM;
697                 goto free_tms;
698         }
699
700         tm->logical = new_root->start;
701         tm->old_root.logical = old_root->start;
702         tm->old_root.level = btrfs_header_level(old_root);
703         tm->generation = btrfs_header_generation(old_root);
704         tm->op = MOD_LOG_ROOT_REPLACE;
705
706         if (tree_mod_dont_log(fs_info, NULL))
707                 goto free_tms;
708
709         if (tm_list)
710                 ret = __tree_mod_log_free_eb(fs_info, tm_list, nritems);
711         if (!ret)
712                 ret = __tree_mod_log_insert(fs_info, tm);
713
714         tree_mod_log_write_unlock(fs_info);
715         if (ret)
716                 goto free_tms;
717         kfree(tm_list);
718
719         return ret;
720
721 free_tms:
722         if (tm_list) {
723                 for (i = 0; i < nritems; i++)
724                         kfree(tm_list[i]);
725                 kfree(tm_list);
726         }
727         kfree(tm);
728
729         return ret;
730 }
731
732 static struct tree_mod_elem *
733 __tree_mod_log_search(struct btrfs_fs_info *fs_info, u64 start, u64 min_seq,
734                       int smallest)
735 {
736         struct rb_root *tm_root;
737         struct rb_node *node;
738         struct tree_mod_elem *cur = NULL;
739         struct tree_mod_elem *found = NULL;
740
741         tree_mod_log_read_lock(fs_info);
742         tm_root = &fs_info->tree_mod_log;
743         node = tm_root->rb_node;
744         while (node) {
745                 cur = rb_entry(node, struct tree_mod_elem, node);
746                 if (cur->logical < start) {
747                         node = node->rb_left;
748                 } else if (cur->logical > start) {
749                         node = node->rb_right;
750                 } else if (cur->seq < min_seq) {
751                         node = node->rb_left;
752                 } else if (!smallest) {
753                         /* we want the node with the highest seq */
754                         if (found)
755                                 BUG_ON(found->seq > cur->seq);
756                         found = cur;
757                         node = node->rb_left;
758                 } else if (cur->seq > min_seq) {
759                         /* we want the node with the smallest seq */
760                         if (found)
761                                 BUG_ON(found->seq < cur->seq);
762                         found = cur;
763                         node = node->rb_right;
764                 } else {
765                         found = cur;
766                         break;
767                 }
768         }
769         tree_mod_log_read_unlock(fs_info);
770
771         return found;
772 }
773
774 /*
775  * this returns the element from the log with the smallest time sequence
776  * value that's in the log (the oldest log item). any element with a time
777  * sequence lower than min_seq will be ignored.
778  */
779 static struct tree_mod_elem *
780 tree_mod_log_search_oldest(struct btrfs_fs_info *fs_info, u64 start,
781                            u64 min_seq)
782 {
783         return __tree_mod_log_search(fs_info, start, min_seq, 1);
784 }
785
786 /*
787  * this returns the element from the log with the largest time sequence
788  * value that's in the log (the most recent log item). any element with
789  * a time sequence lower than min_seq will be ignored.
790  */
791 static struct tree_mod_elem *
792 tree_mod_log_search(struct btrfs_fs_info *fs_info, u64 start, u64 min_seq)
793 {
794         return __tree_mod_log_search(fs_info, start, min_seq, 0);
795 }
796
797 static noinline int
798 tree_mod_log_eb_copy(struct btrfs_fs_info *fs_info, struct extent_buffer *dst,
799                      struct extent_buffer *src, unsigned long dst_offset,
800                      unsigned long src_offset, int nr_items)
801 {
802         int ret = 0;
803         struct tree_mod_elem **tm_list = NULL;
804         struct tree_mod_elem **tm_list_add, **tm_list_rem;
805         int i;
806         int locked = 0;
807
808         if (!tree_mod_need_log(fs_info, NULL))
809                 return 0;
810
811         if (btrfs_header_level(dst) == 0 && btrfs_header_level(src) == 0)
812                 return 0;
813
814         tm_list = kcalloc(nr_items * 2, sizeof(struct tree_mod_elem *),
815                           GFP_NOFS);
816         if (!tm_list)
817                 return -ENOMEM;
818
819         tm_list_add = tm_list;
820         tm_list_rem = tm_list + nr_items;
821         for (i = 0; i < nr_items; i++) {
822                 tm_list_rem[i] = alloc_tree_mod_elem(src, i + src_offset,
823                     MOD_LOG_KEY_REMOVE, GFP_NOFS);
824                 if (!tm_list_rem[i]) {
825                         ret = -ENOMEM;
826                         goto free_tms;
827                 }
828
829                 tm_list_add[i] = alloc_tree_mod_elem(dst, i + dst_offset,
830                     MOD_LOG_KEY_ADD, GFP_NOFS);
831                 if (!tm_list_add[i]) {
832                         ret = -ENOMEM;
833                         goto free_tms;
834                 }
835         }
836
837         if (tree_mod_dont_log(fs_info, NULL))
838                 goto free_tms;
839         locked = 1;
840
841         for (i = 0; i < nr_items; i++) {
842                 ret = __tree_mod_log_insert(fs_info, tm_list_rem[i]);
843                 if (ret)
844                         goto free_tms;
845                 ret = __tree_mod_log_insert(fs_info, tm_list_add[i]);
846                 if (ret)
847                         goto free_tms;
848         }
849
850         tree_mod_log_write_unlock(fs_info);
851         kfree(tm_list);
852
853         return 0;
854
855 free_tms:
856         for (i = 0; i < nr_items * 2; i++) {
857                 if (tm_list[i] && !RB_EMPTY_NODE(&tm_list[i]->node))
858                         rb_erase(&tm_list[i]->node, &fs_info->tree_mod_log);
859                 kfree(tm_list[i]);
860         }
861         if (locked)
862                 tree_mod_log_write_unlock(fs_info);
863         kfree(tm_list);
864
865         return ret;
866 }
867
868 static inline void
869 tree_mod_log_eb_move(struct btrfs_fs_info *fs_info, struct extent_buffer *dst,
870                      int dst_offset, int src_offset, int nr_items)
871 {
872         int ret;
873         ret = tree_mod_log_insert_move(dst, dst_offset, src_offset, nr_items);
874         BUG_ON(ret < 0);
875 }
876
877 static noinline void tree_mod_log_set_node_key(struct extent_buffer *eb,
878                 int slot, int atomic)
879 {
880         int ret;
881
882         ret = tree_mod_log_insert_key(eb->fs_info, eb, slot,
883                                         MOD_LOG_KEY_REPLACE,
884                                         atomic ? GFP_ATOMIC : GFP_NOFS);
885         BUG_ON(ret < 0);
886 }
887
888 static noinline int
889 tree_mod_log_free_eb(struct btrfs_fs_info *fs_info, struct extent_buffer *eb)
890 {
891         struct tree_mod_elem **tm_list = NULL;
892         int nritems = 0;
893         int i;
894         int ret = 0;
895
896         if (btrfs_header_level(eb) == 0)
897                 return 0;
898
899         if (!tree_mod_need_log(fs_info, NULL))
900                 return 0;
901
902         nritems = btrfs_header_nritems(eb);
903         tm_list = kcalloc(nritems, sizeof(struct tree_mod_elem *), GFP_NOFS);
904         if (!tm_list)
905                 return -ENOMEM;
906
907         for (i = 0; i < nritems; i++) {
908                 tm_list[i] = alloc_tree_mod_elem(eb, i,
909                     MOD_LOG_KEY_REMOVE_WHILE_FREEING, GFP_NOFS);
910                 if (!tm_list[i]) {
911                         ret = -ENOMEM;
912                         goto free_tms;
913                 }
914         }
915
916         if (tree_mod_dont_log(fs_info, eb))
917                 goto free_tms;
918
919         ret = __tree_mod_log_free_eb(fs_info, tm_list, nritems);
920         tree_mod_log_write_unlock(fs_info);
921         if (ret)
922                 goto free_tms;
923         kfree(tm_list);
924
925         return 0;
926
927 free_tms:
928         for (i = 0; i < nritems; i++)
929                 kfree(tm_list[i]);
930         kfree(tm_list);
931
932         return ret;
933 }
934
935 static noinline void
936 tree_mod_log_set_root_pointer(struct btrfs_root *root,
937                               struct extent_buffer *new_root_node,
938                               int log_removal)
939 {
940         int ret;
941         ret = tree_mod_log_insert_root(root->fs_info, root->node,
942                                        new_root_node, log_removal);
943         BUG_ON(ret < 0);
944 }
945
946 /*
947  * check if the tree block can be shared by multiple trees
948  */
949 int btrfs_block_can_be_shared(struct btrfs_root *root,
950                               struct extent_buffer *buf)
951 {
952         /*
953          * Tree blocks not in reference counted trees and tree roots
954          * are never shared. If a block was allocated after the last
955          * snapshot and the block was not allocated by tree relocation,
956          * we know the block is not shared.
957          */
958         if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
959             buf != root->node && buf != root->commit_root &&
960             (btrfs_header_generation(buf) <=
961              btrfs_root_last_snapshot(&root->root_item) ||
962              btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)))
963                 return 1;
964 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
965         if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
966             btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
967                 return 1;
968 #endif
969         return 0;
970 }
971
972 static noinline int update_ref_for_cow(struct btrfs_trans_handle *trans,
973                                        struct btrfs_root *root,
974                                        struct extent_buffer *buf,
975                                        struct extent_buffer *cow,
976                                        int *last_ref)
977 {
978         struct btrfs_fs_info *fs_info = root->fs_info;
979         u64 refs;
980         u64 owner;
981         u64 flags;
982         u64 new_flags = 0;
983         int ret;
984
985         /*
986          * Backrefs update rules:
987          *
988          * Always use full backrefs for extent pointers in tree block
989          * allocated by tree relocation.
990          *
991          * If a shared tree block is no longer referenced by its owner
992          * tree (btrfs_header_owner(buf) == root->root_key.objectid),
993          * use full backrefs for extent pointers in tree block.
994          *
995          * If a tree block is been relocating
996          * (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID),
997          * use full backrefs for extent pointers in tree block.
998          * The reason for this is some operations (such as drop tree)
999          * are only allowed for blocks use full backrefs.
1000          */
1001
1002         if (btrfs_block_can_be_shared(root, buf)) {
1003                 ret = btrfs_lookup_extent_info(trans, fs_info, buf->start,
1004                                                btrfs_header_level(buf), 1,
1005                                                &refs, &flags);
1006                 if (ret)
1007                         return ret;
1008                 if (refs == 0) {
1009                         ret = -EROFS;
1010                         btrfs_handle_fs_error(fs_info, ret, NULL);
1011                         return ret;
1012                 }
1013         } else {
1014                 refs = 1;
1015                 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
1016                     btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
1017                         flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
1018                 else
1019                         flags = 0;
1020         }
1021
1022         owner = btrfs_header_owner(buf);
1023         BUG_ON(owner == BTRFS_TREE_RELOC_OBJECTID &&
1024                !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
1025
1026         if (refs > 1) {
1027                 if ((owner == root->root_key.objectid ||
1028                      root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) &&
1029                     !(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
1030                         ret = btrfs_inc_ref(trans, root, buf, 1);
1031                         if (ret)
1032                                 return ret;
1033
1034                         if (root->root_key.objectid ==
1035                             BTRFS_TREE_RELOC_OBJECTID) {
1036                                 ret = btrfs_dec_ref(trans, root, buf, 0);
1037                                 if (ret)
1038                                         return ret;
1039                                 ret = btrfs_inc_ref(trans, root, cow, 1);
1040                                 if (ret)
1041                                         return ret;
1042                         }
1043                         new_flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
1044                 } else {
1045
1046                         if (root->root_key.objectid ==
1047                             BTRFS_TREE_RELOC_OBJECTID)
1048                                 ret = btrfs_inc_ref(trans, root, cow, 1);
1049                         else
1050                                 ret = btrfs_inc_ref(trans, root, cow, 0);
1051                         if (ret)
1052                                 return ret;
1053                 }
1054                 if (new_flags != 0) {
1055                         int level = btrfs_header_level(buf);
1056
1057                         ret = btrfs_set_disk_extent_flags(trans, fs_info,
1058                                                           buf->start,
1059                                                           buf->len,
1060                                                           new_flags, level, 0);
1061                         if (ret)
1062                                 return ret;
1063                 }
1064         } else {
1065                 if (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
1066                         if (root->root_key.objectid ==
1067                             BTRFS_TREE_RELOC_OBJECTID)
1068                                 ret = btrfs_inc_ref(trans, root, cow, 1);
1069                         else
1070                                 ret = btrfs_inc_ref(trans, root, cow, 0);
1071                         if (ret)
1072                                 return ret;
1073                         ret = btrfs_dec_ref(trans, root, buf, 1);
1074                         if (ret)
1075                                 return ret;
1076                 }
1077                 clean_tree_block(fs_info, buf);
1078                 *last_ref = 1;
1079         }
1080         return 0;
1081 }
1082
1083 /*
1084  * does the dirty work in cow of a single block.  The parent block (if
1085  * supplied) is updated to point to the new cow copy.  The new buffer is marked
1086  * dirty and returned locked.  If you modify the block it needs to be marked
1087  * dirty again.
1088  *
1089  * search_start -- an allocation hint for the new block
1090  *
1091  * empty_size -- a hint that you plan on doing more cow.  This is the size in
1092  * bytes the allocator should try to find free next to the block it returns.
1093  * This is just a hint and may be ignored by the allocator.
1094  */
1095 static noinline int __btrfs_cow_block(struct btrfs_trans_handle *trans,
1096                              struct btrfs_root *root,
1097                              struct extent_buffer *buf,
1098                              struct extent_buffer *parent, int parent_slot,
1099                              struct extent_buffer **cow_ret,
1100                              u64 search_start, u64 empty_size)
1101 {
1102         struct btrfs_fs_info *fs_info = root->fs_info;
1103         struct btrfs_disk_key disk_key;
1104         struct extent_buffer *cow;
1105         int level, ret;
1106         int last_ref = 0;
1107         int unlock_orig = 0;
1108         u64 parent_start = 0;
1109
1110         if (*cow_ret == buf)
1111                 unlock_orig = 1;
1112
1113         btrfs_assert_tree_locked(buf);
1114
1115         WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
1116                 trans->transid != fs_info->running_transaction->transid);
1117         WARN_ON(test_bit(BTRFS_ROOT_REF_COWS, &root->state) &&
1118                 trans->transid != root->last_trans);
1119
1120         level = btrfs_header_level(buf);
1121
1122         if (level == 0)
1123                 btrfs_item_key(buf, &disk_key, 0);
1124         else
1125                 btrfs_node_key(buf, &disk_key, 0);
1126
1127         if ((root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID) && parent)
1128                 parent_start = parent->start;
1129
1130         cow = btrfs_alloc_tree_block(trans, root, parent_start,
1131                         root->root_key.objectid, &disk_key, level,
1132                         search_start, empty_size);
1133         if (IS_ERR(cow))
1134                 return PTR_ERR(cow);
1135
1136         /* cow is set to blocking by btrfs_init_new_buffer */
1137
1138         copy_extent_buffer_full(cow, buf);
1139         btrfs_set_header_bytenr(cow, cow->start);
1140         btrfs_set_header_generation(cow, trans->transid);
1141         btrfs_set_header_backref_rev(cow, BTRFS_MIXED_BACKREF_REV);
1142         btrfs_clear_header_flag(cow, BTRFS_HEADER_FLAG_WRITTEN |
1143                                      BTRFS_HEADER_FLAG_RELOC);
1144         if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)
1145                 btrfs_set_header_flag(cow, BTRFS_HEADER_FLAG_RELOC);
1146         else
1147                 btrfs_set_header_owner(cow, root->root_key.objectid);
1148
1149         write_extent_buffer_fsid(cow, fs_info->fsid);
1150
1151         ret = update_ref_for_cow(trans, root, buf, cow, &last_ref);
1152         if (ret) {
1153                 btrfs_abort_transaction(trans, ret);
1154                 return ret;
1155         }
1156
1157         if (test_bit(BTRFS_ROOT_REF_COWS, &root->state)) {
1158                 ret = btrfs_reloc_cow_block(trans, root, buf, cow);
1159                 if (ret) {
1160                         btrfs_abort_transaction(trans, ret);
1161                         return ret;
1162                 }
1163         }
1164
1165         if (buf == root->node) {
1166                 WARN_ON(parent && parent != buf);
1167                 if (root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID ||
1168                     btrfs_header_backref_rev(buf) < BTRFS_MIXED_BACKREF_REV)
1169                         parent_start = buf->start;
1170
1171                 extent_buffer_get(cow);
1172                 tree_mod_log_set_root_pointer(root, cow, 1);
1173                 rcu_assign_pointer(root->node, cow);
1174
1175                 btrfs_free_tree_block(trans, root, buf, parent_start,
1176                                       last_ref);
1177                 free_extent_buffer(buf);
1178                 add_root_to_dirty_list(root);
1179         } else {
1180                 WARN_ON(trans->transid != btrfs_header_generation(parent));
1181                 tree_mod_log_insert_key(fs_info, parent, parent_slot,
1182                                         MOD_LOG_KEY_REPLACE, GFP_NOFS);
1183                 btrfs_set_node_blockptr(parent, parent_slot,
1184                                         cow->start);
1185                 btrfs_set_node_ptr_generation(parent, parent_slot,
1186                                               trans->transid);
1187                 btrfs_mark_buffer_dirty(parent);
1188                 if (last_ref) {
1189                         ret = tree_mod_log_free_eb(fs_info, buf);
1190                         if (ret) {
1191                                 btrfs_abort_transaction(trans, ret);
1192                                 return ret;
1193                         }
1194                 }
1195                 btrfs_free_tree_block(trans, root, buf, parent_start,
1196                                       last_ref);
1197         }
1198         if (unlock_orig)
1199                 btrfs_tree_unlock(buf);
1200         free_extent_buffer_stale(buf);
1201         btrfs_mark_buffer_dirty(cow);
1202         *cow_ret = cow;
1203         return 0;
1204 }
1205
1206 /*
1207  * returns the logical address of the oldest predecessor of the given root.
1208  * entries older than time_seq are ignored.
1209  */
1210 static struct tree_mod_elem *
1211 __tree_mod_log_oldest_root(struct btrfs_fs_info *fs_info,
1212                            struct extent_buffer *eb_root, u64 time_seq)
1213 {
1214         struct tree_mod_elem *tm;
1215         struct tree_mod_elem *found = NULL;
1216         u64 root_logical = eb_root->start;
1217         int looped = 0;
1218
1219         if (!time_seq)
1220                 return NULL;
1221
1222         /*
1223          * the very last operation that's logged for a root is the
1224          * replacement operation (if it is replaced at all). this has
1225          * the logical address of the *new* root, making it the very
1226          * first operation that's logged for this root.
1227          */
1228         while (1) {
1229                 tm = tree_mod_log_search_oldest(fs_info, root_logical,
1230                                                 time_seq);
1231                 if (!looped && !tm)
1232                         return NULL;
1233                 /*
1234                  * if there are no tree operation for the oldest root, we simply
1235                  * return it. this should only happen if that (old) root is at
1236                  * level 0.
1237                  */
1238                 if (!tm)
1239                         break;
1240
1241                 /*
1242                  * if there's an operation that's not a root replacement, we
1243                  * found the oldest version of our root. normally, we'll find a
1244                  * MOD_LOG_KEY_REMOVE_WHILE_FREEING operation here.
1245                  */
1246                 if (tm->op != MOD_LOG_ROOT_REPLACE)
1247                         break;
1248
1249                 found = tm;
1250                 root_logical = tm->old_root.logical;
1251                 looped = 1;
1252         }
1253
1254         /* if there's no old root to return, return what we found instead */
1255         if (!found)
1256                 found = tm;
1257
1258         return found;
1259 }
1260
1261 /*
1262  * tm is a pointer to the first operation to rewind within eb. then, all
1263  * previous operations will be rewound (until we reach something older than
1264  * time_seq).
1265  */
1266 static void
1267 __tree_mod_log_rewind(struct btrfs_fs_info *fs_info, struct extent_buffer *eb,
1268                       u64 time_seq, struct tree_mod_elem *first_tm)
1269 {
1270         u32 n;
1271         struct rb_node *next;
1272         struct tree_mod_elem *tm = first_tm;
1273         unsigned long o_dst;
1274         unsigned long o_src;
1275         unsigned long p_size = sizeof(struct btrfs_key_ptr);
1276
1277         n = btrfs_header_nritems(eb);
1278         tree_mod_log_read_lock(fs_info);
1279         while (tm && tm->seq >= time_seq) {
1280                 /*
1281                  * all the operations are recorded with the operator used for
1282                  * the modification. as we're going backwards, we do the
1283                  * opposite of each operation here.
1284                  */
1285                 switch (tm->op) {
1286                 case MOD_LOG_KEY_REMOVE_WHILE_FREEING:
1287                         BUG_ON(tm->slot < n);
1288                         /* Fallthrough */
1289                 case MOD_LOG_KEY_REMOVE_WHILE_MOVING:
1290                 case MOD_LOG_KEY_REMOVE:
1291                         btrfs_set_node_key(eb, &tm->key, tm->slot);
1292                         btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
1293                         btrfs_set_node_ptr_generation(eb, tm->slot,
1294                                                       tm->generation);
1295                         n++;
1296                         break;
1297                 case MOD_LOG_KEY_REPLACE:
1298                         BUG_ON(tm->slot >= n);
1299                         btrfs_set_node_key(eb, &tm->key, tm->slot);
1300                         btrfs_set_node_blockptr(eb, tm->slot, tm->blockptr);
1301                         btrfs_set_node_ptr_generation(eb, tm->slot,
1302                                                       tm->generation);
1303                         break;
1304                 case MOD_LOG_KEY_ADD:
1305                         /* if a move operation is needed it's in the log */
1306                         n--;
1307                         break;
1308                 case MOD_LOG_MOVE_KEYS:
1309                         o_dst = btrfs_node_key_ptr_offset(tm->slot);
1310                         o_src = btrfs_node_key_ptr_offset(tm->move.dst_slot);
1311                         memmove_extent_buffer(eb, o_dst, o_src,
1312                                               tm->move.nr_items * p_size);
1313                         break;
1314                 case MOD_LOG_ROOT_REPLACE:
1315                         /*
1316                          * this operation is special. for roots, this must be
1317                          * handled explicitly before rewinding.
1318                          * for non-roots, this operation may exist if the node
1319                          * was a root: root A -> child B; then A gets empty and
1320                          * B is promoted to the new root. in the mod log, we'll
1321                          * have a root-replace operation for B, a tree block
1322                          * that is no root. we simply ignore that operation.
1323                          */
1324                         break;
1325                 }
1326                 next = rb_next(&tm->node);
1327                 if (!next)
1328                         break;
1329                 tm = rb_entry(next, struct tree_mod_elem, node);
1330                 if (tm->logical != first_tm->logical)
1331                         break;
1332         }
1333         tree_mod_log_read_unlock(fs_info);
1334         btrfs_set_header_nritems(eb, n);
1335 }
1336
1337 /*
1338  * Called with eb read locked. If the buffer cannot be rewound, the same buffer
1339  * is returned. If rewind operations happen, a fresh buffer is returned. The
1340  * returned buffer is always read-locked. If the returned buffer is not the
1341  * input buffer, the lock on the input buffer is released and the input buffer
1342  * is freed (its refcount is decremented).
1343  */
1344 static struct extent_buffer *
1345 tree_mod_log_rewind(struct btrfs_fs_info *fs_info, struct btrfs_path *path,
1346                     struct extent_buffer *eb, u64 time_seq)
1347 {
1348         struct extent_buffer *eb_rewin;
1349         struct tree_mod_elem *tm;
1350
1351         if (!time_seq)
1352                 return eb;
1353
1354         if (btrfs_header_level(eb) == 0)
1355                 return eb;
1356
1357         tm = tree_mod_log_search(fs_info, eb->start, time_seq);
1358         if (!tm)
1359                 return eb;
1360
1361         btrfs_set_path_blocking(path);
1362         btrfs_set_lock_blocking_rw(eb, BTRFS_READ_LOCK);
1363
1364         if (tm->op == MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
1365                 BUG_ON(tm->slot != 0);
1366                 eb_rewin = alloc_dummy_extent_buffer(fs_info, eb->start);
1367                 if (!eb_rewin) {
1368                         btrfs_tree_read_unlock_blocking(eb);
1369                         free_extent_buffer(eb);
1370                         return NULL;
1371                 }
1372                 btrfs_set_header_bytenr(eb_rewin, eb->start);
1373                 btrfs_set_header_backref_rev(eb_rewin,
1374                                              btrfs_header_backref_rev(eb));
1375                 btrfs_set_header_owner(eb_rewin, btrfs_header_owner(eb));
1376                 btrfs_set_header_level(eb_rewin, btrfs_header_level(eb));
1377         } else {
1378                 eb_rewin = btrfs_clone_extent_buffer(eb);
1379                 if (!eb_rewin) {
1380                         btrfs_tree_read_unlock_blocking(eb);
1381                         free_extent_buffer(eb);
1382                         return NULL;
1383                 }
1384         }
1385
1386         btrfs_clear_path_blocking(path, NULL, BTRFS_READ_LOCK);
1387         btrfs_tree_read_unlock_blocking(eb);
1388         free_extent_buffer(eb);
1389
1390         extent_buffer_get(eb_rewin);
1391         btrfs_tree_read_lock(eb_rewin);
1392         __tree_mod_log_rewind(fs_info, eb_rewin, time_seq, tm);
1393         WARN_ON(btrfs_header_nritems(eb_rewin) >
1394                 BTRFS_NODEPTRS_PER_BLOCK(fs_info));
1395
1396         return eb_rewin;
1397 }
1398
1399 /*
1400  * get_old_root() rewinds the state of @root's root node to the given @time_seq
1401  * value. If there are no changes, the current root->root_node is returned. If
1402  * anything changed in between, there's a fresh buffer allocated on which the
1403  * rewind operations are done. In any case, the returned buffer is read locked.
1404  * Returns NULL on error (with no locks held).
1405  */
1406 static inline struct extent_buffer *
1407 get_old_root(struct btrfs_root *root, u64 time_seq)
1408 {
1409         struct btrfs_fs_info *fs_info = root->fs_info;
1410         struct tree_mod_elem *tm;
1411         struct extent_buffer *eb = NULL;
1412         struct extent_buffer *eb_root;
1413         struct extent_buffer *old;
1414         struct tree_mod_root *old_root = NULL;
1415         u64 old_generation = 0;
1416         u64 logical;
1417
1418         eb_root = btrfs_read_lock_root_node(root);
1419         tm = __tree_mod_log_oldest_root(fs_info, eb_root, time_seq);
1420         if (!tm)
1421                 return eb_root;
1422
1423         if (tm->op == MOD_LOG_ROOT_REPLACE) {
1424                 old_root = &tm->old_root;
1425                 old_generation = tm->generation;
1426                 logical = old_root->logical;
1427         } else {
1428                 logical = eb_root->start;
1429         }
1430
1431         tm = tree_mod_log_search(fs_info, logical, time_seq);
1432         if (old_root && tm && tm->op != MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
1433                 btrfs_tree_read_unlock(eb_root);
1434                 free_extent_buffer(eb_root);
1435                 old = read_tree_block(fs_info, logical, 0);
1436                 if (WARN_ON(IS_ERR(old) || !extent_buffer_uptodate(old))) {
1437                         if (!IS_ERR(old))
1438                                 free_extent_buffer(old);
1439                         btrfs_warn(fs_info,
1440                                    "failed to read tree block %llu from get_old_root",
1441                                    logical);
1442                 } else {
1443                         eb = btrfs_clone_extent_buffer(old);
1444                         free_extent_buffer(old);
1445                 }
1446         } else if (old_root) {
1447                 btrfs_tree_read_unlock(eb_root);
1448                 free_extent_buffer(eb_root);
1449                 eb = alloc_dummy_extent_buffer(fs_info, logical);
1450         } else {
1451                 btrfs_set_lock_blocking_rw(eb_root, BTRFS_READ_LOCK);
1452                 eb = btrfs_clone_extent_buffer(eb_root);
1453                 btrfs_tree_read_unlock_blocking(eb_root);
1454                 free_extent_buffer(eb_root);
1455         }
1456
1457         if (!eb)
1458                 return NULL;
1459         extent_buffer_get(eb);
1460         btrfs_tree_read_lock(eb);
1461         if (old_root) {
1462                 btrfs_set_header_bytenr(eb, eb->start);
1463                 btrfs_set_header_backref_rev(eb, BTRFS_MIXED_BACKREF_REV);
1464                 btrfs_set_header_owner(eb, btrfs_header_owner(eb_root));
1465                 btrfs_set_header_level(eb, old_root->level);
1466                 btrfs_set_header_generation(eb, old_generation);
1467         }
1468         if (tm)
1469                 __tree_mod_log_rewind(fs_info, eb, time_seq, tm);
1470         else
1471                 WARN_ON(btrfs_header_level(eb) != 0);
1472         WARN_ON(btrfs_header_nritems(eb) > BTRFS_NODEPTRS_PER_BLOCK(fs_info));
1473
1474         return eb;
1475 }
1476
1477 int btrfs_old_root_level(struct btrfs_root *root, u64 time_seq)
1478 {
1479         struct tree_mod_elem *tm;
1480         int level;
1481         struct extent_buffer *eb_root = btrfs_root_node(root);
1482
1483         tm = __tree_mod_log_oldest_root(root->fs_info, eb_root, time_seq);
1484         if (tm && tm->op == MOD_LOG_ROOT_REPLACE) {
1485                 level = tm->old_root.level;
1486         } else {
1487                 level = btrfs_header_level(eb_root);
1488         }
1489         free_extent_buffer(eb_root);
1490
1491         return level;
1492 }
1493
1494 static inline int should_cow_block(struct btrfs_trans_handle *trans,
1495                                    struct btrfs_root *root,
1496                                    struct extent_buffer *buf)
1497 {
1498         if (btrfs_is_testing(root->fs_info))
1499                 return 0;
1500
1501         /* ensure we can see the force_cow */
1502         smp_rmb();
1503
1504         /*
1505          * We do not need to cow a block if
1506          * 1) this block is not created or changed in this transaction;
1507          * 2) this block does not belong to TREE_RELOC tree;
1508          * 3) the root is not forced COW.
1509          *
1510          * What is forced COW:
1511          *    when we create snapshot during committing the transaction,
1512          *    after we've finished coping src root, we must COW the shared
1513          *    block to ensure the metadata consistency.
1514          */
1515         if (btrfs_header_generation(buf) == trans->transid &&
1516             !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN) &&
1517             !(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
1518               btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC)) &&
1519             !test_bit(BTRFS_ROOT_FORCE_COW, &root->state))
1520                 return 0;
1521         return 1;
1522 }
1523
1524 /*
1525  * cows a single block, see __btrfs_cow_block for the real work.
1526  * This version of it has extra checks so that a block isn't COWed more than
1527  * once per transaction, as long as it hasn't been written yet
1528  */
1529 noinline int btrfs_cow_block(struct btrfs_trans_handle *trans,
1530                     struct btrfs_root *root, struct extent_buffer *buf,
1531                     struct extent_buffer *parent, int parent_slot,
1532                     struct extent_buffer **cow_ret)
1533 {
1534         struct btrfs_fs_info *fs_info = root->fs_info;
1535         u64 search_start;
1536         int ret;
1537
1538         if (trans->transaction != fs_info->running_transaction)
1539                 WARN(1, KERN_CRIT "trans %llu running %llu\n",
1540                        trans->transid,
1541                        fs_info->running_transaction->transid);
1542
1543         if (trans->transid != fs_info->generation)
1544                 WARN(1, KERN_CRIT "trans %llu running %llu\n",
1545                        trans->transid, fs_info->generation);
1546
1547         if (!should_cow_block(trans, root, buf)) {
1548                 trans->dirty = true;
1549                 *cow_ret = buf;
1550                 return 0;
1551         }
1552
1553         search_start = buf->start & ~((u64)SZ_1G - 1);
1554
1555         if (parent)
1556                 btrfs_set_lock_blocking(parent);
1557         btrfs_set_lock_blocking(buf);
1558
1559         ret = __btrfs_cow_block(trans, root, buf, parent,
1560                                  parent_slot, cow_ret, search_start, 0);
1561
1562         trace_btrfs_cow_block(root, buf, *cow_ret);
1563
1564         return ret;
1565 }
1566
1567 /*
1568  * helper function for defrag to decide if two blocks pointed to by a
1569  * node are actually close by
1570  */
1571 static int close_blocks(u64 blocknr, u64 other, u32 blocksize)
1572 {
1573         if (blocknr < other && other - (blocknr + blocksize) < 32768)
1574                 return 1;
1575         if (blocknr > other && blocknr - (other + blocksize) < 32768)
1576                 return 1;
1577         return 0;
1578 }
1579
1580 /*
1581  * compare two keys in a memcmp fashion
1582  */
1583 static int comp_keys(const struct btrfs_disk_key *disk,
1584                      const struct btrfs_key *k2)
1585 {
1586         struct btrfs_key k1;
1587
1588         btrfs_disk_key_to_cpu(&k1, disk);
1589
1590         return btrfs_comp_cpu_keys(&k1, k2);
1591 }
1592
1593 /*
1594  * same as comp_keys only with two btrfs_key's
1595  */
1596 int btrfs_comp_cpu_keys(const struct btrfs_key *k1, const struct btrfs_key *k2)
1597 {
1598         if (k1->objectid > k2->objectid)
1599                 return 1;
1600         if (k1->objectid < k2->objectid)
1601                 return -1;
1602         if (k1->type > k2->type)
1603                 return 1;
1604         if (k1->type < k2->type)
1605                 return -1;
1606         if (k1->offset > k2->offset)
1607                 return 1;
1608         if (k1->offset < k2->offset)
1609                 return -1;
1610         return 0;
1611 }
1612
1613 /*
1614  * this is used by the defrag code to go through all the
1615  * leaves pointed to by a node and reallocate them so that
1616  * disk order is close to key order
1617  */
1618 int btrfs_realloc_node(struct btrfs_trans_handle *trans,
1619                        struct btrfs_root *root, struct extent_buffer *parent,
1620                        int start_slot, u64 *last_ret,
1621                        struct btrfs_key *progress)
1622 {
1623         struct btrfs_fs_info *fs_info = root->fs_info;
1624         struct extent_buffer *cur;
1625         u64 blocknr;
1626         u64 gen;
1627         u64 search_start = *last_ret;
1628         u64 last_block = 0;
1629         u64 other;
1630         u32 parent_nritems;
1631         int end_slot;
1632         int i;
1633         int err = 0;
1634         int parent_level;
1635         int uptodate;
1636         u32 blocksize;
1637         int progress_passed = 0;
1638         struct btrfs_disk_key disk_key;
1639
1640         parent_level = btrfs_header_level(parent);
1641
1642         WARN_ON(trans->transaction != fs_info->running_transaction);
1643         WARN_ON(trans->transid != fs_info->generation);
1644
1645         parent_nritems = btrfs_header_nritems(parent);
1646         blocksize = fs_info->nodesize;
1647         end_slot = parent_nritems - 1;
1648
1649         if (parent_nritems <= 1)
1650                 return 0;
1651
1652         btrfs_set_lock_blocking(parent);
1653
1654         for (i = start_slot; i <= end_slot; i++) {
1655                 int close = 1;
1656
1657                 btrfs_node_key(parent, &disk_key, i);
1658                 if (!progress_passed && comp_keys(&disk_key, progress) < 0)
1659                         continue;
1660
1661                 progress_passed = 1;
1662                 blocknr = btrfs_node_blockptr(parent, i);
1663                 gen = btrfs_node_ptr_generation(parent, i);
1664                 if (last_block == 0)
1665                         last_block = blocknr;
1666
1667                 if (i > 0) {
1668                         other = btrfs_node_blockptr(parent, i - 1);
1669                         close = close_blocks(blocknr, other, blocksize);
1670                 }
1671                 if (!close && i < end_slot) {
1672                         other = btrfs_node_blockptr(parent, i + 1);
1673                         close = close_blocks(blocknr, other, blocksize);
1674                 }
1675                 if (close) {
1676                         last_block = blocknr;
1677                         continue;
1678                 }
1679
1680                 cur = find_extent_buffer(fs_info, blocknr);
1681                 if (cur)
1682                         uptodate = btrfs_buffer_uptodate(cur, gen, 0);
1683                 else
1684                         uptodate = 0;
1685                 if (!cur || !uptodate) {
1686                         if (!cur) {
1687                                 cur = read_tree_block(fs_info, blocknr, gen);
1688                                 if (IS_ERR(cur)) {
1689                                         return PTR_ERR(cur);
1690                                 } else if (!extent_buffer_uptodate(cur)) {
1691                                         free_extent_buffer(cur);
1692                                         return -EIO;
1693                                 }
1694                         } else if (!uptodate) {
1695                                 err = btrfs_read_buffer(cur, gen);
1696                                 if (err) {
1697                                         free_extent_buffer(cur);
1698                                         return err;
1699                                 }
1700                         }
1701                 }
1702                 if (search_start == 0)
1703                         search_start = last_block;
1704
1705                 btrfs_tree_lock(cur);
1706                 btrfs_set_lock_blocking(cur);
1707                 err = __btrfs_cow_block(trans, root, cur, parent, i,
1708                                         &cur, search_start,
1709                                         min(16 * blocksize,
1710                                             (end_slot - i) * blocksize));
1711                 if (err) {
1712                         btrfs_tree_unlock(cur);
1713                         free_extent_buffer(cur);
1714                         break;
1715                 }
1716                 search_start = cur->start;
1717                 last_block = cur->start;
1718                 *last_ret = search_start;
1719                 btrfs_tree_unlock(cur);
1720                 free_extent_buffer(cur);
1721         }
1722         return err;
1723 }
1724
1725 /*
1726  * search for key in the extent_buffer.  The items start at offset p,
1727  * and they are item_size apart.  There are 'max' items in p.
1728  *
1729  * the slot in the array is returned via slot, and it points to
1730  * the place where you would insert key if it is not found in
1731  * the array.
1732  *
1733  * slot may point to max if the key is bigger than all of the keys
1734  */
1735 static noinline int generic_bin_search(struct extent_buffer *eb,
1736                                        unsigned long p, int item_size,
1737                                        const struct btrfs_key *key,
1738                                        int max, int *slot)
1739 {
1740         int low = 0;
1741         int high = max;
1742         int mid;
1743         int ret;
1744         struct btrfs_disk_key *tmp = NULL;
1745         struct btrfs_disk_key unaligned;
1746         unsigned long offset;
1747         char *kaddr = NULL;
1748         unsigned long map_start = 0;
1749         unsigned long map_len = 0;
1750         int err;
1751
1752         if (low > high) {
1753                 btrfs_err(eb->fs_info,
1754                  "%s: low (%d) > high (%d) eb %llu owner %llu level %d",
1755                           __func__, low, high, eb->start,
1756                           btrfs_header_owner(eb), btrfs_header_level(eb));
1757                 return -EINVAL;
1758         }
1759
1760         while (low < high) {
1761                 mid = (low + high) / 2;
1762                 offset = p + mid * item_size;
1763
1764                 if (!kaddr || offset < map_start ||
1765                     (offset + sizeof(struct btrfs_disk_key)) >
1766                     map_start + map_len) {
1767
1768                         err = map_private_extent_buffer(eb, offset,
1769                                                 sizeof(struct btrfs_disk_key),
1770                                                 &kaddr, &map_start, &map_len);
1771
1772                         if (!err) {
1773                                 tmp = (struct btrfs_disk_key *)(kaddr + offset -
1774                                                         map_start);
1775                         } else if (err == 1) {
1776                                 read_extent_buffer(eb, &unaligned,
1777                                                    offset, sizeof(unaligned));
1778                                 tmp = &unaligned;
1779                         } else {
1780                                 return err;
1781                         }
1782
1783                 } else {
1784                         tmp = (struct btrfs_disk_key *)(kaddr + offset -
1785                                                         map_start);
1786                 }
1787                 ret = comp_keys(tmp, key);
1788
1789                 if (ret < 0)
1790                         low = mid + 1;
1791                 else if (ret > 0)
1792                         high = mid;
1793                 else {
1794                         *slot = mid;
1795                         return 0;
1796                 }
1797         }
1798         *slot = low;
1799         return 1;
1800 }
1801
1802 /*
1803  * simple bin_search frontend that does the right thing for
1804  * leaves vs nodes
1805  */
1806 int btrfs_bin_search(struct extent_buffer *eb, const struct btrfs_key *key,
1807                      int level, int *slot)
1808 {
1809         if (level == 0)
1810                 return generic_bin_search(eb,
1811                                           offsetof(struct btrfs_leaf, items),
1812                                           sizeof(struct btrfs_item),
1813                                           key, btrfs_header_nritems(eb),
1814                                           slot);
1815         else
1816                 return generic_bin_search(eb,
1817                                           offsetof(struct btrfs_node, ptrs),
1818                                           sizeof(struct btrfs_key_ptr),
1819                                           key, btrfs_header_nritems(eb),
1820                                           slot);
1821 }
1822
1823 static void root_add_used(struct btrfs_root *root, u32 size)
1824 {
1825         spin_lock(&root->accounting_lock);
1826         btrfs_set_root_used(&root->root_item,
1827                             btrfs_root_used(&root->root_item) + size);
1828         spin_unlock(&root->accounting_lock);
1829 }
1830
1831 static void root_sub_used(struct btrfs_root *root, u32 size)
1832 {
1833         spin_lock(&root->accounting_lock);
1834         btrfs_set_root_used(&root->root_item,
1835                             btrfs_root_used(&root->root_item) - size);
1836         spin_unlock(&root->accounting_lock);
1837 }
1838
1839 /* given a node and slot number, this reads the blocks it points to.  The
1840  * extent buffer is returned with a reference taken (but unlocked).
1841  */
1842 static noinline struct extent_buffer *
1843 read_node_slot(struct btrfs_fs_info *fs_info, struct extent_buffer *parent,
1844                int slot)
1845 {
1846         int level = btrfs_header_level(parent);
1847         struct extent_buffer *eb;
1848
1849         if (slot < 0 || slot >= btrfs_header_nritems(parent))
1850                 return ERR_PTR(-ENOENT);
1851
1852         BUG_ON(level == 0);
1853
1854         eb = read_tree_block(fs_info, btrfs_node_blockptr(parent, slot),
1855                              btrfs_node_ptr_generation(parent, slot));
1856         if (!IS_ERR(eb) && !extent_buffer_uptodate(eb)) {
1857                 free_extent_buffer(eb);
1858                 eb = ERR_PTR(-EIO);
1859         }
1860
1861         return eb;
1862 }
1863
1864 /*
1865  * node level balancing, used to make sure nodes are in proper order for
1866  * item deletion.  We balance from the top down, so we have to make sure
1867  * that a deletion won't leave an node completely empty later on.
1868  */
1869 static noinline int balance_level(struct btrfs_trans_handle *trans,
1870                          struct btrfs_root *root,
1871                          struct btrfs_path *path, int level)
1872 {
1873         struct btrfs_fs_info *fs_info = root->fs_info;
1874         struct extent_buffer *right = NULL;
1875         struct extent_buffer *mid;
1876         struct extent_buffer *left = NULL;
1877         struct extent_buffer *parent = NULL;
1878         int ret = 0;
1879         int wret;
1880         int pslot;
1881         int orig_slot = path->slots[level];
1882         u64 orig_ptr;
1883
1884         if (level == 0)
1885                 return 0;
1886
1887         mid = path->nodes[level];
1888
1889         WARN_ON(path->locks[level] != BTRFS_WRITE_LOCK &&
1890                 path->locks[level] != BTRFS_WRITE_LOCK_BLOCKING);
1891         WARN_ON(btrfs_header_generation(mid) != trans->transid);
1892
1893         orig_ptr = btrfs_node_blockptr(mid, orig_slot);
1894
1895         if (level < BTRFS_MAX_LEVEL - 1) {
1896                 parent = path->nodes[level + 1];
1897                 pslot = path->slots[level + 1];
1898         }
1899
1900         /*
1901          * deal with the case where there is only one pointer in the root
1902          * by promoting the node below to a root
1903          */
1904         if (!parent) {
1905                 struct extent_buffer *child;
1906
1907                 if (btrfs_header_nritems(mid) != 1)
1908                         return 0;
1909
1910                 /* promote the child to a root */
1911                 child = read_node_slot(fs_info, mid, 0);
1912                 if (IS_ERR(child)) {
1913                         ret = PTR_ERR(child);
1914                         btrfs_handle_fs_error(fs_info, ret, NULL);
1915                         goto enospc;
1916                 }
1917
1918                 btrfs_tree_lock(child);
1919                 btrfs_set_lock_blocking(child);
1920                 ret = btrfs_cow_block(trans, root, child, mid, 0, &child);
1921                 if (ret) {
1922                         btrfs_tree_unlock(child);
1923                         free_extent_buffer(child);
1924                         goto enospc;
1925                 }
1926
1927                 tree_mod_log_set_root_pointer(root, child, 1);
1928                 rcu_assign_pointer(root->node, child);
1929
1930                 add_root_to_dirty_list(root);
1931                 btrfs_tree_unlock(child);
1932
1933                 path->locks[level] = 0;
1934                 path->nodes[level] = NULL;
1935                 clean_tree_block(fs_info, mid);
1936                 btrfs_tree_unlock(mid);
1937                 /* once for the path */
1938                 free_extent_buffer(mid);
1939
1940                 root_sub_used(root, mid->len);
1941                 btrfs_free_tree_block(trans, root, mid, 0, 1);
1942                 /* once for the root ptr */
1943                 free_extent_buffer_stale(mid);
1944                 return 0;
1945         }
1946         if (btrfs_header_nritems(mid) >
1947             BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 4)
1948                 return 0;
1949
1950         left = read_node_slot(fs_info, parent, pslot - 1);
1951         if (IS_ERR(left))
1952                 left = NULL;
1953
1954         if (left) {
1955                 btrfs_tree_lock(left);
1956                 btrfs_set_lock_blocking(left);
1957                 wret = btrfs_cow_block(trans, root, left,
1958                                        parent, pslot - 1, &left);
1959                 if (wret) {
1960                         ret = wret;
1961                         goto enospc;
1962                 }
1963         }
1964
1965         right = read_node_slot(fs_info, parent, pslot + 1);
1966         if (IS_ERR(right))
1967                 right = NULL;
1968
1969         if (right) {
1970                 btrfs_tree_lock(right);
1971                 btrfs_set_lock_blocking(right);
1972                 wret = btrfs_cow_block(trans, root, right,
1973                                        parent, pslot + 1, &right);
1974                 if (wret) {
1975                         ret = wret;
1976                         goto enospc;
1977                 }
1978         }
1979
1980         /* first, try to make some room in the middle buffer */
1981         if (left) {
1982                 orig_slot += btrfs_header_nritems(left);
1983                 wret = push_node_left(trans, fs_info, left, mid, 1);
1984                 if (wret < 0)
1985                         ret = wret;
1986         }
1987
1988         /*
1989          * then try to empty the right most buffer into the middle
1990          */
1991         if (right) {
1992                 wret = push_node_left(trans, fs_info, mid, right, 1);
1993                 if (wret < 0 && wret != -ENOSPC)
1994                         ret = wret;
1995                 if (btrfs_header_nritems(right) == 0) {
1996                         clean_tree_block(fs_info, right);
1997                         btrfs_tree_unlock(right);
1998                         del_ptr(root, path, level + 1, pslot + 1);
1999                         root_sub_used(root, right->len);
2000                         btrfs_free_tree_block(trans, root, right, 0, 1);
2001                         free_extent_buffer_stale(right);
2002                         right = NULL;
2003                 } else {
2004                         struct btrfs_disk_key right_key;
2005                         btrfs_node_key(right, &right_key, 0);
2006                         tree_mod_log_set_node_key(parent, pslot + 1, 0);
2007                         btrfs_set_node_key(parent, &right_key, pslot + 1);
2008                         btrfs_mark_buffer_dirty(parent);
2009                 }
2010         }
2011         if (btrfs_header_nritems(mid) == 1) {
2012                 /*
2013                  * we're not allowed to leave a node with one item in the
2014                  * tree during a delete.  A deletion from lower in the tree
2015                  * could try to delete the only pointer in this node.
2016                  * So, pull some keys from the left.
2017                  * There has to be a left pointer at this point because
2018                  * otherwise we would have pulled some pointers from the
2019                  * right
2020                  */
2021                 if (!left) {
2022                         ret = -EROFS;
2023                         btrfs_handle_fs_error(fs_info, ret, NULL);
2024                         goto enospc;
2025                 }
2026                 wret = balance_node_right(trans, fs_info, mid, left);
2027                 if (wret < 0) {
2028                         ret = wret;
2029                         goto enospc;
2030                 }
2031                 if (wret == 1) {
2032                         wret = push_node_left(trans, fs_info, left, mid, 1);
2033                         if (wret < 0)
2034                                 ret = wret;
2035                 }
2036                 BUG_ON(wret == 1);
2037         }
2038         if (btrfs_header_nritems(mid) == 0) {
2039                 clean_tree_block(fs_info, mid);
2040                 btrfs_tree_unlock(mid);
2041                 del_ptr(root, path, level + 1, pslot);
2042                 root_sub_used(root, mid->len);
2043                 btrfs_free_tree_block(trans, root, mid, 0, 1);
2044                 free_extent_buffer_stale(mid);
2045                 mid = NULL;
2046         } else {
2047                 /* update the parent key to reflect our changes */
2048                 struct btrfs_disk_key mid_key;
2049                 btrfs_node_key(mid, &mid_key, 0);
2050                 tree_mod_log_set_node_key(parent, pslot, 0);
2051                 btrfs_set_node_key(parent, &mid_key, pslot);
2052                 btrfs_mark_buffer_dirty(parent);
2053         }
2054
2055         /* update the path */
2056         if (left) {
2057                 if (btrfs_header_nritems(left) > orig_slot) {
2058                         extent_buffer_get(left);
2059                         /* left was locked after cow */
2060                         path->nodes[level] = left;
2061                         path->slots[level + 1] -= 1;
2062                         path->slots[level] = orig_slot;
2063                         if (mid) {
2064                                 btrfs_tree_unlock(mid);
2065                                 free_extent_buffer(mid);
2066                         }
2067                 } else {
2068                         orig_slot -= btrfs_header_nritems(left);
2069                         path->slots[level] = orig_slot;
2070                 }
2071         }
2072         /* double check we haven't messed things up */
2073         if (orig_ptr !=
2074             btrfs_node_blockptr(path->nodes[level], path->slots[level]))
2075                 BUG();
2076 enospc:
2077         if (right) {
2078                 btrfs_tree_unlock(right);
2079                 free_extent_buffer(right);
2080         }
2081         if (left) {
2082                 if (path->nodes[level] != left)
2083                         btrfs_tree_unlock(left);
2084                 free_extent_buffer(left);
2085         }
2086         return ret;
2087 }
2088
2089 /* Node balancing for insertion.  Here we only split or push nodes around
2090  * when they are completely full.  This is also done top down, so we
2091  * have to be pessimistic.
2092  */
2093 static noinline int push_nodes_for_insert(struct btrfs_trans_handle *trans,
2094                                           struct btrfs_root *root,
2095                                           struct btrfs_path *path, int level)
2096 {
2097         struct btrfs_fs_info *fs_info = root->fs_info;
2098         struct extent_buffer *right = NULL;
2099         struct extent_buffer *mid;
2100         struct extent_buffer *left = NULL;
2101         struct extent_buffer *parent = NULL;
2102         int ret = 0;
2103         int wret;
2104         int pslot;
2105         int orig_slot = path->slots[level];
2106
2107         if (level == 0)
2108                 return 1;
2109
2110         mid = path->nodes[level];
2111         WARN_ON(btrfs_header_generation(mid) != trans->transid);
2112
2113         if (level < BTRFS_MAX_LEVEL - 1) {
2114                 parent = path->nodes[level + 1];
2115                 pslot = path->slots[level + 1];
2116         }
2117
2118         if (!parent)
2119                 return 1;
2120
2121         left = read_node_slot(fs_info, parent, pslot - 1);
2122         if (IS_ERR(left))
2123                 left = NULL;
2124
2125         /* first, try to make some room in the middle buffer */
2126         if (left) {
2127                 u32 left_nr;
2128
2129                 btrfs_tree_lock(left);
2130                 btrfs_set_lock_blocking(left);
2131
2132                 left_nr = btrfs_header_nritems(left);
2133                 if (left_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
2134                         wret = 1;
2135                 } else {
2136                         ret = btrfs_cow_block(trans, root, left, parent,
2137                                               pslot - 1, &left);
2138                         if (ret)
2139                                 wret = 1;
2140                         else {
2141                                 wret = push_node_left(trans, fs_info,
2142                                                       left, mid, 0);
2143                         }
2144                 }
2145                 if (wret < 0)
2146                         ret = wret;
2147                 if (wret == 0) {
2148                         struct btrfs_disk_key disk_key;
2149                         orig_slot += left_nr;
2150                         btrfs_node_key(mid, &disk_key, 0);
2151                         tree_mod_log_set_node_key(parent, pslot, 0);
2152                         btrfs_set_node_key(parent, &disk_key, pslot);
2153                         btrfs_mark_buffer_dirty(parent);
2154                         if (btrfs_header_nritems(left) > orig_slot) {
2155                                 path->nodes[level] = left;
2156                                 path->slots[level + 1] -= 1;
2157                                 path->slots[level] = orig_slot;
2158                                 btrfs_tree_unlock(mid);
2159                                 free_extent_buffer(mid);
2160                         } else {
2161                                 orig_slot -=
2162                                         btrfs_header_nritems(left);
2163                                 path->slots[level] = orig_slot;
2164                                 btrfs_tree_unlock(left);
2165                                 free_extent_buffer(left);
2166                         }
2167                         return 0;
2168                 }
2169                 btrfs_tree_unlock(left);
2170                 free_extent_buffer(left);
2171         }
2172         right = read_node_slot(fs_info, parent, pslot + 1);
2173         if (IS_ERR(right))
2174                 right = NULL;
2175
2176         /*
2177          * then try to empty the right most buffer into the middle
2178          */
2179         if (right) {
2180                 u32 right_nr;
2181
2182                 btrfs_tree_lock(right);
2183                 btrfs_set_lock_blocking(right);
2184
2185                 right_nr = btrfs_header_nritems(right);
2186                 if (right_nr >= BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 1) {
2187                         wret = 1;
2188                 } else {
2189                         ret = btrfs_cow_block(trans, root, right,
2190                                               parent, pslot + 1,
2191                                               &right);
2192                         if (ret)
2193                                 wret = 1;
2194                         else {
2195                                 wret = balance_node_right(trans, fs_info,
2196                                                           right, mid);
2197                         }
2198                 }
2199                 if (wret < 0)
2200                         ret = wret;
2201                 if (wret == 0) {
2202                         struct btrfs_disk_key disk_key;
2203
2204                         btrfs_node_key(right, &disk_key, 0);
2205                         tree_mod_log_set_node_key(parent, pslot + 1, 0);
2206                         btrfs_set_node_key(parent, &disk_key, pslot + 1);
2207                         btrfs_mark_buffer_dirty(parent);
2208
2209                         if (btrfs_header_nritems(mid) <= orig_slot) {
2210                                 path->nodes[level] = right;
2211                                 path->slots[level + 1] += 1;
2212                                 path->slots[level] = orig_slot -
2213                                         btrfs_header_nritems(mid);
2214                                 btrfs_tree_unlock(mid);
2215                                 free_extent_buffer(mid);
2216                         } else {
2217                                 btrfs_tree_unlock(right);
2218                                 free_extent_buffer(right);
2219                         }
2220                         return 0;
2221                 }
2222                 btrfs_tree_unlock(right);
2223                 free_extent_buffer(right);
2224         }
2225         return 1;
2226 }
2227
2228 /*
2229  * readahead one full node of leaves, finding things that are close
2230  * to the block in 'slot', and triggering ra on them.
2231  */
2232 static void reada_for_search(struct btrfs_fs_info *fs_info,
2233                              struct btrfs_path *path,
2234                              int level, int slot, u64 objectid)
2235 {
2236         struct extent_buffer *node;
2237         struct btrfs_disk_key disk_key;
2238         u32 nritems;
2239         u64 search;
2240         u64 target;
2241         u64 nread = 0;
2242         struct extent_buffer *eb;
2243         u32 nr;
2244         u32 blocksize;
2245         u32 nscan = 0;
2246
2247         if (level != 1)
2248                 return;
2249
2250         if (!path->nodes[level])
2251                 return;
2252
2253         node = path->nodes[level];
2254
2255         search = btrfs_node_blockptr(node, slot);
2256         blocksize = fs_info->nodesize;
2257         eb = find_extent_buffer(fs_info, search);
2258         if (eb) {
2259                 free_extent_buffer(eb);
2260                 return;
2261         }
2262
2263         target = search;
2264
2265         nritems = btrfs_header_nritems(node);
2266         nr = slot;
2267
2268         while (1) {
2269                 if (path->reada == READA_BACK) {
2270                         if (nr == 0)
2271                                 break;
2272                         nr--;
2273                 } else if (path->reada == READA_FORWARD) {
2274                         nr++;
2275                         if (nr >= nritems)
2276                                 break;
2277                 }
2278                 if (path->reada == READA_BACK && objectid) {
2279                         btrfs_node_key(node, &disk_key, nr);
2280                         if (btrfs_disk_key_objectid(&disk_key) != objectid)
2281                                 break;
2282                 }
2283                 search = btrfs_node_blockptr(node, nr);
2284                 if ((search <= target && target - search <= 65536) ||
2285                     (search > target && search - target <= 65536)) {
2286                         readahead_tree_block(fs_info, search);
2287                         nread += blocksize;
2288                 }
2289                 nscan++;
2290                 if ((nread > 65536 || nscan > 32))
2291                         break;
2292         }
2293 }
2294
2295 static noinline void reada_for_balance(struct btrfs_fs_info *fs_info,
2296                                        struct btrfs_path *path, int level)
2297 {
2298         int slot;
2299         int nritems;
2300         struct extent_buffer *parent;
2301         struct extent_buffer *eb;
2302         u64 gen;
2303         u64 block1 = 0;
2304         u64 block2 = 0;
2305
2306         parent = path->nodes[level + 1];
2307         if (!parent)
2308                 return;
2309
2310         nritems = btrfs_header_nritems(parent);
2311         slot = path->slots[level + 1];
2312
2313         if (slot > 0) {
2314                 block1 = btrfs_node_blockptr(parent, slot - 1);
2315                 gen = btrfs_node_ptr_generation(parent, slot - 1);
2316                 eb = find_extent_buffer(fs_info, block1);
2317                 /*
2318                  * if we get -eagain from btrfs_buffer_uptodate, we
2319                  * don't want to return eagain here.  That will loop
2320                  * forever
2321                  */
2322                 if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
2323                         block1 = 0;
2324                 free_extent_buffer(eb);
2325         }
2326         if (slot + 1 < nritems) {
2327                 block2 = btrfs_node_blockptr(parent, slot + 1);
2328                 gen = btrfs_node_ptr_generation(parent, slot + 1);
2329                 eb = find_extent_buffer(fs_info, block2);
2330                 if (eb && btrfs_buffer_uptodate(eb, gen, 1) != 0)
2331                         block2 = 0;
2332                 free_extent_buffer(eb);
2333         }
2334
2335         if (block1)
2336                 readahead_tree_block(fs_info, block1);
2337         if (block2)
2338                 readahead_tree_block(fs_info, block2);
2339 }
2340
2341
2342 /*
2343  * when we walk down the tree, it is usually safe to unlock the higher layers
2344  * in the tree.  The exceptions are when our path goes through slot 0, because
2345  * operations on the tree might require changing key pointers higher up in the
2346  * tree.
2347  *
2348  * callers might also have set path->keep_locks, which tells this code to keep
2349  * the lock if the path points to the last slot in the block.  This is part of
2350  * walking through the tree, and selecting the next slot in the higher block.
2351  *
2352  * lowest_unlock sets the lowest level in the tree we're allowed to unlock.  so
2353  * if lowest_unlock is 1, level 0 won't be unlocked
2354  */
2355 static noinline void unlock_up(struct btrfs_path *path, int level,
2356                                int lowest_unlock, int min_write_lock_level,
2357                                int *write_lock_level)
2358 {
2359         int i;
2360         int skip_level = level;
2361         int no_skips = 0;
2362         struct extent_buffer *t;
2363
2364         for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2365                 if (!path->nodes[i])
2366                         break;
2367                 if (!path->locks[i])
2368                         break;
2369                 if (!no_skips && path->slots[i] == 0) {
2370                         skip_level = i + 1;
2371                         continue;
2372                 }
2373                 if (!no_skips && path->keep_locks) {
2374                         u32 nritems;
2375                         t = path->nodes[i];
2376                         nritems = btrfs_header_nritems(t);
2377                         if (nritems < 1 || path->slots[i] >= nritems - 1) {
2378                                 skip_level = i + 1;
2379                                 continue;
2380                         }
2381                 }
2382                 if (skip_level < i && i >= lowest_unlock)
2383                         no_skips = 1;
2384
2385                 t = path->nodes[i];
2386                 if (i >= lowest_unlock && i > skip_level && path->locks[i]) {
2387                         btrfs_tree_unlock_rw(t, path->locks[i]);
2388                         path->locks[i] = 0;
2389                         if (write_lock_level &&
2390                             i > min_write_lock_level &&
2391                             i <= *write_lock_level) {
2392                                 *write_lock_level = i - 1;
2393                         }
2394                 }
2395         }
2396 }
2397
2398 /*
2399  * This releases any locks held in the path starting at level and
2400  * going all the way up to the root.
2401  *
2402  * btrfs_search_slot will keep the lock held on higher nodes in a few
2403  * corner cases, such as COW of the block at slot zero in the node.  This
2404  * ignores those rules, and it should only be called when there are no
2405  * more updates to be done higher up in the tree.
2406  */
2407 noinline void btrfs_unlock_up_safe(struct btrfs_path *path, int level)
2408 {
2409         int i;
2410
2411         if (path->keep_locks)
2412                 return;
2413
2414         for (i = level; i < BTRFS_MAX_LEVEL; i++) {
2415                 if (!path->nodes[i])
2416                         continue;
2417                 if (!path->locks[i])
2418                         continue;
2419                 btrfs_tree_unlock_rw(path->nodes[i], path->locks[i]);
2420                 path->locks[i] = 0;
2421         }
2422 }
2423
2424 /*
2425  * helper function for btrfs_search_slot.  The goal is to find a block
2426  * in cache without setting the path to blocking.  If we find the block
2427  * we return zero and the path is unchanged.
2428  *
2429  * If we can't find the block, we set the path blocking and do some
2430  * reada.  -EAGAIN is returned and the search must be repeated.
2431  */
2432 static int
2433 read_block_for_search(struct btrfs_root *root, struct btrfs_path *p,
2434                       struct extent_buffer **eb_ret, int level, int slot,
2435                       const struct btrfs_key *key)
2436 {
2437         struct btrfs_fs_info *fs_info = root->fs_info;
2438         u64 blocknr;
2439         u64 gen;
2440         struct extent_buffer *b = *eb_ret;
2441         struct extent_buffer *tmp;
2442         int ret;
2443
2444         blocknr = btrfs_node_blockptr(b, slot);
2445         gen = btrfs_node_ptr_generation(b, slot);
2446
2447         tmp = find_extent_buffer(fs_info, blocknr);
2448         if (tmp) {
2449                 /* first we do an atomic uptodate check */
2450                 if (btrfs_buffer_uptodate(tmp, gen, 1) > 0) {
2451                         *eb_ret = tmp;
2452                         return 0;
2453                 }
2454
2455                 /* the pages were up to date, but we failed
2456                  * the generation number check.  Do a full
2457                  * read for the generation number that is correct.
2458                  * We must do this without dropping locks so
2459                  * we can trust our generation number
2460                  */
2461                 btrfs_set_path_blocking(p);
2462
2463                 /* now we're allowed to do a blocking uptodate check */
2464                 ret = btrfs_read_buffer(tmp, gen);
2465                 if (!ret) {
2466                         *eb_ret = tmp;
2467                         return 0;
2468                 }
2469                 free_extent_buffer(tmp);
2470                 btrfs_release_path(p);
2471                 return -EIO;
2472         }
2473
2474         /*
2475          * reduce lock contention at high levels
2476          * of the btree by dropping locks before
2477          * we read.  Don't release the lock on the current
2478          * level because we need to walk this node to figure
2479          * out which blocks to read.
2480          */
2481         btrfs_unlock_up_safe(p, level + 1);
2482         btrfs_set_path_blocking(p);
2483
2484         free_extent_buffer(tmp);
2485         if (p->reada != READA_NONE)
2486                 reada_for_search(fs_info, p, level, slot, key->objectid);
2487
2488         btrfs_release_path(p);
2489
2490         ret = -EAGAIN;
2491         tmp = read_tree_block(fs_info, blocknr, 0);
2492         if (!IS_ERR(tmp)) {
2493                 /*
2494                  * If the read above didn't mark this buffer up to date,
2495                  * it will never end up being up to date.  Set ret to EIO now
2496                  * and give up so that our caller doesn't loop forever
2497                  * on our EAGAINs.
2498                  */
2499                 if (!btrfs_buffer_uptodate(tmp, 0, 0))
2500                         ret = -EIO;
2501                 free_extent_buffer(tmp);
2502         } else {
2503                 ret = PTR_ERR(tmp);
2504         }
2505         return ret;
2506 }
2507
2508 /*
2509  * helper function for btrfs_search_slot.  This does all of the checks
2510  * for node-level blocks and does any balancing required based on
2511  * the ins_len.
2512  *
2513  * If no extra work was required, zero is returned.  If we had to
2514  * drop the path, -EAGAIN is returned and btrfs_search_slot must
2515  * start over
2516  */
2517 static int
2518 setup_nodes_for_search(struct btrfs_trans_handle *trans,
2519                        struct btrfs_root *root, struct btrfs_path *p,
2520                        struct extent_buffer *b, int level, int ins_len,
2521                        int *write_lock_level)
2522 {
2523         struct btrfs_fs_info *fs_info = root->fs_info;
2524         int ret;
2525
2526         if ((p->search_for_split || ins_len > 0) && btrfs_header_nritems(b) >=
2527             BTRFS_NODEPTRS_PER_BLOCK(fs_info) - 3) {
2528                 int sret;
2529
2530                 if (*write_lock_level < level + 1) {
2531                         *write_lock_level = level + 1;
2532                         btrfs_release_path(p);
2533                         goto again;
2534                 }
2535
2536                 btrfs_set_path_blocking(p);
2537                 reada_for_balance(fs_info, p, level);
2538                 sret = split_node(trans, root, p, level);
2539                 btrfs_clear_path_blocking(p, NULL, 0);
2540
2541                 BUG_ON(sret > 0);
2542                 if (sret) {
2543                         ret = sret;
2544                         goto done;
2545                 }
2546                 b = p->nodes[level];
2547         } else if (ins_len < 0 && btrfs_header_nritems(b) <
2548                    BTRFS_NODEPTRS_PER_BLOCK(fs_info) / 2) {
2549                 int sret;
2550
2551                 if (*write_lock_level < level + 1) {
2552                         *write_lock_level = level + 1;
2553                         btrfs_release_path(p);
2554                         goto again;
2555                 }
2556
2557                 btrfs_set_path_blocking(p);
2558                 reada_for_balance(fs_info, p, level);
2559                 sret = balance_level(trans, root, p, level);
2560                 btrfs_clear_path_blocking(p, NULL, 0);
2561
2562                 if (sret) {
2563                         ret = sret;
2564                         goto done;
2565                 }
2566                 b = p->nodes[level];
2567                 if (!b) {
2568                         btrfs_release_path(p);
2569                         goto again;
2570                 }
2571                 BUG_ON(btrfs_header_nritems(b) == 1);
2572         }
2573         return 0;
2574
2575 again:
2576         ret = -EAGAIN;
2577 done:
2578         return ret;
2579 }
2580
2581 static void key_search_validate(struct extent_buffer *b,
2582                                 const struct btrfs_key *key,
2583                                 int level)
2584 {
2585 #ifdef CONFIG_BTRFS_ASSERT
2586         struct btrfs_disk_key disk_key;
2587
2588         btrfs_cpu_key_to_disk(&disk_key, key);
2589
2590         if (level == 0)
2591                 ASSERT(!memcmp_extent_buffer(b, &disk_key,
2592                     offsetof(struct btrfs_leaf, items[0].key),
2593                     sizeof(disk_key)));
2594         else
2595                 ASSERT(!memcmp_extent_buffer(b, &disk_key,
2596                     offsetof(struct btrfs_node, ptrs[0].key),
2597                     sizeof(disk_key)));
2598 #endif
2599 }
2600
2601 static int key_search(struct extent_buffer *b, const struct btrfs_key *key,
2602                       int level, int *prev_cmp, int *slot)
2603 {
2604         if (*prev_cmp != 0) {
2605                 *prev_cmp = btrfs_bin_search(b, key, level, slot);
2606                 return *prev_cmp;
2607         }
2608
2609         key_search_validate(b, key, level);
2610         *slot = 0;
2611
2612         return 0;
2613 }
2614
2615 int btrfs_find_item(struct btrfs_root *fs_root, struct btrfs_path *path,
2616                 u64 iobjectid, u64 ioff, u8 key_type,
2617                 struct btrfs_key *found_key)
2618 {
2619         int ret;
2620         struct btrfs_key key;
2621         struct extent_buffer *eb;
2622
2623         ASSERT(path);
2624         ASSERT(found_key);
2625
2626         key.type = key_type;
2627         key.objectid = iobjectid;
2628         key.offset = ioff;
2629
2630         ret = btrfs_search_slot(NULL, fs_root, &key, path, 0, 0);
2631         if (ret < 0)
2632                 return ret;
2633
2634         eb = path->nodes[0];
2635         if (ret && path->slots[0] >= btrfs_header_nritems(eb)) {
2636                 ret = btrfs_next_leaf(fs_root, path);
2637                 if (ret)
2638                         return ret;
2639                 eb = path->nodes[0];
2640         }
2641
2642         btrfs_item_key_to_cpu(eb, found_key, path->slots[0]);
2643         if (found_key->type != key.type ||
2644                         found_key->objectid != key.objectid)
2645                 return 1;
2646
2647         return 0;
2648 }
2649
2650 /*
2651  * btrfs_search_slot - look for a key in a tree and perform necessary
2652  * modifications to preserve tree invariants.
2653  *
2654  * @trans:      Handle of transaction, used when modifying the tree
2655  * @p:          Holds all btree nodes along the search path
2656  * @root:       The root node of the tree
2657  * @key:        The key we are looking for
2658  * @ins_len:    Indicates purpose of search, for inserts it is 1, for
2659  *              deletions it's -1. 0 for plain searches
2660  * @cow:        boolean should CoW operations be performed. Must always be 1
2661  *              when modifying the tree.
2662  *
2663  * If @ins_len > 0, nodes and leaves will be split as we walk down the tree.
2664  * If @ins_len < 0, nodes will be merged as we walk down the tree (if possible)
2665  *
2666  * If @key is found, 0 is returned and you can find the item in the leaf level
2667  * of the path (level 0)
2668  *
2669  * If @key isn't found, 1 is returned and the leaf level of the path (level 0)
2670  * points to the slot where it should be inserted
2671  *
2672  * If an error is encountered while searching the tree a negative error number
2673  * is returned
2674  */
2675 int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2676                       const struct btrfs_key *key, struct btrfs_path *p,
2677                       int ins_len, int cow)
2678 {
2679         struct btrfs_fs_info *fs_info = root->fs_info;
2680         struct extent_buffer *b;
2681         int slot;
2682         int ret;
2683         int err;
2684         int level;
2685         int lowest_unlock = 1;
2686         int root_lock;
2687         /* everything at write_lock_level or lower must be write locked */
2688         int write_lock_level = 0;
2689         u8 lowest_level = 0;
2690         int min_write_lock_level;
2691         int prev_cmp;
2692
2693         lowest_level = p->lowest_level;
2694         WARN_ON(lowest_level && ins_len > 0);
2695         WARN_ON(p->nodes[0] != NULL);
2696         BUG_ON(!cow && ins_len);
2697
2698         if (ins_len < 0) {
2699                 lowest_unlock = 2;
2700
2701                 /* when we are removing items, we might have to go up to level
2702                  * two as we update tree pointers  Make sure we keep write
2703                  * for those levels as well
2704                  */
2705                 write_lock_level = 2;
2706         } else if (ins_len > 0) {
2707                 /*
2708                  * for inserting items, make sure we have a write lock on
2709                  * level 1 so we can update keys
2710                  */
2711                 write_lock_level = 1;
2712         }
2713
2714         if (!cow)
2715                 write_lock_level = -1;
2716
2717         if (cow && (p->keep_locks || p->lowest_level))
2718                 write_lock_level = BTRFS_MAX_LEVEL;
2719
2720         min_write_lock_level = write_lock_level;
2721
2722 again:
2723         prev_cmp = -1;
2724         /*
2725          * we try very hard to do read locks on the root
2726          */
2727         root_lock = BTRFS_READ_LOCK;
2728         level = 0;
2729         if (p->search_commit_root) {
2730                 /*
2731                  * the commit roots are read only
2732                  * so we always do read locks
2733                  */
2734                 if (p->need_commit_sem)
2735                         down_read(&fs_info->commit_root_sem);
2736                 b = root->commit_root;
2737                 extent_buffer_get(b);
2738                 level = btrfs_header_level(b);
2739                 if (p->need_commit_sem)
2740                         up_read(&fs_info->commit_root_sem);
2741                 if (!p->skip_locking)
2742                         btrfs_tree_read_lock(b);
2743         } else {
2744                 if (p->skip_locking) {
2745                         b = btrfs_root_node(root);
2746                         level = btrfs_header_level(b);
2747                 } else {
2748                         /* we don't know the level of the root node
2749                          * until we actually have it read locked
2750                          */
2751                         b = btrfs_read_lock_root_node(root);
2752                         level = btrfs_header_level(b);
2753                         if (level <= write_lock_level) {
2754                                 /* whoops, must trade for write lock */
2755                                 btrfs_tree_read_unlock(b);
2756                                 free_extent_buffer(b);
2757                                 b = btrfs_lock_root_node(root);
2758                                 root_lock = BTRFS_WRITE_LOCK;
2759
2760                                 /* the level might have changed, check again */
2761                                 level = btrfs_header_level(b);
2762                         }
2763                 }
2764         }
2765         p->nodes[level] = b;
2766         if (!p->skip_locking)
2767                 p->locks[level] = root_lock;
2768
2769         while (b) {
2770                 level = btrfs_header_level(b);
2771
2772                 /*
2773                  * setup the path here so we can release it under lock
2774                  * contention with the cow code
2775                  */
2776                 if (cow) {
2777                         bool last_level = (level == (BTRFS_MAX_LEVEL - 1));
2778
2779                         /*
2780                          * if we don't really need to cow this block
2781                          * then we don't want to set the path blocking,
2782                          * so we test it here
2783                          */
2784                         if (!should_cow_block(trans, root, b)) {
2785                                 trans->dirty = true;
2786                                 goto cow_done;
2787                         }
2788
2789                         /*
2790                          * must have write locks on this node and the
2791                          * parent
2792                          */
2793                         if (level > write_lock_level ||
2794                             (level + 1 > write_lock_level &&
2795                             level + 1 < BTRFS_MAX_LEVEL &&
2796                             p->nodes[level + 1])) {
2797                                 write_lock_level = level + 1;
2798                                 btrfs_release_path(p);
2799                                 goto again;
2800                         }
2801
2802                         btrfs_set_path_blocking(p);
2803                         if (last_level)
2804                                 err = btrfs_cow_block(trans, root, b, NULL, 0,
2805                                                       &b);
2806                         else
2807                                 err = btrfs_cow_block(trans, root, b,
2808                                                       p->nodes[level + 1],
2809                                                       p->slots[level + 1], &b);
2810                         if (err) {
2811                                 ret = err;
2812                                 goto done;
2813                         }
2814                 }
2815 cow_done:
2816                 p->nodes[level] = b;
2817                 btrfs_clear_path_blocking(p, NULL, 0);
2818
2819                 /*
2820                  * we have a lock on b and as long as we aren't changing
2821                  * the tree, there is no way to for the items in b to change.
2822                  * It is safe to drop the lock on our parent before we
2823                  * go through the expensive btree search on b.
2824                  *
2825                  * If we're inserting or deleting (ins_len != 0), then we might
2826                  * be changing slot zero, which may require changing the parent.
2827                  * So, we can't drop the lock until after we know which slot
2828                  * we're operating on.
2829                  */
2830                 if (!ins_len && !p->keep_locks) {
2831                         int u = level + 1;
2832
2833                         if (u < BTRFS_MAX_LEVEL && p->locks[u]) {
2834                                 btrfs_tree_unlock_rw(p->nodes[u], p->locks[u]);
2835                                 p->locks[u] = 0;
2836                         }
2837                 }
2838
2839                 ret = key_search(b, key, level, &prev_cmp, &slot);
2840                 if (ret < 0)
2841                         goto done;
2842
2843                 if (level != 0) {
2844                         int dec = 0;
2845                         if (ret && slot > 0) {
2846                                 dec = 1;
2847                                 slot -= 1;
2848                         }
2849                         p->slots[level] = slot;
2850                         err = setup_nodes_for_search(trans, root, p, b, level,
2851                                              ins_len, &write_lock_level);
2852                         if (err == -EAGAIN)
2853                                 goto again;
2854                         if (err) {
2855                                 ret = err;
2856                                 goto done;
2857                         }
2858                         b = p->nodes[level];
2859                         slot = p->slots[level];
2860
2861                         /*
2862                          * slot 0 is special, if we change the key
2863                          * we have to update the parent pointer
2864                          * which means we must have a write lock
2865                          * on the parent
2866                          */
2867                         if (slot == 0 && ins_len &&
2868                             write_lock_level < level + 1) {
2869                                 write_lock_level = level + 1;
2870                                 btrfs_release_path(p);
2871                                 goto again;
2872                         }
2873
2874                         unlock_up(p, level, lowest_unlock,
2875                                   min_write_lock_level, &write_lock_level);
2876
2877                         if (level == lowest_level) {
2878                                 if (dec)
2879                                         p->slots[level]++;
2880                                 goto done;
2881                         }
2882
2883                         err = read_block_for_search(root, p, &b, level,
2884                                                     slot, key);
2885                         if (err == -EAGAIN)
2886                                 goto again;
2887                         if (err) {
2888                                 ret = err;
2889                                 goto done;
2890                         }
2891
2892                         if (!p->skip_locking) {
2893                                 level = btrfs_header_level(b);
2894                                 if (level <= write_lock_level) {
2895                                         err = btrfs_try_tree_write_lock(b);
2896                                         if (!err) {
2897                                                 btrfs_set_path_blocking(p);
2898                                                 btrfs_tree_lock(b);
2899                                                 btrfs_clear_path_blocking(p, b,
2900                                                                   BTRFS_WRITE_LOCK);
2901                                         }
2902                                         p->locks[level] = BTRFS_WRITE_LOCK;
2903                                 } else {
2904                                         err = btrfs_tree_read_lock_atomic(b);
2905                                         if (!err) {
2906                                                 btrfs_set_path_blocking(p);
2907                                                 btrfs_tree_read_lock(b);
2908                                                 btrfs_clear_path_blocking(p, b,
2909                                                                   BTRFS_READ_LOCK);
2910                                         }
2911                                         p->locks[level] = BTRFS_READ_LOCK;
2912                                 }
2913                                 p->nodes[level] = b;
2914                         }
2915                 } else {
2916                         p->slots[level] = slot;
2917                         if (ins_len > 0 &&
2918                             btrfs_leaf_free_space(fs_info, b) < ins_len) {
2919                                 if (write_lock_level < 1) {
2920                                         write_lock_level = 1;
2921                                         btrfs_release_path(p);
2922                                         goto again;
2923                                 }
2924
2925                                 btrfs_set_path_blocking(p);
2926                                 err = split_leaf(trans, root, key,
2927                                                  p, ins_len, ret == 0);
2928                                 btrfs_clear_path_blocking(p, NULL, 0);
2929
2930                                 BUG_ON(err > 0);
2931                                 if (err) {
2932                                         ret = err;
2933                                         goto done;
2934                                 }
2935                         }
2936                         if (!p->search_for_split)
2937                                 unlock_up(p, level, lowest_unlock,
2938                                           min_write_lock_level, &write_lock_level);
2939                         goto done;
2940                 }
2941         }
2942         ret = 1;
2943 done:
2944         /*
2945          * we don't really know what they plan on doing with the path
2946          * from here on, so for now just mark it as blocking
2947          */
2948         if (!p->leave_spinning)
2949                 btrfs_set_path_blocking(p);
2950         if (ret < 0 && !p->skip_release_on_error)
2951                 btrfs_release_path(p);
2952         return ret;
2953 }
2954
2955 /*
2956  * Like btrfs_search_slot, this looks for a key in the given tree. It uses the
2957  * current state of the tree together with the operations recorded in the tree
2958  * modification log to search for the key in a previous version of this tree, as
2959  * denoted by the time_seq parameter.
2960  *
2961  * Naturally, there is no support for insert, delete or cow operations.
2962  *
2963  * The resulting path and return value will be set up as if we called
2964  * btrfs_search_slot at that point in time with ins_len and cow both set to 0.
2965  */
2966 int btrfs_search_old_slot(struct btrfs_root *root, const struct btrfs_key *key,
2967                           struct btrfs_path *p, u64 time_seq)
2968 {
2969         struct btrfs_fs_info *fs_info = root->fs_info;
2970         struct extent_buffer *b;
2971         int slot;
2972         int ret;
2973         int err;
2974         int level;
2975         int lowest_unlock = 1;
2976         u8 lowest_level = 0;
2977         int prev_cmp = -1;
2978
2979         lowest_level = p->lowest_level;
2980         WARN_ON(p->nodes[0] != NULL);
2981
2982         if (p->search_commit_root) {
2983                 BUG_ON(time_seq);
2984                 return btrfs_search_slot(NULL, root, key, p, 0, 0);
2985         }
2986
2987 again:
2988         b = get_old_root(root, time_seq);
2989         level = btrfs_header_level(b);
2990         p->locks[level] = BTRFS_READ_LOCK;
2991
2992         while (b) {
2993                 level = btrfs_header_level(b);
2994                 p->nodes[level] = b;
2995                 btrfs_clear_path_blocking(p, NULL, 0);
2996
2997                 /*
2998                  * we have a lock on b and as long as we aren't changing
2999                  * the tree, there is no way to for the items in b to change.
3000                  * It is safe to drop the lock on our parent before we
3001                  * go through the expensive btree search on b.
3002                  */
3003                 btrfs_unlock_up_safe(p, level + 1);
3004
3005                 /*
3006                  * Since we can unwind ebs we want to do a real search every
3007                  * time.
3008                  */
3009                 prev_cmp = -1;
3010                 ret = key_search(b, key, level, &prev_cmp, &slot);
3011
3012                 if (level != 0) {
3013                         int dec = 0;
3014                         if (ret && slot > 0) {
3015                                 dec = 1;
3016                                 slot -= 1;
3017                         }
3018                         p->slots[level] = slot;
3019                         unlock_up(p, level, lowest_unlock, 0, NULL);
3020
3021                         if (level == lowest_level) {
3022                                 if (dec)
3023                                         p->slots[level]++;
3024                                 goto done;
3025                         }
3026
3027                         err = read_block_for_search(root, p, &b, level,
3028                                                     slot, key);
3029                         if (err == -EAGAIN)
3030                                 goto again;
3031                         if (err) {
3032                                 ret = err;
3033                                 goto done;
3034                         }
3035
3036                         level = btrfs_header_level(b);
3037                         err = btrfs_tree_read_lock_atomic(b);
3038                         if (!err) {
3039                                 btrfs_set_path_blocking(p);
3040                                 btrfs_tree_read_lock(b);
3041                                 btrfs_clear_path_blocking(p, b,
3042                                                           BTRFS_READ_LOCK);
3043                         }
3044                         b = tree_mod_log_rewind(fs_info, p, b, time_seq);
3045                         if (!b) {
3046                                 ret = -ENOMEM;
3047                                 goto done;
3048                         }
3049                         p->locks[level] = BTRFS_READ_LOCK;
3050                         p->nodes[level] = b;
3051                 } else {
3052                         p->slots[level] = slot;
3053                         unlock_up(p, level, lowest_unlock, 0, NULL);
3054                         goto done;
3055                 }
3056         }
3057         ret = 1;
3058 done:
3059         if (!p->leave_spinning)
3060                 btrfs_set_path_blocking(p);
3061         if (ret < 0)
3062                 btrfs_release_path(p);
3063
3064         return ret;
3065 }
3066
3067 /*
3068  * helper to use instead of search slot if no exact match is needed but
3069  * instead the next or previous item should be returned.
3070  * When find_higher is true, the next higher item is returned, the next lower
3071  * otherwise.
3072  * When return_any and find_higher are both true, and no higher item is found,
3073  * return the next lower instead.
3074  * When return_any is true and find_higher is false, and no lower item is found,
3075  * return the next higher instead.
3076  * It returns 0 if any item is found, 1 if none is found (tree empty), and
3077  * < 0 on error
3078  */
3079 int btrfs_search_slot_for_read(struct btrfs_root *root,
3080                                const struct btrfs_key *key,
3081                                struct btrfs_path *p, int find_higher,
3082                                int return_any)
3083 {
3084         int ret;
3085         struct extent_buffer *leaf;
3086
3087 again:
3088         ret = btrfs_search_slot(NULL, root, key, p, 0, 0);
3089         if (ret <= 0)
3090                 return ret;
3091         /*
3092          * a return value of 1 means the path is at the position where the
3093          * item should be inserted. Normally this is the next bigger item,
3094          * but in case the previous item is the last in a leaf, path points
3095          * to the first free slot in the previous leaf, i.e. at an invalid
3096          * item.
3097          */
3098         leaf = p->nodes[0];
3099
3100         if (find_higher) {
3101                 if (p->slots[0] >= btrfs_header_nritems(leaf)) {
3102                         ret = btrfs_next_leaf(root, p);
3103                         if (ret <= 0)
3104                                 return ret;
3105                         if (!return_any)
3106                                 return 1;
3107                         /*
3108                          * no higher item found, return the next
3109                          * lower instead
3110                          */
3111                         return_any = 0;
3112                         find_higher = 0;
3113                         btrfs_release_path(p);
3114                         goto again;
3115                 }
3116         } else {
3117                 if (p->slots[0] == 0) {
3118                         ret = btrfs_prev_leaf(root, p);
3119                         if (ret < 0)
3120                                 return ret;
3121                         if (!ret) {
3122                                 leaf = p->nodes[0];
3123                                 if (p->slots[0] == btrfs_header_nritems(leaf))
3124                                         p->slots[0]--;
3125                                 return 0;
3126                         }
3127                         if (!return_any)
3128                                 return 1;
3129                         /*
3130                          * no lower item found, return the next
3131                          * higher instead
3132                          */
3133                         return_any = 0;
3134                         find_higher = 1;
3135                         btrfs_release_path(p);
3136                         goto again;
3137                 } else {
3138                         --p->slots[0];
3139                 }