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