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