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