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