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