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