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