OSDN Git Service

c0dc05467ce8c7988d9c43fbd8f7a8a0eabd1a1e
[sagit-ice-cold/kernel_xiaomi_msm8998.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/statfs.h>
37 #include <linux/compat.h>
38 #include <linux/bit_spinlock.h>
39 #include <linux/security.h>
40 #include <linux/xattr.h>
41 #include <linux/vmalloc.h>
42 #include <linux/slab.h>
43 #include <linux/blkdev.h>
44 #include <linux/uuid.h>
45 #include <linux/btrfs.h>
46 #include <linux/uaccess.h>
47 #include "ctree.h"
48 #include "disk-io.h"
49 #include "transaction.h"
50 #include "btrfs_inode.h"
51 #include "print-tree.h"
52 #include "volumes.h"
53 #include "locking.h"
54 #include "inode-map.h"
55 #include "backref.h"
56 #include "rcu-string.h"
57 #include "send.h"
58 #include "dev-replace.h"
59 #include "sysfs.h"
60
61 static int btrfs_clone(struct inode *src, struct inode *inode,
62                        u64 off, u64 olen, u64 olen_aligned, u64 destoff);
63
64 /* Mask out flags that are inappropriate for the given type of inode. */
65 static inline __u32 btrfs_mask_flags(umode_t mode, __u32 flags)
66 {
67         if (S_ISDIR(mode))
68                 return flags;
69         else if (S_ISREG(mode))
70                 return flags & ~FS_DIRSYNC_FL;
71         else
72                 return flags & (FS_NODUMP_FL | FS_NOATIME_FL);
73 }
74
75 /*
76  * Export inode flags to the format expected by the FS_IOC_GETFLAGS ioctl.
77  */
78 static unsigned int btrfs_flags_to_ioctl(unsigned int flags)
79 {
80         unsigned int iflags = 0;
81
82         if (flags & BTRFS_INODE_SYNC)
83                 iflags |= FS_SYNC_FL;
84         if (flags & BTRFS_INODE_IMMUTABLE)
85                 iflags |= FS_IMMUTABLE_FL;
86         if (flags & BTRFS_INODE_APPEND)
87                 iflags |= FS_APPEND_FL;
88         if (flags & BTRFS_INODE_NODUMP)
89                 iflags |= FS_NODUMP_FL;
90         if (flags & BTRFS_INODE_NOATIME)
91                 iflags |= FS_NOATIME_FL;
92         if (flags & BTRFS_INODE_DIRSYNC)
93                 iflags |= FS_DIRSYNC_FL;
94         if (flags & BTRFS_INODE_NODATACOW)
95                 iflags |= FS_NOCOW_FL;
96
97         if ((flags & BTRFS_INODE_COMPRESS) && !(flags & BTRFS_INODE_NOCOMPRESS))
98                 iflags |= FS_COMPR_FL;
99         else if (flags & BTRFS_INODE_NOCOMPRESS)
100                 iflags |= FS_NOCOMP_FL;
101
102         return iflags;
103 }
104
105 /*
106  * Update inode->i_flags based on the btrfs internal flags.
107  */
108 void btrfs_update_iflags(struct inode *inode)
109 {
110         struct btrfs_inode *ip = BTRFS_I(inode);
111
112         inode->i_flags &= ~(S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC);
113
114         if (ip->flags & BTRFS_INODE_SYNC)
115                 inode->i_flags |= S_SYNC;
116         if (ip->flags & BTRFS_INODE_IMMUTABLE)
117                 inode->i_flags |= S_IMMUTABLE;
118         if (ip->flags & BTRFS_INODE_APPEND)
119                 inode->i_flags |= S_APPEND;
120         if (ip->flags & BTRFS_INODE_NOATIME)
121                 inode->i_flags |= S_NOATIME;
122         if (ip->flags & BTRFS_INODE_DIRSYNC)
123                 inode->i_flags |= S_DIRSYNC;
124 }
125
126 /*
127  * Inherit flags from the parent inode.
128  *
129  * Currently only the compression flags and the cow flags are inherited.
130  */
131 void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
132 {
133         unsigned int flags;
134
135         if (!dir)
136                 return;
137
138         flags = BTRFS_I(dir)->flags;
139
140         if (flags & BTRFS_INODE_NOCOMPRESS) {
141                 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
142                 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
143         } else if (flags & BTRFS_INODE_COMPRESS) {
144                 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
145                 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
146         }
147
148         if (flags & BTRFS_INODE_NODATACOW) {
149                 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
150                 if (S_ISREG(inode->i_mode))
151                         BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
152         }
153
154         btrfs_update_iflags(inode);
155 }
156
157 static int btrfs_ioctl_getflags(struct file *file, void __user *arg)
158 {
159         struct btrfs_inode *ip = BTRFS_I(file_inode(file));
160         unsigned int flags = btrfs_flags_to_ioctl(ip->flags);
161
162         if (copy_to_user(arg, &flags, sizeof(flags)))
163                 return -EFAULT;
164         return 0;
165 }
166
167 static int check_flags(unsigned int flags)
168 {
169         if (flags & ~(FS_IMMUTABLE_FL | FS_APPEND_FL | \
170                       FS_NOATIME_FL | FS_NODUMP_FL | \
171                       FS_SYNC_FL | FS_DIRSYNC_FL | \
172                       FS_NOCOMP_FL | FS_COMPR_FL |
173                       FS_NOCOW_FL))
174                 return -EOPNOTSUPP;
175
176         if ((flags & FS_NOCOMP_FL) && (flags & FS_COMPR_FL))
177                 return -EINVAL;
178
179         return 0;
180 }
181
182 static int btrfs_ioctl_setflags(struct file *file, void __user *arg)
183 {
184         struct inode *inode = file_inode(file);
185         struct btrfs_inode *ip = BTRFS_I(inode);
186         struct btrfs_root *root = ip->root;
187         struct btrfs_trans_handle *trans;
188         unsigned int flags, oldflags;
189         int ret;
190         u64 ip_oldflags;
191         unsigned int i_oldflags;
192         umode_t mode;
193
194         if (btrfs_root_readonly(root))
195                 return -EROFS;
196
197         if (copy_from_user(&flags, arg, sizeof(flags)))
198                 return -EFAULT;
199
200         ret = check_flags(flags);
201         if (ret)
202                 return ret;
203
204         if (!inode_owner_or_capable(inode))
205                 return -EACCES;
206
207         ret = mnt_want_write_file(file);
208         if (ret)
209                 return ret;
210
211         mutex_lock(&inode->i_mutex);
212
213         ip_oldflags = ip->flags;
214         i_oldflags = inode->i_flags;
215         mode = inode->i_mode;
216
217         flags = btrfs_mask_flags(inode->i_mode, flags);
218         oldflags = btrfs_flags_to_ioctl(ip->flags);
219         if ((flags ^ oldflags) & (FS_APPEND_FL | FS_IMMUTABLE_FL)) {
220                 if (!capable(CAP_LINUX_IMMUTABLE)) {
221                         ret = -EPERM;
222                         goto out_unlock;
223                 }
224         }
225
226         if (flags & FS_SYNC_FL)
227                 ip->flags |= BTRFS_INODE_SYNC;
228         else
229                 ip->flags &= ~BTRFS_INODE_SYNC;
230         if (flags & FS_IMMUTABLE_FL)
231                 ip->flags |= BTRFS_INODE_IMMUTABLE;
232         else
233                 ip->flags &= ~BTRFS_INODE_IMMUTABLE;
234         if (flags & FS_APPEND_FL)
235                 ip->flags |= BTRFS_INODE_APPEND;
236         else
237                 ip->flags &= ~BTRFS_INODE_APPEND;
238         if (flags & FS_NODUMP_FL)
239                 ip->flags |= BTRFS_INODE_NODUMP;
240         else
241                 ip->flags &= ~BTRFS_INODE_NODUMP;
242         if (flags & FS_NOATIME_FL)
243                 ip->flags |= BTRFS_INODE_NOATIME;
244         else
245                 ip->flags &= ~BTRFS_INODE_NOATIME;
246         if (flags & FS_DIRSYNC_FL)
247                 ip->flags |= BTRFS_INODE_DIRSYNC;
248         else
249                 ip->flags &= ~BTRFS_INODE_DIRSYNC;
250         if (flags & FS_NOCOW_FL) {
251                 if (S_ISREG(mode)) {
252                         /*
253                          * It's safe to turn csums off here, no extents exist.
254                          * Otherwise we want the flag to reflect the real COW
255                          * status of the file and will not set it.
256                          */
257                         if (inode->i_size == 0)
258                                 ip->flags |= BTRFS_INODE_NODATACOW
259                                            | BTRFS_INODE_NODATASUM;
260                 } else {
261                         ip->flags |= BTRFS_INODE_NODATACOW;
262                 }
263         } else {
264                 /*
265                  * Revert back under same assuptions as above
266                  */
267                 if (S_ISREG(mode)) {
268                         if (inode->i_size == 0)
269                                 ip->flags &= ~(BTRFS_INODE_NODATACOW
270                                              | BTRFS_INODE_NODATASUM);
271                 } else {
272                         ip->flags &= ~BTRFS_INODE_NODATACOW;
273                 }
274         }
275
276         /*
277          * The COMPRESS flag can only be changed by users, while the NOCOMPRESS
278          * flag may be changed automatically if compression code won't make
279          * things smaller.
280          */
281         if (flags & FS_NOCOMP_FL) {
282                 ip->flags &= ~BTRFS_INODE_COMPRESS;
283                 ip->flags |= BTRFS_INODE_NOCOMPRESS;
284         } else if (flags & FS_COMPR_FL) {
285                 ip->flags |= BTRFS_INODE_COMPRESS;
286                 ip->flags &= ~BTRFS_INODE_NOCOMPRESS;
287         } else {
288                 ip->flags &= ~(BTRFS_INODE_COMPRESS | BTRFS_INODE_NOCOMPRESS);
289         }
290
291         trans = btrfs_start_transaction(root, 1);
292         if (IS_ERR(trans)) {
293                 ret = PTR_ERR(trans);
294                 goto out_drop;
295         }
296
297         btrfs_update_iflags(inode);
298         inode_inc_iversion(inode);
299         inode->i_ctime = CURRENT_TIME;
300         ret = btrfs_update_inode(trans, root, inode);
301
302         btrfs_end_transaction(trans, root);
303  out_drop:
304         if (ret) {
305                 ip->flags = ip_oldflags;
306                 inode->i_flags = i_oldflags;
307         }
308
309  out_unlock:
310         mutex_unlock(&inode->i_mutex);
311         mnt_drop_write_file(file);
312         return ret;
313 }
314
315 static int btrfs_ioctl_getversion(struct file *file, int __user *arg)
316 {
317         struct inode *inode = file_inode(file);
318
319         return put_user(inode->i_generation, arg);
320 }
321
322 static noinline int btrfs_ioctl_fitrim(struct file *file, void __user *arg)
323 {
324         struct btrfs_fs_info *fs_info = btrfs_sb(file_inode(file)->i_sb);
325         struct btrfs_device *device;
326         struct request_queue *q;
327         struct fstrim_range range;
328         u64 minlen = ULLONG_MAX;
329         u64 num_devices = 0;
330         u64 total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
331         int ret;
332
333         if (!capable(CAP_SYS_ADMIN))
334                 return -EPERM;
335
336         rcu_read_lock();
337         list_for_each_entry_rcu(device, &fs_info->fs_devices->devices,
338                                 dev_list) {
339                 if (!device->bdev)
340                         continue;
341                 q = bdev_get_queue(device->bdev);
342                 if (blk_queue_discard(q)) {
343                         num_devices++;
344                         minlen = min((u64)q->limits.discard_granularity,
345                                      minlen);
346                 }
347         }
348         rcu_read_unlock();
349
350         if (!num_devices)
351                 return -EOPNOTSUPP;
352         if (copy_from_user(&range, arg, sizeof(range)))
353                 return -EFAULT;
354         if (range.start > total_bytes ||
355             range.len < fs_info->sb->s_blocksize)
356                 return -EINVAL;
357
358         range.len = min(range.len, total_bytes - range.start);
359         range.minlen = max(range.minlen, minlen);
360         ret = btrfs_trim_fs(fs_info->tree_root, &range);
361         if (ret < 0)
362                 return ret;
363
364         if (copy_to_user(arg, &range, sizeof(range)))
365                 return -EFAULT;
366
367         return 0;
368 }
369
370 int btrfs_is_empty_uuid(u8 *uuid)
371 {
372         int i;
373
374         for (i = 0; i < BTRFS_UUID_SIZE; i++) {
375                 if (uuid[i])
376                         return 0;
377         }
378         return 1;
379 }
380
381 static noinline int create_subvol(struct inode *dir,
382                                   struct dentry *dentry,
383                                   char *name, int namelen,
384                                   u64 *async_transid,
385                                   struct btrfs_qgroup_inherit *inherit)
386 {
387         struct btrfs_trans_handle *trans;
388         struct btrfs_key key;
389         struct btrfs_root_item root_item;
390         struct btrfs_inode_item *inode_item;
391         struct extent_buffer *leaf;
392         struct btrfs_root *root = BTRFS_I(dir)->root;
393         struct btrfs_root *new_root;
394         struct btrfs_block_rsv block_rsv;
395         struct timespec cur_time = CURRENT_TIME;
396         struct inode *inode;
397         int ret;
398         int err;
399         u64 objectid;
400         u64 new_dirid = BTRFS_FIRST_FREE_OBJECTID;
401         u64 index = 0;
402         u64 qgroup_reserved;
403         uuid_le new_uuid;
404
405         ret = btrfs_find_free_objectid(root->fs_info->tree_root, &objectid);
406         if (ret)
407                 return ret;
408
409         btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
410         /*
411          * The same as the snapshot creation, please see the comment
412          * of create_snapshot().
413          */
414         ret = btrfs_subvolume_reserve_metadata(root, &block_rsv,
415                                                8, &qgroup_reserved, false);
416         if (ret)
417                 return ret;
418
419         trans = btrfs_start_transaction(root, 0);
420         if (IS_ERR(trans)) {
421                 ret = PTR_ERR(trans);
422                 goto out;
423         }
424         trans->block_rsv = &block_rsv;
425         trans->bytes_reserved = block_rsv.size;
426
427         ret = btrfs_qgroup_inherit(trans, root->fs_info, 0, objectid, inherit);
428         if (ret)
429                 goto fail;
430
431         leaf = btrfs_alloc_free_block(trans, root, root->leafsize,
432                                       0, objectid, NULL, 0, 0, 0);
433         if (IS_ERR(leaf)) {
434                 ret = PTR_ERR(leaf);
435                 goto fail;
436         }
437
438         memset_extent_buffer(leaf, 0, 0, sizeof(struct btrfs_header));
439         btrfs_set_header_bytenr(leaf, leaf->start);
440         btrfs_set_header_generation(leaf, trans->transid);
441         btrfs_set_header_backref_rev(leaf, BTRFS_MIXED_BACKREF_REV);
442         btrfs_set_header_owner(leaf, objectid);
443
444         write_extent_buffer(leaf, root->fs_info->fsid, btrfs_header_fsid(),
445                             BTRFS_FSID_SIZE);
446         write_extent_buffer(leaf, root->fs_info->chunk_tree_uuid,
447                             btrfs_header_chunk_tree_uuid(leaf),
448                             BTRFS_UUID_SIZE);
449         btrfs_mark_buffer_dirty(leaf);
450
451         memset(&root_item, 0, sizeof(root_item));
452
453         inode_item = &root_item.inode;
454         btrfs_set_stack_inode_generation(inode_item, 1);
455         btrfs_set_stack_inode_size(inode_item, 3);
456         btrfs_set_stack_inode_nlink(inode_item, 1);
457         btrfs_set_stack_inode_nbytes(inode_item, root->leafsize);
458         btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
459
460         btrfs_set_root_flags(&root_item, 0);
461         btrfs_set_root_limit(&root_item, 0);
462         btrfs_set_stack_inode_flags(inode_item, BTRFS_INODE_ROOT_ITEM_INIT);
463
464         btrfs_set_root_bytenr(&root_item, leaf->start);
465         btrfs_set_root_generation(&root_item, trans->transid);
466         btrfs_set_root_level(&root_item, 0);
467         btrfs_set_root_refs(&root_item, 1);
468         btrfs_set_root_used(&root_item, leaf->len);
469         btrfs_set_root_last_snapshot(&root_item, 0);
470
471         btrfs_set_root_generation_v2(&root_item,
472                         btrfs_root_generation(&root_item));
473         uuid_le_gen(&new_uuid);
474         memcpy(root_item.uuid, new_uuid.b, BTRFS_UUID_SIZE);
475         btrfs_set_stack_timespec_sec(&root_item.otime, cur_time.tv_sec);
476         btrfs_set_stack_timespec_nsec(&root_item.otime, cur_time.tv_nsec);
477         root_item.ctime = root_item.otime;
478         btrfs_set_root_ctransid(&root_item, trans->transid);
479         btrfs_set_root_otransid(&root_item, trans->transid);
480
481         btrfs_tree_unlock(leaf);
482         free_extent_buffer(leaf);
483         leaf = NULL;
484
485         btrfs_set_root_dirid(&root_item, new_dirid);
486
487         key.objectid = objectid;
488         key.offset = 0;
489         btrfs_set_key_type(&key, BTRFS_ROOT_ITEM_KEY);
490         ret = btrfs_insert_root(trans, root->fs_info->tree_root, &key,
491                                 &root_item);
492         if (ret)
493                 goto fail;
494
495         key.offset = (u64)-1;
496         new_root = btrfs_read_fs_root_no_name(root->fs_info, &key);
497         if (IS_ERR(new_root)) {
498                 btrfs_abort_transaction(trans, root, PTR_ERR(new_root));
499                 ret = PTR_ERR(new_root);
500                 goto fail;
501         }
502
503         btrfs_record_root_in_trans(trans, new_root);
504
505         ret = btrfs_create_subvol_root(trans, new_root, new_dirid);
506         if (ret) {
507                 /* We potentially lose an unused inode item here */
508                 btrfs_abort_transaction(trans, root, ret);
509                 goto fail;
510         }
511
512         /*
513          * insert the directory item
514          */
515         ret = btrfs_set_inode_index(dir, &index);
516         if (ret) {
517                 btrfs_abort_transaction(trans, root, ret);
518                 goto fail;
519         }
520
521         ret = btrfs_insert_dir_item(trans, root,
522                                     name, namelen, dir, &key,
523                                     BTRFS_FT_DIR, index);
524         if (ret) {
525                 btrfs_abort_transaction(trans, root, ret);
526                 goto fail;
527         }
528
529         btrfs_i_size_write(dir, dir->i_size + namelen * 2);
530         ret = btrfs_update_inode(trans, root, dir);
531         BUG_ON(ret);
532
533         ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
534                                  objectid, root->root_key.objectid,
535                                  btrfs_ino(dir), index, name, namelen);
536         BUG_ON(ret);
537
538         ret = btrfs_uuid_tree_add(trans, root->fs_info->uuid_root,
539                                   root_item.uuid, BTRFS_UUID_KEY_SUBVOL,
540                                   objectid);
541         if (ret)
542                 btrfs_abort_transaction(trans, root, ret);
543
544 fail:
545         trans->block_rsv = NULL;
546         trans->bytes_reserved = 0;
547         if (async_transid) {
548                 *async_transid = trans->transid;
549                 err = btrfs_commit_transaction_async(trans, root, 1);
550                 if (err)
551                         err = btrfs_commit_transaction(trans, root);
552         } else {
553                 err = btrfs_commit_transaction(trans, root);
554         }
555         if (err && !ret)
556                 ret = err;
557
558         if (!ret) {
559                 inode = btrfs_lookup_dentry(dir, dentry);
560                 if (IS_ERR(inode)) {
561                         ret = PTR_ERR(inode);
562                         goto out;
563                 }
564                 d_instantiate(dentry, inode);
565         }
566 out:
567         btrfs_subvolume_release_metadata(root, &block_rsv, qgroup_reserved);
568         return ret;
569 }
570
571 static int create_snapshot(struct btrfs_root *root, struct inode *dir,
572                            struct dentry *dentry, char *name, int namelen,
573                            u64 *async_transid, bool readonly,
574                            struct btrfs_qgroup_inherit *inherit)
575 {
576         struct inode *inode;
577         struct btrfs_pending_snapshot *pending_snapshot;
578         struct btrfs_trans_handle *trans;
579         int ret;
580
581         if (!root->ref_cows)
582                 return -EINVAL;
583
584         ret = btrfs_start_delalloc_inodes(root, 0);
585         if (ret)
586                 return ret;
587
588         btrfs_wait_ordered_extents(root, -1);
589
590         pending_snapshot = kzalloc(sizeof(*pending_snapshot), GFP_NOFS);
591         if (!pending_snapshot)
592                 return -ENOMEM;
593
594         btrfs_init_block_rsv(&pending_snapshot->block_rsv,
595                              BTRFS_BLOCK_RSV_TEMP);
596         /*
597          * 1 - parent dir inode
598          * 2 - dir entries
599          * 1 - root item
600          * 2 - root ref/backref
601          * 1 - root of snapshot
602          * 1 - UUID item
603          */
604         ret = btrfs_subvolume_reserve_metadata(BTRFS_I(dir)->root,
605                                         &pending_snapshot->block_rsv, 8,
606                                         &pending_snapshot->qgroup_reserved,
607                                         false);
608         if (ret)
609                 goto out;
610
611         pending_snapshot->dentry = dentry;
612         pending_snapshot->root = root;
613         pending_snapshot->readonly = readonly;
614         pending_snapshot->dir = dir;
615         pending_snapshot->inherit = inherit;
616
617         trans = btrfs_start_transaction(root, 0);
618         if (IS_ERR(trans)) {
619                 ret = PTR_ERR(trans);
620                 goto fail;
621         }
622
623         spin_lock(&root->fs_info->trans_lock);
624         list_add(&pending_snapshot->list,
625                  &trans->transaction->pending_snapshots);
626         spin_unlock(&root->fs_info->trans_lock);
627         if (async_transid) {
628                 *async_transid = trans->transid;
629                 ret = btrfs_commit_transaction_async(trans,
630                                      root->fs_info->extent_root, 1);
631                 if (ret)
632                         ret = btrfs_commit_transaction(trans, root);
633         } else {
634                 ret = btrfs_commit_transaction(trans,
635                                                root->fs_info->extent_root);
636         }
637         if (ret)
638                 goto fail;
639
640         ret = pending_snapshot->error;
641         if (ret)
642                 goto fail;
643
644         ret = btrfs_orphan_cleanup(pending_snapshot->snap);
645         if (ret)
646                 goto fail;
647
648         inode = btrfs_lookup_dentry(dentry->d_parent->d_inode, dentry);
649         if (IS_ERR(inode)) {
650                 ret = PTR_ERR(inode);
651                 goto fail;
652         }
653
654         d_instantiate(dentry, inode);
655         ret = 0;
656 fail:
657         btrfs_subvolume_release_metadata(BTRFS_I(dir)->root,
658                                          &pending_snapshot->block_rsv,
659                                          pending_snapshot->qgroup_reserved);
660 out:
661         kfree(pending_snapshot);
662         return ret;
663 }
664
665 /*  copy of check_sticky in fs/namei.c()
666 * It's inline, so penalty for filesystems that don't use sticky bit is
667 * minimal.
668 */
669 static inline int btrfs_check_sticky(struct inode *dir, struct inode *inode)
670 {
671         kuid_t fsuid = current_fsuid();
672
673         if (!(dir->i_mode & S_ISVTX))
674                 return 0;
675         if (uid_eq(inode->i_uid, fsuid))
676                 return 0;
677         if (uid_eq(dir->i_uid, fsuid))
678                 return 0;
679         return !capable(CAP_FOWNER);
680 }
681
682 /*  copy of may_delete in fs/namei.c()
683  *      Check whether we can remove a link victim from directory dir, check
684  *  whether the type of victim is right.
685  *  1. We can't do it if dir is read-only (done in permission())
686  *  2. We should have write and exec permissions on dir
687  *  3. We can't remove anything from append-only dir
688  *  4. We can't do anything with immutable dir (done in permission())
689  *  5. If the sticky bit on dir is set we should either
690  *      a. be owner of dir, or
691  *      b. be owner of victim, or
692  *      c. have CAP_FOWNER capability
693  *  6. If the victim is append-only or immutable we can't do antyhing with
694  *     links pointing to it.
695  *  7. If we were asked to remove a directory and victim isn't one - ENOTDIR.
696  *  8. If we were asked to remove a non-directory and victim isn't one - EISDIR.
697  *  9. We can't remove a root or mountpoint.
698  * 10. We don't allow removal of NFS sillyrenamed files; it's handled by
699  *     nfs_async_unlink().
700  */
701
702 static int btrfs_may_delete(struct inode *dir, struct dentry *victim, int isdir)
703 {
704         int error;
705
706         if (!victim->d_inode)
707                 return -ENOENT;
708
709         BUG_ON(victim->d_parent->d_inode != dir);
710         audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE);
711
712         error = inode_permission(dir, MAY_WRITE | MAY_EXEC);
713         if (error)
714                 return error;
715         if (IS_APPEND(dir))
716                 return -EPERM;
717         if (btrfs_check_sticky(dir, victim->d_inode)||
718                 IS_APPEND(victim->d_inode)||
719             IS_IMMUTABLE(victim->d_inode) || IS_SWAPFILE(victim->d_inode))
720                 return -EPERM;
721         if (isdir) {
722                 if (!S_ISDIR(victim->d_inode->i_mode))
723                         return -ENOTDIR;
724                 if (IS_ROOT(victim))
725                         return -EBUSY;
726         } else if (S_ISDIR(victim->d_inode->i_mode))
727                 return -EISDIR;
728         if (IS_DEADDIR(dir))
729                 return -ENOENT;
730         if (victim->d_flags & DCACHE_NFSFS_RENAMED)
731                 return -EBUSY;
732         return 0;
733 }
734
735 /* copy of may_create in fs/namei.c() */
736 static inline int btrfs_may_create(struct inode *dir, struct dentry *child)
737 {
738         if (child->d_inode)
739                 return -EEXIST;
740         if (IS_DEADDIR(dir))
741                 return -ENOENT;
742         return inode_permission(dir, MAY_WRITE | MAY_EXEC);
743 }
744
745 /*
746  * Create a new subvolume below @parent.  This is largely modeled after
747  * sys_mkdirat and vfs_mkdir, but we only do a single component lookup
748  * inside this filesystem so it's quite a bit simpler.
749  */
750 static noinline int btrfs_mksubvol(struct path *parent,
751                                    char *name, int namelen,
752                                    struct btrfs_root *snap_src,
753                                    u64 *async_transid, bool readonly,
754                                    struct btrfs_qgroup_inherit *inherit)
755 {
756         struct inode *dir  = parent->dentry->d_inode;
757         struct dentry *dentry;
758         int error;
759
760         error = mutex_lock_killable_nested(&dir->i_mutex, I_MUTEX_PARENT);
761         if (error == -EINTR)
762                 return error;
763
764         dentry = lookup_one_len(name, parent->dentry, namelen);
765         error = PTR_ERR(dentry);
766         if (IS_ERR(dentry))
767                 goto out_unlock;
768
769         error = -EEXIST;
770         if (dentry->d_inode)
771                 goto out_dput;
772
773         error = btrfs_may_create(dir, dentry);
774         if (error)
775                 goto out_dput;
776
777         /*
778          * even if this name doesn't exist, we may get hash collisions.
779          * check for them now when we can safely fail
780          */
781         error = btrfs_check_dir_item_collision(BTRFS_I(dir)->root,
782                                                dir->i_ino, name,
783                                                namelen);
784         if (error)
785                 goto out_dput;
786
787         down_read(&BTRFS_I(dir)->root->fs_info->subvol_sem);
788
789         if (btrfs_root_refs(&BTRFS_I(dir)->root->root_item) == 0)
790                 goto out_up_read;
791
792         if (snap_src) {
793                 error = create_snapshot(snap_src, dir, dentry, name, namelen,
794                                         async_transid, readonly, inherit);
795         } else {
796                 error = create_subvol(dir, dentry, name, namelen,
797                                       async_transid, inherit);
798         }
799         if (!error)
800                 fsnotify_mkdir(dir, dentry);
801 out_up_read:
802         up_read(&BTRFS_I(dir)->root->fs_info->subvol_sem);
803 out_dput:
804         dput(dentry);
805 out_unlock:
806         mutex_unlock(&dir->i_mutex);
807         return error;
808 }
809
810 /*
811  * When we're defragging a range, we don't want to kick it off again
812  * if it is really just waiting for delalloc to send it down.
813  * If we find a nice big extent or delalloc range for the bytes in the
814  * file you want to defrag, we return 0 to let you know to skip this
815  * part of the file
816  */
817 static int check_defrag_in_cache(struct inode *inode, u64 offset, int thresh)
818 {
819         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
820         struct extent_map *em = NULL;
821         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
822         u64 end;
823
824         read_lock(&em_tree->lock);
825         em = lookup_extent_mapping(em_tree, offset, PAGE_CACHE_SIZE);
826         read_unlock(&em_tree->lock);
827
828         if (em) {
829                 end = extent_map_end(em);
830                 free_extent_map(em);
831                 if (end - offset > thresh)
832                         return 0;
833         }
834         /* if we already have a nice delalloc here, just stop */
835         thresh /= 2;
836         end = count_range_bits(io_tree, &offset, offset + thresh,
837                                thresh, EXTENT_DELALLOC, 1);
838         if (end >= thresh)
839                 return 0;
840         return 1;
841 }
842
843 /*
844  * helper function to walk through a file and find extents
845  * newer than a specific transid, and smaller than thresh.
846  *
847  * This is used by the defragging code to find new and small
848  * extents
849  */
850 static int find_new_extents(struct btrfs_root *root,
851                             struct inode *inode, u64 newer_than,
852                             u64 *off, int thresh)
853 {
854         struct btrfs_path *path;
855         struct btrfs_key min_key;
856         struct extent_buffer *leaf;
857         struct btrfs_file_extent_item *extent;
858         int type;
859         int ret;
860         u64 ino = btrfs_ino(inode);
861
862         path = btrfs_alloc_path();
863         if (!path)
864                 return -ENOMEM;
865
866         min_key.objectid = ino;
867         min_key.type = BTRFS_EXTENT_DATA_KEY;
868         min_key.offset = *off;
869
870         path->keep_locks = 1;
871
872         while (1) {
873                 ret = btrfs_search_forward(root, &min_key, path, newer_than);
874                 if (ret != 0)
875                         goto none;
876                 if (min_key.objectid != ino)
877                         goto none;
878                 if (min_key.type != BTRFS_EXTENT_DATA_KEY)
879                         goto none;
880
881                 leaf = path->nodes[0];
882                 extent = btrfs_item_ptr(leaf, path->slots[0],
883                                         struct btrfs_file_extent_item);
884
885                 type = btrfs_file_extent_type(leaf, extent);
886                 if (type == BTRFS_FILE_EXTENT_REG &&
887                     btrfs_file_extent_num_bytes(leaf, extent) < thresh &&
888                     check_defrag_in_cache(inode, min_key.offset, thresh)) {
889                         *off = min_key.offset;
890                         btrfs_free_path(path);
891                         return 0;
892                 }
893
894                 if (min_key.offset == (u64)-1)
895                         goto none;
896
897                 min_key.offset++;
898                 btrfs_release_path(path);
899         }
900 none:
901         btrfs_free_path(path);
902         return -ENOENT;
903 }
904
905 static struct extent_map *defrag_lookup_extent(struct inode *inode, u64 start)
906 {
907         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
908         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
909         struct extent_map *em;
910         u64 len = PAGE_CACHE_SIZE;
911
912         /*
913          * hopefully we have this extent in the tree already, try without
914          * the full extent lock
915          */
916         read_lock(&em_tree->lock);
917         em = lookup_extent_mapping(em_tree, start, len);
918         read_unlock(&em_tree->lock);
919
920         if (!em) {
921                 /* get the big lock and read metadata off disk */
922                 lock_extent(io_tree, start, start + len - 1);
923                 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
924                 unlock_extent(io_tree, start, start + len - 1);
925
926                 if (IS_ERR(em))
927                         return NULL;
928         }
929
930         return em;
931 }
932
933 static bool defrag_check_next_extent(struct inode *inode, struct extent_map *em)
934 {
935         struct extent_map *next;
936         bool ret = true;
937
938         /* this is the last extent */
939         if (em->start + em->len >= i_size_read(inode))
940                 return false;
941
942         next = defrag_lookup_extent(inode, em->start + em->len);
943         if (!next || next->block_start >= EXTENT_MAP_LAST_BYTE)
944                 ret = false;
945
946         free_extent_map(next);
947         return ret;
948 }
949
950 static int should_defrag_range(struct inode *inode, u64 start, int thresh,
951                                u64 *last_len, u64 *skip, u64 *defrag_end,
952                                int compress)
953 {
954         struct extent_map *em;
955         int ret = 1;
956         bool next_mergeable = true;
957
958         /*
959          * make sure that once we start defragging an extent, we keep on
960          * defragging it
961          */
962         if (start < *defrag_end)
963                 return 1;
964
965         *skip = 0;
966
967         em = defrag_lookup_extent(inode, start);
968         if (!em)
969                 return 0;
970
971         /* this will cover holes, and inline extents */
972         if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
973                 ret = 0;
974                 goto out;
975         }
976
977         next_mergeable = defrag_check_next_extent(inode, em);
978
979         /*
980          * we hit a real extent, if it is big or the next extent is not a
981          * real extent, don't bother defragging it
982          */
983         if (!compress && (*last_len == 0 || *last_len >= thresh) &&
984             (em->len >= thresh || !next_mergeable))
985                 ret = 0;
986 out:
987         /*
988          * last_len ends up being a counter of how many bytes we've defragged.
989          * every time we choose not to defrag an extent, we reset *last_len
990          * so that the next tiny extent will force a defrag.
991          *
992          * The end result of this is that tiny extents before a single big
993          * extent will force at least part of that big extent to be defragged.
994          */
995         if (ret) {
996                 *defrag_end = extent_map_end(em);
997         } else {
998                 *last_len = 0;
999                 *skip = extent_map_end(em);
1000                 *defrag_end = 0;
1001         }
1002
1003         free_extent_map(em);
1004         return ret;
1005 }
1006
1007 /*
1008  * it doesn't do much good to defrag one or two pages
1009  * at a time.  This pulls in a nice chunk of pages
1010  * to COW and defrag.
1011  *
1012  * It also makes sure the delalloc code has enough
1013  * dirty data to avoid making new small extents as part
1014  * of the defrag
1015  *
1016  * It's a good idea to start RA on this range
1017  * before calling this.
1018  */
1019 static int cluster_pages_for_defrag(struct inode *inode,
1020                                     struct page **pages,
1021                                     unsigned long start_index,
1022                                     int num_pages)
1023 {
1024         unsigned long file_end;
1025         u64 isize = i_size_read(inode);
1026         u64 page_start;
1027         u64 page_end;
1028         u64 page_cnt;
1029         int ret;
1030         int i;
1031         int i_done;
1032         struct btrfs_ordered_extent *ordered;
1033         struct extent_state *cached_state = NULL;
1034         struct extent_io_tree *tree;
1035         gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
1036
1037         file_end = (isize - 1) >> PAGE_CACHE_SHIFT;
1038         if (!isize || start_index > file_end)
1039                 return 0;
1040
1041         page_cnt = min_t(u64, (u64)num_pages, (u64)file_end - start_index + 1);
1042
1043         ret = btrfs_delalloc_reserve_space(inode,
1044                                            page_cnt << PAGE_CACHE_SHIFT);
1045         if (ret)
1046                 return ret;
1047         i_done = 0;
1048         tree = &BTRFS_I(inode)->io_tree;
1049
1050         /* step one, lock all the pages */
1051         for (i = 0; i < page_cnt; i++) {
1052                 struct page *page;
1053 again:
1054                 page = find_or_create_page(inode->i_mapping,
1055                                            start_index + i, mask);
1056                 if (!page)
1057                         break;
1058
1059                 page_start = page_offset(page);
1060                 page_end = page_start + PAGE_CACHE_SIZE - 1;
1061                 while (1) {
1062                         lock_extent(tree, page_start, page_end);
1063                         ordered = btrfs_lookup_ordered_extent(inode,
1064                                                               page_start);
1065                         unlock_extent(tree, page_start, page_end);
1066                         if (!ordered)
1067                                 break;
1068
1069                         unlock_page(page);
1070                         btrfs_start_ordered_extent(inode, ordered, 1);
1071                         btrfs_put_ordered_extent(ordered);
1072                         lock_page(page);
1073                         /*
1074                          * we unlocked the page above, so we need check if
1075                          * it was released or not.
1076                          */
1077                         if (page->mapping != inode->i_mapping) {
1078                                 unlock_page(page);
1079                                 page_cache_release(page);
1080                                 goto again;
1081                         }
1082                 }
1083
1084                 if (!PageUptodate(page)) {
1085                         btrfs_readpage(NULL, page);
1086                         lock_page(page);
1087                         if (!PageUptodate(page)) {
1088                                 unlock_page(page);
1089                                 page_cache_release(page);
1090                                 ret = -EIO;
1091                                 break;
1092                         }
1093                 }
1094
1095                 if (page->mapping != inode->i_mapping) {
1096                         unlock_page(page);
1097                         page_cache_release(page);
1098                         goto again;
1099                 }
1100
1101                 pages[i] = page;
1102                 i_done++;
1103         }
1104         if (!i_done || ret)
1105                 goto out;
1106
1107         if (!(inode->i_sb->s_flags & MS_ACTIVE))
1108                 goto out;
1109
1110         /*
1111          * so now we have a nice long stream of locked
1112          * and up to date pages, lets wait on them
1113          */
1114         for (i = 0; i < i_done; i++)
1115                 wait_on_page_writeback(pages[i]);
1116
1117         page_start = page_offset(pages[0]);
1118         page_end = page_offset(pages[i_done - 1]) + PAGE_CACHE_SIZE;
1119
1120         lock_extent_bits(&BTRFS_I(inode)->io_tree,
1121                          page_start, page_end - 1, 0, &cached_state);
1122         clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start,
1123                           page_end - 1, EXTENT_DIRTY | EXTENT_DELALLOC |
1124                           EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 0, 0,
1125                           &cached_state, GFP_NOFS);
1126
1127         if (i_done != page_cnt) {
1128                 spin_lock(&BTRFS_I(inode)->lock);
1129                 BTRFS_I(inode)->outstanding_extents++;
1130                 spin_unlock(&BTRFS_I(inode)->lock);
1131                 btrfs_delalloc_release_space(inode,
1132                                      (page_cnt - i_done) << PAGE_CACHE_SHIFT);
1133         }
1134
1135
1136         set_extent_defrag(&BTRFS_I(inode)->io_tree, page_start, page_end - 1,
1137                           &cached_state, GFP_NOFS);
1138
1139         unlock_extent_cached(&BTRFS_I(inode)->io_tree,
1140                              page_start, page_end - 1, &cached_state,
1141                              GFP_NOFS);
1142
1143         for (i = 0; i < i_done; i++) {
1144                 clear_page_dirty_for_io(pages[i]);
1145                 ClearPageChecked(pages[i]);
1146                 set_page_extent_mapped(pages[i]);
1147                 set_page_dirty(pages[i]);
1148                 unlock_page(pages[i]);
1149                 page_cache_release(pages[i]);
1150         }
1151         return i_done;
1152 out:
1153         for (i = 0; i < i_done; i++) {
1154                 unlock_page(pages[i]);
1155                 page_cache_release(pages[i]);
1156         }
1157         btrfs_delalloc_release_space(inode, page_cnt << PAGE_CACHE_SHIFT);
1158         return ret;
1159
1160 }
1161
1162 int btrfs_defrag_file(struct inode *inode, struct file *file,
1163                       struct btrfs_ioctl_defrag_range_args *range,
1164                       u64 newer_than, unsigned long max_to_defrag)
1165 {
1166         struct btrfs_root *root = BTRFS_I(inode)->root;
1167         struct file_ra_state *ra = NULL;
1168         unsigned long last_index;
1169         u64 isize = i_size_read(inode);
1170         u64 last_len = 0;
1171         u64 skip = 0;
1172         u64 defrag_end = 0;
1173         u64 newer_off = range->start;
1174         unsigned long i;
1175         unsigned long ra_index = 0;
1176         int ret;
1177         int defrag_count = 0;
1178         int compress_type = BTRFS_COMPRESS_ZLIB;
1179         int extent_thresh = range->extent_thresh;
1180         int max_cluster = (256 * 1024) >> PAGE_CACHE_SHIFT;
1181         int cluster = max_cluster;
1182         u64 new_align = ~((u64)128 * 1024 - 1);
1183         struct page **pages = NULL;
1184
1185         if (isize == 0)
1186                 return 0;
1187
1188         if (range->start >= isize)
1189                 return -EINVAL;
1190
1191         if (range->flags & BTRFS_DEFRAG_RANGE_COMPRESS) {
1192                 if (range->compress_type > BTRFS_COMPRESS_TYPES)
1193                         return -EINVAL;
1194                 if (range->compress_type)
1195                         compress_type = range->compress_type;
1196         }
1197
1198         if (extent_thresh == 0)
1199                 extent_thresh = 256 * 1024;
1200
1201         /*
1202          * if we were not given a file, allocate a readahead
1203          * context
1204          */
1205         if (!file) {
1206                 ra = kzalloc(sizeof(*ra), GFP_NOFS);
1207                 if (!ra)
1208                         return -ENOMEM;
1209                 file_ra_state_init(ra, inode->i_mapping);
1210         } else {
1211                 ra = &file->f_ra;
1212         }
1213
1214         pages = kmalloc_array(max_cluster, sizeof(struct page *),
1215                         GFP_NOFS);
1216         if (!pages) {
1217                 ret = -ENOMEM;
1218                 goto out_ra;
1219         }
1220
1221         /* find the last page to defrag */
1222         if (range->start + range->len > range->start) {
1223                 last_index = min_t(u64, isize - 1,
1224                          range->start + range->len - 1) >> PAGE_CACHE_SHIFT;
1225         } else {
1226                 last_index = (isize - 1) >> PAGE_CACHE_SHIFT;
1227         }
1228
1229         if (newer_than) {
1230                 ret = find_new_extents(root, inode, newer_than,
1231                                        &newer_off, 64 * 1024);
1232                 if (!ret) {
1233                         range->start = newer_off;
1234                         /*
1235                          * we always align our defrag to help keep
1236                          * the extents in the file evenly spaced
1237                          */
1238                         i = (newer_off & new_align) >> PAGE_CACHE_SHIFT;
1239                 } else
1240                         goto out_ra;
1241         } else {
1242                 i = range->start >> PAGE_CACHE_SHIFT;
1243         }
1244         if (!max_to_defrag)
1245                 max_to_defrag = last_index + 1;
1246
1247         /*
1248          * make writeback starts from i, so the defrag range can be
1249          * written sequentially.
1250          */
1251         if (i < inode->i_mapping->writeback_index)
1252                 inode->i_mapping->writeback_index = i;
1253
1254         while (i <= last_index && defrag_count < max_to_defrag &&
1255                (i < (i_size_read(inode) + PAGE_CACHE_SIZE - 1) >>
1256                 PAGE_CACHE_SHIFT)) {
1257                 /*
1258                  * make sure we stop running if someone unmounts
1259                  * the FS
1260                  */
1261                 if (!(inode->i_sb->s_flags & MS_ACTIVE))
1262                         break;
1263
1264                 if (btrfs_defrag_cancelled(root->fs_info)) {
1265                         printk(KERN_DEBUG "btrfs: defrag_file cancelled\n");
1266                         ret = -EAGAIN;
1267                         break;
1268                 }
1269
1270                 if (!should_defrag_range(inode, (u64)i << PAGE_CACHE_SHIFT,
1271                                          extent_thresh, &last_len, &skip,
1272                                          &defrag_end, range->flags &
1273                                          BTRFS_DEFRAG_RANGE_COMPRESS)) {
1274                         unsigned long next;
1275                         /*
1276                          * the should_defrag function tells us how much to skip
1277                          * bump our counter by the suggested amount
1278                          */
1279                         next = (skip + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
1280                         i = max(i + 1, next);
1281                         continue;
1282                 }
1283
1284                 if (!newer_than) {
1285                         cluster = (PAGE_CACHE_ALIGN(defrag_end) >>
1286                                    PAGE_CACHE_SHIFT) - i;
1287                         cluster = min(cluster, max_cluster);
1288                 } else {
1289                         cluster = max_cluster;
1290                 }
1291
1292                 if (i + cluster > ra_index) {
1293                         ra_index = max(i, ra_index);
1294                         btrfs_force_ra(inode->i_mapping, ra, file, ra_index,
1295                                        cluster);
1296                         ra_index += max_cluster;
1297                 }
1298
1299                 mutex_lock(&inode->i_mutex);
1300                 if (range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)
1301                         BTRFS_I(inode)->force_compress = compress_type;
1302                 ret = cluster_pages_for_defrag(inode, pages, i, cluster);
1303                 if (ret < 0) {
1304                         mutex_unlock(&inode->i_mutex);
1305                         goto out_ra;
1306                 }
1307
1308                 defrag_count += ret;
1309                 balance_dirty_pages_ratelimited(inode->i_mapping);
1310                 mutex_unlock(&inode->i_mutex);
1311
1312                 if (newer_than) {
1313                         if (newer_off == (u64)-1)
1314                                 break;
1315
1316                         if (ret > 0)
1317                                 i += ret;
1318
1319                         newer_off = max(newer_off + 1,
1320                                         (u64)i << PAGE_CACHE_SHIFT);
1321
1322                         ret = find_new_extents(root, inode,
1323                                                newer_than, &newer_off,
1324                                                64 * 1024);
1325                         if (!ret) {
1326                                 range->start = newer_off;
1327                                 i = (newer_off & new_align) >> PAGE_CACHE_SHIFT;
1328                         } else {
1329                                 break;
1330                         }
1331                 } else {
1332                         if (ret > 0) {
1333                                 i += ret;
1334                                 last_len += ret << PAGE_CACHE_SHIFT;
1335                         } else {
1336                                 i++;
1337                                 last_len = 0;
1338                         }
1339                 }
1340         }
1341
1342         if ((range->flags & BTRFS_DEFRAG_RANGE_START_IO))
1343                 filemap_flush(inode->i_mapping);
1344
1345         if ((range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)) {
1346                 /* the filemap_flush will queue IO into the worker threads, but
1347                  * we have to make sure the IO is actually started and that
1348                  * ordered extents get created before we return
1349                  */
1350                 atomic_inc(&root->fs_info->async_submit_draining);
1351                 while (atomic_read(&root->fs_info->nr_async_submits) ||
1352                       atomic_read(&root->fs_info->async_delalloc_pages)) {
1353                         wait_event(root->fs_info->async_submit_wait,
1354                            (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
1355                             atomic_read(&root->fs_info->async_delalloc_pages) == 0));
1356                 }
1357                 atomic_dec(&root->fs_info->async_submit_draining);
1358         }
1359
1360         if (range->compress_type == BTRFS_COMPRESS_LZO) {
1361                 btrfs_set_fs_incompat(root->fs_info, COMPRESS_LZO);
1362         }
1363
1364         ret = defrag_count;
1365
1366 out_ra:
1367         if (range->flags & BTRFS_DEFRAG_RANGE_COMPRESS) {
1368                 mutex_lock(&inode->i_mutex);
1369                 BTRFS_I(inode)->force_compress = BTRFS_COMPRESS_NONE;
1370                 mutex_unlock(&inode->i_mutex);
1371         }
1372         if (!file)
1373                 kfree(ra);
1374         kfree(pages);
1375         return ret;
1376 }
1377
1378 static noinline int btrfs_ioctl_resize(struct file *file,
1379                                         void __user *arg)
1380 {
1381         u64 new_size;
1382         u64 old_size;
1383         u64 devid = 1;
1384         struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
1385         struct btrfs_ioctl_vol_args *vol_args;
1386         struct btrfs_trans_handle *trans;
1387         struct btrfs_device *device = NULL;
1388         char *sizestr;
1389         char *devstr = NULL;
1390         int ret = 0;
1391         int mod = 0;
1392
1393         if (!capable(CAP_SYS_ADMIN))
1394                 return -EPERM;
1395
1396         ret = mnt_want_write_file(file);
1397         if (ret)
1398                 return ret;
1399
1400         if (atomic_xchg(&root->fs_info->mutually_exclusive_operation_running,
1401                         1)) {
1402                 mnt_drop_write_file(file);
1403                 return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
1404         }
1405
1406         mutex_lock(&root->fs_info->volume_mutex);
1407         vol_args = memdup_user(arg, sizeof(*vol_args));
1408         if (IS_ERR(vol_args)) {
1409                 ret = PTR_ERR(vol_args);
1410                 goto out;
1411         }
1412
1413         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1414
1415         sizestr = vol_args->name;
1416         devstr = strchr(sizestr, ':');
1417         if (devstr) {
1418                 char *end;
1419                 sizestr = devstr + 1;
1420                 *devstr = '\0';
1421                 devstr = vol_args->name;
1422                 devid = simple_strtoull(devstr, &end, 10);
1423                 if (!devid) {
1424                         ret = -EINVAL;
1425                         goto out_free;
1426                 }
1427                 printk(KERN_INFO "btrfs: resizing devid %llu\n", devid);
1428         }
1429
1430         device = btrfs_find_device(root->fs_info, devid, NULL, NULL);
1431         if (!device) {
1432                 printk(KERN_INFO "btrfs: resizer unable to find device %llu\n",
1433                        devid);
1434                 ret = -ENODEV;
1435                 goto out_free;
1436         }
1437
1438         if (!device->writeable) {
1439                 printk(KERN_INFO "btrfs: resizer unable to apply on "
1440                        "readonly device %llu\n",
1441                        devid);
1442                 ret = -EPERM;
1443                 goto out_free;
1444         }
1445
1446         if (!strcmp(sizestr, "max"))
1447                 new_size = device->bdev->bd_inode->i_size;
1448         else {
1449                 if (sizestr[0] == '-') {
1450                         mod = -1;
1451                         sizestr++;
1452                 } else if (sizestr[0] == '+') {
1453                         mod = 1;
1454                         sizestr++;
1455                 }
1456                 new_size = memparse(sizestr, NULL);
1457                 if (new_size == 0) {
1458                         ret = -EINVAL;
1459                         goto out_free;
1460                 }
1461         }
1462
1463         if (device->is_tgtdev_for_dev_replace) {
1464                 ret = -EPERM;
1465                 goto out_free;
1466         }
1467
1468         old_size = device->total_bytes;
1469
1470         if (mod < 0) {
1471                 if (new_size > old_size) {
1472                         ret = -EINVAL;
1473                         goto out_free;
1474                 }
1475                 new_size = old_size - new_size;
1476         } else if (mod > 0) {
1477                 new_size = old_size + new_size;
1478         }
1479
1480         if (new_size < 256 * 1024 * 1024) {
1481                 ret = -EINVAL;
1482                 goto out_free;
1483         }
1484         if (new_size > device->bdev->bd_inode->i_size) {
1485                 ret = -EFBIG;
1486                 goto out_free;
1487         }
1488
1489         do_div(new_size, root->sectorsize);
1490         new_size *= root->sectorsize;
1491
1492         printk_in_rcu(KERN_INFO "btrfs: new size for %s is %llu\n",
1493                       rcu_str_deref(device->name), new_size);
1494
1495         if (new_size > old_size) {
1496                 trans = btrfs_start_transaction(root, 0);
1497                 if (IS_ERR(trans)) {
1498                         ret = PTR_ERR(trans);
1499                         goto out_free;
1500                 }
1501                 ret = btrfs_grow_device(trans, device, new_size);
1502                 btrfs_commit_transaction(trans, root);
1503         } else if (new_size < old_size) {
1504                 ret = btrfs_shrink_device(device, new_size);
1505         } /* equal, nothing need to do */
1506
1507 out_free:
1508         kfree(vol_args);
1509 out:
1510         mutex_unlock(&root->fs_info->volume_mutex);
1511         atomic_set(&root->fs_info->mutually_exclusive_operation_running, 0);
1512         mnt_drop_write_file(file);
1513         return ret;
1514 }
1515
1516 static noinline int btrfs_ioctl_snap_create_transid(struct file *file,
1517                                 char *name, unsigned long fd, int subvol,
1518                                 u64 *transid, bool readonly,
1519                                 struct btrfs_qgroup_inherit *inherit)
1520 {
1521         int namelen;
1522         int ret = 0;
1523
1524         ret = mnt_want_write_file(file);
1525         if (ret)
1526                 goto out;
1527
1528         namelen = strlen(name);
1529         if (strchr(name, '/')) {
1530                 ret = -EINVAL;
1531                 goto out_drop_write;
1532         }
1533
1534         if (name[0] == '.' &&
1535            (namelen == 1 || (name[1] == '.' && namelen == 2))) {
1536                 ret = -EEXIST;
1537                 goto out_drop_write;
1538         }
1539
1540         if (subvol) {
1541                 ret = btrfs_mksubvol(&file->f_path, name, namelen,
1542                                      NULL, transid, readonly, inherit);
1543         } else {
1544                 struct fd src = fdget(fd);
1545                 struct inode *src_inode;
1546                 if (!src.file) {
1547                         ret = -EINVAL;
1548                         goto out_drop_write;
1549                 }
1550
1551                 src_inode = file_inode(src.file);
1552                 if (src_inode->i_sb != file_inode(file)->i_sb) {
1553                         printk(KERN_INFO "btrfs: Snapshot src from "
1554                                "another FS\n");
1555                         ret = -EINVAL;
1556                 } else {
1557                         ret = btrfs_mksubvol(&file->f_path, name, namelen,
1558                                              BTRFS_I(src_inode)->root,
1559                                              transid, readonly, inherit);
1560                 }
1561                 fdput(src);
1562         }
1563 out_drop_write:
1564         mnt_drop_write_file(file);
1565 out:
1566         return ret;
1567 }
1568
1569 static noinline int btrfs_ioctl_snap_create(struct file *file,
1570                                             void __user *arg, int subvol)
1571 {
1572         struct btrfs_ioctl_vol_args *vol_args;
1573         int ret;
1574
1575         vol_args = memdup_user(arg, sizeof(*vol_args));
1576         if (IS_ERR(vol_args))
1577                 return PTR_ERR(vol_args);
1578         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1579
1580         ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
1581                                               vol_args->fd, subvol,
1582                                               NULL, false, NULL);
1583
1584         kfree(vol_args);
1585         return ret;
1586 }
1587
1588 static noinline int btrfs_ioctl_snap_create_v2(struct file *file,
1589                                                void __user *arg, int subvol)
1590 {
1591         struct btrfs_ioctl_vol_args_v2 *vol_args;
1592         int ret;
1593         u64 transid = 0;
1594         u64 *ptr = NULL;
1595         bool readonly = false;
1596         struct btrfs_qgroup_inherit *inherit = NULL;
1597
1598         vol_args = memdup_user(arg, sizeof(*vol_args));
1599         if (IS_ERR(vol_args))
1600                 return PTR_ERR(vol_args);
1601         vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
1602
1603         if (vol_args->flags &
1604             ~(BTRFS_SUBVOL_CREATE_ASYNC | BTRFS_SUBVOL_RDONLY |
1605               BTRFS_SUBVOL_QGROUP_INHERIT)) {
1606                 ret = -EOPNOTSUPP;
1607                 goto out;
1608         }
1609
1610         if (vol_args->flags & BTRFS_SUBVOL_CREATE_ASYNC)
1611                 ptr = &transid;
1612         if (vol_args->flags & BTRFS_SUBVOL_RDONLY)
1613                 readonly = true;
1614         if (vol_args->flags & BTRFS_SUBVOL_QGROUP_INHERIT) {
1615                 if (vol_args->size > PAGE_CACHE_SIZE) {
1616                         ret = -EINVAL;
1617                         goto out;
1618                 }
1619                 inherit = memdup_user(vol_args->qgroup_inherit, vol_args->size);
1620                 if (IS_ERR(inherit)) {
1621                         ret = PTR_ERR(inherit);
1622                         goto out;
1623                 }
1624         }
1625
1626         ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
1627                                               vol_args->fd, subvol, ptr,
1628                                               readonly, inherit);
1629
1630         if (ret == 0 && ptr &&
1631             copy_to_user(arg +
1632                          offsetof(struct btrfs_ioctl_vol_args_v2,
1633                                   transid), ptr, sizeof(*ptr)))
1634                 ret = -EFAULT;
1635 out:
1636         kfree(vol_args);
1637         kfree(inherit);
1638         return ret;
1639 }
1640
1641 static noinline int btrfs_ioctl_subvol_getflags(struct file *file,
1642                                                 void __user *arg)
1643 {
1644         struct inode *inode = file_inode(file);
1645         struct btrfs_root *root = BTRFS_I(inode)->root;
1646         int ret = 0;
1647         u64 flags = 0;
1648
1649         if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID)
1650                 return -EINVAL;
1651
1652         down_read(&root->fs_info->subvol_sem);
1653         if (btrfs_root_readonly(root))
1654                 flags |= BTRFS_SUBVOL_RDONLY;
1655         up_read(&root->fs_info->subvol_sem);
1656
1657         if (copy_to_user(arg, &flags, sizeof(flags)))
1658                 ret = -EFAULT;
1659
1660         return ret;
1661 }
1662
1663 static noinline int btrfs_ioctl_subvol_setflags(struct file *file,
1664                                               void __user *arg)
1665 {
1666         struct inode *inode = file_inode(file);
1667         struct btrfs_root *root = BTRFS_I(inode)->root;
1668         struct btrfs_trans_handle *trans;
1669         u64 root_flags;
1670         u64 flags;
1671         int ret = 0;
1672
1673         ret = mnt_want_write_file(file);
1674         if (ret)
1675                 goto out;
1676
1677         if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID) {
1678                 ret = -EINVAL;
1679                 goto out_drop_write;
1680         }
1681
1682         if (copy_from_user(&flags, arg, sizeof(flags))) {
1683                 ret = -EFAULT;
1684                 goto out_drop_write;
1685         }
1686
1687         if (flags & BTRFS_SUBVOL_CREATE_ASYNC) {
1688                 ret = -EINVAL;
1689                 goto out_drop_write;
1690         }
1691
1692         if (flags & ~BTRFS_SUBVOL_RDONLY) {
1693                 ret = -EOPNOTSUPP;
1694                 goto out_drop_write;
1695         }
1696
1697         if (!inode_owner_or_capable(inode)) {
1698                 ret = -EACCES;
1699                 goto out_drop_write;
1700         }
1701
1702         down_write(&root->fs_info->subvol_sem);
1703
1704         /* nothing to do */
1705         if (!!(flags & BTRFS_SUBVOL_RDONLY) == btrfs_root_readonly(root))
1706                 goto out_drop_sem;
1707
1708         root_flags = btrfs_root_flags(&root->root_item);
1709         if (flags & BTRFS_SUBVOL_RDONLY) {
1710                 btrfs_set_root_flags(&root->root_item,
1711                                      root_flags | BTRFS_ROOT_SUBVOL_RDONLY);
1712         } else {
1713                 /*
1714                  * Block RO -> RW transition if this subvolume is involved in
1715                  * send
1716                  */
1717                 spin_lock(&root->root_item_lock);
1718                 if (root->send_in_progress == 0) {
1719                         btrfs_set_root_flags(&root->root_item,
1720                                      root_flags & ~BTRFS_ROOT_SUBVOL_RDONLY);
1721                         spin_unlock(&root->root_item_lock);
1722                 } else {
1723                         spin_unlock(&root->root_item_lock);
1724                         btrfs_warn(root->fs_info,
1725                         "Attempt to set subvolume %llu read-write during send",
1726                                         root->root_key.objectid);
1727                         ret = -EPERM;
1728                         goto out_drop_sem;
1729                 }
1730         }
1731
1732         trans = btrfs_start_transaction(root, 1);
1733         if (IS_ERR(trans)) {
1734                 ret = PTR_ERR(trans);
1735                 goto out_reset;
1736         }
1737
1738         ret = btrfs_update_root(trans, root->fs_info->tree_root,
1739                                 &root->root_key, &root->root_item);
1740
1741         btrfs_commit_transaction(trans, root);
1742 out_reset:
1743         if (ret)
1744                 btrfs_set_root_flags(&root->root_item, root_flags);
1745 out_drop_sem:
1746         up_write(&root->fs_info->subvol_sem);
1747 out_drop_write:
1748         mnt_drop_write_file(file);
1749 out:
1750         return ret;
1751 }
1752
1753 /*
1754  * helper to check if the subvolume references other subvolumes
1755  */
1756 static noinline int may_destroy_subvol(struct btrfs_root *root)
1757 {
1758         struct btrfs_path *path;
1759         struct btrfs_dir_item *di;
1760         struct btrfs_key key;
1761         u64 dir_id;
1762         int ret;
1763
1764         path = btrfs_alloc_path();
1765         if (!path)
1766                 return -ENOMEM;
1767
1768         /* Make sure this root isn't set as the default subvol */
1769         dir_id = btrfs_super_root_dir(root->fs_info->super_copy);
1770         di = btrfs_lookup_dir_item(NULL, root->fs_info->tree_root, path,
1771                                    dir_id, "default", 7, 0);
1772         if (di && !IS_ERR(di)) {
1773                 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
1774                 if (key.objectid == root->root_key.objectid) {
1775                         ret = -ENOTEMPTY;
1776                         goto out;
1777                 }
1778                 btrfs_release_path(path);
1779         }
1780
1781         key.objectid = root->root_key.objectid;
1782         key.type = BTRFS_ROOT_REF_KEY;
1783         key.offset = (u64)-1;
1784
1785         ret = btrfs_search_slot(NULL, root->fs_info->tree_root,
1786                                 &key, path, 0, 0);
1787         if (ret < 0)
1788                 goto out;
1789         BUG_ON(ret == 0);
1790
1791         ret = 0;
1792         if (path->slots[0] > 0) {
1793                 path->slots[0]--;
1794                 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1795                 if (key.objectid == root->root_key.objectid &&
1796                     key.type == BTRFS_ROOT_REF_KEY)
1797                         ret = -ENOTEMPTY;
1798         }
1799 out:
1800         btrfs_free_path(path);
1801         return ret;
1802 }
1803
1804 static noinline int key_in_sk(struct btrfs_key *key,
1805                               struct btrfs_ioctl_search_key *sk)
1806 {
1807         struct btrfs_key test;
1808         int ret;
1809
1810         test.objectid = sk->min_objectid;
1811         test.type = sk->min_type;
1812         test.offset = sk->min_offset;
1813
1814         ret = btrfs_comp_cpu_keys(key, &test);
1815         if (ret < 0)
1816                 return 0;
1817
1818         test.objectid = sk->max_objectid;
1819         test.type = sk->max_type;
1820         test.offset = sk->max_offset;
1821
1822         ret = btrfs_comp_cpu_keys(key, &test);
1823         if (ret > 0)
1824                 return 0;
1825         return 1;
1826 }
1827
1828 static noinline int copy_to_sk(struct btrfs_root *root,
1829                                struct btrfs_path *path,
1830                                struct btrfs_key *key,
1831                                struct btrfs_ioctl_search_key *sk,
1832                                char *buf,
1833                                unsigned long *sk_offset,
1834                                int *num_found)
1835 {
1836         u64 found_transid;
1837         struct extent_buffer *leaf;
1838         struct btrfs_ioctl_search_header sh;
1839         unsigned long item_off;
1840         unsigned long item_len;
1841         int nritems;
1842         int i;
1843         int slot;
1844         int ret = 0;
1845
1846         leaf = path->nodes[0];
1847         slot = path->slots[0];
1848         nritems = btrfs_header_nritems(leaf);
1849
1850         if (btrfs_header_generation(leaf) > sk->max_transid) {
1851                 i = nritems;
1852                 goto advance_key;
1853         }
1854         found_transid = btrfs_header_generation(leaf);
1855
1856         for (i = slot; i < nritems; i++) {
1857                 item_off = btrfs_item_ptr_offset(leaf, i);
1858                 item_len = btrfs_item_size_nr(leaf, i);
1859
1860                 btrfs_item_key_to_cpu(leaf, key, i);
1861                 if (!key_in_sk(key, sk))
1862                         continue;
1863
1864                 if (sizeof(sh) + item_len > BTRFS_SEARCH_ARGS_BUFSIZE)
1865                         item_len = 0;
1866
1867                 if (sizeof(sh) + item_len + *sk_offset >
1868                     BTRFS_SEARCH_ARGS_BUFSIZE) {
1869                         ret = 1;
1870                         goto overflow;
1871                 }
1872
1873                 sh.objectid = key->objectid;
1874                 sh.offset = key->offset;
1875                 sh.type = key->type;
1876                 sh.len = item_len;
1877                 sh.transid = found_transid;
1878
1879                 /* copy search result header */
1880                 memcpy(buf + *sk_offset, &sh, sizeof(sh));
1881                 *sk_offset += sizeof(sh);
1882
1883                 if (item_len) {
1884                         char *p = buf + *sk_offset;
1885                         /* copy the item */
1886                         read_extent_buffer(leaf, p,
1887                                            item_off, item_len);
1888                         *sk_offset += item_len;
1889                 }
1890                 (*num_found)++;
1891
1892                 if (*num_found >= sk->nr_items)
1893                         break;
1894         }
1895 advance_key:
1896         ret = 0;
1897         if (key->offset < (u64)-1 && key->offset < sk->max_offset)
1898                 key->offset++;
1899         else if (key->type < (u8)-1 && key->type < sk->max_type) {
1900                 key->offset = 0;
1901                 key->type++;
1902         } else if (key->objectid < (u64)-1 && key->objectid < sk->max_objectid) {
1903                 key->offset = 0;
1904                 key->type = 0;
1905                 key->objectid++;
1906         } else
1907                 ret = 1;
1908 overflow:
1909         return ret;
1910 }
1911
1912 static noinline int search_ioctl(struct inode *inode,
1913                                  struct btrfs_ioctl_search_args *args)
1914 {
1915         struct btrfs_root *root;
1916         struct btrfs_key key;
1917         struct btrfs_path *path;
1918         struct btrfs_ioctl_search_key *sk = &args->key;
1919         struct btrfs_fs_info *info = BTRFS_I(inode)->root->fs_info;
1920         int ret;
1921         int num_found = 0;
1922         unsigned long sk_offset = 0;
1923
1924         path = btrfs_alloc_path();
1925         if (!path)
1926                 return -ENOMEM;
1927
1928         if (sk->tree_id == 0) {
1929                 /* search the root of the inode that was passed */
1930                 root = BTRFS_I(inode)->root;
1931         } else {
1932                 key.objectid = sk->tree_id;
1933                 key.type = BTRFS_ROOT_ITEM_KEY;
1934                 key.offset = (u64)-1;
1935                 root = btrfs_read_fs_root_no_name(info, &key);
1936                 if (IS_ERR(root)) {
1937                         printk(KERN_ERR "could not find root %llu\n",
1938                                sk->tree_id);
1939                         btrfs_free_path(path);
1940                         return -ENOENT;
1941                 }
1942         }
1943
1944         key.objectid = sk->min_objectid;
1945         key.type = sk->min_type;
1946         key.offset = sk->min_offset;
1947
1948         path->keep_locks = 1;
1949
1950         while (1) {
1951                 ret = btrfs_search_forward(root, &key, path, sk->min_transid);
1952                 if (ret != 0) {
1953                         if (ret > 0)
1954                                 ret = 0;
1955                         goto err;
1956                 }
1957                 ret = copy_to_sk(root, path, &key, sk, args->buf,
1958                                  &sk_offset, &num_found);
1959                 btrfs_release_path(path);
1960                 if (ret || num_found >= sk->nr_items)
1961                         break;
1962
1963         }
1964         ret = 0;
1965 err:
1966         sk->nr_items = num_found;
1967         btrfs_free_path(path);
1968         return ret;
1969 }
1970
1971 static noinline int btrfs_ioctl_tree_search(struct file *file,
1972                                            void __user *argp)
1973 {
1974          struct btrfs_ioctl_search_args *args;
1975          struct inode *inode;
1976          int ret;
1977
1978         if (!capable(CAP_SYS_ADMIN))
1979                 return -EPERM;
1980
1981         args = memdup_user(argp, sizeof(*args));
1982         if (IS_ERR(args))
1983                 return PTR_ERR(args);
1984
1985         inode = file_inode(file);
1986         ret = search_ioctl(inode, args);
1987         if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
1988                 ret = -EFAULT;
1989         kfree(args);
1990         return ret;
1991 }
1992
1993 /*
1994  * Search INODE_REFs to identify path name of 'dirid' directory
1995  * in a 'tree_id' tree. and sets path name to 'name'.
1996  */
1997 static noinline int btrfs_search_path_in_tree(struct btrfs_fs_info *info,
1998                                 u64 tree_id, u64 dirid, char *name)
1999 {
2000         struct btrfs_root *root;
2001         struct btrfs_key key;
2002         char *ptr;
2003         int ret = -1;
2004         int slot;
2005         int len;
2006         int total_len = 0;
2007         struct btrfs_inode_ref *iref;
2008         struct extent_buffer *l;
2009         struct btrfs_path *path;
2010
2011         if (dirid == BTRFS_FIRST_FREE_OBJECTID) {
2012                 name[0]='\0';
2013                 return 0;
2014         }
2015
2016         path = btrfs_alloc_path();
2017         if (!path)
2018                 return -ENOMEM;
2019
2020         ptr = &name[BTRFS_INO_LOOKUP_PATH_MAX];
2021
2022         key.objectid = tree_id;
2023         key.type = BTRFS_ROOT_ITEM_KEY;
2024         key.offset = (u64)-1;
2025         root = btrfs_read_fs_root_no_name(info, &key);
2026         if (IS_ERR(root)) {
2027                 printk(KERN_ERR "could not find root %llu\n", tree_id);
2028                 ret = -ENOENT;
2029                 goto out;
2030         }
2031
2032         key.objectid = dirid;
2033         key.type = BTRFS_INODE_REF_KEY;
2034         key.offset = (u64)-1;
2035
2036         while (1) {
2037                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2038                 if (ret < 0)
2039                         goto out;
2040                 else if (ret > 0) {
2041                         ret = btrfs_previous_item(root, path, dirid,
2042                                                   BTRFS_INODE_REF_KEY);
2043                         if (ret < 0)
2044                                 goto out;
2045                         else if (ret > 0) {
2046                                 ret = -ENOENT;
2047                                 goto out;
2048                         }
2049                 }
2050
2051                 l = path->nodes[0];
2052                 slot = path->slots[0];
2053                 btrfs_item_key_to_cpu(l, &key, slot);
2054
2055                 iref = btrfs_item_ptr(l, slot, struct btrfs_inode_ref);
2056                 len = btrfs_inode_ref_name_len(l, iref);
2057                 ptr -= len + 1;
2058                 total_len += len + 1;
2059                 if (ptr < name) {
2060                         ret = -ENAMETOOLONG;
2061                         goto out;
2062                 }
2063
2064                 *(ptr + len) = '/';
2065                 read_extent_buffer(l, ptr, (unsigned long)(iref + 1), len);
2066
2067                 if (key.offset == BTRFS_FIRST_FREE_OBJECTID)
2068                         break;
2069
2070                 btrfs_release_path(path);
2071                 key.objectid = key.offset;
2072                 key.offset = (u64)-1;
2073                 dirid = key.objectid;
2074         }
2075         memmove(name, ptr, total_len);
2076         name[total_len] = '\0';
2077         ret = 0;
2078 out:
2079         btrfs_free_path(path);
2080         return ret;
2081 }
2082
2083 static noinline int btrfs_ioctl_ino_lookup(struct file *file,
2084                                            void __user *argp)
2085 {
2086          struct btrfs_ioctl_ino_lookup_args *args;
2087          struct inode *inode;
2088          int ret;
2089
2090         if (!capable(CAP_SYS_ADMIN))
2091                 return -EPERM;
2092
2093         args = memdup_user(argp, sizeof(*args));
2094         if (IS_ERR(args))
2095                 return PTR_ERR(args);
2096
2097         inode = file_inode(file);
2098
2099         if (args->treeid == 0)
2100                 args->treeid = BTRFS_I(inode)->root->root_key.objectid;
2101
2102         ret = btrfs_search_path_in_tree(BTRFS_I(inode)->root->fs_info,
2103                                         args->treeid, args->objectid,
2104                                         args->name);
2105
2106         if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
2107                 ret = -EFAULT;
2108
2109         kfree(args);
2110         return ret;
2111 }
2112
2113 static noinline int btrfs_ioctl_snap_destroy(struct file *file,
2114                                              void __user *arg)
2115 {
2116         struct dentry *parent = file->f_path.dentry;
2117         struct dentry *dentry;
2118         struct inode *dir = parent->d_inode;
2119         struct inode *inode;
2120         struct btrfs_root *root = BTRFS_I(dir)->root;
2121         struct btrfs_root *dest = NULL;
2122         struct btrfs_ioctl_vol_args *vol_args;
2123         struct btrfs_trans_handle *trans;
2124         struct btrfs_block_rsv block_rsv;
2125         u64 qgroup_reserved;
2126         int namelen;
2127         int ret;
2128         int err = 0;
2129
2130         vol_args = memdup_user(arg, sizeof(*vol_args));
2131         if (IS_ERR(vol_args))
2132                 return PTR_ERR(vol_args);
2133
2134         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
2135         namelen = strlen(vol_args->name);
2136         if (strchr(vol_args->name, '/') ||
2137             strncmp(vol_args->name, "..", namelen) == 0) {
2138                 err = -EINVAL;
2139                 goto out;
2140         }
2141
2142         err = mnt_want_write_file(file);
2143         if (err)
2144                 goto out;
2145
2146         err = mutex_lock_killable_nested(&dir->i_mutex, I_MUTEX_PARENT);
2147         if (err == -EINTR)
2148                 goto out_drop_write;
2149         dentry = lookup_one_len(vol_args->name, parent, namelen);
2150         if (IS_ERR(dentry)) {
2151                 err = PTR_ERR(dentry);
2152                 goto out_unlock_dir;
2153         }
2154
2155         if (!dentry->d_inode) {
2156                 err = -ENOENT;
2157                 goto out_dput;
2158         }
2159
2160         inode = dentry->d_inode;
2161         dest = BTRFS_I(inode)->root;
2162         if (!capable(CAP_SYS_ADMIN)) {
2163                 /*
2164                  * Regular user.  Only allow this with a special mount
2165                  * option, when the user has write+exec access to the
2166                  * subvol root, and when rmdir(2) would have been
2167                  * allowed.
2168                  *
2169                  * Note that this is _not_ check that the subvol is
2170                  * empty or doesn't contain data that we wouldn't
2171                  * otherwise be able to delete.
2172                  *
2173                  * Users who want to delete empty subvols should try
2174                  * rmdir(2).
2175                  */
2176                 err = -EPERM;
2177                 if (!btrfs_test_opt(root, USER_SUBVOL_RM_ALLOWED))
2178                         goto out_dput;
2179
2180                 /*
2181                  * Do not allow deletion if the parent dir is the same
2182                  * as the dir to be deleted.  That means the ioctl
2183                  * must be called on the dentry referencing the root
2184                  * of the subvol, not a random directory contained
2185                  * within it.
2186                  */
2187                 err = -EINVAL;
2188                 if (root == dest)
2189                         goto out_dput;
2190
2191                 err = inode_permission(inode, MAY_WRITE | MAY_EXEC);
2192                 if (err)
2193                         goto out_dput;
2194         }
2195
2196         /* check if subvolume may be deleted by a user */
2197         err = btrfs_may_delete(dir, dentry, 1);
2198         if (err)
2199                 goto out_dput;
2200
2201         if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID) {
2202                 err = -EINVAL;
2203                 goto out_dput;
2204         }
2205
2206         mutex_lock(&inode->i_mutex);
2207         err = d_invalidate(dentry);
2208         if (err)
2209                 goto out_unlock;
2210
2211         down_write(&root->fs_info->subvol_sem);
2212
2213         err = may_destroy_subvol(dest);
2214         if (err)
2215                 goto out_up_write;
2216
2217         btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
2218         /*
2219          * One for dir inode, two for dir entries, two for root
2220          * ref/backref.
2221          */
2222         err = btrfs_subvolume_reserve_metadata(root, &block_rsv,
2223                                                5, &qgroup_reserved, true);
2224         if (err)
2225                 goto out_up_write;
2226
2227         trans = btrfs_start_transaction(root, 0);
2228         if (IS_ERR(trans)) {
2229                 err = PTR_ERR(trans);
2230                 goto out_release;
2231         }
2232         trans->block_rsv = &block_rsv;
2233         trans->bytes_reserved = block_rsv.size;
2234
2235         ret = btrfs_unlink_subvol(trans, root, dir,
2236                                 dest->root_key.objectid,
2237                                 dentry->d_name.name,
2238                                 dentry->d_name.len);
2239         if (ret) {
2240                 err = ret;
2241                 btrfs_abort_transaction(trans, root, ret);
2242                 goto out_end_trans;
2243         }
2244
2245         btrfs_record_root_in_trans(trans, dest);
2246
2247         memset(&dest->root_item.drop_progress, 0,
2248                 sizeof(dest->root_item.drop_progress));
2249         dest->root_item.drop_level = 0;
2250         btrfs_set_root_refs(&dest->root_item, 0);
2251
2252         if (!xchg(&dest->orphan_item_inserted, 1)) {
2253                 ret = btrfs_insert_orphan_item(trans,
2254                                         root->fs_info->tree_root,
2255                                         dest->root_key.objectid);
2256                 if (ret) {
2257                         btrfs_abort_transaction(trans, root, ret);
2258                         err = ret;
2259                         goto out_end_trans;
2260                 }
2261         }
2262
2263         ret = btrfs_uuid_tree_rem(trans, root->fs_info->uuid_root,
2264                                   dest->root_item.uuid, BTRFS_UUID_KEY_SUBVOL,
2265                                   dest->root_key.objectid);
2266         if (ret && ret != -ENOENT) {
2267                 btrfs_abort_transaction(trans, root, ret);
2268                 err = ret;
2269                 goto out_end_trans;
2270         }
2271         if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
2272                 ret = btrfs_uuid_tree_rem(trans, root->fs_info->uuid_root,
2273                                           dest->root_item.received_uuid,
2274                                           BTRFS_UUID_KEY_RECEIVED_SUBVOL,
2275                                           dest->root_key.objectid);
2276                 if (ret && ret != -ENOENT) {
2277                         btrfs_abort_transaction(trans, root, ret);
2278                         err = ret;
2279                         goto out_end_trans;
2280                 }
2281         }
2282
2283 out_end_trans:
2284         trans->block_rsv = NULL;
2285         trans->bytes_reserved = 0;
2286         ret = btrfs_end_transaction(trans, root);
2287         if (ret && !err)
2288                 err = ret;
2289         inode->i_flags |= S_DEAD;
2290 out_release:
2291         btrfs_subvolume_release_metadata(root, &block_rsv, qgroup_reserved);
2292 out_up_write:
2293         up_write(&root->fs_info->subvol_sem);
2294 out_unlock:
2295         mutex_unlock(&inode->i_mutex);
2296         if (!err) {
2297                 shrink_dcache_sb(root->fs_info->sb);
2298                 btrfs_invalidate_inodes(dest);
2299                 d_delete(dentry);
2300
2301                 /* the last ref */
2302                 if (dest->cache_inode) {
2303                         iput(dest->cache_inode);
2304                         dest->cache_inode = NULL;
2305                 }
2306         }
2307 out_dput:
2308         dput(dentry);
2309 out_unlock_dir:
2310         mutex_unlock(&dir->i_mutex);
2311 out_drop_write:
2312         mnt_drop_write_file(file);
2313 out:
2314         kfree(vol_args);
2315         return err;
2316 }
2317
2318 static int btrfs_ioctl_defrag(struct file *file, void __user *argp)
2319 {
2320         struct inode *inode = file_inode(file);
2321         struct btrfs_root *root = BTRFS_I(inode)->root;
2322         struct btrfs_ioctl_defrag_range_args *range;
2323         int ret;
2324
2325         ret = mnt_want_write_file(file);
2326         if (ret)
2327                 return ret;
2328
2329         if (btrfs_root_readonly(root)) {
2330                 ret = -EROFS;
2331                 goto out;
2332         }
2333
2334         switch (inode->i_mode & S_IFMT) {
2335         case S_IFDIR:
2336                 if (!capable(CAP_SYS_ADMIN)) {
2337                         ret = -EPERM;
2338                         goto out;
2339                 }
2340                 ret = btrfs_defrag_root(root);
2341                 if (ret)
2342                         goto out;
2343                 ret = btrfs_defrag_root(root->fs_info->extent_root);
2344                 break;
2345         case S_IFREG:
2346                 if (!(file->f_mode & FMODE_WRITE)) {
2347                         ret = -EINVAL;
2348                         goto out;
2349                 }
2350
2351                 range = kzalloc(sizeof(*range), GFP_KERNEL);
2352                 if (!range) {
2353                         ret = -ENOMEM;
2354                         goto out;
2355                 }
2356
2357                 if (argp) {
2358                         if (copy_from_user(range, argp,
2359                                            sizeof(*range))) {
2360                                 ret = -EFAULT;
2361                                 kfree(range);
2362                                 goto out;
2363                         }
2364                         /* compression requires us to start the IO */
2365                         if ((range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)) {
2366                                 range->flags |= BTRFS_DEFRAG_RANGE_START_IO;
2367                                 range->extent_thresh = (u32)-1;
2368                         }
2369                 } else {
2370                         /* the rest are all set to zero by kzalloc */
2371                         range->len = (u64)-1;
2372                 }
2373                 ret = btrfs_defrag_file(file_inode(file), file,
2374                                         range, 0, 0);
2375                 if (ret > 0)
2376                         ret = 0;
2377                 kfree(range);
2378                 break;
2379         default:
2380                 ret = -EINVAL;
2381         }
2382 out:
2383         mnt_drop_write_file(file);
2384         return ret;
2385 }
2386
2387 static long btrfs_ioctl_add_dev(struct btrfs_root *root, void __user *arg)
2388 {
2389         struct btrfs_ioctl_vol_args *vol_args;
2390         int ret;
2391
2392         if (!capable(CAP_SYS_ADMIN))
2393                 return -EPERM;
2394
2395         if (atomic_xchg(&root->fs_info->mutually_exclusive_operation_running,
2396                         1)) {
2397                 return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
2398         }
2399
2400         mutex_lock(&root->fs_info->volume_mutex);
2401         vol_args = memdup_user(arg, sizeof(*vol_args));
2402         if (IS_ERR(vol_args)) {
2403                 ret = PTR_ERR(vol_args);
2404                 goto out;
2405         }
2406
2407         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
2408         ret = btrfs_init_new_device(root, vol_args->name);
2409
2410         kfree(vol_args);
2411 out:
2412         mutex_unlock(&root->fs_info->volume_mutex);
2413         atomic_set(&root->fs_info->mutually_exclusive_operation_running, 0);
2414         return ret;
2415 }
2416
2417 static long btrfs_ioctl_rm_dev(struct file *file, void __user *arg)
2418 {
2419         struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
2420         struct btrfs_ioctl_vol_args *vol_args;
2421         int ret;
2422
2423         if (!capable(CAP_SYS_ADMIN))
2424                 return -EPERM;
2425
2426         ret = mnt_want_write_file(file);
2427         if (ret)
2428                 return ret;
2429
2430         vol_args = memdup_user(arg, sizeof(*vol_args));
2431         if (IS_ERR(vol_args)) {
2432                 ret = PTR_ERR(vol_args);
2433                 goto out;
2434         }
2435
2436         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
2437
2438         if (atomic_xchg(&root->fs_info->mutually_exclusive_operation_running,
2439                         1)) {
2440                 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
2441                 goto out;
2442         }
2443
2444         mutex_lock(&root->fs_info->volume_mutex);
2445         ret = btrfs_rm_device(root, vol_args->name);
2446         mutex_unlock(&root->fs_info->volume_mutex);
2447         atomic_set(&root->fs_info->mutually_exclusive_operation_running, 0);
2448
2449 out:
2450         kfree(vol_args);
2451         mnt_drop_write_file(file);
2452         return ret;
2453 }
2454
2455 static long btrfs_ioctl_fs_info(struct btrfs_root *root, void __user *arg)
2456 {
2457         struct btrfs_ioctl_fs_info_args *fi_args;
2458         struct btrfs_device *device;
2459         struct btrfs_device *next;
2460         struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
2461         int ret = 0;
2462
2463         if (!capable(CAP_SYS_ADMIN))
2464                 return -EPERM;
2465
2466         fi_args = kzalloc(sizeof(*fi_args), GFP_KERNEL);
2467         if (!fi_args)
2468                 return -ENOMEM;
2469
2470         mutex_lock(&fs_devices->device_list_mutex);
2471         fi_args->num_devices = fs_devices->num_devices;
2472         memcpy(&fi_args->fsid, root->fs_info->fsid, sizeof(fi_args->fsid));
2473
2474         list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
2475                 if (device->devid > fi_args->max_id)
2476                         fi_args->max_id = device->devid;
2477         }
2478         mutex_unlock(&fs_devices->device_list_mutex);
2479
2480         if (copy_to_user(arg, fi_args, sizeof(*fi_args)))
2481                 ret = -EFAULT;
2482
2483         kfree(fi_args);
2484         return ret;
2485 }
2486
2487 static long btrfs_ioctl_dev_info(struct btrfs_root *root, void __user *arg)
2488 {
2489         struct btrfs_ioctl_dev_info_args *di_args;
2490         struct btrfs_device *dev;
2491         struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
2492         int ret = 0;
2493         char *s_uuid = NULL;
2494
2495         if (!capable(CAP_SYS_ADMIN))
2496                 return -EPERM;
2497
2498         di_args = memdup_user(arg, sizeof(*di_args));
2499         if (IS_ERR(di_args))
2500                 return PTR_ERR(di_args);
2501
2502         if (!btrfs_is_empty_uuid(di_args->uuid))
2503                 s_uuid = di_args->uuid;
2504
2505         mutex_lock(&fs_devices->device_list_mutex);
2506         dev = btrfs_find_device(root->fs_info, di_args->devid, s_uuid, NULL);
2507
2508         if (!dev) {
2509                 ret = -ENODEV;
2510                 goto out;
2511         }
2512
2513         di_args->devid = dev->devid;
2514         di_args->bytes_used = dev->bytes_used;
2515         di_args->total_bytes = dev->total_bytes;
2516         memcpy(di_args->uuid, dev->uuid, sizeof(di_args->uuid));
2517         if (dev->name) {
2518                 struct rcu_string *name;
2519
2520                 rcu_read_lock();
2521                 name = rcu_dereference(dev->name);
2522                 strncpy(di_args->path, name->str, sizeof(di_args->path));
2523                 rcu_read_unlock();
2524                 di_args->path[sizeof(di_args->path) - 1] = 0;
2525         } else {
2526                 di_args->path[0] = '\0';
2527         }
2528
2529 out:
2530         mutex_unlock(&fs_devices->device_list_mutex);
2531         if (ret == 0 && copy_to_user(arg, di_args, sizeof(*di_args)))
2532                 ret = -EFAULT;
2533
2534         kfree(di_args);
2535         return ret;
2536 }
2537
2538 static struct page *extent_same_get_page(struct inode *inode, u64 off)
2539 {
2540         struct page *page;
2541         pgoff_t index;
2542         struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
2543
2544         index = off >> PAGE_CACHE_SHIFT;
2545
2546         page = grab_cache_page(inode->i_mapping, index);
2547         if (!page)
2548                 return NULL;
2549
2550         if (!PageUptodate(page)) {
2551                 if (extent_read_full_page_nolock(tree, page, btrfs_get_extent,
2552                                                  0))
2553                         return NULL;
2554                 lock_page(page);
2555                 if (!PageUptodate(page)) {
2556                         unlock_page(page);
2557                         page_cache_release(page);
2558                         return NULL;
2559                 }
2560         }
2561         unlock_page(page);
2562
2563         return page;
2564 }
2565
2566 static inline void lock_extent_range(struct inode *inode, u64 off, u64 len)
2567 {
2568         /* do any pending delalloc/csum calc on src, one way or
2569            another, and lock file content */
2570         while (1) {
2571                 struct btrfs_ordered_extent *ordered;
2572                 lock_extent(&BTRFS_I(inode)->io_tree, off, off + len - 1);
2573                 ordered = btrfs_lookup_first_ordered_extent(inode,
2574                                                             off + len - 1);
2575                 if (!ordered &&
2576                     !test_range_bit(&BTRFS_I(inode)->io_tree, off,
2577                                     off + len - 1, EXTENT_DELALLOC, 0, NULL))
2578                         break;
2579                 unlock_extent(&BTRFS_I(inode)->io_tree, off, off + len - 1);
2580                 if (ordered)
2581                         btrfs_put_ordered_extent(ordered);
2582                 btrfs_wait_ordered_range(inode, off, len);
2583         }
2584 }
2585
2586 static void btrfs_double_unlock(struct inode *inode1, u64 loff1,
2587                                 struct inode *inode2, u64 loff2, u64 len)
2588 {
2589         unlock_extent(&BTRFS_I(inode1)->io_tree, loff1, loff1 + len - 1);
2590         unlock_extent(&BTRFS_I(inode2)->io_tree, loff2, loff2 + len - 1);
2591
2592         mutex_unlock(&inode1->i_mutex);
2593         mutex_unlock(&inode2->i_mutex);
2594 }
2595
2596 static void btrfs_double_lock(struct inode *inode1, u64 loff1,
2597                               struct inode *inode2, u64 loff2, u64 len)
2598 {
2599         if (inode1 < inode2) {
2600                 swap(inode1, inode2);
2601                 swap(loff1, loff2);
2602         }
2603
2604         mutex_lock_nested(&inode1->i_mutex, I_MUTEX_PARENT);
2605         lock_extent_range(inode1, loff1, len);
2606         if (inode1 != inode2) {
2607                 mutex_lock_nested(&inode2->i_mutex, I_MUTEX_CHILD);
2608                 lock_extent_range(inode2, loff2, len);
2609         }
2610 }
2611
2612 static int btrfs_cmp_data(struct inode *src, u64 loff, struct inode *dst,
2613                           u64 dst_loff, u64 len)
2614 {
2615         int ret = 0;
2616         struct page *src_page, *dst_page;
2617         unsigned int cmp_len = PAGE_CACHE_SIZE;
2618         void *addr, *dst_addr;
2619
2620         while (len) {
2621                 if (len < PAGE_CACHE_SIZE)
2622                         cmp_len = len;
2623
2624                 src_page = extent_same_get_page(src, loff);
2625                 if (!src_page)
2626                         return -EINVAL;
2627                 dst_page = extent_same_get_page(dst, dst_loff);
2628                 if (!dst_page) {
2629                         page_cache_release(src_page);
2630                         return -EINVAL;
2631                 }
2632                 addr = kmap_atomic(src_page);
2633                 dst_addr = kmap_atomic(dst_page);
2634
2635                 flush_dcache_page(src_page);
2636                 flush_dcache_page(dst_page);
2637
2638                 if (memcmp(addr, dst_addr, cmp_len))
2639                         ret = BTRFS_SAME_DATA_DIFFERS;
2640
2641                 kunmap_atomic(addr);
2642                 kunmap_atomic(dst_addr);
2643                 page_cache_release(src_page);
2644                 page_cache_release(dst_page);
2645
2646                 if (ret)
2647                         break;
2648
2649                 loff += cmp_len;
2650                 dst_loff += cmp_len;
2651                 len -= cmp_len;
2652         }
2653
2654         return ret;
2655 }
2656
2657 static int extent_same_check_offsets(struct inode *inode, u64 off, u64 len)
2658 {
2659         u64 bs = BTRFS_I(inode)->root->fs_info->sb->s_blocksize;
2660
2661         if (off + len > inode->i_size || off + len < off)
2662                 return -EINVAL;
2663         /* Check that we are block aligned - btrfs_clone() requires this */
2664         if (!IS_ALIGNED(off, bs) || !IS_ALIGNED(off + len, bs))
2665                 return -EINVAL;
2666
2667         return 0;
2668 }
2669
2670 static int btrfs_extent_same(struct inode *src, u64 loff, u64 len,
2671                              struct inode *dst, u64 dst_loff)
2672 {
2673         int ret;
2674
2675         /*
2676          * btrfs_clone() can't handle extents in the same file
2677          * yet. Once that works, we can drop this check and replace it
2678          * with a check for the same inode, but overlapping extents.
2679          */
2680         if (src == dst)
2681                 return -EINVAL;
2682
2683         btrfs_double_lock(src, loff, dst, dst_loff, len);
2684
2685         ret = extent_same_check_offsets(src, loff, len);
2686         if (ret)
2687                 goto out_unlock;
2688
2689         ret = extent_same_check_offsets(dst, dst_loff, len);
2690         if (ret)
2691                 goto out_unlock;
2692
2693         /* don't make the dst file partly checksummed */
2694         if ((BTRFS_I(src)->flags & BTRFS_INODE_NODATASUM) !=
2695             (BTRFS_I(dst)->flags & BTRFS_INODE_NODATASUM)) {
2696                 ret = -EINVAL;
2697                 goto out_unlock;
2698         }
2699
2700         ret = btrfs_cmp_data(src, loff, dst, dst_loff, len);
2701         if (ret == 0)
2702                 ret = btrfs_clone(src, dst, loff, len, len, dst_loff);
2703
2704 out_unlock:
2705         btrfs_double_unlock(src, loff, dst, dst_loff, len);
2706
2707         return ret;
2708 }
2709
2710 #define BTRFS_MAX_DEDUPE_LEN    (16 * 1024 * 1024)
2711
2712 static long btrfs_ioctl_file_extent_same(struct file *file,
2713                                          void __user *argp)
2714 {
2715         struct btrfs_ioctl_same_args tmp;
2716         struct btrfs_ioctl_same_args *same;
2717         struct btrfs_ioctl_same_extent_info *info;
2718         struct inode *src = file->f_dentry->d_inode;
2719         struct file *dst_file = NULL;
2720         struct inode *dst;
2721         u64 off;
2722         u64 len;
2723         int i;
2724         int ret;
2725         unsigned long size;
2726         u64 bs = BTRFS_I(src)->root->fs_info->sb->s_blocksize;
2727         bool is_admin = capable(CAP_SYS_ADMIN);
2728
2729         if (!(file->f_mode & FMODE_READ))
2730                 return -EINVAL;
2731
2732         ret = mnt_want_write_file(file);
2733         if (ret)
2734                 return ret;
2735
2736         if (copy_from_user(&tmp,
2737                            (struct btrfs_ioctl_same_args __user *)argp,
2738                            sizeof(tmp))) {
2739                 ret = -EFAULT;
2740                 goto out;
2741         }
2742
2743         size = sizeof(tmp) +
2744                 tmp.dest_count * sizeof(struct btrfs_ioctl_same_extent_info);
2745
2746         same = memdup_user((struct btrfs_ioctl_same_args __user *)argp, size);
2747
2748         if (IS_ERR(same)) {
2749                 ret = PTR_ERR(same);
2750                 goto out;
2751         }
2752
2753         off = same->logical_offset;
2754         len = same->length;
2755
2756         /*
2757          * Limit the total length we will dedupe for each operation.
2758          * This is intended to bound the total time spent in this
2759          * ioctl to something sane.
2760          */
2761         if (len > BTRFS_MAX_DEDUPE_LEN)
2762                 len = BTRFS_MAX_DEDUPE_LEN;
2763
2764         if (WARN_ON_ONCE(bs < PAGE_CACHE_SIZE)) {
2765                 /*
2766                  * Btrfs does not support blocksize < page_size. As a
2767                  * result, btrfs_cmp_data() won't correctly handle
2768                  * this situation without an update.
2769                  */
2770                 ret = -EINVAL;
2771                 goto out;
2772         }
2773
2774         ret = -EISDIR;
2775         if (S_ISDIR(src->i_mode))
2776                 goto out;
2777
2778         ret = -EACCES;
2779         if (!S_ISREG(src->i_mode))
2780                 goto out;
2781
2782         /* pre-format output fields to sane values */
2783         for (i = 0; i < same->dest_count; i++) {
2784                 same->info[i].bytes_deduped = 0ULL;
2785                 same->info[i].status = 0;
2786         }
2787
2788         ret = 0;
2789         for (i = 0; i < same->dest_count; i++) {
2790                 info = &same->info[i];
2791
2792                 dst_file = fget(info->fd);
2793                 if (!dst_file) {
2794                         info->status = -EBADF;
2795                         goto next;
2796                 }
2797
2798                 if (!(is_admin || (dst_file->f_mode & FMODE_WRITE))) {
2799                         info->status = -EINVAL;
2800                         goto next;
2801                 }
2802
2803                 info->status = -EXDEV;
2804                 if (file->f_path.mnt != dst_file->f_path.mnt)
2805                         goto next;
2806
2807                 dst = dst_file->f_dentry->d_inode;
2808                 if (src->i_sb != dst->i_sb)
2809                         goto next;
2810
2811                 if (S_ISDIR(dst->i_mode)) {
2812                         info->status = -EISDIR;
2813                         goto next;
2814                 }
2815
2816                 if (!S_ISREG(dst->i_mode)) {
2817                         info->status = -EACCES;
2818                         goto next;
2819                 }
2820
2821                 info->status = btrfs_extent_same(src, off, len, dst,
2822                                                 info->logical_offset);
2823                 if (info->status == 0)
2824                         info->bytes_deduped += len;
2825
2826 next:
2827                 if (dst_file)
2828                         fput(dst_file);
2829         }
2830
2831         ret = copy_to_user(argp, same, size);
2832         if (ret)
2833                 ret = -EFAULT;
2834
2835 out:
2836         mnt_drop_write_file(file);
2837         return ret;
2838 }
2839
2840 /**
2841  * btrfs_clone() - clone a range from inode file to another
2842  *
2843  * @src: Inode to clone from
2844  * @inode: Inode to clone to
2845  * @off: Offset within source to start clone from
2846  * @olen: Original length, passed by user, of range to clone
2847  * @olen_aligned: Block-aligned value of olen, extent_same uses
2848  *               identical values here
2849  * @destoff: Offset within @inode to start clone
2850  */
2851 static int btrfs_clone(struct inode *src, struct inode *inode,
2852                        u64 off, u64 olen, u64 olen_aligned, u64 destoff)
2853 {
2854         struct btrfs_root *root = BTRFS_I(inode)->root;
2855         struct btrfs_path *path = NULL;
2856         struct extent_buffer *leaf;
2857         struct btrfs_trans_handle *trans;
2858         char *buf = NULL;
2859         struct btrfs_key key;
2860         u32 nritems;
2861         int slot;
2862         int ret;
2863         u64 len = olen_aligned;
2864
2865         ret = -ENOMEM;
2866         buf = vmalloc(btrfs_level_size(root, 0));
2867         if (!buf)
2868                 return ret;
2869
2870         path = btrfs_alloc_path();
2871         if (!path) {
2872                 vfree(buf);
2873                 return ret;
2874         }
2875
2876         path->reada = 2;
2877         /* clone data */
2878         key.objectid = btrfs_ino(src);
2879         key.type = BTRFS_EXTENT_DATA_KEY;
2880         key.offset = 0;
2881
2882         while (1) {
2883                 /*
2884                  * note the key will change type as we walk through the
2885                  * tree.
2886                  */
2887                 ret = btrfs_search_slot(NULL, BTRFS_I(src)->root, &key, path,
2888                                 0, 0);
2889                 if (ret < 0)
2890                         goto out;
2891
2892                 nritems = btrfs_header_nritems(path->nodes[0]);
2893                 if (path->slots[0] >= nritems) {
2894                         ret = btrfs_next_leaf(BTRFS_I(src)->root, path);
2895                         if (ret < 0)
2896                                 goto out;
2897                         if (ret > 0)
2898                                 break;
2899                         nritems = btrfs_header_nritems(path->nodes[0]);
2900                 }
2901                 leaf = path->nodes[0];
2902                 slot = path->slots[0];
2903
2904                 btrfs_item_key_to_cpu(leaf, &key, slot);
2905                 if (btrfs_key_type(&key) > BTRFS_EXTENT_DATA_KEY ||
2906                     key.objectid != btrfs_ino(src))
2907                         break;
2908
2909                 if (btrfs_key_type(&key) == BTRFS_EXTENT_DATA_KEY) {
2910                         struct btrfs_file_extent_item *extent;
2911                         int type;
2912                         u32 size;
2913                         struct btrfs_key new_key;
2914                         u64 disko = 0, diskl = 0;
2915                         u64 datao = 0, datal = 0;
2916                         u8 comp;
2917                         u64 endoff;
2918
2919                         size = btrfs_item_size_nr(leaf, slot);
2920                         read_extent_buffer(leaf, buf,
2921                                            btrfs_item_ptr_offset(leaf, slot),
2922                                            size);
2923
2924                         extent = btrfs_item_ptr(leaf, slot,
2925                                                 struct btrfs_file_extent_item);
2926                         comp = btrfs_file_extent_compression(leaf, extent);
2927                         type = btrfs_file_extent_type(leaf, extent);
2928                         if (type == BTRFS_FILE_EXTENT_REG ||
2929                             type == BTRFS_FILE_EXTENT_PREALLOC) {
2930                                 disko = btrfs_file_extent_disk_bytenr(leaf,
2931                                                                       extent);
2932                                 diskl = btrfs_file_extent_disk_num_bytes(leaf,
2933                                                                  extent);
2934                                 datao = btrfs_file_extent_offset(leaf, extent);
2935                                 datal = btrfs_file_extent_num_bytes(leaf,
2936                                                                     extent);
2937                         } else if (type == BTRFS_FILE_EXTENT_INLINE) {
2938                                 /* take upper bound, may be compressed */
2939                                 datal = btrfs_file_extent_ram_bytes(leaf,
2940                                                                     extent);
2941                         }
2942                         btrfs_release_path(path);
2943
2944                         if (key.offset + datal <= off ||
2945                             key.offset >= off + len - 1)
2946                                 goto next;
2947
2948                         memcpy(&new_key, &key, sizeof(new_key));
2949                         new_key.objectid = btrfs_ino(inode);
2950                         if (off <= key.offset)
2951                                 new_key.offset = key.offset + destoff - off;
2952                         else
2953                                 new_key.offset = destoff;
2954
2955                         /*
2956                          * 1 - adjusting old extent (we may have to split it)
2957                          * 1 - add new extent
2958                          * 1 - inode update
2959                          */
2960                         trans = btrfs_start_transaction(root, 3);
2961                         if (IS_ERR(trans)) {
2962                                 ret = PTR_ERR(trans);
2963                                 goto out;
2964                         }
2965
2966                         if (type == BTRFS_FILE_EXTENT_REG ||
2967                             type == BTRFS_FILE_EXTENT_PREALLOC) {
2968                                 /*
2969                                  *    a  | --- range to clone ---|  b
2970                                  * | ------------- extent ------------- |
2971                                  */
2972
2973                                 /* substract range b */
2974                                 if (key.offset + datal > off + len)
2975                                         datal = off + len - key.offset;
2976
2977                                 /* substract range a */
2978                                 if (off > key.offset) {
2979                                         datao += off - key.offset;
2980                                         datal -= off - key.offset;
2981                                 }
2982
2983                                 ret = btrfs_drop_extents(trans, root, inode,
2984                                                          new_key.offset,
2985                                                          new_key.offset + datal,
2986                                                          1);
2987                                 if (ret) {
2988                                         btrfs_abort_transaction(trans, root,
2989                                                                 ret);
2990                                         btrfs_end_transaction(trans, root);
2991                                         goto out;
2992                                 }
2993
2994                                 ret = btrfs_insert_empty_item(trans, root, path,
2995                                                               &new_key, size);
2996                                 if (ret) {
2997                                         btrfs_abort_transaction(trans, root,
2998                                                                 ret);
2999                                         btrfs_end_transaction(trans, root);
3000                                         goto out;
3001                                 }
3002
3003                                 leaf = path->nodes[0];
3004                                 slot = path->slots[0];
3005                                 write_extent_buffer(leaf, buf,
3006                                             btrfs_item_ptr_offset(leaf, slot),
3007                                             size);
3008
3009                                 extent = btrfs_item_ptr(leaf, slot,
3010                                                 struct btrfs_file_extent_item);
3011
3012                                 /* disko == 0 means it's a hole */
3013                                 if (!disko)
3014                                         datao = 0;
3015
3016                                 btrfs_set_file_extent_offset(leaf, extent,
3017                                                              datao);
3018                                 btrfs_set_file_extent_num_bytes(leaf, extent,
3019                                                                 datal);
3020                                 if (disko) {
3021                                         inode_add_bytes(inode, datal);
3022                                         ret = btrfs_inc_extent_ref(trans, root,
3023                                                         disko, diskl, 0,
3024                                                         root->root_key.objectid,
3025                                                         btrfs_ino(inode),
3026                                                         new_key.offset - datao,
3027                                                         0);
3028                                         if (ret) {
3029                                                 btrfs_abort_transaction(trans,
3030                                                                         root,
3031                                                                         ret);
3032                                                 btrfs_end_transaction(trans,
3033                                                                       root);
3034                                                 goto out;
3035
3036                                         }
3037                                 }
3038                         } else if (type == BTRFS_FILE_EXTENT_INLINE) {
3039                                 u64 skip = 0;
3040                                 u64 trim = 0;
3041                                 if (off > key.offset) {
3042                                         skip = off - key.offset;
3043                                         new_key.offset += skip;
3044                                 }
3045
3046                                 if (key.offset + datal > off + len)
3047                                         trim = key.offset + datal - (off + len);
3048
3049                                 if (comp && (skip || trim)) {
3050                                         ret = -EINVAL;
3051                                         btrfs_end_transaction(trans, root);
3052                                         goto out;
3053                                 }
3054                                 size -= skip + trim;
3055                                 datal -= skip + trim;
3056
3057                                 ret = btrfs_drop_extents(trans, root, inode,
3058                                                          new_key.offset,
3059                                                          new_key.offset + datal,
3060                                                          1);
3061                                 if (ret) {
3062                                         btrfs_abort_transaction(trans, root,
3063                                                                 ret);
3064                                         btrfs_end_transaction(trans, root);
3065                                         goto out;
3066                                 }
3067
3068                                 ret = btrfs_insert_empty_item(trans, root, path,
3069                                                               &new_key, size);
3070                                 if (ret) {
3071                                         btrfs_abort_transaction(trans, root,
3072                                                                 ret);
3073                                         btrfs_end_transaction(trans, root);
3074                                         goto out;
3075                                 }
3076
3077                                 if (skip) {
3078                                         u32 start =
3079                                           btrfs_file_extent_calc_inline_size(0);
3080                                         memmove(buf+start, buf+start+skip,
3081                                                 datal);
3082                                 }
3083
3084                                 leaf = path->nodes[0];
3085                                 slot = path->slots[0];
3086                                 write_extent_buffer(leaf, buf,
3087                                             btrfs_item_ptr_offset(leaf, slot),
3088                                             size);
3089                                 inode_add_bytes(inode, datal);
3090                         }
3091
3092                         btrfs_mark_buffer_dirty(leaf);
3093                         btrfs_release_path(path);
3094
3095                         inode_inc_iversion(inode);
3096                         inode->i_mtime = inode->i_ctime = CURRENT_TIME;
3097
3098                         /*
3099                          * we round up to the block size at eof when
3100                          * determining which extents to clone above,
3101                          * but shouldn't round up the file size
3102                          */
3103                         endoff = new_key.offset + datal;
3104                         if (endoff > destoff+olen)
3105                                 endoff = destoff+olen;
3106                         if (endoff > inode->i_size)
3107                                 btrfs_i_size_write(inode, endoff);
3108
3109                         ret = btrfs_update_inode(trans, root, inode);
3110                         if (ret) {
3111                                 btrfs_abort_transaction(trans, root, ret);
3112                                 btrfs_end_transaction(trans, root);
3113                                 goto out;
3114                         }
3115                         ret = btrfs_end_transaction(trans, root);
3116                 }
3117 next:
3118                 btrfs_release_path(path);
3119                 key.offset++;
3120         }
3121         ret = 0;
3122
3123 out:
3124         btrfs_release_path(path);
3125         btrfs_free_path(path);
3126         vfree(buf);
3127         return ret;
3128 }
3129
3130 static noinline long btrfs_ioctl_clone(struct file *file, unsigned long srcfd,
3131                                        u64 off, u64 olen, u64 destoff)
3132 {
3133         struct inode *inode = file_inode(file);
3134         struct btrfs_root *root = BTRFS_I(inode)->root;
3135         struct fd src_file;
3136         struct inode *src;
3137         int ret;
3138         u64 len = olen;
3139         u64 bs = root->fs_info->sb->s_blocksize;
3140         int same_inode = 0;
3141
3142         /*
3143          * TODO:
3144          * - split compressed inline extents.  annoying: we need to
3145          *   decompress into destination's address_space (the file offset
3146          *   may change, so source mapping won't do), then recompress (or
3147          *   otherwise reinsert) a subrange.
3148          * - allow ranges within the same file to be cloned (provided
3149          *   they don't overlap)?
3150          */
3151
3152         /* the destination must be opened for writing */
3153         if (!(file->f_mode & FMODE_WRITE) || (file->f_flags & O_APPEND))
3154                 return -EINVAL;
3155
3156         if (btrfs_root_readonly(root))
3157                 return -EROFS;
3158
3159         ret = mnt_want_write_file(file);
3160         if (ret)
3161                 return ret;
3162
3163         src_file = fdget(srcfd);
3164         if (!src_file.file) {
3165                 ret = -EBADF;
3166                 goto out_drop_write;
3167         }
3168
3169         ret = -EXDEV;
3170         if (src_file.file->f_path.mnt != file->f_path.mnt)
3171                 goto out_fput;
3172
3173         src = file_inode(src_file.file);
3174
3175         ret = -EINVAL;
3176         if (src == inode)
3177                 same_inode = 1;
3178
3179         /* the src must be open for reading */
3180         if (!(src_file.file->f_mode & FMODE_READ))
3181                 goto out_fput;
3182
3183         /* don't make the dst file partly checksummed */
3184         if ((BTRFS_I(src)->flags & BTRFS_INODE_NODATASUM) !=
3185             (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM))
3186                 goto out_fput;
3187
3188         ret = -EISDIR;
3189         if (S_ISDIR(src->i_mode) || S_ISDIR(inode->i_mode))
3190                 goto out_fput;
3191
3192         ret = -EXDEV;
3193         if (src->i_sb != inode->i_sb)
3194                 goto out_fput;
3195
3196         if (!same_inode) {
3197                 if (inode < src) {
3198                         mutex_lock_nested(&inode->i_mutex, I_MUTEX_PARENT);
3199                         mutex_lock_nested(&src->i_mutex, I_MUTEX_CHILD);
3200                 } else {
3201                         mutex_lock_nested(&src->i_mutex, I_MUTEX_PARENT);
3202                         mutex_lock_nested(&inode->i_mutex, I_MUTEX_CHILD);
3203                 }
3204         } else {
3205                 mutex_lock(&src->i_mutex);
3206         }
3207
3208         /* determine range to clone */
3209         ret = -EINVAL;
3210         if (off + len > src->i_size || off + len < off)
3211                 goto out_unlock;
3212         if (len == 0)
3213                 olen = len = src->i_size - off;
3214         /* if we extend to eof, continue to block boundary */
3215         if (off + len == src->i_size)
3216                 len = ALIGN(src->i_size, bs) - off;
3217
3218         /* verify the end result is block aligned */
3219         if (!IS_ALIGNED(off, bs) || !IS_ALIGNED(off + len, bs) ||
3220             !IS_ALIGNED(destoff, bs))
3221                 goto out_unlock;
3222
3223         /* verify if ranges are overlapped within the same file */
3224         if (same_inode) {
3225                 if (destoff + len > off && destoff < off + len)
3226                         goto out_unlock;
3227         }
3228
3229         if (destoff > inode->i_size) {
3230                 ret = btrfs_cont_expand(inode, inode->i_size, destoff);
3231                 if (ret)
3232                         goto out_unlock;
3233         }
3234
3235         /* truncate page cache pages from target inode range */
3236         truncate_inode_pages_range(&inode->i_data, destoff,
3237                                    PAGE_CACHE_ALIGN(destoff + len) - 1);
3238
3239         lock_extent_range(src, off, len);
3240
3241         ret = btrfs_clone(src, inode, off, olen, len, destoff);
3242
3243         unlock_extent(&BTRFS_I(src)->io_tree, off, off + len - 1);
3244 out_unlock:
3245         mutex_unlock(&src->i_mutex);
3246         if (!same_inode)
3247                 mutex_unlock(&inode->i_mutex);
3248 out_fput:
3249         fdput(src_file);
3250 out_drop_write:
3251         mnt_drop_write_file(file);
3252         return ret;
3253 }
3254
3255 static long btrfs_ioctl_clone_range(struct file *file, void __user *argp)
3256 {
3257         struct btrfs_ioctl_clone_range_args args;
3258
3259         if (copy_from_user(&args, argp, sizeof(args)))
3260                 return -EFAULT;
3261         return btrfs_ioctl_clone(file, args.src_fd, args.src_offset,
3262                                  args.src_length, args.dest_offset);
3263 }
3264
3265 /*
3266  * there are many ways the trans_start and trans_end ioctls can lead
3267  * to deadlocks.  They should only be used by applications that
3268  * basically own the machine, and have a very in depth understanding
3269  * of all the possible deadlocks and enospc problems.
3270  */
3271 static long btrfs_ioctl_trans_start(struct file *file)
3272 {
3273         struct inode *inode = file_inode(file);
3274         struct btrfs_root *root = BTRFS_I(inode)->root;
3275         struct btrfs_trans_handle *trans;
3276         int ret;
3277
3278         ret = -EPERM;
3279         if (!capable(CAP_SYS_ADMIN))
3280                 goto out;
3281
3282         ret = -EINPROGRESS;
3283         if (file->private_data)
3284                 goto out;
3285
3286         ret = -EROFS;
3287         if (btrfs_root_readonly(root))
3288                 goto out;
3289
3290         ret = mnt_want_write_file(file);
3291         if (ret)
3292                 goto out;
3293
3294         atomic_inc(&root->fs_info->open_ioctl_trans);
3295
3296         ret = -ENOMEM;
3297         trans = btrfs_start_ioctl_transaction(root);
3298         if (IS_ERR(trans))
3299                 goto out_drop;
3300
3301         file->private_data = trans;
3302         return 0;
3303
3304 out_drop:
3305         atomic_dec(&root->fs_info->open_ioctl_trans);
3306         mnt_drop_write_file(file);
3307 out:
3308         return ret;
3309 }
3310
3311 static long btrfs_ioctl_default_subvol(struct file *file, void __user *argp)
3312 {
3313         struct inode *inode = file_inode(file);
3314         struct btrfs_root *root = BTRFS_I(inode)->root;
3315         struct btrfs_root *new_root;
3316         struct btrfs_dir_item *di;
3317         struct btrfs_trans_handle *trans;
3318         struct btrfs_path *path;
3319         struct btrfs_key location;
3320         struct btrfs_disk_key disk_key;
3321         u64 objectid = 0;
3322         u64 dir_id;
3323         int ret;
3324
3325         if (!capable(CAP_SYS_ADMIN))
3326                 return -EPERM;
3327
3328         ret = mnt_want_write_file(file);
3329         if (ret)
3330                 return ret;
3331
3332         if (copy_from_user(&objectid, argp, sizeof(objectid))) {
3333                 ret = -EFAULT;
3334                 goto out;
3335         }
3336
3337         if (!objectid)
3338                 objectid = BTRFS_FS_TREE_OBJECTID;
3339
3340         location.objectid = objectid;
3341         location.type = BTRFS_ROOT_ITEM_KEY;
3342         location.offset = (u64)-1;
3343
3344         new_root = btrfs_read_fs_root_no_name(root->fs_info, &location);
3345         if (IS_ERR(new_root)) {
3346                 ret = PTR_ERR(new_root);
3347                 goto out;
3348         }
3349
3350         path = btrfs_alloc_path();
3351         if (!path) {
3352                 ret = -ENOMEM;
3353                 goto out;
3354         }
3355         path->leave_spinning = 1;
3356
3357         trans = btrfs_start_transaction(root, 1);
3358         if (IS_ERR(trans)) {
3359                 btrfs_free_path(path);
3360                 ret = PTR_ERR(trans);
3361                 goto out;
3362         }
3363
3364         dir_id = btrfs_super_root_dir(root->fs_info->super_copy);
3365         di = btrfs_lookup_dir_item(trans, root->fs_info->tree_root, path,
3366                                    dir_id, "default", 7, 1);
3367         if (IS_ERR_OR_NULL(di)) {
3368                 btrfs_free_path(path);
3369                 btrfs_end_transaction(trans, root);
3370                 printk(KERN_ERR "Umm, you don't have the default dir item, "
3371                        "this isn't going to work\n");
3372                 ret = -ENOENT;
3373                 goto out;
3374         }
3375
3376         btrfs_cpu_key_to_disk(&disk_key, &new_root->root_key);
3377         btrfs_set_dir_item_key(path->nodes[0], di, &disk_key);
3378         btrfs_mark_buffer_dirty(path->nodes[0]);
3379         btrfs_free_path(path);
3380
3381         btrfs_set_fs_incompat(root->fs_info, DEFAULT_SUBVOL);
3382         btrfs_end_transaction(trans, root);
3383 out:
3384         mnt_drop_write_file(file);
3385         return ret;
3386 }
3387
3388 void btrfs_get_block_group_info(struct list_head *groups_list,
3389                                 struct btrfs_ioctl_space_info *space)
3390 {
3391         struct btrfs_block_group_cache *block_group;
3392
3393         space->total_bytes = 0;
3394         space->used_bytes = 0;
3395         space->flags = 0;
3396         list_for_each_entry(block_group, groups_list, list) {
3397                 space->flags = block_group->flags;
3398                 space->total_bytes += block_group->key.offset;
3399                 space->used_bytes +=
3400                         btrfs_block_group_used(&block_group->item);
3401         }
3402 }
3403
3404 static long btrfs_ioctl_space_info(struct btrfs_root *root, void __user *arg)
3405 {
3406         struct btrfs_ioctl_space_args space_args;
3407         struct btrfs_ioctl_space_info space;
3408         struct btrfs_ioctl_space_info *dest;
3409         struct btrfs_ioctl_space_info *dest_orig;
3410         struct btrfs_ioctl_space_info __user *user_dest;
3411         struct btrfs_space_info *info;
3412         u64 types[] = {BTRFS_BLOCK_GROUP_DATA,
3413                        BTRFS_BLOCK_GROUP_SYSTEM,
3414                        BTRFS_BLOCK_GROUP_METADATA,
3415                        BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA};
3416         int num_types = 4;
3417         int alloc_size;
3418         int ret = 0;
3419         u64 slot_count = 0;
3420         int i, c;
3421
3422         if (copy_from_user(&space_args,
3423                            (struct btrfs_ioctl_space_args __user *)arg,
3424                            sizeof(space_args)))
3425                 return -EFAULT;
3426
3427         for (i = 0; i < num_types; i++) {
3428                 struct btrfs_space_info *tmp;
3429
3430                 info = NULL;
3431                 rcu_read_lock();
3432                 list_for_each_entry_rcu(tmp, &root->fs_info->space_info,
3433                                         list) {
3434                         if (tmp->flags == types[i]) {
3435                                 info = tmp;
3436                                 break;
3437                         }
3438                 }
3439                 rcu_read_unlock();
3440
3441                 if (!info)
3442                         continue;
3443
3444                 down_read(&info->groups_sem);
3445                 for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
3446                         if (!list_empty(&info->block_groups[c]))
3447                                 slot_count++;
3448                 }
3449                 up_read(&info->groups_sem);
3450         }
3451
3452         /* space_slots == 0 means they are asking for a count */
3453         if (space_args.space_slots == 0) {
3454                 space_args.total_spaces = slot_count;
3455                 goto out;
3456         }
3457
3458         slot_count = min_t(u64, space_args.space_slots, slot_count);
3459
3460         alloc_size = sizeof(*dest) * slot_count;
3461
3462         /* we generally have at most 6 or so space infos, one for each raid
3463          * level.  So, a whole page should be more than enough for everyone
3464          */
3465         if (alloc_size > PAGE_CACHE_SIZE)
3466                 return -ENOMEM;
3467
3468         space_args.total_spaces = 0;
3469         dest = kmalloc(alloc_size, GFP_NOFS);
3470         if (!dest)
3471                 return -ENOMEM;
3472         dest_orig = dest;
3473
3474         /* now we have a buffer to copy into */
3475         for (i = 0; i < num_types; i++) {
3476                 struct btrfs_space_info *tmp;
3477
3478                 if (!slot_count)
3479                         break;
3480
3481                 info = NULL;
3482                 rcu_read_lock();
3483                 list_for_each_entry_rcu(tmp, &root->fs_info->space_info,
3484                                         list) {
3485                         if (tmp->flags == types[i]) {
3486                                 info = tmp;
3487                                 break;
3488                         }
3489                 }
3490                 rcu_read_unlock();
3491
3492                 if (!info)
3493                         continue;
3494                 down_read(&info->groups_sem);
3495                 for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
3496                         if (!list_empty(&info->block_groups[c])) {
3497                                 btrfs_get_block_group_info(
3498                                         &info->block_groups[c], &space);
3499                                 memcpy(dest, &space, sizeof(space));
3500                                 dest++;
3501                                 space_args.total_spaces++;
3502                                 slot_count--;
3503                         }
3504                         if (!slot_count)
3505                                 break;
3506                 }
3507                 up_read(&info->groups_sem);
3508         }
3509
3510         user_dest = (struct btrfs_ioctl_space_info __user *)
3511                 (arg + sizeof(struct btrfs_ioctl_space_args));
3512
3513         if (copy_to_user(user_dest, dest_orig, alloc_size))
3514                 ret = -EFAULT;
3515
3516         kfree(dest_orig);
3517 out:
3518         if (ret == 0 && copy_to_user(arg, &space_args, sizeof(space_args)))
3519                 ret = -EFAULT;
3520
3521         return ret;
3522 }
3523
3524 static long btrfs_ioctl_global_rsv(struct btrfs_root *root, void __user *arg)
3525 {
3526         struct btrfs_block_rsv *block_rsv = &root->fs_info->global_block_rsv;
3527         u64 reserved;
3528
3529         spin_lock(&block_rsv->lock);
3530         reserved = block_rsv->reserved;
3531         spin_unlock(&block_rsv->lock);
3532
3533         if (arg && copy_to_user(arg, &reserved, sizeof(reserved)))
3534                 return -EFAULT;
3535         return 0;
3536 }
3537
3538 /*
3539  * there are many ways the trans_start and trans_end ioctls can lead
3540  * to deadlocks.  They should only be used by applications that
3541  * basically own the machine, and have a very in depth understanding
3542  * of all the possible deadlocks and enospc problems.
3543  */
3544 long btrfs_ioctl_trans_end(struct file *file)
3545 {
3546         struct inode *inode = file_inode(file);
3547         struct btrfs_root *root = BTRFS_I(inode)->root;
3548         struct btrfs_trans_handle *trans;
3549
3550         trans = file->private_data;
3551         if (!trans)
3552                 return -EINVAL;
3553         file->private_data = NULL;
3554
3555         btrfs_end_transaction(trans, root);
3556
3557         atomic_dec(&root->fs_info->open_ioctl_trans);
3558
3559         mnt_drop_write_file(file);
3560         return 0;
3561 }
3562
3563 static noinline long btrfs_ioctl_start_sync(struct btrfs_root *root,
3564                                             void __user *argp)
3565 {
3566         struct btrfs_trans_handle *trans;
3567         u64 transid;
3568         int ret;
3569
3570         trans = btrfs_attach_transaction_barrier(root);
3571         if (IS_ERR(trans)) {
3572                 if (PTR_ERR(trans) != -ENOENT)
3573                         return PTR_ERR(trans);
3574
3575                 /* No running transaction, don't bother */
3576                 transid = root->fs_info->last_trans_committed;
3577                 goto out;
3578         }
3579         transid = trans->transid;
3580         ret = btrfs_commit_transaction_async(trans, root, 0);
3581         if (ret) {
3582                 btrfs_end_transaction(trans, root);
3583                 return ret;
3584         }
3585 out:
3586         if (argp)
3587                 if (copy_to_user(argp, &transid, sizeof(transid)))
3588                         return -EFAULT;
3589         return 0;
3590 }
3591
3592 static noinline long btrfs_ioctl_wait_sync(struct btrfs_root *root,
3593                                            void __user *argp)
3594 {
3595         u64 transid;
3596
3597         if (argp) {
3598                 if (copy_from_user(&transid, argp, sizeof(transid)))
3599                         return -EFAULT;
3600         } else {
3601                 transid = 0;  /* current trans */
3602         }
3603         return btrfs_wait_for_commit(root, transid);
3604 }
3605
3606 static long btrfs_ioctl_scrub(struct file *file, void __user *arg)
3607 {
3608         struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
3609         struct btrfs_ioctl_scrub_args *sa;
3610         int ret;
3611
3612         if (!capable(CAP_SYS_ADMIN))
3613                 return -EPERM;
3614
3615         sa = memdup_user(arg, sizeof(*sa));
3616         if (IS_ERR(sa))
3617                 return PTR_ERR(sa);
3618
3619         if (!(sa->flags & BTRFS_SCRUB_READONLY)) {
3620                 ret = mnt_want_write_file(file);
3621                 if (ret)
3622                         goto out;
3623         }
3624
3625         ret = btrfs_scrub_dev(root->fs_info, sa->devid, sa->start, sa->end,
3626                               &sa->progress, sa->flags & BTRFS_SCRUB_READONLY,
3627                               0);
3628
3629         if (copy_to_user(arg, sa, sizeof(*sa)))
3630                 ret = -EFAULT;
3631
3632         if (!(sa->flags & BTRFS_SCRUB_READONLY))
3633                 mnt_drop_write_file(file);
3634 out:
3635         kfree(sa);
3636         return ret;
3637 }
3638
3639 static long btrfs_ioctl_scrub_cancel(struct btrfs_root *root, void __user *arg)
3640 {
3641         if (!capable(CAP_SYS_ADMIN))
3642                 return -EPERM;
3643
3644         return btrfs_scrub_cancel(root->fs_info);
3645 }
3646
3647 static long btrfs_ioctl_scrub_progress(struct btrfs_root *root,
3648                                        void __user *arg)
3649 {
3650         struct btrfs_ioctl_scrub_args *sa;
3651         int ret;
3652
3653         if (!capable(CAP_SYS_ADMIN))
3654                 return -EPERM;
3655
3656         sa = memdup_user(arg, sizeof(*sa));
3657         if (IS_ERR(sa))
3658                 return PTR_ERR(sa);
3659
3660         ret = btrfs_scrub_progress(root, sa->devid, &sa->progress);
3661
3662         if (copy_to_user(arg, sa, sizeof(*sa)))
3663                 ret = -EFAULT;
3664
3665         kfree(sa);
3666         return ret;
3667 }
3668
3669 static long btrfs_ioctl_get_dev_stats(struct btrfs_root *root,
3670                                       void __user *arg)
3671 {
3672         struct btrfs_ioctl_get_dev_stats *sa;
3673         int ret;
3674
3675         sa = memdup_user(arg, sizeof(*sa));
3676         if (IS_ERR(sa))
3677                 return PTR_ERR(sa);
3678
3679         if ((sa->flags & BTRFS_DEV_STATS_RESET) && !capable(CAP_SYS_ADMIN)) {
3680                 kfree(sa);
3681                 return -EPERM;
3682         }
3683
3684         ret = btrfs_get_dev_stats(root, sa);
3685
3686         if (copy_to_user(arg, sa, sizeof(*sa)))
3687                 ret = -EFAULT;
3688
3689         kfree(sa);
3690         return ret;
3691 }
3692
3693 static long btrfs_ioctl_dev_replace(struct btrfs_root *root, void __user *arg)
3694 {
3695         struct btrfs_ioctl_dev_replace_args *p;
3696         int ret;
3697
3698         if (!capable(CAP_SYS_ADMIN))
3699                 return -EPERM;
3700
3701         p = memdup_user(arg, sizeof(*p));
3702         if (IS_ERR(p))
3703                 return PTR_ERR(p);
3704
3705         switch (p->cmd) {
3706         case BTRFS_IOCTL_DEV_REPLACE_CMD_START:
3707                 if (root->fs_info->sb->s_flags & MS_RDONLY) {
3708                         ret = -EROFS;
3709                         goto out;
3710                 }
3711                 if (atomic_xchg(
3712                         &root->fs_info->mutually_exclusive_operation_running,
3713                         1)) {
3714                         ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
3715                 } else {
3716                         ret = btrfs_dev_replace_start(root, p);
3717                         atomic_set(
3718                          &root->fs_info->mutually_exclusive_operation_running,
3719                          0);
3720                 }
3721                 break;
3722         case BTRFS_IOCTL_DEV_REPLACE_CMD_STATUS:
3723                 btrfs_dev_replace_status(root->fs_info, p);
3724                 ret = 0;
3725                 break;
3726         case BTRFS_IOCTL_DEV_REPLACE_CMD_CANCEL:
3727                 ret = btrfs_dev_replace_cancel(root->fs_info, p);
3728                 break;
3729         default:
3730                 ret = -EINVAL;
3731                 break;
3732         }
3733
3734         if (copy_to_user(arg, p, sizeof(*p)))
3735                 ret = -EFAULT;
3736 out:
3737         kfree(p);
3738         return ret;
3739 }
3740
3741 static long btrfs_ioctl_ino_to_path(struct btrfs_root *root, void __user *arg)
3742 {
3743         int ret = 0;
3744         int i;
3745         u64 rel_ptr;
3746         int size;
3747         struct btrfs_ioctl_ino_path_args *ipa = NULL;
3748         struct inode_fs_paths *ipath = NULL;
3749         struct btrfs_path *path;
3750
3751         if (!capable(CAP_DAC_READ_SEARCH))
3752                 return -EPERM;
3753
3754         path = btrfs_alloc_path();
3755         if (!path) {
3756                 ret = -ENOMEM;
3757                 goto out;
3758         }
3759
3760         ipa = memdup_user(arg, sizeof(*ipa));
3761         if (IS_ERR(ipa)) {
3762                 ret = PTR_ERR(ipa);
3763                 ipa = NULL;
3764                 goto out;
3765         }
3766
3767         size = min_t(u32, ipa->size, 4096);
3768         ipath = init_ipath(size, root, path);
3769         if (IS_ERR(ipath)) {
3770                 ret = PTR_ERR(ipath);
3771                 ipath = NULL;
3772                 goto out;
3773         }
3774
3775         ret = paths_from_inode(ipa->inum, ipath);
3776         if (ret < 0)
3777                 goto out;
3778
3779         for (i = 0; i < ipath->fspath->elem_cnt; ++i) {
3780                 rel_ptr = ipath->fspath->val[i] -
3781                           (u64)(unsigned long)ipath->fspath->val;
3782                 ipath->fspath->val[i] = rel_ptr;
3783         }
3784
3785         ret = copy_to_user((void *)(unsigned long)ipa->fspath,
3786                            (void *)(unsigned long)ipath->fspath, size);
3787         if (ret) {
3788                 ret = -EFAULT;
3789                 goto out;
3790         }
3791
3792 out:
3793         btrfs_free_path(path);
3794         free_ipath(ipath);
3795         kfree(ipa);
3796
3797         return ret;
3798 }
3799
3800 static int build_ino_list(u64 inum, u64 offset, u64 root, void *ctx)
3801 {
3802         struct btrfs_data_container *inodes = ctx;
3803         const size_t c = 3 * sizeof(u64);
3804
3805         if (inodes->bytes_left >= c) {
3806                 inodes->bytes_left -= c;
3807                 inodes->val[inodes->elem_cnt] = inum;
3808                 inodes->val[inodes->elem_cnt + 1] = offset;
3809                 inodes->val[inodes->elem_cnt + 2] = root;
3810                 inodes->elem_cnt += 3;
3811         } else {
3812                 inodes->bytes_missing += c - inodes->bytes_left;
3813                 inodes->bytes_left = 0;
3814                 inodes->elem_missed += 3;
3815         }
3816
3817         return 0;
3818 }
3819
3820 static long btrfs_ioctl_logical_to_ino(struct btrfs_root *root,
3821                                         void __user *arg)
3822 {
3823         int ret = 0;
3824         int size;
3825         struct btrfs_ioctl_logical_ino_args *loi;
3826         struct btrfs_data_container *inodes = NULL;
3827         struct btrfs_path *path = NULL;
3828
3829         if (!capable(CAP_SYS_ADMIN))
3830                 return -EPERM;
3831
3832         loi = memdup_user(arg, sizeof(*loi));
3833         if (IS_ERR(loi)) {
3834                 ret = PTR_ERR(loi);
3835                 loi = NULL;
3836                 goto out;
3837         }
3838
3839         path = btrfs_alloc_path();
3840         if (!path) {
3841                 ret = -ENOMEM;
3842                 goto out;
3843         }
3844
3845         size = min_t(u32, loi->size, 64 * 1024);
3846         inodes = init_data_container(size);
3847         if (IS_ERR(inodes)) {
3848                 ret = PTR_ERR(inodes);
3849                 inodes = NULL;
3850                 goto out;
3851         }
3852
3853         ret = iterate_inodes_from_logical(loi->logical, root->fs_info, path,
3854                                           build_ino_list, inodes);
3855         if (ret == -EINVAL)
3856                 ret = -ENOENT;
3857         if (ret < 0)
3858                 goto out;
3859
3860         ret = copy_to_user((void *)(unsigned long)loi->inodes,
3861                            (void *)(unsigned long)inodes, size);
3862         if (ret)
3863                 ret = -EFAULT;
3864
3865 out:
3866         btrfs_free_path(path);
3867         vfree(inodes);
3868         kfree(loi);
3869
3870         return ret;
3871 }
3872
3873 void update_ioctl_balance_args(struct btrfs_fs_info *fs_info, int lock,
3874                                struct btrfs_ioctl_balance_args *bargs)
3875 {
3876         struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3877
3878         bargs->flags = bctl->flags;
3879
3880         if (atomic_read(&fs_info->balance_running))
3881                 bargs->state |= BTRFS_BALANCE_STATE_RUNNING;
3882         if (atomic_read(&fs_info->balance_pause_req))
3883                 bargs->state |= BTRFS_BALANCE_STATE_PAUSE_REQ;
3884         if (atomic_read(&fs_info->balance_cancel_req))
3885                 bargs->state |= BTRFS_BALANCE_STATE_CANCEL_REQ;
3886
3887         memcpy(&bargs->data, &bctl->data, sizeof(bargs->data));
3888         memcpy(&bargs->meta, &bctl->meta, sizeof(bargs->meta));
3889         memcpy(&bargs->sys, &bctl->sys, sizeof(bargs->sys));
3890
3891         if (lock) {
3892                 spin_lock(&fs_info->balance_lock);
3893                 memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat));
3894                 spin_unlock(&fs_info->balance_lock);
3895         } else {
3896                 memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat));
3897         }
3898 }
3899
3900 static long btrfs_ioctl_balance(struct file *file, void __user *arg)
3901 {
3902         struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
3903         struct btrfs_fs_info *fs_info = root->fs_info;
3904         struct btrfs_ioctl_balance_args *bargs;
3905         struct btrfs_balance_control *bctl;
3906         bool need_unlock; /* for mut. excl. ops lock */
3907         int ret;
3908
3909         if (!capable(CAP_SYS_ADMIN))
3910                 return -EPERM;
3911
3912         ret = mnt_want_write_file(file);
3913         if (ret)
3914                 return ret;
3915
3916 again:
3917         if (!atomic_xchg(&fs_info->mutually_exclusive_operation_running, 1)) {
3918                 mutex_lock(&fs_info->volume_mutex);
3919                 mutex_lock(&fs_info->balance_mutex);
3920                 need_unlock = true;
3921                 goto locked;
3922         }
3923
3924         /*
3925          * mut. excl. ops lock is locked.  Three possibilites:
3926          *   (1) some other op is running
3927          *   (2) balance is running
3928          *   (3) balance is paused -- special case (think resume)
3929          */
3930         mutex_lock(&fs_info->balance_mutex);
3931         if (fs_info->balance_ctl) {
3932                 /* this is either (2) or (3) */
3933                 if (!atomic_read(&fs_info->balance_running)) {
3934                         mutex_unlock(&fs_info->balance_mutex);
3935                         if (!mutex_trylock(&fs_info->volume_mutex))
3936                                 goto again;
3937                         mutex_lock(&fs_info->balance_mutex);
3938
3939                         if (fs_info->balance_ctl &&
3940                             !atomic_read(&fs_info->balance_running)) {
3941                                 /* this is (3) */
3942                                 need_unlock = false;
3943                                 goto locked;
3944                         }
3945
3946                         mutex_unlock(&fs_info->balance_mutex);
3947                         mutex_unlock(&fs_info->volume_mutex);
3948                         goto again;
3949                 } else {
3950                         /* this is (2) */
3951                         mutex_unlock(&fs_info->balance_mutex);
3952                         ret = -EINPROGRESS;
3953                         goto out;
3954                 }
3955         } else {
3956                 /* this is (1) */
3957                 mutex_unlock(&fs_info->balance_mutex);
3958                 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
3959                 goto out;
3960         }
3961
3962 locked:
3963         BUG_ON(!atomic_read(&fs_info->mutually_exclusive_operation_running));
3964
3965         if (arg) {
3966                 bargs = memdup_user(arg, sizeof(*bargs));
3967                 if (IS_ERR(bargs)) {
3968                         ret = PTR_ERR(bargs);
3969                         goto out_unlock;
3970                 }
3971
3972                 if (bargs->flags & BTRFS_BALANCE_RESUME) {
3973                         if (!fs_info->balance_ctl) {
3974                                 ret = -ENOTCONN;
3975                                 goto out_bargs;
3976                         }
3977
3978                         bctl = fs_info->balance_ctl;
3979                         spin_lock(&fs_info->balance_lock);
3980                         bctl->flags |= BTRFS_BALANCE_RESUME;
3981                         spin_unlock(&fs_info->balance_lock);
3982
3983                         goto do_balance;
3984                 }
3985         } else {
3986                 bargs = NULL;
3987         }
3988
3989         if (fs_info->balance_ctl) {
3990                 ret = -EINPROGRESS;
3991                 goto out_bargs;
3992         }
3993
3994         bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
3995         if (!bctl) {
3996                 ret = -ENOMEM;
3997                 goto out_bargs;
3998         }
3999
4000         bctl->fs_info = fs_info;
4001         if (arg) {
4002                 memcpy(&bctl->data, &bargs->data, sizeof(bctl->data));
4003                 memcpy(&bctl->meta, &bargs->meta, sizeof(bctl->meta));
4004                 memcpy(&bctl->sys, &bargs->sys, sizeof(bctl->sys));
4005
4006                 bctl->flags = bargs->flags;
4007         } else {
4008                 /* balance everything - no filters */
4009                 bctl->flags |= BTRFS_BALANCE_TYPE_MASK;
4010         }
4011
4012 do_balance:
4013         /*
4014          * Ownership of bctl and mutually_exclusive_operation_running
4015          * goes to to btrfs_balance.  bctl is freed in __cancel_balance,
4016          * or, if restriper was paused all the way until unmount, in
4017          * free_fs_info.  mutually_exclusive_operation_running is
4018          * cleared in __cancel_balance.
4019          */
4020         need_unlock = false;
4021
4022         ret = btrfs_balance(bctl, bargs);
4023
4024         if (arg) {
4025                 if (copy_to_user(arg, bargs, sizeof(*bargs)))
4026                         ret = -EFAULT;
4027         }
4028
4029 out_bargs:
4030         kfree(bargs);
4031 out_unlock:
4032         mutex_unlock(&fs_info->balance_mutex);
4033         mutex_unlock(&fs_info->volume_mutex);
4034         if (need_unlock)
4035                 atomic_set(&fs_info->mutually_exclusive_operation_running, 0);
4036 out:
4037         mnt_drop_write_file(file);
4038         return ret;
4039 }
4040
4041 static long btrfs_ioctl_balance_ctl(struct btrfs_root *root, int cmd)
4042 {
4043         if (!capable(CAP_SYS_ADMIN))
4044                 return -EPERM;
4045
4046         switch (cmd) {
4047         case BTRFS_BALANCE_CTL_PAUSE:
4048                 return btrfs_pause_balance(root->fs_info);
4049         case BTRFS_BALANCE_CTL_CANCEL:
4050                 return btrfs_cancel_balance(root->fs_info);
4051         }
4052
4053         return -EINVAL;
4054 }
4055
4056 static long btrfs_ioctl_balance_progress(struct btrfs_root *root,
4057                                          void __user *arg)
4058 {
4059         struct btrfs_fs_info *fs_info = root->fs_info;
4060         struct btrfs_ioctl_balance_args *bargs;
4061         int ret = 0;
4062
4063         if (!capable(CAP_SYS_ADMIN))
4064                 return -EPERM;
4065
4066         mutex_lock(&fs_info->balance_mutex);
4067         if (!fs_info->balance_ctl) {
4068                 ret = -ENOTCONN;
4069                 goto out;
4070         }
4071
4072         bargs = kzalloc(sizeof(*bargs), GFP_NOFS);
4073         if (!bargs) {
4074                 ret = -ENOMEM;
4075                 goto out;
4076         }
4077
4078         update_ioctl_balance_args(fs_info, 1, bargs);
4079
4080         if (copy_to_user(arg, bargs, sizeof(*bargs)))
4081                 ret = -EFAULT;
4082
4083         kfree(bargs);
4084 out:
4085         mutex_unlock(&fs_info->balance_mutex);
4086         return ret;
4087 }
4088
4089 static long btrfs_ioctl_quota_ctl(struct file *file, void __user *arg)
4090 {
4091         struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4092         struct btrfs_ioctl_quota_ctl_args *sa;
4093         struct btrfs_trans_handle *trans = NULL;
4094         int ret;
4095         int err;
4096
4097         if (!capable(CAP_SYS_ADMIN))
4098                 return -EPERM;
4099
4100         ret = mnt_want_write_file(file);
4101         if (ret)
4102                 return ret;
4103
4104         sa = memdup_user(arg, sizeof(*sa));
4105         if (IS_ERR(sa)) {
4106                 ret = PTR_ERR(sa);
4107                 goto drop_write;
4108         }
4109
4110         down_write(&root->fs_info->subvol_sem);
4111         trans = btrfs_start_transaction(root->fs_info->tree_root, 2);
4112         if (IS_ERR(trans)) {
4113                 ret = PTR_ERR(trans);
4114                 goto out;
4115         }
4116
4117         switch (sa->cmd) {
4118         case BTRFS_QUOTA_CTL_ENABLE:
4119                 ret = btrfs_quota_enable(trans, root->fs_info);
4120                 break;
4121         case BTRFS_QUOTA_CTL_DISABLE:
4122                 ret = btrfs_quota_disable(trans, root->fs_info);
4123                 break;
4124         default:
4125                 ret = -EINVAL;
4126                 break;
4127         }
4128
4129         err = btrfs_commit_transaction(trans, root->fs_info->tree_root);
4130         if (err && !ret)
4131                 ret = err;
4132 out:
4133         kfree(sa);
4134         up_write(&root->fs_info->subvol_sem);
4135 drop_write:
4136         mnt_drop_write_file(file);
4137         return ret;
4138 }
4139
4140 static long btrfs_ioctl_qgroup_assign(struct file *file, void __user *arg)
4141 {
4142         struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4143         struct btrfs_ioctl_qgroup_assign_args *sa;
4144         struct btrfs_trans_handle *trans;
4145         int ret;
4146         int err;
4147
4148         if (!capable(CAP_SYS_ADMIN))
4149                 return -EPERM;
4150
4151         ret = mnt_want_write_file(file);
4152         if (ret)
4153                 return ret;
4154
4155         sa = memdup_user(arg, sizeof(*sa));
4156         if (IS_ERR(sa)) {
4157                 ret = PTR_ERR(sa);
4158                 goto drop_write;
4159         }
4160
4161         trans = btrfs_join_transaction(root);
4162         if (IS_ERR(trans)) {
4163                 ret = PTR_ERR(trans);
4164                 goto out;
4165         }
4166
4167         /* FIXME: check if the IDs really exist */
4168         if (sa->assign) {
4169                 ret = btrfs_add_qgroup_relation(trans, root->fs_info,
4170                                                 sa->src, sa->dst);
4171         } else {
4172                 ret = btrfs_del_qgroup_relation(trans, root->fs_info,
4173                                                 sa->src, sa->dst);
4174         }
4175
4176         err = btrfs_end_transaction(trans, root);
4177         if (err && !ret)
4178                 ret = err;
4179
4180 out:
4181         kfree(sa);
4182 drop_write:
4183         mnt_drop_write_file(file);
4184         return ret;
4185 }
4186
4187 static long btrfs_ioctl_qgroup_create(struct file *file, void __user *arg)
4188 {
4189         struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4190         struct btrfs_ioctl_qgroup_create_args *sa;
4191         struct btrfs_trans_handle *trans;
4192         int ret;
4193         int err;
4194
4195         if (!capable(CAP_SYS_ADMIN))
4196                 return -EPERM;
4197
4198         ret = mnt_want_write_file(file);
4199         if (ret)
4200                 return ret;
4201
4202         sa = memdup_user(arg, sizeof(*sa));
4203         if (IS_ERR(sa)) {
4204                 ret = PTR_ERR(sa);
4205                 goto drop_write;
4206         }
4207
4208         if (!sa->qgroupid) {
4209                 ret = -EINVAL;
4210                 goto out;
4211         }
4212
4213         trans = btrfs_join_transaction(root);
4214         if (IS_ERR(trans)) {
4215                 ret = PTR_ERR(trans);
4216                 goto out;
4217         }
4218
4219         /* FIXME: check if the IDs really exist */
4220         if (sa->create) {
4221                 ret = btrfs_create_qgroup(trans, root->fs_info, sa->qgroupid,
4222                                           NULL);
4223         } else {
4224                 ret = btrfs_remove_qgroup(trans, root->fs_info, sa->qgroupid);
4225         }
4226
4227         err = btrfs_end_transaction(trans, root);
4228         if (err && !ret)
4229                 ret = err;
4230
4231 out:
4232         kfree(sa);
4233 drop_write:
4234         mnt_drop_write_file(file);
4235         return ret;
4236 }
4237
4238 static long btrfs_ioctl_qgroup_limit(struct file *file, void __user *arg)
4239 {
4240         struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4241         struct btrfs_ioctl_qgroup_limit_args *sa;
4242         struct btrfs_trans_handle *trans;
4243         int ret;
4244         int err;
4245         u64 qgroupid;
4246
4247         if (!capable(CAP_SYS_ADMIN))
4248                 return -EPERM;
4249
4250         ret = mnt_want_write_file(file);
4251         if (ret)
4252                 return ret;
4253
4254         sa = memdup_user(arg, sizeof(*sa));
4255         if (IS_ERR(sa)) {
4256                 ret = PTR_ERR(sa);
4257                 goto drop_write;
4258         }
4259
4260         trans = btrfs_join_transaction(root);
4261         if (IS_ERR(trans)) {
4262                 ret = PTR_ERR(trans);
4263                 goto out;
4264         }
4265
4266         qgroupid = sa->qgroupid;
4267         if (!qgroupid) {
4268                 /* take the current subvol as qgroup */
4269                 qgroupid = root->root_key.objectid;
4270         }
4271
4272         /* FIXME: check if the IDs really exist */
4273         ret = btrfs_limit_qgroup(trans, root->fs_info, qgroupid, &sa->lim);
4274
4275         err = btrfs_end_transaction(trans, root);
4276         if (err && !ret)
4277                 ret = err;
4278
4279 out:
4280         kfree(sa);
4281 drop_write:
4282         mnt_drop_write_file(file);
4283         return ret;
4284 }
4285
4286 static long btrfs_ioctl_quota_rescan(struct file *file, void __user *arg)
4287 {
4288         struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4289         struct btrfs_ioctl_quota_rescan_args *qsa;
4290         int ret;
4291
4292         if (!capable(CAP_SYS_ADMIN))
4293                 return -EPERM;
4294
4295         ret = mnt_want_write_file(file);
4296         if (ret)
4297                 return ret;
4298
4299         qsa = memdup_user(arg, sizeof(*qsa));
4300         if (IS_ERR(qsa)) {
4301                 ret = PTR_ERR(qsa);
4302                 goto drop_write;
4303         }
4304
4305         if (qsa->flags) {
4306                 ret = -EINVAL;
4307                 goto out;
4308         }
4309
4310         ret = btrfs_qgroup_rescan(root->fs_info);
4311
4312 out:
4313         kfree(qsa);
4314 drop_write:
4315         mnt_drop_write_file(file);
4316         return ret;
4317 }
4318
4319 static long btrfs_ioctl_quota_rescan_status(struct file *file, void __user *arg)
4320 {
4321         struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4322         struct btrfs_ioctl_quota_rescan_args *qsa;
4323         int ret = 0;
4324
4325         if (!capable(CAP_SYS_ADMIN))
4326                 return -EPERM;
4327
4328         qsa = kzalloc(sizeof(*qsa), GFP_NOFS);
4329         if (!qsa)
4330                 return -ENOMEM;
4331
4332         if (root->fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
4333                 qsa->flags = 1;
4334                 qsa->progress = root->fs_info->qgroup_rescan_progress.objectid;
4335         }
4336
4337         if (copy_to_user(arg, qsa, sizeof(*qsa)))
4338                 ret = -EFAULT;
4339
4340         kfree(qsa);
4341         return ret;
4342 }
4343
4344 static long btrfs_ioctl_quota_rescan_wait(struct file *file, void __user *arg)
4345 {
4346         struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4347
4348         if (!capable(CAP_SYS_ADMIN))
4349                 return -EPERM;
4350
4351         return btrfs_qgroup_wait_for_completion(root->fs_info);
4352 }
4353
4354 static long btrfs_ioctl_set_received_subvol(struct file *file,
4355                                             void __user *arg)
4356 {
4357         struct btrfs_ioctl_received_subvol_args *sa = NULL;
4358         struct inode *inode = file_inode(file);
4359         struct btrfs_root *root = BTRFS_I(inode)->root;
4360         struct btrfs_root_item *root_item = &root->root_item;
4361         struct btrfs_trans_handle *trans;
4362         struct timespec ct = CURRENT_TIME;
4363         int ret = 0;
4364         int received_uuid_changed;
4365
4366         ret = mnt_want_write_file(file);
4367         if (ret < 0)
4368                 return ret;
4369
4370         down_write(&root->fs_info->subvol_sem);
4371
4372         if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID) {
4373                 ret = -EINVAL;
4374                 goto out;
4375         }
4376
4377         if (btrfs_root_readonly(root)) {
4378                 ret = -EROFS;
4379                 goto out;
4380         }
4381
4382         if (!inode_owner_or_capable(inode)) {
4383                 ret = -EACCES;
4384                 goto out;
4385         }
4386
4387         sa = memdup_user(arg, sizeof(*sa));
4388         if (IS_ERR(sa)) {
4389                 ret = PTR_ERR(sa);
4390                 sa = NULL;
4391                 goto out;
4392         }
4393
4394         /*
4395          * 1 - root item
4396          * 2 - uuid items (received uuid + subvol uuid)
4397          */
4398         trans = btrfs_start_transaction(root, 3);
4399         if (IS_ERR(trans)) {
4400                 ret = PTR_ERR(trans);
4401                 trans = NULL;
4402                 goto out;
4403         }
4404
4405         sa->rtransid = trans->transid;
4406         sa->rtime.sec = ct.tv_sec;
4407         sa->rtime.nsec = ct.tv_nsec;
4408
4409         received_uuid_changed = memcmp(root_item->received_uuid, sa->uuid,
4410                                        BTRFS_UUID_SIZE);
4411         if (received_uuid_changed &&
4412             !btrfs_is_empty_uuid(root_item->received_uuid))
4413                 btrfs_uuid_tree_rem(trans, root->fs_info->uuid_root,
4414                                     root_item->received_uuid,
4415                                     BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4416                                     root->root_key.objectid);
4417         memcpy(root_item->received_uuid, sa->uuid, BTRFS_UUID_SIZE);
4418         btrfs_set_root_stransid(root_item, sa->stransid);
4419         btrfs_set_root_rtransid(root_item, sa->rtransid);
4420         btrfs_set_stack_timespec_sec(&root_item->stime, sa->stime.sec);
4421         btrfs_set_stack_timespec_nsec(&root_item->stime, sa->stime.nsec);
4422         btrfs_set_stack_timespec_sec(&root_item->rtime, sa->rtime.sec);
4423         btrfs_set_stack_timespec_nsec(&root_item->rtime, sa->rtime.nsec);
4424
4425         ret = btrfs_update_root(trans, root->fs_info->tree_root,
4426                                 &root->root_key, &root->root_item);
4427         if (ret < 0) {
4428                 btrfs_end_transaction(trans, root);
4429                 goto out;
4430         }
4431         if (received_uuid_changed && !btrfs_is_empty_uuid(sa->uuid)) {
4432                 ret = btrfs_uuid_tree_add(trans, root->fs_info->uuid_root,
4433                                           sa->uuid,
4434                                           BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4435                                           root->root_key.objectid);
4436                 if (ret < 0 && ret != -EEXIST) {
4437                         btrfs_abort_transaction(trans, root, ret);
4438                         goto out;
4439                 }
4440         }
4441         ret = btrfs_commit_transaction(trans, root);
4442         if (ret < 0) {
4443                 btrfs_abort_transaction(trans, root, ret);
4444                 goto out;
4445         }
4446
4447         ret = copy_to_user(arg, sa, sizeof(*sa));
4448         if (ret)
4449                 ret = -EFAULT;
4450
4451 out:
4452         kfree(sa);
4453         up_write(&root->fs_info->subvol_sem);
4454         mnt_drop_write_file(file);
4455         return ret;
4456 }
4457
4458 static int btrfs_ioctl_get_fslabel(struct file *file, void __user *arg)
4459 {
4460         struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4461         size_t len;
4462         int ret;
4463         char label[BTRFS_LABEL_SIZE];
4464
4465         spin_lock(&root->fs_info->super_lock);
4466         memcpy(label, root->fs_info->super_copy->label, BTRFS_LABEL_SIZE);
4467         spin_unlock(&root->fs_info->super_lock);
4468
4469         len = strnlen(label, BTRFS_LABEL_SIZE);
4470
4471         if (len == BTRFS_LABEL_SIZE) {
4472                 pr_warn("btrfs: label is too long, return the first %zu bytes\n",
4473                         --len);
4474         }
4475
4476         ret = copy_to_user(arg, label, len);
4477
4478         return ret ? -EFAULT : 0;
4479 }
4480
4481 static int btrfs_ioctl_set_fslabel(struct file *file, void __user *arg)
4482 {
4483         struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4484         struct btrfs_super_block *super_block = root->fs_info->super_copy;
4485         struct btrfs_trans_handle *trans;
4486         char label[BTRFS_LABEL_SIZE];
4487         int ret;
4488
4489         if (!capable(CAP_SYS_ADMIN))
4490                 return -EPERM;
4491
4492         if (copy_from_user(label, arg, sizeof(label)))
4493                 return -EFAULT;
4494
4495         if (strnlen(label, BTRFS_LABEL_SIZE) == BTRFS_LABEL_SIZE) {
4496                 pr_err("btrfs: unable to set label with more than %d bytes\n",
4497                        BTRFS_LABEL_SIZE - 1);
4498                 return -EINVAL;
4499         }
4500
4501         ret = mnt_want_write_file(file);
4502         if (ret)
4503                 return ret;
4504
4505         trans = btrfs_start_transaction(root, 0);
4506         if (IS_ERR(trans)) {
4507                 ret = PTR_ERR(trans);
4508                 goto out_unlock;
4509         }
4510
4511         spin_lock(&root->fs_info->super_lock);
4512         strcpy(super_block->label, label);
4513         spin_unlock(&root->fs_info->super_lock);
4514         ret = btrfs_end_transaction(trans, root);
4515
4516 out_unlock:
4517         mnt_drop_write_file(file);
4518         return ret;
4519 }
4520
4521 #define INIT_FEATURE_FLAGS(suffix) \
4522         { .compat_flags = BTRFS_FEATURE_COMPAT_##suffix, \
4523           .compat_ro_flags = BTRFS_FEATURE_COMPAT_RO_##suffix, \
4524           .incompat_flags = BTRFS_FEATURE_INCOMPAT_##suffix }
4525
4526 static int btrfs_ioctl_get_supported_features(struct file *file,
4527                                               void __user *arg)
4528 {
4529         static struct btrfs_ioctl_feature_flags features[3] = {
4530                 INIT_FEATURE_FLAGS(SUPP),
4531                 INIT_FEATURE_FLAGS(SAFE_SET),
4532                 INIT_FEATURE_FLAGS(SAFE_CLEAR)
4533         };
4534
4535         if (copy_to_user(arg, &features, sizeof(features)))
4536                 return -EFAULT;
4537
4538         return 0;
4539 }
4540
4541 static int btrfs_ioctl_get_features(struct file *file, void __user *arg)
4542 {
4543         struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4544         struct btrfs_super_block *super_block = root->fs_info->super_copy;
4545         struct btrfs_ioctl_feature_flags features;
4546
4547         features.compat_flags = btrfs_super_compat_flags(super_block);
4548         features.compat_ro_flags = btrfs_super_compat_ro_flags(super_block);
4549         features.incompat_flags = btrfs_super_incompat_flags(super_block);
4550
4551         if (copy_to_user(arg, &features, sizeof(features)))
4552                 return -EFAULT;
4553
4554         return 0;
4555 }
4556
4557 static int check_feature_bits(struct btrfs_root *root,
4558                               enum btrfs_feature_set set,
4559                               u64 change_mask, u64 flags, u64 supported_flags,
4560                               u64 safe_set, u64 safe_clear)
4561 {
4562         const char *type = btrfs_feature_set_names[set];
4563         char *names;
4564         u64 disallowed, unsupported;
4565         u64 set_mask = flags & change_mask;
4566         u64 clear_mask = ~flags & change_mask;
4567
4568         unsupported = set_mask & ~supported_flags;
4569         if (unsupported) {
4570                 names = btrfs_printable_features(set, unsupported);
4571                 if (names) {
4572                         btrfs_warn(root->fs_info,
4573                            "this kernel does not support the %s feature bit%s",
4574                            names, strchr(names, ',') ? "s" : "");
4575                         kfree(names);
4576                 } else
4577                         btrfs_warn(root->fs_info,
4578                            "this kernel does not support %s bits 0x%llx",
4579                            type, unsupported);
4580                 return -EOPNOTSUPP;
4581         }
4582
4583         disallowed = set_mask & ~safe_set;
4584         if (disallowed) {
4585                 names = btrfs_printable_features(set, disallowed);
4586                 if (names) {
4587                         btrfs_warn(root->fs_info,
4588                            "can't set the %s feature bit%s while mounted",
4589                            names, strchr(names, ',') ? "s" : "");
4590                         kfree(names);
4591                 } else
4592                         btrfs_warn(root->fs_info,
4593                            "can't set %s bits 0x%llx while mounted",
4594                            type, disallowed);
4595                 return -EPERM;
4596         }
4597
4598         disallowed = clear_mask & ~safe_clear;
4599         if (disallowed) {
4600                 names = btrfs_printable_features(set, disallowed);
4601                 if (names) {
4602                         btrfs_warn(root->fs_info,
4603                            "can't clear the %s feature bit%s while mounted",
4604                            names, strchr(names, ',') ? "s" : "");
4605                         kfree(names);
4606                 } else
4607                         btrfs_warn(root->fs_info,
4608                            "can't clear %s bits 0x%llx while mounted",
4609                            type, disallowed);
4610                 return -EPERM;
4611         }
4612
4613         return 0;
4614 }
4615
4616 #define check_feature(root, change_mask, flags, mask_base)      \
4617 check_feature_bits(root, FEAT_##mask_base, change_mask, flags,  \
4618                    BTRFS_FEATURE_ ## mask_base ## _SUPP,        \
4619                    BTRFS_FEATURE_ ## mask_base ## _SAFE_SET,    \
4620                    BTRFS_FEATURE_ ## mask_base ## _SAFE_CLEAR)
4621
4622 static int btrfs_ioctl_set_features(struct file *file, void __user *arg)
4623 {
4624         struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4625         struct btrfs_super_block *super_block = root->fs_info->super_copy;
4626         struct btrfs_ioctl_feature_flags flags[2];
4627         struct btrfs_trans_handle *trans;
4628         u64 newflags;
4629         int ret;
4630
4631         if (!capable(CAP_SYS_ADMIN))
4632                 return -EPERM;
4633
4634         if (copy_from_user(flags, arg, sizeof(flags)))
4635                 return -EFAULT;
4636
4637         /* Nothing to do */
4638         if (!flags[0].compat_flags && !flags[0].compat_ro_flags &&
4639             !flags[0].incompat_flags)
4640                 return 0;
4641
4642         ret = check_feature(root, flags[0].compat_flags,
4643                             flags[1].compat_flags, COMPAT);
4644         if (ret)
4645                 return ret;
4646
4647         ret = check_feature(root, flags[0].compat_ro_flags,
4648                             flags[1].compat_ro_flags, COMPAT_RO);
4649         if (ret)
4650                 return ret;
4651
4652         ret = check_feature(root, flags[0].incompat_flags,
4653                             flags[1].incompat_flags, INCOMPAT);
4654         if (ret)
4655                 return ret;
4656
4657         trans = btrfs_start_transaction(root, 1);
4658         if (IS_ERR(trans))
4659                 return PTR_ERR(trans);
4660
4661         spin_lock(&root->fs_info->super_lock);
4662         newflags = btrfs_super_compat_flags(super_block);
4663         newflags |= flags[0].compat_flags & flags[1].compat_flags;
4664         newflags &= ~(flags[0].compat_flags & ~flags[1].compat_flags);
4665         btrfs_set_super_compat_flags(super_block, newflags);
4666
4667         newflags = btrfs_super_compat_ro_flags(super_block);
4668         newflags |= flags[0].compat_ro_flags & flags[1].compat_ro_flags;
4669         newflags &= ~(flags[0].compat_ro_flags & ~flags[1].compat_ro_flags);
4670         btrfs_set_super_compat_ro_flags(super_block, newflags);
4671
4672         newflags = btrfs_super_incompat_flags(super_block);
4673         newflags |= flags[0].incompat_flags & flags[1].incompat_flags;
4674         newflags &= ~(flags[0].incompat_flags & ~flags[1].incompat_flags);
4675         btrfs_set_super_incompat_flags(super_block, newflags);
4676         spin_unlock(&root->fs_info->super_lock);
4677
4678         return btrfs_end_transaction(trans, root);
4679 }
4680
4681 long btrfs_ioctl(struct file *file, unsigned int
4682                 cmd, unsigned long arg)
4683 {
4684         struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4685         void __user *argp = (void __user *)arg;
4686
4687         switch (cmd) {
4688         case FS_IOC_GETFLAGS:
4689                 return btrfs_ioctl_getflags(file, argp);
4690         case FS_IOC_SETFLAGS:
4691                 return btrfs_ioctl_setflags(file, argp);
4692         case FS_IOC_GETVERSION:
4693                 return btrfs_ioctl_getversion(file, argp);
4694         case FITRIM:
4695                 return btrfs_ioctl_fitrim(file, argp);
4696         case BTRFS_IOC_SNAP_CREATE:
4697                 return btrfs_ioctl_snap_create(file, argp, 0);
4698         case BTRFS_IOC_SNAP_CREATE_V2:
4699                 return btrfs_ioctl_snap_create_v2(file, argp, 0);
4700         case BTRFS_IOC_SUBVOL_CREATE:
4701                 return btrfs_ioctl_snap_create(file, argp, 1);
4702         case BTRFS_IOC_SUBVOL_CREATE_V2:
4703                 return btrfs_ioctl_snap_create_v2(file, argp, 1);
4704         case BTRFS_IOC_SNAP_DESTROY:
4705                 return btrfs_ioctl_snap_destroy(file, argp);
4706         case BTRFS_IOC_SUBVOL_GETFLAGS:
4707                 return btrfs_ioctl_subvol_getflags(file, argp);
4708         case BTRFS_IOC_SUBVOL_SETFLAGS:
4709                 return btrfs_ioctl_subvol_setflags(file, argp);
4710         case BTRFS_IOC_DEFAULT_SUBVOL:
4711                 return btrfs_ioctl_default_subvol(file, argp);
4712         case BTRFS_IOC_DEFRAG:
4713                 return btrfs_ioctl_defrag(file, NULL);
4714         case BTRFS_IOC_DEFRAG_RANGE:
4715                 return btrfs_ioctl_defrag(file, argp);
4716         case BTRFS_IOC_RESIZE:
4717                 return btrfs_ioctl_resize(file, argp);
4718         case BTRFS_IOC_ADD_DEV:
4719                 return btrfs_ioctl_add_dev(root, argp);
4720         case BTRFS_IOC_RM_DEV:
4721                 return btrfs_ioctl_rm_dev(file, argp);
4722         case BTRFS_IOC_FS_INFO:
4723                 return btrfs_ioctl_fs_info(root, argp);
4724         case BTRFS_IOC_DEV_INFO:
4725                 return btrfs_ioctl_dev_info(root, argp);
4726         case BTRFS_IOC_BALANCE:
4727                 return btrfs_ioctl_balance(file, NULL);
4728         case BTRFS_IOC_CLONE:
4729                 return btrfs_ioctl_clone(file, arg, 0, 0, 0);
4730         case BTRFS_IOC_CLONE_RANGE:
4731                 return btrfs_ioctl_clone_range(file, argp);
4732         case BTRFS_IOC_TRANS_START:
4733                 return btrfs_ioctl_trans_start(file);
4734         case BTRFS_IOC_TRANS_END:
4735                 return btrfs_ioctl_trans_end(file);
4736         case BTRFS_IOC_TREE_SEARCH:
4737                 return btrfs_ioctl_tree_search(file, argp);
4738         case BTRFS_IOC_INO_LOOKUP:
4739                 return btrfs_ioctl_ino_lookup(file, argp);
4740         case BTRFS_IOC_INO_PATHS:
4741                 return btrfs_ioctl_ino_to_path(root, argp);
4742         case BTRFS_IOC_LOGICAL_INO:
4743                 return btrfs_ioctl_logical_to_ino(root, argp);
4744         case BTRFS_IOC_SPACE_INFO:
4745                 return btrfs_ioctl_space_info(root, argp);
4746         case BTRFS_IOC_GLOBAL_RSV:
4747                 return btrfs_ioctl_global_rsv(root, argp);
4748         case BTRFS_IOC_SYNC: {
4749                 int ret;
4750
4751                 ret = btrfs_start_delalloc_roots(root->fs_info, 0);
4752                 if (ret)
4753                         return ret;
4754                 ret = btrfs_sync_fs(file->f_dentry->d_sb, 1);
4755                 return ret;
4756         }
4757         case BTRFS_IOC_START_SYNC:
4758                 return btrfs_ioctl_start_sync(root, argp);
4759         case BTRFS_IOC_WAIT_SYNC:
4760                 return btrfs_ioctl_wait_sync(root, argp);
4761         case BTRFS_IOC_SCRUB:
4762                 return btrfs_ioctl_scrub(file, argp);
4763         case BTRFS_IOC_SCRUB_CANCEL:
4764                 return btrfs_ioctl_scrub_cancel(root, argp);
4765         case BTRFS_IOC_SCRUB_PROGRESS:
4766                 return btrfs_ioctl_scrub_progress(root, argp);
4767         case BTRFS_IOC_BALANCE_V2:
4768                 return btrfs_ioctl_balance(file, argp);
4769         case BTRFS_IOC_BALANCE_CTL:
4770                 return btrfs_ioctl_balance_ctl(root, arg);
4771         case BTRFS_IOC_BALANCE_PROGRESS:
4772                 return btrfs_ioctl_balance_progress(root, argp);
4773         case BTRFS_IOC_SET_RECEIVED_SUBVOL:
4774                 return btrfs_ioctl_set_received_subvol(file, argp);
4775         case BTRFS_IOC_SEND:
4776                 return btrfs_ioctl_send(file, argp);
4777         case BTRFS_IOC_GET_DEV_STATS:
4778                 return btrfs_ioctl_get_dev_stats(root, argp);
4779         case BTRFS_IOC_QUOTA_CTL:
4780                 return btrfs_ioctl_quota_ctl(file, argp);
4781         case BTRFS_IOC_QGROUP_ASSIGN:
4782                 return btrfs_ioctl_qgroup_assign(file, argp);
4783         case BTRFS_IOC_QGROUP_CREATE:
4784                 return btrfs_ioctl_qgroup_create(file, argp);
4785         case BTRFS_IOC_QGROUP_LIMIT:
4786                 return btrfs_ioctl_qgroup_limit(file, argp);
4787         case BTRFS_IOC_QUOTA_RESCAN:
4788                 return btrfs_ioctl_quota_rescan(file, argp);
4789         case BTRFS_IOC_QUOTA_RESCAN_STATUS:
4790                 return btrfs_ioctl_quota_rescan_status(file, argp);
4791         case BTRFS_IOC_QUOTA_RESCAN_WAIT:
4792                 return btrfs_ioctl_quota_rescan_wait(file, argp);
4793         case BTRFS_IOC_DEV_REPLACE:
4794                 return btrfs_ioctl_dev_replace(root, argp);
4795         case BTRFS_IOC_GET_FSLABEL:
4796                 return btrfs_ioctl_get_fslabel(file, argp);
4797         case BTRFS_IOC_SET_FSLABEL:
4798                 return btrfs_ioctl_set_fslabel(file, argp);
4799         case BTRFS_IOC_FILE_EXTENT_SAME:
4800                 return btrfs_ioctl_file_extent_same(file, argp);
4801         case BTRFS_IOC_GET_SUPPORTED_FEATURES:
4802                 return btrfs_ioctl_get_supported_features(file, argp);
4803         case BTRFS_IOC_GET_FEATURES:
4804                 return btrfs_ioctl_get_features(file, argp);
4805         case BTRFS_IOC_SET_FEATURES:
4806                 return btrfs_ioctl_set_features(file, argp);
4807         }
4808
4809         return -ENOTTY;
4810 }