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