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