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