btrfs: Perform locking/unlocking in btrfs_remap_file_range()
[sfrench/cifs-2.6.git] / fs / btrfs / ioctl.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2007 Oracle.  All rights reserved.
4  */
5
6 #include <linux/kernel.h>
7 #include <linux/bio.h>
8 #include <linux/file.h>
9 #include <linux/fs.h>
10 #include <linux/fsnotify.h>
11 #include <linux/pagemap.h>
12 #include <linux/highmem.h>
13 #include <linux/time.h>
14 #include <linux/string.h>
15 #include <linux/backing-dev.h>
16 #include <linux/mount.h>
17 #include <linux/namei.h>
18 #include <linux/writeback.h>
19 #include <linux/compat.h>
20 #include <linux/security.h>
21 #include <linux/xattr.h>
22 #include <linux/mm.h>
23 #include <linux/slab.h>
24 #include <linux/blkdev.h>
25 #include <linux/uuid.h>
26 #include <linux/btrfs.h>
27 #include <linux/uaccess.h>
28 #include <linux/iversion.h>
29 #include "ctree.h"
30 #include "disk-io.h"
31 #include "transaction.h"
32 #include "btrfs_inode.h"
33 #include "print-tree.h"
34 #include "volumes.h"
35 #include "locking.h"
36 #include "inode-map.h"
37 #include "backref.h"
38 #include "rcu-string.h"
39 #include "send.h"
40 #include "dev-replace.h"
41 #include "props.h"
42 #include "sysfs.h"
43 #include "qgroup.h"
44 #include "tree-log.h"
45 #include "compression.h"
46
47 #ifdef CONFIG_64BIT
48 /* If we have a 32-bit userspace and 64-bit kernel, then the UAPI
49  * structures are incorrect, as the timespec structure from userspace
50  * is 4 bytes too small. We define these alternatives here to teach
51  * the kernel about the 32-bit struct packing.
52  */
53 struct btrfs_ioctl_timespec_32 {
54         __u64 sec;
55         __u32 nsec;
56 } __attribute__ ((__packed__));
57
58 struct btrfs_ioctl_received_subvol_args_32 {
59         char    uuid[BTRFS_UUID_SIZE];  /* in */
60         __u64   stransid;               /* in */
61         __u64   rtransid;               /* out */
62         struct btrfs_ioctl_timespec_32 stime; /* in */
63         struct btrfs_ioctl_timespec_32 rtime; /* out */
64         __u64   flags;                  /* in */
65         __u64   reserved[16];           /* in */
66 } __attribute__ ((__packed__));
67
68 #define BTRFS_IOC_SET_RECEIVED_SUBVOL_32 _IOWR(BTRFS_IOCTL_MAGIC, 37, \
69                                 struct btrfs_ioctl_received_subvol_args_32)
70 #endif
71
72 #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
73 struct btrfs_ioctl_send_args_32 {
74         __s64 send_fd;                  /* in */
75         __u64 clone_sources_count;      /* in */
76         compat_uptr_t clone_sources;    /* in */
77         __u64 parent_root;              /* in */
78         __u64 flags;                    /* in */
79         __u64 reserved[4];              /* in */
80 } __attribute__ ((__packed__));
81
82 #define BTRFS_IOC_SEND_32 _IOW(BTRFS_IOCTL_MAGIC, 38, \
83                                struct btrfs_ioctl_send_args_32)
84 #endif
85
86 static int btrfs_clone(struct inode *src, struct inode *inode,
87                        u64 off, u64 olen, u64 olen_aligned, u64 destoff,
88                        int no_time_update);
89
90 /* Mask out flags that are inappropriate for the given type of inode. */
91 static unsigned int btrfs_mask_fsflags_for_type(struct inode *inode,
92                 unsigned int flags)
93 {
94         if (S_ISDIR(inode->i_mode))
95                 return flags;
96         else if (S_ISREG(inode->i_mode))
97                 return flags & ~FS_DIRSYNC_FL;
98         else
99                 return flags & (FS_NODUMP_FL | FS_NOATIME_FL);
100 }
101
102 /*
103  * Export internal inode flags to the format expected by the FS_IOC_GETFLAGS
104  * ioctl.
105  */
106 static unsigned int btrfs_inode_flags_to_fsflags(unsigned int flags)
107 {
108         unsigned int iflags = 0;
109
110         if (flags & BTRFS_INODE_SYNC)
111                 iflags |= FS_SYNC_FL;
112         if (flags & BTRFS_INODE_IMMUTABLE)
113                 iflags |= FS_IMMUTABLE_FL;
114         if (flags & BTRFS_INODE_APPEND)
115                 iflags |= FS_APPEND_FL;
116         if (flags & BTRFS_INODE_NODUMP)
117                 iflags |= FS_NODUMP_FL;
118         if (flags & BTRFS_INODE_NOATIME)
119                 iflags |= FS_NOATIME_FL;
120         if (flags & BTRFS_INODE_DIRSYNC)
121                 iflags |= FS_DIRSYNC_FL;
122         if (flags & BTRFS_INODE_NODATACOW)
123                 iflags |= FS_NOCOW_FL;
124
125         if (flags & BTRFS_INODE_NOCOMPRESS)
126                 iflags |= FS_NOCOMP_FL;
127         else if (flags & BTRFS_INODE_COMPRESS)
128                 iflags |= FS_COMPR_FL;
129
130         return iflags;
131 }
132
133 /*
134  * Update inode->i_flags based on the btrfs internal flags.
135  */
136 void btrfs_sync_inode_flags_to_i_flags(struct inode *inode)
137 {
138         struct btrfs_inode *binode = BTRFS_I(inode);
139         unsigned int new_fl = 0;
140
141         if (binode->flags & BTRFS_INODE_SYNC)
142                 new_fl |= S_SYNC;
143         if (binode->flags & BTRFS_INODE_IMMUTABLE)
144                 new_fl |= S_IMMUTABLE;
145         if (binode->flags & BTRFS_INODE_APPEND)
146                 new_fl |= S_APPEND;
147         if (binode->flags & BTRFS_INODE_NOATIME)
148                 new_fl |= S_NOATIME;
149         if (binode->flags & BTRFS_INODE_DIRSYNC)
150                 new_fl |= S_DIRSYNC;
151
152         set_mask_bits(&inode->i_flags,
153                       S_SYNC | S_APPEND | S_IMMUTABLE | S_NOATIME | S_DIRSYNC,
154                       new_fl);
155 }
156
157 static int btrfs_ioctl_getflags(struct file *file, void __user *arg)
158 {
159         struct btrfs_inode *binode = BTRFS_I(file_inode(file));
160         unsigned int flags = btrfs_inode_flags_to_fsflags(binode->flags);
161
162         if (copy_to_user(arg, &flags, sizeof(flags)))
163                 return -EFAULT;
164         return 0;
165 }
166
167 /* Check if @flags are a supported and valid set of FS_*_FL flags */
168 static int check_fsflags(unsigned int flags)
169 {
170         if (flags & ~(FS_IMMUTABLE_FL | FS_APPEND_FL | \
171                       FS_NOATIME_FL | FS_NODUMP_FL | \
172                       FS_SYNC_FL | FS_DIRSYNC_FL | \
173                       FS_NOCOMP_FL | FS_COMPR_FL |
174                       FS_NOCOW_FL))
175                 return -EOPNOTSUPP;
176
177         if ((flags & FS_NOCOMP_FL) && (flags & FS_COMPR_FL))
178                 return -EINVAL;
179
180         return 0;
181 }
182
183 static int btrfs_ioctl_setflags(struct file *file, void __user *arg)
184 {
185         struct inode *inode = file_inode(file);
186         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
187         struct btrfs_inode *binode = BTRFS_I(inode);
188         struct btrfs_root *root = binode->root;
189         struct btrfs_trans_handle *trans;
190         unsigned int fsflags, old_fsflags;
191         int ret;
192         u64 old_flags;
193         unsigned int old_i_flags;
194         umode_t mode;
195
196         if (!inode_owner_or_capable(inode))
197                 return -EPERM;
198
199         if (btrfs_root_readonly(root))
200                 return -EROFS;
201
202         if (copy_from_user(&fsflags, arg, sizeof(fsflags)))
203                 return -EFAULT;
204
205         ret = check_fsflags(fsflags);
206         if (ret)
207                 return ret;
208
209         ret = mnt_want_write_file(file);
210         if (ret)
211                 return ret;
212
213         inode_lock(inode);
214
215         old_flags = binode->flags;
216         old_i_flags = inode->i_flags;
217         mode = inode->i_mode;
218
219         fsflags = btrfs_mask_fsflags_for_type(inode, fsflags);
220         old_fsflags = btrfs_inode_flags_to_fsflags(binode->flags);
221         if ((fsflags ^ old_fsflags) & (FS_APPEND_FL | FS_IMMUTABLE_FL)) {
222                 if (!capable(CAP_LINUX_IMMUTABLE)) {
223                         ret = -EPERM;
224                         goto out_unlock;
225                 }
226         }
227
228         if (fsflags & FS_SYNC_FL)
229                 binode->flags |= BTRFS_INODE_SYNC;
230         else
231                 binode->flags &= ~BTRFS_INODE_SYNC;
232         if (fsflags & FS_IMMUTABLE_FL)
233                 binode->flags |= BTRFS_INODE_IMMUTABLE;
234         else
235                 binode->flags &= ~BTRFS_INODE_IMMUTABLE;
236         if (fsflags & FS_APPEND_FL)
237                 binode->flags |= BTRFS_INODE_APPEND;
238         else
239                 binode->flags &= ~BTRFS_INODE_APPEND;
240         if (fsflags & FS_NODUMP_FL)
241                 binode->flags |= BTRFS_INODE_NODUMP;
242         else
243                 binode->flags &= ~BTRFS_INODE_NODUMP;
244         if (fsflags & FS_NOATIME_FL)
245                 binode->flags |= BTRFS_INODE_NOATIME;
246         else
247                 binode->flags &= ~BTRFS_INODE_NOATIME;
248         if (fsflags & FS_DIRSYNC_FL)
249                 binode->flags |= BTRFS_INODE_DIRSYNC;
250         else
251                 binode->flags &= ~BTRFS_INODE_DIRSYNC;
252         if (fsflags & FS_NOCOW_FL) {
253                 if (S_ISREG(mode)) {
254                         /*
255                          * It's safe to turn csums off here, no extents exist.
256                          * Otherwise we want the flag to reflect the real COW
257                          * status of the file and will not set it.
258                          */
259                         if (inode->i_size == 0)
260                                 binode->flags |= BTRFS_INODE_NODATACOW
261                                               | BTRFS_INODE_NODATASUM;
262                 } else {
263                         binode->flags |= BTRFS_INODE_NODATACOW;
264                 }
265         } else {
266                 /*
267                  * Revert back under same assumptions as above
268                  */
269                 if (S_ISREG(mode)) {
270                         if (inode->i_size == 0)
271                                 binode->flags &= ~(BTRFS_INODE_NODATACOW
272                                              | BTRFS_INODE_NODATASUM);
273                 } else {
274                         binode->flags &= ~BTRFS_INODE_NODATACOW;
275                 }
276         }
277
278         /*
279          * The COMPRESS flag can only be changed by users, while the NOCOMPRESS
280          * flag may be changed automatically if compression code won't make
281          * things smaller.
282          */
283         if (fsflags & FS_NOCOMP_FL) {
284                 binode->flags &= ~BTRFS_INODE_COMPRESS;
285                 binode->flags |= BTRFS_INODE_NOCOMPRESS;
286
287                 ret = btrfs_set_prop_trans(inode, "btrfs.compression", NULL,
288                                            0, 0);
289                 if (ret && ret != -ENODATA)
290                         goto out_drop;
291         } else if (fsflags & FS_COMPR_FL) {
292                 const char *comp;
293
294                 if (IS_SWAPFILE(inode)) {
295                         ret = -ETXTBSY;
296                         goto out_unlock;
297                 }
298
299                 binode->flags |= BTRFS_INODE_COMPRESS;
300                 binode->flags &= ~BTRFS_INODE_NOCOMPRESS;
301
302                 comp = btrfs_compress_type2str(fs_info->compress_type);
303                 if (!comp || comp[0] == 0)
304                         comp = btrfs_compress_type2str(BTRFS_COMPRESS_ZLIB);
305
306                 ret = btrfs_set_prop_trans(inode, "btrfs.compression", comp,
307                                            strlen(comp), 0);
308                 if (ret)
309                         goto out_drop;
310
311         } else {
312                 ret = btrfs_set_prop_trans(inode, "btrfs.compression", NULL,
313                                            0, 0);
314                 if (ret && ret != -ENODATA)
315                         goto out_drop;
316                 binode->flags &= ~(BTRFS_INODE_COMPRESS | BTRFS_INODE_NOCOMPRESS);
317         }
318
319         trans = btrfs_start_transaction(root, 1);
320         if (IS_ERR(trans)) {
321                 ret = PTR_ERR(trans);
322                 goto out_drop;
323         }
324
325         btrfs_sync_inode_flags_to_i_flags(inode);
326         inode_inc_iversion(inode);
327         inode->i_ctime = current_time(inode);
328         ret = btrfs_update_inode(trans, root, inode);
329
330         btrfs_end_transaction(trans);
331  out_drop:
332         if (ret) {
333                 binode->flags = old_flags;
334                 inode->i_flags = old_i_flags;
335         }
336
337  out_unlock:
338         inode_unlock(inode);
339         mnt_drop_write_file(file);
340         return ret;
341 }
342
343 /*
344  * Translate btrfs internal inode flags to xflags as expected by the
345  * FS_IOC_FSGETXATT ioctl. Filter only the supported ones, unknown flags are
346  * silently dropped.
347  */
348 static unsigned int btrfs_inode_flags_to_xflags(unsigned int flags)
349 {
350         unsigned int xflags = 0;
351
352         if (flags & BTRFS_INODE_APPEND)
353                 xflags |= FS_XFLAG_APPEND;
354         if (flags & BTRFS_INODE_IMMUTABLE)
355                 xflags |= FS_XFLAG_IMMUTABLE;
356         if (flags & BTRFS_INODE_NOATIME)
357                 xflags |= FS_XFLAG_NOATIME;
358         if (flags & BTRFS_INODE_NODUMP)
359                 xflags |= FS_XFLAG_NODUMP;
360         if (flags & BTRFS_INODE_SYNC)
361                 xflags |= FS_XFLAG_SYNC;
362
363         return xflags;
364 }
365
366 /* Check if @flags are a supported and valid set of FS_XFLAGS_* flags */
367 static int check_xflags(unsigned int flags)
368 {
369         if (flags & ~(FS_XFLAG_APPEND | FS_XFLAG_IMMUTABLE | FS_XFLAG_NOATIME |
370                       FS_XFLAG_NODUMP | FS_XFLAG_SYNC))
371                 return -EOPNOTSUPP;
372         return 0;
373 }
374
375 /*
376  * Set the xflags from the internal inode flags. The remaining items of fsxattr
377  * are zeroed.
378  */
379 static int btrfs_ioctl_fsgetxattr(struct file *file, void __user *arg)
380 {
381         struct btrfs_inode *binode = BTRFS_I(file_inode(file));
382         struct fsxattr fa;
383
384         memset(&fa, 0, sizeof(fa));
385         fa.fsx_xflags = btrfs_inode_flags_to_xflags(binode->flags);
386
387         if (copy_to_user(arg, &fa, sizeof(fa)))
388                 return -EFAULT;
389
390         return 0;
391 }
392
393 static int btrfs_ioctl_fssetxattr(struct file *file, void __user *arg)
394 {
395         struct inode *inode = file_inode(file);
396         struct btrfs_inode *binode = BTRFS_I(inode);
397         struct btrfs_root *root = binode->root;
398         struct btrfs_trans_handle *trans;
399         struct fsxattr fa;
400         unsigned old_flags;
401         unsigned old_i_flags;
402         int ret = 0;
403
404         if (!inode_owner_or_capable(inode))
405                 return -EPERM;
406
407         if (btrfs_root_readonly(root))
408                 return -EROFS;
409
410         memset(&fa, 0, sizeof(fa));
411         if (copy_from_user(&fa, arg, sizeof(fa)))
412                 return -EFAULT;
413
414         ret = check_xflags(fa.fsx_xflags);
415         if (ret)
416                 return ret;
417
418         if (fa.fsx_extsize != 0 || fa.fsx_projid != 0 || fa.fsx_cowextsize != 0)
419                 return -EOPNOTSUPP;
420
421         ret = mnt_want_write_file(file);
422         if (ret)
423                 return ret;
424
425         inode_lock(inode);
426
427         old_flags = binode->flags;
428         old_i_flags = inode->i_flags;
429
430         /* We need the capabilities to change append-only or immutable inode */
431         if (((old_flags & (BTRFS_INODE_APPEND | BTRFS_INODE_IMMUTABLE)) ||
432              (fa.fsx_xflags & (FS_XFLAG_APPEND | FS_XFLAG_IMMUTABLE))) &&
433             !capable(CAP_LINUX_IMMUTABLE)) {
434                 ret = -EPERM;
435                 goto out_unlock;
436         }
437
438         if (fa.fsx_xflags & FS_XFLAG_SYNC)
439                 binode->flags |= BTRFS_INODE_SYNC;
440         else
441                 binode->flags &= ~BTRFS_INODE_SYNC;
442         if (fa.fsx_xflags & FS_XFLAG_IMMUTABLE)
443                 binode->flags |= BTRFS_INODE_IMMUTABLE;
444         else
445                 binode->flags &= ~BTRFS_INODE_IMMUTABLE;
446         if (fa.fsx_xflags & FS_XFLAG_APPEND)
447                 binode->flags |= BTRFS_INODE_APPEND;
448         else
449                 binode->flags &= ~BTRFS_INODE_APPEND;
450         if (fa.fsx_xflags & FS_XFLAG_NODUMP)
451                 binode->flags |= BTRFS_INODE_NODUMP;
452         else
453                 binode->flags &= ~BTRFS_INODE_NODUMP;
454         if (fa.fsx_xflags & FS_XFLAG_NOATIME)
455                 binode->flags |= BTRFS_INODE_NOATIME;
456         else
457                 binode->flags &= ~BTRFS_INODE_NOATIME;
458
459         /* 1 item for the inode */
460         trans = btrfs_start_transaction(root, 1);
461         if (IS_ERR(trans)) {
462                 ret = PTR_ERR(trans);
463                 goto out_unlock;
464         }
465
466         btrfs_sync_inode_flags_to_i_flags(inode);
467         inode_inc_iversion(inode);
468         inode->i_ctime = current_time(inode);
469         ret = btrfs_update_inode(trans, root, inode);
470
471         btrfs_end_transaction(trans);
472
473 out_unlock:
474         if (ret) {
475                 binode->flags = old_flags;
476                 inode->i_flags = old_i_flags;
477         }
478
479         inode_unlock(inode);
480         mnt_drop_write_file(file);
481
482         return ret;
483 }
484
485 static int btrfs_ioctl_getversion(struct file *file, int __user *arg)
486 {
487         struct inode *inode = file_inode(file);
488
489         return put_user(inode->i_generation, arg);
490 }
491
492 static noinline int btrfs_ioctl_fitrim(struct file *file, void __user *arg)
493 {
494         struct inode *inode = file_inode(file);
495         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
496         struct btrfs_device *device;
497         struct request_queue *q;
498         struct fstrim_range range;
499         u64 minlen = ULLONG_MAX;
500         u64 num_devices = 0;
501         int ret;
502
503         if (!capable(CAP_SYS_ADMIN))
504                 return -EPERM;
505
506         /*
507          * If the fs is mounted with nologreplay, which requires it to be
508          * mounted in RO mode as well, we can not allow discard on free space
509          * inside block groups, because log trees refer to extents that are not
510          * pinned in a block group's free space cache (pinning the extents is
511          * precisely the first phase of replaying a log tree).
512          */
513         if (btrfs_test_opt(fs_info, NOLOGREPLAY))
514                 return -EROFS;
515
516         rcu_read_lock();
517         list_for_each_entry_rcu(device, &fs_info->fs_devices->devices,
518                                 dev_list) {
519                 if (!device->bdev)
520                         continue;
521                 q = bdev_get_queue(device->bdev);
522                 if (blk_queue_discard(q)) {
523                         num_devices++;
524                         minlen = min_t(u64, q->limits.discard_granularity,
525                                      minlen);
526                 }
527         }
528         rcu_read_unlock();
529
530         if (!num_devices)
531                 return -EOPNOTSUPP;
532         if (copy_from_user(&range, arg, sizeof(range)))
533                 return -EFAULT;
534
535         /*
536          * NOTE: Don't truncate the range using super->total_bytes.  Bytenr of
537          * block group is in the logical address space, which can be any
538          * sectorsize aligned bytenr in  the range [0, U64_MAX].
539          */
540         if (range.len < fs_info->sb->s_blocksize)
541                 return -EINVAL;
542
543         range.minlen = max(range.minlen, minlen);
544         ret = btrfs_trim_fs(fs_info, &range);
545         if (ret < 0)
546                 return ret;
547
548         if (copy_to_user(arg, &range, sizeof(range)))
549                 return -EFAULT;
550
551         return 0;
552 }
553
554 int btrfs_is_empty_uuid(u8 *uuid)
555 {
556         int i;
557
558         for (i = 0; i < BTRFS_UUID_SIZE; i++) {
559                 if (uuid[i])
560                         return 0;
561         }
562         return 1;
563 }
564
565 static noinline int create_subvol(struct inode *dir,
566                                   struct dentry *dentry,
567                                   const char *name, int namelen,
568                                   u64 *async_transid,
569                                   struct btrfs_qgroup_inherit *inherit)
570 {
571         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
572         struct btrfs_trans_handle *trans;
573         struct btrfs_key key;
574         struct btrfs_root_item *root_item;
575         struct btrfs_inode_item *inode_item;
576         struct extent_buffer *leaf;
577         struct btrfs_root *root = BTRFS_I(dir)->root;
578         struct btrfs_root *new_root;
579         struct btrfs_block_rsv block_rsv;
580         struct timespec64 cur_time = current_time(dir);
581         struct inode *inode;
582         int ret;
583         int err;
584         u64 objectid;
585         u64 new_dirid = BTRFS_FIRST_FREE_OBJECTID;
586         u64 index = 0;
587         uuid_le new_uuid;
588
589         root_item = kzalloc(sizeof(*root_item), GFP_KERNEL);
590         if (!root_item)
591                 return -ENOMEM;
592
593         ret = btrfs_find_free_objectid(fs_info->tree_root, &objectid);
594         if (ret)
595                 goto fail_free;
596
597         /*
598          * Don't create subvolume whose level is not zero. Or qgroup will be
599          * screwed up since it assumes subvolume qgroup's level to be 0.
600          */
601         if (btrfs_qgroup_level(objectid)) {
602                 ret = -ENOSPC;
603                 goto fail_free;
604         }
605
606         btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
607         /*
608          * The same as the snapshot creation, please see the comment
609          * of create_snapshot().
610          */
611         ret = btrfs_subvolume_reserve_metadata(root, &block_rsv, 8, false);
612         if (ret)
613                 goto fail_free;
614
615         trans = btrfs_start_transaction(root, 0);
616         if (IS_ERR(trans)) {
617                 ret = PTR_ERR(trans);
618                 btrfs_subvolume_release_metadata(fs_info, &block_rsv);
619                 goto fail_free;
620         }
621         trans->block_rsv = &block_rsv;
622         trans->bytes_reserved = block_rsv.size;
623
624         ret = btrfs_qgroup_inherit(trans, 0, objectid, inherit);
625         if (ret)
626                 goto fail;
627
628         leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0);
629         if (IS_ERR(leaf)) {
630                 ret = PTR_ERR(leaf);
631                 goto fail;
632         }
633
634         btrfs_mark_buffer_dirty(leaf);
635
636         inode_item = &root_item->inode;
637         btrfs_set_stack_inode_generation(inode_item, 1);
638         btrfs_set_stack_inode_size(inode_item, 3);
639         btrfs_set_stack_inode_nlink(inode_item, 1);
640         btrfs_set_stack_inode_nbytes(inode_item,
641                                      fs_info->nodesize);
642         btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
643
644         btrfs_set_root_flags(root_item, 0);
645         btrfs_set_root_limit(root_item, 0);
646         btrfs_set_stack_inode_flags(inode_item, BTRFS_INODE_ROOT_ITEM_INIT);
647
648         btrfs_set_root_bytenr(root_item, leaf->start);
649         btrfs_set_root_generation(root_item, trans->transid);
650         btrfs_set_root_level(root_item, 0);
651         btrfs_set_root_refs(root_item, 1);
652         btrfs_set_root_used(root_item, leaf->len);
653         btrfs_set_root_last_snapshot(root_item, 0);
654
655         btrfs_set_root_generation_v2(root_item,
656                         btrfs_root_generation(root_item));
657         uuid_le_gen(&new_uuid);
658         memcpy(root_item->uuid, new_uuid.b, BTRFS_UUID_SIZE);
659         btrfs_set_stack_timespec_sec(&root_item->otime, cur_time.tv_sec);
660         btrfs_set_stack_timespec_nsec(&root_item->otime, cur_time.tv_nsec);
661         root_item->ctime = root_item->otime;
662         btrfs_set_root_ctransid(root_item, trans->transid);
663         btrfs_set_root_otransid(root_item, trans->transid);
664
665         btrfs_tree_unlock(leaf);
666         free_extent_buffer(leaf);
667         leaf = NULL;
668
669         btrfs_set_root_dirid(root_item, new_dirid);
670
671         key.objectid = objectid;
672         key.offset = 0;
673         key.type = BTRFS_ROOT_ITEM_KEY;
674         ret = btrfs_insert_root(trans, fs_info->tree_root, &key,
675                                 root_item);
676         if (ret)
677                 goto fail;
678
679         key.offset = (u64)-1;
680         new_root = btrfs_read_fs_root_no_name(fs_info, &key);
681         if (IS_ERR(new_root)) {
682                 ret = PTR_ERR(new_root);
683                 btrfs_abort_transaction(trans, ret);
684                 goto fail;
685         }
686
687         btrfs_record_root_in_trans(trans, new_root);
688
689         ret = btrfs_create_subvol_root(trans, new_root, root, new_dirid);
690         if (ret) {
691                 /* We potentially lose an unused inode item here */
692                 btrfs_abort_transaction(trans, ret);
693                 goto fail;
694         }
695
696         mutex_lock(&new_root->objectid_mutex);
697         new_root->highest_objectid = new_dirid;
698         mutex_unlock(&new_root->objectid_mutex);
699
700         /*
701          * insert the directory item
702          */
703         ret = btrfs_set_inode_index(BTRFS_I(dir), &index);
704         if (ret) {
705                 btrfs_abort_transaction(trans, ret);
706                 goto fail;
707         }
708
709         ret = btrfs_insert_dir_item(trans, name, namelen, BTRFS_I(dir), &key,
710                                     BTRFS_FT_DIR, index);
711         if (ret) {
712                 btrfs_abort_transaction(trans, ret);
713                 goto fail;
714         }
715
716         btrfs_i_size_write(BTRFS_I(dir), dir->i_size + namelen * 2);
717         ret = btrfs_update_inode(trans, root, dir);
718         BUG_ON(ret);
719
720         ret = btrfs_add_root_ref(trans, objectid, root->root_key.objectid,
721                                  btrfs_ino(BTRFS_I(dir)), index, name, namelen);
722         BUG_ON(ret);
723
724         ret = btrfs_uuid_tree_add(trans, root_item->uuid,
725                                   BTRFS_UUID_KEY_SUBVOL, objectid);
726         if (ret)
727                 btrfs_abort_transaction(trans, ret);
728
729 fail:
730         kfree(root_item);
731         trans->block_rsv = NULL;
732         trans->bytes_reserved = 0;
733         btrfs_subvolume_release_metadata(fs_info, &block_rsv);
734
735         if (async_transid) {
736                 *async_transid = trans->transid;
737                 err = btrfs_commit_transaction_async(trans, 1);
738                 if (err)
739                         err = btrfs_commit_transaction(trans);
740         } else {
741                 err = btrfs_commit_transaction(trans);
742         }
743         if (err && !ret)
744                 ret = err;
745
746         if (!ret) {
747                 inode = btrfs_lookup_dentry(dir, dentry);
748                 if (IS_ERR(inode))
749                         return PTR_ERR(inode);
750                 d_instantiate(dentry, inode);
751         }
752         return ret;
753
754 fail_free:
755         kfree(root_item);
756         return ret;
757 }
758
759 static int create_snapshot(struct btrfs_root *root, struct inode *dir,
760                            struct dentry *dentry,
761                            u64 *async_transid, bool readonly,
762                            struct btrfs_qgroup_inherit *inherit)
763 {
764         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
765         struct inode *inode;
766         struct btrfs_pending_snapshot *pending_snapshot;
767         struct btrfs_trans_handle *trans;
768         int ret;
769         bool snapshot_force_cow = false;
770
771         if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state))
772                 return -EINVAL;
773
774         if (atomic_read(&root->nr_swapfiles)) {
775                 btrfs_warn(fs_info,
776                            "cannot snapshot subvolume with active swapfile");
777                 return -ETXTBSY;
778         }
779
780         pending_snapshot = kzalloc(sizeof(*pending_snapshot), GFP_KERNEL);
781         if (!pending_snapshot)
782                 return -ENOMEM;
783
784         pending_snapshot->root_item = kzalloc(sizeof(struct btrfs_root_item),
785                         GFP_KERNEL);
786         pending_snapshot->path = btrfs_alloc_path();
787         if (!pending_snapshot->root_item || !pending_snapshot->path) {
788                 ret = -ENOMEM;
789                 goto free_pending;
790         }
791
792         /*
793          * Force new buffered writes to reserve space even when NOCOW is
794          * possible. This is to avoid later writeback (running dealloc) to
795          * fallback to COW mode and unexpectedly fail with ENOSPC.
796          */
797         atomic_inc(&root->will_be_snapshotted);
798         smp_mb__after_atomic();
799         /* wait for no snapshot writes */
800         wait_event(root->subv_writers->wait,
801                    percpu_counter_sum(&root->subv_writers->counter) == 0);
802
803         ret = btrfs_start_delalloc_snapshot(root);
804         if (ret)
805                 goto dec_and_free;
806
807         /*
808          * All previous writes have started writeback in NOCOW mode, so now
809          * we force future writes to fallback to COW mode during snapshot
810          * creation.
811          */
812         atomic_inc(&root->snapshot_force_cow);
813         snapshot_force_cow = true;
814
815         btrfs_wait_ordered_extents(root, U64_MAX, 0, (u64)-1);
816
817         btrfs_init_block_rsv(&pending_snapshot->block_rsv,
818                              BTRFS_BLOCK_RSV_TEMP);
819         /*
820          * 1 - parent dir inode
821          * 2 - dir entries
822          * 1 - root item
823          * 2 - root ref/backref
824          * 1 - root of snapshot
825          * 1 - UUID item
826          */
827         ret = btrfs_subvolume_reserve_metadata(BTRFS_I(dir)->root,
828                                         &pending_snapshot->block_rsv, 8,
829                                         false);
830         if (ret)
831                 goto dec_and_free;
832
833         pending_snapshot->dentry = dentry;
834         pending_snapshot->root = root;
835         pending_snapshot->readonly = readonly;
836         pending_snapshot->dir = dir;
837         pending_snapshot->inherit = inherit;
838
839         trans = btrfs_start_transaction(root, 0);
840         if (IS_ERR(trans)) {
841                 ret = PTR_ERR(trans);
842                 goto fail;
843         }
844
845         spin_lock(&fs_info->trans_lock);
846         list_add(&pending_snapshot->list,
847                  &trans->transaction->pending_snapshots);
848         spin_unlock(&fs_info->trans_lock);
849         if (async_transid) {
850                 *async_transid = trans->transid;
851                 ret = btrfs_commit_transaction_async(trans, 1);
852                 if (ret)
853                         ret = btrfs_commit_transaction(trans);
854         } else {
855                 ret = btrfs_commit_transaction(trans);
856         }
857         if (ret)
858                 goto fail;
859
860         ret = pending_snapshot->error;
861         if (ret)
862                 goto fail;
863
864         ret = btrfs_orphan_cleanup(pending_snapshot->snap);
865         if (ret)
866                 goto fail;
867
868         inode = btrfs_lookup_dentry(d_inode(dentry->d_parent), dentry);
869         if (IS_ERR(inode)) {
870                 ret = PTR_ERR(inode);
871                 goto fail;
872         }
873
874         d_instantiate(dentry, inode);
875         ret = 0;
876 fail:
877         btrfs_subvolume_release_metadata(fs_info, &pending_snapshot->block_rsv);
878 dec_and_free:
879         if (snapshot_force_cow)
880                 atomic_dec(&root->snapshot_force_cow);
881         if (atomic_dec_and_test(&root->will_be_snapshotted))
882                 wake_up_var(&root->will_be_snapshotted);
883 free_pending:
884         kfree(pending_snapshot->root_item);
885         btrfs_free_path(pending_snapshot->path);
886         kfree(pending_snapshot);
887
888         return ret;
889 }
890
891 /*  copy of may_delete in fs/namei.c()
892  *      Check whether we can remove a link victim from directory dir, check
893  *  whether the type of victim is right.
894  *  1. We can't do it if dir is read-only (done in permission())
895  *  2. We should have write and exec permissions on dir
896  *  3. We can't remove anything from append-only dir
897  *  4. We can't do anything with immutable dir (done in permission())
898  *  5. If the sticky bit on dir is set we should either
899  *      a. be owner of dir, or
900  *      b. be owner of victim, or
901  *      c. have CAP_FOWNER capability
902  *  6. If the victim is append-only or immutable we can't do anything with
903  *     links pointing to it.
904  *  7. If we were asked to remove a directory and victim isn't one - ENOTDIR.
905  *  8. If we were asked to remove a non-directory and victim isn't one - EISDIR.
906  *  9. We can't remove a root or mountpoint.
907  * 10. We don't allow removal of NFS sillyrenamed files; it's handled by
908  *     nfs_async_unlink().
909  */
910
911 static int btrfs_may_delete(struct inode *dir, struct dentry *victim, int isdir)
912 {
913         int error;
914
915         if (d_really_is_negative(victim))
916                 return -ENOENT;
917
918         BUG_ON(d_inode(victim->d_parent) != dir);
919         audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE);
920
921         error = inode_permission(dir, MAY_WRITE | MAY_EXEC);
922         if (error)
923                 return error;
924         if (IS_APPEND(dir))
925                 return -EPERM;
926         if (check_sticky(dir, d_inode(victim)) || IS_APPEND(d_inode(victim)) ||
927             IS_IMMUTABLE(d_inode(victim)) || IS_SWAPFILE(d_inode(victim)))
928                 return -EPERM;
929         if (isdir) {
930                 if (!d_is_dir(victim))
931                         return -ENOTDIR;
932                 if (IS_ROOT(victim))
933                         return -EBUSY;
934         } else if (d_is_dir(victim))
935                 return -EISDIR;
936         if (IS_DEADDIR(dir))
937                 return -ENOENT;
938         if (victim->d_flags & DCACHE_NFSFS_RENAMED)
939                 return -EBUSY;
940         return 0;
941 }
942
943 /* copy of may_create in fs/namei.c() */
944 static inline int btrfs_may_create(struct inode *dir, struct dentry *child)
945 {
946         if (d_really_is_positive(child))
947                 return -EEXIST;
948         if (IS_DEADDIR(dir))
949                 return -ENOENT;
950         return inode_permission(dir, MAY_WRITE | MAY_EXEC);
951 }
952
953 /*
954  * Create a new subvolume below @parent.  This is largely modeled after
955  * sys_mkdirat and vfs_mkdir, but we only do a single component lookup
956  * inside this filesystem so it's quite a bit simpler.
957  */
958 static noinline int btrfs_mksubvol(const struct path *parent,
959                                    const char *name, int namelen,
960                                    struct btrfs_root *snap_src,
961                                    u64 *async_transid, bool readonly,
962                                    struct btrfs_qgroup_inherit *inherit)
963 {
964         struct inode *dir = d_inode(parent->dentry);
965         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
966         struct dentry *dentry;
967         int error;
968
969         error = down_write_killable_nested(&dir->i_rwsem, I_MUTEX_PARENT);
970         if (error == -EINTR)
971                 return error;
972
973         dentry = lookup_one_len(name, parent->dentry, namelen);
974         error = PTR_ERR(dentry);
975         if (IS_ERR(dentry))
976                 goto out_unlock;
977
978         error = btrfs_may_create(dir, dentry);
979         if (error)
980                 goto out_dput;
981
982         /*
983          * even if this name doesn't exist, we may get hash collisions.
984          * check for them now when we can safely fail
985          */
986         error = btrfs_check_dir_item_collision(BTRFS_I(dir)->root,
987                                                dir->i_ino, name,
988                                                namelen);
989         if (error)
990                 goto out_dput;
991
992         down_read(&fs_info->subvol_sem);
993
994         if (btrfs_root_refs(&BTRFS_I(dir)->root->root_item) == 0)
995                 goto out_up_read;
996
997         if (snap_src) {
998                 error = create_snapshot(snap_src, dir, dentry,
999                                         async_transid, readonly, inherit);
1000         } else {
1001                 error = create_subvol(dir, dentry, name, namelen,
1002                                       async_transid, inherit);
1003         }
1004         if (!error)
1005                 fsnotify_mkdir(dir, dentry);
1006 out_up_read:
1007         up_read(&fs_info->subvol_sem);
1008 out_dput:
1009         dput(dentry);
1010 out_unlock:
1011         inode_unlock(dir);
1012         return error;
1013 }
1014
1015 /*
1016  * When we're defragging a range, we don't want to kick it off again
1017  * if it is really just waiting for delalloc to send it down.
1018  * If we find a nice big extent or delalloc range for the bytes in the
1019  * file you want to defrag, we return 0 to let you know to skip this
1020  * part of the file
1021  */
1022 static int check_defrag_in_cache(struct inode *inode, u64 offset, u32 thresh)
1023 {
1024         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1025         struct extent_map *em = NULL;
1026         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
1027         u64 end;
1028
1029         read_lock(&em_tree->lock);
1030         em = lookup_extent_mapping(em_tree, offset, PAGE_SIZE);
1031         read_unlock(&em_tree->lock);
1032
1033         if (em) {
1034                 end = extent_map_end(em);
1035                 free_extent_map(em);
1036                 if (end - offset > thresh)
1037                         return 0;
1038         }
1039         /* if we already have a nice delalloc here, just stop */
1040         thresh /= 2;
1041         end = count_range_bits(io_tree, &offset, offset + thresh,
1042                                thresh, EXTENT_DELALLOC, 1);
1043         if (end >= thresh)
1044                 return 0;
1045         return 1;
1046 }
1047
1048 /*
1049  * helper function to walk through a file and find extents
1050  * newer than a specific transid, and smaller than thresh.
1051  *
1052  * This is used by the defragging code to find new and small
1053  * extents
1054  */
1055 static int find_new_extents(struct btrfs_root *root,
1056                             struct inode *inode, u64 newer_than,
1057                             u64 *off, u32 thresh)
1058 {
1059         struct btrfs_path *path;
1060         struct btrfs_key min_key;
1061         struct extent_buffer *leaf;
1062         struct btrfs_file_extent_item *extent;
1063         int type;
1064         int ret;
1065         u64 ino = btrfs_ino(BTRFS_I(inode));
1066
1067         path = btrfs_alloc_path();
1068         if (!path)
1069                 return -ENOMEM;
1070
1071         min_key.objectid = ino;
1072         min_key.type = BTRFS_EXTENT_DATA_KEY;
1073         min_key.offset = *off;
1074
1075         while (1) {
1076                 ret = btrfs_search_forward(root, &min_key, path, newer_than);
1077                 if (ret != 0)
1078                         goto none;
1079 process_slot:
1080                 if (min_key.objectid != ino)
1081                         goto none;
1082                 if (min_key.type != BTRFS_EXTENT_DATA_KEY)
1083                         goto none;
1084
1085                 leaf = path->nodes[0];
1086                 extent = btrfs_item_ptr(leaf, path->slots[0],
1087                                         struct btrfs_file_extent_item);
1088
1089                 type = btrfs_file_extent_type(leaf, extent);
1090                 if (type == BTRFS_FILE_EXTENT_REG &&
1091                     btrfs_file_extent_num_bytes(leaf, extent) < thresh &&
1092                     check_defrag_in_cache(inode, min_key.offset, thresh)) {
1093                         *off = min_key.offset;
1094                         btrfs_free_path(path);
1095                         return 0;
1096                 }
1097
1098                 path->slots[0]++;
1099                 if (path->slots[0] < btrfs_header_nritems(leaf)) {
1100                         btrfs_item_key_to_cpu(leaf, &min_key, path->slots[0]);
1101                         goto process_slot;
1102                 }
1103
1104                 if (min_key.offset == (u64)-1)
1105                         goto none;
1106
1107                 min_key.offset++;
1108                 btrfs_release_path(path);
1109         }
1110 none:
1111         btrfs_free_path(path);
1112         return -ENOENT;
1113 }
1114
1115 static struct extent_map *defrag_lookup_extent(struct inode *inode, u64 start)
1116 {
1117         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
1118         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1119         struct extent_map *em;
1120         u64 len = PAGE_SIZE;
1121
1122         /*
1123          * hopefully we have this extent in the tree already, try without
1124          * the full extent lock
1125          */
1126         read_lock(&em_tree->lock);
1127         em = lookup_extent_mapping(em_tree, start, len);
1128         read_unlock(&em_tree->lock);
1129
1130         if (!em) {
1131                 struct extent_state *cached = NULL;
1132                 u64 end = start + len - 1;
1133
1134                 /* get the big lock and read metadata off disk */
1135                 lock_extent_bits(io_tree, start, end, &cached);
1136                 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
1137                 unlock_extent_cached(io_tree, start, end, &cached);
1138
1139                 if (IS_ERR(em))
1140                         return NULL;
1141         }
1142
1143         return em;
1144 }
1145
1146 static bool defrag_check_next_extent(struct inode *inode, struct extent_map *em)
1147 {
1148         struct extent_map *next;
1149         bool ret = true;
1150
1151         /* this is the last extent */
1152         if (em->start + em->len >= i_size_read(inode))
1153                 return false;
1154
1155         next = defrag_lookup_extent(inode, em->start + em->len);
1156         if (!next || next->block_start >= EXTENT_MAP_LAST_BYTE)
1157                 ret = false;
1158         else if ((em->block_start + em->block_len == next->block_start) &&
1159                  (em->block_len > SZ_128K && next->block_len > SZ_128K))
1160                 ret = false;
1161
1162         free_extent_map(next);
1163         return ret;
1164 }
1165
1166 static int should_defrag_range(struct inode *inode, u64 start, u32 thresh,
1167                                u64 *last_len, u64 *skip, u64 *defrag_end,
1168                                int compress)
1169 {
1170         struct extent_map *em;
1171         int ret = 1;
1172         bool next_mergeable = true;
1173         bool prev_mergeable = true;
1174
1175         /*
1176          * make sure that once we start defragging an extent, we keep on
1177          * defragging it
1178          */
1179         if (start < *defrag_end)
1180                 return 1;
1181
1182         *skip = 0;
1183
1184         em = defrag_lookup_extent(inode, start);
1185         if (!em)
1186                 return 0;
1187
1188         /* this will cover holes, and inline extents */
1189         if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
1190                 ret = 0;
1191                 goto out;
1192         }
1193
1194         if (!*defrag_end)
1195                 prev_mergeable = false;
1196
1197         next_mergeable = defrag_check_next_extent(inode, em);
1198         /*
1199          * we hit a real extent, if it is big or the next extent is not a
1200          * real extent, don't bother defragging it
1201          */
1202         if (!compress && (*last_len == 0 || *last_len >= thresh) &&
1203             (em->len >= thresh || (!next_mergeable && !prev_mergeable)))
1204                 ret = 0;
1205 out:
1206         /*
1207          * last_len ends up being a counter of how many bytes we've defragged.
1208          * every time we choose not to defrag an extent, we reset *last_len
1209          * so that the next tiny extent will force a defrag.
1210          *
1211          * The end result of this is that tiny extents before a single big
1212          * extent will force at least part of that big extent to be defragged.
1213          */
1214         if (ret) {
1215                 *defrag_end = extent_map_end(em);
1216         } else {
1217                 *last_len = 0;
1218                 *skip = extent_map_end(em);
1219                 *defrag_end = 0;
1220         }
1221
1222         free_extent_map(em);
1223         return ret;
1224 }
1225
1226 /*
1227  * it doesn't do much good to defrag one or two pages
1228  * at a time.  This pulls in a nice chunk of pages
1229  * to COW and defrag.
1230  *
1231  * It also makes sure the delalloc code has enough
1232  * dirty data to avoid making new small extents as part
1233  * of the defrag
1234  *
1235  * It's a good idea to start RA on this range
1236  * before calling this.
1237  */
1238 static int cluster_pages_for_defrag(struct inode *inode,
1239                                     struct page **pages,
1240                                     unsigned long start_index,
1241                                     unsigned long num_pages)
1242 {
1243         unsigned long file_end;
1244         u64 isize = i_size_read(inode);
1245         u64 page_start;
1246         u64 page_end;
1247         u64 page_cnt;
1248         int ret;
1249         int i;
1250         int i_done;
1251         struct btrfs_ordered_extent *ordered;
1252         struct extent_state *cached_state = NULL;
1253         struct extent_io_tree *tree;
1254         struct extent_changeset *data_reserved = NULL;
1255         gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
1256
1257         file_end = (isize - 1) >> PAGE_SHIFT;
1258         if (!isize || start_index > file_end)
1259                 return 0;
1260
1261         page_cnt = min_t(u64, (u64)num_pages, (u64)file_end - start_index + 1);
1262
1263         ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
1264                         start_index << PAGE_SHIFT,
1265                         page_cnt << PAGE_SHIFT);
1266         if (ret)
1267                 return ret;
1268         i_done = 0;
1269         tree = &BTRFS_I(inode)->io_tree;
1270
1271         /* step one, lock all the pages */
1272         for (i = 0; i < page_cnt; i++) {
1273                 struct page *page;
1274 again:
1275                 page = find_or_create_page(inode->i_mapping,
1276                                            start_index + i, mask);
1277                 if (!page)
1278                         break;
1279
1280                 page_start = page_offset(page);
1281                 page_end = page_start + PAGE_SIZE - 1;
1282                 while (1) {
1283                         lock_extent_bits(tree, page_start, page_end,
1284                                          &cached_state);
1285                         ordered = btrfs_lookup_ordered_extent(inode,
1286                                                               page_start);
1287                         unlock_extent_cached(tree, page_start, page_end,
1288                                              &cached_state);
1289                         if (!ordered)
1290                                 break;
1291
1292                         unlock_page(page);
1293                         btrfs_start_ordered_extent(inode, ordered, 1);
1294                         btrfs_put_ordered_extent(ordered);
1295                         lock_page(page);
1296                         /*
1297                          * we unlocked the page above, so we need check if
1298                          * it was released or not.
1299                          */
1300                         if (page->mapping != inode->i_mapping) {
1301                                 unlock_page(page);
1302                                 put_page(page);
1303                                 goto again;
1304                         }
1305                 }
1306
1307                 if (!PageUptodate(page)) {
1308                         btrfs_readpage(NULL, page);
1309                         lock_page(page);
1310                         if (!PageUptodate(page)) {
1311                                 unlock_page(page);
1312                                 put_page(page);
1313                                 ret = -EIO;
1314                                 break;
1315                         }
1316                 }
1317
1318                 if (page->mapping != inode->i_mapping) {
1319                         unlock_page(page);
1320                         put_page(page);
1321                         goto again;
1322                 }
1323
1324                 pages[i] = page;
1325                 i_done++;
1326         }
1327         if (!i_done || ret)
1328                 goto out;
1329
1330         if (!(inode->i_sb->s_flags & SB_ACTIVE))
1331                 goto out;
1332
1333         /*
1334          * so now we have a nice long stream of locked
1335          * and up to date pages, lets wait on them
1336          */
1337         for (i = 0; i < i_done; i++)
1338                 wait_on_page_writeback(pages[i]);
1339
1340         page_start = page_offset(pages[0]);
1341         page_end = page_offset(pages[i_done - 1]) + PAGE_SIZE;
1342
1343         lock_extent_bits(&BTRFS_I(inode)->io_tree,
1344                          page_start, page_end - 1, &cached_state);
1345         clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start,
1346                           page_end - 1, EXTENT_DIRTY | EXTENT_DELALLOC |
1347                           EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 0, 0,
1348                           &cached_state);
1349
1350         if (i_done != page_cnt) {
1351                 spin_lock(&BTRFS_I(inode)->lock);
1352                 btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
1353                 spin_unlock(&BTRFS_I(inode)->lock);
1354                 btrfs_delalloc_release_space(inode, data_reserved,
1355                                 start_index << PAGE_SHIFT,
1356                                 (page_cnt - i_done) << PAGE_SHIFT, true);
1357         }
1358
1359
1360         set_extent_defrag(&BTRFS_I(inode)->io_tree, page_start, page_end - 1,
1361                           &cached_state);
1362
1363         unlock_extent_cached(&BTRFS_I(inode)->io_tree,
1364                              page_start, page_end - 1, &cached_state);
1365
1366         for (i = 0; i < i_done; i++) {
1367                 clear_page_dirty_for_io(pages[i]);
1368                 ClearPageChecked(pages[i]);
1369                 set_page_extent_mapped(pages[i]);
1370                 set_page_dirty(pages[i]);
1371                 unlock_page(pages[i]);
1372                 put_page(pages[i]);
1373         }
1374         btrfs_delalloc_release_extents(BTRFS_I(inode), page_cnt << PAGE_SHIFT,
1375                                        false);
1376         extent_changeset_free(data_reserved);
1377         return i_done;
1378 out:
1379         for (i = 0; i < i_done; i++) {
1380                 unlock_page(pages[i]);
1381                 put_page(pages[i]);
1382         }
1383         btrfs_delalloc_release_space(inode, data_reserved,
1384                         start_index << PAGE_SHIFT,
1385                         page_cnt << PAGE_SHIFT, true);
1386         btrfs_delalloc_release_extents(BTRFS_I(inode), page_cnt << PAGE_SHIFT,
1387                                        true);
1388         extent_changeset_free(data_reserved);
1389         return ret;
1390
1391 }
1392
1393 int btrfs_defrag_file(struct inode *inode, struct file *file,
1394                       struct btrfs_ioctl_defrag_range_args *range,
1395                       u64 newer_than, unsigned long max_to_defrag)
1396 {
1397         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1398         struct btrfs_root *root = BTRFS_I(inode)->root;
1399         struct file_ra_state *ra = NULL;
1400         unsigned long last_index;
1401         u64 isize = i_size_read(inode);
1402         u64 last_len = 0;
1403         u64 skip = 0;
1404         u64 defrag_end = 0;
1405         u64 newer_off = range->start;
1406         unsigned long i;
1407         unsigned long ra_index = 0;
1408         int ret;
1409         int defrag_count = 0;
1410         int compress_type = BTRFS_COMPRESS_ZLIB;
1411         u32 extent_thresh = range->extent_thresh;
1412         unsigned long max_cluster = SZ_256K >> PAGE_SHIFT;
1413         unsigned long cluster = max_cluster;
1414         u64 new_align = ~((u64)SZ_128K - 1);
1415         struct page **pages = NULL;
1416         bool do_compress = range->flags & BTRFS_DEFRAG_RANGE_COMPRESS;
1417
1418         if (isize == 0)
1419                 return 0;
1420
1421         if (range->start >= isize)
1422                 return -EINVAL;
1423
1424         if (do_compress) {
1425                 if (range->compress_type > BTRFS_COMPRESS_TYPES)
1426                         return -EINVAL;
1427                 if (range->compress_type)
1428                         compress_type = range->compress_type;
1429         }
1430
1431         if (extent_thresh == 0)
1432                 extent_thresh = SZ_256K;
1433
1434         /*
1435          * If we were not given a file, allocate a readahead context. As
1436          * readahead is just an optimization, defrag will work without it so
1437          * we don't error out.
1438          */
1439         if (!file) {
1440                 ra = kzalloc(sizeof(*ra), GFP_KERNEL);
1441                 if (ra)
1442                         file_ra_state_init(ra, inode->i_mapping);
1443         } else {
1444                 ra = &file->f_ra;
1445         }
1446
1447         pages = kmalloc_array(max_cluster, sizeof(struct page *), GFP_KERNEL);
1448         if (!pages) {
1449                 ret = -ENOMEM;
1450                 goto out_ra;
1451         }
1452
1453         /* find the last page to defrag */
1454         if (range->start + range->len > range->start) {
1455                 last_index = min_t(u64, isize - 1,
1456                          range->start + range->len - 1) >> PAGE_SHIFT;
1457         } else {
1458                 last_index = (isize - 1) >> PAGE_SHIFT;
1459         }
1460
1461         if (newer_than) {
1462                 ret = find_new_extents(root, inode, newer_than,
1463                                        &newer_off, SZ_64K);
1464                 if (!ret) {
1465                         range->start = newer_off;
1466                         /*
1467                          * we always align our defrag to help keep
1468                          * the extents in the file evenly spaced
1469                          */
1470                         i = (newer_off & new_align) >> PAGE_SHIFT;
1471                 } else
1472                         goto out_ra;
1473         } else {
1474                 i = range->start >> PAGE_SHIFT;
1475         }
1476         if (!max_to_defrag)
1477                 max_to_defrag = last_index - i + 1;
1478
1479         /*
1480          * make writeback starts from i, so the defrag range can be
1481          * written sequentially.
1482          */
1483         if (i < inode->i_mapping->writeback_index)
1484                 inode->i_mapping->writeback_index = i;
1485
1486         while (i <= last_index && defrag_count < max_to_defrag &&
1487                (i < DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE))) {
1488                 /*
1489                  * make sure we stop running if someone unmounts
1490                  * the FS
1491                  */
1492                 if (!(inode->i_sb->s_flags & SB_ACTIVE))
1493                         break;
1494
1495                 if (btrfs_defrag_cancelled(fs_info)) {
1496                         btrfs_debug(fs_info, "defrag_file cancelled");
1497                         ret = -EAGAIN;
1498                         break;
1499                 }
1500
1501                 if (!should_defrag_range(inode, (u64)i << PAGE_SHIFT,
1502                                          extent_thresh, &last_len, &skip,
1503                                          &defrag_end, do_compress)){
1504                         unsigned long next;
1505                         /*
1506                          * the should_defrag function tells us how much to skip
1507                          * bump our counter by the suggested amount
1508                          */
1509                         next = DIV_ROUND_UP(skip, PAGE_SIZE);
1510                         i = max(i + 1, next);
1511                         continue;
1512                 }
1513
1514                 if (!newer_than) {
1515                         cluster = (PAGE_ALIGN(defrag_end) >>
1516                                    PAGE_SHIFT) - i;
1517                         cluster = min(cluster, max_cluster);
1518                 } else {
1519                         cluster = max_cluster;
1520                 }
1521
1522                 if (i + cluster > ra_index) {
1523                         ra_index = max(i, ra_index);
1524                         if (ra)
1525                                 page_cache_sync_readahead(inode->i_mapping, ra,
1526                                                 file, ra_index, cluster);
1527                         ra_index += cluster;
1528                 }
1529
1530                 inode_lock(inode);
1531                 if (IS_SWAPFILE(inode)) {
1532                         ret = -ETXTBSY;
1533                 } else {
1534                         if (do_compress)
1535                                 BTRFS_I(inode)->defrag_compress = compress_type;
1536                         ret = cluster_pages_for_defrag(inode, pages, i, cluster);
1537                 }
1538                 if (ret < 0) {
1539                         inode_unlock(inode);
1540                         goto out_ra;
1541                 }
1542
1543                 defrag_count += ret;
1544                 balance_dirty_pages_ratelimited(inode->i_mapping);
1545                 inode_unlock(inode);
1546
1547                 if (newer_than) {
1548                         if (newer_off == (u64)-1)
1549                                 break;
1550
1551                         if (ret > 0)
1552                                 i += ret;
1553
1554                         newer_off = max(newer_off + 1,
1555                                         (u64)i << PAGE_SHIFT);
1556
1557                         ret = find_new_extents(root, inode, newer_than,
1558                                                &newer_off, SZ_64K);
1559                         if (!ret) {
1560                                 range->start = newer_off;
1561                                 i = (newer_off & new_align) >> PAGE_SHIFT;
1562                         } else {
1563                                 break;
1564                         }
1565                 } else {
1566                         if (ret > 0) {
1567                                 i += ret;
1568                                 last_len += ret << PAGE_SHIFT;
1569                         } else {
1570                                 i++;
1571                                 last_len = 0;
1572                         }
1573                 }
1574         }
1575
1576         if ((range->flags & BTRFS_DEFRAG_RANGE_START_IO)) {
1577                 filemap_flush(inode->i_mapping);
1578                 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1579                              &BTRFS_I(inode)->runtime_flags))
1580                         filemap_flush(inode->i_mapping);
1581         }
1582
1583         if (range->compress_type == BTRFS_COMPRESS_LZO) {
1584                 btrfs_set_fs_incompat(fs_info, COMPRESS_LZO);
1585         } else if (range->compress_type == BTRFS_COMPRESS_ZSTD) {
1586                 btrfs_set_fs_incompat(fs_info, COMPRESS_ZSTD);
1587         }
1588
1589         ret = defrag_count;
1590
1591 out_ra:
1592         if (do_compress) {
1593                 inode_lock(inode);
1594                 BTRFS_I(inode)->defrag_compress = BTRFS_COMPRESS_NONE;
1595                 inode_unlock(inode);
1596         }
1597         if (!file)
1598                 kfree(ra);
1599         kfree(pages);
1600         return ret;
1601 }
1602
1603 static noinline int btrfs_ioctl_resize(struct file *file,
1604                                         void __user *arg)
1605 {
1606         struct inode *inode = file_inode(file);
1607         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1608         u64 new_size;
1609         u64 old_size;
1610         u64 devid = 1;
1611         struct btrfs_root *root = BTRFS_I(inode)->root;
1612         struct btrfs_ioctl_vol_args *vol_args;
1613         struct btrfs_trans_handle *trans;
1614         struct btrfs_device *device = NULL;
1615         char *sizestr;
1616         char *retptr;
1617         char *devstr = NULL;
1618         int ret = 0;
1619         int mod = 0;
1620
1621         if (!capable(CAP_SYS_ADMIN))
1622                 return -EPERM;
1623
1624         ret = mnt_want_write_file(file);
1625         if (ret)
1626                 return ret;
1627
1628         if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
1629                 mnt_drop_write_file(file);
1630                 return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
1631         }
1632
1633         vol_args = memdup_user(arg, sizeof(*vol_args));
1634         if (IS_ERR(vol_args)) {
1635                 ret = PTR_ERR(vol_args);
1636                 goto out;
1637         }
1638
1639         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1640
1641         sizestr = vol_args->name;
1642         devstr = strchr(sizestr, ':');
1643         if (devstr) {
1644                 sizestr = devstr + 1;
1645                 *devstr = '\0';
1646                 devstr = vol_args->name;
1647                 ret = kstrtoull(devstr, 10, &devid);
1648                 if (ret)
1649                         goto out_free;
1650                 if (!devid) {
1651                         ret = -EINVAL;
1652                         goto out_free;
1653                 }
1654                 btrfs_info(fs_info, "resizing devid %llu", devid);
1655         }
1656
1657         device = btrfs_find_device(fs_info->fs_devices, devid, NULL, NULL, true);
1658         if (!device) {
1659                 btrfs_info(fs_info, "resizer unable to find device %llu",
1660                            devid);
1661                 ret = -ENODEV;
1662                 goto out_free;
1663         }
1664
1665         if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1666                 btrfs_info(fs_info,
1667                            "resizer unable to apply on readonly device %llu",
1668                        devid);
1669                 ret = -EPERM;
1670                 goto out_free;
1671         }
1672
1673         if (!strcmp(sizestr, "max"))
1674                 new_size = device->bdev->bd_inode->i_size;
1675         else {
1676                 if (sizestr[0] == '-') {
1677                         mod = -1;
1678                         sizestr++;
1679                 } else if (sizestr[0] == '+') {
1680                         mod = 1;
1681                         sizestr++;
1682                 }
1683                 new_size = memparse(sizestr, &retptr);
1684                 if (*retptr != '\0' || new_size == 0) {
1685                         ret = -EINVAL;
1686                         goto out_free;
1687                 }
1688         }
1689
1690         if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1691                 ret = -EPERM;
1692                 goto out_free;
1693         }
1694
1695         old_size = btrfs_device_get_total_bytes(device);
1696
1697         if (mod < 0) {
1698                 if (new_size > old_size) {
1699                         ret = -EINVAL;
1700                         goto out_free;
1701                 }
1702                 new_size = old_size - new_size;
1703         } else if (mod > 0) {
1704                 if (new_size > ULLONG_MAX - old_size) {
1705                         ret = -ERANGE;
1706                         goto out_free;
1707                 }
1708                 new_size = old_size + new_size;
1709         }
1710
1711         if (new_size < SZ_256M) {
1712                 ret = -EINVAL;
1713                 goto out_free;
1714         }
1715         if (new_size > device->bdev->bd_inode->i_size) {
1716                 ret = -EFBIG;
1717                 goto out_free;
1718         }
1719
1720         new_size = round_down(new_size, fs_info->sectorsize);
1721
1722         btrfs_info_in_rcu(fs_info, "new size for %s is %llu",
1723                           rcu_str_deref(device->name), new_size);
1724
1725         if (new_size > old_size) {
1726                 trans = btrfs_start_transaction(root, 0);
1727                 if (IS_ERR(trans)) {
1728                         ret = PTR_ERR(trans);
1729                         goto out_free;
1730                 }
1731                 ret = btrfs_grow_device(trans, device, new_size);
1732                 btrfs_commit_transaction(trans);
1733         } else if (new_size < old_size) {
1734                 ret = btrfs_shrink_device(device, new_size);
1735         } /* equal, nothing need to do */
1736
1737 out_free:
1738         kfree(vol_args);
1739 out:
1740         clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
1741         mnt_drop_write_file(file);
1742         return ret;
1743 }
1744
1745 static noinline int btrfs_ioctl_snap_create_transid(struct file *file,
1746                                 const char *name, unsigned long fd, int subvol,
1747                                 u64 *transid, bool readonly,
1748                                 struct btrfs_qgroup_inherit *inherit)
1749 {
1750         int namelen;
1751         int ret = 0;
1752
1753         if (!S_ISDIR(file_inode(file)->i_mode))
1754                 return -ENOTDIR;
1755
1756         ret = mnt_want_write_file(file);
1757         if (ret)
1758                 goto out;
1759
1760         namelen = strlen(name);
1761         if (strchr(name, '/')) {
1762                 ret = -EINVAL;
1763                 goto out_drop_write;
1764         }
1765
1766         if (name[0] == '.' &&
1767            (namelen == 1 || (name[1] == '.' && namelen == 2))) {
1768                 ret = -EEXIST;
1769                 goto out_drop_write;
1770         }
1771
1772         if (subvol) {
1773                 ret = btrfs_mksubvol(&file->f_path, name, namelen,
1774                                      NULL, transid, readonly, inherit);
1775         } else {
1776                 struct fd src = fdget(fd);
1777                 struct inode *src_inode;
1778                 if (!src.file) {
1779                         ret = -EINVAL;
1780                         goto out_drop_write;
1781                 }
1782
1783                 src_inode = file_inode(src.file);
1784                 if (src_inode->i_sb != file_inode(file)->i_sb) {
1785                         btrfs_info(BTRFS_I(file_inode(file))->root->fs_info,
1786                                    "Snapshot src from another FS");
1787                         ret = -EXDEV;
1788                 } else if (!inode_owner_or_capable(src_inode)) {
1789                         /*
1790                          * Subvolume creation is not restricted, but snapshots
1791                          * are limited to own subvolumes only
1792                          */
1793                         ret = -EPERM;
1794                 } else {
1795                         ret = btrfs_mksubvol(&file->f_path, name, namelen,
1796                                              BTRFS_I(src_inode)->root,
1797                                              transid, readonly, inherit);
1798                 }
1799                 fdput(src);
1800         }
1801 out_drop_write:
1802         mnt_drop_write_file(file);
1803 out:
1804         return ret;
1805 }
1806
1807 static noinline int btrfs_ioctl_snap_create(struct file *file,
1808                                             void __user *arg, int subvol)
1809 {
1810         struct btrfs_ioctl_vol_args *vol_args;
1811         int ret;
1812
1813         if (!S_ISDIR(file_inode(file)->i_mode))
1814                 return -ENOTDIR;
1815
1816         vol_args = memdup_user(arg, sizeof(*vol_args));
1817         if (IS_ERR(vol_args))
1818                 return PTR_ERR(vol_args);
1819         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1820
1821         ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
1822                                               vol_args->fd, subvol,
1823                                               NULL, false, NULL);
1824
1825         kfree(vol_args);
1826         return ret;
1827 }
1828
1829 static noinline int btrfs_ioctl_snap_create_v2(struct file *file,
1830                                                void __user *arg, int subvol)
1831 {
1832         struct btrfs_ioctl_vol_args_v2 *vol_args;
1833         int ret;
1834         u64 transid = 0;
1835         u64 *ptr = NULL;
1836         bool readonly = false;
1837         struct btrfs_qgroup_inherit *inherit = NULL;
1838
1839         if (!S_ISDIR(file_inode(file)->i_mode))
1840                 return -ENOTDIR;
1841
1842         vol_args = memdup_user(arg, sizeof(*vol_args));
1843         if (IS_ERR(vol_args))
1844                 return PTR_ERR(vol_args);
1845         vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
1846
1847         if (vol_args->flags &
1848             ~(BTRFS_SUBVOL_CREATE_ASYNC | BTRFS_SUBVOL_RDONLY |
1849               BTRFS_SUBVOL_QGROUP_INHERIT)) {
1850                 ret = -EOPNOTSUPP;
1851                 goto free_args;
1852         }
1853
1854         if (vol_args->flags & BTRFS_SUBVOL_CREATE_ASYNC)
1855                 ptr = &transid;
1856         if (vol_args->flags & BTRFS_SUBVOL_RDONLY)
1857                 readonly = true;
1858         if (vol_args->flags & BTRFS_SUBVOL_QGROUP_INHERIT) {
1859                 if (vol_args->size > PAGE_SIZE) {
1860                         ret = -EINVAL;
1861                         goto free_args;
1862                 }
1863                 inherit = memdup_user(vol_args->qgroup_inherit, vol_args->size);
1864                 if (IS_ERR(inherit)) {
1865                         ret = PTR_ERR(inherit);
1866                         goto free_args;
1867                 }
1868         }
1869
1870         ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
1871                                               vol_args->fd, subvol, ptr,
1872                                               readonly, inherit);
1873         if (ret)
1874                 goto free_inherit;
1875
1876         if (ptr && copy_to_user(arg +
1877                                 offsetof(struct btrfs_ioctl_vol_args_v2,
1878                                         transid),
1879                                 ptr, sizeof(*ptr)))
1880                 ret = -EFAULT;
1881
1882 free_inherit:
1883         kfree(inherit);
1884 free_args:
1885         kfree(vol_args);
1886         return ret;
1887 }
1888
1889 static noinline int btrfs_ioctl_subvol_getflags(struct file *file,
1890                                                 void __user *arg)
1891 {
1892         struct inode *inode = file_inode(file);
1893         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1894         struct btrfs_root *root = BTRFS_I(inode)->root;
1895         int ret = 0;
1896         u64 flags = 0;
1897
1898         if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID)
1899                 return -EINVAL;
1900
1901         down_read(&fs_info->subvol_sem);
1902         if (btrfs_root_readonly(root))
1903                 flags |= BTRFS_SUBVOL_RDONLY;
1904         up_read(&fs_info->subvol_sem);
1905
1906         if (copy_to_user(arg, &flags, sizeof(flags)))
1907                 ret = -EFAULT;
1908
1909         return ret;
1910 }
1911
1912 static noinline int btrfs_ioctl_subvol_setflags(struct file *file,
1913                                               void __user *arg)
1914 {
1915         struct inode *inode = file_inode(file);
1916         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1917         struct btrfs_root *root = BTRFS_I(inode)->root;
1918         struct btrfs_trans_handle *trans;
1919         u64 root_flags;
1920         u64 flags;
1921         int ret = 0;
1922
1923         if (!inode_owner_or_capable(inode))
1924                 return -EPERM;
1925
1926         ret = mnt_want_write_file(file);
1927         if (ret)
1928                 goto out;
1929
1930         if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
1931                 ret = -EINVAL;
1932                 goto out_drop_write;
1933         }
1934
1935         if (copy_from_user(&flags, arg, sizeof(flags))) {
1936                 ret = -EFAULT;
1937                 goto out_drop_write;
1938         }
1939
1940         if (flags & BTRFS_SUBVOL_CREATE_ASYNC) {
1941                 ret = -EINVAL;
1942                 goto out_drop_write;
1943         }
1944
1945         if (flags & ~BTRFS_SUBVOL_RDONLY) {
1946                 ret = -EOPNOTSUPP;
1947                 goto out_drop_write;
1948         }
1949
1950         down_write(&fs_info->subvol_sem);
1951
1952         /* nothing to do */
1953         if (!!(flags & BTRFS_SUBVOL_RDONLY) == btrfs_root_readonly(root))
1954                 goto out_drop_sem;
1955
1956         root_flags = btrfs_root_flags(&root->root_item);
1957         if (flags & BTRFS_SUBVOL_RDONLY) {
1958                 btrfs_set_root_flags(&root->root_item,
1959                                      root_flags | BTRFS_ROOT_SUBVOL_RDONLY);
1960         } else {
1961                 /*
1962                  * Block RO -> RW transition if this subvolume is involved in
1963                  * send
1964                  */
1965                 spin_lock(&root->root_item_lock);
1966                 if (root->send_in_progress == 0) {
1967                         btrfs_set_root_flags(&root->root_item,
1968                                      root_flags & ~BTRFS_ROOT_SUBVOL_RDONLY);
1969                         spin_unlock(&root->root_item_lock);
1970                 } else {
1971                         spin_unlock(&root->root_item_lock);
1972                         btrfs_warn(fs_info,
1973                                    "Attempt to set subvolume %llu read-write during send",
1974                                    root->root_key.objectid);
1975                         ret = -EPERM;
1976                         goto out_drop_sem;
1977                 }
1978         }
1979
1980         trans = btrfs_start_transaction(root, 1);
1981         if (IS_ERR(trans)) {
1982                 ret = PTR_ERR(trans);
1983                 goto out_reset;
1984         }
1985
1986         ret = btrfs_update_root(trans, fs_info->tree_root,
1987                                 &root->root_key, &root->root_item);
1988         if (ret < 0) {
1989                 btrfs_end_transaction(trans);
1990                 goto out_reset;
1991         }
1992
1993         ret = btrfs_commit_transaction(trans);
1994
1995 out_reset:
1996         if (ret)
1997                 btrfs_set_root_flags(&root->root_item, root_flags);
1998 out_drop_sem:
1999         up_write(&fs_info->subvol_sem);
2000 out_drop_write:
2001         mnt_drop_write_file(file);
2002 out:
2003         return ret;
2004 }
2005
2006 static noinline int key_in_sk(struct btrfs_key *key,
2007                               struct btrfs_ioctl_search_key *sk)
2008 {
2009         struct btrfs_key test;
2010         int ret;
2011
2012         test.objectid = sk->min_objectid;
2013         test.type = sk->min_type;
2014         test.offset = sk->min_offset;
2015
2016         ret = btrfs_comp_cpu_keys(key, &test);
2017         if (ret < 0)
2018                 return 0;
2019
2020         test.objectid = sk->max_objectid;
2021         test.type = sk->max_type;
2022         test.offset = sk->max_offset;
2023
2024         ret = btrfs_comp_cpu_keys(key, &test);
2025         if (ret > 0)
2026                 return 0;
2027         return 1;
2028 }
2029
2030 static noinline int copy_to_sk(struct btrfs_path *path,
2031                                struct btrfs_key *key,
2032                                struct btrfs_ioctl_search_key *sk,
2033                                size_t *buf_size,
2034                                char __user *ubuf,
2035                                unsigned long *sk_offset,
2036                                int *num_found)
2037 {
2038         u64 found_transid;
2039         struct extent_buffer *leaf;
2040         struct btrfs_ioctl_search_header sh;
2041         struct btrfs_key test;
2042         unsigned long item_off;
2043         unsigned long item_len;
2044         int nritems;
2045         int i;
2046         int slot;
2047         int ret = 0;
2048
2049         leaf = path->nodes[0];
2050         slot = path->slots[0];
2051         nritems = btrfs_header_nritems(leaf);
2052
2053         if (btrfs_header_generation(leaf) > sk->max_transid) {
2054                 i = nritems;
2055                 goto advance_key;
2056         }
2057         found_transid = btrfs_header_generation(leaf);
2058
2059         for (i = slot; i < nritems; i++) {
2060                 item_off = btrfs_item_ptr_offset(leaf, i);
2061                 item_len = btrfs_item_size_nr(leaf, i);
2062
2063                 btrfs_item_key_to_cpu(leaf, key, i);
2064                 if (!key_in_sk(key, sk))
2065                         continue;
2066
2067                 if (sizeof(sh) + item_len > *buf_size) {
2068                         if (*num_found) {
2069                                 ret = 1;
2070                                 goto out;
2071                         }
2072
2073                         /*
2074                          * return one empty item back for v1, which does not
2075                          * handle -EOVERFLOW
2076                          */
2077
2078                         *buf_size = sizeof(sh) + item_len;
2079                         item_len = 0;
2080                         ret = -EOVERFLOW;
2081                 }
2082
2083                 if (sizeof(sh) + item_len + *sk_offset > *buf_size) {
2084                         ret = 1;
2085                         goto out;
2086                 }
2087
2088                 sh.objectid = key->objectid;
2089                 sh.offset = key->offset;
2090                 sh.type = key->type;
2091                 sh.len = item_len;
2092                 sh.transid = found_transid;
2093
2094                 /* copy search result header */
2095                 if (copy_to_user(ubuf + *sk_offset, &sh, sizeof(sh))) {
2096                         ret = -EFAULT;
2097                         goto out;
2098                 }
2099
2100                 *sk_offset += sizeof(sh);
2101
2102                 if (item_len) {
2103                         char __user *up = ubuf + *sk_offset;
2104                         /* copy the item */
2105                         if (read_extent_buffer_to_user(leaf, up,
2106                                                        item_off, item_len)) {
2107                                 ret = -EFAULT;
2108                                 goto out;
2109                         }
2110
2111                         *sk_offset += item_len;
2112                 }
2113                 (*num_found)++;
2114
2115                 if (ret) /* -EOVERFLOW from above */
2116                         goto out;
2117
2118                 if (*num_found >= sk->nr_items) {
2119                         ret = 1;
2120                         goto out;
2121                 }
2122         }
2123 advance_key:
2124         ret = 0;
2125         test.objectid = sk->max_objectid;
2126         test.type = sk->max_type;
2127         test.offset = sk->max_offset;
2128         if (btrfs_comp_cpu_keys(key, &test) >= 0)
2129                 ret = 1;
2130         else if (key->offset < (u64)-1)
2131                 key->offset++;
2132         else if (key->type < (u8)-1) {
2133                 key->offset = 0;
2134                 key->type++;
2135         } else if (key->objectid < (u64)-1) {
2136                 key->offset = 0;
2137                 key->type = 0;
2138                 key->objectid++;
2139         } else
2140                 ret = 1;
2141 out:
2142         /*
2143          *  0: all items from this leaf copied, continue with next
2144          *  1: * more items can be copied, but unused buffer is too small
2145          *     * all items were found
2146          *     Either way, it will stops the loop which iterates to the next
2147          *     leaf
2148          *  -EOVERFLOW: item was to large for buffer
2149          *  -EFAULT: could not copy extent buffer back to userspace
2150          */
2151         return ret;
2152 }
2153
2154 static noinline int search_ioctl(struct inode *inode,
2155                                  struct btrfs_ioctl_search_key *sk,
2156                                  size_t *buf_size,
2157                                  char __user *ubuf)
2158 {
2159         struct btrfs_fs_info *info = btrfs_sb(inode->i_sb);
2160         struct btrfs_root *root;
2161         struct btrfs_key key;
2162         struct btrfs_path *path;
2163         int ret;
2164         int num_found = 0;
2165         unsigned long sk_offset = 0;
2166
2167         if (*buf_size < sizeof(struct btrfs_ioctl_search_header)) {
2168                 *buf_size = sizeof(struct btrfs_ioctl_search_header);
2169                 return -EOVERFLOW;
2170         }
2171
2172         path = btrfs_alloc_path();
2173         if (!path)
2174                 return -ENOMEM;
2175
2176         if (sk->tree_id == 0) {
2177                 /* search the root of the inode that was passed */
2178                 root = BTRFS_I(inode)->root;
2179         } else {
2180                 key.objectid = sk->tree_id;
2181                 key.type = BTRFS_ROOT_ITEM_KEY;
2182                 key.offset = (u64)-1;
2183                 root = btrfs_read_fs_root_no_name(info, &key);
2184                 if (IS_ERR(root)) {
2185                         btrfs_free_path(path);
2186                         return PTR_ERR(root);
2187                 }
2188         }
2189
2190         key.objectid = sk->min_objectid;
2191         key.type = sk->min_type;
2192         key.offset = sk->min_offset;
2193
2194         while (1) {
2195                 ret = btrfs_search_forward(root, &key, path, sk->min_transid);
2196                 if (ret != 0) {
2197                         if (ret > 0)
2198                                 ret = 0;
2199                         goto err;
2200                 }
2201                 ret = copy_to_sk(path, &key, sk, buf_size, ubuf,
2202                                  &sk_offset, &num_found);
2203                 btrfs_release_path(path);
2204                 if (ret)
2205                         break;
2206
2207         }
2208         if (ret > 0)
2209                 ret = 0;
2210 err:
2211         sk->nr_items = num_found;
2212         btrfs_free_path(path);
2213         return ret;
2214 }
2215
2216 static noinline int btrfs_ioctl_tree_search(struct file *file,
2217                                            void __user *argp)
2218 {
2219         struct btrfs_ioctl_search_args __user *uargs;
2220         struct btrfs_ioctl_search_key sk;
2221         struct inode *inode;
2222         int ret;
2223         size_t buf_size;
2224
2225         if (!capable(CAP_SYS_ADMIN))
2226                 return -EPERM;
2227
2228         uargs = (struct btrfs_ioctl_search_args __user *)argp;
2229
2230         if (copy_from_user(&sk, &uargs->key, sizeof(sk)))
2231                 return -EFAULT;
2232
2233         buf_size = sizeof(uargs->buf);
2234
2235         inode = file_inode(file);
2236         ret = search_ioctl(inode, &sk, &buf_size, uargs->buf);
2237
2238         /*
2239          * In the origin implementation an overflow is handled by returning a
2240          * search header with a len of zero, so reset ret.
2241          */
2242         if (ret == -EOVERFLOW)
2243                 ret = 0;
2244
2245         if (ret == 0 && copy_to_user(&uargs->key, &sk, sizeof(sk)))
2246                 ret = -EFAULT;
2247         return ret;
2248 }
2249
2250 static noinline int btrfs_ioctl_tree_search_v2(struct file *file,
2251                                                void __user *argp)
2252 {
2253         struct btrfs_ioctl_search_args_v2 __user *uarg;
2254         struct btrfs_ioctl_search_args_v2 args;
2255         struct inode *inode;
2256         int ret;
2257         size_t buf_size;
2258         const size_t buf_limit = SZ_16M;
2259
2260         if (!capable(CAP_SYS_ADMIN))
2261                 return -EPERM;
2262
2263         /* copy search header and buffer size */
2264         uarg = (struct btrfs_ioctl_search_args_v2 __user *)argp;
2265         if (copy_from_user(&args, uarg, sizeof(args)))
2266                 return -EFAULT;
2267
2268         buf_size = args.buf_size;
2269
2270         /* limit result size to 16MB */
2271         if (buf_size > buf_limit)
2272                 buf_size = buf_limit;
2273
2274         inode = file_inode(file);
2275         ret = search_ioctl(inode, &args.key, &buf_size,
2276                            (char __user *)(&uarg->buf[0]));
2277         if (ret == 0 && copy_to_user(&uarg->key, &args.key, sizeof(args.key)))
2278                 ret = -EFAULT;
2279         else if (ret == -EOVERFLOW &&
2280                 copy_to_user(&uarg->buf_size, &buf_size, sizeof(buf_size)))
2281                 ret = -EFAULT;
2282
2283         return ret;
2284 }
2285
2286 /*
2287  * Search INODE_REFs to identify path name of 'dirid' directory
2288  * in a 'tree_id' tree. and sets path name to 'name'.
2289  */
2290 static noinline int btrfs_search_path_in_tree(struct btrfs_fs_info *info,
2291                                 u64 tree_id, u64 dirid, char *name)
2292 {
2293         struct btrfs_root *root;
2294         struct btrfs_key key;
2295         char *ptr;
2296         int ret = -1;
2297         int slot;
2298         int len;
2299         int total_len = 0;
2300         struct btrfs_inode_ref *iref;
2301         struct extent_buffer *l;
2302         struct btrfs_path *path;
2303
2304         if (dirid == BTRFS_FIRST_FREE_OBJECTID) {
2305                 name[0]='\0';
2306                 return 0;
2307         }
2308
2309         path = btrfs_alloc_path();
2310         if (!path)
2311                 return -ENOMEM;
2312
2313         ptr = &name[BTRFS_INO_LOOKUP_PATH_MAX - 1];
2314
2315         key.objectid = tree_id;
2316         key.type = BTRFS_ROOT_ITEM_KEY;
2317         key.offset = (u64)-1;
2318         root = btrfs_read_fs_root_no_name(info, &key);
2319         if (IS_ERR(root)) {
2320                 ret = PTR_ERR(root);
2321                 goto out;
2322         }
2323
2324         key.objectid = dirid;
2325         key.type = BTRFS_INODE_REF_KEY;
2326         key.offset = (u64)-1;
2327
2328         while (1) {
2329                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2330                 if (ret < 0)
2331                         goto out;
2332                 else if (ret > 0) {
2333                         ret = btrfs_previous_item(root, path, dirid,
2334                                                   BTRFS_INODE_REF_KEY);
2335                         if (ret < 0)
2336                                 goto out;
2337                         else if (ret > 0) {
2338                                 ret = -ENOENT;
2339                                 goto out;
2340                         }
2341                 }
2342
2343                 l = path->nodes[0];
2344                 slot = path->slots[0];
2345                 btrfs_item_key_to_cpu(l, &key, slot);
2346
2347                 iref = btrfs_item_ptr(l, slot, struct btrfs_inode_ref);
2348                 len = btrfs_inode_ref_name_len(l, iref);
2349                 ptr -= len + 1;
2350                 total_len += len + 1;
2351                 if (ptr < name) {
2352                         ret = -ENAMETOOLONG;
2353                         goto out;
2354                 }
2355
2356                 *(ptr + len) = '/';
2357                 read_extent_buffer(l, ptr, (unsigned long)(iref + 1), len);
2358
2359                 if (key.offset == BTRFS_FIRST_FREE_OBJECTID)
2360                         break;
2361
2362                 btrfs_release_path(path);
2363                 key.objectid = key.offset;
2364                 key.offset = (u64)-1;
2365                 dirid = key.objectid;
2366         }
2367         memmove(name, ptr, total_len);
2368         name[total_len] = '\0';
2369         ret = 0;
2370 out:
2371         btrfs_free_path(path);
2372         return ret;
2373 }
2374
2375 static int btrfs_search_path_in_tree_user(struct inode *inode,
2376                                 struct btrfs_ioctl_ino_lookup_user_args *args)
2377 {
2378         struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
2379         struct super_block *sb = inode->i_sb;
2380         struct btrfs_key upper_limit = BTRFS_I(inode)->location;
2381         u64 treeid = BTRFS_I(inode)->root->root_key.objectid;
2382         u64 dirid = args->dirid;
2383         unsigned long item_off;
2384         unsigned long item_len;
2385         struct btrfs_inode_ref *iref;
2386         struct btrfs_root_ref *rref;
2387         struct btrfs_root *root;
2388         struct btrfs_path *path;
2389         struct btrfs_key key, key2;
2390         struct extent_buffer *leaf;
2391         struct inode *temp_inode;
2392         char *ptr;
2393         int slot;
2394         int len;
2395         int total_len = 0;
2396         int ret;
2397
2398         path = btrfs_alloc_path();
2399         if (!path)
2400                 return -ENOMEM;
2401
2402         /*
2403          * If the bottom subvolume does not exist directly under upper_limit,
2404          * construct the path in from the bottom up.
2405          */
2406         if (dirid != upper_limit.objectid) {
2407                 ptr = &args->path[BTRFS_INO_LOOKUP_USER_PATH_MAX - 1];
2408
2409                 key.objectid = treeid;
2410                 key.type = BTRFS_ROOT_ITEM_KEY;
2411                 key.offset = (u64)-1;
2412                 root = btrfs_read_fs_root_no_name(fs_info, &key);
2413                 if (IS_ERR(root)) {
2414                         ret = PTR_ERR(root);
2415                         goto out;
2416                 }
2417
2418                 key.objectid = dirid;
2419                 key.type = BTRFS_INODE_REF_KEY;
2420                 key.offset = (u64)-1;
2421                 while (1) {
2422                         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2423                         if (ret < 0) {
2424                                 goto out;
2425                         } else if (ret > 0) {
2426                                 ret = btrfs_previous_item(root, path, dirid,
2427                                                           BTRFS_INODE_REF_KEY);
2428                                 if (ret < 0) {
2429                                         goto out;
2430                                 } else if (ret > 0) {
2431                                         ret = -ENOENT;
2432                                         goto out;
2433                                 }
2434                         }
2435
2436                         leaf = path->nodes[0];
2437                         slot = path->slots[0];
2438                         btrfs_item_key_to_cpu(leaf, &key, slot);
2439
2440                         iref = btrfs_item_ptr(leaf, slot, struct btrfs_inode_ref);
2441                         len = btrfs_inode_ref_name_len(leaf, iref);
2442                         ptr -= len + 1;
2443                         total_len += len + 1;
2444                         if (ptr < args->path) {
2445                                 ret = -ENAMETOOLONG;
2446                                 goto out;
2447                         }
2448
2449                         *(ptr + len) = '/';
2450                         read_extent_buffer(leaf, ptr,
2451                                         (unsigned long)(iref + 1), len);
2452
2453                         /* Check the read+exec permission of this directory */
2454                         ret = btrfs_previous_item(root, path, dirid,
2455                                                   BTRFS_INODE_ITEM_KEY);
2456                         if (ret < 0) {
2457                                 goto out;
2458                         } else if (ret > 0) {
2459                                 ret = -ENOENT;
2460                                 goto out;
2461                         }
2462
2463                         leaf = path->nodes[0];
2464                         slot = path->slots[0];
2465                         btrfs_item_key_to_cpu(leaf, &key2, slot);
2466                         if (key2.objectid != dirid) {
2467                                 ret = -ENOENT;
2468                                 goto out;
2469                         }
2470
2471                         temp_inode = btrfs_iget(sb, &key2, root, NULL);
2472                         if (IS_ERR(temp_inode)) {
2473                                 ret = PTR_ERR(temp_inode);
2474                                 goto out;
2475                         }
2476                         ret = inode_permission(temp_inode, MAY_READ | MAY_EXEC);
2477                         iput(temp_inode);
2478                         if (ret) {
2479                                 ret = -EACCES;
2480                                 goto out;
2481                         }
2482
2483                         if (key.offset == upper_limit.objectid)
2484                                 break;
2485                         if (key.objectid == BTRFS_FIRST_FREE_OBJECTID) {
2486                                 ret = -EACCES;
2487                                 goto out;
2488                         }
2489
2490                         btrfs_release_path(path);
2491                         key.objectid = key.offset;
2492                         key.offset = (u64)-1;
2493                         dirid = key.objectid;
2494                 }
2495
2496                 memmove(args->path, ptr, total_len);
2497                 args->path[total_len] = '\0';
2498                 btrfs_release_path(path);
2499         }
2500
2501         /* Get the bottom subvolume's name from ROOT_REF */
2502         root = fs_info->tree_root;
2503         key.objectid = treeid;
2504         key.type = BTRFS_ROOT_REF_KEY;
2505         key.offset = args->treeid;
2506         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2507         if (ret < 0) {
2508                 goto out;
2509         } else if (ret > 0) {
2510                 ret = -ENOENT;
2511                 goto out;
2512         }
2513
2514         leaf = path->nodes[0];
2515         slot = path->slots[0];
2516         btrfs_item_key_to_cpu(leaf, &key, slot);
2517
2518         item_off = btrfs_item_ptr_offset(leaf, slot);
2519         item_len = btrfs_item_size_nr(leaf, slot);
2520         /* Check if dirid in ROOT_REF corresponds to passed dirid */
2521         rref = btrfs_item_ptr(leaf, slot, struct btrfs_root_ref);
2522         if (args->dirid != btrfs_root_ref_dirid(leaf, rref)) {
2523                 ret = -EINVAL;
2524                 goto out;
2525         }
2526
2527         /* Copy subvolume's name */
2528         item_off += sizeof(struct btrfs_root_ref);
2529         item_len -= sizeof(struct btrfs_root_ref);
2530         read_extent_buffer(leaf, args->name, item_off, item_len);
2531         args->name[item_len] = 0;
2532
2533 out:
2534         btrfs_free_path(path);
2535         return ret;
2536 }
2537
2538 static noinline int btrfs_ioctl_ino_lookup(struct file *file,
2539                                            void __user *argp)
2540 {
2541         struct btrfs_ioctl_ino_lookup_args *args;
2542         struct inode *inode;
2543         int ret = 0;
2544
2545         args = memdup_user(argp, sizeof(*args));
2546         if (IS_ERR(args))
2547                 return PTR_ERR(args);
2548
2549         inode = file_inode(file);
2550
2551         /*
2552          * Unprivileged query to obtain the containing subvolume root id. The
2553          * path is reset so it's consistent with btrfs_search_path_in_tree.
2554          */
2555         if (args->treeid == 0)
2556                 args->treeid = BTRFS_I(inode)->root->root_key.objectid;
2557
2558         if (args->objectid == BTRFS_FIRST_FREE_OBJECTID) {
2559                 args->name[0] = 0;
2560                 goto out;
2561         }
2562
2563         if (!capable(CAP_SYS_ADMIN)) {
2564                 ret = -EPERM;
2565                 goto out;
2566         }
2567
2568         ret = btrfs_search_path_in_tree(BTRFS_I(inode)->root->fs_info,
2569                                         args->treeid, args->objectid,
2570                                         args->name);
2571
2572 out:
2573         if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
2574                 ret = -EFAULT;
2575
2576         kfree(args);
2577         return ret;
2578 }
2579
2580 /*
2581  * Version of ino_lookup ioctl (unprivileged)
2582  *
2583  * The main differences from ino_lookup ioctl are:
2584  *
2585  *   1. Read + Exec permission will be checked using inode_permission() during
2586  *      path construction. -EACCES will be returned in case of failure.
2587  *   2. Path construction will be stopped at the inode number which corresponds
2588  *      to the fd with which this ioctl is called. If constructed path does not
2589  *      exist under fd's inode, -EACCES will be returned.
2590  *   3. The name of bottom subvolume is also searched and filled.
2591  */
2592 static int btrfs_ioctl_ino_lookup_user(struct file *file, void __user *argp)
2593 {
2594         struct btrfs_ioctl_ino_lookup_user_args *args;
2595         struct inode *inode;
2596         int ret;
2597
2598         args = memdup_user(argp, sizeof(*args));
2599         if (IS_ERR(args))
2600                 return PTR_ERR(args);
2601
2602         inode = file_inode(file);
2603
2604         if (args->dirid == BTRFS_FIRST_FREE_OBJECTID &&
2605             BTRFS_I(inode)->location.objectid != BTRFS_FIRST_FREE_OBJECTID) {
2606                 /*
2607                  * The subvolume does not exist under fd with which this is
2608                  * called
2609                  */
2610                 kfree(args);
2611                 return -EACCES;
2612         }
2613
2614         ret = btrfs_search_path_in_tree_user(inode, args);
2615
2616         if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
2617                 ret = -EFAULT;
2618
2619         kfree(args);
2620         return ret;
2621 }
2622
2623 /* Get the subvolume information in BTRFS_ROOT_ITEM and BTRFS_ROOT_BACKREF */
2624 static int btrfs_ioctl_get_subvol_info(struct file *file, void __user *argp)
2625 {
2626         struct btrfs_ioctl_get_subvol_info_args *subvol_info;
2627         struct btrfs_fs_info *fs_info;
2628         struct btrfs_root *root;
2629         struct btrfs_path *path;
2630         struct btrfs_key key;
2631         struct btrfs_root_item *root_item;
2632         struct btrfs_root_ref *rref;
2633         struct extent_buffer *leaf;
2634         unsigned long item_off;
2635         unsigned long item_len;
2636         struct inode *inode;
2637         int slot;
2638         int ret = 0;
2639
2640         path = btrfs_alloc_path();
2641         if (!path)
2642                 return -ENOMEM;
2643
2644         subvol_info = kzalloc(sizeof(*subvol_info), GFP_KERNEL);
2645         if (!subvol_info) {
2646                 btrfs_free_path(path);
2647                 return -ENOMEM;
2648         }
2649
2650         inode = file_inode(file);
2651         fs_info = BTRFS_I(inode)->root->fs_info;
2652
2653         /* Get root_item of inode's subvolume */
2654         key.objectid = BTRFS_I(inode)->root->root_key.objectid;
2655         key.type = BTRFS_ROOT_ITEM_KEY;
2656         key.offset = (u64)-1;
2657         root = btrfs_read_fs_root_no_name(fs_info, &key);
2658         if (IS_ERR(root)) {
2659                 ret = PTR_ERR(root);
2660                 goto out;
2661         }
2662         root_item = &root->root_item;
2663
2664         subvol_info->treeid = key.objectid;
2665
2666         subvol_info->generation = btrfs_root_generation(root_item);
2667         subvol_info->flags = btrfs_root_flags(root_item);
2668
2669         memcpy(subvol_info->uuid, root_item->uuid, BTRFS_UUID_SIZE);
2670         memcpy(subvol_info->parent_uuid, root_item->parent_uuid,
2671                                                     BTRFS_UUID_SIZE);
2672         memcpy(subvol_info->received_uuid, root_item->received_uuid,
2673                                                     BTRFS_UUID_SIZE);
2674
2675         subvol_info->ctransid = btrfs_root_ctransid(root_item);
2676         subvol_info->ctime.sec = btrfs_stack_timespec_sec(&root_item->ctime);
2677         subvol_info->ctime.nsec = btrfs_stack_timespec_nsec(&root_item->ctime);
2678
2679         subvol_info->otransid = btrfs_root_otransid(root_item);
2680         subvol_info->otime.sec = btrfs_stack_timespec_sec(&root_item->otime);
2681         subvol_info->otime.nsec = btrfs_stack_timespec_nsec(&root_item->otime);
2682
2683         subvol_info->stransid = btrfs_root_stransid(root_item);
2684         subvol_info->stime.sec = btrfs_stack_timespec_sec(&root_item->stime);
2685         subvol_info->stime.nsec = btrfs_stack_timespec_nsec(&root_item->stime);
2686
2687         subvol_info->rtransid = btrfs_root_rtransid(root_item);
2688         subvol_info->rtime.sec = btrfs_stack_timespec_sec(&root_item->rtime);
2689         subvol_info->rtime.nsec = btrfs_stack_timespec_nsec(&root_item->rtime);
2690
2691         if (key.objectid != BTRFS_FS_TREE_OBJECTID) {
2692                 /* Search root tree for ROOT_BACKREF of this subvolume */
2693                 root = fs_info->tree_root;
2694
2695                 key.type = BTRFS_ROOT_BACKREF_KEY;
2696                 key.offset = 0;
2697                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2698                 if (ret < 0) {
2699                         goto out;
2700                 } else if (path->slots[0] >=
2701                            btrfs_header_nritems(path->nodes[0])) {
2702                         ret = btrfs_next_leaf(root, path);
2703                         if (ret < 0) {
2704                                 goto out;
2705                         } else if (ret > 0) {
2706                                 ret = -EUCLEAN;
2707                                 goto out;
2708                         }
2709                 }
2710
2711                 leaf = path->nodes[0];
2712                 slot = path->slots[0];
2713                 btrfs_item_key_to_cpu(leaf, &key, slot);
2714                 if (key.objectid == subvol_info->treeid &&
2715                     key.type == BTRFS_ROOT_BACKREF_KEY) {
2716                         subvol_info->parent_id = key.offset;
2717
2718                         rref = btrfs_item_ptr(leaf, slot, struct btrfs_root_ref);
2719                         subvol_info->dirid = btrfs_root_ref_dirid(leaf, rref);
2720
2721                         item_off = btrfs_item_ptr_offset(leaf, slot)
2722                                         + sizeof(struct btrfs_root_ref);
2723                         item_len = btrfs_item_size_nr(leaf, slot)
2724                                         - sizeof(struct btrfs_root_ref);
2725                         read_extent_buffer(leaf, subvol_info->name,
2726                                            item_off, item_len);
2727                 } else {
2728                         ret = -ENOENT;
2729                         goto out;
2730                 }
2731         }
2732
2733         if (copy_to_user(argp, subvol_info, sizeof(*subvol_info)))
2734                 ret = -EFAULT;
2735
2736 out:
2737         btrfs_free_path(path);
2738         kzfree(subvol_info);
2739         return ret;
2740 }
2741
2742 /*
2743  * Return ROOT_REF information of the subvolume containing this inode
2744  * except the subvolume name.
2745  */
2746 static int btrfs_ioctl_get_subvol_rootref(struct file *file, void __user *argp)
2747 {
2748         struct btrfs_ioctl_get_subvol_rootref_args *rootrefs;
2749         struct btrfs_root_ref *rref;
2750         struct btrfs_root *root;
2751         struct btrfs_path *path;
2752         struct btrfs_key key;
2753         struct extent_buffer *leaf;
2754         struct inode *inode;
2755         u64 objectid;
2756         int slot;
2757         int ret;
2758         u8 found;
2759
2760         path = btrfs_alloc_path();
2761         if (!path)
2762                 return -ENOMEM;
2763
2764         rootrefs = memdup_user(argp, sizeof(*rootrefs));
2765         if (IS_ERR(rootrefs)) {
2766                 btrfs_free_path(path);
2767                 return PTR_ERR(rootrefs);
2768         }
2769
2770         inode = file_inode(file);
2771         root = BTRFS_I(inode)->root->fs_info->tree_root;
2772         objectid = BTRFS_I(inode)->root->root_key.objectid;
2773
2774         key.objectid = objectid;
2775         key.type = BTRFS_ROOT_REF_KEY;
2776         key.offset = rootrefs->min_treeid;
2777         found = 0;
2778
2779         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2780         if (ret < 0) {
2781                 goto out;
2782         } else if (path->slots[0] >=
2783                    btrfs_header_nritems(path->nodes[0])) {
2784                 ret = btrfs_next_leaf(root, path);
2785                 if (ret < 0) {
2786                         goto out;
2787                 } else if (ret > 0) {
2788                         ret = -EUCLEAN;
2789                         goto out;
2790                 }
2791         }
2792         while (1) {
2793                 leaf = path->nodes[0];
2794                 slot = path->slots[0];
2795
2796                 btrfs_item_key_to_cpu(leaf, &key, slot);
2797                 if (key.objectid != objectid || key.type != BTRFS_ROOT_REF_KEY) {
2798                         ret = 0;
2799                         goto out;
2800                 }
2801
2802                 if (found == BTRFS_MAX_ROOTREF_BUFFER_NUM) {
2803                         ret = -EOVERFLOW;
2804                         goto out;
2805                 }
2806
2807                 rref = btrfs_item_ptr(leaf, slot, struct btrfs_root_ref);
2808                 rootrefs->rootref[found].treeid = key.offset;
2809                 rootrefs->rootref[found].dirid =
2810                                   btrfs_root_ref_dirid(leaf, rref);
2811                 found++;
2812
2813                 ret = btrfs_next_item(root, path);
2814                 if (ret < 0) {
2815                         goto out;
2816                 } else if (ret > 0) {
2817                         ret = -EUCLEAN;
2818                         goto out;
2819                 }
2820         }
2821
2822 out:
2823         if (!ret || ret == -EOVERFLOW) {
2824                 rootrefs->num_items = found;
2825                 /* update min_treeid for next search */
2826                 if (found)
2827                         rootrefs->min_treeid =
2828                                 rootrefs->rootref[found - 1].treeid + 1;
2829                 if (copy_to_user(argp, rootrefs, sizeof(*rootrefs)))
2830                         ret = -EFAULT;
2831         }
2832
2833         kfree(rootrefs);
2834         btrfs_free_path(path);
2835
2836         return ret;
2837 }
2838
2839 static noinline int btrfs_ioctl_snap_destroy(struct file *file,
2840                                              void __user *arg)
2841 {
2842         struct dentry *parent = file->f_path.dentry;
2843         struct btrfs_fs_info *fs_info = btrfs_sb(parent->d_sb);
2844         struct dentry *dentry;
2845         struct inode *dir = d_inode(parent);
2846         struct inode *inode;
2847         struct btrfs_root *root = BTRFS_I(dir)->root;
2848         struct btrfs_root *dest = NULL;
2849         struct btrfs_ioctl_vol_args *vol_args;
2850         int namelen;
2851         int err = 0;
2852
2853         if (!S_ISDIR(dir->i_mode))
2854                 return -ENOTDIR;
2855
2856         vol_args = memdup_user(arg, sizeof(*vol_args));
2857         if (IS_ERR(vol_args))
2858                 return PTR_ERR(vol_args);
2859
2860         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
2861         namelen = strlen(vol_args->name);
2862         if (strchr(vol_args->name, '/') ||
2863             strncmp(vol_args->name, "..", namelen) == 0) {
2864                 err = -EINVAL;
2865                 goto out;
2866         }
2867
2868         err = mnt_want_write_file(file);
2869         if (err)
2870                 goto out;
2871
2872
2873         err = down_write_killable_nested(&dir->i_rwsem, I_MUTEX_PARENT);
2874         if (err == -EINTR)
2875                 goto out_drop_write;
2876         dentry = lookup_one_len(vol_args->name, parent, namelen);
2877         if (IS_ERR(dentry)) {
2878                 err = PTR_ERR(dentry);
2879                 goto out_unlock_dir;
2880         }
2881
2882         if (d_really_is_negative(dentry)) {
2883                 err = -ENOENT;
2884                 goto out_dput;
2885         }
2886
2887         inode = d_inode(dentry);
2888         dest = BTRFS_I(inode)->root;
2889         if (!capable(CAP_SYS_ADMIN)) {
2890                 /*
2891                  * Regular user.  Only allow this with a special mount
2892                  * option, when the user has write+exec access to the
2893                  * subvol root, and when rmdir(2) would have been
2894                  * allowed.
2895                  *
2896                  * Note that this is _not_ check that the subvol is
2897                  * empty or doesn't contain data that we wouldn't
2898                  * otherwise be able to delete.
2899                  *
2900                  * Users who want to delete empty subvols should try
2901                  * rmdir(2).
2902                  */
2903                 err = -EPERM;
2904                 if (!btrfs_test_opt(fs_info, USER_SUBVOL_RM_ALLOWED))
2905                         goto out_dput;
2906
2907                 /*
2908                  * Do not allow deletion if the parent dir is the same
2909                  * as the dir to be deleted.  That means the ioctl
2910                  * must be called on the dentry referencing the root
2911                  * of the subvol, not a random directory contained
2912                  * within it.
2913                  */
2914                 err = -EINVAL;
2915                 if (root == dest)
2916                         goto out_dput;
2917
2918                 err = inode_permission(inode, MAY_WRITE | MAY_EXEC);
2919                 if (err)
2920                         goto out_dput;
2921         }
2922
2923         /* check if subvolume may be deleted by a user */
2924         err = btrfs_may_delete(dir, dentry, 1);
2925         if (err)
2926                 goto out_dput;
2927
2928         if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
2929                 err = -EINVAL;
2930                 goto out_dput;
2931         }
2932
2933         inode_lock(inode);
2934         err = btrfs_delete_subvolume(dir, dentry);
2935         inode_unlock(inode);
2936         if (!err)
2937                 d_delete(dentry);
2938
2939 out_dput:
2940         dput(dentry);
2941 out_unlock_dir:
2942         inode_unlock(dir);
2943 out_drop_write:
2944         mnt_drop_write_file(file);
2945 out:
2946         kfree(vol_args);
2947         return err;
2948 }
2949
2950 static int btrfs_ioctl_defrag(struct file *file, void __user *argp)
2951 {
2952         struct inode *inode = file_inode(file);
2953         struct btrfs_root *root = BTRFS_I(inode)->root;
2954         struct btrfs_ioctl_defrag_range_args *range;
2955         int ret;
2956
2957         ret = mnt_want_write_file(file);
2958         if (ret)
2959                 return ret;
2960
2961         if (btrfs_root_readonly(root)) {
2962                 ret = -EROFS;
2963                 goto out;
2964         }
2965
2966         switch (inode->i_mode & S_IFMT) {
2967         case S_IFDIR:
2968                 if (!capable(CAP_SYS_ADMIN)) {
2969                         ret = -EPERM;
2970                         goto out;
2971                 }
2972                 ret = btrfs_defrag_root(root);
2973                 break;
2974         case S_IFREG:
2975                 /*
2976                  * Note that this does not check the file descriptor for write
2977                  * access. This prevents defragmenting executables that are
2978                  * running and allows defrag on files open in read-only mode.
2979                  */
2980                 if (!capable(CAP_SYS_ADMIN) &&
2981                     inode_permission(inode, MAY_WRITE)) {
2982                         ret = -EPERM;
2983                         goto out;
2984                 }
2985
2986                 range = kzalloc(sizeof(*range), GFP_KERNEL);
2987                 if (!range) {
2988                         ret = -ENOMEM;
2989                         goto out;
2990                 }
2991
2992                 if (argp) {
2993                         if (copy_from_user(range, argp,
2994                                            sizeof(*range))) {
2995                                 ret = -EFAULT;
2996                                 kfree(range);
2997                                 goto out;
2998                         }
2999                         /* compression requires us to start the IO */
3000                         if ((range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)) {
3001                                 range->flags |= BTRFS_DEFRAG_RANGE_START_IO;
3002                                 range->extent_thresh = (u32)-1;
3003                         }
3004                 } else {
3005                         /* the rest are all set to zero by kzalloc */
3006                         range->len = (u64)-1;
3007                 }
3008                 ret = btrfs_defrag_file(file_inode(file), file,
3009                                         range, BTRFS_OLDEST_GENERATION, 0);
3010                 if (ret > 0)
3011                         ret = 0;
3012                 kfree(range);
3013                 break;
3014         default:
3015                 ret = -EINVAL;
3016         }
3017 out:
3018         mnt_drop_write_file(file);
3019         return ret;
3020 }
3021
3022 static long btrfs_ioctl_add_dev(struct btrfs_fs_info *fs_info, void __user *arg)
3023 {
3024         struct btrfs_ioctl_vol_args *vol_args;
3025         int ret;
3026
3027         if (!capable(CAP_SYS_ADMIN))
3028                 return -EPERM;
3029
3030         if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags))
3031                 return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
3032
3033         vol_args = memdup_user(arg, sizeof(*vol_args));
3034         if (IS_ERR(vol_args)) {
3035                 ret = PTR_ERR(vol_args);
3036                 goto out;
3037         }
3038
3039         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
3040         ret = btrfs_init_new_device(fs_info, vol_args->name);
3041
3042         if (!ret)
3043                 btrfs_info(fs_info, "disk added %s", vol_args->name);
3044
3045         kfree(vol_args);
3046 out:
3047         clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
3048         return ret;
3049 }
3050
3051 static long btrfs_ioctl_rm_dev_v2(struct file *file, void __user *arg)
3052 {
3053         struct inode *inode = file_inode(file);
3054         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3055         struct btrfs_ioctl_vol_args_v2 *vol_args;
3056         int ret;
3057
3058         if (!capable(CAP_SYS_ADMIN))
3059                 return -EPERM;
3060
3061         ret = mnt_want_write_file(file);
3062         if (ret)
3063                 return ret;
3064
3065         vol_args = memdup_user(arg, sizeof(*vol_args));
3066         if (IS_ERR(vol_args)) {
3067                 ret = PTR_ERR(vol_args);
3068                 goto err_drop;
3069         }
3070
3071         /* Check for compatibility reject unknown flags */
3072         if (vol_args->flags & ~BTRFS_VOL_ARG_V2_FLAGS_SUPPORTED) {
3073                 ret = -EOPNOTSUPP;
3074                 goto out;
3075         }
3076
3077         if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
3078                 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
3079                 goto out;
3080         }
3081
3082         if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID) {
3083                 ret = btrfs_rm_device(fs_info, NULL, vol_args->devid);
3084         } else {
3085                 vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
3086                 ret = btrfs_rm_device(fs_info, vol_args->name, 0);
3087         }
3088         clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
3089
3090         if (!ret) {
3091                 if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID)
3092                         btrfs_info(fs_info, "device deleted: id %llu",
3093                                         vol_args->devid);
3094                 else
3095                         btrfs_info(fs_info, "device deleted: %s",
3096                                         vol_args->name);
3097         }
3098 out:
3099         kfree(vol_args);
3100 err_drop:
3101         mnt_drop_write_file(file);
3102         return ret;
3103 }
3104
3105 static long btrfs_ioctl_rm_dev(struct file *file, void __user *arg)
3106 {
3107         struct inode *inode = file_inode(file);
3108         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3109         struct btrfs_ioctl_vol_args *vol_args;
3110         int ret;
3111
3112         if (!capable(CAP_SYS_ADMIN))
3113                 return -EPERM;
3114
3115         ret = mnt_want_write_file(file);
3116         if (ret)
3117                 return ret;
3118
3119         if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
3120                 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
3121                 goto out_drop_write;
3122         }
3123
3124         vol_args = memdup_user(arg, sizeof(*vol_args));
3125         if (IS_ERR(vol_args)) {
3126                 ret = PTR_ERR(vol_args);
3127                 goto out;
3128         }
3129
3130         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
3131         ret = btrfs_rm_device(fs_info, vol_args->name, 0);
3132
3133         if (!ret)
3134                 btrfs_info(fs_info, "disk deleted %s", vol_args->name);
3135         kfree(vol_args);
3136 out:
3137         clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
3138 out_drop_write:
3139         mnt_drop_write_file(file);
3140
3141         return ret;
3142 }
3143
3144 static long btrfs_ioctl_fs_info(struct btrfs_fs_info *fs_info,
3145                                 void __user *arg)
3146 {
3147         struct btrfs_ioctl_fs_info_args *fi_args;
3148         struct btrfs_device *device;
3149         struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
3150         int ret = 0;
3151
3152         fi_args = kzalloc(sizeof(*fi_args), GFP_KERNEL);
3153         if (!fi_args)
3154                 return -ENOMEM;
3155
3156         rcu_read_lock();
3157         fi_args->num_devices = fs_devices->num_devices;
3158
3159         list_for_each_entry_rcu(device, &fs_devices->devices, dev_list) {
3160                 if (device->devid > fi_args->max_id)
3161                         fi_args->max_id = device->devid;
3162         }
3163         rcu_read_unlock();
3164
3165         memcpy(&fi_args->fsid, fs_devices->fsid, sizeof(fi_args->fsid));
3166         fi_args->nodesize = fs_info->nodesize;
3167         fi_args->sectorsize = fs_info->sectorsize;
3168         fi_args->clone_alignment = fs_info->sectorsize;
3169
3170         if (copy_to_user(arg, fi_args, sizeof(*fi_args)))
3171                 ret = -EFAULT;
3172
3173         kfree(fi_args);
3174         return ret;
3175 }
3176
3177 static long btrfs_ioctl_dev_info(struct btrfs_fs_info *fs_info,
3178                                  void __user *arg)
3179 {
3180         struct btrfs_ioctl_dev_info_args *di_args;
3181         struct btrfs_device *dev;
3182         int ret = 0;
3183         char *s_uuid = NULL;
3184
3185         di_args = memdup_user(arg, sizeof(*di_args));
3186         if (IS_ERR(di_args))
3187                 return PTR_ERR(di_args);
3188
3189         if (!btrfs_is_empty_uuid(di_args->uuid))
3190                 s_uuid = di_args->uuid;
3191
3192         rcu_read_lock();
3193         dev = btrfs_find_device(fs_info->fs_devices, di_args->devid, s_uuid,
3194                                 NULL, true);
3195
3196         if (!dev) {
3197                 ret = -ENODEV;
3198                 goto out;
3199         }
3200
3201         di_args->devid = dev->devid;
3202         di_args->bytes_used = btrfs_device_get_bytes_used(dev);
3203         di_args->total_bytes = btrfs_device_get_total_bytes(dev);
3204         memcpy(di_args->uuid, dev->uuid, sizeof(di_args->uuid));
3205         if (dev->name) {
3206                 strncpy(di_args->path, rcu_str_deref(dev->name),
3207                                 sizeof(di_args->path) - 1);
3208                 di_args->path[sizeof(di_args->path) - 1] = 0;
3209         } else {
3210                 di_args->path[0] = '\0';
3211         }
3212
3213 out:
3214         rcu_read_unlock();
3215         if (ret == 0 && copy_to_user(arg, di_args, sizeof(*di_args)))
3216                 ret = -EFAULT;
3217
3218         kfree(di_args);
3219         return ret;
3220 }
3221
3222 static void btrfs_double_extent_unlock(struct inode *inode1, u64 loff1,
3223                                        struct inode *inode2, u64 loff2, u64 len)
3224 {
3225         unlock_extent(&BTRFS_I(inode1)->io_tree, loff1, loff1 + len - 1);
3226         unlock_extent(&BTRFS_I(inode2)->io_tree, loff2, loff2 + len - 1);
3227 }
3228
3229 static void btrfs_double_extent_lock(struct inode *inode1, u64 loff1,
3230                                      struct inode *inode2, u64 loff2, u64 len)
3231 {
3232         if (inode1 < inode2) {
3233                 swap(inode1, inode2);
3234                 swap(loff1, loff2);
3235         } else if (inode1 == inode2 && loff2 < loff1) {
3236                 swap(loff1, loff2);
3237         }
3238         lock_extent(&BTRFS_I(inode1)->io_tree, loff1, loff1 + len - 1);
3239         lock_extent(&BTRFS_I(inode2)->io_tree, loff2, loff2 + len - 1);
3240 }
3241
3242 static int btrfs_extent_same_range(struct inode *src, u64 loff, u64 len,
3243                                    struct inode *dst, u64 dst_loff)
3244 {
3245         int ret;
3246
3247         /*
3248          * Lock destination range to serialize with concurrent readpages() and
3249          * source range to serialize with relocation.
3250          */
3251         btrfs_double_extent_lock(src, loff, dst, dst_loff, len);
3252         ret = btrfs_clone(src, dst, loff, len, len, dst_loff, 1);
3253         btrfs_double_extent_unlock(src, loff, dst, dst_loff, len);
3254
3255         return ret;
3256 }
3257