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