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