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