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