OSDN Git Service

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