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