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