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