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