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