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