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