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