root/fs/btrfs/ioctl.c

/* [<][>][^][v][top][bottom][index][help] */

DEFINITIONS

This source file includes following definitions.
  1. btrfs_mask_fsflags_for_type
  2. btrfs_inode_flags_to_fsflags
  3. btrfs_sync_inode_flags_to_i_flags
  4. btrfs_ioctl_getflags
  5. check_fsflags
  6. btrfs_ioctl_setflags
  7. btrfs_inode_flags_to_xflags
  8. check_xflags
  9. btrfs_ioctl_fsgetxattr
  10. btrfs_ioctl_fssetxattr
  11. btrfs_ioctl_getversion
  12. btrfs_ioctl_fitrim
  13. btrfs_is_empty_uuid
  14. create_subvol
  15. create_snapshot
  16. btrfs_may_delete
  17. btrfs_may_create
  18. btrfs_mksubvol
  19. check_defrag_in_cache
  20. find_new_extents
  21. defrag_lookup_extent
  22. defrag_check_next_extent
  23. should_defrag_range
  24. cluster_pages_for_defrag
  25. btrfs_defrag_file
  26. btrfs_ioctl_resize
  27. btrfs_ioctl_snap_create_transid
  28. btrfs_ioctl_snap_create
  29. btrfs_ioctl_snap_create_v2
  30. btrfs_ioctl_subvol_getflags
  31. btrfs_ioctl_subvol_setflags
  32. key_in_sk
  33. copy_to_sk
  34. search_ioctl
  35. btrfs_ioctl_tree_search
  36. btrfs_ioctl_tree_search_v2
  37. btrfs_search_path_in_tree
  38. btrfs_search_path_in_tree_user
  39. btrfs_ioctl_ino_lookup
  40. btrfs_ioctl_ino_lookup_user
  41. btrfs_ioctl_get_subvol_info
  42. btrfs_ioctl_get_subvol_rootref
  43. btrfs_ioctl_snap_destroy
  44. btrfs_ioctl_defrag
  45. btrfs_ioctl_add_dev
  46. btrfs_ioctl_rm_dev_v2
  47. btrfs_ioctl_rm_dev
  48. btrfs_ioctl_fs_info
  49. btrfs_ioctl_dev_info
  50. btrfs_double_extent_unlock
  51. btrfs_double_extent_lock
  52. btrfs_extent_same_range
  53. btrfs_extent_same
  54. clone_finish_inode_update
  55. clone_copy_inline_extent
  56. btrfs_clone
  57. btrfs_clone_files
  58. btrfs_remap_file_range_prep
  59. btrfs_remap_file_range
  60. btrfs_ioctl_default_subvol
  61. get_block_group_info
  62. btrfs_ioctl_space_info
  63. btrfs_ioctl_start_sync
  64. btrfs_ioctl_wait_sync
  65. btrfs_ioctl_scrub
  66. btrfs_ioctl_scrub_cancel
  67. btrfs_ioctl_scrub_progress
  68. btrfs_ioctl_get_dev_stats
  69. btrfs_ioctl_dev_replace
  70. btrfs_ioctl_ino_to_path
  71. build_ino_list
  72. btrfs_ioctl_logical_to_ino
  73. btrfs_update_ioctl_balance_args
  74. btrfs_ioctl_balance
  75. btrfs_ioctl_balance_ctl
  76. btrfs_ioctl_balance_progress
  77. btrfs_ioctl_quota_ctl
  78. btrfs_ioctl_qgroup_assign
  79. btrfs_ioctl_qgroup_create
  80. btrfs_ioctl_qgroup_limit
  81. btrfs_ioctl_quota_rescan
  82. btrfs_ioctl_quota_rescan_status
  83. btrfs_ioctl_quota_rescan_wait
  84. _btrfs_ioctl_set_received_subvol
  85. btrfs_ioctl_set_received_subvol_32
  86. btrfs_ioctl_set_received_subvol
  87. btrfs_ioctl_get_fslabel
  88. btrfs_ioctl_set_fslabel
  89. btrfs_ioctl_get_supported_features
  90. btrfs_ioctl_get_features
  91. check_feature_bits
  92. btrfs_ioctl_set_features
  93. _btrfs_ioctl_send
  94. btrfs_ioctl
  95. btrfs_compat_ioctl

   1 // SPDX-License-Identifier: GPL-2.0
   2 /*
   3  * Copyright (C) 2007 Oracle.  All rights reserved.
   4  */
   5 
   6 #include <linux/kernel.h>
   7 #include <linux/bio.h>
   8 #include <linux/file.h>
   9 #include <linux/fs.h>
  10 #include <linux/fsnotify.h>
  11 #include <linux/pagemap.h>
  12 #include <linux/highmem.h>
  13 #include <linux/time.h>
  14 #include <linux/string.h>
  15 #include <linux/backing-dev.h>
  16 #include <linux/mount.h>
  17 #include <linux/namei.h>
  18 #include <linux/writeback.h>
  19 #include <linux/compat.h>
  20 #include <linux/security.h>
  21 #include <linux/xattr.h>
  22 #include <linux/mm.h>
  23 #include <linux/slab.h>
  24 #include <linux/blkdev.h>
  25 #include <linux/uuid.h>
  26 #include <linux/btrfs.h>
  27 #include <linux/uaccess.h>
  28 #include <linux/iversion.h>
  29 #include "ctree.h"
  30 #include "disk-io.h"
  31 #include "transaction.h"
  32 #include "btrfs_inode.h"
  33 #include "print-tree.h"
  34 #include "volumes.h"
  35 #include "locking.h"
  36 #include "inode-map.h"
  37 #include "backref.h"
  38 #include "rcu-string.h"
  39 #include "send.h"
  40 #include "dev-replace.h"
  41 #include "props.h"
  42 #include "sysfs.h"
  43 #include "qgroup.h"
  44 #include "tree-log.h"
  45 #include "compression.h"
  46 #include "space-info.h"
  47 #include "delalloc-space.h"
  48 #include "block-group.h"
  49 
  50 #ifdef CONFIG_64BIT
  51 /* If we have a 32-bit userspace and 64-bit kernel, then the UAPI
  52  * structures are incorrect, as the timespec structure from userspace
  53  * is 4 bytes too small. We define these alternatives here to teach
  54  * the kernel about the 32-bit struct packing.
  55  */
  56 struct btrfs_ioctl_timespec_32 {
  57         __u64 sec;
  58         __u32 nsec;
  59 } __attribute__ ((__packed__));
  60 
  61 struct btrfs_ioctl_received_subvol_args_32 {
  62         char    uuid[BTRFS_UUID_SIZE];  /* in */
  63         __u64   stransid;               /* in */
  64         __u64   rtransid;               /* out */
  65         struct btrfs_ioctl_timespec_32 stime; /* in */
  66         struct btrfs_ioctl_timespec_32 rtime; /* out */
  67         __u64   flags;                  /* in */
  68         __u64   reserved[16];           /* in */
  69 } __attribute__ ((__packed__));
  70 
  71 #define BTRFS_IOC_SET_RECEIVED_SUBVOL_32 _IOWR(BTRFS_IOCTL_MAGIC, 37, \
  72                                 struct btrfs_ioctl_received_subvol_args_32)
  73 #endif
  74 
  75 #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
  76 struct btrfs_ioctl_send_args_32 {
  77         __s64 send_fd;                  /* in */
  78         __u64 clone_sources_count;      /* in */
  79         compat_uptr_t clone_sources;    /* in */
  80         __u64 parent_root;              /* in */
  81         __u64 flags;                    /* in */
  82         __u64 reserved[4];              /* in */
  83 } __attribute__ ((__packed__));
  84 
  85 #define BTRFS_IOC_SEND_32 _IOW(BTRFS_IOCTL_MAGIC, 38, \
  86                                struct btrfs_ioctl_send_args_32)
  87 #endif
  88 
  89 static int btrfs_clone(struct inode *src, struct inode *inode,
  90                        u64 off, u64 olen, u64 olen_aligned, u64 destoff,
  91                        int no_time_update);
  92 
  93 /* Mask out flags that are inappropriate for the given type of inode. */
  94 static unsigned int btrfs_mask_fsflags_for_type(struct inode *inode,
  95                 unsigned int flags)
  96 {
  97         if (S_ISDIR(inode->i_mode))
  98                 return flags;
  99         else if (S_ISREG(inode->i_mode))
 100                 return flags & ~FS_DIRSYNC_FL;
 101         else
 102                 return flags & (FS_NODUMP_FL | FS_NOATIME_FL);
 103 }
 104 
 105 /*
 106  * Export internal inode flags to the format expected by the FS_IOC_GETFLAGS
 107  * ioctl.
 108  */
 109 static unsigned int btrfs_inode_flags_to_fsflags(unsigned int flags)
 110 {
 111         unsigned int iflags = 0;
 112 
 113         if (flags & BTRFS_INODE_SYNC)
 114                 iflags |= FS_SYNC_FL;
 115         if (flags & BTRFS_INODE_IMMUTABLE)
 116                 iflags |= FS_IMMUTABLE_FL;
 117         if (flags & BTRFS_INODE_APPEND)
 118                 iflags |= FS_APPEND_FL;
 119         if (flags & BTRFS_INODE_NODUMP)
 120                 iflags |= FS_NODUMP_FL;
 121         if (flags & BTRFS_INODE_NOATIME)
 122                 iflags |= FS_NOATIME_FL;
 123         if (flags & BTRFS_INODE_DIRSYNC)
 124                 iflags |= FS_DIRSYNC_FL;
 125         if (flags & BTRFS_INODE_NODATACOW)
 126                 iflags |= FS_NOCOW_FL;
 127 
 128         if (flags & BTRFS_INODE_NOCOMPRESS)
 129                 iflags |= FS_NOCOMP_FL;
 130         else if (flags & BTRFS_INODE_COMPRESS)
 131                 iflags |= FS_COMPR_FL;
 132 
 133         return iflags;
 134 }
 135 
 136 /*
 137  * Update inode->i_flags based on the btrfs internal flags.
 138  */
 139 void btrfs_sync_inode_flags_to_i_flags(struct inode *inode)
 140 {
 141         struct btrfs_inode *binode = BTRFS_I(inode);
 142         unsigned int new_fl = 0;
 143 
 144         if (binode->flags & BTRFS_INODE_SYNC)
 145                 new_fl |= S_SYNC;
 146         if (binode->flags & BTRFS_INODE_IMMUTABLE)
 147                 new_fl |= S_IMMUTABLE;
 148         if (binode->flags & BTRFS_INODE_APPEND)
 149                 new_fl |= S_APPEND;
 150         if (binode->flags & BTRFS_INODE_NOATIME)
 151                 new_fl |= S_NOATIME;
 152         if (binode->flags & BTRFS_INODE_DIRSYNC)
 153                 new_fl |= S_DIRSYNC;
 154 
 155         set_mask_bits(&inode->i_flags,
 156                       S_SYNC | S_APPEND | S_IMMUTABLE | S_NOATIME | S_DIRSYNC,
 157                       new_fl);
 158 }
 159 
 160 static int btrfs_ioctl_getflags(struct file *file, void __user *arg)
 161 {
 162         struct btrfs_inode *binode = BTRFS_I(file_inode(file));
 163         unsigned int flags = btrfs_inode_flags_to_fsflags(binode->flags);
 164 
 165         if (copy_to_user(arg, &flags, sizeof(flags)))
 166                 return -EFAULT;
 167         return 0;
 168 }
 169 
 170 /* Check if @flags are a supported and valid set of FS_*_FL flags */
 171 static int check_fsflags(unsigned int flags)
 172 {
 173         if (flags & ~(FS_IMMUTABLE_FL | FS_APPEND_FL | \
 174                       FS_NOATIME_FL | FS_NODUMP_FL | \
 175                       FS_SYNC_FL | FS_DIRSYNC_FL | \
 176                       FS_NOCOMP_FL | FS_COMPR_FL |
 177                       FS_NOCOW_FL))
 178                 return -EOPNOTSUPP;
 179 
 180         if ((flags & FS_NOCOMP_FL) && (flags & FS_COMPR_FL))
 181                 return -EINVAL;
 182 
 183         return 0;
 184 }
 185 
 186 static int btrfs_ioctl_setflags(struct file *file, void __user *arg)
 187 {
 188         struct inode *inode = file_inode(file);
 189         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
 190         struct btrfs_inode *binode = BTRFS_I(inode);
 191         struct btrfs_root *root = binode->root;
 192         struct btrfs_trans_handle *trans;
 193         unsigned int fsflags, old_fsflags;
 194         int ret;
 195         const char *comp = NULL;
 196         u32 binode_flags = binode->flags;
 197 
 198         if (!inode_owner_or_capable(inode))
 199                 return -EPERM;
 200 
 201         if (btrfs_root_readonly(root))
 202                 return -EROFS;
 203 
 204         if (copy_from_user(&fsflags, arg, sizeof(fsflags)))
 205                 return -EFAULT;
 206 
 207         ret = check_fsflags(fsflags);
 208         if (ret)
 209                 return ret;
 210 
 211         ret = mnt_want_write_file(file);
 212         if (ret)
 213                 return ret;
 214 
 215         inode_lock(inode);
 216 
 217         fsflags = btrfs_mask_fsflags_for_type(inode, fsflags);
 218         old_fsflags = btrfs_inode_flags_to_fsflags(binode->flags);
 219         ret = vfs_ioc_setflags_prepare(inode, old_fsflags, fsflags);
 220         if (ret)
 221                 goto out_unlock;
 222 
 223         if (fsflags & FS_SYNC_FL)
 224                 binode_flags |= BTRFS_INODE_SYNC;
 225         else
 226                 binode_flags &= ~BTRFS_INODE_SYNC;
 227         if (fsflags & FS_IMMUTABLE_FL)
 228                 binode_flags |= BTRFS_INODE_IMMUTABLE;
 229         else
 230                 binode_flags &= ~BTRFS_INODE_IMMUTABLE;
 231         if (fsflags & FS_APPEND_FL)
 232                 binode_flags |= BTRFS_INODE_APPEND;
 233         else
 234                 binode_flags &= ~BTRFS_INODE_APPEND;
 235         if (fsflags & FS_NODUMP_FL)
 236                 binode_flags |= BTRFS_INODE_NODUMP;
 237         else
 238                 binode_flags &= ~BTRFS_INODE_NODUMP;
 239         if (fsflags & FS_NOATIME_FL)
 240                 binode_flags |= BTRFS_INODE_NOATIME;
 241         else
 242                 binode_flags &= ~BTRFS_INODE_NOATIME;
 243         if (fsflags & FS_DIRSYNC_FL)
 244                 binode_flags |= BTRFS_INODE_DIRSYNC;
 245         else
 246                 binode_flags &= ~BTRFS_INODE_DIRSYNC;
 247         if (fsflags & FS_NOCOW_FL) {
 248                 if (S_ISREG(inode->i_mode)) {
 249                         /*
 250                          * It's safe to turn csums off here, no extents exist.
 251                          * Otherwise we want the flag to reflect the real COW
 252                          * status of the file and will not set it.
 253                          */
 254                         if (inode->i_size == 0)
 255                                 binode_flags |= BTRFS_INODE_NODATACOW |
 256                                                 BTRFS_INODE_NODATASUM;
 257                 } else {
 258                         binode_flags |= BTRFS_INODE_NODATACOW;
 259                 }
 260         } else {
 261                 /*
 262                  * Revert back under same assumptions as above
 263                  */
 264                 if (S_ISREG(inode->i_mode)) {
 265                         if (inode->i_size == 0)
 266                                 binode_flags &= ~(BTRFS_INODE_NODATACOW |
 267                                                   BTRFS_INODE_NODATASUM);
 268                 } else {
 269                         binode_flags &= ~BTRFS_INODE_NODATACOW;
 270                 }
 271         }
 272 
 273         /*
 274          * The COMPRESS flag can only be changed by users, while the NOCOMPRESS
 275          * flag may be changed automatically if compression code won't make
 276          * things smaller.
 277          */
 278         if (fsflags & FS_NOCOMP_FL) {
 279                 binode_flags &= ~BTRFS_INODE_COMPRESS;
 280                 binode_flags |= BTRFS_INODE_NOCOMPRESS;
 281         } else if (fsflags & FS_COMPR_FL) {
 282 
 283                 if (IS_SWAPFILE(inode)) {
 284                         ret = -ETXTBSY;
 285                         goto out_unlock;
 286                 }
 287 
 288                 binode_flags |= BTRFS_INODE_COMPRESS;
 289                 binode_flags &= ~BTRFS_INODE_NOCOMPRESS;
 290 
 291                 comp = btrfs_compress_type2str(fs_info->compress_type);
 292                 if (!comp || comp[0] == 0)
 293                         comp = btrfs_compress_type2str(BTRFS_COMPRESS_ZLIB);
 294         } else {
 295                 binode_flags &= ~(BTRFS_INODE_COMPRESS | BTRFS_INODE_NOCOMPRESS);
 296         }
 297 
 298         /*
 299          * 1 for inode item
 300          * 2 for properties
 301          */
 302         trans = btrfs_start_transaction(root, 3);
 303         if (IS_ERR(trans)) {
 304                 ret = PTR_ERR(trans);
 305                 goto out_unlock;
 306         }
 307 
 308         if (comp) {
 309                 ret = btrfs_set_prop(trans, inode, "btrfs.compression", comp,
 310                                      strlen(comp), 0);
 311                 if (ret) {
 312                         btrfs_abort_transaction(trans, ret);
 313                         goto out_end_trans;
 314                 }
 315         } else {
 316                 ret = btrfs_set_prop(trans, inode, "btrfs.compression", NULL,
 317                                      0, 0);
 318                 if (ret && ret != -ENODATA) {
 319                         btrfs_abort_transaction(trans, ret);
 320                         goto out_end_trans;
 321                 }
 322         }
 323 
 324         binode->flags = binode_flags;
 325         btrfs_sync_inode_flags_to_i_flags(inode);
 326         inode_inc_iversion(inode);
 327         inode->i_ctime = current_time(inode);
 328         ret = btrfs_update_inode(trans, root, inode);
 329 
 330  out_end_trans:
 331         btrfs_end_transaction(trans);
 332  out_unlock:
 333         inode_unlock(inode);
 334         mnt_drop_write_file(file);
 335         return ret;
 336 }
 337 
 338 /*
 339  * Translate btrfs internal inode flags to xflags as expected by the
 340  * FS_IOC_FSGETXATT ioctl. Filter only the supported ones, unknown flags are
 341  * silently dropped.
 342  */
 343 static unsigned int btrfs_inode_flags_to_xflags(unsigned int flags)
 344 {
 345         unsigned int xflags = 0;
 346 
 347         if (flags & BTRFS_INODE_APPEND)
 348                 xflags |= FS_XFLAG_APPEND;
 349         if (flags & BTRFS_INODE_IMMUTABLE)
 350                 xflags |= FS_XFLAG_IMMUTABLE;
 351         if (flags & BTRFS_INODE_NOATIME)
 352                 xflags |= FS_XFLAG_NOATIME;
 353         if (flags & BTRFS_INODE_NODUMP)
 354                 xflags |= FS_XFLAG_NODUMP;
 355         if (flags & BTRFS_INODE_SYNC)
 356                 xflags |= FS_XFLAG_SYNC;
 357 
 358         return xflags;
 359 }
 360 
 361 /* Check if @flags are a supported and valid set of FS_XFLAGS_* flags */
 362 static int check_xflags(unsigned int flags)
 363 {
 364         if (flags & ~(FS_XFLAG_APPEND | FS_XFLAG_IMMUTABLE | FS_XFLAG_NOATIME |
 365                       FS_XFLAG_NODUMP | FS_XFLAG_SYNC))
 366                 return -EOPNOTSUPP;
 367         return 0;
 368 }
 369 
 370 /*
 371  * Set the xflags from the internal inode flags. The remaining items of fsxattr
 372  * are zeroed.
 373  */
 374 static int btrfs_ioctl_fsgetxattr(struct file *file, void __user *arg)
 375 {
 376         struct btrfs_inode *binode = BTRFS_I(file_inode(file));
 377         struct fsxattr fa;
 378 
 379         simple_fill_fsxattr(&fa, btrfs_inode_flags_to_xflags(binode->flags));
 380         if (copy_to_user(arg, &fa, sizeof(fa)))
 381                 return -EFAULT;
 382 
 383         return 0;
 384 }
 385 
 386 static int btrfs_ioctl_fssetxattr(struct file *file, void __user *arg)
 387 {
 388         struct inode *inode = file_inode(file);
 389         struct btrfs_inode *binode = BTRFS_I(inode);
 390         struct btrfs_root *root = binode->root;
 391         struct btrfs_trans_handle *trans;
 392         struct fsxattr fa, old_fa;
 393         unsigned old_flags;
 394         unsigned old_i_flags;
 395         int ret = 0;
 396 
 397         if (!inode_owner_or_capable(inode))
 398                 return -EPERM;
 399 
 400         if (btrfs_root_readonly(root))
 401                 return -EROFS;
 402 
 403         if (copy_from_user(&fa, arg, sizeof(fa)))
 404                 return -EFAULT;
 405 
 406         ret = check_xflags(fa.fsx_xflags);
 407         if (ret)
 408                 return ret;
 409 
 410         if (fa.fsx_extsize != 0 || fa.fsx_projid != 0 || fa.fsx_cowextsize != 0)
 411                 return -EOPNOTSUPP;
 412 
 413         ret = mnt_want_write_file(file);
 414         if (ret)
 415                 return ret;
 416 
 417         inode_lock(inode);
 418 
 419         old_flags = binode->flags;
 420         old_i_flags = inode->i_flags;
 421 
 422         simple_fill_fsxattr(&old_fa,
 423                             btrfs_inode_flags_to_xflags(binode->flags));
 424         ret = vfs_ioc_fssetxattr_check(inode, &old_fa, &fa);
 425         if (ret)
 426                 goto out_unlock;
 427 
 428         if (fa.fsx_xflags & FS_XFLAG_SYNC)
 429                 binode->flags |= BTRFS_INODE_SYNC;
 430         else
 431                 binode->flags &= ~BTRFS_INODE_SYNC;
 432         if (fa.fsx_xflags & FS_XFLAG_IMMUTABLE)
 433                 binode->flags |= BTRFS_INODE_IMMUTABLE;
 434         else
 435                 binode->flags &= ~BTRFS_INODE_IMMUTABLE;
 436         if (fa.fsx_xflags & FS_XFLAG_APPEND)
 437                 binode->flags |= BTRFS_INODE_APPEND;
 438         else
 439                 binode->flags &= ~BTRFS_INODE_APPEND;
 440         if (fa.fsx_xflags & FS_XFLAG_NODUMP)
 441                 binode->flags |= BTRFS_INODE_NODUMP;
 442         else
 443                 binode->flags &= ~BTRFS_INODE_NODUMP;
 444         if (fa.fsx_xflags & FS_XFLAG_NOATIME)
 445                 binode->flags |= BTRFS_INODE_NOATIME;
 446         else
 447                 binode->flags &= ~BTRFS_INODE_NOATIME;
 448 
 449         /* 1 item for the inode */
 450         trans = btrfs_start_transaction(root, 1);
 451         if (IS_ERR(trans)) {
 452                 ret = PTR_ERR(trans);
 453                 goto out_unlock;
 454         }
 455 
 456         btrfs_sync_inode_flags_to_i_flags(inode);
 457         inode_inc_iversion(inode);
 458         inode->i_ctime = current_time(inode);
 459         ret = btrfs_update_inode(trans, root, inode);
 460 
 461         btrfs_end_transaction(trans);
 462 
 463 out_unlock:
 464         if (ret) {
 465                 binode->flags = old_flags;
 466                 inode->i_flags = old_i_flags;
 467         }
 468 
 469         inode_unlock(inode);
 470         mnt_drop_write_file(file);
 471 
 472         return ret;
 473 }
 474 
 475 static int btrfs_ioctl_getversion(struct file *file, int __user *arg)
 476 {
 477         struct inode *inode = file_inode(file);
 478 
 479         return put_user(inode->i_generation, arg);
 480 }
 481 
 482 static noinline int btrfs_ioctl_fitrim(struct file *file, void __user *arg)
 483 {
 484         struct inode *inode = file_inode(file);
 485         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
 486         struct btrfs_device *device;
 487         struct request_queue *q;
 488         struct fstrim_range range;
 489         u64 minlen = ULLONG_MAX;
 490         u64 num_devices = 0;
 491         int ret;
 492 
 493         if (!capable(CAP_SYS_ADMIN))
 494                 return -EPERM;
 495 
 496         /*
 497          * If the fs is mounted with nologreplay, which requires it to be
 498          * mounted in RO mode as well, we can not allow discard on free space
 499          * inside block groups, because log trees refer to extents that are not
 500          * pinned in a block group's free space cache (pinning the extents is
 501          * precisely the first phase of replaying a log tree).
 502          */
 503         if (btrfs_test_opt(fs_info, NOLOGREPLAY))
 504                 return -EROFS;
 505 
 506         rcu_read_lock();
 507         list_for_each_entry_rcu(device, &fs_info->fs_devices->devices,
 508                                 dev_list) {
 509                 if (!device->bdev)
 510                         continue;
 511                 q = bdev_get_queue(device->bdev);
 512                 if (blk_queue_discard(q)) {
 513                         num_devices++;
 514                         minlen = min_t(u64, q->limits.discard_granularity,
 515                                      minlen);
 516                 }
 517         }
 518         rcu_read_unlock();
 519 
 520         if (!num_devices)
 521                 return -EOPNOTSUPP;
 522         if (copy_from_user(&range, arg, sizeof(range)))
 523                 return -EFAULT;
 524 
 525         /*
 526          * NOTE: Don't truncate the range using super->total_bytes.  Bytenr of
 527          * block group is in the logical address space, which can be any
 528          * sectorsize aligned bytenr in  the range [0, U64_MAX].
 529          */
 530         if (range.len < fs_info->sb->s_blocksize)
 531                 return -EINVAL;
 532 
 533         range.minlen = max(range.minlen, minlen);
 534         ret = btrfs_trim_fs(fs_info, &range);
 535         if (ret < 0)
 536                 return ret;
 537 
 538         if (copy_to_user(arg, &range, sizeof(range)))
 539                 return -EFAULT;
 540 
 541         return 0;
 542 }
 543 
 544 int btrfs_is_empty_uuid(u8 *uuid)
 545 {
 546         int i;
 547 
 548         for (i = 0; i < BTRFS_UUID_SIZE; i++) {
 549                 if (uuid[i])
 550                         return 0;
 551         }
 552         return 1;
 553 }
 554 
 555 static noinline int create_subvol(struct inode *dir,
 556                                   struct dentry *dentry,
 557                                   const char *name, int namelen,
 558                                   u64 *async_transid,
 559                                   struct btrfs_qgroup_inherit *inherit)
 560 {
 561         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
 562         struct btrfs_trans_handle *trans;
 563         struct btrfs_key key;
 564         struct btrfs_root_item *root_item;
 565         struct btrfs_inode_item *inode_item;
 566         struct extent_buffer *leaf;
 567         struct btrfs_root *root = BTRFS_I(dir)->root;
 568         struct btrfs_root *new_root;
 569         struct btrfs_block_rsv block_rsv;
 570         struct timespec64 cur_time = current_time(dir);
 571         struct inode *inode;
 572         int ret;
 573         int err;
 574         u64 objectid;
 575         u64 new_dirid = BTRFS_FIRST_FREE_OBJECTID;
 576         u64 index = 0;
 577         uuid_le new_uuid;
 578 
 579         root_item = kzalloc(sizeof(*root_item), GFP_KERNEL);
 580         if (!root_item)
 581                 return -ENOMEM;
 582 
 583         ret = btrfs_find_free_objectid(fs_info->tree_root, &objectid);
 584         if (ret)
 585                 goto fail_free;
 586 
 587         /*
 588          * Don't create subvolume whose level is not zero. Or qgroup will be
 589          * screwed up since it assumes subvolume qgroup's level to be 0.
 590          */
 591         if (btrfs_qgroup_level(objectid)) {
 592                 ret = -ENOSPC;
 593                 goto fail_free;
 594         }
 595 
 596         btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
 597         /*
 598          * The same as the snapshot creation, please see the comment
 599          * of create_snapshot().
 600          */
 601         ret = btrfs_subvolume_reserve_metadata(root, &block_rsv, 8, false);
 602         if (ret)
 603                 goto fail_free;
 604 
 605         trans = btrfs_start_transaction(root, 0);
 606         if (IS_ERR(trans)) {
 607                 ret = PTR_ERR(trans);
 608                 btrfs_subvolume_release_metadata(fs_info, &block_rsv);
 609                 goto fail_free;
 610         }
 611         trans->block_rsv = &block_rsv;
 612         trans->bytes_reserved = block_rsv.size;
 613 
 614         ret = btrfs_qgroup_inherit(trans, 0, objectid, inherit);
 615         if (ret)
 616                 goto fail;
 617 
 618         leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0);
 619         if (IS_ERR(leaf)) {
 620                 ret = PTR_ERR(leaf);
 621                 goto fail;
 622         }
 623 
 624         btrfs_mark_buffer_dirty(leaf);
 625 
 626         inode_item = &root_item->inode;
 627         btrfs_set_stack_inode_generation(inode_item, 1);
 628         btrfs_set_stack_inode_size(inode_item, 3);
 629         btrfs_set_stack_inode_nlink(inode_item, 1);
 630         btrfs_set_stack_inode_nbytes(inode_item,
 631                                      fs_info->nodesize);
 632         btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
 633 
 634         btrfs_set_root_flags(root_item, 0);
 635         btrfs_set_root_limit(root_item, 0);
 636         btrfs_set_stack_inode_flags(inode_item, BTRFS_INODE_ROOT_ITEM_INIT);
 637 
 638         btrfs_set_root_bytenr(root_item, leaf->start);
 639         btrfs_set_root_generation(root_item, trans->transid);
 640         btrfs_set_root_level(root_item, 0);
 641         btrfs_set_root_refs(root_item, 1);
 642         btrfs_set_root_used(root_item, leaf->len);
 643         btrfs_set_root_last_snapshot(root_item, 0);
 644 
 645         btrfs_set_root_generation_v2(root_item,
 646                         btrfs_root_generation(root_item));
 647         uuid_le_gen(&new_uuid);
 648         memcpy(root_item->uuid, new_uuid.b, BTRFS_UUID_SIZE);
 649         btrfs_set_stack_timespec_sec(&root_item->otime, cur_time.tv_sec);
 650         btrfs_set_stack_timespec_nsec(&root_item->otime, cur_time.tv_nsec);
 651         root_item->ctime = root_item->otime;
 652         btrfs_set_root_ctransid(root_item, trans->transid);
 653         btrfs_set_root_otransid(root_item, trans->transid);
 654 
 655         btrfs_tree_unlock(leaf);
 656         free_extent_buffer(leaf);
 657         leaf = NULL;
 658 
 659         btrfs_set_root_dirid(root_item, new_dirid);
 660 
 661         key.objectid = objectid;
 662         key.offset = 0;
 663         key.type = BTRFS_ROOT_ITEM_KEY;
 664         ret = btrfs_insert_root(trans, fs_info->tree_root, &key,
 665                                 root_item);
 666         if (ret)
 667                 goto fail;
 668 
 669         key.offset = (u64)-1;
 670         new_root = btrfs_read_fs_root_no_name(fs_info, &key);
 671         if (IS_ERR(new_root)) {
 672                 ret = PTR_ERR(new_root);
 673                 btrfs_abort_transaction(trans, ret);
 674                 goto fail;
 675         }
 676 
 677         btrfs_record_root_in_trans(trans, new_root);
 678 
 679         ret = btrfs_create_subvol_root(trans, new_root, root, new_dirid);
 680         if (ret) {
 681                 /* We potentially lose an unused inode item here */
 682                 btrfs_abort_transaction(trans, ret);
 683                 goto fail;
 684         }
 685 
 686         mutex_lock(&new_root->objectid_mutex);
 687         new_root->highest_objectid = new_dirid;
 688         mutex_unlock(&new_root->objectid_mutex);
 689 
 690         /*
 691          * insert the directory item
 692          */
 693         ret = btrfs_set_inode_index(BTRFS_I(dir), &index);
 694         if (ret) {
 695                 btrfs_abort_transaction(trans, ret);
 696                 goto fail;
 697         }
 698 
 699         ret = btrfs_insert_dir_item(trans, name, namelen, BTRFS_I(dir), &key,
 700                                     BTRFS_FT_DIR, index);
 701         if (ret) {
 702                 btrfs_abort_transaction(trans, ret);
 703                 goto fail;
 704         }
 705 
 706         btrfs_i_size_write(BTRFS_I(dir), dir->i_size + namelen * 2);
 707         ret = btrfs_update_inode(trans, root, dir);
 708         if (ret) {
 709                 btrfs_abort_transaction(trans, ret);
 710                 goto fail;
 711         }
 712 
 713         ret = btrfs_add_root_ref(trans, objectid, root->root_key.objectid,
 714                                  btrfs_ino(BTRFS_I(dir)), index, name, namelen);
 715         if (ret) {
 716                 btrfs_abort_transaction(trans, ret);
 717                 goto fail;
 718         }
 719 
 720         ret = btrfs_uuid_tree_add(trans, root_item->uuid,
 721                                   BTRFS_UUID_KEY_SUBVOL, objectid);
 722         if (ret)
 723                 btrfs_abort_transaction(trans, ret);
 724 
 725 fail:
 726         kfree(root_item);
 727         trans->block_rsv = NULL;
 728         trans->bytes_reserved = 0;
 729         btrfs_subvolume_release_metadata(fs_info, &block_rsv);
 730 
 731         if (async_transid) {
 732                 *async_transid = trans->transid;
 733                 err = btrfs_commit_transaction_async(trans, 1);
 734                 if (err)
 735                         err = btrfs_commit_transaction(trans);
 736         } else {
 737                 err = btrfs_commit_transaction(trans);
 738         }
 739         if (err && !ret)
 740                 ret = err;
 741 
 742         if (!ret) {
 743                 inode = btrfs_lookup_dentry(dir, dentry);
 744                 if (IS_ERR(inode))
 745                         return PTR_ERR(inode);
 746                 d_instantiate(dentry, inode);
 747         }
 748         return ret;
 749 
 750 fail_free:
 751         kfree(root_item);
 752         return ret;
 753 }
 754 
 755 static int create_snapshot(struct btrfs_root *root, struct inode *dir,
 756                            struct dentry *dentry,
 757                            u64 *async_transid, bool readonly,
 758                            struct btrfs_qgroup_inherit *inherit)
 759 {
 760         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
 761         struct inode *inode;
 762         struct btrfs_pending_snapshot *pending_snapshot;
 763         struct btrfs_trans_handle *trans;
 764         int ret;
 765         bool snapshot_force_cow = false;
 766 
 767         if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state))
 768                 return -EINVAL;
 769 
 770         if (atomic_read(&root->nr_swapfiles)) {
 771                 btrfs_warn(fs_info,
 772                            "cannot snapshot subvolume with active swapfile");
 773                 return -ETXTBSY;
 774         }
 775 
 776         pending_snapshot = kzalloc(sizeof(*pending_snapshot), GFP_KERNEL);
 777         if (!pending_snapshot)
 778                 return -ENOMEM;
 779 
 780         pending_snapshot->root_item = kzalloc(sizeof(struct btrfs_root_item),
 781                         GFP_KERNEL);
 782         pending_snapshot->path = btrfs_alloc_path();
 783         if (!pending_snapshot->root_item || !pending_snapshot->path) {
 784                 ret = -ENOMEM;
 785                 goto free_pending;
 786         }
 787 
 788         /*
 789          * Force new buffered writes to reserve space even when NOCOW is
 790          * possible. This is to avoid later writeback (running dealloc) to
 791          * fallback to COW mode and unexpectedly fail with ENOSPC.
 792          */
 793         atomic_inc(&root->will_be_snapshotted);
 794         smp_mb__after_atomic();
 795         /* wait for no snapshot writes */
 796         wait_event(root->subv_writers->wait,
 797                    percpu_counter_sum(&root->subv_writers->counter) == 0);
 798 
 799         ret = btrfs_start_delalloc_snapshot(root);
 800         if (ret)
 801                 goto dec_and_free;
 802 
 803         /*
 804          * All previous writes have started writeback in NOCOW mode, so now
 805          * we force future writes to fallback to COW mode during snapshot
 806          * creation.
 807          */
 808         atomic_inc(&root->snapshot_force_cow);
 809         snapshot_force_cow = true;
 810 
 811         btrfs_wait_ordered_extents(root, U64_MAX, 0, (u64)-1);
 812 
 813         btrfs_init_block_rsv(&pending_snapshot->block_rsv,
 814                              BTRFS_BLOCK_RSV_TEMP);
 815         /*
 816          * 1 - parent dir inode
 817          * 2 - dir entries
 818          * 1 - root item
 819          * 2 - root ref/backref
 820          * 1 - root of snapshot
 821          * 1 - UUID item
 822          */
 823         ret = btrfs_subvolume_reserve_metadata(BTRFS_I(dir)->root,
 824                                         &pending_snapshot->block_rsv, 8,
 825                                         false);
 826         if (ret)
 827                 goto dec_and_free;
 828 
 829         pending_snapshot->dentry = dentry;
 830         pending_snapshot->root = root;
 831         pending_snapshot->readonly = readonly;
 832         pending_snapshot->dir = dir;
 833         pending_snapshot->inherit = inherit;
 834 
 835         trans = btrfs_start_transaction(root, 0);
 836         if (IS_ERR(trans)) {
 837                 ret = PTR_ERR(trans);
 838                 goto fail;
 839         }
 840 
 841         spin_lock(&fs_info->trans_lock);
 842         list_add(&pending_snapshot->list,
 843                  &trans->transaction->pending_snapshots);
 844         spin_unlock(&fs_info->trans_lock);
 845         if (async_transid) {
 846                 *async_transid = trans->transid;
 847                 ret = btrfs_commit_transaction_async(trans, 1);
 848                 if (ret)
 849                         ret = btrfs_commit_transaction(trans);
 850         } else {
 851                 ret = btrfs_commit_transaction(trans);
 852         }
 853         if (ret)
 854                 goto fail;
 855 
 856         ret = pending_snapshot->error;
 857         if (ret)
 858                 goto fail;
 859 
 860         ret = btrfs_orphan_cleanup(pending_snapshot->snap);
 861         if (ret)
 862                 goto fail;
 863 
 864         inode = btrfs_lookup_dentry(d_inode(dentry->d_parent), dentry);
 865         if (IS_ERR(inode)) {
 866                 ret = PTR_ERR(inode);
 867                 goto fail;
 868         }
 869 
 870         d_instantiate(dentry, inode);
 871         ret = 0;
 872 fail:
 873         btrfs_subvolume_release_metadata(fs_info, &pending_snapshot->block_rsv);
 874 dec_and_free:
 875         if (snapshot_force_cow)
 876                 atomic_dec(&root->snapshot_force_cow);
 877         if (atomic_dec_and_test(&root->will_be_snapshotted))
 878                 wake_up_var(&root->will_be_snapshotted);
 879 free_pending:
 880         kfree(pending_snapshot->root_item);
 881         btrfs_free_path(pending_snapshot->path);
 882         kfree(pending_snapshot);
 883 
 884         return ret;
 885 }
 886 
 887 /*  copy of may_delete in fs/namei.c()
 888  *      Check whether we can remove a link victim from directory dir, check
 889  *  whether the type of victim is right.
 890  *  1. We can't do it if dir is read-only (done in permission())
 891  *  2. We should have write and exec permissions on dir
 892  *  3. We can't remove anything from append-only dir
 893  *  4. We can't do anything with immutable dir (done in permission())
 894  *  5. If the sticky bit on dir is set we should either
 895  *      a. be owner of dir, or
 896  *      b. be owner of victim, or
 897  *      c. have CAP_FOWNER capability
 898  *  6. If the victim is append-only or immutable we can't do anything with
 899  *     links pointing to it.
 900  *  7. If we were asked to remove a directory and victim isn't one - ENOTDIR.
 901  *  8. If we were asked to remove a non-directory and victim isn't one - EISDIR.
 902  *  9. We can't remove a root or mountpoint.
 903  * 10. We don't allow removal of NFS sillyrenamed files; it's handled by
 904  *     nfs_async_unlink().
 905  */
 906 
 907 static int btrfs_may_delete(struct inode *dir, struct dentry *victim, int isdir)
 908 {
 909         int error;
 910 
 911         if (d_really_is_negative(victim))
 912                 return -ENOENT;
 913 
 914         BUG_ON(d_inode(victim->d_parent) != dir);
 915         audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE);
 916 
 917         error = inode_permission(dir, MAY_WRITE | MAY_EXEC);
 918         if (error)
 919                 return error;
 920         if (IS_APPEND(dir))
 921                 return -EPERM;
 922         if (check_sticky(dir, d_inode(victim)) || IS_APPEND(d_inode(victim)) ||
 923             IS_IMMUTABLE(d_inode(victim)) || IS_SWAPFILE(d_inode(victim)))
 924                 return -EPERM;
 925         if (isdir) {
 926                 if (!d_is_dir(victim))
 927                         return -ENOTDIR;
 928                 if (IS_ROOT(victim))
 929                         return -EBUSY;
 930         } else if (d_is_dir(victim))
 931                 return -EISDIR;
 932         if (IS_DEADDIR(dir))
 933                 return -ENOENT;
 934         if (victim->d_flags & DCACHE_NFSFS_RENAMED)
 935                 return -EBUSY;
 936         return 0;
 937 }
 938 
 939 /* copy of may_create in fs/namei.c() */
 940 static inline int btrfs_may_create(struct inode *dir, struct dentry *child)
 941 {
 942         if (d_really_is_positive(child))
 943                 return -EEXIST;
 944         if (IS_DEADDIR(dir))
 945                 return -ENOENT;
 946         return inode_permission(dir, MAY_WRITE | MAY_EXEC);
 947 }
 948 
 949 /*
 950  * Create a new subvolume below @parent.  This is largely modeled after
 951  * sys_mkdirat and vfs_mkdir, but we only do a single component lookup
 952  * inside this filesystem so it's quite a bit simpler.
 953  */
 954 static noinline int btrfs_mksubvol(const struct path *parent,
 955                                    const char *name, int namelen,
 956                                    struct btrfs_root *snap_src,
 957                                    u64 *async_transid, bool readonly,
 958                                    struct btrfs_qgroup_inherit *inherit)
 959 {
 960         struct inode *dir = d_inode(parent->dentry);
 961         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
 962         struct dentry *dentry;
 963         int error;
 964 
 965         error = down_write_killable_nested(&dir->i_rwsem, I_MUTEX_PARENT);
 966         if (error == -EINTR)
 967                 return error;
 968 
 969         dentry = lookup_one_len(name, parent->dentry, namelen);
 970         error = PTR_ERR(dentry);
 971         if (IS_ERR(dentry))
 972                 goto out_unlock;
 973 
 974         error = btrfs_may_create(dir, dentry);
 975         if (error)
 976                 goto out_dput;
 977 
 978         /*
 979          * even if this name doesn't exist, we may get hash collisions.
 980          * check for them now when we can safely fail
 981          */
 982         error = btrfs_check_dir_item_collision(BTRFS_I(dir)->root,
 983                                                dir->i_ino, name,
 984                                                namelen);
 985         if (error)
 986                 goto out_dput;
 987 
 988         down_read(&fs_info->subvol_sem);
 989 
 990         if (btrfs_root_refs(&BTRFS_I(dir)->root->root_item) == 0)
 991                 goto out_up_read;
 992 
 993         if (snap_src) {
 994                 error = create_snapshot(snap_src, dir, dentry,
 995                                         async_transid, readonly, inherit);
 996         } else {
 997                 error = create_subvol(dir, dentry, name, namelen,
 998                                       async_transid, inherit);
 999         }
1000         if (!error)
1001                 fsnotify_mkdir(dir, dentry);
1002 out_up_read:
1003         up_read(&fs_info->subvol_sem);
1004 out_dput:
1005         dput(dentry);
1006 out_unlock:
1007         inode_unlock(dir);
1008         return error;
1009 }
1010 
1011 /*
1012  * When we're defragging a range, we don't want to kick it off again
1013  * if it is really just waiting for delalloc to send it down.
1014  * If we find a nice big extent or delalloc range for the bytes in the
1015  * file you want to defrag, we return 0 to let you know to skip this
1016  * part of the file
1017  */
1018 static int check_defrag_in_cache(struct inode *inode, u64 offset, u32 thresh)
1019 {
1020         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1021         struct extent_map *em = NULL;
1022         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
1023         u64 end;
1024 
1025         read_lock(&em_tree->lock);
1026         em = lookup_extent_mapping(em_tree, offset, PAGE_SIZE);
1027         read_unlock(&em_tree->lock);
1028 
1029         if (em) {
1030                 end = extent_map_end(em);
1031                 free_extent_map(em);
1032                 if (end - offset > thresh)
1033                         return 0;
1034         }
1035         /* if we already have a nice delalloc here, just stop */
1036         thresh /= 2;
1037         end = count_range_bits(io_tree, &offset, offset + thresh,
1038                                thresh, EXTENT_DELALLOC, 1);
1039         if (end >= thresh)
1040                 return 0;
1041         return 1;
1042 }
1043 
1044 /*
1045  * helper function to walk through a file and find extents
1046  * newer than a specific transid, and smaller than thresh.
1047  *
1048  * This is used by the defragging code to find new and small
1049  * extents
1050  */
1051 static int find_new_extents(struct btrfs_root *root,
1052                             struct inode *inode, u64 newer_than,
1053                             u64 *off, u32 thresh)
1054 {
1055         struct btrfs_path *path;
1056         struct btrfs_key min_key;
1057         struct extent_buffer *leaf;
1058         struct btrfs_file_extent_item *extent;
1059         int type;
1060         int ret;
1061         u64 ino = btrfs_ino(BTRFS_I(inode));
1062 
1063         path = btrfs_alloc_path();
1064         if (!path)
1065                 return -ENOMEM;
1066 
1067         min_key.objectid = ino;
1068         min_key.type = BTRFS_EXTENT_DATA_KEY;
1069         min_key.offset = *off;
1070 
1071         while (1) {
1072                 ret = btrfs_search_forward(root, &min_key, path, newer_than);
1073                 if (ret != 0)
1074                         goto none;
1075 process_slot:
1076                 if (min_key.objectid != ino)
1077                         goto none;
1078                 if (min_key.type != BTRFS_EXTENT_DATA_KEY)
1079                         goto none;
1080 
1081                 leaf = path->nodes[0];
1082                 extent = btrfs_item_ptr(leaf, path->slots[0],
1083                                         struct btrfs_file_extent_item);
1084 
1085                 type = btrfs_file_extent_type(leaf, extent);
1086                 if (type == BTRFS_FILE_EXTENT_REG &&
1087                     btrfs_file_extent_num_bytes(leaf, extent) < thresh &&
1088                     check_defrag_in_cache(inode, min_key.offset, thresh)) {
1089                         *off = min_key.offset;
1090                         btrfs_free_path(path);
1091                         return 0;
1092                 }
1093 
1094                 path->slots[0]++;
1095                 if (path->slots[0] < btrfs_header_nritems(leaf)) {
1096                         btrfs_item_key_to_cpu(leaf, &min_key, path->slots[0]);
1097                         goto process_slot;
1098                 }
1099 
1100                 if (min_key.offset == (u64)-1)
1101                         goto none;
1102 
1103                 min_key.offset++;
1104                 btrfs_release_path(path);
1105         }
1106 none:
1107         btrfs_free_path(path);
1108         return -ENOENT;
1109 }
1110 
1111 static struct extent_map *defrag_lookup_extent(struct inode *inode, u64 start)
1112 {
1113         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
1114         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1115         struct extent_map *em;
1116         u64 len = PAGE_SIZE;
1117 
1118         /*
1119          * hopefully we have this extent in the tree already, try without
1120          * the full extent lock
1121          */
1122         read_lock(&em_tree->lock);
1123         em = lookup_extent_mapping(em_tree, start, len);
1124         read_unlock(&em_tree->lock);
1125 
1126         if (!em) {
1127                 struct extent_state *cached = NULL;
1128                 u64 end = start + len - 1;
1129 
1130                 /* get the big lock and read metadata off disk */
1131                 lock_extent_bits(io_tree, start, end, &cached);
1132                 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
1133                 unlock_extent_cached(io_tree, start, end, &cached);
1134 
1135                 if (IS_ERR(em))
1136                         return NULL;
1137         }
1138 
1139         return em;
1140 }
1141 
1142 static bool defrag_check_next_extent(struct inode *inode, struct extent_map *em)
1143 {
1144         struct extent_map *next;
1145         bool ret = true;
1146 
1147         /* this is the last extent */
1148         if (em->start + em->len >= i_size_read(inode))
1149                 return false;
1150 
1151         next = defrag_lookup_extent(inode, em->start + em->len);
1152         if (!next || next->block_start >= EXTENT_MAP_LAST_BYTE)
1153                 ret = false;
1154         else if ((em->block_start + em->block_len == next->block_start) &&
1155                  (em->block_len > SZ_128K && next->block_len > SZ_128K))
1156                 ret = false;
1157 
1158         free_extent_map(next);
1159         return ret;
1160 }
1161 
1162 static int should_defrag_range(struct inode *inode, u64 start, u32 thresh,
1163                                u64 *last_len, u64 *skip, u64 *defrag_end,
1164                                int compress)
1165 {
1166         struct extent_map *em;
1167         int ret = 1;
1168         bool next_mergeable = true;
1169         bool prev_mergeable = true;
1170 
1171         /*
1172          * make sure that once we start defragging an extent, we keep on
1173          * defragging it
1174          */
1175         if (start < *defrag_end)
1176                 return 1;
1177 
1178         *skip = 0;
1179 
1180         em = defrag_lookup_extent(inode, start);
1181         if (!em)
1182                 return 0;
1183 
1184         /* this will cover holes, and inline extents */
1185         if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
1186                 ret = 0;
1187                 goto out;
1188         }
1189 
1190         if (!*defrag_end)
1191                 prev_mergeable = false;
1192 
1193         next_mergeable = defrag_check_next_extent(inode, em);
1194         /*
1195          * we hit a real extent, if it is big or the next extent is not a
1196          * real extent, don't bother defragging it
1197          */
1198         if (!compress && (*last_len == 0 || *last_len >= thresh) &&
1199             (em->len >= thresh || (!next_mergeable && !prev_mergeable)))
1200                 ret = 0;
1201 out:
1202         /*
1203          * last_len ends up being a counter of how many bytes we've defragged.
1204          * every time we choose not to defrag an extent, we reset *last_len
1205          * so that the next tiny extent will force a defrag.
1206          *
1207          * The end result of this is that tiny extents before a single big
1208          * extent will force at least part of that big extent to be defragged.
1209          */
1210         if (ret) {
1211                 *defrag_end = extent_map_end(em);
1212         } else {
1213                 *last_len = 0;
1214                 *skip = extent_map_end(em);
1215                 *defrag_end = 0;
1216         }
1217 
1218         free_extent_map(em);
1219         return ret;
1220 }
1221 
1222 /*
1223  * it doesn't do much good to defrag one or two pages
1224  * at a time.  This pulls in a nice chunk of pages
1225  * to COW and defrag.
1226  *
1227  * It also makes sure the delalloc code has enough
1228  * dirty data to avoid making new small extents as part
1229  * of the defrag
1230  *
1231  * It's a good idea to start RA on this range
1232  * before calling this.
1233  */
1234 static int cluster_pages_for_defrag(struct inode *inode,
1235                                     struct page **pages,
1236                                     unsigned long start_index,
1237                                     unsigned long num_pages)
1238 {
1239         unsigned long file_end;
1240         u64 isize = i_size_read(inode);
1241         u64 page_start;
1242         u64 page_end;
1243         u64 page_cnt;
1244         int ret;
1245         int i;
1246         int i_done;
1247         struct btrfs_ordered_extent *ordered;
1248         struct extent_state *cached_state = NULL;
1249         struct extent_io_tree *tree;
1250         struct extent_changeset *data_reserved = NULL;
1251         gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
1252 
1253         file_end = (isize - 1) >> PAGE_SHIFT;
1254         if (!isize || start_index > file_end)
1255                 return 0;
1256 
1257         page_cnt = min_t(u64, (u64)num_pages, (u64)file_end - start_index + 1);
1258 
1259         ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
1260                         start_index << PAGE_SHIFT,
1261                         page_cnt << PAGE_SHIFT);
1262         if (ret)
1263                 return ret;
1264         i_done = 0;
1265         tree = &BTRFS_I(inode)->io_tree;
1266 
1267         /* step one, lock all the pages */
1268         for (i = 0; i < page_cnt; i++) {
1269                 struct page *page;
1270 again:
1271                 page = find_or_create_page(inode->i_mapping,
1272                                            start_index + i, mask);
1273                 if (!page)
1274                         break;
1275 
1276                 page_start = page_offset(page);
1277                 page_end = page_start + PAGE_SIZE - 1;
1278                 while (1) {
1279                         lock_extent_bits(tree, page_start, page_end,
1280                                          &cached_state);
1281                         ordered = btrfs_lookup_ordered_extent(inode,
1282                                                               page_start);
1283                         unlock_extent_cached(tree, page_start, page_end,
1284                                              &cached_state);
1285                         if (!ordered)
1286                                 break;
1287 
1288                         unlock_page(page);
1289                         btrfs_start_ordered_extent(inode, ordered, 1);
1290                         btrfs_put_ordered_extent(ordered);
1291                         lock_page(page);
1292                         /*
1293                          * we unlocked the page above, so we need check if
1294                          * it was released or not.
1295                          */
1296                         if (page->mapping != inode->i_mapping) {
1297                                 unlock_page(page);
1298                                 put_page(page);
1299                                 goto again;
1300                         }
1301                 }
1302 
1303                 if (!PageUptodate(page)) {
1304                         btrfs_readpage(NULL, page);
1305                         lock_page(page);
1306                         if (!PageUptodate(page)) {
1307                                 unlock_page(page);
1308                                 put_page(page);
1309                                 ret = -EIO;
1310                                 break;
1311                         }
1312                 }
1313 
1314                 if (page->mapping != inode->i_mapping) {
1315                         unlock_page(page);
1316                         put_page(page);
1317                         goto again;
1318                 }
1319 
1320                 pages[i] = page;
1321                 i_done++;
1322         }
1323         if (!i_done || ret)
1324                 goto out;
1325 
1326         if (!(inode->i_sb->s_flags & SB_ACTIVE))
1327                 goto out;
1328 
1329         /*
1330          * so now we have a nice long stream of locked
1331          * and up to date pages, lets wait on them
1332          */
1333         for (i = 0; i < i_done; i++)
1334                 wait_on_page_writeback(pages[i]);
1335 
1336         page_start = page_offset(pages[0]);
1337         page_end = page_offset(pages[i_done - 1]) + PAGE_SIZE;
1338 
1339         lock_extent_bits(&BTRFS_I(inode)->io_tree,
1340                          page_start, page_end - 1, &cached_state);
1341         clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start,
1342                           page_end - 1, EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
1343                           EXTENT_DEFRAG, 0, 0, &cached_state);
1344 
1345         if (i_done != page_cnt) {
1346                 spin_lock(&BTRFS_I(inode)->lock);
1347                 btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
1348                 spin_unlock(&BTRFS_I(inode)->lock);
1349                 btrfs_delalloc_release_space(inode, data_reserved,
1350                                 start_index << PAGE_SHIFT,
1351                                 (page_cnt - i_done) << PAGE_SHIFT, true);
1352         }
1353 
1354 
1355         set_extent_defrag(&BTRFS_I(inode)->io_tree, page_start, page_end - 1,
1356                           &cached_state);
1357 
1358         unlock_extent_cached(&BTRFS_I(inode)->io_tree,
1359                              page_start, page_end - 1, &cached_state);
1360 
1361         for (i = 0; i < i_done; i++) {
1362                 clear_page_dirty_for_io(pages[i]);
1363                 ClearPageChecked(pages[i]);
1364                 set_page_extent_mapped(pages[i]);
1365                 set_page_dirty(pages[i]);
1366                 unlock_page(pages[i]);
1367                 put_page(pages[i]);
1368         }
1369         btrfs_delalloc_release_extents(BTRFS_I(inode), page_cnt << PAGE_SHIFT);
1370         extent_changeset_free(data_reserved);
1371         return i_done;
1372 out:
1373         for (i = 0; i < i_done; i++) {
1374                 unlock_page(pages[i]);
1375                 put_page(pages[i]);
1376         }
1377         btrfs_delalloc_release_space(inode, data_reserved,
1378                         start_index << PAGE_SHIFT,
1379                         page_cnt << PAGE_SHIFT, true);
1380         btrfs_delalloc_release_extents(BTRFS_I(inode), page_cnt << PAGE_SHIFT);
1381         extent_changeset_free(data_reserved);
1382         return ret;
1383 
1384 }
1385 
1386 int btrfs_defrag_file(struct inode *inode, struct file *file,
1387                       struct btrfs_ioctl_defrag_range_args *range,
1388                       u64 newer_than, unsigned long max_to_defrag)
1389 {
1390         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1391         struct btrfs_root *root = BTRFS_I(inode)->root;
1392         struct file_ra_state *ra = NULL;
1393         unsigned long last_index;
1394         u64 isize = i_size_read(inode);
1395         u64 last_len = 0;
1396         u64 skip = 0;
1397         u64 defrag_end = 0;
1398         u64 newer_off = range->start;
1399         unsigned long i;
1400         unsigned long ra_index = 0;
1401         int ret;
1402         int defrag_count = 0;
1403         int compress_type = BTRFS_COMPRESS_ZLIB;
1404         u32 extent_thresh = range->extent_thresh;
1405         unsigned long max_cluster = SZ_256K >> PAGE_SHIFT;
1406         unsigned long cluster = max_cluster;
1407         u64 new_align = ~((u64)SZ_128K - 1);
1408         struct page **pages = NULL;
1409         bool do_compress = range->flags & BTRFS_DEFRAG_RANGE_COMPRESS;
1410 
1411         if (isize == 0)
1412                 return 0;
1413 
1414         if (range->start >= isize)
1415                 return -EINVAL;
1416 
1417         if (do_compress) {
1418                 if (range->compress_type > BTRFS_COMPRESS_TYPES)
1419                         return -EINVAL;
1420                 if (range->compress_type)
1421                         compress_type = range->compress_type;
1422         }
1423 
1424         if (extent_thresh == 0)
1425                 extent_thresh = SZ_256K;
1426 
1427         /*
1428          * If we were not given a file, allocate a readahead context. As
1429          * readahead is just an optimization, defrag will work without it so
1430          * we don't error out.
1431          */
1432         if (!file) {
1433                 ra = kzalloc(sizeof(*ra), GFP_KERNEL);
1434                 if (ra)
1435                         file_ra_state_init(ra, inode->i_mapping);
1436         } else {
1437                 ra = &file->f_ra;
1438         }
1439 
1440         pages = kmalloc_array(max_cluster, sizeof(struct page *), GFP_KERNEL);
1441         if (!pages) {
1442                 ret = -ENOMEM;
1443                 goto out_ra;
1444         }
1445 
1446         /* find the last page to defrag */
1447         if (range->start + range->len > range->start) {
1448                 last_index = min_t(u64, isize - 1,
1449                          range->start + range->len - 1) >> PAGE_SHIFT;
1450         } else {
1451                 last_index = (isize - 1) >> PAGE_SHIFT;
1452         }
1453 
1454         if (newer_than) {
1455                 ret = find_new_extents(root, inode, newer_than,
1456                                        &newer_off, SZ_64K);
1457                 if (!ret) {
1458                         range->start = newer_off;
1459                         /*
1460                          * we always align our defrag to help keep
1461                          * the extents in the file evenly spaced
1462                          */
1463                         i = (newer_off & new_align) >> PAGE_SHIFT;
1464                 } else
1465                         goto out_ra;
1466         } else {
1467                 i = range->start >> PAGE_SHIFT;
1468         }
1469         if (!max_to_defrag)
1470                 max_to_defrag = last_index - i + 1;
1471 
1472         /*
1473          * make writeback starts from i, so the defrag range can be
1474          * written sequentially.
1475          */
1476         if (i < inode->i_mapping->writeback_index)
1477                 inode->i_mapping->writeback_index = i;
1478 
1479         while (i <= last_index && defrag_count < max_to_defrag &&
1480                (i < DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE))) {
1481                 /*
1482                  * make sure we stop running if someone unmounts
1483                  * the FS
1484                  */
1485                 if (!(inode->i_sb->s_flags & SB_ACTIVE))
1486                         break;
1487 
1488                 if (btrfs_defrag_cancelled(fs_info)) {
1489                         btrfs_debug(fs_info, "defrag_file cancelled");
1490                         ret = -EAGAIN;
1491                         break;
1492                 }
1493 
1494                 if (!should_defrag_range(inode, (u64)i << PAGE_SHIFT,
1495                                          extent_thresh, &last_len, &skip,
1496                                          &defrag_end, do_compress)){
1497                         unsigned long next;
1498                         /*
1499                          * the should_defrag function tells us how much to skip
1500                          * bump our counter by the suggested amount
1501                          */
1502                         next = DIV_ROUND_UP(skip, PAGE_SIZE);
1503                         i = max(i + 1, next);
1504                         continue;
1505                 }
1506 
1507                 if (!newer_than) {
1508                         cluster = (PAGE_ALIGN(defrag_end) >>
1509                                    PAGE_SHIFT) - i;
1510                         cluster = min(cluster, max_cluster);
1511                 } else {
1512                         cluster = max_cluster;
1513                 }
1514 
1515                 if (i + cluster > ra_index) {
1516                         ra_index = max(i, ra_index);
1517                         if (ra)
1518                                 page_cache_sync_readahead(inode->i_mapping, ra,
1519                                                 file, ra_index, cluster);
1520                         ra_index += cluster;
1521                 }
1522 
1523                 inode_lock(inode);
1524                 if (IS_SWAPFILE(inode)) {
1525                         ret = -ETXTBSY;
1526                 } else {
1527                         if (do_compress)
1528                                 BTRFS_I(inode)->defrag_compress = compress_type;
1529                         ret = cluster_pages_for_defrag(inode, pages, i, cluster);
1530                 }
1531                 if (ret < 0) {
1532                         inode_unlock(inode);
1533                         goto out_ra;
1534                 }
1535 
1536                 defrag_count += ret;
1537                 balance_dirty_pages_ratelimited(inode->i_mapping);
1538                 inode_unlock(inode);
1539 
1540                 if (newer_than) {
1541                         if (newer_off == (u64)-1)
1542                                 break;
1543 
1544                         if (ret > 0)
1545                                 i += ret;
1546 
1547                         newer_off = max(newer_off + 1,
1548                                         (u64)i << PAGE_SHIFT);
1549 
1550                         ret = find_new_extents(root, inode, newer_than,
1551                                                &newer_off, SZ_64K);
1552                         if (!ret) {
1553                                 range->start = newer_off;
1554                                 i = (newer_off & new_align) >> PAGE_SHIFT;
1555                         } else {
1556                                 break;
1557                         }
1558                 } else {
1559                         if (ret > 0) {
1560                                 i += ret;
1561                                 last_len += ret << PAGE_SHIFT;
1562                         } else {
1563                                 i++;
1564                                 last_len = 0;
1565                         }
1566                 }
1567         }
1568 
1569         if ((range->flags & BTRFS_DEFRAG_RANGE_START_IO)) {
1570                 filemap_flush(inode->i_mapping);
1571                 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1572                              &BTRFS_I(inode)->runtime_flags))
1573                         filemap_flush(inode->i_mapping);
1574         }
1575 
1576         if (range->compress_type == BTRFS_COMPRESS_LZO) {
1577                 btrfs_set_fs_incompat(fs_info, COMPRESS_LZO);
1578         } else if (range->compress_type == BTRFS_COMPRESS_ZSTD) {
1579                 btrfs_set_fs_incompat(fs_info, COMPRESS_ZSTD);
1580         }
1581 
1582         ret = defrag_count;
1583 
1584 out_ra:
1585         if (do_compress) {
1586                 inode_lock(inode);
1587                 BTRFS_I(inode)->defrag_compress = BTRFS_COMPRESS_NONE;
1588                 inode_unlock(inode);
1589         }
1590         if (!file)
1591                 kfree(ra);
1592         kfree(pages);
1593         return ret;
1594 }
1595 
1596 static noinline int btrfs_ioctl_resize(struct file *file,
1597                                         void __user *arg)
1598 {
1599         struct inode *inode = file_inode(file);
1600         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1601         u64 new_size;
1602         u64 old_size;
1603         u64 devid = 1;
1604         struct btrfs_root *root = BTRFS_I(inode)->root;
1605         struct btrfs_ioctl_vol_args *vol_args;
1606         struct btrfs_trans_handle *trans;
1607         struct btrfs_device *device = NULL;
1608         char *sizestr;
1609         char *retptr;
1610         char *devstr = NULL;
1611         int ret = 0;
1612         int mod = 0;
1613 
1614         if (!capable(CAP_SYS_ADMIN))
1615                 return -EPERM;
1616 
1617         ret = mnt_want_write_file(file);
1618         if (ret)
1619                 return ret;
1620 
1621         if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
1622                 mnt_drop_write_file(file);
1623                 return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
1624         }
1625 
1626         vol_args = memdup_user(arg, sizeof(*vol_args));
1627         if (IS_ERR(vol_args)) {
1628                 ret = PTR_ERR(vol_args);
1629                 goto out;
1630         }
1631 
1632         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1633 
1634         sizestr = vol_args->name;
1635         devstr = strchr(sizestr, ':');
1636         if (devstr) {
1637                 sizestr = devstr + 1;
1638                 *devstr = '\0';
1639                 devstr = vol_args->name;
1640                 ret = kstrtoull(devstr, 10, &devid);
1641                 if (ret)
1642                         goto out_free;
1643                 if (!devid) {
1644                         ret = -EINVAL;
1645                         goto out_free;
1646                 }
1647                 btrfs_info(fs_info, "resizing devid %llu", devid);
1648         }
1649 
1650         device = btrfs_find_device(fs_info->fs_devices, devid, NULL, NULL, true);
1651         if (!device) {
1652                 btrfs_info(fs_info, "resizer unable to find device %llu",
1653                            devid);
1654                 ret = -ENODEV;
1655                 goto out_free;
1656         }
1657 
1658         if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1659                 btrfs_info(fs_info,
1660                            "resizer unable to apply on readonly device %llu",
1661                        devid);
1662                 ret = -EPERM;
1663                 goto out_free;
1664         }
1665 
1666         if (!strcmp(sizestr, "max"))
1667                 new_size = device->bdev->bd_inode->i_size;
1668         else {
1669                 if (sizestr[0] == '-') {
1670                         mod = -1;
1671                         sizestr++;
1672                 } else if (sizestr[0] == '+') {
1673                         mod = 1;
1674                         sizestr++;
1675                 }
1676                 new_size = memparse(sizestr, &retptr);
1677                 if (*retptr != '\0' || new_size == 0) {
1678                         ret = -EINVAL;
1679                         goto out_free;
1680                 }
1681         }
1682 
1683         if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1684                 ret = -EPERM;
1685                 goto out_free;
1686         }
1687 
1688         old_size = btrfs_device_get_total_bytes(device);
1689 
1690         if (mod < 0) {
1691                 if (new_size > old_size) {
1692                         ret = -EINVAL;
1693                         goto out_free;
1694                 }
1695                 new_size = old_size - new_size;
1696         } else if (mod > 0) {
1697                 if (new_size > ULLONG_MAX - old_size) {
1698                         ret = -ERANGE;
1699                         goto out_free;
1700                 }
1701                 new_size = old_size + new_size;
1702         }
1703 
1704         if (new_size < SZ_256M) {
1705                 ret = -EINVAL;
1706                 goto out_free;
1707         }
1708         if (new_size > device->bdev->bd_inode->i_size) {
1709                 ret = -EFBIG;
1710                 goto out_free;
1711         }
1712 
1713         new_size = round_down(new_size, fs_info->sectorsize);
1714 
1715         btrfs_info_in_rcu(fs_info, "new size for %s is %llu",
1716                           rcu_str_deref(device->name), new_size);
1717 
1718         if (new_size > old_size) {
1719                 trans = btrfs_start_transaction(root, 0);
1720                 if (IS_ERR(trans)) {
1721                         ret = PTR_ERR(trans);
1722                         goto out_free;
1723                 }
1724                 ret = btrfs_grow_device(trans, device, new_size);
1725                 btrfs_commit_transaction(trans);
1726         } else if (new_size < old_size) {
1727                 ret = btrfs_shrink_device(device, new_size);
1728         } /* equal, nothing need to do */
1729 
1730 out_free:
1731         kfree(vol_args);
1732 out:
1733         clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
1734         mnt_drop_write_file(file);
1735         return ret;
1736 }
1737 
1738 static noinline int btrfs_ioctl_snap_create_transid(struct file *file,
1739                                 const char *name, unsigned long fd, int subvol,
1740                                 u64 *transid, bool readonly,
1741                                 struct btrfs_qgroup_inherit *inherit)
1742 {
1743         int namelen;
1744         int ret = 0;
1745 
1746         if (!S_ISDIR(file_inode(file)->i_mode))
1747                 return -ENOTDIR;
1748 
1749         ret = mnt_want_write_file(file);
1750         if (ret)
1751                 goto out;
1752 
1753         namelen = strlen(name);
1754         if (strchr(name, '/')) {
1755                 ret = -EINVAL;
1756                 goto out_drop_write;
1757         }
1758 
1759         if (name[0] == '.' &&
1760            (namelen == 1 || (name[1] == '.' && namelen == 2))) {
1761                 ret = -EEXIST;
1762                 goto out_drop_write;
1763         }
1764 
1765         if (subvol) {
1766                 ret = btrfs_mksubvol(&file->f_path, name, namelen,
1767                                      NULL, transid, readonly, inherit);
1768         } else {
1769                 struct fd src = fdget(fd);
1770                 struct inode *src_inode;
1771                 if (!src.file) {
1772                         ret = -EINVAL;
1773                         goto out_drop_write;
1774                 }
1775 
1776                 src_inode = file_inode(src.file);
1777                 if (src_inode->i_sb != file_inode(file)->i_sb) {
1778                         btrfs_info(BTRFS_I(file_inode(file))->root->fs_info,
1779                                    "Snapshot src from another FS");
1780                         ret = -EXDEV;
1781                 } else if (!inode_owner_or_capable(src_inode)) {
1782                         /*
1783                          * Subvolume creation is not restricted, but snapshots
1784                          * are limited to own subvolumes only
1785                          */
1786                         ret = -EPERM;
1787                 } else {
1788                         ret = btrfs_mksubvol(&file->f_path, name, namelen,
1789                                              BTRFS_I(src_inode)->root,
1790                                              transid, readonly, inherit);
1791                 }
1792                 fdput(src);
1793         }
1794 out_drop_write:
1795         mnt_drop_write_file(file);
1796 out:
1797         return ret;
1798 }
1799 
1800 static noinline int btrfs_ioctl_snap_create(struct file *file,
1801                                             void __user *arg, int subvol)
1802 {
1803         struct btrfs_ioctl_vol_args *vol_args;
1804         int ret;
1805 
1806         if (!S_ISDIR(file_inode(file)->i_mode))
1807                 return -ENOTDIR;
1808 
1809         vol_args = memdup_user(arg, sizeof(*vol_args));
1810         if (IS_ERR(vol_args))
1811                 return PTR_ERR(vol_args);
1812         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1813 
1814         ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
1815                                               vol_args->fd, subvol,
1816                                               NULL, false, NULL);
1817 
1818         kfree(vol_args);
1819         return ret;
1820 }
1821 
1822 static noinline int btrfs_ioctl_snap_create_v2(struct file *file,
1823                                                void __user *arg, int subvol)
1824 {
1825         struct btrfs_ioctl_vol_args_v2 *vol_args;
1826         int ret;
1827         u64 transid = 0;
1828         u64 *ptr = NULL;
1829         bool readonly = false;
1830         struct btrfs_qgroup_inherit *inherit = NULL;
1831 
1832         if (!S_ISDIR(file_inode(file)->i_mode))
1833                 return -ENOTDIR;
1834 
1835         vol_args = memdup_user(arg, sizeof(*vol_args));
1836         if (IS_ERR(vol_args))
1837                 return PTR_ERR(vol_args);
1838         vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
1839 
1840         if (vol_args->flags &
1841             ~(BTRFS_SUBVOL_CREATE_ASYNC | BTRFS_SUBVOL_RDONLY |
1842               BTRFS_SUBVOL_QGROUP_INHERIT)) {
1843                 ret = -EOPNOTSUPP;
1844                 goto free_args;
1845         }
1846 
1847         if (vol_args->flags & BTRFS_SUBVOL_CREATE_ASYNC) {
1848                 struct inode *inode = file_inode(file);
1849                 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1850 
1851                 btrfs_warn(fs_info,
1852 "SNAP_CREATE_V2 ioctl with CREATE_ASYNC is deprecated and will be removed in kernel 5.7");
1853 
1854                 ptr = &transid;
1855         }
1856         if (vol_args->flags & BTRFS_SUBVOL_RDONLY)
1857                 readonly = true;
1858         if (vol_args->flags & BTRFS_SUBVOL_QGROUP_INHERIT) {
1859                 if (vol_args->size > PAGE_SIZE) {
1860                         ret = -EINVAL;
1861                         goto free_args;
1862                 }
1863                 inherit = memdup_user(vol_args->qgroup_inherit, vol_args->size);
1864                 if (IS_ERR(inherit)) {
1865                         ret = PTR_ERR(inherit);
1866                         goto free_args;
1867                 }
1868         }
1869 
1870         ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
1871                                               vol_args->fd, subvol, ptr,
1872                                               readonly, inherit);
1873         if (ret)
1874                 goto free_inherit;
1875 
1876         if (ptr && copy_to_user(arg +
1877                                 offsetof(struct btrfs_ioctl_vol_args_v2,
1878                                         transid),
1879                                 ptr, sizeof(*ptr)))
1880                 ret = -EFAULT;
1881 
1882 free_inherit:
1883         kfree(inherit);
1884 free_args:
1885         kfree(vol_args);
1886         return ret;
1887 }
1888 
1889 static noinline int btrfs_ioctl_subvol_getflags(struct file *file,
1890                                                 void __user *arg)
1891 {
1892         struct inode *inode = file_inode(file);
1893         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1894         struct btrfs_root *root = BTRFS_I(inode)->root;
1895         int ret = 0;
1896         u64 flags = 0;
1897 
1898         if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID)
1899                 return -EINVAL;
1900 
1901         down_read(&fs_info->subvol_sem);
1902         if (btrfs_root_readonly(root))
1903                 flags |= BTRFS_SUBVOL_RDONLY;
1904         up_read(&fs_info->subvol_sem);
1905 
1906         if (copy_to_user(arg, &flags, sizeof(flags)))
1907                 ret = -EFAULT;
1908 
1909         return ret;
1910 }
1911 
1912 static noinline int btrfs_ioctl_subvol_setflags(struct file *file,
1913                                               void __user *arg)
1914 {
1915         struct inode *inode = file_inode(file);
1916         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1917         struct btrfs_root *root = BTRFS_I(inode)->root;
1918         struct btrfs_trans_handle *trans;
1919         u64 root_flags;
1920         u64 flags;
1921         int ret = 0;
1922 
1923         if (!inode_owner_or_capable(inode))
1924                 return -EPERM;
1925 
1926         ret = mnt_want_write_file(file);
1927         if (ret)
1928                 goto out;
1929 
1930         if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
1931                 ret = -EINVAL;
1932                 goto out_drop_write;
1933         }
1934 
1935         if (copy_from_user(&flags, arg, sizeof(flags))) {
1936                 ret = -EFAULT;
1937                 goto out_drop_write;
1938         }
1939 
1940         if (flags & BTRFS_SUBVOL_CREATE_ASYNC) {
1941                 ret = -EINVAL;
1942                 goto out_drop_write;
1943         }
1944 
1945         if (flags & ~BTRFS_SUBVOL_RDONLY) {
1946                 ret = -EOPNOTSUPP;
1947                 goto out_drop_write;
1948         }
1949 
1950         down_write(&fs_info->subvol_sem);
1951 
1952         /* nothing to do */
1953         if (!!(flags & BTRFS_SUBVOL_RDONLY) == btrfs_root_readonly(root))
1954                 goto out_drop_sem;
1955 
1956         root_flags = btrfs_root_flags(&root->root_item);
1957         if (flags & BTRFS_SUBVOL_RDONLY) {
1958                 btrfs_set_root_flags(&root->root_item,
1959                                      root_flags | BTRFS_ROOT_SUBVOL_RDONLY);
1960         } else {
1961                 /*
1962                  * Block RO -> RW transition if this subvolume is involved in
1963                  * send
1964                  */
1965                 spin_lock(&root->root_item_lock);
1966                 if (root->send_in_progress == 0) {
1967                         btrfs_set_root_flags(&root->root_item,
1968                                      root_flags & ~BTRFS_ROOT_SUBVOL_RDONLY);
1969                         spin_unlock(&root->root_item_lock);
1970                 } else {
1971                         spin_unlock(&root->root_item_lock);
1972                         btrfs_warn(fs_info,
1973                                    "Attempt to set subvolume %llu read-write during send",
1974                                    root->root_key.objectid);
1975                         ret = -EPERM;
1976                         goto out_drop_sem;
1977                 }
1978         }
1979 
1980         trans = btrfs_start_transaction(root, 1);
1981         if (IS_ERR(trans)) {
1982                 ret = PTR_ERR(trans);
1983                 goto out_reset;
1984         }
1985 
1986         ret = btrfs_update_root(trans, fs_info->tree_root,
1987                                 &root->root_key, &root->root_item);
1988         if (ret < 0) {
1989                 btrfs_end_transaction(trans);
1990                 goto out_reset;
1991         }
1992 
1993         ret = btrfs_commit_transaction(trans);
1994 
1995 out_reset:
1996         if (ret)
1997                 btrfs_set_root_flags(&root->root_item, root_flags);
1998 out_drop_sem:
1999         up_write(&fs_info->subvol_sem);
2000 out_drop_write:
2001         mnt_drop_write_file(file);
2002 out:
2003         return ret;
2004 }
2005 
2006 static noinline int key_in_sk(struct btrfs_key *key,
2007                               struct btrfs_ioctl_search_key *sk)
2008 {
2009         struct btrfs_key test;
2010         int ret;
2011 
2012         test.objectid = sk->min_objectid;
2013         test.type = sk->min_type;
2014         test.offset = sk->min_offset;
2015 
2016         ret = btrfs_comp_cpu_keys(key, &test);
2017         if (ret < 0)
2018                 return 0;
2019 
2020         test.objectid = sk->max_objectid;
2021         test.type = sk->max_type;
2022         test.offset = sk->max_offset;
2023 
2024         ret = btrfs_comp_cpu_keys(key, &test);
2025         if (ret > 0)
2026                 return 0;
2027         return 1;
2028 }
2029 
2030 static noinline int copy_to_sk(struct btrfs_path *path,
2031                                struct btrfs_key *key,
2032                                struct btrfs_ioctl_search_key *sk,
2033                                size_t *buf_size,
2034                                char __user *ubuf,
2035                                unsigned long *sk_offset,
2036                                int *num_found)
2037 {
2038         u64 found_transid;
2039         struct extent_buffer *leaf;
2040         struct btrfs_ioctl_search_header sh;
2041         struct btrfs_key test;
2042         unsigned long item_off;
2043         unsigned long item_len;
2044         int nritems;
2045         int i;
2046         int slot;
2047         int ret = 0;
2048 
2049         leaf = path->nodes[0];
2050         slot = path->slots[0];
2051         nritems = btrfs_header_nritems(leaf);
2052 
2053         if (btrfs_header_generation(leaf) > sk->max_transid) {
2054                 i = nritems;
2055                 goto advance_key;
2056         }
2057         found_transid = btrfs_header_generation(leaf);
2058 
2059         for (i = slot; i < nritems; i++) {
2060                 item_off = btrfs_item_ptr_offset(leaf, i);
2061                 item_len = btrfs_item_size_nr(leaf, i);
2062 
2063                 btrfs_item_key_to_cpu(leaf, key, i);
2064                 if (!key_in_sk(key, sk))
2065                         continue;
2066 
2067                 if (sizeof(sh) + item_len > *buf_size) {
2068                         if (*num_found) {
2069                                 ret = 1;
2070                                 goto out;
2071                         }
2072 
2073                         /*
2074                          * return one empty item back for v1, which does not
2075                          * handle -EOVERFLOW
2076                          */
2077 
2078                         *buf_size = sizeof(sh) + item_len;
2079                         item_len = 0;
2080                         ret = -EOVERFLOW;
2081                 }
2082 
2083                 if (sizeof(sh) + item_len + *sk_offset > *buf_size) {
2084                         ret = 1;
2085                         goto out;
2086                 }
2087 
2088                 sh.objectid = key->objectid;
2089                 sh.offset = key->offset;
2090                 sh.type = key->type;
2091                 sh.len = item_len;
2092                 sh.transid = found_transid;
2093 
2094                 /* copy search result header */
2095                 if (copy_to_user(ubuf + *sk_offset, &sh, sizeof(sh))) {
2096                         ret = -EFAULT;
2097                         goto out;
2098                 }
2099 
2100                 *sk_offset += sizeof(sh);
2101 
2102                 if (item_len) {
2103                         char __user *up = ubuf + *sk_offset;
2104                         /* copy the item */
2105                         if (read_extent_buffer_to_user(leaf, up,
2106                                                        item_off, item_len)) {
2107                                 ret = -EFAULT;
2108                                 goto out;
2109                         }
2110 
2111                         *sk_offset += item_len;
2112                 }
2113                 (*num_found)++;
2114 
2115                 if (ret) /* -EOVERFLOW from above */
2116                         goto out;
2117 
2118                 if (*num_found >= sk->nr_items) {
2119                         ret = 1;
2120                         goto out;
2121                 }
2122         }
2123 advance_key:
2124         ret = 0;
2125         test.objectid = sk->max_objectid;
2126         test.type = sk->max_type;
2127         test.offset = sk->max_offset;
2128         if (btrfs_comp_cpu_keys(key, &test) >= 0)
2129                 ret = 1;
2130         else if (key->offset < (u64)-1)
2131                 key->offset++;
2132         else if (key->type < (u8)-1) {
2133                 key->offset = 0;
2134                 key->type++;
2135         } else if (key->objectid < (u64)-1) {
2136                 key->offset = 0;
2137                 key->type = 0;
2138                 key->objectid++;
2139         } else
2140                 ret = 1;
2141 out:
2142         /*
2143          *  0: all items from this leaf copied, continue with next
2144          *  1: * more items can be copied, but unused buffer is too small
2145          *     * all items were found
2146          *     Either way, it will stops the loop which iterates to the next
2147          *     leaf
2148          *  -EOVERFLOW: item was to large for buffer
2149          *  -EFAULT: could not copy extent buffer back to userspace
2150          */
2151         return ret;
2152 }
2153 
2154 static noinline int search_ioctl(struct inode *inode,
2155                                  struct btrfs_ioctl_search_key *sk,
2156                                  size_t *buf_size,
2157                                  char __user *ubuf)
2158 {
2159         struct btrfs_fs_info *info = btrfs_sb(inode->i_sb);
2160         struct btrfs_root *root;
2161         struct btrfs_key key;
2162         struct btrfs_path *path;
2163         int ret;
2164         int num_found = 0;
2165         unsigned long sk_offset = 0;
2166 
2167         if (*buf_size < sizeof(struct btrfs_ioctl_search_header)) {
2168                 *buf_size = sizeof(struct btrfs_ioctl_search_header);
2169                 return -EOVERFLOW;
2170         }
2171 
2172         path = btrfs_alloc_path();
2173         if (!path)
2174                 return -ENOMEM;
2175 
2176         if (sk->tree_id == 0) {
2177                 /* search the root of the inode that was passed */
2178                 root = BTRFS_I(inode)->root;
2179         } else {
2180                 key.objectid = sk->tree_id;
2181                 key.type = BTRFS_ROOT_ITEM_KEY;
2182                 key.offset = (u64)-1;
2183                 root = btrfs_read_fs_root_no_name(info, &key);
2184                 if (IS_ERR(root)) {
2185                         btrfs_free_path(path);
2186                         return PTR_ERR(root);
2187                 }
2188         }
2189 
2190         key.objectid = sk->min_objectid;
2191         key.type = sk->min_type;
2192         key.offset = sk->min_offset;
2193 
2194         while (1) {
2195                 ret = btrfs_search_forward(root, &key, path, sk->min_transid);
2196                 if (ret != 0) {
2197                         if (ret > 0)
2198                                 ret = 0;
2199                         goto err;
2200                 }
2201                 ret = copy_to_sk(path, &key, sk, buf_size, ubuf,
2202                                  &sk_offset, &num_found);
2203                 btrfs_release_path(path);
2204                 if (ret)
2205                         break;
2206 
2207         }
2208         if (ret > 0)
2209                 ret = 0;
2210 err:
2211         sk->nr_items = num_found;
2212         btrfs_free_path(path);
2213         return ret;
2214 }
2215 
2216 static noinline int btrfs_ioctl_tree_search(struct file *file,
2217                                            void __user *argp)
2218 {
2219         struct btrfs_ioctl_search_args __user *uargs;
2220         struct btrfs_ioctl_search_key sk;
2221         struct inode *inode;
2222         int ret;
2223         size_t buf_size;
2224 
2225         if (!capable(CAP_SYS_ADMIN))
2226                 return -EPERM;
2227 
2228         uargs = (struct btrfs_ioctl_search_args __user *)argp;
2229 
2230         if (copy_from_user(&sk, &uargs->key, sizeof(sk)))
2231                 return -EFAULT;
2232 
2233         buf_size = sizeof(uargs->buf);
2234 
2235         inode = file_inode(file);
2236         ret = search_ioctl(inode, &sk, &buf_size, uargs->buf);
2237 
2238         /*
2239          * In the origin implementation an overflow is handled by returning a
2240          * search header with a len of zero, so reset ret.
2241          */
2242         if (ret == -EOVERFLOW)
2243                 ret = 0;
2244 
2245         if (ret == 0 && copy_to_user(&uargs->key, &sk, sizeof(sk)))
2246                 ret = -EFAULT;
2247         return ret;
2248 }
2249 
2250 static noinline int btrfs_ioctl_tree_search_v2(struct file *file,
2251                                                void __user *argp)
2252 {
2253         struct btrfs_ioctl_search_args_v2 __user *uarg;
2254         struct btrfs_ioctl_search_args_v2 args;
2255         struct inode *inode;
2256         int ret;
2257         size_t buf_size;
2258         const size_t buf_limit = SZ_16M;
2259 
2260         if (!capable(CAP_SYS_ADMIN))
2261                 return -EPERM;
2262 
2263         /* copy search header and buffer size */
2264         uarg = (struct btrfs_ioctl_search_args_v2 __user *)argp;
2265         if (copy_from_user(&args, uarg, sizeof(args)))
2266                 return -EFAULT;
2267 
2268         buf_size = args.buf_size;
2269 
2270         /* limit result size to 16MB */
2271         if (buf_size > buf_limit)
2272                 buf_size = buf_limit;
2273 
2274         inode = file_inode(file);
2275         ret = search_ioctl(inode, &args.key, &buf_size,
2276                            (char __user *)(&uarg->buf[0]));
2277         if (ret == 0 && copy_to_user(&uarg->key, &args.key, sizeof(args.key)))
2278                 ret = -EFAULT;
2279         else if (ret == -EOVERFLOW &&
2280                 copy_to_user(&uarg->buf_size, &buf_size, sizeof(buf_size)))
2281                 ret = -EFAULT;
2282 
2283         return ret;
2284 }
2285 
2286 /*
2287  * Search INODE_REFs to identify path name of 'dirid' directory
2288  * in a 'tree_id' tree. and sets path name to 'name'.
2289  */
2290 static noinline int btrfs_search_path_in_tree(struct btrfs_fs_info *info,
2291                                 u64 tree_id, u64 dirid, char *name)
2292 {
2293         struct btrfs_root *root;
2294         struct btrfs_key key;
2295         char *ptr;
2296         int ret = -1;
2297         int slot;
2298         int len;
2299         int total_len = 0;
2300         struct btrfs_inode_ref *iref;
2301         struct extent_buffer *l;
2302         struct btrfs_path *path;
2303 
2304         if (dirid == BTRFS_FIRST_FREE_OBJECTID) {
2305                 name[0]='\0';
2306                 return 0;
2307         }
2308 
2309         path = btrfs_alloc_path();
2310         if (!path)
2311                 return -ENOMEM;
2312 
2313         ptr = &name[BTRFS_INO_LOOKUP_PATH_MAX - 1];
2314 
2315         key.objectid = tree_id;
2316         key.type = BTRFS_ROOT_ITEM_KEY;
2317         key.offset = (u64)-1;
2318         root = btrfs_read_fs_root_no_name(info, &key);
2319         if (IS_ERR(root)) {
2320                 ret = PTR_ERR(root);
2321                 goto out;
2322         }
2323 
2324         key.objectid = dirid;
2325         key.type = BTRFS_INODE_REF_KEY;
2326         key.offset = (u64)-1;
2327 
2328         while (1) {
2329                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2330                 if (ret < 0)
2331                         goto out;
2332                 else if (ret > 0) {
2333                         ret = btrfs_previous_item(root, path, dirid,
2334                                                   BTRFS_INODE_REF_KEY);
2335                         if (ret < 0)
2336                                 goto out;
2337                         else if (ret > 0) {
2338                                 ret = -ENOENT;
2339                                 goto out;
2340                         }
2341                 }
2342 
2343                 l = path->nodes[0];
2344                 slot = path->slots[0];
2345                 btrfs_item_key_to_cpu(l, &key, slot);
2346 
2347                 iref = btrfs_item_ptr(l, slot, struct btrfs_inode_ref);
2348                 len = btrfs_inode_ref_name_len(l, iref);
2349                 ptr -= len + 1;
2350                 total_len += len + 1;
2351                 if (ptr < name) {
2352                         ret = -ENAMETOOLONG;
2353                         goto out;
2354                 }
2355 
2356                 *(ptr + len) = '/';
2357                 read_extent_buffer(l, ptr, (unsigned long)(iref + 1), len);
2358 
2359                 if (key.offset == BTRFS_FIRST_FREE_OBJECTID)
2360                         break;
2361 
2362                 btrfs_release_path(path);
2363                 key.objectid = key.offset;
2364                 key.offset = (u64)-1;
2365                 dirid = key.objectid;
2366         }
2367         memmove(name, ptr, total_len);
2368         name[total_len] = '\0';
2369         ret = 0;
2370 out:
2371         btrfs_free_path(path);
2372         return ret;
2373 }
2374 
2375 static int btrfs_search_path_in_tree_user(struct inode *inode,
2376                                 struct btrfs_ioctl_ino_lookup_user_args *args)
2377 {
2378         struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
2379         struct super_block *sb = inode->i_sb;
2380         struct btrfs_key upper_limit = BTRFS_I(inode)->location;
2381         u64 treeid = BTRFS_I(inode)->root->root_key.objectid;
2382         u64 dirid = args->dirid;
2383         unsigned long item_off;
2384         unsigned long item_len;
2385         struct btrfs_inode_ref *iref;
2386         struct btrfs_root_ref *rref;
2387         struct btrfs_root *root;
2388         struct btrfs_path *path;
2389         struct btrfs_key key, key2;
2390         struct extent_buffer *leaf;
2391         struct inode *temp_inode;
2392         char *ptr;
2393         int slot;
2394         int len;
2395         int total_len = 0;
2396         int ret;
2397 
2398         path = btrfs_alloc_path();
2399         if (!path)
2400                 return -ENOMEM;
2401 
2402         /*
2403          * If the bottom subvolume does not exist directly under upper_limit,
2404          * construct the path in from the bottom up.
2405          */
2406         if (dirid != upper_limit.objectid) {
2407                 ptr = &args->path[BTRFS_INO_LOOKUP_USER_PATH_MAX - 1];
2408 
2409                 key.objectid = treeid;
2410                 key.type = BTRFS_ROOT_ITEM_KEY;
2411                 key.offset = (u64)-1;
2412                 root = btrfs_read_fs_root_no_name(fs_info, &key);
2413                 if (IS_ERR(root)) {
2414                         ret = PTR_ERR(root);
2415                         goto out;
2416                 }
2417 
2418                 key.objectid = dirid;
2419                 key.type = BTRFS_INODE_REF_KEY;
2420                 key.offset = (u64)-1;
2421                 while (1) {
2422                         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2423                         if (ret < 0) {
2424                                 goto out;
2425                         } else if (ret > 0) {
2426                                 ret = btrfs_previous_item(root, path, dirid,
2427                                                           BTRFS_INODE_REF_KEY);
2428                                 if (ret < 0) {
2429                                         goto out;
2430                                 } else if (ret > 0) {
2431                                         ret = -ENOENT;
2432                                         goto out;
2433                                 }
2434                         }
2435 
2436                         leaf = path->nodes[0];
2437                         slot = path->slots[0];
2438                         btrfs_item_key_to_cpu(leaf, &key, slot);
2439 
2440                         iref = btrfs_item_ptr(leaf, slot, struct btrfs_inode_ref);
2441                         len = btrfs_inode_ref_name_len(leaf, iref);
2442                         ptr -= len + 1;
2443                         total_len += len + 1;
2444                         if (ptr < args->path) {
2445                                 ret = -ENAMETOOLONG;
2446                                 goto out;
2447                         }
2448 
2449                         *(ptr + len) = '/';
2450                         read_extent_buffer(leaf, ptr,
2451                                         (unsigned long)(iref + 1), len);
2452 
2453                         /* Check the read+exec permission of this directory */
2454                         ret = btrfs_previous_item(root, path, dirid,
2455                                                   BTRFS_INODE_ITEM_KEY);
2456                         if (ret < 0) {
2457                                 goto out;
2458                         } else if (ret > 0) {
2459                                 ret = -ENOENT;
2460                                 goto out;
2461                         }
2462 
2463                         leaf = path->nodes[0];
2464                         slot = path->slots[0];
2465                         btrfs_item_key_to_cpu(leaf, &key2, slot);
2466                         if (key2.objectid != dirid) {
2467                                 ret = -ENOENT;
2468                                 goto out;
2469                         }
2470 
2471                         temp_inode = btrfs_iget(sb, &key2, root, NULL);
2472                         if (IS_ERR(temp_inode)) {
2473                                 ret = PTR_ERR(temp_inode);
2474                                 goto out;
2475                         }
2476                         ret = inode_permission(temp_inode, MAY_READ | MAY_EXEC);
2477                         iput(temp_inode);
2478                         if (ret) {
2479                                 ret = -EACCES;
2480                                 goto out;
2481                         }
2482 
2483                         if (key.offset == upper_limit.objectid)
2484                                 break;
2485                         if (key.objectid == BTRFS_FIRST_FREE_OBJECTID) {
2486                                 ret = -EACCES;
2487                                 goto out;
2488                         }
2489 
2490                         btrfs_release_path(path);
2491                         key.objectid = key.offset;
2492                         key.offset = (u64)-1;
2493                         dirid = key.objectid;
2494                 }
2495 
2496                 memmove(args->path, ptr, total_len);
2497                 args->path[total_len] = '\0';
2498                 btrfs_release_path(path);
2499         }
2500 
2501         /* Get the bottom subvolume's name from ROOT_REF */
2502         root = fs_info->tree_root;
2503         key.objectid = treeid;
2504         key.type = BTRFS_ROOT_REF_KEY;
2505         key.offset = args->treeid;
2506         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2507         if (ret < 0) {
2508                 goto out;
2509         } else if (ret > 0) {
2510                 ret = -ENOENT;
2511                 goto out;
2512         }
2513 
2514         leaf = path->nodes[0];
2515         slot = path->slots[0];
2516         btrfs_item_key_to_cpu(leaf, &key, slot);
2517 
2518         item_off = btrfs_item_ptr_offset(leaf, slot);
2519         item_len = btrfs_item_size_nr(leaf, slot);
2520         /* Check if dirid in ROOT_REF corresponds to passed dirid */
2521         rref = btrfs_item_ptr(leaf, slot, struct btrfs_root_ref);
2522         if (args->dirid != btrfs_root_ref_dirid(leaf, rref)) {
2523                 ret = -EINVAL;
2524                 goto out;
2525         }
2526 
2527         /* Copy subvolume's name */
2528         item_off += sizeof(struct btrfs_root_ref);
2529         item_len -= sizeof(struct btrfs_root_ref);
2530         read_extent_buffer(leaf, args->name, item_off, item_len);
2531         args->name[item_len] = 0;
2532 
2533 out:
2534         btrfs_free_path(path);
2535         return ret;
2536 }
2537 
2538 static noinline int btrfs_ioctl_ino_lookup(struct file *file,
2539                                            void __user *argp)
2540 {
2541         struct btrfs_ioctl_ino_lookup_args *args;
2542         struct inode *inode;
2543         int ret = 0;
2544 
2545         args = memdup_user(argp, sizeof(*args));
2546         if (IS_ERR(args))
2547                 return PTR_ERR(args);
2548 
2549         inode = file_inode(file);
2550 
2551         /*
2552          * Unprivileged query to obtain the containing subvolume root id. The
2553          * path is reset so it's consistent with btrfs_search_path_in_tree.
2554          */
2555         if (args->treeid == 0)
2556                 args->treeid = BTRFS_I(inode)->root->root_key.objectid;
2557 
2558         if (args->objectid == BTRFS_FIRST_FREE_OBJECTID) {
2559                 args->name[0] = 0;
2560                 goto out;
2561         }
2562 
2563         if (!capable(CAP_SYS_ADMIN)) {
2564                 ret = -EPERM;
2565                 goto out;
2566         }
2567 
2568         ret = btrfs_search_path_in_tree(BTRFS_I(inode)->root->fs_info,
2569                                         args->treeid, args->objectid,
2570                                         args->name);
2571 
2572 out:
2573         if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
2574                 ret = -EFAULT;
2575 
2576         kfree(args);
2577         return ret;
2578 }
2579 
2580 /*
2581  * Version of ino_lookup ioctl (unprivileged)
2582  *
2583  * The main differences from ino_lookup ioctl are:
2584  *
2585  *   1. Read + Exec permission will be checked using inode_permission() during
2586  *      path construction. -EACCES will be returned in case of failure.
2587  *   2. Path construction will be stopped at the inode number which corresponds
2588  *      to the fd with which this ioctl is called. If constructed path does not
2589  *      exist under fd's inode, -EACCES will be returned.
2590  *   3. The name of bottom subvolume is also searched and filled.
2591  */
2592 static int btrfs_ioctl_ino_lookup_user(struct file *file, void __user *argp)
2593 {
2594         struct btrfs_ioctl_ino_lookup_user_args *args;
2595         struct inode *inode;
2596         int ret;
2597 
2598         args = memdup_user(argp, sizeof(*args));
2599         if (IS_ERR(args))
2600                 return PTR_ERR(args);
2601 
2602         inode = file_inode(file);
2603 
2604         if (args->dirid == BTRFS_FIRST_FREE_OBJECTID &&
2605             BTRFS_I(inode)->location.objectid != BTRFS_FIRST_FREE_OBJECTID) {
2606                 /*
2607                  * The subvolume does not exist under fd with which this is
2608                  * called
2609                  */
2610                 kfree(args);
2611                 return -EACCES;
2612         }
2613 
2614         ret = btrfs_search_path_in_tree_user(inode, args);
2615 
2616         if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
2617                 ret = -EFAULT;
2618 
2619         kfree(args);
2620         return ret;
2621 }
2622 
2623 /* Get the subvolume information in BTRFS_ROOT_ITEM and BTRFS_ROOT_BACKREF */
2624 static int btrfs_ioctl_get_subvol_info(struct file *file, void __user *argp)
2625 {
2626         struct btrfs_ioctl_get_subvol_info_args *subvol_info;
2627         struct btrfs_fs_info *fs_info;
2628         struct btrfs_root *root;
2629         struct btrfs_path *path;
2630         struct btrfs_key key;
2631         struct btrfs_root_item *root_item;
2632         struct btrfs_root_ref *rref;
2633         struct extent_buffer *leaf;
2634         unsigned long item_off;
2635         unsigned long item_len;
2636         struct inode *inode;
2637         int slot;
2638         int ret = 0;
2639 
2640         path = btrfs_alloc_path();
2641         if (!path)
2642                 return -ENOMEM;
2643 
2644         subvol_info = kzalloc(sizeof(*subvol_info), GFP_KERNEL);
2645         if (!subvol_info) {
2646                 btrfs_free_path(path);
2647                 return -ENOMEM;
2648         }
2649 
2650         inode = file_inode(file);
2651         fs_info = BTRFS_I(inode)->root->fs_info;
2652 
2653         /* Get root_item of inode's subvolume */
2654         key.objectid = BTRFS_I(inode)->root->root_key.objectid;
2655         key.type = BTRFS_ROOT_ITEM_KEY;
2656         key.offset = (u64)-1;
2657         root = btrfs_read_fs_root_no_name(fs_info, &key);
2658         if (IS_ERR(root)) {
2659                 ret = PTR_ERR(root);
2660                 goto out;
2661         }
2662         root_item = &root->root_item;
2663 
2664         subvol_info->treeid = key.objectid;
2665 
2666         subvol_info->generation = btrfs_root_generation(root_item);
2667         subvol_info->flags = btrfs_root_flags(root_item);
2668 
2669         memcpy(subvol_info->uuid, root_item->uuid, BTRFS_UUID_SIZE);
2670         memcpy(subvol_info->parent_uuid, root_item->parent_uuid,
2671                                                     BTRFS_UUID_SIZE);
2672         memcpy(subvol_info->received_uuid, root_item->received_uuid,
2673                                                     BTRFS_UUID_SIZE);
2674 
2675         subvol_info->ctransid = btrfs_root_ctransid(root_item);
2676         subvol_info->ctime.sec = btrfs_stack_timespec_sec(&root_item->ctime);
2677         subvol_info->ctime.nsec = btrfs_stack_timespec_nsec(&root_item->ctime);
2678 
2679         subvol_info->otransid = btrfs_root_otransid(root_item);
2680         subvol_info->otime.sec = btrfs_stack_timespec_sec(&root_item->otime);
2681         subvol_info->otime.nsec = btrfs_stack_timespec_nsec(&root_item->otime);
2682 
2683         subvol_info->stransid = btrfs_root_stransid(root_item);
2684         subvol_info->stime.sec = btrfs_stack_timespec_sec(&root_item->stime);
2685         subvol_info->stime.nsec = btrfs_stack_timespec_nsec(&root_item->stime);
2686 
2687         subvol_info->rtransid = btrfs_root_rtransid(root_item);
2688         subvol_info->rtime.sec = btrfs_stack_timespec_sec(&root_item->rtime);
2689         subvol_info->rtime.nsec = btrfs_stack_timespec_nsec(&root_item->rtime);
2690 
2691         if (key.objectid != BTRFS_FS_TREE_OBJECTID) {
2692                 /* Search root tree for ROOT_BACKREF of this subvolume */
2693                 root = fs_info->tree_root;
2694 
2695                 key.type = BTRFS_ROOT_BACKREF_KEY;
2696                 key.offset = 0;
2697                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2698                 if (ret < 0) {
2699                         goto out;
2700                 } else if (path->slots[0] >=
2701                            btrfs_header_nritems(path->nodes[0])) {
2702                         ret = btrfs_next_leaf(root, path);
2703                         if (ret < 0) {
2704                                 goto out;
2705                         } else if (ret > 0) {
2706                                 ret = -EUCLEAN;
2707                                 goto out;
2708                         }
2709                 }
2710 
2711                 leaf = path->nodes[0];
2712                 slot = path->slots[0];
2713                 btrfs_item_key_to_cpu(leaf, &key, slot);
2714                 if (key.objectid == subvol_info->treeid &&
2715                     key.type == BTRFS_ROOT_BACKREF_KEY) {
2716                         subvol_info->parent_id = key.offset;
2717 
2718                         rref = btrfs_item_ptr(leaf, slot, struct btrfs_root_ref);
2719                         subvol_info->dirid = btrfs_root_ref_dirid(leaf, rref);
2720 
2721                         item_off = btrfs_item_ptr_offset(leaf, slot)
2722                                         + sizeof(struct btrfs_root_ref);
2723                         item_len = btrfs_item_size_nr(leaf, slot)
2724                                         - sizeof(struct btrfs_root_ref);
2725                         read_extent_buffer(leaf, subvol_info->name,
2726                                            item_off, item_len);
2727                 } else {
2728                         ret = -ENOENT;
2729                         goto out;
2730                 }
2731         }
2732 
2733         if (copy_to_user(argp, subvol_info, sizeof(*subvol_info)))
2734                 ret = -EFAULT;
2735 
2736 out:
2737         btrfs_free_path(path);
2738         kzfree(subvol_info);
2739         return ret;
2740 }
2741 
2742 /*
2743  * Return ROOT_REF information of the subvolume containing this inode
2744  * except the subvolume name.
2745  */
2746 static int btrfs_ioctl_get_subvol_rootref(struct file *file, void __user *argp)
2747 {
2748         struct btrfs_ioctl_get_subvol_rootref_args *rootrefs;
2749         struct btrfs_root_ref *rref;
2750         struct btrfs_root *root;
2751         struct btrfs_path *path;
2752         struct btrfs_key key;
2753         struct extent_buffer *leaf;
2754         struct inode *inode;
2755         u64 objectid;
2756         int slot;
2757         int ret;
2758         u8 found;
2759 
2760         path = btrfs_alloc_path();
2761         if (!path)
2762                 return -ENOMEM;
2763 
2764         rootrefs = memdup_user(argp, sizeof(*rootrefs));
2765         if (IS_ERR(rootrefs)) {
2766                 btrfs_free_path(path);
2767                 return PTR_ERR(rootrefs);
2768         }
2769 
2770         inode = file_inode(file);
2771         root = BTRFS_I(inode)->root->fs_info->tree_root;
2772         objectid = BTRFS_I(inode)->root->root_key.objectid;
2773 
2774         key.objectid = objectid;
2775         key.type = BTRFS_ROOT_REF_KEY;
2776         key.offset = rootrefs->min_treeid;
2777         found = 0;
2778 
2779         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2780         if (ret < 0) {
2781                 goto out;
2782         } else if (path->slots[0] >=
2783                    btrfs_header_nritems(path->nodes[0])) {
2784                 ret = btrfs_next_leaf(root, path);
2785                 if (ret < 0) {
2786                         goto out;
2787                 } else if (ret > 0) {
2788                         ret = -EUCLEAN;
2789                         goto out;
2790                 }
2791         }
2792         while (1) {
2793                 leaf = path->nodes[0];
2794                 slot = path->slots[0];
2795 
2796                 btrfs_item_key_to_cpu(leaf, &key, slot);
2797                 if (key.objectid != objectid || key.type != BTRFS_ROOT_REF_KEY) {
2798                         ret = 0;
2799                         goto out;
2800                 }
2801 
2802                 if (found == BTRFS_MAX_ROOTREF_BUFFER_NUM) {
2803                         ret = -EOVERFLOW;
2804                         goto out;
2805                 }
2806 
2807                 rref = btrfs_item_ptr(leaf, slot, struct btrfs_root_ref);
2808                 rootrefs->rootref[found].treeid = key.offset;
2809                 rootrefs->rootref[found].dirid =
2810                                   btrfs_root_ref_dirid(leaf, rref);
2811                 found++;
2812 
2813                 ret = btrfs_next_item(root, path);
2814                 if (ret < 0) {
2815                         goto out;
2816                 } else if (ret > 0) {
2817                         ret = -EUCLEAN;
2818                         goto out;
2819                 }
2820         }
2821 
2822 out:
2823         if (!ret || ret == -EOVERFLOW) {
2824                 rootrefs->num_items = found;
2825                 /* update min_treeid for next search */
2826                 if (found)
2827                         rootrefs->min_treeid =
2828                                 rootrefs->rootref[found - 1].treeid + 1;
2829                 if (copy_to_user(argp, rootrefs, sizeof(*rootrefs)))
2830                         ret = -EFAULT;
2831         }
2832 
2833         kfree(rootrefs);
2834         btrfs_free_path(path);
2835 
2836         return ret;
2837 }
2838 
2839 static noinline int btrfs_ioctl_snap_destroy(struct file *file,
2840                                              void __user *arg)
2841 {
2842         struct dentry *parent = file->f_path.dentry;
2843         struct btrfs_fs_info *fs_info = btrfs_sb(parent->d_sb);
2844         struct dentry *dentry;
2845         struct inode *dir = d_inode(parent);
2846         struct inode *inode;
2847         struct btrfs_root *root = BTRFS_I(dir)->root;
2848         struct btrfs_root *dest = NULL;
2849         struct btrfs_ioctl_vol_args *vol_args;
2850         int namelen;
2851         int err = 0;
2852 
2853         if (!S_ISDIR(dir->i_mode))
2854                 return -ENOTDIR;
2855 
2856         vol_args = memdup_user(arg, sizeof(*vol_args));
2857         if (IS_ERR(vol_args))
2858                 return PTR_ERR(vol_args);
2859 
2860         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
2861         namelen = strlen(vol_args->name);
2862         if (strchr(vol_args->name, '/') ||
2863             strncmp(vol_args->name, "..", namelen) == 0) {
2864                 err = -EINVAL;
2865                 goto out;
2866         }
2867 
2868         err = mnt_want_write_file(file);
2869         if (err)
2870                 goto out;
2871 
2872 
2873         err = down_write_killable_nested(&dir->i_rwsem, I_MUTEX_PARENT);
2874         if (err == -EINTR)
2875                 goto out_drop_write;
2876         dentry = lookup_one_len(vol_args->name, parent, namelen);
2877         if (IS_ERR(dentry)) {
2878                 err = PTR_ERR(dentry);
2879                 goto out_unlock_dir;
2880         }
2881 
2882         if (d_really_is_negative(dentry)) {
2883                 err = -ENOENT;
2884                 goto out_dput;
2885         }
2886 
2887         inode = d_inode(dentry);
2888         dest = BTRFS_I(inode)->root;
2889         if (!capable(CAP_SYS_ADMIN)) {
2890                 /*
2891                  * Regular user.  Only allow this with a special mount
2892                  * option, when the user has write+exec access to the
2893                  * subvol root, and when rmdir(2) would have been
2894                  * allowed.
2895                  *
2896                  * Note that this is _not_ check that the subvol is
2897                  * empty or doesn't contain data that we wouldn't
2898                  * otherwise be able to delete.
2899                  *
2900                  * Users who want to delete empty subvols should try
2901                  * rmdir(2).
2902                  */
2903                 err = -EPERM;
2904                 if (!btrfs_test_opt(fs_info, USER_SUBVOL_RM_ALLOWED))
2905                         goto out_dput;
2906 
2907                 /*
2908                  * Do not allow deletion if the parent dir is the same
2909                  * as the dir to be deleted.  That means the ioctl
2910                  * must be called on the dentry referencing the root
2911                  * of the subvol, not a random directory contained
2912                  * within it.
2913                  */
2914                 err = -EINVAL;
2915                 if (root == dest)
2916                         goto out_dput;
2917 
2918                 err = inode_permission(inode, MAY_WRITE | MAY_EXEC);
2919                 if (err)
2920                         goto out_dput;
2921         }
2922 
2923         /* check if subvolume may be deleted by a user */
2924         err = btrfs_may_delete(dir, dentry, 1);
2925         if (err)
2926                 goto out_dput;
2927 
2928         if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
2929                 err = -EINVAL;
2930                 goto out_dput;
2931         }
2932 
2933         inode_lock(inode);
2934         err = btrfs_delete_subvolume(dir, dentry);
2935         inode_unlock(inode);
2936         if (!err) {
2937                 fsnotify_rmdir(dir, dentry);
2938                 d_delete(dentry);
2939         }
2940 
2941 out_dput:
2942         dput(dentry);
2943 out_unlock_dir:
2944         inode_unlock(dir);
2945 out_drop_write:
2946         mnt_drop_write_file(file);
2947 out:
2948         kfree(vol_args);
2949         return err;
2950 }
2951 
2952 static int btrfs_ioctl_defrag(struct file *file, void __user *argp)
2953 {
2954         struct inode *inode = file_inode(file);
2955         struct btrfs_root *root = BTRFS_I(inode)->root;
2956         struct btrfs_ioctl_defrag_range_args *range;
2957         int ret;
2958 
2959         ret = mnt_want_write_file(file);
2960         if (ret)
2961                 return ret;
2962 
2963         if (btrfs_root_readonly(root)) {
2964                 ret = -EROFS;
2965                 goto out;
2966         }
2967 
2968         switch (inode->i_mode & S_IFMT) {
2969         case S_IFDIR:
2970                 if (!capable(CAP_SYS_ADMIN)) {
2971                         ret = -EPERM;
2972                         goto out;
2973                 }
2974                 ret = btrfs_defrag_root(root);
2975                 break;
2976         case S_IFREG:
2977                 /*
2978                  * Note that this does not check the file descriptor for write
2979                  * access. This prevents defragmenting executables that are
2980                  * running and allows defrag on files open in read-only mode.
2981                  */
2982                 if (!capable(CAP_SYS_ADMIN) &&
2983                     inode_permission(inode, MAY_WRITE)) {
2984                         ret = -EPERM;
2985                         goto out;
2986                 }
2987 
2988                 range = kzalloc(sizeof(*range), GFP_KERNEL);
2989                 if (!range) {
2990                         ret = -ENOMEM;
2991                         goto out;
2992                 }
2993 
2994                 if (argp) {
2995                         if (copy_from_user(range, argp,
2996                                            sizeof(*range))) {
2997                                 ret = -EFAULT;
2998                                 kfree(range);
2999                                 goto out;
3000                         }
3001                         /* compression requires us to start the IO */
3002                         if ((range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)) {
3003                                 range->flags |= BTRFS_DEFRAG_RANGE_START_IO;
3004                                 range->extent_thresh = (u32)-1;
3005                         }
3006                 } else {
3007                         /* the rest are all set to zero by kzalloc */
3008                         range->len = (u64)-1;
3009                 }
3010                 ret = btrfs_defrag_file(file_inode(file), file,
3011                                         range, BTRFS_OLDEST_GENERATION, 0);
3012                 if (ret > 0)
3013                         ret = 0;
3014                 kfree(range);
3015                 break;
3016         default:
3017                 ret = -EINVAL;
3018         }
3019 out:
3020         mnt_drop_write_file(file);
3021         return ret;
3022 }
3023 
3024 static long btrfs_ioctl_add_dev(struct btrfs_fs_info *fs_info, void __user *arg)
3025 {
3026         struct btrfs_ioctl_vol_args *vol_args;
3027         int ret;
3028 
3029         if (!capable(CAP_SYS_ADMIN))
3030                 return -EPERM;
3031 
3032         if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags))
3033                 return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
3034 
3035         vol_args = memdup_user(arg, sizeof(*vol_args));
3036         if (IS_ERR(vol_args)) {
3037                 ret = PTR_ERR(vol_args);
3038                 goto out;
3039         }
3040 
3041         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
3042         ret = btrfs_init_new_device(fs_info, vol_args->name);
3043 
3044         if (!ret)
3045                 btrfs_info(fs_info, "disk added %s", vol_args->name);
3046 
3047         kfree(vol_args);
3048 out:
3049         clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
3050         return ret;
3051 }
3052 
3053 static long btrfs_ioctl_rm_dev_v2(struct file *file, void __user *arg)
3054 {
3055         struct inode *inode = file_inode(file);
3056         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3057         struct btrfs_ioctl_vol_args_v2 *vol_args;
3058         int ret;
3059 
3060         if (!capable(CAP_SYS_ADMIN))
3061                 return -EPERM;
3062 
3063         ret = mnt_want_write_file(file);
3064         if (ret)
3065                 return ret;
3066 
3067         vol_args = memdup_user(arg, sizeof(*vol_args));
3068         if (IS_ERR(vol_args)) {
3069                 ret = PTR_ERR(vol_args);
3070                 goto err_drop;
3071         }
3072 
3073         /* Check for compatibility reject unknown flags */
3074         if (vol_args->flags & ~BTRFS_VOL_ARG_V2_FLAGS_SUPPORTED) {
3075                 ret = -EOPNOTSUPP;
3076                 goto out;
3077         }
3078 
3079         if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
3080                 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
3081                 goto out;
3082         }
3083 
3084         if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID) {
3085                 ret = btrfs_rm_device(fs_info, NULL, vol_args->devid);
3086         } else {
3087                 vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
3088                 ret = btrfs_rm_device(fs_info, vol_args->name, 0);
3089         }
3090         clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
3091 
3092         if (!ret) {
3093                 if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID)
3094                         btrfs_info(fs_info, "device deleted: id %llu",
3095                                         vol_args->devid);
3096                 else
3097                         btrfs_info(fs_info, "device deleted: %s",
3098                                         vol_args->name);
3099         }
3100 out:
3101         kfree(vol_args);
3102 err_drop:
3103         mnt_drop_write_file(file);
3104         return ret;
3105 }
3106 
3107 static long btrfs_ioctl_rm_dev(struct file *file, void __user *arg)
3108 {
3109         struct inode *inode = file_inode(file);
3110         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3111         struct btrfs_ioctl_vol_args *vol_args;
3112         int ret;
3113 
3114         if (!capable(CAP_SYS_ADMIN))
3115                 return -EPERM;
3116 
3117         ret = mnt_want_write_file(file);
3118         if (ret)
3119                 return ret;
3120 
3121         if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
3122                 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
3123                 goto out_drop_write;
3124         }
3125 
3126         vol_args = memdup_user(arg, sizeof(*vol_args));
3127         if (IS_ERR(vol_args)) {
3128                 ret = PTR_ERR(vol_args);
3129                 goto out;
3130         }
3131 
3132         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
3133         ret = btrfs_rm_device(fs_info, vol_args->name, 0);
3134 
3135         if (!ret)
3136                 btrfs_info(fs_info, "disk deleted %s", vol_args->name);
3137         kfree(vol_args);
3138 out:
3139         clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
3140 out_drop_write:
3141         mnt_drop_write_file(file);
3142 
3143         return ret;
3144 }
3145 
3146 static long btrfs_ioctl_fs_info(struct btrfs_fs_info *fs_info,
3147                                 void __user *arg)
3148 {
3149         struct btrfs_ioctl_fs_info_args *fi_args;
3150         struct btrfs_device *device;
3151         struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
3152         int ret = 0;
3153 
3154         fi_args = kzalloc(sizeof(*fi_args), GFP_KERNEL);
3155         if (!fi_args)
3156                 return -ENOMEM;
3157 
3158         rcu_read_lock();
3159         fi_args->num_devices = fs_devices->num_devices;
3160 
3161         list_for_each_entry_rcu(device, &fs_devices->devices, dev_list) {
3162                 if (device->devid > fi_args->max_id)
3163                         fi_args->max_id = device->devid;
3164         }
3165         rcu_read_unlock();
3166 
3167         memcpy(&fi_args->fsid, fs_devices->fsid, sizeof(fi_args->fsid));
3168         fi_args->nodesize = fs_info->nodesize;
3169         fi_args->sectorsize = fs_info->sectorsize;
3170         fi_args->clone_alignment = fs_info->sectorsize;
3171 
3172         if (copy_to_user(arg, fi_args, sizeof(*fi_args)))
3173                 ret = -EFAULT;
3174 
3175         kfree(fi_args);
3176         return ret;
3177 }
3178 
3179 static long btrfs_ioctl_dev_info(struct btrfs_fs_info *fs_info,
3180                                  void __user *arg)
3181 {
3182         struct btrfs_ioctl_dev_info_args *di_args;
3183         struct btrfs_device *dev;
3184         int ret = 0;
3185         char *s_uuid = NULL;
3186 
3187         di_args = memdup_user(arg, sizeof(*di_args));
3188         if (IS_ERR(di_args))
3189                 return PTR_ERR(di_args);
3190 
3191         if (!btrfs_is_empty_uuid(di_args->uuid))
3192                 s_uuid = di_args->uuid;
3193 
3194         rcu_read_lock();
3195         dev = btrfs_find_device(fs_info->fs_devices, di_args->devid, s_uuid,
3196                                 NULL, true);
3197 
3198         if (!dev) {
3199                 ret = -ENODEV;
3200                 goto out;
3201         }
3202 
3203         di_args->devid = dev->devid;
3204         di_args->bytes_used = btrfs_device_get_bytes_used(dev);
3205         di_args->total_bytes = btrfs_device_get_total_bytes(dev);
3206         memcpy(di_args->uuid, dev->uuid, sizeof(di_args->uuid));
3207         if (dev->name) {
3208                 strncpy(di_args->path, rcu_str_deref(dev->name),
3209                                 sizeof(di_args->path) - 1);
3210                 di_args->path[sizeof(di_args->path) - 1] = 0;
3211         } else {
3212                 di_args->path[0] = '\0';
3213         }
3214 
3215 out:
3216         rcu_read_unlock();
3217         if (ret == 0 && copy_to_user(arg, di_args, sizeof(*di_args)))
3218                 ret = -EFAULT;
3219 
3220         kfree(di_args);
3221         return ret;
3222 }
3223 
3224 static void btrfs_double_extent_unlock(struct inode *inode1, u64 loff1,
3225                                        struct inode *inode2, u64 loff2, u64 len)
3226 {
3227         unlock_extent(&BTRFS_I(inode1)->io_tree, loff1, loff1 + len - 1);
3228         unlock_extent(&BTRFS_I(inode2)->io_tree, loff2, loff2 + len - 1);
3229 }
3230 
3231 static void btrfs_double_extent_lock(struct inode *inode1, u64 loff1,
3232                                      struct inode *inode2, u64 loff2, u64 len)
3233 {
3234         if (inode1 < inode2) {
3235                 swap(inode1, inode2);
3236                 swap(loff1, loff2);
3237         } else if (inode1 == inode2 && loff2 < loff1) {
3238                 swap(loff1, loff2);
3239         }
3240         lock_extent(&BTRFS_I(inode1)->io_tree, loff1, loff1 + len - 1);
3241         lock_extent(&BTRFS_I(inode2)->io_tree, loff2, loff2 + len - 1);
3242 }
3243 
3244 static int btrfs_extent_same_range(struct inode *src, u64 loff, u64 len,
3245                                    struct inode *dst, u64 dst_loff)
3246 {
3247         const u64 bs = BTRFS_I(src)->root->fs_info->sb->s_blocksize;
3248         int ret;
3249 
3250         /*
3251          * Lock destination range to serialize with concurrent readpages() and
3252          * source range to serialize with relocation.
3253          */
3254         btrfs_double_extent_lock(src, loff, dst, dst_loff, len);
3255         ret = btrfs_clone(src, dst, loff, len, ALIGN(len, bs), dst_loff, 1);
3256         btrfs_double_extent_unlock(src, loff, dst, dst_loff, len);
3257 
3258         return ret;
3259 }
3260 
3261 #define BTRFS_MAX_DEDUPE_LEN    SZ_16M
3262 
3263 static int btrfs_extent_same(struct inode *src, u64 loff, u64 olen,
3264                              struct inode *dst, u64 dst_loff)
3265 {
3266         int ret;
3267         u64 i, tail_len, chunk_count;
3268         struct btrfs_root *root_dst = BTRFS_I(dst)->root;
3269 
3270         spin_lock(&root_dst->root_item_lock);
3271         if (root_dst->send_in_progress) {
3272                 btrfs_warn_rl(root_dst->fs_info,
3273 "cannot deduplicate to root %llu while send operations are using it (%d in progress)",
3274                               root_dst->root_key.objectid,
3275                               root_dst->send_in_progress);
3276                 spin_unlock(&root_dst->root_item_lock);
3277                 return -EAGAIN;
3278         }
3279         root_dst->dedupe_in_progress++;
3280         spin_unlock(&root_dst->root_item_lock);
3281 
3282         tail_len = olen % BTRFS_MAX_DEDUPE_LEN;
3283         chunk_count = div_u64(olen, BTRFS_MAX_DEDUPE_LEN);
3284 
3285         for (i = 0; i < chunk_count; i++) {
3286                 ret = btrfs_extent_same_range(src, loff, BTRFS_MAX_DEDUPE_LEN,
3287                                               dst, dst_loff);
3288                 if (ret)
3289                         goto out;
3290 
3291                 loff += BTRFS_MAX_DEDUPE_LEN;
3292                 dst_loff += BTRFS_MAX_DEDUPE_LEN;
3293         }
3294 
3295         if (tail_len > 0)
3296                 ret = btrfs_extent_same_range(src, loff, tail_len, dst,
3297                                               dst_loff);
3298 out:
3299         spin_lock(&root_dst->root_item_lock);
3300         root_dst->dedupe_in_progress--;
3301         spin_unlock(&root_dst->root_item_lock);
3302 
3303         return ret;
3304 }
3305 
3306 static int clone_finish_inode_update(struct btrfs_trans_handle *trans,
3307                                      struct inode *inode,
3308                                      u64 endoff,
3309                                      const u64 destoff,
3310                                      const u64 olen,
3311                                      int no_time_update)
3312 {
3313         struct btrfs_root *root = BTRFS_I(inode)->root;
3314         int ret;
3315 
3316         inode_inc_iversion(inode);
3317         if (!no_time_update)
3318                 inode->i_mtime = inode->i_ctime = current_time(inode);
3319         /*
3320          * We round up to the block size at eof when determining which
3321          * extents to clone above, but shouldn't round up the file size.
3322          */
3323         if (endoff > destoff + olen)
3324                 endoff = destoff + olen;
3325         if (endoff > inode->i_size)
3326                 btrfs_i_size_write(BTRFS_I(inode), endoff);
3327 
3328         ret = btrfs_update_inode(trans, root, inode);
3329         if (ret) {
3330                 btrfs_abort_transaction(trans, ret);
3331                 btrfs_end_transaction(trans);
3332                 goto out;
3333         }
3334         ret = btrfs_end_transaction(trans);
3335 out:
3336         return ret;
3337 }
3338 
3339 /*
3340  * Make sure we do not end up inserting an inline extent into a file that has
3341  * already other (non-inline) extents. If a file has an inline extent it can
3342  * not have any other extents and the (single) inline extent must start at the
3343  * file offset 0. Failing to respect these rules will lead to file corruption,
3344  * resulting in EIO errors on read/write operations, hitting BUG_ON's in mm, etc
3345  *
3346  * We can have extents that have been already written to disk or we can have
3347  * dirty ranges still in delalloc, in which case the extent maps and items are
3348  * created only when we run delalloc, and the delalloc ranges might fall outside
3349  * the range we are currently locking in the inode's io tree. So we check the
3350  * inode's i_size because of that (i_size updates are done while holding the
3351  * i_mutex, which we are holding here).
3352  * We also check to see if the inode has a size not greater than "datal" but has
3353  * extents beyond it, due to an fallocate with FALLOC_FL_KEEP_SIZE (and we are
3354  * protected against such concurrent fallocate calls by the i_mutex).
3355  *
3356  * If the file has no extents but a size greater than datal, do not allow the
3357  * copy because we would need turn the inline extent into a non-inline one (even
3358  * with NO_HOLES enabled). If we find our destination inode only has one inline
3359  * extent, just overwrite it with the source inline extent if its size is less
3360  * than the source extent's size, or we could copy the source inline extent's
3361  * data into the destination inode's inline extent if the later is greater then
3362  * the former.
3363  */
3364 static int clone_copy_inline_extent(struct inode *dst,
3365                                     struct btrfs_trans_handle *trans,
3366                                     struct btrfs_path *path,
3367                                     struct btrfs_key *new_key,
3368                                     const u64 drop_start,
3369                                     const u64 datal,
3370                                     const u64 skip,
3371                                     const u64 size,
3372                                     char *inline_data)
3373 {
3374         struct btrfs_fs_info *fs_info = btrfs_sb(dst->i_sb);
3375         struct btrfs_root *root = BTRFS_I(dst)->root;
3376         const u64 aligned_end = ALIGN(new_key->offset + datal,
3377                                       fs_info->sectorsize);
3378         int ret;
3379         struct btrfs_key key;
3380 
3381         if (new_key->offset > 0)
3382                 return -EOPNOTSUPP;
3383 
3384         key.objectid = btrfs_ino(BTRFS_I(dst));
3385         key.type = BTRFS_EXTENT_DATA_KEY;
3386         key.offset = 0;
3387         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3388         if (ret < 0) {
3389                 return ret;
3390         } else if (ret > 0) {
3391                 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
3392                         ret = btrfs_next_leaf(root, path);
3393                         if (ret < 0)
3394                                 return ret;
3395                         else if (ret > 0)
3396                                 goto copy_inline_extent;
3397                 }
3398                 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
3399                 if (key.objectid == btrfs_ino(BTRFS_I(dst)) &&
3400                     key.type == BTRFS_EXTENT_DATA_KEY) {
3401                         ASSERT(key.offset > 0);
3402                         return -EOPNOTSUPP;
3403                 }
3404         } else if (i_size_read(dst) <= datal) {
3405                 struct btrfs_file_extent_item *ei;
3406                 u64 ext_len;
3407 
3408                 /*
3409                  * If the file size is <= datal, make sure there are no other
3410                  * extents following (can happen do to an fallocate call with
3411                  * the flag FALLOC_FL_KEEP_SIZE).
3412                  */
3413                 ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
3414                                     struct btrfs_file_extent_item);
3415                 /*
3416                  * If it's an inline extent, it can not have other extents
3417                  * following it.
3418                  */
3419                 if (btrfs_file_extent_type(path->nodes[0], ei) ==
3420                     BTRFS_FILE_EXTENT_INLINE)
3421                         goto copy_inline_extent;
3422 
3423                 ext_len = btrfs_file_extent_num_bytes(path->nodes[0], ei);
3424                 if (ext_len > aligned_end)
3425                         return -EOPNOTSUPP;
3426 
3427                 ret = btrfs_next_item(root, path);
3428                 if (ret < 0) {
3429                         return ret;
3430                 } else if (ret == 0) {
3431                         btrfs_item_key_to_cpu(path->nodes[0], &key,
3432                                               path->slots[0]);
3433                         if (key.objectid == btrfs_ino(BTRFS_I(dst)) &&
3434                             key.type == BTRFS_EXTENT_DATA_KEY)
3435                                 return -EOPNOTSUPP;
3436                 }
3437         }
3438 
3439 copy_inline_extent:
3440         /*
3441          * We have no extent items, or we have an extent at offset 0 which may
3442          * or may not be inlined. All these cases are dealt the same way.
3443          */
3444         if (i_size_read(dst) > datal) {
3445                 /*
3446                  * If the destination inode has an inline extent...
3447                  * This would require copying the data from the source inline
3448                  * extent into the beginning of the destination's inline extent.
3449                  * But this is really complex, both extents can be compressed
3450                  * or just one of them, which would require decompressing and
3451                  * re-compressing data (which could increase the new compressed
3452                  * size, not allowing the compressed data to fit anymore in an
3453                  * inline extent).
3454                  * So just don't support this case for now (it should be rare,
3455                  * we are not really saving space when cloning inline extents).
3456                  */
3457                 return -EOPNOTSUPP;
3458         }
3459 
3460         btrfs_release_path(path);
3461         ret = btrfs_drop_extents(trans, root, dst, drop_start, aligned_end, 1);
3462         if (ret)
3463                 return ret;
3464         ret = btrfs_insert_empty_item(trans, root, path, new_key, size);
3465         if (ret)
3466                 return ret;
3467 
3468         if (skip) {
3469                 const u32 start = btrfs_file_extent_calc_inline_size(0);
3470 
3471                 memmove(inline_data + start, inline_data + start + skip, datal);
3472         }
3473 
3474         write_extent_buffer(path->nodes[0], inline_data,
3475                             btrfs_item_ptr_offset(path->nodes[0],
3476                                                   path->slots[0]),
3477                             size);
3478         inode_add_bytes(dst, datal);
3479         set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(dst)->runtime_flags);
3480 
3481         return 0;
3482 }
3483 
3484 /**
3485  * btrfs_clone() - clone a range from inode file to another
3486  *
3487  * @src: Inode to clone from
3488  * @inode: Inode to clone to
3489  * @off: Offset within source to start clone from
3490  * @olen: Original length, passed by user, of range to clone
3491  * @olen_aligned: Block-aligned value of olen
3492  * @destoff: Offset within @inode to start clone
3493  * @no_time_update: Whether to update mtime/ctime on the target inode
3494  */
3495 static int btrfs_clone(struct inode *src, struct inode *inode,
3496                        const u64 off, const u64 olen, const u64 olen_aligned,
3497                        const u64 destoff, int no_time_update)
3498 {
3499         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3500         struct btrfs_root *root = BTRFS_I(inode)->root;
3501         struct btrfs_path *path = NULL;
3502         struct extent_buffer *leaf;
3503         struct btrfs_trans_handle *trans;
3504         char *buf = NULL;
3505         struct btrfs_key key;
3506         u32 nritems;
3507         int slot;
3508         int ret;
3509         const u64 len = olen_aligned;
3510         u64 last_dest_end = destoff;
3511 
3512         ret = -ENOMEM;
3513         buf = kvmalloc(fs_info->nodesize, GFP_KERNEL);
3514         if (!buf)
3515                 return ret;
3516 
3517         path = btrfs_alloc_path();
3518         if (!path) {
3519                 kvfree(buf);
3520                 return ret;
3521         }
3522 
3523         path->reada = READA_FORWARD;
3524         /* clone data */
3525         key.objectid = btrfs_ino(BTRFS_I(src));
3526         key.type = BTRFS_EXTENT_DATA_KEY;
3527         key.offset = off;
3528 
3529         while (1) {
3530                 u64 next_key_min_offset = key.offset + 1;
3531                 struct btrfs_file_extent_item *extent;
3532                 int type;
3533                 u32 size;
3534                 struct btrfs_key new_key;
3535                 u64 disko = 0, diskl = 0;
3536                 u64 datao = 0, datal = 0;
3537                 u8 comp;
3538                 u64 drop_start;
3539 
3540                 /*
3541                  * note the key will change type as we walk through the
3542                  * tree.
3543                  */
3544                 path->leave_spinning = 1;
3545                 ret = btrfs_search_slot(NULL, BTRFS_I(src)->root, &key, path,
3546                                 0, 0);
3547                 if (ret < 0)
3548                         goto out;
3549                 /*
3550                  * First search, if no extent item that starts at offset off was
3551                  * found but the previous item is an extent item, it's possible
3552                  * it might overlap our target range, therefore process it.
3553                  */
3554                 if (key.offset == off && ret > 0 && path->slots[0] > 0) {
3555                         btrfs_item_key_to_cpu(path->nodes[0], &key,
3556                                               path->slots[0] - 1);
3557                         if (key.type == BTRFS_EXTENT_DATA_KEY)
3558                                 path->slots[0]--;
3559                 }
3560 
3561                 nritems = btrfs_header_nritems(path->nodes[0]);
3562 process_slot:
3563                 if (path->slots[0] >= nritems) {
3564                         ret = btrfs_next_leaf(BTRFS_I(src)->root, path);
3565                         if (ret < 0)
3566                                 goto out;
3567                         if (ret > 0)
3568                                 break;
3569                         nritems = btrfs_header_nritems(path->nodes[0]);
3570                 }
3571                 leaf = path->nodes[0];
3572                 slot = path->slots[0];
3573 
3574                 btrfs_item_key_to_cpu(leaf, &key, slot);
3575                 if (key.type > BTRFS_EXTENT_DATA_KEY ||
3576                     key.objectid != btrfs_ino(BTRFS_I(src)))
3577                         break;
3578 
3579                 ASSERT(key.type == BTRFS_EXTENT_DATA_KEY);
3580 
3581                 extent = btrfs_item_ptr(leaf, slot,
3582                                         struct btrfs_file_extent_item);
3583                 comp = btrfs_file_extent_compression(leaf, extent);
3584                 type = btrfs_file_extent_type(leaf, extent);
3585                 if (type == BTRFS_FILE_EXTENT_REG ||
3586                     type == BTRFS_FILE_EXTENT_PREALLOC) {
3587                         disko = btrfs_file_extent_disk_bytenr(leaf, extent);
3588                         diskl = btrfs_file_extent_disk_num_bytes(leaf, extent);
3589                         datao = btrfs_file_extent_offset(leaf, extent);
3590                         datal = btrfs_file_extent_num_bytes(leaf, extent);
3591                 } else if (type == BTRFS_FILE_EXTENT_INLINE) {
3592                         /* Take upper bound, may be compressed */
3593                         datal = btrfs_file_extent_ram_bytes(leaf, extent);
3594                 }
3595 
3596                 /*
3597                  * The first search might have left us at an extent item that
3598                  * ends before our target range's start, can happen if we have
3599                  * holes and NO_HOLES feature enabled.
3600                  */
3601                 if (key.offset + datal <= off) {
3602                         path->slots[0]++;
3603                         goto process_slot;
3604                 } else if (key.offset >= off + len) {
3605                         break;
3606                 }
3607                 next_key_min_offset = key.offset + datal;
3608                 size = btrfs_item_size_nr(leaf, slot);
3609                 read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf, slot),
3610                                    size);
3611 
3612                 btrfs_release_path(path);
3613                 path->leave_spinning = 0;
3614 
3615                 memcpy(&new_key, &key, sizeof(new_key));
3616                 new_key.objectid = btrfs_ino(BTRFS_I(inode));
3617                 if (off <= key.offset)
3618                         new_key.offset = key.offset + destoff - off;
3619                 else
3620                         new_key.offset = destoff;
3621 
3622                 /*
3623                  * Deal with a hole that doesn't have an extent item that
3624                  * represents it (NO_HOLES feature enabled).
3625                  * This hole is either in the middle of the cloning range or at
3626                  * the beginning (fully overlaps it or partially overlaps it).
3627                  */
3628                 if (new_key.offset != last_dest_end)
3629                         drop_start = last_dest_end;
3630                 else
3631                         drop_start = new_key.offset;
3632 
3633                 if (type == BTRFS_FILE_EXTENT_REG ||
3634                     type == BTRFS_FILE_EXTENT_PREALLOC) {
3635                         struct btrfs_clone_extent_info clone_info;
3636 
3637                         /*
3638                          *    a  | --- range to clone ---|  b
3639                          * | ------------- extent ------------- |
3640                          */
3641 
3642                         /* Subtract range b */
3643                         if (key.offset + datal > off + len)
3644                                 datal = off + len - key.offset;
3645 
3646                         /* Subtract range a */
3647                         if (off > key.offset) {
3648                                 datao += off - key.offset;
3649                                 datal -= off - key.offset;
3650                         }
3651 
3652                         clone_info.disk_offset = disko;
3653                         clone_info.disk_len = diskl;
3654                         clone_info.data_offset = datao;
3655                         clone_info.data_len = datal;
3656                         clone_info.file_offset = new_key.offset;
3657                         clone_info.extent_buf = buf;
3658                         clone_info.item_size = size;
3659                         ret = btrfs_punch_hole_range(inode, path,
3660                                                      drop_start,
3661                                                      new_key.offset + datal - 1,
3662                                                      &clone_info, &trans);
3663                         if (ret)
3664                                 goto out;
3665                 } else if (type == BTRFS_FILE_EXTENT_INLINE) {
3666                         u64 skip = 0;
3667                         u64 trim = 0;
3668 
3669                         if (off > key.offset) {
3670                                 skip = off - key.offset;
3671                                 new_key.offset += skip;
3672                         }
3673 
3674                         if (key.offset + datal > off + len)
3675                                 trim = key.offset + datal - (off + len);
3676 
3677                         if (comp && (skip || trim)) {
3678                                 ret = -EINVAL;
3679                                 goto out;
3680                         }
3681                         size -= skip + trim;
3682                         datal -= skip + trim;
3683 
3684                         /*
3685                          * If our extent is inline, we know we will drop or
3686                          * adjust at most 1 extent item in the destination root.
3687                          *
3688                          * 1 - adjusting old extent (we may have to split it)
3689                          * 1 - add new extent
3690                          * 1 - inode update
3691                          */
3692                         trans = btrfs_start_transaction(root, 3);
3693                         if (IS_ERR(trans)) {
3694                                 ret = PTR_ERR(trans);
3695                                 goto out;
3696                         }
3697 
3698                         ret = clone_copy_inline_extent(inode, trans, path,
3699                                                        &new_key, drop_start,
3700                                                        datal, skip, size, buf);
3701                         if (ret) {
3702                                 if (ret != -EOPNOTSUPP)
3703                                         btrfs_abort_transaction(trans, ret);
3704                                 btrfs_end_transaction(trans);
3705                                 goto out;
3706                         }
3707                 }
3708 
3709                 btrfs_release_path(path);
3710 
3711                 last_dest_end = ALIGN(new_key.offset + datal,
3712                                       fs_info->sectorsize);
3713                 ret = clone_finish_inode_update(trans, inode, last_dest_end,
3714                                                 destoff, olen, no_time_update);
3715                 if (ret)
3716                         goto out;
3717                 if (new_key.offset + datal >= destoff + len)
3718                         break;
3719 
3720                 btrfs_release_path(path);
3721                 key.offset = next_key_min_offset;
3722 
3723                 if (fatal_signal_pending(current)) {
3724                         ret = -EINTR;
3725                         goto out;
3726                 }
3727         }
3728         ret = 0;
3729 
3730         if (last_dest_end < destoff + len) {
3731                 /*
3732                  * We have an implicit hole that fully or partially overlaps our
3733                  * cloning range at its end. This means that we either have the
3734                  * NO_HOLES feature enabled or the implicit hole happened due to
3735                  * mixing buffered and direct IO writes against this file.
3736                  */
3737                 btrfs_release_path(path);
3738                 path->leave_spinning = 0;
3739 
3740                 ret = btrfs_punch_hole_range(inode, path,
3741                                              last_dest_end, destoff + len - 1,
3742                                              NULL, &trans);
3743                 if (ret)
3744                         goto out;
3745 
3746                 ret = clone_finish_inode_update(trans, inode, destoff + len,
3747                                                 destoff, olen, no_time_update);
3748         }
3749 
3750 out:
3751         btrfs_free_path(path);
3752         kvfree(buf);
3753         return ret;
3754 }
3755 
3756 static noinline int btrfs_clone_files(struct file *file, struct file *file_src,
3757                                         u64 off, u64 olen, u64 destoff)
3758 {
3759         struct inode *inode = file_inode(file);
3760         struct inode *src = file_inode(file_src);
3761         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3762         int ret;
3763         u64 len = olen;
3764         u64 bs = fs_info->sb->s_blocksize;
3765 
3766         /*
3767          * TODO:
3768          * - split compressed inline extents.  annoying: we need to
3769          *   decompress into destination's address_space (the file offset
3770          *   may change, so source mapping won't do), then recompress (or
3771          *   otherwise reinsert) a subrange.
3772          *
3773          * - split destination inode's inline extents.  The inline extents can
3774          *   be either compressed or non-compressed.
3775          */
3776 
3777         /*
3778          * VFS's generic_remap_file_range_prep() protects us from cloning the
3779          * eof block into the middle of a file, which would result in corruption
3780          * if the file size is not blocksize aligned. So we don't need to check
3781          * for that case here.
3782          */
3783         if (off + len == src->i_size)
3784                 len = ALIGN(src->i_size, bs) - off;
3785 
3786         if (destoff > inode->i_size) {
3787                 const u64 wb_start = ALIGN_DOWN(inode->i_size, bs);
3788 
3789                 ret = btrfs_cont_expand(inode, inode->i_size, destoff);
3790                 if (ret)
3791                         return ret;
3792                 /*
3793                  * We may have truncated the last block if the inode's size is
3794                  * not sector size aligned, so we need to wait for writeback to
3795                  * complete before proceeding further, otherwise we can race
3796                  * with cloning and attempt to increment a reference to an
3797                  * extent that no longer exists (writeback completed right after
3798                  * we found the previous extent covering eof and before we
3799                  * attempted to increment its reference count).
3800                  */
3801                 ret = btrfs_wait_ordered_range(inode, wb_start,
3802                                                destoff - wb_start);
3803                 if (ret)
3804                         return ret;
3805         }
3806 
3807         /*
3808          * Lock destination range to serialize with concurrent readpages() and
3809          * source range to serialize with relocation.
3810          */
3811         btrfs_double_extent_lock(src, off, inode, destoff, len);
3812         ret = btrfs_clone(src, inode, off, olen, len, destoff, 0);
3813         btrfs_double_extent_unlock(src, off, inode, destoff, len);
3814         /*
3815          * Truncate page cache pages so that future reads will see the cloned
3816          * data immediately and not the previous data.
3817          */
3818         truncate_inode_pages_range(&inode->i_data,
3819                                 round_down(destoff, PAGE_SIZE),
3820                                 round_up(destoff + len, PAGE_SIZE) - 1);
3821 
3822         return ret;
3823 }
3824 
3825 static int btrfs_remap_file_range_prep(struct file *file_in, loff_t pos_in,
3826                                        struct file *file_out, loff_t pos_out,
3827                                        loff_t *len, unsigned int remap_flags)
3828 {
3829         struct inode *inode_in = file_inode(file_in);
3830         struct inode *inode_out = file_inode(file_out);
3831         u64 bs = BTRFS_I(inode_out)->root->fs_info->sb->s_blocksize;
3832         bool same_inode = inode_out == inode_in;
3833         u64 wb_len;
3834         int ret;
3835 
3836         if (!(remap_flags & REMAP_FILE_DEDUP)) {
3837                 struct btrfs_root *root_out = BTRFS_I(inode_out)->root;
3838 
3839                 if (btrfs_root_readonly(root_out))
3840                         return -EROFS;
3841 
3842                 if (file_in->f_path.mnt != file_out->f_path.mnt ||
3843                     inode_in->i_sb != inode_out->i_sb)
3844                         return -EXDEV;
3845         }
3846 
3847         /* don't make the dst file partly checksummed */
3848         if ((BTRFS_I(inode_in)->flags & BTRFS_INODE_NODATASUM) !=
3849             (BTRFS_I(inode_out)->flags & BTRFS_INODE_NODATASUM)) {
3850                 return -EINVAL;
3851         }
3852 
3853         /*
3854          * Now that the inodes are locked, we need to start writeback ourselves
3855          * and can not rely on the writeback from the VFS's generic helper
3856          * generic_remap_file_range_prep() because:
3857          *
3858          * 1) For compression we must call filemap_fdatawrite_range() range
3859          *    twice (btrfs_fdatawrite_range() does it for us), and the generic
3860          *    helper only calls it once;
3861          *
3862          * 2) filemap_fdatawrite_range(), called by the generic helper only
3863          *    waits for the writeback to complete, i.e. for IO to be done, and
3864          *    not for the ordered extents to complete. We need to wait for them
3865          *    to complete so that new file extent items are in the fs tree.
3866          */
3867         if (*len == 0 && !(remap_flags & REMAP_FILE_DEDUP))
3868                 wb_len = ALIGN(inode_in->i_size, bs) - ALIGN_DOWN(pos_in, bs);
3869         else
3870                 wb_len = ALIGN(*len, bs);
3871 
3872         /*
3873          * Since we don't lock ranges, wait for ongoing lockless dio writes (as
3874          * any in progress could create its ordered extents after we wait for
3875          * existing ordered extents below).
3876          */
3877         inode_dio_wait(inode_in);
3878         if (!same_inode)
3879                 inode_dio_wait(inode_out);
3880 
3881         /*
3882          * Workaround to make sure NOCOW buffered write reach disk as NOCOW.
3883          *
3884          * Btrfs' back references do not have a block level granularity, they
3885          * work at the whole extent level.
3886          * NOCOW buffered write without data space reserved may not be able
3887          * to fall back to CoW due to lack of data space, thus could cause
3888          * data loss.
3889          *
3890          * Here we take a shortcut by flushing the whole inode, so that all
3891          * nocow write should reach disk as nocow before we increase the
3892          * reference of the extent. We could do better by only flushing NOCOW
3893          * data, but that needs extra accounting.
3894          *
3895          * Also we don't need to check ASYNC_EXTENT, as async extent will be
3896          * CoWed anyway, not affecting nocow part.
3897          */
3898         ret = filemap_flush(inode_in->i_mapping);
3899         if (ret < 0)
3900                 return ret;
3901 
3902         ret = btrfs_wait_ordered_range(inode_in, ALIGN_DOWN(pos_in, bs),
3903                                        wb_len);
3904         if (ret < 0)
3905                 return ret;
3906         ret = btrfs_wait_ordered_range(inode_out, ALIGN_DOWN(pos_out, bs),
3907                                        wb_len);
3908         if (ret < 0)
3909                 return ret;
3910 
3911         return generic_remap_file_range_prep(file_in, pos_in, file_out, pos_out,
3912                                             len, remap_flags);
3913 }
3914 
3915 loff_t btrfs_remap_file_range(struct file *src_file, loff_t off,
3916                 struct file *dst_file, loff_t destoff, loff_t len,
3917                 unsigned int remap_flags)
3918 {
3919         struct inode *src_inode = file_inode(src_file);
3920         struct inode *dst_inode = file_inode(dst_file);
3921         bool same_inode = dst_inode == src_inode;
3922         int ret;
3923 
3924         if (remap_flags & ~(REMAP_FILE_DEDUP | REMAP_FILE_ADVISORY))
3925                 return -EINVAL;
3926 
3927         if (same_inode)
3928                 inode_lock(src_inode);
3929         else
3930                 lock_two_nondirectories(src_inode, dst_inode);
3931 
3932         ret = btrfs_remap_file_range_prep(src_file, off, dst_file, destoff,
3933                                           &len, remap_flags);
3934         if (ret < 0 || len == 0)
3935                 goto out_unlock;
3936 
3937         if (remap_flags & REMAP_FILE_DEDUP)
3938                 ret = btrfs_extent_same(src_inode, off, len, dst_inode, destoff);
3939         else
3940                 ret = btrfs_clone_files(dst_file, src_file, off, len, destoff);
3941 
3942 out_unlock:
3943         if (same_inode)
3944                 inode_unlock(src_inode);
3945         else
3946                 unlock_two_nondirectories(src_inode, dst_inode);
3947 
3948         return ret < 0 ? ret : len;
3949 }
3950 
3951 static long btrfs_ioctl_default_subvol(struct file *file, void __user *argp)
3952 {
3953         struct inode *inode = file_inode(file);
3954         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3955         struct btrfs_root *root = BTRFS_I(inode)->root;
3956         struct btrfs_root *new_root;
3957         struct btrfs_dir_item *di;
3958         struct btrfs_trans_handle *trans;
3959         struct btrfs_path *path;
3960         struct btrfs_key location;
3961         struct btrfs_disk_key disk_key;
3962         u64 objectid = 0;
3963         u64 dir_id;
3964         int ret;
3965 
3966         if (!capable(CAP_SYS_ADMIN))
3967                 return -EPERM;
3968 
3969         ret = mnt_want_write_file(file);
3970         if (ret)
3971                 return ret;
3972 
3973         if (copy_from_user(&objectid, argp, sizeof(objectid))) {
3974                 ret = -EFAULT;
3975                 goto out;
3976         }
3977 
3978         if (!objectid)
3979                 objectid = BTRFS_FS_TREE_OBJECTID;
3980 
3981         location.objectid = objectid;
3982         location.type = BTRFS_ROOT_ITEM_KEY;
3983         location.offset = (u64)-1;
3984 
3985         new_root = btrfs_read_fs_root_no_name(fs_info, &location);
3986         if (IS_ERR(new_root)) {
3987                 ret = PTR_ERR(new_root);
3988                 goto out;
3989         }
3990         if (!is_fstree(new_root->root_key.objectid)) {
3991                 ret = -ENOENT;
3992                 goto out;
3993         }
3994 
3995         path = btrfs_alloc_path();
3996         if (!path) {
3997                 ret = -ENOMEM;
3998                 goto out;
3999         }
4000         path->leave_spinning = 1;
4001 
4002         trans = btrfs_start_transaction(root, 1);
4003         if (IS_ERR(trans)) {
4004                 btrfs_free_path(path);
4005                 ret = PTR_ERR(trans);
4006                 goto out;
4007         }
4008 
4009         dir_id = btrfs_super_root_dir(fs_info->super_copy);
4010         di = btrfs_lookup_dir_item(trans, fs_info->tree_root, path,
4011                                    dir_id, "default", 7, 1);
4012         if (IS_ERR_OR_NULL(di)) {
4013                 btrfs_free_path(path);
4014                 btrfs_end_transaction(trans);
4015                 btrfs_err(fs_info,
4016                           "Umm, you don't have the default diritem, this isn't going to work");
4017                 ret = -ENOENT;
4018                 goto out;
4019         }
4020 
4021         btrfs_cpu_key_to_disk(&disk_key, &new_root->root_key);
4022         btrfs_set_dir_item_key(path->nodes[0], di, &disk_key);
4023         btrfs_mark_buffer_dirty(path->nodes[0]);
4024         btrfs_free_path(path);
4025 
4026         btrfs_set_fs_incompat(fs_info, DEFAULT_SUBVOL);
4027         btrfs_end_transaction(trans);
4028 out:
4029         mnt_drop_write_file(file);
4030         return ret;
4031 }
4032 
4033 static void get_block_group_info(struct list_head *groups_list,
4034                                  struct btrfs_ioctl_space_info *space)
4035 {
4036         struct btrfs_block_group_cache *block_group;
4037 
4038         space->total_bytes = 0;
4039         space->used_bytes = 0;
4040         space->flags = 0;
4041         list_for_each_entry(block_group, groups_list, list) {
4042                 space->flags = block_group->flags;
4043                 space->total_bytes += block_group->key.offset;
4044                 space->used_bytes +=
4045                         btrfs_block_group_used(&block_group->item);
4046         }
4047 }
4048 
4049 static long btrfs_ioctl_space_info(struct btrfs_fs_info *fs_info,
4050                                    void __user *arg)
4051 {
4052         struct btrfs_ioctl_space_args space_args;
4053         struct btrfs_ioctl_space_info space;
4054         struct btrfs_ioctl_space_info *dest;
4055         struct btrfs_ioctl_space_info *dest_orig;
4056         struct btrfs_ioctl_space_info __user *user_dest;
4057         struct btrfs_space_info *info;
4058         static const u64 types[] = {
4059                 BTRFS_BLOCK_GROUP_DATA,
4060                 BTRFS_BLOCK_GROUP_SYSTEM,
4061                 BTRFS_BLOCK_GROUP_METADATA,
4062                 BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA
4063         };
4064         int num_types = 4;
4065         int alloc_size;
4066         int ret = 0;
4067         u64 slot_count = 0;
4068         int i, c;
4069 
4070         if (copy_from_user(&space_args,
4071                            (struct btrfs_ioctl_space_args __user *)arg,
4072                            sizeof(space_args)))
4073                 return -EFAULT;
4074 
4075         for (i = 0; i < num_types; i++) {
4076                 struct btrfs_space_info *tmp;
4077 
4078                 info = NULL;
4079                 rcu_read_lock();
4080                 list_for_each_entry_rcu(tmp, &fs_info->space_info,
4081                                         list) {
4082                         if (tmp->flags == types[i]) {
4083                                 info = tmp;
4084                                 break;
4085                         }
4086                 }
4087                 rcu_read_unlock();
4088 
4089                 if (!info)
4090                         continue;
4091 
4092                 down_read(&info->groups_sem);
4093                 for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
4094                         if (!list_empty(&info->block_groups[c]))
4095                                 slot_count++;
4096                 }
4097                 up_read(&info->groups_sem);
4098         }
4099 
4100         /*
4101          * Global block reserve, exported as a space_info
4102          */
4103         slot_count++;
4104 
4105         /* space_slots == 0 means they are asking for a count */
4106         if (space_args.space_slots == 0) {
4107                 space_args.total_spaces = slot_count;
4108                 goto out;
4109         }
4110 
4111         slot_count = min_t(u64, space_args.space_slots, slot_count);
4112 
4113         alloc_size = sizeof(*dest) * slot_count;
4114 
4115         /* we generally have at most 6 or so space infos, one for each raid
4116          * level.  So, a whole page should be more than enough for everyone
4117          */
4118         if (alloc_size > PAGE_SIZE)
4119                 return -ENOMEM;
4120 
4121         space_args.total_spaces = 0;
4122         dest = kmalloc(alloc_size, GFP_KERNEL);
4123         if (!dest)
4124                 return -ENOMEM;
4125         dest_orig = dest;
4126 
4127         /* now we have a buffer to copy into */
4128         for (i = 0; i < num_types; i++) {
4129                 struct btrfs_space_info *tmp;
4130 
4131                 if (!slot_count)
4132                         break;
4133 
4134                 info = NULL;
4135                 rcu_read_lock();
4136                 list_for_each_entry_rcu(tmp, &fs_info->space_info,
4137                                         list) {
4138                         if (tmp->flags == types[i]) {
4139                                 info = tmp;
4140                                 break;
4141                         }
4142                 }
4143                 rcu_read_unlock();
4144 
4145                 if (!info)
4146                         continue;
4147                 down_read(&info->groups_sem);
4148                 for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
4149                         if (!list_empty(&info->block_groups[c])) {
4150                                 get_block_group_info(&info->block_groups[c],
4151                                                      &space);
4152                                 memcpy(dest, &space, sizeof(space));
4153                                 dest++;
4154                                 space_args.total_spaces++;
4155                                 slot_count--;
4156                         }
4157                         if (!slot_count)
4158                                 break;
4159                 }
4160                 up_read(&info->groups_sem);
4161         }
4162 
4163         /*
4164          * Add global block reserve
4165          */
4166         if (slot_count) {
4167                 struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
4168 
4169                 spin_lock(&block_rsv->lock);
4170                 space.total_bytes = block_rsv->size;
4171                 space.used_bytes = block_rsv->size - block_rsv->reserved;
4172                 spin_unlock(&block_rsv->lock);
4173                 space.flags = BTRFS_SPACE_INFO_GLOBAL_RSV;
4174                 memcpy(dest, &space, sizeof(space));
4175                 space_args.total_spaces++;
4176         }
4177 
4178         user_dest = (struct btrfs_ioctl_space_info __user *)
4179                 (arg + sizeof(struct btrfs_ioctl_space_args));
4180 
4181         if (copy_to_user(user_dest, dest_orig, alloc_size))
4182                 ret = -EFAULT;
4183 
4184         kfree(dest_orig);
4185 out:
4186         if (ret == 0 && copy_to_user(arg, &space_args, sizeof(space_args)))
4187                 ret = -EFAULT;
4188 
4189         return ret;
4190 }
4191 
4192 static noinline long btrfs_ioctl_start_sync(struct btrfs_root *root,
4193                                             void __user *argp)
4194 {
4195         struct btrfs_trans_handle *trans;
4196         u64 transid;
4197         int ret;
4198 
4199         trans = btrfs_attach_transaction_barrier(root);
4200         if (IS_ERR(trans)) {
4201                 if (PTR_ERR(trans) != -ENOENT)
4202                         return PTR_ERR(trans);
4203 
4204                 /* No running transaction, don't bother */
4205                 transid = root->fs_info->last_trans_committed;
4206                 goto out;
4207         }
4208         transid = trans->transid;
4209         ret = btrfs_commit_transaction_async(trans, 0);
4210         if (ret) {
4211                 btrfs_end_transaction(trans);
4212                 return ret;
4213         }
4214 out:
4215         if (argp)
4216                 if (copy_to_user(argp, &transid, sizeof(transid)))
4217                         return -EFAULT;
4218         return 0;
4219 }
4220 
4221 static noinline long btrfs_ioctl_wait_sync(struct btrfs_fs_info *fs_info,
4222                                            void __user *argp)
4223 {
4224         u64 transid;
4225 
4226         if (argp) {
4227                 if (copy_from_user(&transid, argp, sizeof(transid)))
4228                         return -EFAULT;
4229         } else {
4230                 transid = 0;  /* current trans */
4231         }
4232         return btrfs_wait_for_commit(fs_info, transid);
4233 }
4234 
4235 static long btrfs_ioctl_scrub(struct file *file, void __user *arg)
4236 {
4237         struct btrfs_fs_info *fs_info = btrfs_sb(file_inode(file)->i_sb);
4238         struct btrfs_ioctl_scrub_args *sa;
4239         int ret;
4240 
4241         if (!capable(CAP_SYS_ADMIN))
4242                 return -EPERM;
4243 
4244         sa = memdup_user(arg, sizeof(*sa));
4245         if (IS_ERR(sa))
4246                 return PTR_ERR(sa);
4247 
4248         if (!(sa->flags & BTRFS_SCRUB_READONLY)) {
4249                 ret = mnt_want_write_file(file);
4250                 if (ret)
4251                         goto out;
4252         }
4253 
4254         ret = btrfs_scrub_dev(fs_info, sa->devid, sa->start, sa->end,
4255                               &sa->progress, sa->flags & BTRFS_SCRUB_READONLY,
4256                               0);
4257 
4258         /*
4259          * Copy scrub args to user space even if btrfs_scrub_dev() returned an
4260          * error. This is important as it allows user space to know how much
4261          * progress scrub has done. For example, if scrub is canceled we get
4262          * -ECANCELED from btrfs_scrub_dev() and return that error back to user
4263          * space. Later user space can inspect the progress from the structure
4264          * btrfs_ioctl_scrub_args and resume scrub from where it left off
4265          * previously (btrfs-progs does this).
4266          * If we fail to copy the btrfs_ioctl_scrub_args structure to user space
4267          * then return -EFAULT to signal the structure was not copied or it may
4268          * be corrupt and unreliable due to a partial copy.
4269          */
4270         if (copy_to_user(arg, sa, sizeof(*sa)))
4271                 ret = -EFAULT;
4272 
4273         if (!(sa->flags & BTRFS_SCRUB_READONLY))
4274                 mnt_drop_write_file(file);
4275 out:
4276         kfree(sa);
4277         return ret;
4278 }
4279 
4280 static long btrfs_ioctl_scrub_cancel(struct btrfs_fs_info *fs_info)
4281 {
4282         if (!capable(CAP_SYS_ADMIN))
4283                 return -EPERM;
4284 
4285         return btrfs_scrub_cancel(fs_info);
4286 }
4287 
4288 static long btrfs_ioctl_scrub_progress(struct btrfs_fs_info *fs_info,
4289                                        void __user *arg)
4290 {
4291         struct btrfs_ioctl_scrub_args *sa;
4292         int ret;
4293 
4294         if (!capable(CAP_SYS_ADMIN))
4295                 return -EPERM;
4296 
4297         sa = memdup_user(arg, sizeof(*sa));
4298         if (IS_ERR(sa))
4299                 return PTR_ERR(sa);
4300 
4301         ret = btrfs_scrub_progress(fs_info, sa->devid, &sa->progress);
4302 
4303         if (ret == 0 && copy_to_user(arg, sa, sizeof(*sa)))
4304                 ret = -EFAULT;
4305 
4306         kfree(sa);
4307         return ret;
4308 }
4309 
4310 static long btrfs_ioctl_get_dev_stats(struct btrfs_fs_info *fs_info,
4311                                       void __user *arg)
4312 {
4313         struct btrfs_ioctl_get_dev_stats *sa;
4314         int ret;
4315 
4316         sa = memdup_user(arg, sizeof(*sa));
4317         if (IS_ERR(sa))
4318                 return PTR_ERR(sa);
4319 
4320         if ((sa->flags & BTRFS_DEV_STATS_RESET) && !capable(CAP_SYS_ADMIN)) {
4321                 kfree(sa);
4322                 return -EPERM;
4323         }
4324 
4325         ret = btrfs_get_dev_stats(fs_info, sa);
4326 
4327         if (ret == 0 && copy_to_user(arg, sa, sizeof(*sa)))
4328                 ret = -EFAULT;
4329 
4330         kfree(sa);
4331         return ret;
4332 }
4333 
4334 static long btrfs_ioctl_dev_replace(struct btrfs_fs_info *fs_info,
4335                                     void __user *arg)
4336 {
4337         struct btrfs_ioctl_dev_replace_args *p;
4338         int ret;
4339 
4340         if (!capable(CAP_SYS_ADMIN))
4341                 return -EPERM;
4342 
4343         p = memdup_user(arg, sizeof(*p));
4344         if (IS_ERR(p))
4345                 return PTR_ERR(p);
4346 
4347         switch (p->cmd) {
4348         case BTRFS_IOCTL_DEV_REPLACE_CMD_START:
4349                 if (sb_rdonly(fs_info->sb)) {
4350                         ret = -EROFS;
4351                         goto out;
4352                 }
4353                 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
4354                         ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
4355                 } else {
4356                         ret = btrfs_dev_replace_by_ioctl(fs_info, p);
4357                         clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4358                 }
4359                 break;
4360         case BTRFS_IOCTL_DEV_REPLACE_CMD_STATUS:
4361                 btrfs_dev_replace_status(fs_info, p);
4362                 ret = 0;
4363                 break;
4364         case BTRFS_IOCTL_DEV_REPLACE_CMD_CANCEL:
4365                 p->result = btrfs_dev_replace_cancel(fs_info);
4366                 ret = 0;
4367                 break;
4368         default:
4369                 ret = -EINVAL;
4370                 break;
4371         }
4372 
4373         if ((ret == 0 || ret == -ECANCELED) && copy_to_user(arg, p, sizeof(*p)))
4374                 ret = -EFAULT;
4375 out:
4376         kfree(p);
4377         return ret;
4378 }
4379 
4380 static long btrfs_ioctl_ino_to_path(struct btrfs_root *root, void __user *arg)
4381 {
4382         int ret = 0;
4383         int i;
4384         u64 rel_ptr;
4385         int size;
4386         struct btrfs_ioctl_ino_path_args *ipa = NULL;
4387         struct inode_fs_paths *ipath = NULL;
4388         struct btrfs_path *path;
4389 
4390         if (!capable(CAP_DAC_READ_SEARCH))
4391                 return -EPERM;
4392 
4393         path = btrfs_alloc_path();
4394         if (!path) {
4395                 ret = -ENOMEM;
4396                 goto out;
4397         }
4398 
4399         ipa = memdup_user(arg, sizeof(*ipa));
4400         if (IS_ERR(ipa)) {
4401                 ret = PTR_ERR(ipa);
4402                 ipa = NULL;
4403                 goto out;
4404         }
4405 
4406         size = min_t(u32, ipa->size, 4096);
4407         ipath = init_ipath(size, root, path);
4408         if (IS_ERR(ipath)) {
4409                 ret = PTR_ERR(ipath);
4410                 ipath = NULL;
4411                 goto out;
4412         }
4413 
4414         ret = paths_from_inode(ipa->inum, ipath);
4415         if (ret < 0)
4416                 goto out;
4417 
4418         for (i = 0; i < ipath->fspath->elem_cnt; ++i) {
4419                 rel_ptr = ipath->fspath->val[i] -
4420                           (u64)(unsigned long)ipath->fspath->val;
4421                 ipath->fspath->val[i] = rel_ptr;
4422         }
4423 
4424         ret = copy_to_user((void __user *)(unsigned long)ipa->fspath,
4425                            ipath->fspath, size);
4426         if (ret) {
4427                 ret = -EFAULT;
4428                 goto out;
4429         }
4430 
4431 out:
4432         btrfs_free_path(path);
4433         free_ipath(ipath);
4434         kfree(ipa);
4435 
4436         return ret;
4437 }
4438 
4439 static int build_ino_list(u64 inum, u64 offset, u64 root, void *ctx)
4440 {
4441         struct btrfs_data_container *inodes = ctx;
4442         const size_t c = 3 * sizeof(u64);
4443 
4444         if (inodes->bytes_left >= c) {
4445                 inodes->bytes_left -= c;
4446                 inodes->val[inodes->elem_cnt] = inum;
4447                 inodes->val[inodes->elem_cnt + 1] = offset;
4448                 inodes->val[inodes->elem_cnt + 2] = root;
4449                 inodes->elem_cnt += 3;
4450         } else {
4451                 inodes->bytes_missing += c - inodes->bytes_left;
4452                 inodes->bytes_left = 0;
4453                 inodes->elem_missed += 3;
4454         }
4455 
4456         return 0;
4457 }
4458 
4459 static long btrfs_ioctl_logical_to_ino(struct btrfs_fs_info *fs_info,
4460                                         void __user *arg, int version)
4461 {
4462         int ret = 0;
4463         int size;
4464         struct btrfs_ioctl_logical_ino_args *loi;
4465         struct btrfs_data_container *inodes = NULL;
4466         struct btrfs_path *path = NULL;
4467         bool ignore_offset;
4468 
4469         if (!capable(CAP_SYS_ADMIN))
4470                 return -EPERM;
4471 
4472         loi = memdup_user(arg, sizeof(*loi));
4473         if (IS_ERR(loi))
4474                 return PTR_ERR(loi);
4475 
4476         if (version == 1) {
4477                 ignore_offset = false;
4478                 size = min_t(u32, loi->size, SZ_64K);
4479         } else {
4480                 /* All reserved bits must be 0 for now */
4481                 if (memchr_inv(loi->reserved, 0, sizeof(loi->reserved))) {
4482                         ret = -EINVAL;
4483                         goto out_loi;
4484                 }
4485                 /* Only accept flags we have defined so far */
4486                 if (loi->flags & ~(BTRFS_LOGICAL_INO_ARGS_IGNORE_OFFSET)) {
4487                         ret = -EINVAL;
4488                         goto out_loi;
4489                 }
4490                 ignore_offset = loi->flags & BTRFS_LOGICAL_INO_ARGS_IGNORE_OFFSET;
4491                 size = min_t(u32, loi->size, SZ_16M);
4492         }
4493 
4494         path = btrfs_alloc_path();
4495         if (!path) {
4496                 ret = -ENOMEM;
4497                 goto out;
4498         }
4499 
4500         inodes = init_data_container(size);
4501         if (IS_ERR(inodes)) {
4502                 ret = PTR_ERR(inodes);
4503                 inodes = NULL;
4504                 goto out;
4505         }
4506 
4507         ret = iterate_inodes_from_logical(loi->logical, fs_info, path,
4508                                           build_ino_list, inodes, ignore_offset);
4509         if (ret == -EINVAL)
4510                 ret = -ENOENT;
4511         if (ret < 0)
4512                 goto out;
4513 
4514         ret = copy_to_user((void __user *)(unsigned long)loi->inodes, inodes,
4515                            size);
4516         if (ret)
4517                 ret = -EFAULT;
4518 
4519 out:
4520         btrfs_free_path(path);
4521         kvfree(inodes);
4522 out_loi:
4523         kfree(loi);
4524 
4525         return ret;
4526 }
4527 
4528 void btrfs_update_ioctl_balance_args(struct btrfs_fs_info *fs_info,
4529                                struct btrfs_ioctl_balance_args *bargs)
4530 {
4531         struct btrfs_balance_control *bctl = fs_info->balance_ctl;
4532 
4533         bargs->flags = bctl->flags;
4534 
4535         if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags))
4536                 bargs->state |= BTRFS_BALANCE_STATE_RUNNING;
4537         if (atomic_read(&fs_info->balance_pause_req))
4538                 bargs->state |= BTRFS_BALANCE_STATE_PAUSE_REQ;
4539         if (atomic_read(&fs_info->balance_cancel_req))
4540                 bargs->state |= BTRFS_BALANCE_STATE_CANCEL_REQ;
4541 
4542         memcpy(&bargs->data, &bctl->data, sizeof(bargs->data));
4543         memcpy(&bargs->meta, &bctl->meta, sizeof(bargs->meta));
4544         memcpy(&bargs->sys, &bctl->sys, sizeof(bargs->sys));
4545 
4546         spin_lock(&fs_info->balance_lock);
4547         memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat));
4548         spin_unlock(&fs_info->balance_lock);
4549 }
4550 
4551 static long btrfs_ioctl_balance(struct file *file, void __user *arg)
4552 {
4553         struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4554         struct btrfs_fs_info *fs_info = root->fs_info;
4555         struct btrfs_ioctl_balance_args *bargs;
4556         struct btrfs_balance_control *bctl;
4557         bool need_unlock; /* for mut. excl. ops lock */
4558         int ret;
4559 
4560         if (!capable(CAP_SYS_ADMIN))
4561                 return -EPERM;
4562 
4563         ret = mnt_want_write_file(file);
4564         if (ret)
4565                 return ret;
4566 
4567 again:
4568         if (!test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
4569                 mutex_lock(&fs_info->balance_mutex);
4570                 need_unlock = true;
4571                 goto locked;
4572         }
4573 
4574         /*
4575          * mut. excl. ops lock is locked.  Three possibilities:
4576          *   (1) some other op is running
4577          *   (2) balance is running
4578          *   (3) balance is paused -- special case (think resume)
4579          */
4580         mutex_lock(&fs_info->balance_mutex);
4581         if (fs_info->balance_ctl) {
4582                 /* this is either (2) or (3) */
4583                 if (!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4584                         mutex_unlock(&fs_info->balance_mutex);
4585                         /*
4586                          * Lock released to allow other waiters to continue,
4587                          * we'll reexamine the status again.
4588                          */
4589                         mutex_lock(&fs_info->balance_mutex);
4590 
4591                         if (fs_info->balance_ctl &&
4592                             !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4593                                 /* this is (3) */
4594                                 need_unlock = false;
4595                                 goto locked;
4596                         }
4597 
4598                         mutex_unlock(&fs_info->balance_mutex);
4599                         goto again;
4600                 } else {
4601                         /* this is (2) */
4602                         mutex_unlock(&fs_info->balance_mutex);
4603                         ret = -EINPROGRESS;
4604                         goto out;
4605                 }
4606         } else {
4607                 /* this is (1) */
4608                 mutex_unlock(&fs_info->balance_mutex);
4609                 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
4610                 goto out;
4611         }
4612 
4613 locked:
4614         BUG_ON(!test_bit(BTRFS_FS_EXCL_OP, &fs_info->flags));
4615 
4616         if (arg) {
4617                 bargs = memdup_user(arg, sizeof(*bargs));
4618                 if (IS_ERR(bargs)) {
4619                         ret = PTR_ERR(bargs);
4620                         goto out_unlock;
4621                 }
4622 
4623                 if (bargs->flags & BTRFS_BALANCE_RESUME) {
4624                         if (!fs_info->balance_ctl) {
4625                                 ret = -ENOTCONN;
4626                                 goto out_bargs;
4627                         }
4628 
4629                         bctl = fs_info->balance_ctl;
4630                         spin_lock(&fs_info->balance_lock);
4631                         bctl->flags |= BTRFS_BALANCE_RESUME;
4632                         spin_unlock(&fs_info->balance_lock);
4633 
4634                         goto do_balance;
4635                 }
4636         } else {
4637                 bargs = NULL;
4638         }
4639 
4640         if (fs_info->balance_ctl) {
4641                 ret = -EINPROGRESS;
4642                 goto out_bargs;
4643         }
4644 
4645         bctl = kzalloc(sizeof(*bctl), GFP_KERNEL);
4646         if (!bctl) {
4647                 ret = -ENOMEM;
4648                 goto out_bargs;
4649         }
4650 
4651         if (arg) {
4652                 memcpy(&bctl->data, &bargs->data, sizeof(bctl->data));
4653                 memcpy(&bctl->meta, &bargs->meta, sizeof(bctl->meta));
4654                 memcpy(&bctl->sys, &bargs->sys, sizeof(bctl->sys));
4655 
4656                 bctl->flags = bargs->flags;
4657         } else {
4658                 /* balance everything - no filters */
4659                 bctl->flags |= BTRFS_BALANCE_TYPE_MASK;
4660         }
4661 
4662         if (bctl->flags & ~(BTRFS_BALANCE_ARGS_MASK | BTRFS_BALANCE_TYPE_MASK)) {
4663                 ret = -EINVAL;
4664                 goto out_bctl;
4665         }
4666 
4667 do_balance:
4668         /*
4669          * Ownership of bctl and filesystem flag BTRFS_FS_EXCL_OP goes to
4670          * btrfs_balance.  bctl is freed in reset_balance_state, or, if
4671          * restriper was paused all the way until unmount, in free_fs_info.
4672          * The flag should be cleared after reset_balance_state.
4673          */
4674         need_unlock = false;
4675 
4676         ret = btrfs_balance(fs_info, bctl, bargs);
4677         bctl = NULL;
4678 
4679         if ((ret == 0 || ret == -ECANCELED) && arg) {
4680                 if (copy_to_user(arg, bargs, sizeof(*bargs)))
4681                         ret = -EFAULT;
4682         }
4683 
4684 out_bctl:
4685         kfree(bctl);
4686 out_bargs:
4687         kfree(bargs);
4688 out_unlock:
4689         mutex_unlock(&fs_info->balance_mutex);
4690         if (need_unlock)
4691                 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4692 out:
4693         mnt_drop_write_file(file);
4694         return ret;
4695 }
4696 
4697 static long btrfs_ioctl_balance_ctl(struct btrfs_fs_info *fs_info, int cmd)
4698 {
4699         if (!capable(CAP_SYS_ADMIN))
4700                 return -EPERM;
4701 
4702         switch (cmd) {
4703         case BTRFS_BALANCE_CTL_PAUSE:
4704                 return btrfs_pause_balance(fs_info);
4705         case BTRFS_BALANCE_CTL_CANCEL:
4706                 return btrfs_cancel_balance(fs_info);
4707         }
4708 
4709         return -EINVAL;
4710 }
4711 
4712 static long btrfs_ioctl_balance_progress(struct btrfs_fs_info *fs_info,
4713                                          void __user *arg)
4714 {
4715         struct btrfs_ioctl_balance_args *bargs;
4716         int ret = 0;
4717 
4718         if (!capable(CAP_SYS_ADMIN))
4719                 return -EPERM;
4720 
4721         mutex_lock(&fs_info->balance_mutex);
4722         if (!fs_info->balance_ctl) {
4723                 ret = -ENOTCONN;
4724                 goto out;
4725         }
4726 
4727         bargs = kzalloc(sizeof(*bargs), GFP_KERNEL);
4728         if (!bargs) {
4729                 ret = -ENOMEM;
4730                 goto out;
4731         }
4732 
4733         btrfs_update_ioctl_balance_args(fs_info, bargs);
4734 
4735         if (copy_to_user(arg, bargs, sizeof(*bargs)))
4736                 ret = -EFAULT;
4737 
4738         kfree(bargs);
4739 out:
4740         mutex_unlock(&fs_info->balance_mutex);
4741         return ret;
4742 }
4743 
4744 static long btrfs_ioctl_quota_ctl(struct file *file, void __user *arg)
4745 {
4746         struct inode *inode = file_inode(file);
4747         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4748         struct btrfs_ioctl_quota_ctl_args *sa;
4749         int ret;
4750 
4751         if (!capable(CAP_SYS_ADMIN))
4752                 return -EPERM;
4753 
4754         ret = mnt_want_write_file(file);
4755         if (ret)
4756                 return ret;
4757 
4758         sa = memdup_user(arg, sizeof(*sa));
4759         if (IS_ERR(sa)) {
4760                 ret = PTR_ERR(sa);
4761                 goto drop_write;
4762         }
4763 
4764         down_write(&fs_info->subvol_sem);
4765 
4766         switch (sa->cmd) {
4767         case BTRFS_QUOTA_CTL_ENABLE:
4768                 ret = btrfs_quota_enable(fs_info);
4769                 break;
4770         case BTRFS_QUOTA_CTL_DISABLE:
4771                 ret = btrfs_quota_disable(fs_info);
4772                 break;
4773         default:
4774                 ret = -EINVAL;
4775                 break;
4776         }
4777 
4778         kfree(sa);
4779         up_write(&fs_info->subvol_sem);
4780 drop_write:
4781         mnt_drop_write_file(file);
4782         return ret;
4783 }
4784 
4785 static long btrfs_ioctl_qgroup_assign(struct file *file, void __user *arg)
4786 {
4787         struct inode *inode = file_inode(file);
4788         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4789         struct btrfs_root *root = BTRFS_I(inode)->root;
4790         struct btrfs_ioctl_qgroup_assign_args *sa;
4791         struct btrfs_trans_handle *trans;
4792         int ret;
4793         int err;
4794 
4795         if (!capable(CAP_SYS_ADMIN))
4796                 return -EPERM;
4797 
4798         ret = mnt_want_write_file(file);
4799         if (ret)
4800                 return ret;
4801 
4802         sa = memdup_user(arg, sizeof(*sa));
4803         if (IS_ERR(sa)) {
4804                 ret = PTR_ERR(sa);
4805                 goto drop_write;
4806         }
4807 
4808         trans = btrfs_join_transaction(root);
4809         if (IS_ERR(trans)) {
4810                 ret = PTR_ERR(trans);
4811                 goto out;
4812         }
4813 
4814         if (sa->assign) {
4815                 ret = btrfs_add_qgroup_relation(trans, sa->src, sa->dst);
4816         } else {
4817                 ret = btrfs_del_qgroup_relation(trans, sa->src, sa->dst);
4818         }
4819 
4820         /* update qgroup status and info */
4821         err = btrfs_run_qgroups(trans);
4822         if (err < 0)
4823                 btrfs_handle_fs_error(fs_info, err,
4824                                       "failed to update qgroup status and info");
4825         err = btrfs_end_transaction(trans);
4826         if (err && !ret)
4827                 ret = err;
4828 
4829 out:
4830         kfree(sa);
4831 drop_write:
4832         mnt_drop_write_file(file);
4833         return ret;
4834 }
4835 
4836 static long btrfs_ioctl_qgroup_create(struct file *file, void __user *arg)
4837 {
4838         struct inode *inode = file_inode(file);
4839         struct btrfs_root *root = BTRFS_I(inode)->root;
4840         struct btrfs_ioctl_qgroup_create_args *sa;
4841         struct btrfs_trans_handle *trans;
4842         int ret;
4843         int err;
4844 
4845         if (!capable(CAP_SYS_ADMIN))
4846                 return -EPERM;
4847 
4848         ret = mnt_want_write_file(file);
4849         if (ret)
4850                 return ret;
4851 
4852         sa = memdup_user(arg, sizeof(*sa));
4853         if (IS_ERR(sa)) {
4854                 ret = PTR_ERR(sa);
4855                 goto drop_write;
4856         }
4857 
4858         if (!sa->qgroupid) {
4859                 ret = -EINVAL;
4860                 goto out;
4861         }
4862 
4863         trans = btrfs_join_transaction(root);
4864         if (IS_ERR(trans)) {
4865                 ret = PTR_ERR(trans);
4866                 goto out;
4867         }
4868 
4869         if (sa->create) {
4870                 ret = btrfs_create_qgroup(trans, sa->qgroupid);
4871         } else {
4872                 ret = btrfs_remove_qgroup(trans, sa->qgroupid);
4873         }
4874 
4875         err = btrfs_end_transaction(trans);
4876         if (err && !ret)
4877                 ret = err;
4878 
4879 out:
4880         kfree(sa);
4881 drop_write:
4882         mnt_drop_write_file(file);
4883         return ret;
4884 }
4885 
4886 static long btrfs_ioctl_qgroup_limit(struct file *file, void __user *arg)
4887 {
4888         struct inode *inode = file_inode(file);
4889         struct btrfs_root *root = BTRFS_I(inode)->root;
4890         struct btrfs_ioctl_qgroup_limit_args *sa;
4891         struct btrfs_trans_handle *trans;
4892         int ret;
4893         int err;
4894         u64 qgroupid;
4895 
4896         if (!capable(CAP_SYS_ADMIN))
4897                 return -EPERM;
4898 
4899         ret = mnt_want_write_file(file);
4900         if (ret)
4901                 return ret;
4902 
4903         sa = memdup_user(arg, sizeof(*sa));
4904         if (IS_ERR(sa)) {
4905                 ret = PTR_ERR(sa);
4906                 goto drop_write;
4907         }
4908 
4909         trans = btrfs_join_transaction(root);
4910         if (IS_ERR(trans)) {
4911                 ret = PTR_ERR(trans);
4912                 goto out;
4913         }
4914 
4915         qgroupid = sa->qgroupid;
4916         if (!qgroupid) {
4917                 /* take the current subvol as qgroup */
4918                 qgroupid = root->root_key.objectid;
4919         }
4920 
4921         ret = btrfs_limit_qgroup(trans, qgroupid, &sa->lim);
4922 
4923         err = btrfs_end_transaction(trans);
4924         if (err && !ret)
4925                 ret = err;
4926 
4927 out:
4928         kfree(sa);
4929 drop_write:
4930         mnt_drop_write_file(file);
4931         return ret;
4932 }
4933 
4934 static long btrfs_ioctl_quota_rescan(struct file *file, void __user *arg)
4935 {
4936         struct inode *inode = file_inode(file);
4937         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4938         struct btrfs_ioctl_quota_rescan_args *qsa;
4939         int ret;
4940 
4941         if (!capable(CAP_SYS_ADMIN))
4942                 return -EPERM;
4943 
4944         ret = mnt_want_write_file(file);
4945         if (ret)
4946                 return ret;
4947 
4948         qsa = memdup_user(arg, sizeof(*qsa));
4949         if (IS_ERR(qsa)) {
4950                 ret = PTR_ERR(qsa);
4951                 goto drop_write;
4952         }
4953 
4954         if (qsa->flags) {
4955                 ret = -EINVAL;
4956                 goto out;
4957         }
4958 
4959         ret = btrfs_qgroup_rescan(fs_info);
4960 
4961 out:
4962         kfree(qsa);
4963 drop_write:
4964         mnt_drop_write_file(file);
4965         return ret;
4966 }
4967 
4968 static long btrfs_ioctl_quota_rescan_status(struct file *file, void __user *arg)
4969 {
4970         struct inode *inode = file_inode(file);
4971         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4972         struct btrfs_ioctl_quota_rescan_args *qsa;
4973         int ret = 0;
4974 
4975         if (!capable(CAP_SYS_ADMIN))
4976                 return -EPERM;
4977 
4978         qsa = kzalloc(sizeof(*qsa), GFP_KERNEL);
4979         if (!qsa)
4980                 return -ENOMEM;
4981 
4982         if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
4983                 qsa->flags = 1;
4984                 qsa->progress = fs_info->qgroup_rescan_progress.objectid;
4985         }
4986 
4987         if (copy_to_user(arg, qsa, sizeof(*qsa)))
4988                 ret = -EFAULT;
4989 
4990         kfree(qsa);
4991         return ret;
4992 }
4993 
4994 static long btrfs_ioctl_quota_rescan_wait(struct file *file, void __user *arg)
4995 {
4996         struct inode *inode = file_inode(file);
4997         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4998 
4999         if (!capable(CAP_SYS_ADMIN))
5000                 return -EPERM;
5001 
5002         return btrfs_qgroup_wait_for_completion(fs_info, true);
5003 }
5004 
5005 static long _btrfs_ioctl_set_received_subvol(struct file *file,
5006                                             struct btrfs_ioctl_received_subvol_args *sa)
5007 {
5008         struct inode *inode = file_inode(file);
5009         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5010         struct btrfs_root *root = BTRFS_I(inode)->root;
5011         struct btrfs_root_item *root_item = &root->root_item;
5012         struct btrfs_trans_handle *trans;
5013         struct timespec64 ct = current_time(inode);
5014         int ret = 0;
5015         int received_uuid_changed;
5016 
5017         if (!inode_owner_or_capable(inode))
5018                 return -EPERM;
5019 
5020         ret = mnt_want_write_file(file);
5021         if (ret < 0)
5022                 return ret;
5023 
5024         down_write(&fs_info->subvol_sem);
5025 
5026         if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
5027                 ret = -EINVAL;
5028                 goto out;
5029         }
5030 
5031         if (btrfs_root_readonly(root)) {
5032                 ret = -EROFS;
5033                 goto out;
5034         }
5035 
5036         /*
5037          * 1 - root item
5038          * 2 - uuid items (received uuid + subvol uuid)
5039          */
5040         trans = btrfs_start_transaction(root, 3);
5041         if (IS_ERR(trans)) {
5042                 ret = PTR_ERR(trans);
5043                 trans = NULL;
5044                 goto out;
5045         }
5046 
5047         sa->rtransid = trans->transid;
5048         sa->rtime.sec = ct.tv_sec;
5049         sa->rtime.nsec = ct.tv_nsec;
5050 
5051         received_uuid_changed = memcmp(root_item->received_uuid, sa->uuid,
5052                                        BTRFS_UUID_SIZE);
5053         if (received_uuid_changed &&
5054             !btrfs_is_empty_uuid(root_item->received_uuid)) {
5055                 ret = btrfs_uuid_tree_remove(trans, root_item->received_uuid,
5056                                           BTRFS_UUID_KEY_RECEIVED_SUBVOL,
5057                                           root->root_key.objectid);
5058                 if (ret && ret != -ENOENT) {
5059                         btrfs_abort_transaction(trans, ret);
5060                         btrfs_end_transaction(trans);
5061                         goto out;
5062                 }
5063         }
5064         memcpy(root_item->received_uuid, sa->uuid, BTRFS_UUID_SIZE);
5065         btrfs_set_root_stransid(root_item, sa->stransid);
5066         btrfs_set_root_rtransid(root_item, sa->rtransid);
5067         btrfs_set_stack_timespec_sec(&root_item->stime, sa->stime.sec);
5068         btrfs_set_stack_timespec_nsec(&root_item->stime, sa->stime.nsec);
5069         btrfs_set_stack_timespec_sec(&root_item->rtime, sa->rtime.sec);
5070         btrfs_set_stack_timespec_nsec(&root_item->rtime, sa->rtime.nsec);
5071 
5072         ret = btrfs_update_root(trans, fs_info->tree_root,
5073                                 &root->root_key, &root->root_item);
5074         if (ret < 0) {
5075                 btrfs_end_transaction(trans);
5076                 goto out;
5077         }
5078         if (received_uuid_changed && !btrfs_is_empty_uuid(sa->uuid)) {
5079                 ret = btrfs_uuid_tree_add(trans, sa->uuid,
5080                                           BTRFS_UUID_KEY_RECEIVED_SUBVOL,
5081                                           root->root_key.objectid);
5082                 if (ret < 0 && ret != -EEXIST) {
5083                         btrfs_abort_transaction(trans, ret);
5084                         btrfs_end_transaction(trans);
5085                         goto out;
5086                 }
5087         }
5088         ret = btrfs_commit_transaction(trans);
5089 out:
5090         up_write(&fs_info->subvol_sem);
5091         mnt_drop_write_file(file);
5092         return ret;
5093 }
5094 
5095 #ifdef CONFIG_64BIT
5096 static long btrfs_ioctl_set_received_subvol_32(struct file *file,
5097                                                 void __user *arg)
5098 {
5099         struct btrfs_ioctl_received_subvol_args_32 *args32 = NULL;
5100         struct btrfs_ioctl_received_subvol_args *args64 = NULL;
5101         int ret = 0;
5102 
5103         args32 = memdup_user(arg, sizeof(*args32));
5104         if (IS_ERR(args32))
5105                 return PTR_ERR(args32);
5106 
5107         args64 = kmalloc(sizeof(*args64), GFP_KERNEL);
5108         if (!args64) {
5109                 ret = -ENOMEM;
5110                 goto out;
5111         }
5112 
5113         memcpy(args64->uuid, args32->uuid, BTRFS_UUID_SIZE);
5114         args64->stransid = args32->stransid;
5115         args64->rtransid = args32->rtransid;
5116         args64->stime.sec = args32->stime.sec;
5117         args64->stime.nsec = args32->stime.nsec;
5118         args64->rtime.sec = args32->rtime.sec;
5119         args64->rtime.nsec = args32->rtime.nsec;
5120         args64->flags = args32->flags;
5121 
5122         ret = _btrfs_ioctl_set_received_subvol(file, args64);
5123         if (ret)
5124                 goto out;
5125 
5126         memcpy(args32->uuid, args64->uuid, BTRFS_UUID_SIZE);
5127         args32->stransid = args64->stransid;
5128         args32->rtransid = args64->rtransid;
5129         args32->stime.sec = args64->stime.sec;
5130         args32->stime.nsec = args64->stime.nsec;
5131         args32->rtime.sec = args64->rtime.sec;
5132         args32->rtime.nsec = args64->rtime.nsec;
5133         args32->flags = args64->flags;
5134 
5135         ret = copy_to_user(arg, args32, sizeof(*args32));
5136         if (ret)
5137                 ret = -EFAULT;
5138 
5139 out:
5140         kfree(args32);
5141         kfree(args64);
5142         return ret;
5143 }
5144 #endif
5145 
5146 static long btrfs_ioctl_set_received_subvol(struct file *file,
5147                                             void __user *arg)
5148 {
5149         struct btrfs_ioctl_received_subvol_args *sa = NULL;
5150         int ret = 0;
5151 
5152         sa = memdup_user(arg, sizeof(*sa));
5153         if (IS_ERR(sa))
5154                 return PTR_ERR(sa);
5155 
5156         ret = _btrfs_ioctl_set_received_subvol(file, sa);
5157 
5158         if (ret)
5159                 goto out;
5160 
5161         ret = copy_to_user(arg, sa, sizeof(*sa));
5162         if (ret)
5163                 ret = -EFAULT;
5164 
5165 out:
5166         kfree(sa);
5167         return ret;
5168 }
5169 
5170 static int btrfs_ioctl_get_fslabel(struct file *file, void __user *arg)
5171 {
5172         struct inode *inode = file_inode(file);
5173         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5174         size_t len;
5175         int ret;
5176         char label[BTRFS_LABEL_SIZE];
5177 
5178         spin_lock(&fs_info->super_lock);
5179         memcpy(label, fs_info->super_copy->label, BTRFS_LABEL_SIZE);
5180         spin_unlock(&fs_info->super_lock);
5181 
5182         len = strnlen(label, BTRFS_LABEL_SIZE);
5183 
5184         if (len == BTRFS_LABEL_SIZE) {
5185                 btrfs_warn(fs_info,
5186                            "label is too long, return the first %zu bytes",
5187                            --len);
5188         }
5189 
5190         ret = copy_to_user(arg, label, len);
5191 
5192         return ret ? -EFAULT : 0;
5193 }
5194 
5195 static int btrfs_ioctl_set_fslabel(struct file *file, void __user *arg)
5196 {
5197         struct inode *inode = file_inode(file);
5198         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5199         struct btrfs_root *root = BTRFS_I(inode)->root;
5200         struct btrfs_super_block *super_block = fs_info->super_copy;
5201         struct btrfs_trans_handle *trans;
5202         char label[BTRFS_LABEL_SIZE];
5203         int ret;
5204 
5205         if (!capable(CAP_SYS_ADMIN))
5206                 return -EPERM;
5207 
5208         if (copy_from_user(label, arg, sizeof(label)))
5209                 return -EFAULT;
5210 
5211         if (strnlen(label, BTRFS_LABEL_SIZE) == BTRFS_LABEL_SIZE) {
5212                 btrfs_err(fs_info,
5213                           "unable to set label with more than %d bytes",
5214                           BTRFS_LABEL_SIZE - 1);
5215                 return -EINVAL;
5216         }
5217 
5218         ret = mnt_want_write_file(file);
5219         if (ret)
5220                 return ret;
5221 
5222         trans = btrfs_start_transaction(root, 0);
5223         if (IS_ERR(trans)) {
5224                 ret = PTR_ERR(trans);
5225                 goto out_unlock;
5226         }
5227 
5228         spin_lock(&fs_info->super_lock);
5229         strcpy(super_block->label, label);
5230         spin_unlock(&fs_info->super_lock);
5231         ret = btrfs_commit_transaction(trans);
5232 
5233 out_unlock:
5234         mnt_drop_write_file(file);
5235         return ret;
5236 }
5237 
5238 #define INIT_FEATURE_FLAGS(suffix) \
5239         { .compat_flags = BTRFS_FEATURE_COMPAT_##suffix, \
5240           .compat_ro_flags = BTRFS_FEATURE_COMPAT_RO_##suffix, \
5241           .incompat_flags = BTRFS_FEATURE_INCOMPAT_##suffix }
5242 
5243 int btrfs_ioctl_get_supported_features(void __user *arg)
5244 {
5245         static const struct btrfs_ioctl_feature_flags features[3] = {
5246                 INIT_FEATURE_FLAGS(SUPP),
5247                 INIT_FEATURE_FLAGS(SAFE_SET),
5248                 INIT_FEATURE_FLAGS(SAFE_CLEAR)
5249         };
5250 
5251         if (copy_to_user(arg, &features, sizeof(features)))
5252                 return -EFAULT;
5253 
5254         return 0;
5255 }
5256 
5257 static int btrfs_ioctl_get_features(struct file *file, void __user *arg)
5258 {
5259         struct inode *inode = file_inode(file);
5260         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5261         struct btrfs_super_block *super_block = fs_info->super_copy;
5262         struct btrfs_ioctl_feature_flags features;
5263 
5264         features.compat_flags = btrfs_super_compat_flags(super_block);
5265         features.compat_ro_flags = btrfs_super_compat_ro_flags(super_block);
5266         features.incompat_flags = btrfs_super_incompat_flags(super_block);
5267 
5268         if (copy_to_user(arg, &features, sizeof(features)))
5269                 return -EFAULT;
5270 
5271         return 0;
5272 }
5273 
5274 static int check_feature_bits(struct btrfs_fs_info *fs_info,
5275                               enum btrfs_feature_set set,
5276                               u64 change_mask, u64 flags, u64 supported_flags,
5277                               u64 safe_set, u64 safe_clear)
5278 {
5279         const char *type = btrfs_feature_set_name(set);
5280         char *names;
5281         u64 disallowed, unsupported;
5282         u64 set_mask = flags & change_mask;
5283         u64 clear_mask = ~flags & change_mask;
5284 
5285         unsupported = set_mask & ~supported_flags;
5286         if (unsupported) {
5287                 names = btrfs_printable_features(set, unsupported);
5288                 if (names) {
5289                         btrfs_warn(fs_info,
5290                                    "this kernel does not support the %s feature bit%s",
5291                                    names, strchr(names, ',') ? "s" : "");
5292                         kfree(names);
5293                 } else
5294                         btrfs_warn(fs_info,
5295                                    "this kernel does not support %s bits 0x%llx",
5296                                    type, unsupported);
5297                 return -EOPNOTSUPP;
5298         }
5299 
5300         disallowed = set_mask & ~safe_set;
5301         if (disallowed) {
5302                 names = btrfs_printable_features(set, disallowed);
5303                 if (names) {
5304                         btrfs_warn(fs_info,
5305                                    "can't set the %s feature bit%s while mounted",
5306                                    names, strchr(names, ',') ? "s" : "");
5307                         kfree(names);
5308                 } else
5309                         btrfs_warn(fs_info,
5310                                    "can't set %s bits 0x%llx while mounted",
5311                                    type, disallowed);
5312                 return -EPERM;
5313         }
5314 
5315         disallowed = clear_mask & ~safe_clear;
5316         if (disallowed) {
5317                 names = btrfs_printable_features(set, disallowed);
5318                 if (names) {
5319                         btrfs_warn(fs_info,
5320                                    "can't clear the %s feature bit%s while mounted",
5321                                    names, strchr(names, ',') ? "s" : "");
5322                         kfree(names);
5323                 } else
5324                         btrfs_warn(fs_info,
5325                                    "can't clear %s bits 0x%llx while mounted",
5326                                    type, disallowed);
5327                 return -EPERM;
5328         }
5329 
5330         return 0;
5331 }
5332 
5333 #define check_feature(fs_info, change_mask, flags, mask_base)   \
5334 check_feature_bits(fs_info, FEAT_##mask_base, change_mask, flags,       \
5335                    BTRFS_FEATURE_ ## mask_base ## _SUPP,        \
5336                    BTRFS_FEATURE_ ## mask_base ## _SAFE_SET,    \
5337                    BTRFS_FEATURE_ ## mask_base ## _SAFE_CLEAR)
5338 
5339 static int btrfs_ioctl_set_features(struct file *file, void __user *arg)
5340 {
5341         struct inode *inode = file_inode(file);
5342         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5343         struct btrfs_root *root = BTRFS_I(inode)->root;
5344         struct btrfs_super_block *super_block = fs_info->super_copy;
5345         struct btrfs_ioctl_feature_flags flags[2];
5346         struct btrfs_trans_handle *trans;
5347         u64 newflags;
5348         int ret;
5349 
5350         if (!capable(CAP_SYS_ADMIN))
5351                 return -EPERM;
5352 
5353         if (copy_from_user(flags, arg, sizeof(flags)))
5354                 return -EFAULT;
5355 
5356         /* Nothing to do */
5357         if (!flags[0].compat_flags && !flags[0].compat_ro_flags &&
5358             !flags[0].incompat_flags)
5359                 return 0;
5360 
5361         ret = check_feature(fs_info, flags[0].compat_flags,
5362                             flags[1].compat_flags, COMPAT);
5363         if (ret)
5364                 return ret;
5365 
5366         ret = check_feature(fs_info, flags[0].compat_ro_flags,
5367                             flags[1].compat_ro_flags, COMPAT_RO);
5368         if (ret)
5369                 return ret;
5370 
5371         ret = check_feature(fs_info, flags[0].incompat_flags,
5372                             flags[1].incompat_flags, INCOMPAT);
5373         if (ret)
5374                 return ret;
5375 
5376         ret = mnt_want_write_file(file);
5377         if (ret)
5378                 return ret;
5379 
5380         trans = btrfs_start_transaction(root, 0);
5381         if (IS_ERR(trans)) {
5382                 ret = PTR_ERR(trans);
5383                 goto out_drop_write;
5384         }
5385 
5386         spin_lock(&fs_info->super_lock);
5387         newflags = btrfs_super_compat_flags(super_block);
5388         newflags |= flags[0].compat_flags & flags[1].compat_flags;
5389         newflags &= ~(flags[0].compat_flags & ~flags[1].compat_flags);
5390         btrfs_set_super_compat_flags(super_block, newflags);
5391 
5392         newflags = btrfs_super_compat_ro_flags(super_block);
5393         newflags |= flags[0].compat_ro_flags & flags[1].compat_ro_flags;
5394         newflags &= ~(flags[0].compat_ro_flags & ~flags[1].compat_ro_flags);
5395         btrfs_set_super_compat_ro_flags(super_block, newflags);
5396 
5397         newflags = btrfs_super_incompat_flags(super_block);
5398         newflags |= flags[0].incompat_flags & flags[1].incompat_flags;
5399         newflags &= ~(flags[0].incompat_flags & ~flags[1].incompat_flags);
5400         btrfs_set_super_incompat_flags(super_block, newflags);
5401         spin_unlock(&fs_info->super_lock);
5402 
5403         ret = btrfs_commit_transaction(trans);
5404 out_drop_write:
5405         mnt_drop_write_file(file);
5406 
5407         return ret;
5408 }
5409 
5410 static int _btrfs_ioctl_send(struct file *file, void __user *argp, bool compat)
5411 {
5412         struct btrfs_ioctl_send_args *arg;
5413         int ret;
5414 
5415         if (compat) {
5416 #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
5417                 struct btrfs_ioctl_send_args_32 args32;
5418 
5419                 ret = copy_from_user(&args32, argp, sizeof(args32));
5420                 if (ret)
5421                         return -EFAULT;
5422                 arg = kzalloc(sizeof(*arg), GFP_KERNEL);
5423                 if (!arg)
5424                         return -ENOMEM;
5425                 arg->send_fd = args32.send_fd;
5426                 arg->clone_sources_count = args32.clone_sources_count;
5427                 arg->clone_sources = compat_ptr(args32.clone_sources);
5428                 arg->parent_root = args32.parent_root;
5429                 arg->flags = args32.flags;
5430                 memcpy(arg->reserved, args32.reserved,
5431                        sizeof(args32.reserved));
5432 #else
5433                 return -ENOTTY;
5434 #endif
5435         } else {
5436                 arg = memdup_user(argp, sizeof(*arg));
5437                 if (IS_ERR(arg))
5438                         return PTR_ERR(arg);
5439         }
5440         ret = btrfs_ioctl_send(file, arg);
5441         kfree(arg);
5442         return ret;
5443 }
5444 
5445 long btrfs_ioctl(struct file *file, unsigned int
5446                 cmd, unsigned long arg)
5447 {
5448         struct inode *inode = file_inode(file);
5449         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5450         struct btrfs_root *root = BTRFS_I(inode)->root;
5451         void __user *argp = (void __user *)arg;
5452 
5453         switch (cmd) {
5454         case FS_IOC_GETFLAGS:
5455                 return btrfs_ioctl_getflags(file, argp);
5456         case FS_IOC_SETFLAGS:
5457                 return btrfs_ioctl_setflags(file, argp);
5458         case FS_IOC_GETVERSION:
5459                 return btrfs_ioctl_getversion(file, argp);
5460         case FS_IOC_GETFSLABEL:
5461                 return btrfs_ioctl_get_fslabel(file, argp);
5462         case FS_IOC_SETFSLABEL:
5463                 return btrfs_ioctl_set_fslabel(file, argp);
5464         case FITRIM:
5465                 return btrfs_ioctl_fitrim(file, argp);
5466         case BTRFS_IOC_SNAP_CREATE:
5467                 return btrfs_ioctl_snap_create(file, argp, 0);
5468         case BTRFS_IOC_SNAP_CREATE_V2:
5469                 return btrfs_ioctl_snap_create_v2(file, argp, 0);
5470         case BTRFS_IOC_SUBVOL_CREATE:
5471                 return btrfs_ioctl_snap_create(file, argp, 1);
5472         case BTRFS_IOC_SUBVOL_CREATE_V2:
5473                 return btrfs_ioctl_snap_create_v2(file, argp, 1);
5474         case BTRFS_IOC_SNAP_DESTROY:
5475                 return btrfs_ioctl_snap_destroy(file, argp);
5476         case BTRFS_IOC_SUBVOL_GETFLAGS:
5477                 return btrfs_ioctl_subvol_getflags(file, argp);
5478         case BTRFS_IOC_SUBVOL_SETFLAGS:
5479                 return btrfs_ioctl_subvol_setflags(file, argp);
5480         case BTRFS_IOC_DEFAULT_SUBVOL:
5481                 return btrfs_ioctl_default_subvol(file, argp);
5482         case BTRFS_IOC_DEFRAG:
5483                 return btrfs_ioctl_defrag(file, NULL);
5484         case BTRFS_IOC_DEFRAG_RANGE:
5485                 return btrfs_ioctl_defrag(file, argp);
5486         case BTRFS_IOC_RESIZE:
5487                 return btrfs_ioctl_resize(file, argp);
5488         case BTRFS_IOC_ADD_DEV:
5489                 return btrfs_ioctl_add_dev(fs_info, argp);
5490         case BTRFS_IOC_RM_DEV:
5491                 return btrfs_ioctl_rm_dev(file, argp);
5492         case BTRFS_IOC_RM_DEV_V2:
5493                 return btrfs_ioctl_rm_dev_v2(file, argp);
5494         case BTRFS_IOC_FS_INFO:
5495                 return btrfs_ioctl_fs_info(fs_info, argp);
5496         case BTRFS_IOC_DEV_INFO:
5497                 return btrfs_ioctl_dev_info(fs_info, argp);
5498         case BTRFS_IOC_BALANCE:
5499                 return btrfs_ioctl_balance(file, NULL);
5500         case BTRFS_IOC_TREE_SEARCH:
5501                 return btrfs_ioctl_tree_search(file, argp);
5502         case BTRFS_IOC_TREE_SEARCH_V2:
5503                 return btrfs_ioctl_tree_search_v2(file, argp);
5504         case BTRFS_IOC_INO_LOOKUP:
5505                 return btrfs_ioctl_ino_lookup(file, argp);
5506         case BTRFS_IOC_INO_PATHS:
5507                 return btrfs_ioctl_ino_to_path(root, argp);
5508         case BTRFS_IOC_LOGICAL_INO:
5509                 return btrfs_ioctl_logical_to_ino(fs_info, argp, 1);
5510         case BTRFS_IOC_LOGICAL_INO_V2:
5511                 return btrfs_ioctl_logical_to_ino(fs_info, argp, 2);
5512         case BTRFS_IOC_SPACE_INFO:
5513                 return btrfs_ioctl_space_info(fs_info, argp);
5514         case BTRFS_IOC_SYNC: {
5515                 int ret;
5516 
5517                 ret = btrfs_start_delalloc_roots(fs_info, -1);
5518                 if (ret)
5519                         return ret;
5520                 ret = btrfs_sync_fs(inode->i_sb, 1);
5521                 /*
5522                  * The transaction thread may want to do more work,
5523                  * namely it pokes the cleaner kthread that will start
5524                  * processing uncleaned subvols.
5525                  */
5526                 wake_up_process(fs_info->transaction_kthread);
5527                 return ret;
5528         }
5529         case BTRFS_IOC_START_SYNC:
5530                 return btrfs_ioctl_start_sync(root, argp);
5531         case BTRFS_IOC_WAIT_SYNC:
5532                 return btrfs_ioctl_wait_sync(fs_info, argp);
5533         case BTRFS_IOC_SCRUB:
5534                 return btrfs_ioctl_scrub(file, argp);
5535         case BTRFS_IOC_SCRUB_CANCEL:
5536                 return btrfs_ioctl_scrub_cancel(fs_info);
5537         case BTRFS_IOC_SCRUB_PROGRESS:
5538                 return btrfs_ioctl_scrub_progress(fs_info, argp);
5539         case BTRFS_IOC_BALANCE_V2:
5540                 return btrfs_ioctl_balance(file, argp);
5541         case BTRFS_IOC_BALANCE_CTL:
5542                 return btrfs_ioctl_balance_ctl(fs_info, arg);
5543         case BTRFS_IOC_BALANCE_PROGRESS:
5544                 return btrfs_ioctl_balance_progress(fs_info, argp);
5545         case BTRFS_IOC_SET_RECEIVED_SUBVOL:
5546                 return btrfs_ioctl_set_received_subvol(file, argp);
5547 #ifdef CONFIG_64BIT
5548         case BTRFS_IOC_SET_RECEIVED_SUBVOL_32:
5549                 return btrfs_ioctl_set_received_subvol_32(file, argp);
5550 #endif
5551         case BTRFS_IOC_SEND:
5552                 return _btrfs_ioctl_send(file, argp, false);
5553 #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
5554         case BTRFS_IOC_SEND_32:
5555                 return _btrfs_ioctl_send(file, argp, true);
5556 #endif
5557         case BTRFS_IOC_GET_DEV_STATS:
5558                 return btrfs_ioctl_get_dev_stats(fs_info, argp);
5559         case BTRFS_IOC_QUOTA_CTL:
5560                 return btrfs_ioctl_quota_ctl(file, argp);
5561         case BTRFS_IOC_QGROUP_ASSIGN:
5562                 return btrfs_ioctl_qgroup_assign(file, argp);
5563         case BTRFS_IOC_QGROUP_CREATE:
5564                 return btrfs_ioctl_qgroup_create(file, argp);
5565         case BTRFS_IOC_QGROUP_LIMIT:
5566                 return btrfs_ioctl_qgroup_limit(file, argp);
5567         case BTRFS_IOC_QUOTA_RESCAN:
5568                 return btrfs_ioctl_quota_rescan(file, argp);
5569         case BTRFS_IOC_QUOTA_RESCAN_STATUS:
5570                 return btrfs_ioctl_quota_rescan_status(file, argp);
5571         case BTRFS_IOC_QUOTA_RESCAN_WAIT:
5572                 return btrfs_ioctl_quota_rescan_wait(file, argp);
5573         case BTRFS_IOC_DEV_REPLACE:
5574                 return btrfs_ioctl_dev_replace(fs_info, argp);
5575         case BTRFS_IOC_GET_SUPPORTED_FEATURES:
5576                 return btrfs_ioctl_get_supported_features(argp);
5577         case BTRFS_IOC_GET_FEATURES:
5578                 return btrfs_ioctl_get_features(file, argp);
5579         case BTRFS_IOC_SET_FEATURES:
5580                 return btrfs_ioctl_set_features(file, argp);
5581         case FS_IOC_FSGETXATTR:
5582                 return btrfs_ioctl_fsgetxattr(file, argp);
5583         case FS_IOC_FSSETXATTR:
5584                 return btrfs_ioctl_fssetxattr(file, argp);
5585         case BTRFS_IOC_GET_SUBVOL_INFO:
5586                 return btrfs_ioctl_get_subvol_info(file, argp);
5587         case BTRFS_IOC_GET_SUBVOL_ROOTREF:
5588                 return btrfs_ioctl_get_subvol_rootref(file, argp);
5589         case BTRFS_IOC_INO_LOOKUP_USER:
5590                 return btrfs_ioctl_ino_lookup_user(file, argp);
5591         }
5592 
5593         return -ENOTTY;
5594 }
5595 
5596 #ifdef CONFIG_COMPAT
5597 long btrfs_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
5598 {
5599         /*
5600          * These all access 32-bit values anyway so no further
5601          * handling is necessary.
5602          */
5603         switch (cmd) {
5604         case FS_IOC32_GETFLAGS:
5605                 cmd = FS_IOC_GETFLAGS;
5606                 break;
5607         case FS_IOC32_SETFLAGS:
5608                 cmd = FS_IOC_SETFLAGS;
5609                 break;
5610         case FS_IOC32_GETVERSION:
5611                 cmd = FS_IOC_GETVERSION;
5612                 break;
5613         }
5614 
5615         return btrfs_ioctl(file, cmd, (unsigned long) compat_ptr(arg));
5616 }
5617 #endif

/* [<][>][^][v][top][bottom][index][help] */