0001
0002
0003
0004
0005
0006 #include <linux/sched.h>
0007 #include "ctree.h"
0008 #include "disk-io.h"
0009 #include "print-tree.h"
0010 #include "transaction.h"
0011 #include "locking.h"
0012
0013
0014
0015
0016
0017
0018
0019 int btrfs_defrag_leaves(struct btrfs_trans_handle *trans,
0020 struct btrfs_root *root)
0021 {
0022 struct btrfs_path *path = NULL;
0023 struct btrfs_key key;
0024 int ret = 0;
0025 int wret;
0026 int level;
0027 int next_key_ret = 0;
0028 u64 last_ret = 0;
0029
0030 if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
0031 goto out;
0032
0033 path = btrfs_alloc_path();
0034 if (!path)
0035 return -ENOMEM;
0036
0037 level = btrfs_header_level(root->node);
0038
0039 if (level == 0)
0040 goto out;
0041
0042 if (root->defrag_progress.objectid == 0) {
0043 struct extent_buffer *root_node;
0044 u32 nritems;
0045
0046 root_node = btrfs_lock_root_node(root);
0047 nritems = btrfs_header_nritems(root_node);
0048 root->defrag_max.objectid = 0;
0049
0050 btrfs_node_key_to_cpu(root_node, &root->defrag_max,
0051 nritems - 1);
0052 btrfs_tree_unlock(root_node);
0053 free_extent_buffer(root_node);
0054 memset(&key, 0, sizeof(key));
0055 } else {
0056 memcpy(&key, &root->defrag_progress, sizeof(key));
0057 }
0058
0059 path->keep_locks = 1;
0060
0061 ret = btrfs_search_forward(root, &key, path, BTRFS_OLDEST_GENERATION);
0062 if (ret < 0)
0063 goto out;
0064 if (ret > 0) {
0065 ret = 0;
0066 goto out;
0067 }
0068 btrfs_release_path(path);
0069
0070
0071
0072
0073
0074 path->lowest_level = 1;
0075 wret = btrfs_search_slot(trans, root, &key, path, 0, 1);
0076
0077 if (wret < 0) {
0078 ret = wret;
0079 goto out;
0080 }
0081 if (!path->nodes[1]) {
0082 ret = 0;
0083 goto out;
0084 }
0085
0086
0087
0088
0089
0090 BUG_ON(path->locks[1] == 0);
0091 ret = btrfs_realloc_node(trans, root,
0092 path->nodes[1], 0,
0093 &last_ret,
0094 &root->defrag_progress);
0095 if (ret) {
0096 WARN_ON(ret == -EAGAIN);
0097 goto out;
0098 }
0099
0100
0101
0102
0103
0104
0105
0106
0107
0108 path->slots[1] = btrfs_header_nritems(path->nodes[1]);
0109 next_key_ret = btrfs_find_next_key(root, path, &key, 1,
0110 BTRFS_OLDEST_GENERATION);
0111 if (next_key_ret == 0) {
0112 memcpy(&root->defrag_progress, &key, sizeof(key));
0113 ret = -EAGAIN;
0114 }
0115 out:
0116 btrfs_free_path(path);
0117 if (ret == -EAGAIN) {
0118 if (root->defrag_max.objectid > root->defrag_progress.objectid)
0119 goto done;
0120 if (root->defrag_max.type > root->defrag_progress.type)
0121 goto done;
0122 if (root->defrag_max.offset > root->defrag_progress.offset)
0123 goto done;
0124 ret = 0;
0125 }
0126 done:
0127 if (ret != -EAGAIN)
0128 memset(&root->defrag_progress, 0,
0129 sizeof(root->defrag_progress));
0130
0131 return ret;
0132 }