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