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