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