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