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