btrfs: fix search key advancing condition
[muen/linux.git] / fs / btrfs / ioctl.c
1 /*
2  * Copyright (C) 2007 Oracle.  All rights reserved.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public
6  * License v2 as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public
14  * License along with this program; if not, write to the
15  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16  * Boston, MA 021110-1307, USA.
17  */
18
19 #include <linux/kernel.h>
20 #include <linux/bio.h>
21 #include <linux/buffer_head.h>
22 #include <linux/file.h>
23 #include <linux/fs.h>
24 #include <linux/fsnotify.h>
25 #include <linux/pagemap.h>
26 #include <linux/highmem.h>
27 #include <linux/time.h>
28 #include <linux/init.h>
29 #include <linux/string.h>
30 #include <linux/backing-dev.h>
31 #include <linux/mount.h>
32 #include <linux/mpage.h>
33 #include <linux/namei.h>
34 #include <linux/swap.h>
35 #include <linux/writeback.h>
36 #include <linux/statfs.h>
37 #include <linux/compat.h>
38 #include <linux/bit_spinlock.h>
39 #include <linux/security.h>
40 #include <linux/xattr.h>
41 #include <linux/vmalloc.h>
42 #include <linux/slab.h>
43 #include <linux/blkdev.h>
44 #include <linux/uuid.h>
45 #include <linux/btrfs.h>
46 #include <linux/uaccess.h>
47 #include "ctree.h"
48 #include "disk-io.h"
49 #include "transaction.h"
50 #include "btrfs_inode.h"
51 #include "print-tree.h"
52 #include "volumes.h"
53 #include "locking.h"
54 #include "inode-map.h"
55 #include "backref.h"
56 #include "rcu-string.h"
57 #include "send.h"
58 #include "dev-replace.h"
59 #include "props.h"
60 #include "sysfs.h"
61 #include "qgroup.h"
62
63 #ifdef CONFIG_64BIT
64 /* If we have a 32-bit userspace and 64-bit kernel, then the UAPI
65  * structures are incorrect, as the timespec structure from userspace
66  * is 4 bytes too small. We define these alternatives here to teach
67  * the kernel about the 32-bit struct packing.
68  */
69 struct btrfs_ioctl_timespec_32 {
70         __u64 sec;
71         __u32 nsec;
72 } __attribute__ ((__packed__));
73
74 struct btrfs_ioctl_received_subvol_args_32 {
75         char    uuid[BTRFS_UUID_SIZE];  /* in */
76         __u64   stransid;               /* in */
77         __u64   rtransid;               /* out */
78         struct btrfs_ioctl_timespec_32 stime; /* in */
79         struct btrfs_ioctl_timespec_32 rtime; /* out */
80         __u64   flags;                  /* in */
81         __u64   reserved[16];           /* in */
82 } __attribute__ ((__packed__));
83
84 #define BTRFS_IOC_SET_RECEIVED_SUBVOL_32 _IOWR(BTRFS_IOCTL_MAGIC, 37, \
85                                 struct btrfs_ioctl_received_subvol_args_32)
86 #endif
87
88
89 static int btrfs_clone(struct inode *src, struct inode *inode,
90                        u64 off, u64 olen, u64 olen_aligned, u64 destoff,
91                        int no_time_update);
92
93 /* Mask out flags that are inappropriate for the given type of inode. */
94 static inline __u32 btrfs_mask_flags(umode_t mode, __u32 flags)
95 {
96         if (S_ISDIR(mode))
97                 return flags;
98         else if (S_ISREG(mode))
99                 return flags & ~FS_DIRSYNC_FL;
100         else
101                 return flags & (FS_NODUMP_FL | FS_NOATIME_FL);
102 }
103
104 /*
105  * Export inode flags to the format expected by the FS_IOC_GETFLAGS ioctl.
106  */
107 static unsigned int btrfs_flags_to_ioctl(unsigned int flags)
108 {
109         unsigned int iflags = 0;
110
111         if (flags & BTRFS_INODE_SYNC)
112                 iflags |= FS_SYNC_FL;
113         if (flags & BTRFS_INODE_IMMUTABLE)
114                 iflags |= FS_IMMUTABLE_FL;
115         if (flags & BTRFS_INODE_APPEND)
116                 iflags |= FS_APPEND_FL;
117         if (flags & BTRFS_INODE_NODUMP)
118                 iflags |= FS_NODUMP_FL;
119         if (flags & BTRFS_INODE_NOATIME)
120                 iflags |= FS_NOATIME_FL;
121         if (flags & BTRFS_INODE_DIRSYNC)
122                 iflags |= FS_DIRSYNC_FL;
123         if (flags & BTRFS_INODE_NODATACOW)
124                 iflags |= FS_NOCOW_FL;
125
126         if ((flags & BTRFS_INODE_COMPRESS) && !(flags & BTRFS_INODE_NOCOMPRESS))
127                 iflags |= FS_COMPR_FL;
128         else if (flags & BTRFS_INODE_NOCOMPRESS)
129                 iflags |= FS_NOCOMP_FL;
130
131         return iflags;
132 }
133
134 /*
135  * Update inode->i_flags based on the btrfs internal flags.
136  */
137 void btrfs_update_iflags(struct inode *inode)
138 {
139         struct btrfs_inode *ip = BTRFS_I(inode);
140         unsigned int new_fl = 0;
141
142         if (ip->flags & BTRFS_INODE_SYNC)
143                 new_fl |= S_SYNC;
144         if (ip->flags & BTRFS_INODE_IMMUTABLE)
145                 new_fl |= S_IMMUTABLE;
146         if (ip->flags & BTRFS_INODE_APPEND)
147                 new_fl |= S_APPEND;
148         if (ip->flags & BTRFS_INODE_NOATIME)
149                 new_fl |= S_NOATIME;
150         if (ip->flags & BTRFS_INODE_DIRSYNC)
151                 new_fl |= S_DIRSYNC;
152
153         set_mask_bits(&inode->i_flags,
154                       S_SYNC | S_APPEND | S_IMMUTABLE | S_NOATIME | S_DIRSYNC,
155                       new_fl);
156 }
157
158 /*
159  * Inherit flags from the parent inode.
160  *
161  * Currently only the compression flags and the cow flags are inherited.
162  */
163 void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
164 {
165         unsigned int flags;
166
167         if (!dir)
168                 return;
169
170         flags = BTRFS_I(dir)->flags;
171
172         if (flags & BTRFS_INODE_NOCOMPRESS) {
173                 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
174                 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
175         } else if (flags & BTRFS_INODE_COMPRESS) {
176                 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
177                 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
178         }
179
180         if (flags & BTRFS_INODE_NODATACOW) {
181                 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
182                 if (S_ISREG(inode->i_mode))
183                         BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
184         }
185
186         btrfs_update_iflags(inode);
187 }
188
189 static int btrfs_ioctl_getflags(struct file *file, void __user *arg)
190 {
191         struct btrfs_inode *ip = BTRFS_I(file_inode(file));
192         unsigned int flags = btrfs_flags_to_ioctl(ip->flags);
193
194         if (copy_to_user(arg, &flags, sizeof(flags)))
195                 return -EFAULT;
196         return 0;
197 }
198
199 static int check_flags(unsigned int flags)
200 {
201         if (flags & ~(FS_IMMUTABLE_FL | FS_APPEND_FL | \
202                       FS_NOATIME_FL | FS_NODUMP_FL | \
203                       FS_SYNC_FL | FS_DIRSYNC_FL | \
204                       FS_NOCOMP_FL | FS_COMPR_FL |
205                       FS_NOCOW_FL))
206                 return -EOPNOTSUPP;
207
208         if ((flags & FS_NOCOMP_FL) && (flags & FS_COMPR_FL))
209                 return -EINVAL;
210
211         return 0;
212 }
213
214 static int btrfs_ioctl_setflags(struct file *file, void __user *arg)
215 {
216         struct inode *inode = file_inode(file);
217         struct btrfs_inode *ip = BTRFS_I(inode);
218         struct btrfs_root *root = ip->root;
219         struct btrfs_trans_handle *trans;
220         unsigned int flags, oldflags;
221         int ret;
222         u64 ip_oldflags;
223         unsigned int i_oldflags;
224         umode_t mode;
225
226         if (!inode_owner_or_capable(inode))
227                 return -EPERM;
228
229         if (btrfs_root_readonly(root))
230                 return -EROFS;
231
232         if (copy_from_user(&flags, arg, sizeof(flags)))
233                 return -EFAULT;
234
235         ret = check_flags(flags);
236         if (ret)
237                 return ret;
238
239         ret = mnt_want_write_file(file);
240         if (ret)
241                 return ret;
242
243         mutex_lock(&inode->i_mutex);
244
245         ip_oldflags = ip->flags;
246         i_oldflags = inode->i_flags;
247         mode = inode->i_mode;
248
249         flags = btrfs_mask_flags(inode->i_mode, flags);
250         oldflags = btrfs_flags_to_ioctl(ip->flags);
251         if ((flags ^ oldflags) & (FS_APPEND_FL | FS_IMMUTABLE_FL)) {
252                 if (!capable(CAP_LINUX_IMMUTABLE)) {
253                         ret = -EPERM;
254                         goto out_unlock;
255                 }
256         }
257
258         if (flags & FS_SYNC_FL)
259                 ip->flags |= BTRFS_INODE_SYNC;
260         else
261                 ip->flags &= ~BTRFS_INODE_SYNC;
262         if (flags & FS_IMMUTABLE_FL)
263                 ip->flags |= BTRFS_INODE_IMMUTABLE;
264         else
265                 ip->flags &= ~BTRFS_INODE_IMMUTABLE;
266         if (flags & FS_APPEND_FL)
267                 ip->flags |= BTRFS_INODE_APPEND;
268         else
269                 ip->flags &= ~BTRFS_INODE_APPEND;
270         if (flags & FS_NODUMP_FL)
271                 ip->flags |= BTRFS_INODE_NODUMP;
272         else
273                 ip->flags &= ~BTRFS_INODE_NODUMP;
274         if (flags & FS_NOATIME_FL)
275                 ip->flags |= BTRFS_INODE_NOATIME;
276         else
277                 ip->flags &= ~BTRFS_INODE_NOATIME;
278         if (flags & FS_DIRSYNC_FL)
279                 ip->flags |= BTRFS_INODE_DIRSYNC;
280         else
281                 ip->flags &= ~BTRFS_INODE_DIRSYNC;
282         if (flags & FS_NOCOW_FL) {
283                 if (S_ISREG(mode)) {
284                         /*
285                          * It's safe to turn csums off here, no extents exist.
286                          * Otherwise we want the flag to reflect the real COW
287                          * status of the file and will not set it.
288                          */
289                         if (inode->i_size == 0)
290                                 ip->flags |= BTRFS_INODE_NODATACOW
291                                            | BTRFS_INODE_NODATASUM;
292                 } else {
293                         ip->flags |= BTRFS_INODE_NODATACOW;
294                 }
295         } else {
296                 /*
297                  * Revert back under same assuptions as above
298                  */
299                 if (S_ISREG(mode)) {
300                         if (inode->i_size == 0)
301                                 ip->flags &= ~(BTRFS_INODE_NODATACOW
302                                              | BTRFS_INODE_NODATASUM);
303                 } else {
304                         ip->flags &= ~BTRFS_INODE_NODATACOW;
305                 }
306         }
307
308         /*
309          * The COMPRESS flag can only be changed by users, while the NOCOMPRESS
310          * flag may be changed automatically if compression code won't make
311          * things smaller.
312          */
313         if (flags & FS_NOCOMP_FL) {
314                 ip->flags &= ~BTRFS_INODE_COMPRESS;
315                 ip->flags |= BTRFS_INODE_NOCOMPRESS;
316
317                 ret = btrfs_set_prop(inode, "btrfs.compression", NULL, 0, 0);
318                 if (ret && ret != -ENODATA)
319                         goto out_drop;
320         } else if (flags & FS_COMPR_FL) {
321                 const char *comp;
322
323                 ip->flags |= BTRFS_INODE_COMPRESS;
324                 ip->flags &= ~BTRFS_INODE_NOCOMPRESS;
325
326                 if (root->fs_info->compress_type == BTRFS_COMPRESS_LZO)
327                         comp = "lzo";
328                 else
329                         comp = "zlib";
330                 ret = btrfs_set_prop(inode, "btrfs.compression",
331                                      comp, strlen(comp), 0);
332                 if (ret)
333                         goto out_drop;
334
335         } else {
336                 ret = btrfs_set_prop(inode, "btrfs.compression", NULL, 0, 0);
337                 if (ret && ret != -ENODATA)
338                         goto out_drop;
339                 ip->flags &= ~(BTRFS_INODE_COMPRESS | BTRFS_INODE_NOCOMPRESS);
340         }
341
342         trans = btrfs_start_transaction(root, 1);
343         if (IS_ERR(trans)) {
344                 ret = PTR_ERR(trans);
345                 goto out_drop;
346         }
347
348         btrfs_update_iflags(inode);
349         inode_inc_iversion(inode);
350         inode->i_ctime = CURRENT_TIME;
351         ret = btrfs_update_inode(trans, root, inode);
352
353         btrfs_end_transaction(trans, root);
354  out_drop:
355         if (ret) {
356                 ip->flags = ip_oldflags;
357                 inode->i_flags = i_oldflags;
358         }
359
360  out_unlock:
361         mutex_unlock(&inode->i_mutex);
362         mnt_drop_write_file(file);
363         return ret;
364 }
365
366 static int btrfs_ioctl_getversion(struct file *file, int __user *arg)
367 {
368         struct inode *inode = file_inode(file);
369
370         return put_user(inode->i_generation, arg);
371 }
372
373 static noinline int btrfs_ioctl_fitrim(struct file *file, void __user *arg)
374 {
375         struct btrfs_fs_info *fs_info = btrfs_sb(file_inode(file)->i_sb);
376         struct btrfs_device *device;
377         struct request_queue *q;
378         struct fstrim_range range;
379         u64 minlen = ULLONG_MAX;
380         u64 num_devices = 0;
381         u64 total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
382         int ret;
383
384         if (!capable(CAP_SYS_ADMIN))
385                 return -EPERM;
386
387         rcu_read_lock();
388         list_for_each_entry_rcu(device, &fs_info->fs_devices->devices,
389                                 dev_list) {
390                 if (!device->bdev)
391                         continue;
392                 q = bdev_get_queue(device->bdev);
393                 if (blk_queue_discard(q)) {
394                         num_devices++;
395                         minlen = min((u64)q->limits.discard_granularity,
396                                      minlen);
397                 }
398         }
399         rcu_read_unlock();
400
401         if (!num_devices)
402                 return -EOPNOTSUPP;
403         if (copy_from_user(&range, arg, sizeof(range)))
404                 return -EFAULT;
405         if (range.start > total_bytes ||
406             range.len < fs_info->sb->s_blocksize)
407                 return -EINVAL;
408
409         range.len = min(range.len, total_bytes - range.start);
410         range.minlen = max(range.minlen, minlen);
411         ret = btrfs_trim_fs(fs_info->tree_root, &range);
412         if (ret < 0)
413                 return ret;
414
415         if (copy_to_user(arg, &range, sizeof(range)))
416                 return -EFAULT;
417
418         return 0;
419 }
420
421 int btrfs_is_empty_uuid(u8 *uuid)
422 {
423         int i;
424
425         for (i = 0; i < BTRFS_UUID_SIZE; i++) {
426                 if (uuid[i])
427                         return 0;
428         }
429         return 1;
430 }
431
432 static noinline int create_subvol(struct inode *dir,
433                                   struct dentry *dentry,
434                                   char *name, int namelen,
435                                   u64 *async_transid,
436                                   struct btrfs_qgroup_inherit *inherit)
437 {
438         struct btrfs_trans_handle *trans;
439         struct btrfs_key key;
440         struct btrfs_root_item root_item;
441         struct btrfs_inode_item *inode_item;
442         struct extent_buffer *leaf;
443         struct btrfs_root *root = BTRFS_I(dir)->root;
444         struct btrfs_root *new_root;
445         struct btrfs_block_rsv block_rsv;
446         struct timespec cur_time = CURRENT_TIME;
447         struct inode *inode;
448         int ret;
449         int err;
450         u64 objectid;
451         u64 new_dirid = BTRFS_FIRST_FREE_OBJECTID;
452         u64 index = 0;
453         u64 qgroup_reserved;
454         uuid_le new_uuid;
455
456         ret = btrfs_find_free_objectid(root->fs_info->tree_root, &objectid);
457         if (ret)
458                 return ret;
459
460         /*
461          * Don't create subvolume whose level is not zero. Or qgroup will be
462          * screwed up since it assume subvolme qgroup's level to be 0.
463          */
464         if (btrfs_qgroup_level(objectid))
465                 return -ENOSPC;
466
467         btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
468         /*
469          * The same as the snapshot creation, please see the comment
470          * of create_snapshot().
471          */
472         ret = btrfs_subvolume_reserve_metadata(root, &block_rsv,
473                                                8, &qgroup_reserved, false);
474         if (ret)
475                 return ret;
476
477         trans = btrfs_start_transaction(root, 0);
478         if (IS_ERR(trans)) {
479                 ret = PTR_ERR(trans);
480                 btrfs_subvolume_release_metadata(root, &block_rsv,
481                                                  qgroup_reserved);
482                 return ret;
483         }
484         trans->block_rsv = &block_rsv;
485         trans->bytes_reserved = block_rsv.size;
486
487         ret = btrfs_qgroup_inherit(trans, root->fs_info, 0, objectid, inherit);
488         if (ret)
489                 goto fail;
490
491         leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0);
492         if (IS_ERR(leaf)) {
493                 ret = PTR_ERR(leaf);
494                 goto fail;
495         }
496
497         memset_extent_buffer(leaf, 0, 0, sizeof(struct btrfs_header));
498         btrfs_set_header_bytenr(leaf, leaf->start);
499         btrfs_set_header_generation(leaf, trans->transid);
500         btrfs_set_header_backref_rev(leaf, BTRFS_MIXED_BACKREF_REV);
501         btrfs_set_header_owner(leaf, objectid);
502
503         write_extent_buffer(leaf, root->fs_info->fsid, btrfs_header_fsid(),
504                             BTRFS_FSID_SIZE);
505         write_extent_buffer(leaf, root->fs_info->chunk_tree_uuid,
506                             btrfs_header_chunk_tree_uuid(leaf),
507                             BTRFS_UUID_SIZE);
508         btrfs_mark_buffer_dirty(leaf);
509
510         memset(&root_item, 0, sizeof(root_item));
511
512         inode_item = &root_item.inode;
513         btrfs_set_stack_inode_generation(inode_item, 1);
514         btrfs_set_stack_inode_size(inode_item, 3);
515         btrfs_set_stack_inode_nlink(inode_item, 1);
516         btrfs_set_stack_inode_nbytes(inode_item, root->nodesize);
517         btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
518
519         btrfs_set_root_flags(&root_item, 0);
520         btrfs_set_root_limit(&root_item, 0);
521         btrfs_set_stack_inode_flags(inode_item, BTRFS_INODE_ROOT_ITEM_INIT);
522
523         btrfs_set_root_bytenr(&root_item, leaf->start);
524         btrfs_set_root_generation(&root_item, trans->transid);
525         btrfs_set_root_level(&root_item, 0);
526         btrfs_set_root_refs(&root_item, 1);
527         btrfs_set_root_used(&root_item, leaf->len);
528         btrfs_set_root_last_snapshot(&root_item, 0);
529
530         btrfs_set_root_generation_v2(&root_item,
531                         btrfs_root_generation(&root_item));
532         uuid_le_gen(&new_uuid);
533         memcpy(root_item.uuid, new_uuid.b, BTRFS_UUID_SIZE);
534         btrfs_set_stack_timespec_sec(&root_item.otime, cur_time.tv_sec);
535         btrfs_set_stack_timespec_nsec(&root_item.otime, cur_time.tv_nsec);
536         root_item.ctime = root_item.otime;
537         btrfs_set_root_ctransid(&root_item, trans->transid);
538         btrfs_set_root_otransid(&root_item, trans->transid);
539
540         btrfs_tree_unlock(leaf);
541         free_extent_buffer(leaf);
542         leaf = NULL;
543
544         btrfs_set_root_dirid(&root_item, new_dirid);
545
546         key.objectid = objectid;
547         key.offset = 0;
548         key.type = BTRFS_ROOT_ITEM_KEY;
549         ret = btrfs_insert_root(trans, root->fs_info->tree_root, &key,
550                                 &root_item);
551         if (ret)
552                 goto fail;
553
554         key.offset = (u64)-1;
555         new_root = btrfs_read_fs_root_no_name(root->fs_info, &key);
556         if (IS_ERR(new_root)) {
557                 ret = PTR_ERR(new_root);
558                 btrfs_abort_transaction(trans, root, ret);
559                 goto fail;
560         }
561
562         btrfs_record_root_in_trans(trans, new_root);
563
564         ret = btrfs_create_subvol_root(trans, new_root, root, new_dirid);
565         if (ret) {
566                 /* We potentially lose an unused inode item here */
567                 btrfs_abort_transaction(trans, root, ret);
568                 goto fail;
569         }
570
571         /*
572          * insert the directory item
573          */
574         ret = btrfs_set_inode_index(dir, &index);
575         if (ret) {
576                 btrfs_abort_transaction(trans, root, ret);
577                 goto fail;
578         }
579
580         ret = btrfs_insert_dir_item(trans, root,
581                                     name, namelen, dir, &key,
582                                     BTRFS_FT_DIR, index);
583         if (ret) {
584                 btrfs_abort_transaction(trans, root, ret);
585                 goto fail;
586         }
587
588         btrfs_i_size_write(dir, dir->i_size + namelen * 2);
589         ret = btrfs_update_inode(trans, root, dir);
590         BUG_ON(ret);
591
592         ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
593                                  objectid, root->root_key.objectid,
594                                  btrfs_ino(dir), index, name, namelen);
595         BUG_ON(ret);
596
597         ret = btrfs_uuid_tree_add(trans, root->fs_info->uuid_root,
598                                   root_item.uuid, BTRFS_UUID_KEY_SUBVOL,
599                                   objectid);
600         if (ret)
601                 btrfs_abort_transaction(trans, root, ret);
602
603 fail:
604         trans->block_rsv = NULL;
605         trans->bytes_reserved = 0;
606         btrfs_subvolume_release_metadata(root, &block_rsv, qgroup_reserved);
607
608         if (async_transid) {
609                 *async_transid = trans->transid;
610                 err = btrfs_commit_transaction_async(trans, root, 1);
611                 if (err)
612                         err = btrfs_commit_transaction(trans, root);
613         } else {
614                 err = btrfs_commit_transaction(trans, root);
615         }
616         if (err && !ret)
617                 ret = err;
618
619         if (!ret) {
620                 inode = btrfs_lookup_dentry(dir, dentry);
621                 if (IS_ERR(inode))
622                         return PTR_ERR(inode);
623                 d_instantiate(dentry, inode);
624         }
625         return ret;
626 }
627
628 static void btrfs_wait_for_no_snapshoting_writes(struct btrfs_root *root)
629 {
630         s64 writers;
631         DEFINE_WAIT(wait);
632
633         do {
634                 prepare_to_wait(&root->subv_writers->wait, &wait,
635                                 TASK_UNINTERRUPTIBLE);
636
637                 writers = percpu_counter_sum(&root->subv_writers->counter);
638                 if (writers)
639                         schedule();
640
641                 finish_wait(&root->subv_writers->wait, &wait);
642         } while (writers);
643 }
644
645 static int create_snapshot(struct btrfs_root *root, struct inode *dir,
646                            struct dentry *dentry, char *name, int namelen,
647                            u64 *async_transid, bool readonly,
648                            struct btrfs_qgroup_inherit *inherit)
649 {
650         struct inode *inode;
651         struct btrfs_pending_snapshot *pending_snapshot;
652         struct btrfs_trans_handle *trans;
653         int ret;
654
655         if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state))
656                 return -EINVAL;
657
658         atomic_inc(&root->will_be_snapshoted);
659         smp_mb__after_atomic();
660         btrfs_wait_for_no_snapshoting_writes(root);
661
662         ret = btrfs_start_delalloc_inodes(root, 0);
663         if (ret)
664                 goto out;
665
666         btrfs_wait_ordered_extents(root, -1);
667
668         pending_snapshot = kzalloc(sizeof(*pending_snapshot), GFP_NOFS);
669         if (!pending_snapshot) {
670                 ret = -ENOMEM;
671                 goto out;
672         }
673
674         btrfs_init_block_rsv(&pending_snapshot->block_rsv,
675                              BTRFS_BLOCK_RSV_TEMP);
676         /*
677          * 1 - parent dir inode
678          * 2 - dir entries
679          * 1 - root item
680          * 2 - root ref/backref
681          * 1 - root of snapshot
682          * 1 - UUID item
683          */
684         ret = btrfs_subvolume_reserve_metadata(BTRFS_I(dir)->root,
685                                         &pending_snapshot->block_rsv, 8,
686                                         &pending_snapshot->qgroup_reserved,
687                                         false);
688         if (ret)
689                 goto free;
690
691         pending_snapshot->dentry = dentry;
692         pending_snapshot->root = root;
693         pending_snapshot->readonly = readonly;
694         pending_snapshot->dir = dir;
695         pending_snapshot->inherit = inherit;
696
697         trans = btrfs_start_transaction(root, 0);
698         if (IS_ERR(trans)) {
699                 ret = PTR_ERR(trans);
700                 goto fail;
701         }
702
703         spin_lock(&root->fs_info->trans_lock);
704         list_add(&pending_snapshot->list,
705                  &trans->transaction->pending_snapshots);
706         spin_unlock(&root->fs_info->trans_lock);
707         if (async_transid) {
708                 *async_transid = trans->transid;
709                 ret = btrfs_commit_transaction_async(trans,
710                                      root->fs_info->extent_root, 1);
711                 if (ret)
712                         ret = btrfs_commit_transaction(trans, root);
713         } else {
714                 ret = btrfs_commit_transaction(trans,
715                                                root->fs_info->extent_root);
716         }
717         if (ret)
718                 goto fail;
719
720         ret = pending_snapshot->error;
721         if (ret)
722                 goto fail;
723
724         ret = btrfs_orphan_cleanup(pending_snapshot->snap);
725         if (ret)
726                 goto fail;
727
728         inode = btrfs_lookup_dentry(d_inode(dentry->d_parent), dentry);
729         if (IS_ERR(inode)) {
730                 ret = PTR_ERR(inode);
731                 goto fail;
732         }
733
734         d_instantiate(dentry, inode);
735         ret = 0;
736 fail:
737         btrfs_subvolume_release_metadata(BTRFS_I(dir)->root,
738                                          &pending_snapshot->block_rsv,
739                                          pending_snapshot->qgroup_reserved);
740 free:
741         kfree(pending_snapshot);
742 out:
743         if (atomic_dec_and_test(&root->will_be_snapshoted))
744                 wake_up_atomic_t(&root->will_be_snapshoted);
745         return ret;
746 }
747
748 /*  copy of may_delete in fs/namei.c()
749  *      Check whether we can remove a link victim from directory dir, check
750  *  whether the type of victim is right.
751  *  1. We can't do it if dir is read-only (done in permission())
752  *  2. We should have write and exec permissions on dir
753  *  3. We can't remove anything from append-only dir
754  *  4. We can't do anything with immutable dir (done in permission())
755  *  5. If the sticky bit on dir is set we should either
756  *      a. be owner of dir, or
757  *      b. be owner of victim, or
758  *      c. have CAP_FOWNER capability
759  *  6. If the victim is append-only or immutable we can't do antyhing with
760  *     links pointing to it.
761  *  7. If we were asked to remove a directory and victim isn't one - ENOTDIR.
762  *  8. If we were asked to remove a non-directory and victim isn't one - EISDIR.
763  *  9. We can't remove a root or mountpoint.
764  * 10. We don't allow removal of NFS sillyrenamed files; it's handled by
765  *     nfs_async_unlink().
766  */
767
768 static int btrfs_may_delete(struct inode *dir, struct dentry *victim, int isdir)
769 {
770         int error;
771
772         if (d_really_is_negative(victim))
773                 return -ENOENT;
774
775         BUG_ON(d_inode(victim->d_parent) != dir);
776         audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE);
777
778         error = inode_permission(dir, MAY_WRITE | MAY_EXEC);
779         if (error)
780                 return error;
781         if (IS_APPEND(dir))
782                 return -EPERM;
783         if (check_sticky(dir, d_inode(victim)) || IS_APPEND(d_inode(victim)) ||
784             IS_IMMUTABLE(d_inode(victim)) || IS_SWAPFILE(d_inode(victim)))
785                 return -EPERM;
786         if (isdir) {
787                 if (!d_is_dir(victim))
788                         return -ENOTDIR;
789                 if (IS_ROOT(victim))
790                         return -EBUSY;
791         } else if (d_is_dir(victim))
792                 return -EISDIR;
793         if (IS_DEADDIR(dir))
794                 return -ENOENT;
795         if (victim->d_flags & DCACHE_NFSFS_RENAMED)
796                 return -EBUSY;
797         return 0;
798 }
799
800 /* copy of may_create in fs/namei.c() */
801 static inline int btrfs_may_create(struct inode *dir, struct dentry *child)
802 {
803         if (d_really_is_positive(child))
804                 return -EEXIST;
805         if (IS_DEADDIR(dir))
806                 return -ENOENT;
807         return inode_permission(dir, MAY_WRITE | MAY_EXEC);
808 }
809
810 /*
811  * Create a new subvolume below @parent.  This is largely modeled after
812  * sys_mkdirat and vfs_mkdir, but we only do a single component lookup
813  * inside this filesystem so it's quite a bit simpler.
814  */
815 static noinline int btrfs_mksubvol(struct path *parent,
816                                    char *name, int namelen,
817                                    struct btrfs_root *snap_src,
818                                    u64 *async_transid, bool readonly,
819                                    struct btrfs_qgroup_inherit *inherit)
820 {
821         struct inode *dir  = d_inode(parent->dentry);
822         struct dentry *dentry;
823         int error;
824
825         error = mutex_lock_killable_nested(&dir->i_mutex, I_MUTEX_PARENT);
826         if (error == -EINTR)
827                 return error;
828
829         dentry = lookup_one_len(name, parent->dentry, namelen);
830         error = PTR_ERR(dentry);
831         if (IS_ERR(dentry))
832                 goto out_unlock;
833
834         error = -EEXIST;
835         if (d_really_is_positive(dentry))
836                 goto out_dput;
837
838         error = btrfs_may_create(dir, dentry);
839         if (error)
840                 goto out_dput;
841
842         /*
843          * even if this name doesn't exist, we may get hash collisions.
844          * check for them now when we can safely fail
845          */
846         error = btrfs_check_dir_item_collision(BTRFS_I(dir)->root,
847                                                dir->i_ino, name,
848                                                namelen);
849         if (error)
850                 goto out_dput;
851
852         down_read(&BTRFS_I(dir)->root->fs_info->subvol_sem);
853
854         if (btrfs_root_refs(&BTRFS_I(dir)->root->root_item) == 0)
855                 goto out_up_read;
856
857         if (snap_src) {
858                 error = create_snapshot(snap_src, dir, dentry, name, namelen,
859                                         async_transid, readonly, inherit);
860         } else {
861                 error = create_subvol(dir, dentry, name, namelen,
862                                       async_transid, inherit);
863         }
864         if (!error)
865                 fsnotify_mkdir(dir, dentry);
866 out_up_read:
867         up_read(&BTRFS_I(dir)->root->fs_info->subvol_sem);
868 out_dput:
869         dput(dentry);
870 out_unlock:
871         mutex_unlock(&dir->i_mutex);
872         return error;
873 }
874
875 /*
876  * When we're defragging a range, we don't want to kick it off again
877  * if it is really just waiting for delalloc to send it down.
878  * If we find a nice big extent or delalloc range for the bytes in the
879  * file you want to defrag, we return 0 to let you know to skip this
880  * part of the file
881  */
882 static int check_defrag_in_cache(struct inode *inode, u64 offset, u32 thresh)
883 {
884         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
885         struct extent_map *em = NULL;
886         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
887         u64 end;
888
889         read_lock(&em_tree->lock);
890         em = lookup_extent_mapping(em_tree, offset, PAGE_CACHE_SIZE);
891         read_unlock(&em_tree->lock);
892
893         if (em) {
894                 end = extent_map_end(em);
895                 free_extent_map(em);
896                 if (end - offset > thresh)
897                         return 0;
898         }
899         /* if we already have a nice delalloc here, just stop */
900         thresh /= 2;
901         end = count_range_bits(io_tree, &offset, offset + thresh,
902                                thresh, EXTENT_DELALLOC, 1);
903         if (end >= thresh)
904                 return 0;
905         return 1;
906 }
907
908 /*
909  * helper function to walk through a file and find extents
910  * newer than a specific transid, and smaller than thresh.
911  *
912  * This is used by the defragging code to find new and small
913  * extents
914  */
915 static int find_new_extents(struct btrfs_root *root,
916                             struct inode *inode, u64 newer_than,
917                             u64 *off, u32 thresh)
918 {
919         struct btrfs_path *path;
920         struct btrfs_key min_key;
921         struct extent_buffer *leaf;
922         struct btrfs_file_extent_item *extent;
923         int type;
924         int ret;
925         u64 ino = btrfs_ino(inode);
926
927         path = btrfs_alloc_path();
928         if (!path)
929                 return -ENOMEM;
930
931         min_key.objectid = ino;
932         min_key.type = BTRFS_EXTENT_DATA_KEY;
933         min_key.offset = *off;
934
935         while (1) {
936                 ret = btrfs_search_forward(root, &min_key, path, newer_than);
937                 if (ret != 0)
938                         goto none;
939 process_slot:
940                 if (min_key.objectid != ino)
941                         goto none;
942                 if (min_key.type != BTRFS_EXTENT_DATA_KEY)
943                         goto none;
944
945                 leaf = path->nodes[0];
946                 extent = btrfs_item_ptr(leaf, path->slots[0],
947                                         struct btrfs_file_extent_item);
948
949                 type = btrfs_file_extent_type(leaf, extent);
950                 if (type == BTRFS_FILE_EXTENT_REG &&
951                     btrfs_file_extent_num_bytes(leaf, extent) < thresh &&
952                     check_defrag_in_cache(inode, min_key.offset, thresh)) {
953                         *off = min_key.offset;
954                         btrfs_free_path(path);
955                         return 0;
956                 }
957
958                 path->slots[0]++;
959                 if (path->slots[0] < btrfs_header_nritems(leaf)) {
960                         btrfs_item_key_to_cpu(leaf, &min_key, path->slots[0]);
961                         goto process_slot;
962                 }
963
964                 if (min_key.offset == (u64)-1)
965                         goto none;
966
967                 min_key.offset++;
968                 btrfs_release_path(path);
969         }
970 none:
971         btrfs_free_path(path);
972         return -ENOENT;
973 }
974
975 static struct extent_map *defrag_lookup_extent(struct inode *inode, u64 start)
976 {
977         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
978         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
979         struct extent_map *em;
980         u64 len = PAGE_CACHE_SIZE;
981
982         /*
983          * hopefully we have this extent in the tree already, try without
984          * the full extent lock
985          */
986         read_lock(&em_tree->lock);
987         em = lookup_extent_mapping(em_tree, start, len);
988         read_unlock(&em_tree->lock);
989
990         if (!em) {
991                 struct extent_state *cached = NULL;
992                 u64 end = start + len - 1;
993
994                 /* get the big lock and read metadata off disk */
995                 lock_extent_bits(io_tree, start, end, 0, &cached);
996                 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
997                 unlock_extent_cached(io_tree, start, end, &cached, GFP_NOFS);
998
999                 if (IS_ERR(em))
1000                         return NULL;
1001         }
1002
1003         return em;
1004 }
1005
1006 static bool defrag_check_next_extent(struct inode *inode, struct extent_map *em)
1007 {
1008         struct extent_map *next;
1009         bool ret = true;
1010
1011         /* this is the last extent */
1012         if (em->start + em->len >= i_size_read(inode))
1013                 return false;
1014
1015         next = defrag_lookup_extent(inode, em->start + em->len);
1016         if (!next || next->block_start >= EXTENT_MAP_LAST_BYTE)
1017                 ret = false;
1018         else if ((em->block_start + em->block_len == next->block_start) &&
1019                  (em->block_len > 128 * 1024 && next->block_len > 128 * 1024))
1020                 ret = false;
1021
1022         free_extent_map(next);
1023         return ret;
1024 }
1025
1026 static int should_defrag_range(struct inode *inode, u64 start, u32 thresh,
1027                                u64 *last_len, u64 *skip, u64 *defrag_end,
1028                                int compress)
1029 {
1030         struct extent_map *em;
1031         int ret = 1;
1032         bool next_mergeable = true;
1033
1034         /*
1035          * make sure that once we start defragging an extent, we keep on
1036          * defragging it
1037          */
1038         if (start < *defrag_end)
1039                 return 1;
1040
1041         *skip = 0;
1042
1043         em = defrag_lookup_extent(inode, start);
1044         if (!em)
1045                 return 0;
1046
1047         /* this will cover holes, and inline extents */
1048         if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
1049                 ret = 0;
1050                 goto out;
1051         }
1052
1053         next_mergeable = defrag_check_next_extent(inode, em);
1054         /*
1055          * we hit a real extent, if it is big or the next extent is not a
1056          * real extent, don't bother defragging it
1057          */
1058         if (!compress && (*last_len == 0 || *last_len >= thresh) &&
1059             (em->len >= thresh || !next_mergeable))
1060                 ret = 0;
1061 out:
1062         /*
1063          * last_len ends up being a counter of how many bytes we've defragged.
1064          * every time we choose not to defrag an extent, we reset *last_len
1065          * so that the next tiny extent will force a defrag.
1066          *
1067          * The end result of this is that tiny extents before a single big
1068          * extent will force at least part of that big extent to be defragged.
1069          */
1070         if (ret) {
1071                 *defrag_end = extent_map_end(em);
1072         } else {
1073                 *last_len = 0;
1074                 *skip = extent_map_end(em);
1075                 *defrag_end = 0;
1076         }
1077
1078         free_extent_map(em);
1079         return ret;
1080 }
1081
1082 /*
1083  * it doesn't do much good to defrag one or two pages
1084  * at a time.  This pulls in a nice chunk of pages
1085  * to COW and defrag.
1086  *
1087  * It also makes sure the delalloc code has enough
1088  * dirty data to avoid making new small extents as part
1089  * of the defrag
1090  *
1091  * It's a good idea to start RA on this range
1092  * before calling this.
1093  */
1094 static int cluster_pages_for_defrag(struct inode *inode,
1095                                     struct page **pages,
1096                                     unsigned long start_index,
1097                                     unsigned long num_pages)
1098 {
1099         unsigned long file_end;
1100         u64 isize = i_size_read(inode);
1101         u64 page_start;
1102         u64 page_end;
1103         u64 page_cnt;
1104         int ret;
1105         int i;
1106         int i_done;
1107         struct btrfs_ordered_extent *ordered;
1108         struct extent_state *cached_state = NULL;
1109         struct extent_io_tree *tree;
1110         gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
1111
1112         file_end = (isize - 1) >> PAGE_CACHE_SHIFT;
1113         if (!isize || start_index > file_end)
1114                 return 0;
1115
1116         page_cnt = min_t(u64, (u64)num_pages, (u64)file_end - start_index + 1);
1117
1118         ret = btrfs_delalloc_reserve_space(inode,
1119                                            page_cnt << PAGE_CACHE_SHIFT);
1120         if (ret)
1121                 return ret;
1122         i_done = 0;
1123         tree = &BTRFS_I(inode)->io_tree;
1124
1125         /* step one, lock all the pages */
1126         for (i = 0; i < page_cnt; i++) {
1127                 struct page *page;
1128 again:
1129                 page = find_or_create_page(inode->i_mapping,
1130                                            start_index + i, mask);
1131                 if (!page)
1132                         break;
1133
1134                 page_start = page_offset(page);
1135                 page_end = page_start + PAGE_CACHE_SIZE - 1;
1136                 while (1) {
1137                         lock_extent_bits(tree, page_start, page_end,
1138                                          0, &cached_state);
1139                         ordered = btrfs_lookup_ordered_extent(inode,
1140                                                               page_start);
1141                         unlock_extent_cached(tree, page_start, page_end,
1142                                              &cached_state, GFP_NOFS);
1143                         if (!ordered)
1144                                 break;
1145
1146                         unlock_page(page);
1147                         btrfs_start_ordered_extent(inode, ordered, 1);
1148                         btrfs_put_ordered_extent(ordered);
1149                         lock_page(page);
1150                         /*
1151                          * we unlocked the page above, so we need check if
1152                          * it was released or not.
1153                          */
1154                         if (page->mapping != inode->i_mapping) {
1155                                 unlock_page(page);
1156                                 page_cache_release(page);
1157                                 goto again;
1158                         }
1159                 }
1160
1161                 if (!PageUptodate(page)) {
1162                         btrfs_readpage(NULL, page);
1163                         lock_page(page);
1164                         if (!PageUptodate(page)) {
1165                                 unlock_page(page);
1166                                 page_cache_release(page);
1167                                 ret = -EIO;
1168                                 break;
1169                         }
1170                 }
1171
1172                 if (page->mapping != inode->i_mapping) {
1173                         unlock_page(page);
1174                         page_cache_release(page);
1175                         goto again;
1176                 }
1177
1178                 pages[i] = page;
1179                 i_done++;
1180         }
1181         if (!i_done || ret)
1182                 goto out;
1183
1184         if (!(inode->i_sb->s_flags & MS_ACTIVE))
1185                 goto out;
1186
1187         /*
1188          * so now we have a nice long stream of locked
1189          * and up to date pages, lets wait on them
1190          */
1191         for (i = 0; i < i_done; i++)
1192                 wait_on_page_writeback(pages[i]);
1193
1194         page_start = page_offset(pages[0]);
1195         page_end = page_offset(pages[i_done - 1]) + PAGE_CACHE_SIZE;
1196
1197         lock_extent_bits(&BTRFS_I(inode)->io_tree,
1198                          page_start, page_end - 1, 0, &cached_state);
1199         clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start,
1200                           page_end - 1, EXTENT_DIRTY | EXTENT_DELALLOC |
1201                           EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 0, 0,
1202                           &cached_state, GFP_NOFS);
1203
1204         if (i_done != page_cnt) {
1205                 spin_lock(&BTRFS_I(inode)->lock);
1206                 BTRFS_I(inode)->outstanding_extents++;
1207                 spin_unlock(&BTRFS_I(inode)->lock);
1208                 btrfs_delalloc_release_space(inode,
1209                                      (page_cnt - i_done) << PAGE_CACHE_SHIFT);
1210         }
1211
1212
1213         set_extent_defrag(&BTRFS_I(inode)->io_tree, page_start, page_end - 1,
1214                           &cached_state, GFP_NOFS);
1215
1216         unlock_extent_cached(&BTRFS_I(inode)->io_tree,
1217                              page_start, page_end - 1, &cached_state,
1218                              GFP_NOFS);
1219
1220         for (i = 0; i < i_done; i++) {
1221                 clear_page_dirty_for_io(pages[i]);
1222                 ClearPageChecked(pages[i]);
1223                 set_page_extent_mapped(pages[i]);
1224                 set_page_dirty(pages[i]);
1225                 unlock_page(pages[i]);
1226                 page_cache_release(pages[i]);
1227         }
1228         return i_done;
1229 out:
1230         for (i = 0; i < i_done; i++) {
1231                 unlock_page(pages[i]);
1232                 page_cache_release(pages[i]);
1233         }
1234         btrfs_delalloc_release_space(inode, page_cnt << PAGE_CACHE_SHIFT);
1235         return ret;
1236
1237 }
1238
1239 int btrfs_defrag_file(struct inode *inode, struct file *file,
1240                       struct btrfs_ioctl_defrag_range_args *range,
1241                       u64 newer_than, unsigned long max_to_defrag)
1242 {
1243         struct btrfs_root *root = BTRFS_I(inode)->root;
1244         struct file_ra_state *ra = NULL;
1245         unsigned long last_index;
1246         u64 isize = i_size_read(inode);
1247         u64 last_len = 0;
1248         u64 skip = 0;
1249         u64 defrag_end = 0;
1250         u64 newer_off = range->start;
1251         unsigned long i;
1252         unsigned long ra_index = 0;
1253         int ret;
1254         int defrag_count = 0;
1255         int compress_type = BTRFS_COMPRESS_ZLIB;
1256         u32 extent_thresh = range->extent_thresh;
1257         unsigned long max_cluster = (256 * 1024) >> PAGE_CACHE_SHIFT;
1258         unsigned long cluster = max_cluster;
1259         u64 new_align = ~((u64)128 * 1024 - 1);
1260         struct page **pages = NULL;
1261
1262         if (isize == 0)
1263                 return 0;
1264
1265         if (range->start >= isize)
1266                 return -EINVAL;
1267
1268         if (range->flags & BTRFS_DEFRAG_RANGE_COMPRESS) {
1269                 if (range->compress_type > BTRFS_COMPRESS_TYPES)
1270                         return -EINVAL;
1271                 if (range->compress_type)
1272                         compress_type = range->compress_type;
1273         }
1274
1275         if (extent_thresh == 0)
1276                 extent_thresh = 256 * 1024;
1277
1278         /*
1279          * if we were not given a file, allocate a readahead
1280          * context
1281          */
1282         if (!file) {
1283                 ra = kzalloc(sizeof(*ra), GFP_NOFS);
1284                 if (!ra)
1285                         return -ENOMEM;
1286                 file_ra_state_init(ra, inode->i_mapping);
1287         } else {
1288                 ra = &file->f_ra;
1289         }
1290
1291         pages = kmalloc_array(max_cluster, sizeof(struct page *),
1292                         GFP_NOFS);
1293         if (!pages) {
1294                 ret = -ENOMEM;
1295                 goto out_ra;
1296         }
1297
1298         /* find the last page to defrag */
1299         if (range->start + range->len > range->start) {
1300                 last_index = min_t(u64, isize - 1,
1301                          range->start + range->len - 1) >> PAGE_CACHE_SHIFT;
1302         } else {
1303                 last_index = (isize - 1) >> PAGE_CACHE_SHIFT;
1304         }
1305
1306         if (newer_than) {
1307                 ret = find_new_extents(root, inode, newer_than,
1308                                        &newer_off, 64 * 1024);
1309                 if (!ret) {
1310                         range->start = newer_off;
1311                         /*
1312                          * we always align our defrag to help keep
1313                          * the extents in the file evenly spaced
1314                          */
1315                         i = (newer_off & new_align) >> PAGE_CACHE_SHIFT;
1316                 } else
1317                         goto out_ra;
1318         } else {
1319                 i = range->start >> PAGE_CACHE_SHIFT;
1320         }
1321         if (!max_to_defrag)
1322                 max_to_defrag = last_index - i + 1;
1323
1324         /*
1325          * make writeback starts from i, so the defrag range can be
1326          * written sequentially.
1327          */
1328         if (i < inode->i_mapping->writeback_index)
1329                 inode->i_mapping->writeback_index = i;
1330
1331         while (i <= last_index && defrag_count < max_to_defrag &&
1332                (i < DIV_ROUND_UP(i_size_read(inode), PAGE_CACHE_SIZE))) {
1333                 /*
1334                  * make sure we stop running if someone unmounts
1335                  * the FS
1336                  */
1337                 if (!(inode->i_sb->s_flags & MS_ACTIVE))
1338                         break;
1339
1340                 if (btrfs_defrag_cancelled(root->fs_info)) {
1341                         printk(KERN_DEBUG "BTRFS: defrag_file cancelled\n");
1342                         ret = -EAGAIN;
1343                         break;
1344                 }
1345
1346                 if (!should_defrag_range(inode, (u64)i << PAGE_CACHE_SHIFT,
1347                                          extent_thresh, &last_len, &skip,
1348                                          &defrag_end, range->flags &
1349                                          BTRFS_DEFRAG_RANGE_COMPRESS)) {
1350                         unsigned long next;
1351                         /*
1352                          * the should_defrag function tells us how much to skip
1353                          * bump our counter by the suggested amount
1354                          */
1355                         next = DIV_ROUND_UP(skip, PAGE_CACHE_SIZE);
1356                         i = max(i + 1, next);
1357                         continue;
1358                 }
1359
1360                 if (!newer_than) {
1361                         cluster = (PAGE_CACHE_ALIGN(defrag_end) >>
1362                                    PAGE_CACHE_SHIFT) - i;
1363                         cluster = min(cluster, max_cluster);
1364                 } else {
1365                         cluster = max_cluster;
1366                 }
1367
1368                 if (i + cluster > ra_index) {
1369                         ra_index = max(i, ra_index);
1370                         btrfs_force_ra(inode->i_mapping, ra, file, ra_index,
1371                                        cluster);
1372                         ra_index += cluster;
1373                 }
1374
1375                 mutex_lock(&inode->i_mutex);
1376                 if (range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)
1377                         BTRFS_I(inode)->force_compress = compress_type;
1378                 ret = cluster_pages_for_defrag(inode, pages, i, cluster);
1379                 if (ret < 0) {
1380                         mutex_unlock(&inode->i_mutex);
1381                         goto out_ra;
1382                 }
1383
1384                 defrag_count += ret;
1385                 balance_dirty_pages_ratelimited(inode->i_mapping);
1386                 mutex_unlock(&inode->i_mutex);
1387
1388                 if (newer_than) {
1389                         if (newer_off == (u64)-1)
1390                                 break;
1391
1392                         if (ret > 0)
1393                                 i += ret;
1394
1395                         newer_off = max(newer_off + 1,
1396                                         (u64)i << PAGE_CACHE_SHIFT);
1397
1398                         ret = find_new_extents(root, inode,
1399                                                newer_than, &newer_off,
1400                                                64 * 1024);
1401                         if (!ret) {
1402                                 range->start = newer_off;
1403                                 i = (newer_off & new_align) >> PAGE_CACHE_SHIFT;
1404                         } else {
1405                                 break;
1406                         }
1407                 } else {
1408                         if (ret > 0) {
1409                                 i += ret;
1410                                 last_len += ret << PAGE_CACHE_SHIFT;
1411                         } else {
1412                                 i++;
1413                                 last_len = 0;
1414                         }
1415                 }
1416         }
1417
1418         if ((range->flags & BTRFS_DEFRAG_RANGE_START_IO)) {
1419                 filemap_flush(inode->i_mapping);
1420                 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1421                              &BTRFS_I(inode)->runtime_flags))
1422                         filemap_flush(inode->i_mapping);
1423         }
1424
1425         if ((range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)) {
1426                 /* the filemap_flush will queue IO into the worker threads, but
1427                  * we have to make sure the IO is actually started and that
1428                  * ordered extents get created before we return
1429                  */
1430                 atomic_inc(&root->fs_info->async_submit_draining);
1431                 while (atomic_read(&root->fs_info->nr_async_submits) ||
1432                       atomic_read(&root->fs_info->async_delalloc_pages)) {
1433                         wait_event(root->fs_info->async_submit_wait,
1434                            (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
1435                             atomic_read(&root->fs_info->async_delalloc_pages) == 0));
1436                 }
1437                 atomic_dec(&root->fs_info->async_submit_draining);
1438         }
1439
1440         if (range->compress_type == BTRFS_COMPRESS_LZO) {
1441                 btrfs_set_fs_incompat(root->fs_info, COMPRESS_LZO);
1442         }
1443
1444         ret = defrag_count;
1445
1446 out_ra:
1447         if (range->flags & BTRFS_DEFRAG_RANGE_COMPRESS) {
1448                 mutex_lock(&inode->i_mutex);
1449                 BTRFS_I(inode)->force_compress = BTRFS_COMPRESS_NONE;
1450                 mutex_unlock(&inode->i_mutex);
1451         }
1452         if (!file)
1453                 kfree(ra);
1454         kfree(pages);
1455         return ret;
1456 }
1457
1458 static noinline int btrfs_ioctl_resize(struct file *file,
1459                                         void __user *arg)
1460 {
1461         u64 new_size;
1462         u64 old_size;
1463         u64 devid = 1;
1464         struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
1465         struct btrfs_ioctl_vol_args *vol_args;
1466         struct btrfs_trans_handle *trans;
1467         struct btrfs_device *device = NULL;
1468         char *sizestr;
1469         char *retptr;
1470         char *devstr = NULL;
1471         int ret = 0;
1472         int mod = 0;
1473
1474         if (!capable(CAP_SYS_ADMIN))
1475                 return -EPERM;
1476
1477         ret = mnt_want_write_file(file);
1478         if (ret)
1479                 return ret;
1480
1481         if (atomic_xchg(&root->fs_info->mutually_exclusive_operation_running,
1482                         1)) {
1483                 mnt_drop_write_file(file);
1484                 return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
1485         }
1486
1487         mutex_lock(&root->fs_info->volume_mutex);
1488         vol_args = memdup_user(arg, sizeof(*vol_args));
1489         if (IS_ERR(vol_args)) {
1490                 ret = PTR_ERR(vol_args);
1491                 goto out;
1492         }
1493
1494         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1495
1496         sizestr = vol_args->name;
1497         devstr = strchr(sizestr, ':');
1498         if (devstr) {
1499                 sizestr = devstr + 1;
1500                 *devstr = '\0';
1501                 devstr = vol_args->name;
1502                 ret = kstrtoull(devstr, 10, &devid);
1503                 if (ret)
1504                         goto out_free;
1505                 if (!devid) {
1506                         ret = -EINVAL;
1507                         goto out_free;
1508                 }
1509                 btrfs_info(root->fs_info, "resizing devid %llu", devid);
1510         }
1511
1512         device = btrfs_find_device(root->fs_info, devid, NULL, NULL);
1513         if (!device) {
1514                 btrfs_info(root->fs_info, "resizer unable to find device %llu",
1515                        devid);
1516                 ret = -ENODEV;
1517                 goto out_free;
1518         }
1519
1520         if (!device->writeable) {
1521                 btrfs_info(root->fs_info,
1522                            "resizer unable to apply on readonly device %llu",
1523                        devid);
1524                 ret = -EPERM;
1525                 goto out_free;
1526         }
1527
1528         if (!strcmp(sizestr, "max"))
1529                 new_size = device->bdev->bd_inode->i_size;
1530         else {
1531                 if (sizestr[0] == '-') {
1532                         mod = -1;
1533                         sizestr++;
1534                 } else if (sizestr[0] == '+') {
1535                         mod = 1;
1536                         sizestr++;
1537                 }
1538                 new_size = memparse(sizestr, &retptr);
1539                 if (*retptr != '\0' || new_size == 0) {
1540                         ret = -EINVAL;
1541                         goto out_free;
1542                 }
1543         }
1544
1545         if (device->is_tgtdev_for_dev_replace) {
1546                 ret = -EPERM;
1547                 goto out_free;
1548         }
1549
1550         old_size = btrfs_device_get_total_bytes(device);
1551
1552         if (mod < 0) {
1553                 if (new_size > old_size) {
1554                         ret = -EINVAL;
1555                         goto out_free;
1556                 }
1557                 new_size = old_size - new_size;
1558         } else if (mod > 0) {
1559                 if (new_size > ULLONG_MAX - old_size) {
1560                         ret = -ERANGE;
1561                         goto out_free;
1562                 }
1563                 new_size = old_size + new_size;
1564         }
1565
1566         if (new_size < 256 * 1024 * 1024) {
1567                 ret = -EINVAL;
1568                 goto out_free;
1569         }
1570         if (new_size > device->bdev->bd_inode->i_size) {
1571                 ret = -EFBIG;
1572                 goto out_free;
1573         }
1574
1575         new_size = div_u64(new_size, root->sectorsize);
1576         new_size *= root->sectorsize;
1577
1578         printk_in_rcu(KERN_INFO "BTRFS: new size for %s is %llu\n",
1579                       rcu_str_deref(device->name), new_size);
1580
1581         if (new_size > old_size) {
1582                 trans = btrfs_start_transaction(root, 0);
1583                 if (IS_ERR(trans)) {
1584                         ret = PTR_ERR(trans);
1585                         goto out_free;
1586                 }
1587                 ret = btrfs_grow_device(trans, device, new_size);
1588                 btrfs_commit_transaction(trans, root);
1589         } else if (new_size < old_size) {
1590                 ret = btrfs_shrink_device(device, new_size);
1591         } /* equal, nothing need to do */
1592
1593 out_free:
1594         kfree(vol_args);
1595 out:
1596         mutex_unlock(&root->fs_info->volume_mutex);
1597         atomic_set(&root->fs_info->mutually_exclusive_operation_running, 0);
1598         mnt_drop_write_file(file);
1599         return ret;
1600 }
1601
1602 static noinline int btrfs_ioctl_snap_create_transid(struct file *file,
1603                                 char *name, unsigned long fd, int subvol,
1604                                 u64 *transid, bool readonly,
1605                                 struct btrfs_qgroup_inherit *inherit)
1606 {
1607         int namelen;
1608         int ret = 0;
1609
1610         ret = mnt_want_write_file(file);
1611         if (ret)
1612                 goto out;
1613
1614         namelen = strlen(name);
1615         if (strchr(name, '/')) {
1616                 ret = -EINVAL;
1617                 goto out_drop_write;
1618         }
1619
1620         if (name[0] == '.' &&
1621            (namelen == 1 || (name[1] == '.' && namelen == 2))) {
1622                 ret = -EEXIST;
1623                 goto out_drop_write;
1624         }
1625
1626         if (subvol) {
1627                 ret = btrfs_mksubvol(&file->f_path, name, namelen,
1628                                      NULL, transid, readonly, inherit);
1629         } else {
1630                 struct fd src = fdget(fd);
1631                 struct inode *src_inode;
1632                 if (!src.file) {
1633                         ret = -EINVAL;
1634                         goto out_drop_write;
1635                 }
1636
1637                 src_inode = file_inode(src.file);
1638                 if (src_inode->i_sb != file_inode(file)->i_sb) {
1639                         btrfs_info(BTRFS_I(src_inode)->root->fs_info,
1640                                    "Snapshot src from another FS");
1641                         ret = -EXDEV;
1642                 } else if (!inode_owner_or_capable(src_inode)) {
1643                         /*
1644                          * Subvolume creation is not restricted, but snapshots
1645                          * are limited to own subvolumes only
1646                          */
1647                         ret = -EPERM;
1648                 } else {
1649                         ret = btrfs_mksubvol(&file->f_path, name, namelen,
1650                                              BTRFS_I(src_inode)->root,
1651                                              transid, readonly, inherit);
1652                 }
1653                 fdput(src);
1654         }
1655 out_drop_write:
1656         mnt_drop_write_file(file);
1657 out:
1658         return ret;
1659 }
1660
1661 static noinline int btrfs_ioctl_snap_create(struct file *file,
1662                                             void __user *arg, int subvol)
1663 {
1664         struct btrfs_ioctl_vol_args *vol_args;
1665         int ret;
1666
1667         vol_args = memdup_user(arg, sizeof(*vol_args));
1668         if (IS_ERR(vol_args))
1669                 return PTR_ERR(vol_args);
1670         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1671
1672         ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
1673                                               vol_args->fd, subvol,
1674                                               NULL, false, NULL);
1675
1676         kfree(vol_args);
1677         return ret;
1678 }
1679
1680 static noinline int btrfs_ioctl_snap_create_v2(struct file *file,
1681                                                void __user *arg, int subvol)
1682 {
1683         struct btrfs_ioctl_vol_args_v2 *vol_args;
1684         int ret;
1685         u64 transid = 0;
1686         u64 *ptr = NULL;
1687         bool readonly = false;
1688         struct btrfs_qgroup_inherit *inherit = NULL;
1689
1690         vol_args = memdup_user(arg, sizeof(*vol_args));
1691         if (IS_ERR(vol_args))
1692                 return PTR_ERR(vol_args);
1693         vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
1694
1695         if (vol_args->flags &
1696             ~(BTRFS_SUBVOL_CREATE_ASYNC | BTRFS_SUBVOL_RDONLY |
1697               BTRFS_SUBVOL_QGROUP_INHERIT)) {
1698                 ret = -EOPNOTSUPP;
1699                 goto free_args;
1700         }
1701
1702         if (vol_args->flags & BTRFS_SUBVOL_CREATE_ASYNC)
1703                 ptr = &transid;
1704         if (vol_args->flags & BTRFS_SUBVOL_RDONLY)
1705                 readonly = true;
1706         if (vol_args->flags & BTRFS_SUBVOL_QGROUP_INHERIT) {
1707                 if (vol_args->size > PAGE_CACHE_SIZE) {
1708                         ret = -EINVAL;
1709                         goto free_args;
1710                 }
1711                 inherit = memdup_user(vol_args->qgroup_inherit, vol_args->size);
1712                 if (IS_ERR(inherit)) {
1713                         ret = PTR_ERR(inherit);
1714                         goto free_args;
1715                 }
1716         }
1717
1718         ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
1719                                               vol_args->fd, subvol, ptr,
1720                                               readonly, inherit);
1721         if (ret)
1722                 goto free_inherit;
1723
1724         if (ptr && copy_to_user(arg +
1725                                 offsetof(struct btrfs_ioctl_vol_args_v2,
1726                                         transid),
1727                                 ptr, sizeof(*ptr)))
1728                 ret = -EFAULT;
1729
1730 free_inherit:
1731         kfree(inherit);
1732 free_args:
1733         kfree(vol_args);
1734         return ret;
1735 }
1736
1737 static noinline int btrfs_ioctl_subvol_getflags(struct file *file,
1738                                                 void __user *arg)
1739 {
1740         struct inode *inode = file_inode(file);
1741         struct btrfs_root *root = BTRFS_I(inode)->root;
1742         int ret = 0;
1743         u64 flags = 0;
1744
1745         if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID)
1746                 return -EINVAL;
1747
1748         down_read(&root->fs_info->subvol_sem);
1749         if (btrfs_root_readonly(root))
1750                 flags |= BTRFS_SUBVOL_RDONLY;
1751         up_read(&root->fs_info->subvol_sem);
1752
1753         if (copy_to_user(arg, &flags, sizeof(flags)))
1754                 ret = -EFAULT;
1755
1756         return ret;
1757 }
1758
1759 static noinline int btrfs_ioctl_subvol_setflags(struct file *file,
1760                                               void __user *arg)
1761 {
1762         struct inode *inode = file_inode(file);
1763         struct btrfs_root *root = BTRFS_I(inode)->root;
1764         struct btrfs_trans_handle *trans;
1765         u64 root_flags;
1766         u64 flags;
1767         int ret = 0;
1768
1769         if (!inode_owner_or_capable(inode))
1770                 return -EPERM;
1771
1772         ret = mnt_want_write_file(file);
1773         if (ret)
1774                 goto out;
1775
1776         if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID) {
1777                 ret = -EINVAL;
1778                 goto out_drop_write;
1779         }
1780
1781         if (copy_from_user(&flags, arg, sizeof(flags))) {
1782                 ret = -EFAULT;
1783                 goto out_drop_write;
1784         }
1785
1786         if (flags & BTRFS_SUBVOL_CREATE_ASYNC) {
1787                 ret = -EINVAL;
1788                 goto out_drop_write;
1789         }
1790
1791         if (flags & ~BTRFS_SUBVOL_RDONLY) {
1792                 ret = -EOPNOTSUPP;
1793                 goto out_drop_write;
1794         }
1795
1796         down_write(&root->fs_info->subvol_sem);
1797
1798         /* nothing to do */
1799         if (!!(flags & BTRFS_SUBVOL_RDONLY) == btrfs_root_readonly(root))
1800                 goto out_drop_sem;
1801
1802         root_flags = btrfs_root_flags(&root->root_item);
1803         if (flags & BTRFS_SUBVOL_RDONLY) {
1804                 btrfs_set_root_flags(&root->root_item,
1805                                      root_flags | BTRFS_ROOT_SUBVOL_RDONLY);
1806         } else {
1807                 /*
1808                  * Block RO -> RW transition if this subvolume is involved in
1809                  * send
1810                  */
1811                 spin_lock(&root->root_item_lock);
1812                 if (root->send_in_progress == 0) {
1813                         btrfs_set_root_flags(&root->root_item,
1814                                      root_flags & ~BTRFS_ROOT_SUBVOL_RDONLY);
1815                         spin_unlock(&root->root_item_lock);
1816                 } else {
1817                         spin_unlock(&root->root_item_lock);
1818                         btrfs_warn(root->fs_info,
1819                         "Attempt to set subvolume %llu read-write during send",
1820                                         root->root_key.objectid);
1821                         ret = -EPERM;
1822                         goto out_drop_sem;
1823                 }
1824         }
1825
1826         trans = btrfs_start_transaction(root, 1);
1827         if (IS_ERR(trans)) {
1828                 ret = PTR_ERR(trans);
1829                 goto out_reset;
1830         }
1831
1832         ret = btrfs_update_root(trans, root->fs_info->tree_root,
1833                                 &root->root_key, &root->root_item);
1834
1835         btrfs_commit_transaction(trans, root);
1836 out_reset:
1837         if (ret)
1838                 btrfs_set_root_flags(&root->root_item, root_flags);
1839 out_drop_sem:
1840         up_write(&root->fs_info->subvol_sem);
1841 out_drop_write:
1842         mnt_drop_write_file(file);
1843 out:
1844         return ret;
1845 }
1846
1847 /*
1848  * helper to check if the subvolume references other subvolumes
1849  */
1850 static noinline int may_destroy_subvol(struct btrfs_root *root)
1851 {
1852         struct btrfs_path *path;
1853         struct btrfs_dir_item *di;
1854         struct btrfs_key key;
1855         u64 dir_id;
1856         int ret;
1857
1858         path = btrfs_alloc_path();
1859         if (!path)
1860                 return -ENOMEM;
1861
1862         /* Make sure this root isn't set as the default subvol */
1863         dir_id = btrfs_super_root_dir(root->fs_info->super_copy);
1864         di = btrfs_lookup_dir_item(NULL, root->fs_info->tree_root, path,
1865                                    dir_id, "default", 7, 0);
1866         if (di && !IS_ERR(di)) {
1867                 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
1868                 if (key.objectid == root->root_key.objectid) {
1869                         ret = -EPERM;
1870                         btrfs_err(root->fs_info, "deleting default subvolume "
1871                                   "%llu is not allowed", key.objectid);
1872                         goto out;
1873                 }
1874                 btrfs_release_path(path);
1875         }
1876
1877         key.objectid = root->root_key.objectid;
1878         key.type = BTRFS_ROOT_REF_KEY;
1879         key.offset = (u64)-1;
1880
1881         ret = btrfs_search_slot(NULL, root->fs_info->tree_root,
1882                                 &key, path, 0, 0);
1883         if (ret < 0)
1884                 goto out;
1885         BUG_ON(ret == 0);
1886
1887         ret = 0;
1888         if (path->slots[0] > 0) {
1889                 path->slots[0]--;
1890                 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1891                 if (key.objectid == root->root_key.objectid &&
1892                     key.type == BTRFS_ROOT_REF_KEY)
1893                         ret = -ENOTEMPTY;
1894         }
1895 out:
1896         btrfs_free_path(path);
1897         return ret;
1898 }
1899
1900 static noinline int key_in_sk(struct btrfs_key *key,
1901                               struct btrfs_ioctl_search_key *sk)
1902 {
1903         struct btrfs_key test;
1904         int ret;
1905
1906         test.objectid = sk->min_objectid;
1907         test.type = sk->min_type;
1908         test.offset = sk->min_offset;
1909
1910         ret = btrfs_comp_cpu_keys(key, &test);
1911         if (ret < 0)
1912                 return 0;
1913
1914         test.objectid = sk->max_objectid;
1915         test.type = sk->max_type;
1916         test.offset = sk->max_offset;
1917
1918         ret = btrfs_comp_cpu_keys(key, &test);
1919         if (ret > 0)
1920                 return 0;
1921         return 1;
1922 }
1923
1924 static noinline int copy_to_sk(struct btrfs_root *root,
1925                                struct btrfs_path *path,
1926                                struct btrfs_key *key,
1927                                struct btrfs_ioctl_search_key *sk,
1928                                size_t *buf_size,
1929                                char __user *ubuf,
1930                                unsigned long *sk_offset,
1931                                int *num_found)
1932 {
1933         u64 found_transid;
1934         struct extent_buffer *leaf;
1935         struct btrfs_ioctl_search_header sh;
1936         struct btrfs_key test;
1937         unsigned long item_off;
1938         unsigned long item_len;
1939         int nritems;
1940         int i;
1941         int slot;
1942         int ret = 0;
1943
1944         leaf = path->nodes[0];
1945         slot = path->slots[0];
1946         nritems = btrfs_header_nritems(leaf);
1947
1948         if (btrfs_header_generation(leaf) > sk->max_transid) {
1949                 i = nritems;
1950                 goto advance_key;
1951         }
1952         found_transid = btrfs_header_generation(leaf);
1953
1954         for (i = slot; i < nritems; i++) {
1955                 item_off = btrfs_item_ptr_offset(leaf, i);
1956                 item_len = btrfs_item_size_nr(leaf, i);
1957
1958                 btrfs_item_key_to_cpu(leaf, key, i);
1959                 if (!key_in_sk(key, sk))
1960                         continue;
1961
1962                 if (sizeof(sh) + item_len > *buf_size) {
1963                         if (*num_found) {
1964                                 ret = 1;
1965                                 goto out;
1966                         }
1967
1968                         /*
1969                          * return one empty item back for v1, which does not
1970                          * handle -EOVERFLOW
1971                          */
1972
1973                         *buf_size = sizeof(sh) + item_len;
1974                         item_len = 0;
1975                         ret = -EOVERFLOW;
1976                 }
1977
1978                 if (sizeof(sh) + item_len + *sk_offset > *buf_size) {
1979                         ret = 1;
1980                         goto out;
1981                 }
1982
1983                 sh.objectid = key->objectid;
1984                 sh.offset = key->offset;
1985                 sh.type = key->type;
1986                 sh.len = item_len;
1987                 sh.transid = found_transid;
1988
1989                 /* copy search result header */
1990                 if (copy_to_user(ubuf + *sk_offset, &sh, sizeof(sh))) {
1991                         ret = -EFAULT;
1992                         goto out;
1993                 }
1994
1995                 *sk_offset += sizeof(sh);
1996
1997                 if (item_len) {
1998                         char __user *up = ubuf + *sk_offset;
1999                         /* copy the item */
2000                         if (read_extent_buffer_to_user(leaf, up,
2001                                                        item_off, item_len)) {
2002                                 ret = -EFAULT;
2003                                 goto out;
2004                         }
2005
2006                         *sk_offset += item_len;
2007                 }
2008                 (*num_found)++;
2009
2010                 if (ret) /* -EOVERFLOW from above */
2011                         goto out;
2012
2013                 if (*num_found >= sk->nr_items) {
2014                         ret = 1;
2015                         goto out;
2016                 }
2017         }
2018 advance_key:
2019         ret = 0;
2020         test.objectid = sk->max_objectid;
2021         test.type = sk->max_type;
2022         test.offset = sk->max_offset;
2023         if (btrfs_comp_cpu_keys(key, &test) >= 0)
2024                 ret = 1;
2025         else if (key->offset < (u64)-1)
2026                 key->offset++;
2027         else if (key->type < (u8)-1) {
2028                 key->offset = 0;
2029                 key->type++;
2030         } else if (key->objectid < (u64)-1) {
2031                 key->offset = 0;
2032                 key->type = 0;
2033                 key->objectid++;
2034         } else
2035                 ret = 1;
2036 out:
2037         /*
2038          *  0: all items from this leaf copied, continue with next
2039          *  1: * more items can be copied, but unused buffer is too small
2040          *     * all items were found
2041          *     Either way, it will stops the loop which iterates to the next
2042          *     leaf
2043          *  -EOVERFLOW: item was to large for buffer
2044          *  -EFAULT: could not copy extent buffer back to userspace
2045          */
2046         return ret;
2047 }
2048
2049 static noinline int search_ioctl(struct inode *inode,
2050                                  struct btrfs_ioctl_search_key *sk,
2051                                  size_t *buf_size,
2052                                  char __user *ubuf)
2053 {
2054         struct btrfs_root *root;
2055         struct btrfs_key key;
2056         struct btrfs_path *path;
2057         struct btrfs_fs_info *info = BTRFS_I(inode)->root->fs_info;
2058         int ret;
2059         int num_found = 0;
2060         unsigned long sk_offset = 0;
2061
2062         if (*buf_size < sizeof(struct btrfs_ioctl_search_header)) {
2063                 *buf_size = sizeof(struct btrfs_ioctl_search_header);
2064                 return -EOVERFLOW;
2065         }
2066
2067         path = btrfs_alloc_path();
2068         if (!path)
2069                 return -ENOMEM;
2070
2071         if (sk->tree_id == 0) {
2072                 /* search the root of the inode that was passed */
2073                 root = BTRFS_I(inode)->root;
2074         } else {
2075                 key.objectid = sk->tree_id;
2076                 key.type = BTRFS_ROOT_ITEM_KEY;
2077                 key.offset = (u64)-1;
2078                 root = btrfs_read_fs_root_no_name(info, &key);
2079                 if (IS_ERR(root)) {
2080                         printk(KERN_ERR "BTRFS: could not find root %llu\n",
2081                                sk->tree_id);
2082                         btrfs_free_path(path);
2083                         return -ENOENT;
2084                 }
2085         }
2086
2087         key.objectid = sk->min_objectid;
2088         key.type = sk->min_type;
2089         key.offset = sk->min_offset;
2090
2091         while (1) {
2092                 ret = btrfs_search_forward(root, &key, path, sk->min_transid);
2093                 if (ret != 0) {
2094                         if (ret > 0)
2095                                 ret = 0;
2096                         goto err;
2097                 }
2098                 ret = copy_to_sk(root, path, &key, sk, buf_size, ubuf,
2099                                  &sk_offset, &num_found);
2100                 btrfs_release_path(path);
2101                 if (ret)
2102                         break;
2103
2104         }
2105         if (ret > 0)
2106                 ret = 0;
2107 err:
2108         sk->nr_items = num_found;
2109         btrfs_free_path(path);
2110         return ret;
2111 }
2112
2113 static noinline int btrfs_ioctl_tree_search(struct file *file,
2114                                            void __user *argp)
2115 {
2116         struct btrfs_ioctl_search_args __user *uargs;
2117         struct btrfs_ioctl_search_key sk;
2118         struct inode *inode;
2119         int ret;
2120         size_t buf_size;
2121
2122         if (!capable(CAP_SYS_ADMIN))
2123                 return -EPERM;
2124
2125         uargs = (struct btrfs_ioctl_search_args __user *)argp;
2126
2127         if (copy_from_user(&sk, &uargs->key, sizeof(sk)))
2128                 return -EFAULT;
2129
2130         buf_size = sizeof(uargs->buf);
2131
2132         inode = file_inode(file);
2133         ret = search_ioctl(inode, &sk, &buf_size, uargs->buf);
2134
2135         /*
2136          * In the origin implementation an overflow is handled by returning a
2137          * search header with a len of zero, so reset ret.
2138          */
2139         if (ret == -EOVERFLOW)
2140                 ret = 0;
2141
2142         if (ret == 0 && copy_to_user(&uargs->key, &sk, sizeof(sk)))
2143                 ret = -EFAULT;
2144         return ret;
2145 }
2146
2147 static noinline int btrfs_ioctl_tree_search_v2(struct file *file,
2148                                                void __user *argp)
2149 {
2150         struct btrfs_ioctl_search_args_v2 __user *uarg;
2151         struct btrfs_ioctl_search_args_v2 args;
2152         struct inode *inode;
2153         int ret;
2154         size_t buf_size;
2155         const size_t buf_limit = 16 * 1024 * 1024;
2156
2157         if (!capable(CAP_SYS_ADMIN))
2158                 return -EPERM;
2159
2160         /* copy search header and buffer size */
2161         uarg = (struct btrfs_ioctl_search_args_v2 __user *)argp;
2162         if (copy_from_user(&args, uarg, sizeof(args)))
2163                 return -EFAULT;
2164
2165         buf_size = args.buf_size;
2166
2167         if (buf_size < sizeof(struct btrfs_ioctl_search_header))
2168                 return -EOVERFLOW;
2169
2170         /* limit result size to 16MB */
2171         if (buf_size > buf_limit)
2172                 buf_size = buf_limit;
2173
2174         inode = file_inode(file);
2175         ret = search_ioctl(inode, &args.key, &buf_size,
2176                            (char *)(&uarg->buf[0]));
2177         if (ret == 0 && copy_to_user(&uarg->key, &args.key, sizeof(args.key)))
2178                 ret = -EFAULT;
2179         else if (ret == -EOVERFLOW &&
2180                 copy_to_user(&uarg->buf_size, &buf_size, sizeof(buf_size)))
2181                 ret = -EFAULT;
2182
2183         return ret;
2184 }
2185
2186 /*
2187  * Search INODE_REFs to identify path name of 'dirid' directory
2188  * in a 'tree_id' tree. and sets path name to 'name'.
2189  */
2190 static noinline int btrfs_search_path_in_tree(struct btrfs_fs_info *info,
2191                                 u64 tree_id, u64 dirid, char *name)
2192 {
2193         struct btrfs_root *root;
2194         struct btrfs_key key;
2195         char *ptr;
2196         int ret = -1;
2197         int slot;
2198         int len;
2199         int total_len = 0;
2200         struct btrfs_inode_ref *iref;
2201         struct extent_buffer *l;
2202         struct btrfs_path *path;
2203
2204         if (dirid == BTRFS_FIRST_FREE_OBJECTID) {
2205                 name[0]='\0';
2206                 return 0;
2207         }
2208
2209         path = btrfs_alloc_path();
2210         if (!path)
2211                 return -ENOMEM;
2212
2213         ptr = &name[BTRFS_INO_LOOKUP_PATH_MAX];
2214
2215         key.objectid = tree_id;
2216         key.type = BTRFS_ROOT_ITEM_KEY;
2217         key.offset = (u64)-1;
2218         root = btrfs_read_fs_root_no_name(info, &key);
2219         if (IS_ERR(root)) {
2220                 printk(KERN_ERR "BTRFS: could not find root %llu\n", tree_id);
2221                 ret = -ENOENT;
2222                 goto out;
2223         }
2224
2225         key.objectid = dirid;
2226         key.type = BTRFS_INODE_REF_KEY;
2227         key.offset = (u64)-1;
2228
2229         while (1) {
2230                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2231                 if (ret < 0)
2232                         goto out;
2233                 else if (ret > 0) {
2234                         ret = btrfs_previous_item(root, path, dirid,
2235                                                   BTRFS_INODE_REF_KEY);
2236                         if (ret < 0)
2237                                 goto out;
2238                         else if (ret > 0) {
2239                                 ret = -ENOENT;
2240                                 goto out;
2241                         }
2242                 }
2243
2244                 l = path->nodes[0];
2245                 slot = path->slots[0];
2246                 btrfs_item_key_to_cpu(l, &key, slot);
2247
2248                 iref = btrfs_item_ptr(l, slot, struct btrfs_inode_ref);
2249                 len = btrfs_inode_ref_name_len(l, iref);
2250                 ptr -= len + 1;
2251                 total_len += len + 1;
2252                 if (ptr < name) {
2253                         ret = -ENAMETOOLONG;
2254                         goto out;
2255                 }
2256
2257                 *(ptr + len) = '/';
2258                 read_extent_buffer(l, ptr, (unsigned long)(iref + 1), len);
2259
2260                 if (key.offset == BTRFS_FIRST_FREE_OBJECTID)
2261                         break;
2262
2263                 btrfs_release_path(path);
2264                 key.objectid = key.offset;
2265                 key.offset = (u64)-1;
2266                 dirid = key.objectid;
2267         }
2268         memmove(name, ptr, total_len);
2269         name[total_len] = '\0';
2270         ret = 0;
2271 out:
2272         btrfs_free_path(path);
2273         return ret;
2274 }
2275
2276 static noinline int btrfs_ioctl_ino_lookup(struct file *file,
2277                                            void __user *argp)
2278 {
2279          struct btrfs_ioctl_ino_lookup_args *args;
2280          struct inode *inode;
2281         int ret = 0;
2282
2283         args = memdup_user(argp, sizeof(*args));
2284         if (IS_ERR(args))
2285                 return PTR_ERR(args);
2286
2287         inode = file_inode(file);
2288
2289         /*
2290          * Unprivileged query to obtain the containing subvolume root id. The
2291          * path is reset so it's consistent with btrfs_search_path_in_tree.
2292          */
2293         if (args->treeid == 0)
2294                 args->treeid = BTRFS_I(inode)->root->root_key.objectid;
2295
2296         if (args->objectid == BTRFS_FIRST_FREE_OBJECTID) {
2297                 args->name[0] = 0;
2298                 goto out;
2299         }
2300
2301         if (!capable(CAP_SYS_ADMIN)) {
2302                 ret = -EPERM;
2303                 goto out;
2304         }
2305
2306         ret = btrfs_search_path_in_tree(BTRFS_I(inode)->root->fs_info,
2307                                         args->treeid, args->objectid,
2308                                         args->name);
2309
2310 out:
2311         if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
2312                 ret = -EFAULT;
2313
2314         kfree(args);
2315         return ret;
2316 }
2317
2318 static noinline int btrfs_ioctl_snap_destroy(struct file *file,
2319                                              void __user *arg)
2320 {
2321         struct dentry *parent = file->f_path.dentry;
2322         struct dentry *dentry;
2323         struct inode *dir = d_inode(parent);
2324         struct inode *inode;
2325         struct btrfs_root *root = BTRFS_I(dir)->root;
2326         struct btrfs_root *dest = NULL;
2327         struct btrfs_ioctl_vol_args *vol_args;
2328         struct btrfs_trans_handle *trans;
2329         struct btrfs_block_rsv block_rsv;
2330         u64 root_flags;
2331         u64 qgroup_reserved;
2332         int namelen;
2333         int ret;
2334         int err = 0;
2335
2336         vol_args = memdup_user(arg, sizeof(*vol_args));
2337         if (IS_ERR(vol_args))
2338                 return PTR_ERR(vol_args);
2339
2340         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
2341         namelen = strlen(vol_args->name);
2342         if (strchr(vol_args->name, '/') ||
2343             strncmp(vol_args->name, "..", namelen) == 0) {
2344                 err = -EINVAL;
2345                 goto out;
2346         }
2347
2348         err = mnt_want_write_file(file);
2349         if (err)
2350                 goto out;
2351
2352
2353         err = mutex_lock_killable_nested(&dir->i_mutex, I_MUTEX_PARENT);
2354         if (err == -EINTR)
2355                 goto out_drop_write;
2356         dentry = lookup_one_len(vol_args->name, parent, namelen);
2357         if (IS_ERR(dentry)) {
2358                 err = PTR_ERR(dentry);
2359                 goto out_unlock_dir;
2360         }
2361
2362         if (d_really_is_negative(dentry)) {
2363                 err = -ENOENT;
2364                 goto out_dput;
2365         }
2366
2367         inode = d_inode(dentry);
2368         dest = BTRFS_I(inode)->root;
2369         if (!capable(CAP_SYS_ADMIN)) {
2370                 /*
2371                  * Regular user.  Only allow this with a special mount
2372                  * option, when the user has write+exec access to the
2373                  * subvol root, and when rmdir(2) would have been
2374                  * allowed.
2375                  *
2376                  * Note that this is _not_ check that the subvol is
2377                  * empty or doesn't contain data that we wouldn't
2378                  * otherwise be able to delete.
2379                  *
2380                  * Users who want to delete empty subvols should try
2381                  * rmdir(2).
2382                  */
2383                 err = -EPERM;
2384                 if (!btrfs_test_opt(root, USER_SUBVOL_RM_ALLOWED))
2385                         goto out_dput;
2386
2387                 /*
2388                  * Do not allow deletion if the parent dir is the same
2389                  * as the dir to be deleted.  That means the ioctl
2390                  * must be called on the dentry referencing the root
2391                  * of the subvol, not a random directory contained
2392                  * within it.
2393                  */
2394                 err = -EINVAL;
2395                 if (root == dest)
2396                         goto out_dput;
2397
2398                 err = inode_permission(inode, MAY_WRITE | MAY_EXEC);
2399                 if (err)
2400                         goto out_dput;
2401         }
2402
2403         /* check if subvolume may be deleted by a user */
2404         err = btrfs_may_delete(dir, dentry, 1);
2405         if (err)
2406                 goto out_dput;
2407
2408         if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID) {
2409                 err = -EINVAL;
2410                 goto out_dput;
2411         }
2412
2413         mutex_lock(&inode->i_mutex);
2414
2415         /*
2416          * Don't allow to delete a subvolume with send in progress. This is
2417          * inside the i_mutex so the error handling that has to drop the bit
2418          * again is not run concurrently.
2419          */
2420         spin_lock(&dest->root_item_lock);
2421         root_flags = btrfs_root_flags(&dest->root_item);
2422         if (dest->send_in_progress == 0) {
2423                 btrfs_set_root_flags(&dest->root_item,
2424                                 root_flags | BTRFS_ROOT_SUBVOL_DEAD);
2425                 spin_unlock(&dest->root_item_lock);
2426         } else {
2427                 spin_unlock(&dest->root_item_lock);
2428                 btrfs_warn(root->fs_info,
2429                         "Attempt to delete subvolume %llu during send",
2430                         dest->root_key.objectid);
2431                 err = -EPERM;
2432                 goto out_unlock_inode;
2433         }
2434
2435         down_write(&root->fs_info->subvol_sem);
2436
2437         err = may_destroy_subvol(dest);
2438         if (err)
2439                 goto out_up_write;
2440
2441         btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
2442         /*
2443          * One for dir inode, two for dir entries, two for root
2444          * ref/backref.
2445          */
2446         err = btrfs_subvolume_reserve_metadata(root, &block_rsv,
2447                                                5, &qgroup_reserved, true);
2448         if (err)
2449                 goto out_up_write;
2450
2451         trans = btrfs_start_transaction(root, 0);
2452         if (IS_ERR(trans)) {
2453                 err = PTR_ERR(trans);
2454                 goto out_release;
2455         }
2456         trans->block_rsv = &block_rsv;
2457         trans->bytes_reserved = block_rsv.size;
2458
2459         ret = btrfs_unlink_subvol(trans, root, dir,
2460                                 dest->root_key.objectid,
2461                                 dentry->d_name.name,
2462                                 dentry->d_name.len);
2463         if (ret) {
2464                 err = ret;
2465                 btrfs_abort_transaction(trans, root, ret);
2466                 goto out_end_trans;
2467         }
2468
2469         btrfs_record_root_in_trans(trans, dest);
2470
2471         memset(&dest->root_item.drop_progress, 0,
2472                 sizeof(dest->root_item.drop_progress));
2473         dest->root_item.drop_level = 0;
2474         btrfs_set_root_refs(&dest->root_item, 0);
2475
2476         if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
2477                 ret = btrfs_insert_orphan_item(trans,
2478                                         root->fs_info->tree_root,
2479                                         dest->root_key.objectid);
2480                 if (ret) {
2481                         btrfs_abort_transaction(trans, root, ret);
2482                         err = ret;
2483                         goto out_end_trans;
2484                 }
2485         }
2486
2487         ret = btrfs_uuid_tree_rem(trans, root->fs_info->uuid_root,
2488                                   dest->root_item.uuid, BTRFS_UUID_KEY_SUBVOL,
2489                                   dest->root_key.objectid);
2490         if (ret && ret != -ENOENT) {
2491                 btrfs_abort_transaction(trans, root, ret);
2492                 err = ret;
2493                 goto out_end_trans;
2494         }
2495         if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
2496                 ret = btrfs_uuid_tree_rem(trans, root->fs_info->uuid_root,
2497                                           dest->root_item.received_uuid,
2498                                           BTRFS_UUID_KEY_RECEIVED_SUBVOL,
2499                                           dest->root_key.objectid);
2500                 if (ret && ret != -ENOENT) {
2501                         btrfs_abort_transaction(trans, root, ret);
2502                         err = ret;
2503                         goto out_end_trans;
2504                 }
2505         }
2506
2507 out_end_trans:
2508         trans->block_rsv = NULL;
2509         trans->bytes_reserved = 0;
2510         ret = btrfs_end_transaction(trans, root);
2511         if (ret && !err)
2512                 err = ret;
2513         inode->i_flags |= S_DEAD;
2514 out_release:
2515         btrfs_subvolume_release_metadata(root, &block_rsv, qgroup_reserved);
2516 out_up_write:
2517         up_write(&root->fs_info->subvol_sem);
2518         if (err) {
2519                 spin_lock(&dest->root_item_lock);
2520                 root_flags = btrfs_root_flags(&dest->root_item);
2521                 btrfs_set_root_flags(&dest->root_item,
2522                                 root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
2523                 spin_unlock(&dest->root_item_lock);
2524         }
2525 out_unlock_inode:
2526         mutex_unlock(&inode->i_mutex);
2527         if (!err) {
2528                 d_invalidate(dentry);
2529                 btrfs_invalidate_inodes(dest);
2530                 d_delete(dentry);
2531                 ASSERT(dest->send_in_progress == 0);
2532
2533                 /* the last ref */
2534                 if (dest->ino_cache_inode) {
2535                         iput(dest->ino_cache_inode);
2536                         dest->ino_cache_inode = NULL;
2537                 }
2538         }
2539 out_dput:
2540         dput(dentry);
2541 out_unlock_dir:
2542         mutex_unlock(&dir->i_mutex);
2543 out_drop_write:
2544         mnt_drop_write_file(file);
2545 out:
2546         kfree(vol_args);
2547         return err;
2548 }
2549
2550 static int btrfs_ioctl_defrag(struct file *file, void __user *argp)
2551 {
2552         struct inode *inode = file_inode(file);
2553         struct btrfs_root *root = BTRFS_I(inode)->root;
2554         struct btrfs_ioctl_defrag_range_args *range;
2555         int ret;
2556
2557         ret = mnt_want_write_file(file);
2558         if (ret)
2559                 return ret;
2560
2561         if (btrfs_root_readonly(root)) {
2562                 ret = -EROFS;
2563                 goto out;
2564         }
2565
2566         switch (inode->i_mode & S_IFMT) {
2567         case S_IFDIR:
2568                 if (!capable(CAP_SYS_ADMIN)) {
2569                         ret = -EPERM;
2570                         goto out;
2571                 }
2572                 ret = btrfs_defrag_root(root);
2573                 if (ret)
2574                         goto out;
2575                 ret = btrfs_defrag_root(root->fs_info->extent_root);
2576                 break;
2577         case S_IFREG:
2578                 if (!(file->f_mode & FMODE_WRITE)) {
2579                         ret = -EINVAL;
2580                         goto out;
2581                 }
2582
2583                 range = kzalloc(sizeof(*range), GFP_KERNEL);
2584                 if (!range) {
2585                         ret = -ENOMEM;
2586                         goto out;
2587                 }
2588
2589                 if (argp) {
2590                         if (copy_from_user(range, argp,
2591                                            sizeof(*range))) {
2592                                 ret = -EFAULT;
2593                                 kfree(range);
2594                                 goto out;
2595                         }
2596                         /* compression requires us to start the IO */
2597                         if ((range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)) {
2598                                 range->flags |= BTRFS_DEFRAG_RANGE_START_IO;
2599                                 range->extent_thresh = (u32)-1;
2600                         }
2601                 } else {
2602                         /* the rest are all set to zero by kzalloc */
2603                         range->len = (u64)-1;
2604                 }
2605                 ret = btrfs_defrag_file(file_inode(file), file,
2606                                         range, 0, 0);
2607                 if (ret > 0)
2608                         ret = 0;
2609                 kfree(range);
2610                 break;
2611         default:
2612                 ret = -EINVAL;
2613         }
2614 out:
2615         mnt_drop_write_file(file);
2616         return ret;
2617 }
2618
2619 static long btrfs_ioctl_add_dev(struct btrfs_root *root, void __user *arg)
2620 {
2621         struct btrfs_ioctl_vol_args *vol_args;
2622         int ret;
2623
2624         if (!capable(CAP_SYS_ADMIN))
2625                 return -EPERM;
2626
2627         if (atomic_xchg(&root->fs_info->mutually_exclusive_operation_running,
2628                         1)) {
2629                 return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
2630         }
2631
2632         mutex_lock(&root->fs_info->volume_mutex);
2633         vol_args = memdup_user(arg, sizeof(*vol_args));
2634         if (IS_ERR(vol_args)) {
2635                 ret = PTR_ERR(vol_args);
2636                 goto out;
2637         }
2638
2639         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
2640         ret = btrfs_init_new_device(root, vol_args->name);
2641
2642         if (!ret)
2643                 btrfs_info(root->fs_info, "disk added %s",vol_args->name);
2644
2645         kfree(vol_args);
2646 out:
2647         mutex_unlock(&root->fs_info->volume_mutex);
2648         atomic_set(&root->fs_info->mutually_exclusive_operation_running, 0);
2649         return ret;
2650 }
2651
2652 static long btrfs_ioctl_rm_dev(struct file *file, void __user *arg)
2653 {
2654         struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
2655         struct btrfs_ioctl_vol_args *vol_args;
2656         int ret;
2657
2658         if (!capable(CAP_SYS_ADMIN))
2659                 return -EPERM;
2660
2661         ret = mnt_want_write_file(file);
2662         if (ret)
2663                 return ret;
2664
2665         vol_args = memdup_user(arg, sizeof(*vol_args));
2666         if (IS_ERR(vol_args)) {
2667                 ret = PTR_ERR(vol_args);
2668                 goto err_drop;
2669         }
2670
2671         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
2672
2673         if (atomic_xchg(&root->fs_info->mutually_exclusive_operation_running,
2674                         1)) {
2675                 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
2676                 goto out;
2677         }
2678
2679         mutex_lock(&root->fs_info->volume_mutex);
2680         ret = btrfs_rm_device(root, vol_args->name);
2681         mutex_unlock(&root->fs_info->volume_mutex);
2682         atomic_set(&root->fs_info->mutually_exclusive_operation_running, 0);
2683
2684         if (!ret)
2685                 btrfs_info(root->fs_info, "disk deleted %s",vol_args->name);
2686
2687 out:
2688         kfree(vol_args);
2689 err_drop:
2690         mnt_drop_write_file(file);
2691         return ret;
2692 }
2693
2694 static long btrfs_ioctl_fs_info(struct btrfs_root *root, void __user *arg)
2695 {
2696         struct btrfs_ioctl_fs_info_args *fi_args;
2697         struct btrfs_device *device;
2698         struct btrfs_device *next;
2699         struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
2700         int ret = 0;
2701
2702         fi_args = kzalloc(sizeof(*fi_args), GFP_KERNEL);
2703         if (!fi_args)
2704                 return -ENOMEM;
2705
2706         mutex_lock(&fs_devices->device_list_mutex);
2707         fi_args->num_devices = fs_devices->num_devices;
2708         memcpy(&fi_args->fsid, root->fs_info->fsid, sizeof(fi_args->fsid));
2709
2710         list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
2711                 if (device->devid > fi_args->max_id)
2712                         fi_args->max_id = device->devid;
2713         }
2714         mutex_unlock(&fs_devices->device_list_mutex);
2715
2716         fi_args->nodesize = root->fs_info->super_copy->nodesize;
2717         fi_args->sectorsize = root->fs_info->super_copy->sectorsize;
2718         fi_args->clone_alignment = root->fs_info->super_copy->sectorsize;
2719
2720         if (copy_to_user(arg, fi_args, sizeof(*fi_args)))
2721                 ret = -EFAULT;
2722
2723         kfree(fi_args);
2724         return ret;
2725 }
2726
2727 static long btrfs_ioctl_dev_info(struct btrfs_root *root, void __user *arg)
2728 {
2729         struct btrfs_ioctl_dev_info_args *di_args;
2730         struct btrfs_device *dev;
2731         struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
2732         int ret = 0;
2733         char *s_uuid = NULL;
2734
2735         di_args = memdup_user(arg, sizeof(*di_args));
2736         if (IS_ERR(di_args))
2737                 return PTR_ERR(di_args);
2738
2739         if (!btrfs_is_empty_uuid(di_args->uuid))
2740                 s_uuid = di_args->uuid;
2741
2742         mutex_lock(&fs_devices->device_list_mutex);
2743         dev = btrfs_find_device(root->fs_info, di_args->devid, s_uuid, NULL);
2744
2745         if (!dev) {
2746                 ret = -ENODEV;
2747                 goto out;
2748         }
2749
2750         di_args->devid = dev->devid;
2751         di_args->bytes_used = btrfs_device_get_bytes_used(dev);
2752         di_args->total_bytes = btrfs_device_get_total_bytes(dev);
2753         memcpy(di_args->uuid, dev->uuid, sizeof(di_args->uuid));
2754         if (dev->name) {
2755                 struct rcu_string *name;
2756
2757                 rcu_read_lock();
2758                 name = rcu_dereference(dev->name);
2759                 strncpy(di_args->path, name->str, sizeof(di_args->path));
2760                 rcu_read_unlock();
2761                 di_args->path[sizeof(di_args->path) - 1] = 0;
2762         } else {
2763                 di_args->path[0] = '\0';
2764         }
2765
2766 out:
2767         mutex_unlock(&fs_devices->device_list_mutex);
2768         if (ret == 0 && copy_to_user(arg, di_args, sizeof(*di_args)))
2769                 ret = -EFAULT;
2770
2771         kfree(di_args);
2772         return ret;
2773 }
2774
2775 static struct page *extent_same_get_page(struct inode *inode, pgoff_t index)
2776 {
2777         struct page *page;
2778         struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
2779
2780         page = grab_cache_page(inode->i_mapping, index);
2781         if (!page)
2782                 return NULL;
2783
2784         if (!PageUptodate(page)) {
2785                 if (extent_read_full_page_nolock(tree, page, btrfs_get_extent,
2786                                                  0))
2787                         return NULL;
2788                 lock_page(page);
2789                 if (!PageUptodate(page)) {
2790                         unlock_page(page);
2791                         page_cache_release(page);
2792                         return NULL;
2793                 }
2794         }
2795         unlock_page(page);
2796
2797         return page;
2798 }
2799
2800 static int gather_extent_pages(struct inode *inode, struct page **pages,
2801                                int num_pages, u64 off)
2802 {
2803         int i;
2804         pgoff_t index = off >> PAGE_CACHE_SHIFT;
2805
2806         for (i = 0; i < num_pages; i++) {
2807                 pages[i] = extent_same_get_page(inode, index + i);
2808                 if (!pages[i])
2809                         return -ENOMEM;
2810         }
2811         return 0;
2812 }
2813
2814 static inline void lock_extent_range(struct inode *inode, u64 off, u64 len)
2815 {
2816         /* do any pending delalloc/csum calc on src, one way or
2817            another, and lock file content */
2818         while (1) {
2819                 struct btrfs_ordered_extent *ordered;
2820                 lock_extent(&BTRFS_I(inode)->io_tree, off, off + len - 1);
2821                 ordered = btrfs_lookup_first_ordered_extent(inode,
2822                                                             off + len - 1);
2823                 if ((!ordered ||
2824                      ordered->file_offset + ordered->len <= off ||
2825                      ordered->file_offset >= off + len) &&
2826                     !test_range_bit(&BTRFS_I(inode)->io_tree, off,
2827                                     off + len - 1, EXTENT_DELALLOC, 0, NULL)) {
2828                         if (ordered)
2829                                 btrfs_put_ordered_extent(ordered);
2830                         break;
2831                 }
2832                 unlock_extent(&BTRFS_I(inode)->io_tree, off, off + len - 1);
2833                 if (ordered)
2834                         btrfs_put_ordered_extent(ordered);
2835                 btrfs_wait_ordered_range(inode, off, len);
2836         }
2837 }
2838
2839 static void btrfs_double_inode_unlock(struct inode *inode1, struct inode *inode2)
2840 {
2841         mutex_unlock(&inode1->i_mutex);
2842         mutex_unlock(&inode2->i_mutex);
2843 }
2844
2845 static void btrfs_double_inode_lock(struct inode *inode1, struct inode *inode2)
2846 {
2847         if (inode1 < inode2)
2848                 swap(inode1, inode2);
2849
2850         mutex_lock_nested(&inode1->i_mutex, I_MUTEX_PARENT);
2851         if (inode1 != inode2)
2852                 mutex_lock_nested(&inode2->i_mutex, I_MUTEX_CHILD);
2853 }
2854
2855 static void btrfs_double_extent_unlock(struct inode *inode1, u64 loff1,
2856                                       struct inode *inode2, u64 loff2, u64 len)
2857 {
2858         unlock_extent(&BTRFS_I(inode1)->io_tree, loff1, loff1 + len - 1);
2859         unlock_extent(&BTRFS_I(inode2)->io_tree, loff2, loff2 + len - 1);
2860 }
2861
2862 static void btrfs_double_extent_lock(struct inode *inode1, u64 loff1,
2863                                      struct inode *inode2, u64 loff2, u64 len)
2864 {
2865         if (inode1 < inode2) {
2866                 swap(inode1, inode2);
2867                 swap(loff1, loff2);
2868         }
2869         lock_extent_range(inode1, loff1, len);
2870         if (inode1 != inode2)
2871                 lock_extent_range(inode2, loff2, len);
2872 }
2873
2874 struct cmp_pages {
2875         int             num_pages;
2876         struct page     **src_pages;
2877         struct page     **dst_pages;
2878 };
2879
2880 static void btrfs_cmp_data_free(struct cmp_pages *cmp)
2881 {
2882         int i;
2883         struct page *pg;
2884
2885         for (i = 0; i < cmp->num_pages; i++) {
2886                 pg = cmp->src_pages[i];
2887                 if (pg)
2888                         page_cache_release(pg);
2889                 pg = cmp->dst_pages[i];
2890                 if (pg)
2891                         page_cache_release(pg);
2892         }
2893         kfree(cmp->src_pages);
2894         kfree(cmp->dst_pages);
2895 }
2896
2897 static int btrfs_cmp_data_prepare(struct inode *src, u64 loff,
2898                                   struct inode *dst, u64 dst_loff,
2899                                   u64 len, struct cmp_pages *cmp)
2900 {
2901         int ret;
2902         int num_pages = PAGE_CACHE_ALIGN(len) >> PAGE_CACHE_SHIFT;
2903         struct page **src_pgarr, **dst_pgarr;
2904
2905         /*
2906          * We must gather up all the pages before we initiate our
2907          * extent locking. We use an array for the page pointers. Size
2908          * of the array is bounded by len, which is in turn bounded by
2909          * BTRFS_MAX_DEDUPE_LEN.
2910          */
2911         src_pgarr = kzalloc(num_pages * sizeof(struct page *), GFP_NOFS);
2912         dst_pgarr = kzalloc(num_pages * sizeof(struct page *), GFP_NOFS);
2913         if (!src_pgarr || !dst_pgarr) {
2914                 kfree(src_pgarr);
2915                 kfree(dst_pgarr);
2916                 return -ENOMEM;
2917         }
2918         cmp->num_pages = num_pages;
2919         cmp->src_pages = src_pgarr;
2920         cmp->dst_pages = dst_pgarr;
2921
2922         ret = gather_extent_pages(src, cmp->src_pages, cmp->num_pages, loff);
2923         if (ret)
2924                 goto out;
2925
2926         ret = gather_extent_pages(dst, cmp->dst_pages, cmp->num_pages, dst_loff);
2927
2928 out:
2929         if (ret)
2930                 btrfs_cmp_data_free(cmp);
2931         return 0;
2932 }
2933
2934 static int btrfs_cmp_data(struct inode *src, u64 loff, struct inode *dst,
2935                           u64 dst_loff, u64 len, struct cmp_pages *cmp)
2936 {
2937         int ret = 0;
2938         int i;
2939         struct page *src_page, *dst_page;
2940         unsigned int cmp_len = PAGE_CACHE_SIZE;
2941         void *addr, *dst_addr;
2942
2943         i = 0;
2944         while (len) {
2945                 if (len < PAGE_CACHE_SIZE)
2946                         cmp_len = len;
2947
2948                 BUG_ON(i >= cmp->num_pages);
2949
2950                 src_page = cmp->src_pages[i];
2951                 dst_page = cmp->dst_pages[i];
2952
2953                 addr = kmap_atomic(src_page);
2954                 dst_addr = kmap_atomic(dst_page);
2955
2956                 flush_dcache_page(src_page);
2957                 flush_dcache_page(dst_page);
2958
2959                 if (memcmp(addr, dst_addr, cmp_len))
2960                         ret = BTRFS_SAME_DATA_DIFFERS;
2961
2962                 kunmap_atomic(addr);
2963                 kunmap_atomic(dst_addr);
2964
2965                 if (ret)
2966                         break;
2967
2968                 len -= cmp_len;
2969                 i++;
2970         }
2971
2972         return ret;
2973 }
2974
2975 static int extent_same_check_offsets(struct inode *inode, u64 off, u64 *plen,
2976                                      u64 olen)
2977 {
2978         u64 len = *plen;
2979         u64 bs = BTRFS_I(inode)->root->fs_info->sb->s_blocksize;
2980
2981         if (off + olen > inode->i_size || off + olen < off)
2982                 return -EINVAL;
2983
2984         /* if we extend to eof, continue to block boundary */
2985         if (off + len == inode->i_size)
2986                 *plen = len = ALIGN(inode->i_size, bs) - off;
2987
2988         /* Check that we are block aligned - btrfs_clone() requires this */
2989         if (!IS_ALIGNED(off, bs) || !IS_ALIGNED(off + len, bs))
2990                 return -EINVAL;
2991
2992         return 0;
2993 }
2994
2995 static int btrfs_extent_same(struct inode *src, u64 loff, u64 olen,
2996                              struct inode *dst, u64 dst_loff)
2997 {
2998         int ret;
2999         u64 len = olen;
3000         struct cmp_pages cmp;
3001         int same_inode = 0;
3002         u64 same_lock_start = 0;
3003         u64 same_lock_len = 0;
3004
3005         if (src == dst)
3006                 same_inode = 1;
3007
3008         if (len == 0)
3009                 return 0;
3010
3011         if (same_inode) {
3012                 mutex_lock(&src->i_mutex);
3013
3014                 ret = extent_same_check_offsets(src, loff, &len, olen);
3015                 if (ret)
3016                         goto out_unlock;
3017
3018                 /*
3019                  * Single inode case wants the same checks, except we
3020                  * don't want our length pushed out past i_size as
3021                  * comparing that data range makes no sense.
3022                  *
3023                  * extent_same_check_offsets() will do this for an
3024                  * unaligned length at i_size, so catch it here and
3025                  * reject the request.
3026                  *
3027                  * This effectively means we require aligned extents
3028                  * for the single-inode case, whereas the other cases
3029                  * allow an unaligned length so long as it ends at
3030                  * i_size.
3031                  */
3032                 if (len != olen) {
3033                         ret = -EINVAL;
3034                         goto out_unlock;
3035                 }
3036
3037                 /* Check for overlapping ranges */
3038                 if (dst_loff + len > loff && dst_loff < loff + len) {
3039                         ret = -EINVAL;
3040                         goto out_unlock;
3041                 }
3042
3043                 same_lock_start = min_t(u64, loff, dst_loff);
3044                 same_lock_len = max_t(u64, loff, dst_loff) + len - same_lock_start;
3045         } else {
3046                 btrfs_double_inode_lock(src, dst);
3047
3048                 ret = extent_same_check_offsets(src, loff, &len, olen);
3049                 if (ret)
3050                         goto out_unlock;
3051
3052                 ret = extent_same_check_offsets(dst, dst_loff, &len, olen);
3053                 if (ret)
3054                         goto out_unlock;
3055         }
3056
3057         /* don't make the dst file partly checksummed */
3058         if ((BTRFS_I(src)->flags & BTRFS_INODE_NODATASUM) !=
3059             (BTRFS_I(dst)->flags & BTRFS_INODE_NODATASUM)) {
3060                 ret = -EINVAL;
3061                 goto out_unlock;
3062         }
3063
3064         ret = btrfs_cmp_data_prepare(src, loff, dst, dst_loff, olen, &cmp);
3065         if (ret)
3066                 goto out_unlock;
3067
3068         if (same_inode)
3069                 lock_extent_range(src, same_lock_start, same_lock_len);
3070         else
3071                 btrfs_double_extent_lock(src, loff, dst, dst_loff, len);
3072
3073         /* pass original length for comparison so we stay within i_size */
3074         ret = btrfs_cmp_data(src, loff, dst, dst_loff, olen, &cmp);
3075         if (ret == 0)
3076                 ret = btrfs_clone(src, dst, loff, olen, len, dst_loff, 1);
3077
3078         if (same_inode)
3079                 unlock_extent(&BTRFS_I(src)->io_tree, same_lock_start,
3080                               same_lock_start + same_lock_len - 1);
3081         else
3082                 btrfs_double_extent_unlock(src, loff, dst, dst_loff, len);
3083
3084         btrfs_cmp_data_free(&cmp);
3085 out_unlock:
3086         if (same_inode)
3087                 mutex_unlock(&src->i_mutex);
3088         else
3089                 btrfs_double_inode_unlock(src, dst);
3090
3091         return ret;
3092 }
3093
3094 #define BTRFS_MAX_DEDUPE_LEN    (16 * 1024 * 1024)
3095
3096 static long btrfs_ioctl_file_extent_same(struct file *file,
3097                         struct btrfs_ioctl_same_args __user *argp)
3098 {
3099         struct btrfs_ioctl_same_args *same = NULL;
3100         struct btrfs_ioctl_same_extent_info *info;
3101         struct inode *src = file_inode(file);
3102         u64 off;
3103         u64 len;
3104         int i;
3105         int ret;
3106         unsigned long size;
3107         u64 bs = BTRFS_I(src)->root->fs_info->sb->s_blocksize;
3108         bool is_admin = capable(CAP_SYS_ADMIN);
3109         u16 count;
3110
3111         if (!(file->f_mode & FMODE_READ))
3112                 return -EINVAL;
3113
3114         ret = mnt_want_write_file(file);
3115         if (ret)
3116                 return ret;
3117
3118         if (get_user(count, &argp->dest_count)) {
3119                 ret = -EFAULT;
3120                 goto out;
3121         }
3122
3123         size = offsetof(struct btrfs_ioctl_same_args __user, info[count]);
3124
3125         same = memdup_user(argp, size);
3126
3127         if (IS_ERR(same)) {
3128                 ret = PTR_ERR(same);
3129                 same = NULL;
3130                 goto out;
3131         }
3132
3133         off = same->logical_offset;
3134         len = same->length;
3135
3136         /*
3137          * Limit the total length we will dedupe for each operation.
3138          * This is intended to bound the total time spent in this
3139          * ioctl to something sane.
3140          */
3141         if (len > BTRFS_MAX_DEDUPE_LEN)
3142                 len = BTRFS_MAX_DEDUPE_LEN;
3143
3144         if (WARN_ON_ONCE(bs < PAGE_CACHE_SIZE)) {
3145                 /*
3146                  * Btrfs does not support blocksize < page_size. As a
3147                  * result, btrfs_cmp_data() won't correctly handle
3148                  * this situation without an update.
3149                  */
3150                 ret = -EINVAL;
3151                 goto out;
3152         }
3153
3154         ret = -EISDIR;
3155         if (S_ISDIR(src->i_mode))
3156                 goto out;
3157
3158         ret = -EACCES;
3159         if (!S_ISREG(src->i_mode))
3160                 goto out;
3161
3162         /* pre-format output fields to sane values */
3163         for (i = 0; i < count; i++) {
3164                 same->info[i].bytes_deduped = 0ULL;
3165                 same->info[i].status = 0;
3166         }
3167
3168         for (i = 0, info = same->info; i < count; i++, info++) {
3169                 struct inode *dst;
3170                 struct fd dst_file = fdget(info->fd);
3171                 if (!dst_file.file) {
3172                         info->status = -EBADF;
3173                         continue;
3174                 }
3175                 dst = file_inode(dst_file.file);
3176
3177                 if (!(is_admin || (dst_file.file->f_mode & FMODE_WRITE))) {
3178                         info->status = -EINVAL;
3179                 } else if (file->f_path.mnt != dst_file.file->f_path.mnt) {
3180                         info->status = -EXDEV;
3181                 } else if (S_ISDIR(dst->i_mode)) {
3182                         info->status = -EISDIR;
3183                 } else if (!S_ISREG(dst->i_mode)) {
3184                         info->status = -EACCES;
3185                 } else {
3186                         info->status = btrfs_extent_same(src, off, len, dst,
3187                                                         info->logical_offset);
3188                         if (info->status == 0)
3189                                 info->bytes_deduped += len;
3190                 }
3191                 fdput(dst_file);
3192         }
3193
3194         ret = copy_to_user(argp, same, size);
3195         if (ret)
3196                 ret = -EFAULT;
3197
3198 out:
3199         mnt_drop_write_file(file);
3200         kfree(same);
3201         return ret;
3202 }
3203
3204 /* Helper to check and see if this root currently has a ref on the given disk
3205  * bytenr.  If it does then we need to update the quota for this root.  This
3206  * doesn't do anything if quotas aren't enabled.
3207  */
3208 static int check_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
3209                      u64 disko)
3210 {
3211         struct seq_list tree_mod_seq_elem = SEQ_LIST_INIT(tree_mod_seq_elem);
3212         struct ulist *roots;
3213         struct ulist_iterator uiter;
3214         struct ulist_node *root_node = NULL;
3215         int ret;
3216
3217         if (!root->fs_info->quota_enabled)
3218                 return 1;
3219
3220         btrfs_get_tree_mod_seq(root->fs_info, &tree_mod_seq_elem);
3221         ret = btrfs_find_all_roots(trans, root->fs_info, disko,
3222                                    tree_mod_seq_elem.seq, &roots);
3223         if (ret < 0)
3224                 goto out;
3225         ret = 0;
3226         ULIST_ITER_INIT(&uiter);
3227         while ((root_node = ulist_next(roots, &uiter))) {
3228                 if (root_node->val == root->objectid) {
3229                         ret = 1;
3230                         break;
3231                 }
3232         }
3233         ulist_free(roots);
3234 out:
3235         btrfs_put_tree_mod_seq(root->fs_info, &tree_mod_seq_elem);
3236         return ret;
3237 }
3238
3239 static int clone_finish_inode_update(struct btrfs_trans_handle *trans,
3240                                      struct inode *inode,
3241                                      u64 endoff,
3242                                      const u64 destoff,
3243                                      const u64 olen,
3244                                      int no_time_update)
3245 {
3246         struct btrfs_root *root = BTRFS_I(inode)->root;
3247         int ret;
3248
3249         inode_inc_iversion(inode);
3250         if (!no_time_update)
3251                 inode->i_mtime = inode->i_ctime = CURRENT_TIME;
3252         /*
3253          * We round up to the block size at eof when determining which
3254          * extents to clone above, but shouldn't round up the file size.
3255          */
3256         if (endoff > destoff + olen)
3257                 endoff = destoff + olen;
3258         if (endoff > inode->i_size)
3259                 btrfs_i_size_write(inode, endoff);
3260
3261         ret = btrfs_update_inode(trans, root, inode);
3262         if (ret) {
3263                 btrfs_abort_transaction(trans, root, ret);
3264                 btrfs_end_transaction(trans, root);
3265                 goto out;
3266         }
3267         ret = btrfs_end_transaction(trans, root);
3268 out:
3269         return ret;
3270 }
3271
3272 static void clone_update_extent_map(struct inode *inode,
3273                                     const struct btrfs_trans_handle *trans,
3274                                     const struct btrfs_path *path,
3275                                     const u64 hole_offset,
3276                                     const u64 hole_len)
3277 {
3278         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
3279         struct extent_map *em;
3280         int ret;
3281
3282         em = alloc_extent_map();
3283         if (!em) {
3284                 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3285                         &BTRFS_I(inode)->runtime_flags);
3286                 return;
3287         }
3288
3289         if (path) {
3290                 struct btrfs_file_extent_item *fi;
3291
3292                 fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
3293                                     struct btrfs_file_extent_item);
3294                 btrfs_extent_item_to_extent_map(inode, path, fi, false, em);
3295                 em->generation = -1;
3296                 if (btrfs_file_extent_type(path->nodes[0], fi) ==
3297                     BTRFS_FILE_EXTENT_INLINE)
3298                         set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3299                                 &BTRFS_I(inode)->runtime_flags);
3300         } else {
3301                 em->start = hole_offset;
3302                 em->len = hole_len;
3303                 em->ram_bytes = em->len;
3304                 em->orig_start = hole_offset;
3305                 em->block_start = EXTENT_MAP_HOLE;
3306                 em->block_len = 0;
3307                 em->orig_block_len = 0;
3308                 em->compress_type = BTRFS_COMPRESS_NONE;
3309                 em->generation = trans->transid;
3310         }
3311
3312         while (1) {
3313                 write_lock(&em_tree->lock);
3314                 ret = add_extent_mapping(em_tree, em, 1);
3315                 write_unlock(&em_tree->lock);
3316                 if (ret != -EEXIST) {
3317                         free_extent_map(em);
3318                         break;
3319                 }
3320                 btrfs_drop_extent_cache(inode, em->start,
3321                                         em->start + em->len - 1, 0);
3322         }
3323
3324         if (ret)
3325                 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3326                         &BTRFS_I(inode)->runtime_flags);
3327 }
3328
3329 /**
3330  * btrfs_clone() - clone a range from inode file to another
3331  *
3332  * @src: Inode to clone from
3333  * @inode: Inode to clone to
3334  * @off: Offset within source to start clone from
3335  * @olen: Original length, passed by user, of range to clone
3336  * @olen_aligned: Block-aligned value of olen
3337  * @destoff: Offset within @inode to start clone
3338  * @no_time_update: Whether to update mtime/ctime on the target inode
3339  */
3340 static int btrfs_clone(struct inode *src, struct inode *inode,
3341                        const u64 off, const u64 olen, const u64 olen_aligned,
3342                        const u64 destoff, int no_time_update)
3343 {
3344         struct btrfs_root *root = BTRFS_I(inode)->root;
3345         struct btrfs_path *path = NULL;
3346         struct extent_buffer *leaf;
3347         struct btrfs_trans_handle *trans;
3348         char *buf = NULL;
3349         struct btrfs_key key;
3350         u32 nritems;
3351         int slot;
3352         int ret;
3353         int no_quota;
3354         const u64 len = olen_aligned;
3355         u64 last_disko = 0;
3356         u64 last_dest_end = destoff;
3357
3358         ret = -ENOMEM;
3359         buf = vmalloc(root->nodesize);
3360         if (!buf)
3361                 return ret;
3362
3363         path = btrfs_alloc_path();
3364         if (!path) {
3365                 vfree(buf);
3366                 return ret;
3367         }
3368
3369         path->reada = 2;
3370         /* clone data */
3371         key.objectid = btrfs_ino(src);
3372         key.type = BTRFS_EXTENT_DATA_KEY;
3373         key.offset = off;
3374
3375         while (1) {
3376                 u64 next_key_min_offset = key.offset + 1;
3377
3378                 /*
3379                  * note the key will change type as we walk through the
3380                  * tree.
3381                  */
3382                 path->leave_spinning = 1;
3383                 ret = btrfs_search_slot(NULL, BTRFS_I(src)->root, &key, path,
3384                                 0, 0);
3385                 if (ret < 0)
3386                         goto out;
3387                 /*
3388                  * First search, if no extent item that starts at offset off was
3389                  * found but the previous item is an extent item, it's possible
3390                  * it might overlap our target range, therefore process it.
3391                  */
3392                 if (key.offset == off && ret > 0 && path->slots[0] > 0) {
3393                         btrfs_item_key_to_cpu(path->nodes[0], &key,
3394                                               path->slots[0] - 1);
3395                         if (key.type == BTRFS_EXTENT_DATA_KEY)
3396                                 path->slots[0]--;
3397                 }
3398
3399                 nritems = btrfs_header_nritems(path->nodes[0]);
3400 process_slot:
3401                 no_quota = 1;
3402                 if (path->slots[0] >= nritems) {
3403                         ret = btrfs_next_leaf(BTRFS_I(src)->root, path);
3404                         if (ret < 0)
3405                                 goto out;
3406                         if (ret > 0)
3407                                 break;
3408                         nritems = btrfs_header_nritems(path->nodes[0]);
3409                 }
3410                 leaf = path->nodes[0];
3411                 slot = path->slots[0];
3412
3413                 btrfs_item_key_to_cpu(leaf, &key, slot);
3414                 if (key.type > BTRFS_EXTENT_DATA_KEY ||
3415                     key.objectid != btrfs_ino(src))
3416                         break;
3417
3418                 if (key.type == BTRFS_EXTENT_DATA_KEY) {
3419                         struct btrfs_file_extent_item *extent;
3420                         int type;
3421      &n