btrfs: fix root ref counts in error handling in btrfs_get_root_ref
authorJia-Ju Bai <baijiaju1990@gmail.com>
Thu, 24 Mar 2022 13:44:54 +0000 (06:44 -0700)
committerDavid Sterba <dsterba@suse.com>
Tue, 5 Apr 2022 22:50:47 +0000 (00:50 +0200)
In btrfs_get_root_ref(), when btrfs_insert_fs_root() fails,
btrfs_put_root() can happen for two reasons:

- the root already exists in the tree, in that case it returns the
  reference obtained in btrfs_lookup_fs_root()

- another error so the cleanup is done in the fail label

Calling btrfs_put_root() unconditionally would lead to double decrement
of the root reference possibly freeing it in the second case.

Reported-by: TOTE Robot <oslab@tsinghua.edu.cn>
Fixes: bc44d7c4b2b1 ("btrfs: push btrfs_grab_fs_root into btrfs_get_fs_root")
CC: stable@vger.kernel.org # 5.10+
Signed-off-by: Jia-Ju Bai <baijiaju1990@gmail.com>
Reviewed-by: David Sterba <dsterba@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
fs/btrfs/disk-io.c

index 09693ab4fde0f483853fd61fb84e063f502b9577..cebd7a78c964fcc76ecd3aa8c65af997a23ca91d 100644 (file)
@@ -1849,9 +1849,10 @@ again:
 
        ret = btrfs_insert_fs_root(fs_info, root);
        if (ret) {
-               btrfs_put_root(root);
-               if (ret == -EEXIST)
+               if (ret == -EEXIST) {
+                       btrfs_put_root(root);
                        goto again;
+               }
                goto fail;
        }
        return root;