~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/fs/btrfs/ioctl.c

Version: ~ [ linux-5.5 ] ~ [ linux-5.4.15 ] ~ [ linux-5.3.18 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.98 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.167 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.211 ] ~ [ linux-4.8.17 ] ~ [ linux-4.7.10 ] ~ [ linux-4.6.7 ] ~ [ linux-4.5.7 ] ~ [ linux-4.4.211 ] ~ [ linux-4.3.6 ] ~ [ linux-4.2.8 ] ~ [ linux-4.1.52 ] ~ [ linux-4.0.9 ] ~ [ linux-3.19.8 ] ~ [ linux-3.18.140 ] ~ [ linux-3.17.8 ] ~ [ linux-3.16.81 ] ~ [ linux-3.15.10 ] ~ [ linux-3.14.79 ] ~ [ linux-3.13.11 ] ~ [ linux-3.12.74 ] ~ [ linux-3.11.10 ] ~ [ linux-3.10.108 ] ~ [ linux-3.9.11 ] ~ [ linux-3.8.13 ] ~ [ linux-3.7.10 ] ~ [ linux-3.6.11 ] ~ [ linux-3.5.7 ] ~ [ linux-3.4.113 ] ~ [ linux-3.3.8 ] ~ [ linux-3.2.102 ] ~ [ linux-3.1.10 ] ~ [ linux-3.0.101 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.5 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

  1 // SPDX-License-Identifier: GPL-2.0
  2 /*
  3  * Copyright (C) 2007 Oracle.  All rights reserved.
  4  */
  5 
  6 #include <linux/kernel.h>
  7 #include <linux/bio.h>
  8 #include <linux/buffer_head.h>
  9 #include <linux/file.h>
 10 #include <linux/fs.h>
 11 #include <linux/fsnotify.h>
 12 #include <linux/pagemap.h>
 13 #include <linux/highmem.h>
 14 #include <linux/time.h>
 15 #include <linux/init.h>
 16 #include <linux/string.h>
 17 #include <linux/backing-dev.h>
 18 #include <linux/mount.h>
 19 #include <linux/mpage.h>
 20 #include <linux/namei.h>
 21 #include <linux/swap.h>
 22 #include <linux/writeback.h>
 23 #include <linux/compat.h>
 24 #include <linux/bit_spinlock.h>
 25 #include <linux/security.h>
 26 #include <linux/xattr.h>
 27 #include <linux/mm.h>
 28 #include <linux/slab.h>
 29 #include <linux/blkdev.h>
 30 #include <linux/uuid.h>
 31 #include <linux/btrfs.h>
 32 #include <linux/uaccess.h>
 33 #include <linux/iversion.h>
 34 #include "ctree.h"
 35 #include "disk-io.h"
 36 #include "transaction.h"
 37 #include "btrfs_inode.h"
 38 #include "print-tree.h"
 39 #include "volumes.h"
 40 #include "locking.h"
 41 #include "inode-map.h"
 42 #include "backref.h"
 43 #include "rcu-string.h"
 44 #include "send.h"
 45 #include "dev-replace.h"
 46 #include "props.h"
 47 #include "sysfs.h"
 48 #include "qgroup.h"
 49 #include "tree-log.h"
 50 #include "compression.h"
 51 
 52 #ifdef CONFIG_64BIT
 53 /* If we have a 32-bit userspace and 64-bit kernel, then the UAPI
 54  * structures are incorrect, as the timespec structure from userspace
 55  * is 4 bytes too small. We define these alternatives here to teach
 56  * the kernel about the 32-bit struct packing.
 57  */
 58 struct btrfs_ioctl_timespec_32 {
 59         __u64 sec;
 60         __u32 nsec;
 61 } __attribute__ ((__packed__));
 62 
 63 struct btrfs_ioctl_received_subvol_args_32 {
 64         char    uuid[BTRFS_UUID_SIZE];  /* in */
 65         __u64   stransid;               /* in */
 66         __u64   rtransid;               /* out */
 67         struct btrfs_ioctl_timespec_32 stime; /* in */
 68         struct btrfs_ioctl_timespec_32 rtime; /* out */
 69         __u64   flags;                  /* in */
 70         __u64   reserved[16];           /* in */
 71 } __attribute__ ((__packed__));
 72 
 73 #define BTRFS_IOC_SET_RECEIVED_SUBVOL_32 _IOWR(BTRFS_IOCTL_MAGIC, 37, \
 74                                 struct btrfs_ioctl_received_subvol_args_32)
 75 #endif
 76 
 77 #if defined(CONFIG_64BIT) && defined(CONFIG_COMPAT)
 78 struct btrfs_ioctl_send_args_32 {
 79         __s64 send_fd;                  /* in */
 80         __u64 clone_sources_count;      /* in */
 81         compat_uptr_t clone_sources;    /* in */
 82         __u64 parent_root;              /* in */
 83         __u64 flags;                    /* in */
 84         __u64 reserved[4];              /* in */
 85 } __attribute__ ((__packed__));
 86 
 87 #define BTRFS_IOC_SEND_32 _IOW(BTRFS_IOCTL_MAGIC, 38, \
 88                                struct btrfs_ioctl_send_args_32)
 89 #endif
 90 
 91 static int btrfs_clone(struct inode *src, struct inode *inode,
 92                        u64 off, u64 olen, u64 olen_aligned, u64 destoff,
 93                        int no_time_update);
 94 
 95 /* Mask out flags that are inappropriate for the given type of inode. */
 96 static unsigned int btrfs_mask_fsflags_for_type(struct inode *inode,
 97                 unsigned int flags)
 98 {
 99         if (S_ISDIR(inode->i_mode))
100                 return flags;
101         else if (S_ISREG(inode->i_mode))
102                 return flags & ~FS_DIRSYNC_FL;
103         else
104                 return flags & (FS_NODUMP_FL | FS_NOATIME_FL);
105 }
106 
107 /*
108  * Export internal inode flags to the format expected by the FS_IOC_GETFLAGS
109  * ioctl.
110  */
111 static unsigned int btrfs_inode_flags_to_fsflags(unsigned int flags)
112 {
113         unsigned int iflags = 0;
114 
115         if (flags & BTRFS_INODE_SYNC)
116                 iflags |= FS_SYNC_FL;
117         if (flags & BTRFS_INODE_IMMUTABLE)
118                 iflags |= FS_IMMUTABLE_FL;
119         if (flags & BTRFS_INODE_APPEND)
120                 iflags |= FS_APPEND_FL;
121         if (flags & BTRFS_INODE_NODUMP)
122                 iflags |= FS_NODUMP_FL;
123         if (flags & BTRFS_INODE_NOATIME)
124                 iflags |= FS_NOATIME_FL;
125         if (flags & BTRFS_INODE_DIRSYNC)
126                 iflags |= FS_DIRSYNC_FL;
127         if (flags & BTRFS_INODE_NODATACOW)
128                 iflags |= FS_NOCOW_FL;
129 
130         if (flags & BTRFS_INODE_NOCOMPRESS)
131                 iflags |= FS_NOCOMP_FL;
132         else if (flags & BTRFS_INODE_COMPRESS)
133                 iflags |= FS_COMPR_FL;
134 
135         return iflags;
136 }
137 
138 /*
139  * Update inode->i_flags based on the btrfs internal flags.
140  */
141 void btrfs_sync_inode_flags_to_i_flags(struct inode *inode)
142 {
143         struct btrfs_inode *binode = BTRFS_I(inode);
144         unsigned int new_fl = 0;
145 
146         if (binode->flags & BTRFS_INODE_SYNC)
147                 new_fl |= S_SYNC;
148         if (binode->flags & BTRFS_INODE_IMMUTABLE)
149                 new_fl |= S_IMMUTABLE;
150         if (binode->flags & BTRFS_INODE_APPEND)
151                 new_fl |= S_APPEND;
152         if (binode->flags & BTRFS_INODE_NOATIME)
153                 new_fl |= S_NOATIME;
154         if (binode->flags & BTRFS_INODE_DIRSYNC)
155                 new_fl |= S_DIRSYNC;
156 
157         set_mask_bits(&inode->i_flags,
158                       S_SYNC | S_APPEND | S_IMMUTABLE | S_NOATIME | S_DIRSYNC,
159                       new_fl);
160 }
161 
162 static int btrfs_ioctl_getflags(struct file *file, void __user *arg)
163 {
164         struct btrfs_inode *binode = BTRFS_I(file_inode(file));
165         unsigned int flags = btrfs_inode_flags_to_fsflags(binode->flags);
166 
167         if (copy_to_user(arg, &flags, sizeof(flags)))
168                 return -EFAULT;
169         return 0;
170 }
171 
172 /* Check if @flags are a supported and valid set of FS_*_FL flags */
173 static int check_fsflags(unsigned int flags)
174 {
175         if (flags & ~(FS_IMMUTABLE_FL | FS_APPEND_FL | \
176                       FS_NOATIME_FL | FS_NODUMP_FL | \
177                       FS_SYNC_FL | FS_DIRSYNC_FL | \
178                       FS_NOCOMP_FL | FS_COMPR_FL |
179                       FS_NOCOW_FL))
180                 return -EOPNOTSUPP;
181 
182         if ((flags & FS_NOCOMP_FL) && (flags & FS_COMPR_FL))
183                 return -EINVAL;
184 
185         return 0;
186 }
187 
188 static int btrfs_ioctl_setflags(struct file *file, void __user *arg)
189 {
190         struct inode *inode = file_inode(file);
191         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
192         struct btrfs_inode *binode = BTRFS_I(inode);
193         struct btrfs_root *root = binode->root;
194         struct btrfs_trans_handle *trans;
195         unsigned int fsflags, old_fsflags;
196         int ret;
197         u64 old_flags;
198         unsigned int old_i_flags;
199         umode_t mode;
200 
201         if (!inode_owner_or_capable(inode))
202                 return -EPERM;
203 
204         if (btrfs_root_readonly(root))
205                 return -EROFS;
206 
207         if (copy_from_user(&fsflags, arg, sizeof(fsflags)))
208                 return -EFAULT;
209 
210         ret = check_fsflags(fsflags);
211         if (ret)
212                 return ret;
213 
214         ret = mnt_want_write_file(file);
215         if (ret)
216                 return ret;
217 
218         inode_lock(inode);
219 
220         old_flags = binode->flags;
221         old_i_flags = inode->i_flags;
222         mode = inode->i_mode;
223 
224         fsflags = btrfs_mask_fsflags_for_type(inode, fsflags);
225         old_fsflags = btrfs_inode_flags_to_fsflags(binode->flags);
226         if ((fsflags ^ old_fsflags) & (FS_APPEND_FL | FS_IMMUTABLE_FL)) {
227                 if (!capable(CAP_LINUX_IMMUTABLE)) {
228                         ret = -EPERM;
229                         goto out_unlock;
230                 }
231         }
232 
233         if (fsflags & FS_SYNC_FL)
234                 binode->flags |= BTRFS_INODE_SYNC;
235         else
236                 binode->flags &= ~BTRFS_INODE_SYNC;
237         if (fsflags & FS_IMMUTABLE_FL)
238                 binode->flags |= BTRFS_INODE_IMMUTABLE;
239         else
240                 binode->flags &= ~BTRFS_INODE_IMMUTABLE;
241         if (fsflags & FS_APPEND_FL)
242                 binode->flags |= BTRFS_INODE_APPEND;
243         else
244                 binode->flags &= ~BTRFS_INODE_APPEND;
245         if (fsflags & FS_NODUMP_FL)
246                 binode->flags |= BTRFS_INODE_NODUMP;
247         else
248                 binode->flags &= ~BTRFS_INODE_NODUMP;
249         if (fsflags & FS_NOATIME_FL)
250                 binode->flags |= BTRFS_INODE_NOATIME;
251         else
252                 binode->flags &= ~BTRFS_INODE_NOATIME;
253         if (fsflags & FS_DIRSYNC_FL)
254                 binode->flags |= BTRFS_INODE_DIRSYNC;
255         else
256                 binode->flags &= ~BTRFS_INODE_DIRSYNC;
257         if (fsflags & FS_NOCOW_FL) {
258                 if (S_ISREG(mode)) {
259                         /*
260                          * It's safe to turn csums off here, no extents exist.
261                          * Otherwise we want the flag to reflect the real COW
262                          * status of the file and will not set it.
263                          */
264                         if (inode->i_size == 0)
265                                 binode->flags |= BTRFS_INODE_NODATACOW
266                                               | BTRFS_INODE_NODATASUM;
267                 } else {
268                         binode->flags |= BTRFS_INODE_NODATACOW;
269                 }
270         } else {
271                 /*
272                  * Revert back under same assumptions as above
273                  */
274                 if (S_ISREG(mode)) {
275                         if (inode->i_size == 0)
276                                 binode->flags &= ~(BTRFS_INODE_NODATACOW
277                                              | BTRFS_INODE_NODATASUM);
278                 } else {
279                         binode->flags &= ~BTRFS_INODE_NODATACOW;
280                 }
281         }
282 
283         /*
284          * The COMPRESS flag can only be changed by users, while the NOCOMPRESS
285          * flag may be changed automatically if compression code won't make
286          * things smaller.
287          */
288         if (fsflags & FS_NOCOMP_FL) {
289                 binode->flags &= ~BTRFS_INODE_COMPRESS;
290                 binode->flags |= BTRFS_INODE_NOCOMPRESS;
291 
292                 ret = btrfs_set_prop(inode, "btrfs.compression", NULL, 0, 0);
293                 if (ret && ret != -ENODATA)
294                         goto out_drop;
295         } else if (fsflags & FS_COMPR_FL) {
296                 const char *comp;
297 
298                 binode->flags |= BTRFS_INODE_COMPRESS;
299                 binode->flags &= ~BTRFS_INODE_NOCOMPRESS;
300 
301                 comp = btrfs_compress_type2str(fs_info->compress_type);
302                 if (!comp || comp[0] == 0)
303                         comp = btrfs_compress_type2str(BTRFS_COMPRESS_ZLIB);
304 
305                 ret = btrfs_set_prop(inode, "btrfs.compression",
306                                      comp, strlen(comp), 0);
307                 if (ret)
308                         goto out_drop;
309 
310         } else {
311                 ret = btrfs_set_prop(inode, "btrfs.compression", NULL, 0, 0);
312                 if (ret && ret != -ENODATA)
313                         goto out_drop;
314                 binode->flags &= ~(BTRFS_INODE_COMPRESS | BTRFS_INODE_NOCOMPRESS);
315         }
316 
317         trans = btrfs_start_transaction(root, 1);
318         if (IS_ERR(trans)) {
319                 ret = PTR_ERR(trans);
320                 goto out_drop;
321         }
322 
323         btrfs_sync_inode_flags_to_i_flags(inode);
324         inode_inc_iversion(inode);
325         inode->i_ctime = current_time(inode);
326         ret = btrfs_update_inode(trans, root, inode);
327 
328         btrfs_end_transaction(trans);
329  out_drop:
330         if (ret) {
331                 binode->flags = old_flags;
332                 inode->i_flags = old_i_flags;
333         }
334 
335  out_unlock:
336         inode_unlock(inode);
337         mnt_drop_write_file(file);
338         return ret;
339 }
340 
341 /*
342  * Translate btrfs internal inode flags to xflags as expected by the
343  * FS_IOC_FSGETXATT ioctl. Filter only the supported ones, unknown flags are
344  * silently dropped.
345  */
346 static unsigned int btrfs_inode_flags_to_xflags(unsigned int flags)
347 {
348         unsigned int xflags = 0;
349 
350         if (flags & BTRFS_INODE_APPEND)
351                 xflags |= FS_XFLAG_APPEND;
352         if (flags & BTRFS_INODE_IMMUTABLE)
353                 xflags |= FS_XFLAG_IMMUTABLE;
354         if (flags & BTRFS_INODE_NOATIME)
355                 xflags |= FS_XFLAG_NOATIME;
356         if (flags & BTRFS_INODE_NODUMP)
357                 xflags |= FS_XFLAG_NODUMP;
358         if (flags & BTRFS_INODE_SYNC)
359                 xflags |= FS_XFLAG_SYNC;
360 
361         return xflags;
362 }
363 
364 /* Check if @flags are a supported and valid set of FS_XFLAGS_* flags */
365 static int check_xflags(unsigned int flags)
366 {
367         if (flags & ~(FS_XFLAG_APPEND | FS_XFLAG_IMMUTABLE | FS_XFLAG_NOATIME |
368                       FS_XFLAG_NODUMP | FS_XFLAG_SYNC))
369                 return -EOPNOTSUPP;
370         return 0;
371 }
372 
373 /*
374  * Set the xflags from the internal inode flags. The remaining items of fsxattr
375  * are zeroed.
376  */
377 static int btrfs_ioctl_fsgetxattr(struct file *file, void __user *arg)
378 {
379         struct btrfs_inode *binode = BTRFS_I(file_inode(file));
380         struct fsxattr fa;
381 
382         memset(&fa, 0, sizeof(fa));
383         fa.fsx_xflags = btrfs_inode_flags_to_xflags(binode->flags);
384 
385         if (copy_to_user(arg, &fa, sizeof(fa)))
386                 return -EFAULT;
387 
388         return 0;
389 }
390 
391 static int btrfs_ioctl_fssetxattr(struct file *file, void __user *arg)
392 {
393         struct inode *inode = file_inode(file);
394         struct btrfs_inode *binode = BTRFS_I(inode);
395         struct btrfs_root *root = binode->root;
396         struct btrfs_trans_handle *trans;
397         struct fsxattr fa;
398         unsigned old_flags;
399         unsigned old_i_flags;
400         int ret = 0;
401 
402         if (!inode_owner_or_capable(inode))
403                 return -EPERM;
404 
405         if (btrfs_root_readonly(root))
406                 return -EROFS;
407 
408         memset(&fa, 0, sizeof(fa));
409         if (copy_from_user(&fa, arg, sizeof(fa)))
410                 return -EFAULT;
411 
412         ret = check_xflags(fa.fsx_xflags);
413         if (ret)
414                 return ret;
415 
416         if (fa.fsx_extsize != 0 || fa.fsx_projid != 0 || fa.fsx_cowextsize != 0)
417                 return -EOPNOTSUPP;
418 
419         ret = mnt_want_write_file(file);
420         if (ret)
421                 return ret;
422 
423         inode_lock(inode);
424 
425         old_flags = binode->flags;
426         old_i_flags = inode->i_flags;
427 
428         /* We need the capabilities to change append-only or immutable inode */
429         if (((old_flags & (BTRFS_INODE_APPEND | BTRFS_INODE_IMMUTABLE)) ||
430              (fa.fsx_xflags & (FS_XFLAG_APPEND | FS_XFLAG_IMMUTABLE))) &&
431             !capable(CAP_LINUX_IMMUTABLE)) {
432                 ret = -EPERM;
433                 goto out_unlock;
434         }
435 
436         if (fa.fsx_xflags & FS_XFLAG_SYNC)
437                 binode->flags |= BTRFS_INODE_SYNC;
438         else
439                 binode->flags &= ~BTRFS_INODE_SYNC;
440         if (fa.fsx_xflags & FS_XFLAG_IMMUTABLE)
441                 binode->flags |= BTRFS_INODE_IMMUTABLE;
442         else
443                 binode->flags &= ~BTRFS_INODE_IMMUTABLE;
444         if (fa.fsx_xflags & FS_XFLAG_APPEND)
445                 binode->flags |= BTRFS_INODE_APPEND;
446         else
447                 binode->flags &= ~BTRFS_INODE_APPEND;
448         if (fa.fsx_xflags & FS_XFLAG_NODUMP)
449                 binode->flags |= BTRFS_INODE_NODUMP;
450         else
451                 binode->flags &= ~BTRFS_INODE_NODUMP;
452         if (fa.fsx_xflags & FS_XFLAG_NOATIME)
453                 binode->flags |= BTRFS_INODE_NOATIME;
454         else
455                 binode->flags &= ~BTRFS_INODE_NOATIME;
456 
457         /* 1 item for the inode */
458         trans = btrfs_start_transaction(root, 1);
459         if (IS_ERR(trans)) {
460                 ret = PTR_ERR(trans);
461                 goto out_unlock;
462         }
463 
464         btrfs_sync_inode_flags_to_i_flags(inode);
465         inode_inc_iversion(inode);
466         inode->i_ctime = current_time(inode);
467         ret = btrfs_update_inode(trans, root, inode);
468 
469         btrfs_end_transaction(trans);
470 
471 out_unlock:
472         if (ret) {
473                 binode->flags = old_flags;
474                 inode->i_flags = old_i_flags;
475         }
476 
477         inode_unlock(inode);
478         mnt_drop_write_file(file);
479 
480         return ret;
481 }
482 
483 static int btrfs_ioctl_getversion(struct file *file, int __user *arg)
484 {
485         struct inode *inode = file_inode(file);
486 
487         return put_user(inode->i_generation, arg);
488 }
489 
490 static noinline int btrfs_ioctl_fitrim(struct file *file, void __user *arg)
491 {
492         struct inode *inode = file_inode(file);
493         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
494         struct btrfs_device *device;
495         struct request_queue *q;
496         struct fstrim_range range;
497         u64 minlen = ULLONG_MAX;
498         u64 num_devices = 0;
499         int ret;
500 
501         if (!capable(CAP_SYS_ADMIN))
502                 return -EPERM;
503 
504         rcu_read_lock();
505         list_for_each_entry_rcu(device, &fs_info->fs_devices->devices,
506                                 dev_list) {
507                 if (!device->bdev)
508                         continue;
509                 q = bdev_get_queue(device->bdev);
510                 if (blk_queue_discard(q)) {
511                         num_devices++;
512                         minlen = min_t(u64, q->limits.discard_granularity,
513                                      minlen);
514                 }
515         }
516         rcu_read_unlock();
517 
518         if (!num_devices)
519                 return -EOPNOTSUPP;
520         if (copy_from_user(&range, arg, sizeof(range)))
521                 return -EFAULT;
522 
523         /*
524          * NOTE: Don't truncate the range using super->total_bytes.  Bytenr of
525          * block group is in the logical address space, which can be any
526          * sectorsize aligned bytenr in  the range [0, U64_MAX].
527          */
528         if (range.len < fs_info->sb->s_blocksize)
529                 return -EINVAL;
530 
531         range.minlen = max(range.minlen, minlen);
532         ret = btrfs_trim_fs(fs_info, &range);
533         if (ret < 0)
534                 return ret;
535 
536         if (copy_to_user(arg, &range, sizeof(range)))
537                 return -EFAULT;
538 
539         return 0;
540 }
541 
542 int btrfs_is_empty_uuid(u8 *uuid)
543 {
544         int i;
545 
546         for (i = 0; i < BTRFS_UUID_SIZE; i++) {
547                 if (uuid[i])
548                         return 0;
549         }
550         return 1;
551 }
552 
553 static noinline int create_subvol(struct inode *dir,
554                                   struct dentry *dentry,
555                                   const char *name, int namelen,
556                                   u64 *async_transid,
557                                   struct btrfs_qgroup_inherit *inherit)
558 {
559         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
560         struct btrfs_trans_handle *trans;
561         struct btrfs_key key;
562         struct btrfs_root_item *root_item;
563         struct btrfs_inode_item *inode_item;
564         struct extent_buffer *leaf;
565         struct btrfs_root *root = BTRFS_I(dir)->root;
566         struct btrfs_root *new_root;
567         struct btrfs_block_rsv block_rsv;
568         struct timespec64 cur_time = current_time(dir);
569         struct inode *inode;
570         int ret;
571         int err;
572         u64 objectid;
573         u64 new_dirid = BTRFS_FIRST_FREE_OBJECTID;
574         u64 index = 0;
575         uuid_le new_uuid;
576 
577         root_item = kzalloc(sizeof(*root_item), GFP_KERNEL);
578         if (!root_item)
579                 return -ENOMEM;
580 
581         ret = btrfs_find_free_objectid(fs_info->tree_root, &objectid);
582         if (ret)
583                 goto fail_free;
584 
585         /*
586          * Don't create subvolume whose level is not zero. Or qgroup will be
587          * screwed up since it assumes subvolume qgroup's level to be 0.
588          */
589         if (btrfs_qgroup_level(objectid)) {
590                 ret = -ENOSPC;
591                 goto fail_free;
592         }
593 
594         btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
595         /*
596          * The same as the snapshot creation, please see the comment
597          * of create_snapshot().
598          */
599         ret = btrfs_subvolume_reserve_metadata(root, &block_rsv, 8, false);
600         if (ret)
601                 goto fail_free;
602 
603         trans = btrfs_start_transaction(root, 0);
604         if (IS_ERR(trans)) {
605                 ret = PTR_ERR(trans);
606                 btrfs_subvolume_release_metadata(fs_info, &block_rsv);
607                 goto fail_free;
608         }
609         trans->block_rsv = &block_rsv;
610         trans->bytes_reserved = block_rsv.size;
611 
612         ret = btrfs_qgroup_inherit(trans, fs_info, 0, objectid, inherit);
613         if (ret)
614                 goto fail;
615 
616         leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0);
617         if (IS_ERR(leaf)) {
618                 ret = PTR_ERR(leaf);
619                 goto fail;
620         }
621 
622         memzero_extent_buffer(leaf, 0, sizeof(struct btrfs_header));
623         btrfs_set_header_bytenr(leaf, leaf->start);
624         btrfs_set_header_generation(leaf, trans->transid);
625         btrfs_set_header_backref_rev(leaf, BTRFS_MIXED_BACKREF_REV);
626         btrfs_set_header_owner(leaf, objectid);
627 
628         write_extent_buffer_fsid(leaf, fs_info->fsid);
629         write_extent_buffer_chunk_tree_uuid(leaf, fs_info->chunk_tree_uuid);
630         btrfs_mark_buffer_dirty(leaf);
631 
632         inode_item = &root_item->inode;
633         btrfs_set_stack_inode_generation(inode_item, 1);
634         btrfs_set_stack_inode_size(inode_item, 3);
635         btrfs_set_stack_inode_nlink(inode_item, 1);
636         btrfs_set_stack_inode_nbytes(inode_item,
637                                      fs_info->nodesize);
638         btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
639 
640         btrfs_set_root_flags(root_item, 0);
641         btrfs_set_root_limit(root_item, 0);
642         btrfs_set_stack_inode_flags(inode_item, BTRFS_INODE_ROOT_ITEM_INIT);
643 
644         btrfs_set_root_bytenr(root_item, leaf->start);
645         btrfs_set_root_generation(root_item, trans->transid);
646         btrfs_set_root_level(root_item, 0);
647         btrfs_set_root_refs(root_item, 1);
648         btrfs_set_root_used(root_item, leaf->len);
649         btrfs_set_root_last_snapshot(root_item, 0);
650 
651         btrfs_set_root_generation_v2(root_item,
652                         btrfs_root_generation(root_item));
653         uuid_le_gen(&new_uuid);
654         memcpy(root_item->uuid, new_uuid.b, BTRFS_UUID_SIZE);
655         btrfs_set_stack_timespec_sec(&root_item->otime, cur_time.tv_sec);
656         btrfs_set_stack_timespec_nsec(&root_item->otime, cur_time.tv_nsec);
657         root_item->ctime = root_item->otime;
658         btrfs_set_root_ctransid(root_item, trans->transid);
659         btrfs_set_root_otransid(root_item, trans->transid);
660 
661         btrfs_tree_unlock(leaf);
662         free_extent_buffer(leaf);
663         leaf = NULL;
664 
665         btrfs_set_root_dirid(root_item, new_dirid);
666 
667         key.objectid = objectid;
668         key.offset = 0;
669         key.type = BTRFS_ROOT_ITEM_KEY;
670         ret = btrfs_insert_root(trans, fs_info->tree_root, &key,
671                                 root_item);
672         if (ret)
673                 goto fail;
674 
675         key.offset = (u64)-1;
676         new_root = btrfs_read_fs_root_no_name(fs_info, &key);
677         if (IS_ERR(new_root)) {
678                 ret = PTR_ERR(new_root);
679                 btrfs_abort_transaction(trans, ret);
680                 goto fail;
681         }
682 
683         btrfs_record_root_in_trans(trans, new_root);
684 
685         ret = btrfs_create_subvol_root(trans, new_root, root, new_dirid);
686         if (ret) {
687                 /* We potentially lose an unused inode item here */
688                 btrfs_abort_transaction(trans, ret);
689                 goto fail;
690         }
691 
692         mutex_lock(&new_root->objectid_mutex);
693         new_root->highest_objectid = new_dirid;
694         mutex_unlock(&new_root->objectid_mutex);
695 
696         /*
697          * insert the directory item
698          */
699         ret = btrfs_set_inode_index(BTRFS_I(dir), &index);
700         if (ret) {
701                 btrfs_abort_transaction(trans, ret);
702                 goto fail;
703         }
704 
705         ret = btrfs_insert_dir_item(trans, root,
706                                     name, namelen, BTRFS_I(dir), &key,
707                                     BTRFS_FT_DIR, index);
708         if (ret) {
709                 btrfs_abort_transaction(trans, ret);
710                 goto fail;
711         }
712 
713         btrfs_i_size_write(BTRFS_I(dir), dir->i_size + namelen * 2);
714         ret = btrfs_update_inode(trans, root, dir);
715         BUG_ON(ret);
716 
717         ret = btrfs_add_root_ref(trans, fs_info,
718                                  objectid, root->root_key.objectid,
719                                  btrfs_ino(BTRFS_I(dir)), index, name, namelen);
720         BUG_ON(ret);
721 
722         ret = btrfs_uuid_tree_add(trans, root_item->uuid,
723                                   BTRFS_UUID_KEY_SUBVOL, objectid);
724         if (ret)
725                 btrfs_abort_transaction(trans, ret);
726 
727 fail:
728         kfree(root_item);
729         trans->block_rsv = NULL;
730         trans->bytes_reserved = 0;
731         btrfs_subvolume_release_metadata(fs_info, &block_rsv);
732 
733         if (async_transid) {
734                 *async_transid = trans->transid;
735                 err = btrfs_commit_transaction_async(trans, 1);
736                 if (err)
737                         err = btrfs_commit_transaction(trans);
738         } else {
739                 err = btrfs_commit_transaction(trans);
740         }
741         if (err && !ret)
742                 ret = err;
743 
744         if (!ret) {
745                 inode = btrfs_lookup_dentry(dir, dentry);
746                 if (IS_ERR(inode))
747                         return PTR_ERR(inode);
748                 d_instantiate(dentry, inode);
749         }
750         return ret;
751 
752 fail_free:
753         kfree(root_item);
754         return ret;
755 }
756 
757 static int create_snapshot(struct btrfs_root *root, struct inode *dir,
758                            struct dentry *dentry,
759                            u64 *async_transid, bool readonly,
760                            struct btrfs_qgroup_inherit *inherit)
761 {
762         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
763         struct inode *inode;
764         struct btrfs_pending_snapshot *pending_snapshot;
765         struct btrfs_trans_handle *trans;
766         int ret;
767         bool snapshot_force_cow = false;
768 
769         if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state))
770                 return -EINVAL;
771 
772         pending_snapshot = kzalloc(sizeof(*pending_snapshot), GFP_KERNEL);
773         if (!pending_snapshot)
774                 return -ENOMEM;
775 
776         pending_snapshot->root_item = kzalloc(sizeof(struct btrfs_root_item),
777                         GFP_KERNEL);
778         pending_snapshot->path = btrfs_alloc_path();
779         if (!pending_snapshot->root_item || !pending_snapshot->path) {
780                 ret = -ENOMEM;
781                 goto free_pending;
782         }
783 
784         /*
785          * Force new buffered writes to reserve space even when NOCOW is
786          * possible. This is to avoid later writeback (running dealloc) to
787          * fallback to COW mode and unexpectedly fail with ENOSPC.
788          */
789         atomic_inc(&root->will_be_snapshotted);
790         smp_mb__after_atomic();
791         /* wait for no snapshot writes */
792         wait_event(root->subv_writers->wait,
793                    percpu_counter_sum(&root->subv_writers->counter) == 0);
794 
795         ret = btrfs_start_delalloc_inodes(root);
796         if (ret)
797                 goto dec_and_free;
798 
799         /*
800          * All previous writes have started writeback in NOCOW mode, so now
801          * we force future writes to fallback to COW mode during snapshot
802          * creation.
803          */
804         atomic_inc(&root->snapshot_force_cow);
805         snapshot_force_cow = true;
806 
807         btrfs_wait_ordered_extents(root, U64_MAX, 0, (u64)-1);
808 
809         btrfs_init_block_rsv(&pending_snapshot->block_rsv,
810                              BTRFS_BLOCK_RSV_TEMP);
811         /*
812          * 1 - parent dir inode
813          * 2 - dir entries
814          * 1 - root item
815          * 2 - root ref/backref
816          * 1 - root of snapshot
817          * 1 - UUID item
818          */
819         ret = btrfs_subvolume_reserve_metadata(BTRFS_I(dir)->root,
820                                         &pending_snapshot->block_rsv, 8,
821                                         false);
822         if (ret)
823                 goto dec_and_free;
824 
825         pending_snapshot->dentry = dentry;
826         pending_snapshot->root = root;
827         pending_snapshot->readonly = readonly;
828         pending_snapshot->dir = dir;
829         pending_snapshot->inherit = inherit;
830 
831         trans = btrfs_start_transaction(root, 0);
832         if (IS_ERR(trans)) {
833                 ret = PTR_ERR(trans);
834                 goto fail;
835         }
836 
837         spin_lock(&fs_info->trans_lock);
838         list_add(&pending_snapshot->list,
839                  &trans->transaction->pending_snapshots);
840         spin_unlock(&fs_info->trans_lock);
841         if (async_transid) {
842                 *async_transid = trans->transid;
843                 ret = btrfs_commit_transaction_async(trans, 1);
844                 if (ret)
845                         ret = btrfs_commit_transaction(trans);
846         } else {
847                 ret = btrfs_commit_transaction(trans);
848         }
849         if (ret)
850                 goto fail;
851 
852         ret = pending_snapshot->error;
853         if (ret)
854                 goto fail;
855 
856         ret = btrfs_orphan_cleanup(pending_snapshot->snap);
857         if (ret)
858                 goto fail;
859 
860         inode = btrfs_lookup_dentry(d_inode(dentry->d_parent), dentry);
861         if (IS_ERR(inode)) {
862                 ret = PTR_ERR(inode);
863                 goto fail;
864         }
865 
866         d_instantiate(dentry, inode);
867         ret = 0;
868 fail:
869         btrfs_subvolume_release_metadata(fs_info, &pending_snapshot->block_rsv);
870 dec_and_free:
871         if (snapshot_force_cow)
872                 atomic_dec(&root->snapshot_force_cow);
873         if (atomic_dec_and_test(&root->will_be_snapshotted))
874                 wake_up_var(&root->will_be_snapshotted);
875 free_pending:
876         kfree(pending_snapshot->root_item);
877         btrfs_free_path(pending_snapshot->path);
878         kfree(pending_snapshot);
879 
880         return ret;
881 }
882 
883 /*  copy of may_delete in fs/namei.c()
884  *      Check whether we can remove a link victim from directory dir, check
885  *  whether the type of victim is right.
886  *  1. We can't do it if dir is read-only (done in permission())
887  *  2. We should have write and exec permissions on dir
888  *  3. We can't remove anything from append-only dir
889  *  4. We can't do anything with immutable dir (done in permission())
890  *  5. If the sticky bit on dir is set we should either
891  *      a. be owner of dir, or
892  *      b. be owner of victim, or
893  *      c. have CAP_FOWNER capability
894  *  6. If the victim is append-only or immutable we can't do anything with
895  *     links pointing to it.
896  *  7. If we were asked to remove a directory and victim isn't one - ENOTDIR.
897  *  8. If we were asked to remove a non-directory and victim isn't one - EISDIR.
898  *  9. We can't remove a root or mountpoint.
899  * 10. We don't allow removal of NFS sillyrenamed files; it's handled by
900  *     nfs_async_unlink().
901  */
902 
903 static int btrfs_may_delete(struct inode *dir, struct dentry *victim, int isdir)
904 {
905         int error;
906 
907         if (d_really_is_negative(victim))
908                 return -ENOENT;
909 
910         BUG_ON(d_inode(victim->d_parent) != dir);
911         audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE);
912 
913         error = inode_permission(dir, MAY_WRITE | MAY_EXEC);
914         if (error)
915                 return error;
916         if (IS_APPEND(dir))
917                 return -EPERM;
918         if (check_sticky(dir, d_inode(victim)) || IS_APPEND(d_inode(victim)) ||
919             IS_IMMUTABLE(d_inode(victim)) || IS_SWAPFILE(d_inode(victim)))
920                 return -EPERM;
921         if (isdir) {
922                 if (!d_is_dir(victim))
923                         return -ENOTDIR;
924                 if (IS_ROOT(victim))
925                         return -EBUSY;
926         } else if (d_is_dir(victim))
927                 return -EISDIR;
928         if (IS_DEADDIR(dir))
929                 return -ENOENT;
930         if (victim->d_flags & DCACHE_NFSFS_RENAMED)
931                 return -EBUSY;
932         return 0;
933 }
934 
935 /* copy of may_create in fs/namei.c() */
936 static inline int btrfs_may_create(struct inode *dir, struct dentry *child)
937 {
938         if (d_really_is_positive(child))
939                 return -EEXIST;
940         if (IS_DEADDIR(dir))
941                 return -ENOENT;
942         return inode_permission(dir, MAY_WRITE | MAY_EXEC);
943 }
944 
945 /*
946  * Create a new subvolume below @parent.  This is largely modeled after
947  * sys_mkdirat and vfs_mkdir, but we only do a single component lookup
948  * inside this filesystem so it's quite a bit simpler.
949  */
950 static noinline int btrfs_mksubvol(const struct path *parent,
951                                    const char *name, int namelen,
952                                    struct btrfs_root *snap_src,
953                                    u64 *async_transid, bool readonly,
954                                    struct btrfs_qgroup_inherit *inherit)
955 {
956         struct inode *dir = d_inode(parent->dentry);
957         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
958         struct dentry *dentry;
959         int error;
960 
961         error = down_write_killable_nested(&dir->i_rwsem, I_MUTEX_PARENT);
962         if (error == -EINTR)
963                 return error;
964 
965         dentry = lookup_one_len(name, parent->dentry, namelen);
966         error = PTR_ERR(dentry);
967         if (IS_ERR(dentry))
968                 goto out_unlock;
969 
970         error = btrfs_may_create(dir, dentry);
971         if (error)
972                 goto out_dput;
973 
974         /*
975          * even if this name doesn't exist, we may get hash collisions.
976          * check for them now when we can safely fail
977          */
978         error = btrfs_check_dir_item_collision(BTRFS_I(dir)->root,
979                                                dir->i_ino, name,
980                                                namelen);
981         if (error)
982                 goto out_dput;
983 
984         down_read(&fs_info->subvol_sem);
985 
986         if (btrfs_root_refs(&BTRFS_I(dir)->root->root_item) == 0)
987                 goto out_up_read;
988 
989         if (snap_src) {
990                 error = create_snapshot(snap_src, dir, dentry,
991                                         async_transid, readonly, inherit);
992         } else {
993                 error = create_subvol(dir, dentry, name, namelen,
994                                       async_transid, inherit);
995         }
996         if (!error)
997                 fsnotify_mkdir(dir, dentry);
998 out_up_read:
999         up_read(&fs_info->subvol_sem);
1000 out_dput:
1001         dput(dentry);
1002 out_unlock:
1003         inode_unlock(dir);
1004         return error;
1005 }
1006 
1007 /*
1008  * When we're defragging a range, we don't want to kick it off again
1009  * if it is really just waiting for delalloc to send it down.
1010  * If we find a nice big extent or delalloc range for the bytes in the
1011  * file you want to defrag, we return 0 to let you know to skip this
1012  * part of the file
1013  */
1014 static int check_defrag_in_cache(struct inode *inode, u64 offset, u32 thresh)
1015 {
1016         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1017         struct extent_map *em = NULL;
1018         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
1019         u64 end;
1020 
1021         read_lock(&em_tree->lock);
1022         em = lookup_extent_mapping(em_tree, offset, PAGE_SIZE);
1023         read_unlock(&em_tree->lock);
1024 
1025         if (em) {
1026                 end = extent_map_end(em);
1027                 free_extent_map(em);
1028                 if (end - offset > thresh)
1029                         return 0;
1030         }
1031         /* if we already have a nice delalloc here, just stop */
1032         thresh /= 2;
1033         end = count_range_bits(io_tree, &offset, offset + thresh,
1034                                thresh, EXTENT_DELALLOC, 1);
1035         if (end >= thresh)
1036                 return 0;
1037         return 1;
1038 }
1039 
1040 /*
1041  * helper function to walk through a file and find extents
1042  * newer than a specific transid, and smaller than thresh.
1043  *
1044  * This is used by the defragging code to find new and small
1045  * extents
1046  */
1047 static int find_new_extents(struct btrfs_root *root,
1048                             struct inode *inode, u64 newer_than,
1049                             u64 *off, u32 thresh)
1050 {
1051         struct btrfs_path *path;
1052         struct btrfs_key min_key;
1053         struct extent_buffer *leaf;
1054         struct btrfs_file_extent_item *extent;
1055         int type;
1056         int ret;
1057         u64 ino = btrfs_ino(BTRFS_I(inode));
1058 
1059         path = btrfs_alloc_path();
1060         if (!path)
1061                 return -ENOMEM;
1062 
1063         min_key.objectid = ino;
1064         min_key.type = BTRFS_EXTENT_DATA_KEY;
1065         min_key.offset = *off;
1066 
1067         while (1) {
1068                 ret = btrfs_search_forward(root, &min_key, path, newer_than);
1069                 if (ret != 0)
1070                         goto none;
1071 process_slot:
1072                 if (min_key.objectid != ino)
1073                         goto none;
1074                 if (min_key.type != BTRFS_EXTENT_DATA_KEY)
1075                         goto none;
1076 
1077                 leaf = path->nodes[0];
1078                 extent = btrfs_item_ptr(leaf, path->slots[0],
1079                                         struct btrfs_file_extent_item);
1080 
1081                 type = btrfs_file_extent_type(leaf, extent);
1082                 if (type == BTRFS_FILE_EXTENT_REG &&
1083                     btrfs_file_extent_num_bytes(leaf, extent) < thresh &&
1084                     check_defrag_in_cache(inode, min_key.offset, thresh)) {
1085                         *off = min_key.offset;
1086                         btrfs_free_path(path);
1087                         return 0;
1088                 }
1089 
1090                 path->slots[0]++;
1091                 if (path->slots[0] < btrfs_header_nritems(leaf)) {
1092                         btrfs_item_key_to_cpu(leaf, &min_key, path->slots[0]);
1093                         goto process_slot;
1094                 }
1095 
1096                 if (min_key.offset == (u64)-1)
1097                         goto none;
1098 
1099                 min_key.offset++;
1100                 btrfs_release_path(path);
1101         }
1102 none:
1103         btrfs_free_path(path);
1104         return -ENOENT;
1105 }
1106 
1107 static struct extent_map *defrag_lookup_extent(struct inode *inode, u64 start)
1108 {
1109         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
1110         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1111         struct extent_map *em;
1112         u64 len = PAGE_SIZE;
1113 
1114         /*
1115          * hopefully we have this extent in the tree already, try without
1116          * the full extent lock
1117          */
1118         read_lock(&em_tree->lock);
1119         em = lookup_extent_mapping(em_tree, start, len);
1120         read_unlock(&em_tree->lock);
1121 
1122         if (!em) {
1123                 struct extent_state *cached = NULL;
1124                 u64 end = start + len - 1;
1125 
1126                 /* get the big lock and read metadata off disk */
1127                 lock_extent_bits(io_tree, start, end, &cached);
1128                 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
1129                 unlock_extent_cached(io_tree, start, end, &cached);
1130 
1131                 if (IS_ERR(em))
1132                         return NULL;
1133         }
1134 
1135         return em;
1136 }
1137 
1138 static bool defrag_check_next_extent(struct inode *inode, struct extent_map *em)
1139 {
1140         struct extent_map *next;
1141         bool ret = true;
1142 
1143         /* this is the last extent */
1144         if (em->start + em->len >= i_size_read(inode))
1145                 return false;
1146 
1147         next = defrag_lookup_extent(inode, em->start + em->len);
1148         if (!next || next->block_start >= EXTENT_MAP_LAST_BYTE)
1149                 ret = false;
1150         else if ((em->block_start + em->block_len == next->block_start) &&
1151                  (em->block_len > SZ_128K && next->block_len > SZ_128K))
1152                 ret = false;
1153 
1154         free_extent_map(next);
1155         return ret;
1156 }
1157 
1158 static int should_defrag_range(struct inode *inode, u64 start, u32 thresh,
1159                                u64 *last_len, u64 *skip, u64 *defrag_end,
1160                                int compress)
1161 {
1162         struct extent_map *em;
1163         int ret = 1;
1164         bool next_mergeable = true;
1165         bool prev_mergeable = true;
1166 
1167         /*
1168          * make sure that once we start defragging an extent, we keep on
1169          * defragging it
1170          */
1171         if (start < *defrag_end)
1172                 return 1;
1173 
1174         *skip = 0;
1175 
1176         em = defrag_lookup_extent(inode, start);
1177         if (!em)
1178                 return 0;
1179 
1180         /* this will cover holes, and inline extents */
1181         if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
1182                 ret = 0;
1183                 goto out;
1184         }
1185 
1186         if (!*defrag_end)
1187                 prev_mergeable = false;
1188 
1189         next_mergeable = defrag_check_next_extent(inode, em);
1190         /*
1191          * we hit a real extent, if it is big or the next extent is not a
1192          * real extent, don't bother defragging it
1193          */
1194         if (!compress && (*last_len == 0 || *last_len >= thresh) &&
1195             (em->len >= thresh || (!next_mergeable && !prev_mergeable)))
1196                 ret = 0;
1197 out:
1198         /*
1199          * last_len ends up being a counter of how many bytes we've defragged.
1200          * every time we choose not to defrag an extent, we reset *last_len
1201          * so that the next tiny extent will force a defrag.
1202          *
1203          * The end result of this is that tiny extents before a single big
1204          * extent will force at least part of that big extent to be defragged.
1205          */
1206         if (ret) {
1207                 *defrag_end = extent_map_end(em);
1208         } else {
1209                 *last_len = 0;
1210                 *skip = extent_map_end(em);
1211                 *defrag_end = 0;
1212         }
1213 
1214         free_extent_map(em);
1215         return ret;
1216 }
1217 
1218 /*
1219  * it doesn't do much good to defrag one or two pages
1220  * at a time.  This pulls in a nice chunk of pages
1221  * to COW and defrag.
1222  *
1223  * It also makes sure the delalloc code has enough
1224  * dirty data to avoid making new small extents as part
1225  * of the defrag
1226  *
1227  * It's a good idea to start RA on this range
1228  * before calling this.
1229  */
1230 static int cluster_pages_for_defrag(struct inode *inode,
1231                                     struct page **pages,
1232                                     unsigned long start_index,
1233                                     unsigned long num_pages)
1234 {
1235         unsigned long file_end;
1236         u64 isize = i_size_read(inode);
1237         u64 page_start;
1238         u64 page_end;
1239         u64 page_cnt;
1240         int ret;
1241         int i;
1242         int i_done;
1243         struct btrfs_ordered_extent *ordered;
1244         struct extent_state *cached_state = NULL;
1245         struct extent_io_tree *tree;
1246         struct extent_changeset *data_reserved = NULL;
1247         gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
1248 
1249         file_end = (isize - 1) >> PAGE_SHIFT;
1250         if (!isize || start_index > file_end)
1251                 return 0;
1252 
1253         page_cnt = min_t(u64, (u64)num_pages, (u64)file_end - start_index + 1);
1254 
1255         ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
1256                         start_index << PAGE_SHIFT,
1257                         page_cnt << PAGE_SHIFT);
1258         if (ret)
1259                 return ret;
1260         i_done = 0;
1261         tree = &BTRFS_I(inode)->io_tree;
1262 
1263         /* step one, lock all the pages */
1264         for (i = 0; i < page_cnt; i++) {
1265                 struct page *page;
1266 again:
1267                 page = find_or_create_page(inode->i_mapping,
1268                                            start_index + i, mask);
1269                 if (!page)
1270                         break;
1271 
1272                 page_start = page_offset(page);
1273                 page_end = page_start + PAGE_SIZE - 1;
1274                 while (1) {
1275                         lock_extent_bits(tree, page_start, page_end,
1276                                          &cached_state);
1277                         ordered = btrfs_lookup_ordered_extent(inode,
1278                                                               page_start);
1279                         unlock_extent_cached(tree, page_start, page_end,
1280                                              &cached_state);
1281                         if (!ordered)
1282                                 break;
1283 
1284                         unlock_page(page);
1285                         btrfs_start_ordered_extent(inode, ordered, 1);
1286                         btrfs_put_ordered_extent(ordered);
1287                         lock_page(page);
1288                         /*
1289                          * we unlocked the page above, so we need check if
1290                          * it was released or not.
1291                          */
1292                         if (page->mapping != inode->i_mapping) {
1293                                 unlock_page(page);
1294                                 put_page(page);
1295                                 goto again;
1296                         }
1297                 }
1298 
1299                 if (!PageUptodate(page)) {
1300                         btrfs_readpage(NULL, page);
1301                         lock_page(page);
1302                         if (!PageUptodate(page)) {
1303                                 unlock_page(page);
1304                                 put_page(page);
1305                                 ret = -EIO;
1306                                 break;
1307                         }
1308                 }
1309 
1310                 if (page->mapping != inode->i_mapping) {
1311                         unlock_page(page);
1312                         put_page(page);
1313                         goto again;
1314                 }
1315 
1316                 pages[i] = page;
1317                 i_done++;
1318         }
1319         if (!i_done || ret)
1320                 goto out;
1321 
1322         if (!(inode->i_sb->s_flags & SB_ACTIVE))
1323                 goto out;
1324 
1325         /*
1326          * so now we have a nice long stream of locked
1327          * and up to date pages, lets wait on them
1328          */
1329         for (i = 0; i < i_done; i++)
1330                 wait_on_page_writeback(pages[i]);
1331 
1332         page_start = page_offset(pages[0]);
1333         page_end = page_offset(pages[i_done - 1]) + PAGE_SIZE;
1334 
1335         lock_extent_bits(&BTRFS_I(inode)->io_tree,
1336                          page_start, page_end - 1, &cached_state);
1337         clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start,
1338                           page_end - 1, EXTENT_DIRTY | EXTENT_DELALLOC |
1339                           EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 0, 0,
1340                           &cached_state);
1341 
1342         if (i_done != page_cnt) {
1343                 spin_lock(&BTRFS_I(inode)->lock);
1344                 BTRFS_I(inode)->outstanding_extents++;
1345                 spin_unlock(&BTRFS_I(inode)->lock);
1346                 btrfs_delalloc_release_space(inode, data_reserved,
1347                                 start_index << PAGE_SHIFT,
1348                                 (page_cnt - i_done) << PAGE_SHIFT, true);
1349         }
1350 
1351 
1352         set_extent_defrag(&BTRFS_I(inode)->io_tree, page_start, page_end - 1,
1353                           &cached_state);
1354 
1355         unlock_extent_cached(&BTRFS_I(inode)->io_tree,
1356                              page_start, page_end - 1, &cached_state);
1357 
1358         for (i = 0; i < i_done; i++) {
1359                 clear_page_dirty_for_io(pages[i]);
1360                 ClearPageChecked(pages[i]);
1361                 set_page_extent_mapped(pages[i]);
1362                 set_page_dirty(pages[i]);
1363                 unlock_page(pages[i]);
1364                 put_page(pages[i]);
1365         }
1366         btrfs_delalloc_release_extents(BTRFS_I(inode), page_cnt << PAGE_SHIFT,
1367                                        false);
1368         extent_changeset_free(data_reserved);
1369         return i_done;
1370 out:
1371         for (i = 0; i < i_done; i++) {
1372                 unlock_page(pages[i]);
1373                 put_page(pages[i]);
1374         }
1375         btrfs_delalloc_release_space(inode, data_reserved,
1376                         start_index << PAGE_SHIFT,
1377                         page_cnt << PAGE_SHIFT, true);
1378         btrfs_delalloc_release_extents(BTRFS_I(inode), page_cnt << PAGE_SHIFT,
1379                                        true);
1380         extent_changeset_free(data_reserved);
1381         return ret;
1382 
1383 }
1384 
1385 int btrfs_defrag_file(struct inode *inode, struct file *file,
1386                       struct btrfs_ioctl_defrag_range_args *range,
1387                       u64 newer_than, unsigned long max_to_defrag)
1388 {
1389         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1390         struct btrfs_root *root = BTRFS_I(inode)->root;
1391         struct file_ra_state *ra = NULL;
1392         unsigned long last_index;
1393         u64 isize = i_size_read(inode);
1394         u64 last_len = 0;
1395         u64 skip = 0;
1396         u64 defrag_end = 0;
1397         u64 newer_off = range->start;
1398         unsigned long i;
1399         unsigned long ra_index = 0;
1400         int ret;
1401         int defrag_count = 0;
1402         int compress_type = BTRFS_COMPRESS_ZLIB;
1403         u32 extent_thresh = range->extent_thresh;
1404         unsigned long max_cluster = SZ_256K >> PAGE_SHIFT;
1405         unsigned long cluster = max_cluster;
1406         u64 new_align = ~((u64)SZ_128K - 1);
1407         struct page **pages = NULL;
1408         bool do_compress = range->flags & BTRFS_DEFRAG_RANGE_COMPRESS;
1409 
1410         if (isize == 0)
1411                 return 0;
1412 
1413         if (range->start >= isize)
1414                 return -EINVAL;
1415 
1416         if (do_compress) {
1417                 if (range->compress_type > BTRFS_COMPRESS_TYPES)
1418                         return -EINVAL;
1419                 if (range->compress_type)
1420                         compress_type = range->compress_type;
1421         }
1422 
1423         if (extent_thresh == 0)
1424                 extent_thresh = SZ_256K;
1425 
1426         /*
1427          * If we were not given a file, allocate a readahead context. As
1428          * readahead is just an optimization, defrag will work without it so
1429          * we don't error out.
1430          */
1431         if (!file) {
1432                 ra = kzalloc(sizeof(*ra), GFP_KERNEL);
1433                 if (ra)
1434                         file_ra_state_init(ra, inode->i_mapping);
1435         } else {
1436                 ra = &file->f_ra;
1437         }
1438 
1439         pages = kmalloc_array(max_cluster, sizeof(struct page *), GFP_KERNEL);
1440         if (!pages) {
1441                 ret = -ENOMEM;
1442                 goto out_ra;
1443         }
1444 
1445         /* find the last page to defrag */
1446         if (range->start + range->len > range->start) {
1447                 last_index = min_t(u64, isize - 1,
1448                          range->start + range->len - 1) >> PAGE_SHIFT;
1449         } else {
1450                 last_index = (isize - 1) >> PAGE_SHIFT;
1451         }
1452 
1453         if (newer_than) {
1454                 ret = find_new_extents(root, inode, newer_than,
1455                                        &newer_off, SZ_64K);
1456                 if (!ret) {
1457                         range->start = newer_off;
1458                         /*
1459                          * we always align our defrag to help keep
1460                          * the extents in the file evenly spaced
1461                          */
1462                         i = (newer_off & new_align) >> PAGE_SHIFT;
1463                 } else
1464                         goto out_ra;
1465         } else {
1466                 i = range->start >> PAGE_SHIFT;
1467         }
1468         if (!max_to_defrag)
1469                 max_to_defrag = last_index - i + 1;
1470 
1471         /*
1472          * make writeback starts from i, so the defrag range can be
1473          * written sequentially.
1474          */
1475         if (i < inode->i_mapping->writeback_index)
1476                 inode->i_mapping->writeback_index = i;
1477 
1478         while (i <= last_index && defrag_count < max_to_defrag &&
1479                (i < DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE))) {
1480                 /*
1481                  * make sure we stop running if someone unmounts
1482                  * the FS
1483                  */
1484                 if (!(inode->i_sb->s_flags & SB_ACTIVE))
1485                         break;
1486 
1487                 if (btrfs_defrag_cancelled(fs_info)) {
1488                         btrfs_debug(fs_info, "defrag_file cancelled");
1489                         ret = -EAGAIN;
1490                         break;
1491                 }
1492 
1493                 if (!should_defrag_range(inode, (u64)i << PAGE_SHIFT,
1494                                          extent_thresh, &last_len, &skip,
1495                                          &defrag_end, do_compress)){
1496                         unsigned long next;
1497                         /*
1498                          * the should_defrag function tells us how much to skip
1499                          * bump our counter by the suggested amount
1500                          */
1501                         next = DIV_ROUND_UP(skip, PAGE_SIZE);
1502                         i = max(i + 1, next);
1503                         continue;
1504                 }
1505 
1506                 if (!newer_than) {
1507                         cluster = (PAGE_ALIGN(defrag_end) >>
1508                                    PAGE_SHIFT) - i;
1509                         cluster = min(cluster, max_cluster);
1510                 } else {
1511                         cluster = max_cluster;
1512                 }
1513 
1514                 if (i + cluster > ra_index) {
1515                         ra_index = max(i, ra_index);
1516                         if (ra)
1517                                 page_cache_sync_readahead(inode->i_mapping, ra,
1518                                                 file, ra_index, cluster);
1519                         ra_index += cluster;
1520                 }
1521 
1522                 inode_lock(inode);
1523                 if (do_compress)
1524                         BTRFS_I(inode)->defrag_compress = compress_type;
1525                 ret = cluster_pages_for_defrag(inode, pages, i, cluster);
1526                 if (ret < 0) {
1527                         inode_unlock(inode);
1528                         goto out_ra;
1529                 }
1530 
1531                 defrag_count += ret;
1532                 balance_dirty_pages_ratelimited(inode->i_mapping);
1533                 inode_unlock(inode);
1534 
1535                 if (newer_than) {
1536                         if (newer_off == (u64)-1)
1537                                 break;
1538 
1539                         if (ret > 0)
1540                                 i += ret;
1541 
1542                         newer_off = max(newer_off + 1,
1543                                         (u64)i << PAGE_SHIFT);
1544 
1545                         ret = find_new_extents(root, inode, newer_than,
1546                                                &newer_off, SZ_64K);
1547                         if (!ret) {
1548                                 range->start = newer_off;
1549                                 i = (newer_off & new_align) >> PAGE_SHIFT;
1550                         } else {
1551                                 break;
1552                         }
1553                 } else {
1554                         if (ret > 0) {
1555                                 i += ret;
1556                                 last_len += ret << PAGE_SHIFT;
1557                         } else {
1558                                 i++;
1559                                 last_len = 0;
1560                         }
1561                 }
1562         }
1563 
1564         if ((range->flags & BTRFS_DEFRAG_RANGE_START_IO)) {
1565                 filemap_flush(inode->i_mapping);
1566                 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1567                              &BTRFS_I(inode)->runtime_flags))
1568                         filemap_flush(inode->i_mapping);
1569         }
1570 
1571         if (range->compress_type == BTRFS_COMPRESS_LZO) {
1572                 btrfs_set_fs_incompat(fs_info, COMPRESS_LZO);
1573         } else if (range->compress_type == BTRFS_COMPRESS_ZSTD) {
1574                 btrfs_set_fs_incompat(fs_info, COMPRESS_ZSTD);
1575         }
1576 
1577         ret = defrag_count;
1578 
1579 out_ra:
1580         if (do_compress) {
1581                 inode_lock(inode);
1582                 BTRFS_I(inode)->defrag_compress = BTRFS_COMPRESS_NONE;
1583                 inode_unlock(inode);
1584         }
1585         if (!file)
1586                 kfree(ra);
1587         kfree(pages);
1588         return ret;
1589 }
1590 
1591 static noinline int btrfs_ioctl_resize(struct file *file,
1592                                         void __user *arg)
1593 {
1594         struct inode *inode = file_inode(file);
1595         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1596         u64 new_size;
1597         u64 old_size;
1598         u64 devid = 1;
1599         struct btrfs_root *root = BTRFS_I(inode)->root;
1600         struct btrfs_ioctl_vol_args *vol_args;
1601         struct btrfs_trans_handle *trans;
1602         struct btrfs_device *device = NULL;
1603         char *sizestr;
1604         char *retptr;
1605         char *devstr = NULL;
1606         int ret = 0;
1607         int mod = 0;
1608 
1609         if (!capable(CAP_SYS_ADMIN))
1610                 return -EPERM;
1611 
1612         ret = mnt_want_write_file(file);
1613         if (ret)
1614                 return ret;
1615 
1616         if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
1617                 mnt_drop_write_file(file);
1618                 return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
1619         }
1620 
1621         vol_args = memdup_user(arg, sizeof(*vol_args));
1622         if (IS_ERR(vol_args)) {
1623                 ret = PTR_ERR(vol_args);
1624                 goto out;
1625         }
1626 
1627         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1628 
1629         sizestr = vol_args->name;
1630         devstr = strchr(sizestr, ':');
1631         if (devstr) {
1632                 sizestr = devstr + 1;
1633                 *devstr = '\0';
1634                 devstr = vol_args->name;
1635                 ret = kstrtoull(devstr, 10, &devid);
1636                 if (ret)
1637                         goto out_free;
1638                 if (!devid) {
1639                         ret = -EINVAL;
1640                         goto out_free;
1641                 }
1642                 btrfs_info(fs_info, "resizing devid %llu", devid);
1643         }
1644 
1645         device = btrfs_find_device(fs_info, devid, NULL, NULL);
1646         if (!device) {
1647                 btrfs_info(fs_info, "resizer unable to find device %llu",
1648                            devid);
1649                 ret = -ENODEV;
1650                 goto out_free;
1651         }
1652 
1653         if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1654                 btrfs_info(fs_info,
1655                            "resizer unable to apply on readonly device %llu",
1656                        devid);
1657                 ret = -EPERM;
1658                 goto out_free;
1659         }
1660 
1661         if (!strcmp(sizestr, "max"))
1662                 new_size = device->bdev->bd_inode->i_size;
1663         else {
1664                 if (sizestr[0] == '-') {
1665                         mod = -1;
1666                         sizestr++;
1667                 } else if (sizestr[0] == '+') {
1668                         mod = 1;
1669                         sizestr++;
1670                 }
1671                 new_size = memparse(sizestr, &retptr);
1672                 if (*retptr != '\0' || new_size == 0) {
1673                         ret = -EINVAL;
1674                         goto out_free;
1675                 }
1676         }
1677 
1678         if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1679                 ret = -EPERM;
1680                 goto out_free;
1681         }
1682 
1683         old_size = btrfs_device_get_total_bytes(device);
1684 
1685         if (mod < 0) {
1686                 if (new_size > old_size) {
1687                         ret = -EINVAL;
1688                         goto out_free;
1689                 }
1690                 new_size = old_size - new_size;
1691         } else if (mod > 0) {
1692                 if (new_size > ULLONG_MAX - old_size) {
1693                         ret = -ERANGE;
1694                         goto out_free;
1695                 }
1696                 new_size = old_size + new_size;
1697         }
1698 
1699         if (new_size < SZ_256M) {
1700                 ret = -EINVAL;
1701                 goto out_free;
1702         }
1703         if (new_size > device->bdev->bd_inode->i_size) {
1704                 ret = -EFBIG;
1705                 goto out_free;
1706         }
1707 
1708         new_size = round_down(new_size, fs_info->sectorsize);
1709 
1710         btrfs_info_in_rcu(fs_info, "new size for %s is %llu",
1711                           rcu_str_deref(device->name), new_size);
1712 
1713         if (new_size > old_size) {
1714                 trans = btrfs_start_transaction(root, 0);
1715                 if (IS_ERR(trans)) {
1716                         ret = PTR_ERR(trans);
1717                         goto out_free;
1718                 }
1719                 ret = btrfs_grow_device(trans, device, new_size);
1720                 btrfs_commit_transaction(trans);
1721         } else if (new_size < old_size) {
1722                 ret = btrfs_shrink_device(device, new_size);
1723         } /* equal, nothing need to do */
1724 
1725 out_free:
1726         kfree(vol_args);
1727 out:
1728         clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
1729         mnt_drop_write_file(file);
1730         return ret;
1731 }
1732 
1733 static noinline int btrfs_ioctl_snap_create_transid(struct file *file,
1734                                 const char *name, unsigned long fd, int subvol,
1735                                 u64 *transid, bool readonly,
1736                                 struct btrfs_qgroup_inherit *inherit)
1737 {
1738         int namelen;
1739         int ret = 0;
1740 
1741         if (!S_ISDIR(file_inode(file)->i_mode))
1742                 return -ENOTDIR;
1743 
1744         ret = mnt_want_write_file(file);
1745         if (ret)
1746                 goto out;
1747 
1748         namelen = strlen(name);
1749         if (strchr(name, '/')) {
1750                 ret = -EINVAL;
1751                 goto out_drop_write;
1752         }
1753 
1754         if (name[0] == '.' &&
1755            (namelen == 1 || (name[1] == '.' && namelen == 2))) {
1756                 ret = -EEXIST;
1757                 goto out_drop_write;
1758         }
1759 
1760         if (subvol) {
1761                 ret = btrfs_mksubvol(&file->f_path, name, namelen,
1762                                      NULL, transid, readonly, inherit);
1763         } else {
1764                 struct fd src = fdget(fd);
1765                 struct inode *src_inode;
1766                 if (!src.file) {
1767                         ret = -EINVAL;
1768                         goto out_drop_write;
1769                 }
1770 
1771                 src_inode = file_inode(src.file);
1772                 if (src_inode->i_sb != file_inode(file)->i_sb) {
1773                         btrfs_info(BTRFS_I(file_inode(file))->root->fs_info,
1774                                    "Snapshot src from another FS");
1775                         ret = -EXDEV;
1776                 } else if (!inode_owner_or_capable(src_inode)) {
1777                         /*
1778                          * Subvolume creation is not restricted, but snapshots
1779                          * are limited to own subvolumes only
1780                          */
1781                         ret = -EPERM;
1782                 } else {
1783                         ret = btrfs_mksubvol(&file->f_path, name, namelen,
1784                                              BTRFS_I(src_inode)->root,
1785                                              transid, readonly, inherit);
1786                 }
1787                 fdput(src);
1788         }
1789 out_drop_write:
1790         mnt_drop_write_file(file);
1791 out:
1792         return ret;
1793 }
1794 
1795 static noinline int btrfs_ioctl_snap_create(struct file *file,
1796                                             void __user *arg, int subvol)
1797 {
1798         struct btrfs_ioctl_vol_args *vol_args;
1799         int ret;
1800 
1801         if (!S_ISDIR(file_inode(file)->i_mode))
1802                 return -ENOTDIR;
1803 
1804         vol_args = memdup_user(arg, sizeof(*vol_args));
1805         if (IS_ERR(vol_args))
1806                 return PTR_ERR(vol_args);
1807         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
1808 
1809         ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
1810                                               vol_args->fd, subvol,
1811                                               NULL, false, NULL);
1812 
1813         kfree(vol_args);
1814         return ret;
1815 }
1816 
1817 static noinline int btrfs_ioctl_snap_create_v2(struct file *file,
1818                                                void __user *arg, int subvol)
1819 {
1820         struct btrfs_ioctl_vol_args_v2 *vol_args;
1821         int ret;
1822         u64 transid = 0;
1823         u64 *ptr = NULL;
1824         bool readonly = false;
1825         struct btrfs_qgroup_inherit *inherit = NULL;
1826 
1827         if (!S_ISDIR(file_inode(file)->i_mode))
1828                 return -ENOTDIR;
1829 
1830         vol_args = memdup_user(arg, sizeof(*vol_args));
1831         if (IS_ERR(vol_args))
1832                 return PTR_ERR(vol_args);
1833         vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
1834 
1835         if (vol_args->flags &
1836             ~(BTRFS_SUBVOL_CREATE_ASYNC | BTRFS_SUBVOL_RDONLY |
1837               BTRFS_SUBVOL_QGROUP_INHERIT)) {
1838                 ret = -EOPNOTSUPP;
1839                 goto free_args;
1840         }
1841 
1842         if (vol_args->flags & BTRFS_SUBVOL_CREATE_ASYNC)
1843                 ptr = &transid;
1844         if (vol_args->flags & BTRFS_SUBVOL_RDONLY)
1845                 readonly = true;
1846         if (vol_args->flags & BTRFS_SUBVOL_QGROUP_INHERIT) {
1847                 if (vol_args->size > PAGE_SIZE) {
1848                         ret = -EINVAL;
1849                         goto free_args;
1850                 }
1851                 inherit = memdup_user(vol_args->qgroup_inherit, vol_args->size);
1852                 if (IS_ERR(inherit)) {
1853                         ret = PTR_ERR(inherit);
1854                         goto free_args;
1855                 }
1856         }
1857 
1858         ret = btrfs_ioctl_snap_create_transid(file, vol_args->name,
1859                                               vol_args->fd, subvol, ptr,
1860                                               readonly, inherit);
1861         if (ret)
1862                 goto free_inherit;
1863 
1864         if (ptr && copy_to_user(arg +
1865                                 offsetof(struct btrfs_ioctl_vol_args_v2,
1866                                         transid),
1867                                 ptr, sizeof(*ptr)))
1868                 ret = -EFAULT;
1869 
1870 free_inherit:
1871         kfree(inherit);
1872 free_args:
1873         kfree(vol_args);
1874         return ret;
1875 }
1876 
1877 static noinline int btrfs_ioctl_subvol_getflags(struct file *file,
1878                                                 void __user *arg)
1879 {
1880         struct inode *inode = file_inode(file);
1881         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1882         struct btrfs_root *root = BTRFS_I(inode)->root;
1883         int ret = 0;
1884         u64 flags = 0;
1885 
1886         if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID)
1887                 return -EINVAL;
1888 
1889         down_read(&fs_info->subvol_sem);
1890         if (btrfs_root_readonly(root))
1891                 flags |= BTRFS_SUBVOL_RDONLY;
1892         up_read(&fs_info->subvol_sem);
1893 
1894         if (copy_to_user(arg, &flags, sizeof(flags)))
1895                 ret = -EFAULT;
1896 
1897         return ret;
1898 }
1899 
1900 static noinline int btrfs_ioctl_subvol_setflags(struct file *file,
1901                                               void __user *arg)
1902 {
1903         struct inode *inode = file_inode(file);
1904         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1905         struct btrfs_root *root = BTRFS_I(inode)->root;
1906         struct btrfs_trans_handle *trans;
1907         u64 root_flags;
1908         u64 flags;
1909         int ret = 0;
1910 
1911         if (!inode_owner_or_capable(inode))
1912                 return -EPERM;
1913 
1914         ret = mnt_want_write_file(file);
1915         if (ret)
1916                 goto out;
1917 
1918         if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
1919                 ret = -EINVAL;
1920                 goto out_drop_write;
1921         }
1922 
1923         if (copy_from_user(&flags, arg, sizeof(flags))) {
1924                 ret = -EFAULT;
1925                 goto out_drop_write;
1926         }
1927 
1928         if (flags & BTRFS_SUBVOL_CREATE_ASYNC) {
1929                 ret = -EINVAL;
1930                 goto out_drop_write;
1931         }
1932 
1933         if (flags & ~BTRFS_SUBVOL_RDONLY) {
1934                 ret = -EOPNOTSUPP;
1935                 goto out_drop_write;
1936         }
1937 
1938         down_write(&fs_info->subvol_sem);
1939 
1940         /* nothing to do */
1941         if (!!(flags & BTRFS_SUBVOL_RDONLY) == btrfs_root_readonly(root))
1942                 goto out_drop_sem;
1943 
1944         root_flags = btrfs_root_flags(&root->root_item);
1945         if (flags & BTRFS_SUBVOL_RDONLY) {
1946                 btrfs_set_root_flags(&root->root_item,
1947                                      root_flags | BTRFS_ROOT_SUBVOL_RDONLY);
1948         } else {
1949                 /*
1950                  * Block RO -> RW transition if this subvolume is involved in
1951                  * send
1952                  */
1953                 spin_lock(&root->root_item_lock);
1954                 if (root->send_in_progress == 0) {
1955                         btrfs_set_root_flags(&root->root_item,
1956                                      root_flags & ~BTRFS_ROOT_SUBVOL_RDONLY);
1957                         spin_unlock(&root->root_item_lock);
1958                 } else {
1959                         spin_unlock(&root->root_item_lock);
1960                         btrfs_warn(fs_info,
1961                                    "Attempt to set subvolume %llu read-write during send",
1962                                    root->root_key.objectid);
1963                         ret = -EPERM;
1964                         goto out_drop_sem;
1965                 }
1966         }
1967 
1968         trans = btrfs_start_transaction(root, 1);
1969         if (IS_ERR(trans)) {
1970                 ret = PTR_ERR(trans);
1971                 goto out_reset;
1972         }
1973 
1974         ret = btrfs_update_root(trans, fs_info->tree_root,
1975                                 &root->root_key, &root->root_item);
1976         if (ret < 0) {
1977                 btrfs_end_transaction(trans);
1978                 goto out_reset;
1979         }
1980 
1981         ret = btrfs_commit_transaction(trans);
1982 
1983 out_reset:
1984         if (ret)
1985                 btrfs_set_root_flags(&root->root_item, root_flags);
1986 out_drop_sem:
1987         up_write(&fs_info->subvol_sem);
1988 out_drop_write:
1989         mnt_drop_write_file(file);
1990 out:
1991         return ret;
1992 }
1993 
1994 static noinline int key_in_sk(struct btrfs_key *key,
1995                               struct btrfs_ioctl_search_key *sk)
1996 {
1997         struct btrfs_key test;
1998         int ret;
1999 
2000         test.objectid = sk->min_objectid;
2001         test.type = sk->min_type;
2002         test.offset = sk->min_offset;
2003 
2004         ret = btrfs_comp_cpu_keys(key, &test);
2005         if (ret < 0)
2006                 return 0;
2007 
2008         test.objectid = sk->max_objectid;
2009         test.type = sk->max_type;
2010         test.offset = sk->max_offset;
2011 
2012         ret = btrfs_comp_cpu_keys(key, &test);
2013         if (ret > 0)
2014                 return 0;
2015         return 1;
2016 }
2017 
2018 static noinline int copy_to_sk(struct btrfs_path *path,
2019                                struct btrfs_key *key,
2020                                struct btrfs_ioctl_search_key *sk,
2021                                size_t *buf_size,
2022                                char __user *ubuf,
2023                                unsigned long *sk_offset,
2024                                int *num_found)
2025 {
2026         u64 found_transid;
2027         struct extent_buffer *leaf;
2028         struct btrfs_ioctl_search_header sh;
2029         struct btrfs_key test;
2030         unsigned long item_off;
2031         unsigned long item_len;
2032         int nritems;
2033         int i;
2034         int slot;
2035         int ret = 0;
2036 
2037         leaf = path->nodes[0];
2038         slot = path->slots[0];
2039         nritems = btrfs_header_nritems(leaf);
2040 
2041         if (btrfs_header_generation(leaf) > sk->max_transid) {
2042                 i = nritems;
2043                 goto advance_key;
2044         }
2045         found_transid = btrfs_header_generation(leaf);
2046 
2047         for (i = slot; i < nritems; i++) {
2048                 item_off = btrfs_item_ptr_offset(leaf, i);
2049                 item_len = btrfs_item_size_nr(leaf, i);
2050 
2051                 btrfs_item_key_to_cpu(leaf, key, i);
2052                 if (!key_in_sk(key, sk))
2053                         continue;
2054 
2055                 if (sizeof(sh) + item_len > *buf_size) {
2056                         if (*num_found) {
2057                                 ret = 1;
2058                                 goto out;
2059                         }
2060 
2061                         /*
2062                          * return one empty item back for v1, which does not
2063                          * handle -EOVERFLOW
2064                          */
2065 
2066                         *buf_size = sizeof(sh) + item_len;
2067                         item_len = 0;
2068                         ret = -EOVERFLOW;
2069                 }
2070 
2071                 if (sizeof(sh) + item_len + *sk_offset > *buf_size) {
2072                         ret = 1;
2073                         goto out;
2074                 }
2075 
2076                 sh.objectid = key->objectid;
2077                 sh.offset = key->offset;
2078                 sh.type = key->type;
2079                 sh.len = item_len;
2080                 sh.transid = found_transid;
2081 
2082                 /* copy search result header */
2083                 if (copy_to_user(ubuf + *sk_offset, &sh, sizeof(sh))) {
2084                         ret = -EFAULT;
2085                         goto out;
2086                 }
2087 
2088                 *sk_offset += sizeof(sh);
2089 
2090                 if (item_len) {
2091                         char __user *up = ubuf + *sk_offset;
2092                         /* copy the item */
2093                         if (read_extent_buffer_to_user(leaf, up,
2094                                                        item_off, item_len)) {
2095                                 ret = -EFAULT;
2096                                 goto out;
2097                         }
2098 
2099                         *sk_offset += item_len;
2100                 }
2101                 (*num_found)++;
2102 
2103                 if (ret) /* -EOVERFLOW from above */
2104                         goto out;
2105 
2106                 if (*num_found >= sk->nr_items) {
2107                         ret = 1;
2108                         goto out;
2109                 }
2110         }
2111 advance_key:
2112         ret = 0;
2113         test.objectid = sk->max_objectid;
2114         test.type = sk->max_type;
2115         test.offset = sk->max_offset;
2116         if (btrfs_comp_cpu_keys(key, &test) >= 0)
2117                 ret = 1;
2118         else if (key->offset < (u64)-1)
2119                 key->offset++;
2120         else if (key->type < (u8)-1) {
2121                 key->offset = 0;
2122                 key->type++;
2123         } else if (key->objectid < (u64)-1) {
2124                 key->offset = 0;
2125                 key->type = 0;
2126                 key->objectid++;
2127         } else
2128                 ret = 1;
2129 out:
2130         /*
2131          *  0: all items from this leaf copied, continue with next
2132          *  1: * more items can be copied, but unused buffer is too small
2133          *     * all items were found
2134          *     Either way, it will stops the loop which iterates to the next
2135          *     leaf
2136          *  -EOVERFLOW: item was to large for buffer
2137          *  -EFAULT: could not copy extent buffer back to userspace
2138          */
2139         return ret;
2140 }
2141 
2142 static noinline int search_ioctl(struct inode *inode,
2143                                  struct btrfs_ioctl_search_key *sk,
2144                                  size_t *buf_size,
2145                                  char __user *ubuf)
2146 {
2147         struct btrfs_fs_info *info = btrfs_sb(inode->i_sb);
2148         struct btrfs_root *root;
2149         struct btrfs_key key;
2150         struct btrfs_path *path;
2151         int ret;
2152         int num_found = 0;
2153         unsigned long sk_offset = 0;
2154 
2155         if (*buf_size < sizeof(struct btrfs_ioctl_search_header)) {
2156                 *buf_size = sizeof(struct btrfs_ioctl_search_header);
2157                 return -EOVERFLOW;
2158         }
2159 
2160         path = btrfs_alloc_path();
2161         if (!path)
2162                 return -ENOMEM;
2163 
2164         if (sk->tree_id == 0) {
2165                 /* search the root of the inode that was passed */
2166                 root = BTRFS_I(inode)->root;
2167         } else {
2168                 key.objectid = sk->tree_id;
2169                 key.type = BTRFS_ROOT_ITEM_KEY;
2170                 key.offset = (u64)-1;
2171                 root = btrfs_read_fs_root_no_name(info, &key);
2172                 if (IS_ERR(root)) {
2173                         btrfs_free_path(path);
2174                         return PTR_ERR(root);
2175                 }
2176         }
2177 
2178         key.objectid = sk->min_objectid;
2179         key.type = sk->min_type;
2180         key.offset = sk->min_offset;
2181 
2182         while (1) {
2183                 ret = btrfs_search_forward(root, &key, path, sk->min_transid);
2184                 if (ret != 0) {
2185                         if (ret > 0)
2186                                 ret = 0;
2187                         goto err;
2188                 }
2189                 ret = copy_to_sk(path, &key, sk, buf_size, ubuf,
2190                                  &sk_offset, &num_found);
2191                 btrfs_release_path(path);
2192                 if (ret)
2193                         break;
2194 
2195         }
2196         if (ret > 0)
2197                 ret = 0;
2198 err:
2199         sk->nr_items = num_found;
2200         btrfs_free_path(path);
2201         return ret;
2202 }
2203 
2204 static noinline int btrfs_ioctl_tree_search(struct file *file,
2205                                            void __user *argp)
2206 {
2207         struct btrfs_ioctl_search_args __user *uargs;
2208         struct btrfs_ioctl_search_key sk;
2209         struct inode *inode;
2210         int ret;
2211         size_t buf_size;
2212 
2213         if (!capable(CAP_SYS_ADMIN))
2214                 return -EPERM;
2215 
2216         uargs = (struct btrfs_ioctl_search_args __user *)argp;
2217 
2218         if (copy_from_user(&sk, &uargs->key, sizeof(sk)))
2219                 return -EFAULT;
2220 
2221         buf_size = sizeof(uargs->buf);
2222 
2223         inode = file_inode(file);
2224         ret = search_ioctl(inode, &sk, &buf_size, uargs->buf);
2225 
2226         /*
2227          * In the origin implementation an overflow is handled by returning a
2228          * search header with a len of zero, so reset ret.
2229          */
2230         if (ret == -EOVERFLOW)
2231                 ret = 0;
2232 
2233         if (ret == 0 && copy_to_user(&uargs->key, &sk, sizeof(sk)))
2234                 ret = -EFAULT;
2235         return ret;
2236 }
2237 
2238 static noinline int btrfs_ioctl_tree_search_v2(struct file *file,
2239                                                void __user *argp)
2240 {
2241         struct btrfs_ioctl_search_args_v2 __user *uarg;
2242         struct btrfs_ioctl_search_args_v2 args;
2243         struct inode *inode;
2244         int ret;
2245         size_t buf_size;
2246         const size_t buf_limit = SZ_16M;
2247 
2248         if (!capable(CAP_SYS_ADMIN))
2249                 return -EPERM;
2250 
2251         /* copy search header and buffer size */
2252         uarg = (struct btrfs_ioctl_search_args_v2 __user *)argp;
2253         if (copy_from_user(&args, uarg, sizeof(args)))
2254                 return -EFAULT;
2255 
2256         buf_size = args.buf_size;
2257 
2258         /* limit result size to 16MB */
2259         if (buf_size > buf_limit)
2260                 buf_size = buf_limit;
2261 
2262         inode = file_inode(file);
2263         ret = search_ioctl(inode, &args.key, &buf_size,
2264                            (char __user *)(&uarg->buf[0]));
2265         if (ret == 0 && copy_to_user(&uarg->key, &args.key, sizeof(args.key)))
2266                 ret = -EFAULT;
2267         else if (ret == -EOVERFLOW &&
2268                 copy_to_user(&uarg->buf_size, &buf_size, sizeof(buf_size)))
2269                 ret = -EFAULT;
2270 
2271         return ret;
2272 }
2273 
2274 /*
2275  * Search INODE_REFs to identify path name of 'dirid' directory
2276  * in a 'tree_id' tree. and sets path name to 'name'.
2277  */
2278 static noinline int btrfs_search_path_in_tree(struct btrfs_fs_info *info,
2279                                 u64 tree_id, u64 dirid, char *name)
2280 {
2281         struct btrfs_root *root;
2282         struct btrfs_key key;
2283         char *ptr;
2284         int ret = -1;
2285         int slot;
2286         int len;
2287         int total_len = 0;
2288         struct btrfs_inode_ref *iref;
2289         struct extent_buffer *l;
2290         struct btrfs_path *path;
2291 
2292         if (dirid == BTRFS_FIRST_FREE_OBJECTID) {
2293                 name[0]='\0';
2294                 return 0;
2295         }
2296 
2297         path = btrfs_alloc_path();
2298         if (!path)
2299                 return -ENOMEM;
2300 
2301         ptr = &name[BTRFS_INO_LOOKUP_PATH_MAX - 1];
2302 
2303         key.objectid = tree_id;
2304         key.type = BTRFS_ROOT_ITEM_KEY;
2305         key.offset = (u64)-1;
2306         root = btrfs_read_fs_root_no_name(info, &key);
2307         if (IS_ERR(root)) {
2308                 ret = PTR_ERR(root);
2309                 goto out;
2310         }
2311 
2312         key.objectid = dirid;
2313         key.type = BTRFS_INODE_REF_KEY;
2314         key.offset = (u64)-1;
2315 
2316         while (1) {
2317                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2318                 if (ret < 0)
2319                         goto out;
2320                 else if (ret > 0) {
2321                         ret = btrfs_previous_item(root, path, dirid,
2322                                                   BTRFS_INODE_REF_KEY);
2323                         if (ret < 0)
2324                                 goto out;
2325                         else if (ret > 0) {
2326                                 ret = -ENOENT;
2327                                 goto out;
2328                         }
2329                 }
2330 
2331                 l = path->nodes[0];
2332                 slot = path->slots[0];
2333                 btrfs_item_key_to_cpu(l, &key, slot);
2334 
2335                 iref = btrfs_item_ptr(l, slot, struct btrfs_inode_ref);
2336                 len = btrfs_inode_ref_name_len(l, iref);
2337                 ptr -= len + 1;
2338                 total_len += len + 1;
2339                 if (ptr < name) {
2340                         ret = -ENAMETOOLONG;
2341                         goto out;
2342                 }
2343 
2344                 *(ptr + len) = '/';
2345                 read_extent_buffer(l, ptr, (unsigned long)(iref + 1), len);
2346 
2347                 if (key.offset == BTRFS_FIRST_FREE_OBJECTID)
2348                         break;
2349 
2350                 btrfs_release_path(path);
2351                 key.objectid = key.offset;
2352                 key.offset = (u64)-1;
2353                 dirid = key.objectid;
2354         }
2355         memmove(name, ptr, total_len);
2356         name[total_len] = '\0';
2357         ret = 0;
2358 out:
2359         btrfs_free_path(path);
2360         return ret;
2361 }
2362 
2363 static int btrfs_search_path_in_tree_user(struct inode *inode,
2364                                 struct btrfs_ioctl_ino_lookup_user_args *args)
2365 {
2366         struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
2367         struct super_block *sb = inode->i_sb;
2368         struct btrfs_key upper_limit = BTRFS_I(inode)->location;
2369         u64 treeid = BTRFS_I(inode)->root->root_key.objectid;
2370         u64 dirid = args->dirid;
2371         unsigned long item_off;
2372         unsigned long item_len;
2373         struct btrfs_inode_ref *iref;
2374         struct btrfs_root_ref *rref;
2375         struct btrfs_root *root;
2376         struct btrfs_path *path;
2377         struct btrfs_key key, key2;
2378         struct extent_buffer *leaf;
2379         struct inode *temp_inode;
2380         char *ptr;
2381         int slot;
2382         int len;
2383         int total_len = 0;
2384         int ret;
2385 
2386         path = btrfs_alloc_path();
2387         if (!path)
2388                 return -ENOMEM;
2389 
2390         /*
2391          * If the bottom subvolume does not exist directly under upper_limit,
2392          * construct the path in from the bottom up.
2393          */
2394         if (dirid != upper_limit.objectid) {
2395                 ptr = &args->path[BTRFS_INO_LOOKUP_USER_PATH_MAX - 1];
2396 
2397                 key.objectid = treeid;
2398                 key.type = BTRFS_ROOT_ITEM_KEY;
2399                 key.offset = (u64)-1;
2400                 root = btrfs_read_fs_root_no_name(fs_info, &key);
2401                 if (IS_ERR(root)) {
2402                         ret = PTR_ERR(root);
2403                         goto out;
2404                 }
2405 
2406                 key.objectid = dirid;
2407                 key.type = BTRFS_INODE_REF_KEY;
2408                 key.offset = (u64)-1;
2409                 while (1) {
2410                         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2411                         if (ret < 0) {
2412                                 goto out;
2413                         } else if (ret > 0) {
2414                                 ret = btrfs_previous_item(root, path, dirid,
2415                                                           BTRFS_INODE_REF_KEY);
2416                                 if (ret < 0) {
2417                                         goto out;
2418                                 } else if (ret > 0) {
2419                                         ret = -ENOENT;
2420                                         goto out;
2421                                 }
2422                         }
2423 
2424                         leaf = path->nodes[0];
2425                         slot = path->slots[0];
2426                         btrfs_item_key_to_cpu(leaf, &key, slot);
2427 
2428                         iref = btrfs_item_ptr(leaf, slot, struct btrfs_inode_ref);
2429                         len = btrfs_inode_ref_name_len(leaf, iref);
2430                         ptr -= len + 1;
2431                         total_len += len + 1;
2432                         if (ptr < args->path) {
2433                                 ret = -ENAMETOOLONG;
2434                                 goto out;
2435                         }
2436 
2437                         *(ptr + len) = '/';
2438                         read_extent_buffer(leaf, ptr,
2439                                         (unsigned long)(iref + 1), len);
2440 
2441                         /* Check the read+exec permission of this directory */
2442                         ret = btrfs_previous_item(root, path, dirid,
2443                                                   BTRFS_INODE_ITEM_KEY);
2444                         if (ret < 0) {
2445                                 goto out;
2446                         } else if (ret > 0) {
2447                                 ret = -ENOENT;
2448                                 goto out;
2449                         }
2450 
2451                         leaf = path->nodes[0];
2452                         slot = path->slots[0];
2453                         btrfs_item_key_to_cpu(leaf, &key2, slot);
2454                         if (key2.objectid != dirid) {
2455                                 ret = -ENOENT;
2456                                 goto out;
2457                         }
2458 
2459                         temp_inode = btrfs_iget(sb, &key2, root, NULL);
2460                         if (IS_ERR(temp_inode)) {
2461                                 ret = PTR_ERR(temp_inode);
2462                                 goto out;
2463                         }
2464                         ret = inode_permission(temp_inode, MAY_READ | MAY_EXEC);
2465                         iput(temp_inode);
2466                         if (ret) {
2467                                 ret = -EACCES;
2468                                 goto out;
2469                         }
2470 
2471                         if (key.offset == upper_limit.objectid)
2472                                 break;
2473                         if (key.objectid == BTRFS_FIRST_FREE_OBJECTID) {
2474                                 ret = -EACCES;
2475                                 goto out;
2476                         }
2477 
2478                         btrfs_release_path(path);
2479                         key.objectid = key.offset;
2480                         key.offset = (u64)-1;
2481                         dirid = key.objectid;
2482                 }
2483 
2484                 memmove(args->path, ptr, total_len);
2485                 args->path[total_len] = '\0';
2486                 btrfs_release_path(path);
2487         }
2488 
2489         /* Get the bottom subvolume's name from ROOT_REF */
2490         root = fs_info->tree_root;
2491         key.objectid = treeid;
2492         key.type = BTRFS_ROOT_REF_KEY;
2493         key.offset = args->treeid;
2494         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2495         if (ret < 0) {
2496                 goto out;
2497         } else if (ret > 0) {
2498                 ret = -ENOENT;
2499                 goto out;
2500         }
2501 
2502         leaf = path->nodes[0];
2503         slot = path->slots[0];
2504         btrfs_item_key_to_cpu(leaf, &key, slot);
2505 
2506         item_off = btrfs_item_ptr_offset(leaf, slot);
2507         item_len = btrfs_item_size_nr(leaf, slot);
2508         /* Check if dirid in ROOT_REF corresponds to passed dirid */
2509         rref = btrfs_item_ptr(leaf, slot, struct btrfs_root_ref);
2510         if (args->dirid != btrfs_root_ref_dirid(leaf, rref)) {
2511                 ret = -EINVAL;
2512                 goto out;
2513         }
2514 
2515         /* Copy subvolume's name */
2516         item_off += sizeof(struct btrfs_root_ref);
2517         item_len -= sizeof(struct btrfs_root_ref);
2518         read_extent_buffer(leaf, args->name, item_off, item_len);
2519         args->name[item_len] = 0;
2520 
2521 out:
2522         btrfs_free_path(path);
2523         return ret;
2524 }
2525 
2526 static noinline int btrfs_ioctl_ino_lookup(struct file *file,
2527                                            void __user *argp)
2528 {
2529          struct btrfs_ioctl_ino_lookup_args *args;
2530          struct inode *inode;
2531         int ret = 0;
2532 
2533         args = memdup_user(argp, sizeof(*args));
2534         if (IS_ERR(args))
2535                 return PTR_ERR(args);
2536 
2537         inode = file_inode(file);
2538 
2539         /*
2540          * Unprivileged query to obtain the containing subvolume root id. The
2541          * path is reset so it's consistent with btrfs_search_path_in_tree.
2542          */
2543         if (args->treeid == 0)
2544                 args->treeid = BTRFS_I(inode)->root->root_key.objectid;
2545 
2546         if (args->objectid == BTRFS_FIRST_FREE_OBJECTID) {
2547                 args->name[0] = 0;
2548                 goto out;
2549         }
2550 
2551         if (!capable(CAP_SYS_ADMIN)) {
2552                 ret = -EPERM;
2553                 goto out;
2554         }
2555 
2556         ret = btrfs_search_path_in_tree(BTRFS_I(inode)->root->fs_info,
2557                                         args->treeid, args->objectid,
2558                                         args->name);
2559 
2560 out:
2561         if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
2562                 ret = -EFAULT;
2563 
2564         kfree(args);
2565         return ret;
2566 }
2567 
2568 /*
2569  * Version of ino_lookup ioctl (unprivileged)
2570  *
2571  * The main differences from ino_lookup ioctl are:
2572  *
2573  *   1. Read + Exec permission will be checked using inode_permission() during
2574  *      path construction. -EACCES will be returned in case of failure.
2575  *   2. Path construction will be stopped at the inode number which corresponds
2576  *      to the fd with which this ioctl is called. If constructed path does not
2577  *      exist under fd's inode, -EACCES will be returned.
2578  *   3. The name of bottom subvolume is also searched and filled.
2579  */
2580 static int btrfs_ioctl_ino_lookup_user(struct file *file, void __user *argp)
2581 {
2582         struct btrfs_ioctl_ino_lookup_user_args *args;
2583         struct inode *inode;
2584         int ret;
2585 
2586         args = memdup_user(argp, sizeof(*args));
2587         if (IS_ERR(args))
2588                 return PTR_ERR(args);
2589 
2590         inode = file_inode(file);
2591 
2592         if (args->dirid == BTRFS_FIRST_FREE_OBJECTID &&
2593             BTRFS_I(inode)->location.objectid != BTRFS_FIRST_FREE_OBJECTID) {
2594                 /*
2595                  * The subvolume does not exist under fd with which this is
2596                  * called
2597                  */
2598                 kfree(args);
2599                 return -EACCES;
2600         }
2601 
2602         ret = btrfs_search_path_in_tree_user(inode, args);
2603 
2604         if (ret == 0 && copy_to_user(argp, args, sizeof(*args)))
2605                 ret = -EFAULT;
2606 
2607         kfree(args);
2608         return ret;
2609 }
2610 
2611 /* Get the subvolume information in BTRFS_ROOT_ITEM and BTRFS_ROOT_BACKREF */
2612 static int btrfs_ioctl_get_subvol_info(struct file *file, void __user *argp)
2613 {
2614         struct btrfs_ioctl_get_subvol_info_args *subvol_info;
2615         struct btrfs_fs_info *fs_info;
2616         struct btrfs_root *root;
2617         struct btrfs_path *path;
2618         struct btrfs_key key;
2619         struct btrfs_root_item *root_item;
2620         struct btrfs_root_ref *rref;
2621         struct extent_buffer *leaf;
2622         unsigned long item_off;
2623         unsigned long item_len;
2624         struct inode *inode;
2625         int slot;
2626         int ret = 0;
2627 
2628         path = btrfs_alloc_path();
2629         if (!path)
2630                 return -ENOMEM;
2631 
2632         subvol_info = kzalloc(sizeof(*subvol_info), GFP_KERNEL);
2633         if (!subvol_info) {
2634                 btrfs_free_path(path);
2635                 return -ENOMEM;
2636         }
2637 
2638         inode = file_inode(file);
2639         fs_info = BTRFS_I(inode)->root->fs_info;
2640 
2641         /* Get root_item of inode's subvolume */
2642         key.objectid = BTRFS_I(inode)->root->root_key.objectid;
2643         key.type = BTRFS_ROOT_ITEM_KEY;
2644         key.offset = (u64)-1;
2645         root = btrfs_read_fs_root_no_name(fs_info, &key);
2646         if (IS_ERR(root)) {
2647                 ret = PTR_ERR(root);
2648                 goto out;
2649         }
2650         root_item = &root->root_item;
2651 
2652         subvol_info->treeid = key.objectid;
2653 
2654         subvol_info->generation = btrfs_root_generation(root_item);
2655         subvol_info->flags = btrfs_root_flags(root_item);
2656 
2657         memcpy(subvol_info->uuid, root_item->uuid, BTRFS_UUID_SIZE);
2658         memcpy(subvol_info->parent_uuid, root_item->parent_uuid,
2659                                                     BTRFS_UUID_SIZE);
2660         memcpy(subvol_info->received_uuid, root_item->received_uuid,
2661                                                     BTRFS_UUID_SIZE);
2662 
2663         subvol_info->ctransid = btrfs_root_ctransid(root_item);
2664         subvol_info->ctime.sec = btrfs_stack_timespec_sec(&root_item->ctime);
2665         subvol_info->ctime.nsec = btrfs_stack_timespec_nsec(&root_item->ctime);
2666 
2667         subvol_info->otransid = btrfs_root_otransid(root_item);
2668         subvol_info->otime.sec = btrfs_stack_timespec_sec(&root_item->otime);
2669         subvol_info->otime.nsec = btrfs_stack_timespec_nsec(&root_item->otime);
2670 
2671         subvol_info->stransid = btrfs_root_stransid(root_item);
2672         subvol_info->stime.sec = btrfs_stack_timespec_sec(&root_item->stime);
2673         subvol_info->stime.nsec = btrfs_stack_timespec_nsec(&root_item->stime);
2674 
2675         subvol_info->rtransid = btrfs_root_rtransid(root_item);
2676         subvol_info->rtime.sec = btrfs_stack_timespec_sec(&root_item->rtime);
2677         subvol_info->rtime.nsec = btrfs_stack_timespec_nsec(&root_item->rtime);
2678 
2679         if (key.objectid != BTRFS_FS_TREE_OBJECTID) {
2680                 /* Search root tree for ROOT_BACKREF of this subvolume */
2681                 root = fs_info->tree_root;
2682 
2683                 key.type = BTRFS_ROOT_BACKREF_KEY;
2684                 key.offset = 0;
2685                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2686                 if (ret < 0) {
2687                         goto out;
2688                 } else if (path->slots[0] >=
2689                            btrfs_header_nritems(path->nodes[0])) {
2690                         ret = btrfs_next_leaf(root, path);
2691                         if (ret < 0) {
2692                                 goto out;
2693                         } else if (ret > 0) {
2694                                 ret = -EUCLEAN;
2695                                 goto out;
2696                         }
2697                 }
2698 
2699                 leaf = path->nodes[0];
2700                 slot = path->slots[0];
2701                 btrfs_item_key_to_cpu(leaf, &key, slot);
2702                 if (key.objectid == subvol_info->treeid &&
2703                     key.type == BTRFS_ROOT_BACKREF_KEY) {
2704                         subvol_info->parent_id = key.offset;
2705 
2706                         rref = btrfs_item_ptr(leaf, slot, struct btrfs_root_ref);
2707                         subvol_info->dirid = btrfs_root_ref_dirid(leaf, rref);
2708 
2709                         item_off = btrfs_item_ptr_offset(leaf, slot)
2710                                         + sizeof(struct btrfs_root_ref);
2711                         item_len = btrfs_item_size_nr(leaf, slot)
2712                                         - sizeof(struct btrfs_root_ref);
2713                         read_extent_buffer(leaf, subvol_info->name,
2714                                            item_off, item_len);
2715                 } else {
2716                         ret = -ENOENT;
2717                         goto out;
2718                 }
2719         }
2720 
2721         if (copy_to_user(argp, subvol_info, sizeof(*subvol_info)))
2722                 ret = -EFAULT;
2723 
2724 out:
2725         btrfs_free_path(path);
2726         kzfree(subvol_info);
2727         return ret;
2728 }
2729 
2730 /*
2731  * Return ROOT_REF information of the subvolume containing this inode
2732  * except the subvolume name.
2733  */
2734 static int btrfs_ioctl_get_subvol_rootref(struct file *file, void __user *argp)
2735 {
2736         struct btrfs_ioctl_get_subvol_rootref_args *rootrefs;
2737         struct btrfs_root_ref *rref;
2738         struct btrfs_root *root;
2739         struct btrfs_path *path;
2740         struct btrfs_key key;
2741         struct extent_buffer *leaf;
2742         struct inode *inode;
2743         u64 objectid;
2744         int slot;
2745         int ret;
2746         u8 found;
2747 
2748         path = btrfs_alloc_path();
2749         if (!path)
2750                 return -ENOMEM;
2751 
2752         rootrefs = memdup_user(argp, sizeof(*rootrefs));
2753         if (IS_ERR(rootrefs)) {
2754                 btrfs_free_path(path);
2755                 return PTR_ERR(rootrefs);
2756         }
2757 
2758         inode = file_inode(file);
2759         root = BTRFS_I(inode)->root->fs_info->tree_root;
2760         objectid = BTRFS_I(inode)->root->root_key.objectid;
2761 
2762         key.objectid = objectid;
2763         key.type = BTRFS_ROOT_REF_KEY;
2764         key.offset = rootrefs->min_treeid;
2765         found = 0;
2766 
2767         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2768         if (ret < 0) {
2769                 goto out;
2770         } else if (path->slots[0] >=
2771                    btrfs_header_nritems(path->nodes[0])) {
2772                 ret = btrfs_next_leaf(root, path);
2773                 if (ret < 0) {
2774                         goto out;
2775                 } else if (ret > 0) {
2776                         ret = -EUCLEAN;
2777                         goto out;
2778                 }
2779         }
2780         while (1) {
2781                 leaf = path->nodes[0];
2782                 slot = path->slots[0];
2783 
2784                 btrfs_item_key_to_cpu(leaf, &key, slot);
2785                 if (key.objectid != objectid || key.type != BTRFS_ROOT_REF_KEY) {
2786                         ret = 0;
2787                         goto out;
2788                 }
2789 
2790                 if (found == BTRFS_MAX_ROOTREF_BUFFER_NUM) {
2791                         ret = -EOVERFLOW;
2792                         goto out;
2793                 }
2794 
2795                 rref = btrfs_item_ptr(leaf, slot, struct btrfs_root_ref);
2796                 rootrefs->rootref[found].treeid = key.offset;
2797                 rootrefs->rootref[found].dirid =
2798                                   btrfs_root_ref_dirid(leaf, rref);
2799                 found++;
2800 
2801                 ret = btrfs_next_item(root, path);
2802                 if (ret < 0) {
2803                         goto out;
2804                 } else if (ret > 0) {
2805                         ret = -EUCLEAN;
2806                         goto out;
2807                 }
2808         }
2809 
2810 out:
2811         if (!ret || ret == -EOVERFLOW) {
2812                 rootrefs->num_items = found;
2813                 /* update min_treeid for next search */
2814                 if (found)
2815                         rootrefs->min_treeid =
2816                                 rootrefs->rootref[found - 1].treeid + 1;
2817                 if (copy_to_user(argp, rootrefs, sizeof(*rootrefs)))
2818                         ret = -EFAULT;
2819         }
2820 
2821         kfree(rootrefs);
2822         btrfs_free_path(path);
2823 
2824         return ret;
2825 }
2826 
2827 static noinline int btrfs_ioctl_snap_destroy(struct file *file,
2828                                              void __user *arg)
2829 {
2830         struct dentry *parent = file->f_path.dentry;
2831         struct btrfs_fs_info *fs_info = btrfs_sb(parent->d_sb);
2832         struct dentry *dentry;
2833         struct inode *dir = d_inode(parent);
2834         struct inode *inode;
2835         struct btrfs_root *root = BTRFS_I(dir)->root;
2836         struct btrfs_root *dest = NULL;
2837         struct btrfs_ioctl_vol_args *vol_args;
2838         int namelen;
2839         int err = 0;
2840 
2841         if (!S_ISDIR(dir->i_mode))
2842                 return -ENOTDIR;
2843 
2844         vol_args = memdup_user(arg, sizeof(*vol_args));
2845         if (IS_ERR(vol_args))
2846                 return PTR_ERR(vol_args);
2847 
2848         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
2849         namelen = strlen(vol_args->name);
2850         if (strchr(vol_args->name, '/') ||
2851             strncmp(vol_args->name, "..", namelen) == 0) {
2852                 err = -EINVAL;
2853                 goto out;
2854         }
2855 
2856         err = mnt_want_write_file(file);
2857         if (err)
2858                 goto out;
2859 
2860 
2861         err = down_write_killable_nested(&dir->i_rwsem, I_MUTEX_PARENT);
2862         if (err == -EINTR)
2863                 goto out_drop_write;
2864         dentry = lookup_one_len(vol_args->name, parent, namelen);
2865         if (IS_ERR(dentry)) {
2866                 err = PTR_ERR(dentry);
2867                 goto out_unlock_dir;
2868         }
2869 
2870         if (d_really_is_negative(dentry)) {
2871                 err = -ENOENT;
2872                 goto out_dput;
2873         }
2874 
2875         inode = d_inode(dentry);
2876         dest = BTRFS_I(inode)->root;
2877         if (!capable(CAP_SYS_ADMIN)) {
2878                 /*
2879                  * Regular user.  Only allow this with a special mount
2880                  * option, when the user has write+exec access to the
2881                  * subvol root, and when rmdir(2) would have been
2882                  * allowed.
2883                  *
2884                  * Note that this is _not_ check that the subvol is
2885                  * empty or doesn't contain data that we wouldn't
2886                  * otherwise be able to delete.
2887                  *
2888                  * Users who want to delete empty subvols should try
2889                  * rmdir(2).
2890                  */
2891                 err = -EPERM;
2892                 if (!btrfs_test_opt(fs_info, USER_SUBVOL_RM_ALLOWED))
2893                         goto out_dput;
2894 
2895                 /*
2896                  * Do not allow deletion if the parent dir is the same
2897                  * as the dir to be deleted.  That means the ioctl
2898                  * must be called on the dentry referencing the root
2899                  * of the subvol, not a random directory contained
2900                  * within it.
2901                  */
2902                 err = -EINVAL;
2903                 if (root == dest)
2904                         goto out_dput;
2905 
2906                 err = inode_permission(inode, MAY_WRITE | MAY_EXEC);
2907                 if (err)
2908                         goto out_dput;
2909         }
2910 
2911         /* check if subvolume may be deleted by a user */
2912         err = btrfs_may_delete(dir, dentry, 1);
2913         if (err)
2914                 goto out_dput;
2915 
2916         if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
2917                 err = -EINVAL;
2918                 goto out_dput;
2919         }
2920 
2921         inode_lock(inode);
2922         err = btrfs_delete_subvolume(dir, dentry);
2923         inode_unlock(inode);
2924         if (!err)
2925                 d_delete(dentry);
2926 
2927 out_dput:
2928         dput(dentry);
2929 out_unlock_dir:
2930         inode_unlock(dir);
2931 out_drop_write:
2932         mnt_drop_write_file(file);
2933 out:
2934         kfree(vol_args);
2935         return err;
2936 }
2937 
2938 static int btrfs_ioctl_defrag(struct file *file, void __user *argp)
2939 {
2940         struct inode *inode = file_inode(file);
2941         struct btrfs_root *root = BTRFS_I(inode)->root;
2942         struct btrfs_ioctl_defrag_range_args *range;
2943         int ret;
2944 
2945         ret = mnt_want_write_file(file);
2946         if (ret)
2947                 return ret;
2948 
2949         if (btrfs_root_readonly(root)) {
2950                 ret = -EROFS;
2951                 goto out;
2952         }
2953 
2954         switch (inode->i_mode & S_IFMT) {
2955         case S_IFDIR:
2956                 if (!capable(CAP_SYS_ADMIN)) {
2957                         ret = -EPERM;
2958                         goto out;
2959                 }
2960                 ret = btrfs_defrag_root(root);
2961                 break;
2962         case S_IFREG:
2963                 if (!(file->f_mode & FMODE_WRITE)) {
2964                         ret = -EINVAL;
2965                         goto out;
2966                 }
2967 
2968                 range = kzalloc(sizeof(*range), GFP_KERNEL);
2969                 if (!range) {
2970                         ret = -ENOMEM;
2971                         goto out;
2972                 }
2973 
2974                 if (argp) {
2975                         if (copy_from_user(range, argp,
2976                                            sizeof(*range))) {
2977                                 ret = -EFAULT;
2978                                 kfree(range);
2979                                 goto out;
2980                         }
2981                         /* compression requires us to start the IO */
2982                         if ((range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)) {
2983                                 range->flags |= BTRFS_DEFRAG_RANGE_START_IO;
2984                                 range->extent_thresh = (u32)-1;
2985                         }
2986                 } else {
2987                         /* the rest are all set to zero by kzalloc */
2988                         range->len = (u64)-1;
2989                 }
2990                 ret = btrfs_defrag_file(file_inode(file), file,
2991                                         range, BTRFS_OLDEST_GENERATION, 0);
2992                 if (ret > 0)
2993                         ret = 0;
2994                 kfree(range);
2995                 break;
2996         default:
2997                 ret = -EINVAL;
2998         }
2999 out:
3000         mnt_drop_write_file(file);
3001         return ret;
3002 }
3003 
3004 static long btrfs_ioctl_add_dev(struct btrfs_fs_info *fs_info, void __user *arg)
3005 {
3006         struct btrfs_ioctl_vol_args *vol_args;
3007         int ret;
3008 
3009         if (!capable(CAP_SYS_ADMIN))
3010                 return -EPERM;
3011 
3012         if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags))
3013                 return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
3014 
3015         vol_args = memdup_user(arg, sizeof(*vol_args));
3016         if (IS_ERR(vol_args)) {
3017                 ret = PTR_ERR(vol_args);
3018                 goto out;
3019         }
3020 
3021         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
3022         ret = btrfs_init_new_device(fs_info, vol_args->name);
3023 
3024         if (!ret)
3025                 btrfs_info(fs_info, "disk added %s", vol_args->name);
3026 
3027         kfree(vol_args);
3028 out:
3029         clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
3030         return ret;
3031 }
3032 
3033 static long btrfs_ioctl_rm_dev_v2(struct file *file, void __user *arg)
3034 {
3035         struct inode *inode = file_inode(file);
3036         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3037         struct btrfs_ioctl_vol_args_v2 *vol_args;
3038         int ret;
3039 
3040         if (!capable(CAP_SYS_ADMIN))
3041                 return -EPERM;
3042 
3043         ret = mnt_want_write_file(file);
3044         if (ret)
3045                 return ret;
3046 
3047         vol_args = memdup_user(arg, sizeof(*vol_args));
3048         if (IS_ERR(vol_args)) {
3049                 ret = PTR_ERR(vol_args);
3050                 goto err_drop;
3051         }
3052 
3053         /* Check for compatibility reject unknown flags */
3054         if (vol_args->flags & ~BTRFS_VOL_ARG_V2_FLAGS_SUPPORTED) {
3055                 ret = -EOPNOTSUPP;
3056                 goto out;
3057         }
3058 
3059         if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
3060                 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
3061                 goto out;
3062         }
3063 
3064         if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID) {
3065                 ret = btrfs_rm_device(fs_info, NULL, vol_args->devid);
3066         } else {
3067                 vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0';
3068                 ret = btrfs_rm_device(fs_info, vol_args->name, 0);
3069         }
3070         clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
3071 
3072         if (!ret) {
3073                 if (vol_args->flags & BTRFS_DEVICE_SPEC_BY_ID)
3074                         btrfs_info(fs_info, "device deleted: id %llu",
3075                                         vol_args->devid);
3076                 else
3077                         btrfs_info(fs_info, "device deleted: %s",
3078                                         vol_args->name);
3079         }
3080 out:
3081         kfree(vol_args);
3082 err_drop:
3083         mnt_drop_write_file(file);
3084         return ret;
3085 }
3086 
3087 static long btrfs_ioctl_rm_dev(struct file *file, void __user *arg)
3088 {
3089         struct inode *inode = file_inode(file);
3090         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3091         struct btrfs_ioctl_vol_args *vol_args;
3092         int ret;
3093 
3094         if (!capable(CAP_SYS_ADMIN))
3095                 return -EPERM;
3096 
3097         ret = mnt_want_write_file(file);
3098         if (ret)
3099                 return ret;
3100 
3101         if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
3102                 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
3103                 goto out_drop_write;
3104         }
3105 
3106         vol_args = memdup_user(arg, sizeof(*vol_args));
3107         if (IS_ERR(vol_args)) {
3108                 ret = PTR_ERR(vol_args);
3109                 goto out;
3110         }
3111 
3112         vol_args->name[BTRFS_PATH_NAME_MAX] = '\0';
3113         ret = btrfs_rm_device(fs_info, vol_args->name, 0);
3114 
3115         if (!ret)
3116                 btrfs_info(fs_info, "disk deleted %s", vol_args->name);
3117         kfree(vol_args);
3118 out:
3119         clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
3120 out_drop_write:
3121         mnt_drop_write_file(file);
3122 
3123         return ret;
3124 }
3125 
3126 static long btrfs_ioctl_fs_info(struct btrfs_fs_info *fs_info,
3127                                 void __user *arg)
3128 {
3129         struct btrfs_ioctl_fs_info_args *fi_args;
3130         struct btrfs_device *device;
3131         struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
3132         int ret = 0;
3133 
3134         fi_args = kzalloc(sizeof(*fi_args), GFP_KERNEL);
3135         if (!fi_args)
3136                 return -ENOMEM;
3137 
3138         rcu_read_lock();
3139         fi_args->num_devices = fs_devices->num_devices;
3140 
3141         list_for_each_entry_rcu(device, &fs_devices->devices, dev_list) {
3142                 if (device->devid > fi_args->max_id)
3143                         fi_args->max_id = device->devid;
3144         }
3145         rcu_read_unlock();
3146 
3147         memcpy(&fi_args->fsid, fs_info->fsid, sizeof(fi_args->fsid));
3148         fi_args->nodesize = fs_info->nodesize;
3149         fi_args->sectorsize = fs_info->sectorsize;
3150         fi_args->clone_alignment = fs_info->sectorsize;
3151 
3152         if (copy_to_user(arg, fi_args, sizeof(*fi_args)))
3153                 ret = -EFAULT;
3154 
3155         kfree(fi_args);
3156         return ret;
3157 }
3158 
3159 static long btrfs_ioctl_dev_info(struct btrfs_fs_info *fs_info,
3160                                  void __user *arg)
3161 {
3162         struct btrfs_ioctl_dev_info_args *di_args;
3163         struct btrfs_device *dev;
3164         int ret = 0;
3165         char *s_uuid = NULL;
3166 
3167         di_args = memdup_user(arg, sizeof(*di_args));
3168         if (IS_ERR(di_args))
3169                 return PTR_ERR(di_args);
3170 
3171         if (!btrfs_is_empty_uuid(di_args->uuid))
3172                 s_uuid = di_args->uuid;
3173 
3174         rcu_read_lock();
3175         dev = btrfs_find_device(fs_info, di_args->devid, s_uuid, NULL);
3176 
3177         if (!dev) {
3178                 ret = -ENODEV;
3179                 goto out;
3180         }
3181 
3182         di_args->devid = dev->devid;
3183         di_args->bytes_used = btrfs_device_get_bytes_used(dev);
3184         di_args->total_bytes = btrfs_device_get_total_bytes(dev);
3185         memcpy(di_args->uuid, dev->uuid, sizeof(di_args->uuid));
3186         if (dev->name) {
3187                 struct rcu_string *name;
3188 
3189                 name = rcu_dereference(dev->name);
3190                 strncpy(di_args->path, name->str, sizeof(di_args->path) - 1);
3191                 di_args->path[sizeof(di_args->path) - 1] = 0;
3192         } else {
3193                 di_args->path[0] = '\0';
3194         }
3195 
3196 out:
3197         rcu_read_unlock();
3198         if (ret == 0 && copy_to_user(arg, di_args, sizeof(*di_args)))
3199                 ret = -EFAULT;
3200 
3201         kfree(di_args);
3202         return ret;
3203 }
3204 
3205 static struct page *extent_same_get_page(struct inode *inode, pgoff_t index)
3206 {
3207         struct page *page;
3208 
3209         page = grab_cache_page(inode->i_mapping, index);
3210         if (!page)
3211                 return ERR_PTR(-ENOMEM);
3212 
3213         if (!PageUptodate(page)) {
3214                 int ret;
3215 
3216                 ret = btrfs_readpage(NULL, page);
3217                 if (ret)
3218                         return ERR_PTR(ret);
3219                 lock_page(page);
3220                 if (!PageUptodate(page)) {
3221                         unlock_page(page);
3222                         put_page(page);
3223                         return ERR_PTR(-EIO);
3224                 }
3225                 if (page->mapping != inode->i_mapping) {
3226                         unlock_page(page);
3227                         put_page(page);
3228                         return ERR_PTR(-EAGAIN);
3229                 }
3230         }
3231 
3232         return page;
3233 }
3234 
3235 static int gather_extent_pages(struct inode *inode, struct page **pages,
3236                                int num_pages, u64 off)
3237 {
3238         int i;
3239         pgoff_t index = off >> PAGE_SHIFT;
3240 
3241         for (i = 0; i < num_pages; i++) {
3242 again:
3243                 pages[i] = extent_same_get_page(inode, index + i);
3244                 if (IS_ERR(pages[i])) {
3245                         int err = PTR_ERR(pages[i]);
3246 
3247                         if (err == -EAGAIN)
3248                                 goto again;
3249                         pages[i] = NULL;
3250                         return err;
3251                 }
3252         }
3253         return 0;
3254 }
3255 
3256 static int lock_extent_range(struct inode *inode, u64 off, u64 len,
3257                              bool retry_range_locking)
3258 {
3259         /*
3260          * Do any pending delalloc/csum calculations on inode, one way or
3261          * another, and lock file content.
3262          * The locking order is:
3263          *
3264          *   1) pages
3265          *   2) range in the inode's io tree
3266          */
3267         while (1) {
3268                 struct btrfs_ordered_extent *ordered;
3269                 lock_extent(&BTRFS_I(inode)->io_tree, off, off + len - 1);
3270                 ordered = btrfs_lookup_first_ordered_extent(inode,
3271                                                             off + len - 1);
3272                 if ((!ordered ||
3273                      ordered->file_offset + ordered->len <= off ||
3274                      ordered->file_offset >= off + len) &&
3275                     !test_range_bit(&BTRFS_I(inode)->io_tree, off,
3276                                     off + len - 1, EXTENT_DELALLOC, 0, NULL)) {
3277                         if (ordered)
3278                                 btrfs_put_ordered_extent(ordered);
3279                         break;
3280                 }
3281                 unlock_extent(&BTRFS_I(inode)->io_tree, off, off + len - 1);
3282                 if (ordered)
3283                         btrfs_put_ordered_extent(ordered);
3284                 if (!retry_range_locking)
3285                         return -EAGAIN;
3286                 btrfs_wait_ordered_range(inode, off, len);
3287         }
3288         return 0;
3289 }
3290 
3291 static void btrfs_double_inode_unlock(struct inode *inode1, struct inode *inode2)
3292 {
3293         inode_unlock(inode1);
3294         inode_unlock(inode2);
3295 }
3296 
3297 static void btrfs_double_inode_lock(struct inode *inode1, struct inode *inode2)
3298 {
3299         if (inode1 < inode2)
3300                 swap(inode1, inode2);
3301 
3302         inode_lock_nested(inode1, I_MUTEX_PARENT);
3303         inode_lock_nested(inode2, I_MUTEX_CHILD);
3304 }
3305 
3306 static void btrfs_double_extent_unlock(struct inode *inode1, u64 loff1,
3307                                       struct inode *inode2, u64 loff2, u64 len)
3308 {
3309         unlock_extent(&BTRFS_I(inode1)->io_tree, loff1, loff1 + len - 1);
3310         unlock_extent(&BTRFS_I(inode2)->io_tree, loff2, loff2 + len - 1);
3311 }
3312 
3313 static int btrfs_double_extent_lock(struct inode *inode1, u64 loff1,
3314                                     struct inode *inode2, u64 loff2, u64 len,
3315                                     bool retry_range_locking)
3316 {
3317         int ret;
3318 
3319         if (inode1 < inode2) {
3320                 swap(inode1, inode2);
3321                 swap(loff1, loff2);
3322         }
3323         ret = lock_extent_range(inode1, loff1, len, retry_range_locking);
3324         if (ret)
3325                 return ret;
3326         ret = lock_extent_range(inode2, loff2, len, retry_range_locking);
3327         if (ret)
3328                 unlock_extent(&BTRFS_I(inode1)->io_tree, loff1,
3329                               loff1 + len - 1);
3330         return ret;
3331 }
3332 
3333 struct cmp_pages {
3334         int             num_pages;
3335         struct page     **src_pages;
3336         struct page     **dst_pages;
3337 };
3338 
3339 static void btrfs_cmp_data_free(struct cmp_pages *cmp)
3340 {
3341         int i;
3342         struct page *pg;
3343 
3344         for (i = 0; i < cmp->num_pages; i++) {
3345                 pg = cmp->src_pages[i];
3346                 if (pg) {
3347                         unlock_page(pg);
3348                         put_page(pg);
3349                         cmp->src_pages[i] = NULL;
3350                 }
3351                 pg = cmp->dst_pages[i];
3352                 if (pg) {
3353                         unlock_page(pg);
3354                         put_page(pg);
3355                         cmp->dst_pages[i] = NULL;
3356                 }
3357         }
3358 }
3359 
3360 static int btrfs_cmp_data_prepare(struct inode *src, u64 loff,
3361                                   struct inode *dst, u64 dst_loff,
3362                                   u64 len, struct cmp_pages *cmp)
3363 {
3364         int ret;
3365         int num_pages = PAGE_ALIGN(len) >> PAGE_SHIFT;
3366 
3367         cmp->num_pages = num_pages;
3368 
3369         ret = gather_extent_pages(src, cmp->src_pages, num_pages, loff);
3370         if (ret)
3371                 goto out;
3372 
3373         ret = gather_extent_pages(dst, cmp->dst_pages, num_pages, dst_loff);
3374 
3375 out:
3376         if (ret)
3377                 btrfs_cmp_data_free(cmp);
3378         return ret;
3379 }
3380 
3381 static int btrfs_cmp_data(u64 len, struct cmp_pages *cmp)
3382 {
3383         int ret = 0;
3384         int i;
3385         struct page *src_page, *dst_page;
3386         unsigned int cmp_len = PAGE_SIZE;
3387         void *addr, *dst_addr;
3388 
3389         i = 0;
3390         while (len) {
3391                 if (len < PAGE_SIZE)
3392                         cmp_len = len;
3393 
3394                 BUG_ON(i >= cmp->num_pages);
3395 
3396                 src_page = cmp->src_pages[i];
3397                 dst_page = cmp->dst_pages[i];
3398                 ASSERT(PageLocked(src_page));
3399                 ASSERT(PageLocked(dst_page));
3400 
3401                 addr = kmap_atomic(src_page);
3402                 dst_addr = kmap_atomic(dst_page);
3403 
3404                 flush_dcache_page(src_page);
3405                 flush_dcache_page(dst_page);
3406 
3407                 if (memcmp(addr, dst_addr, cmp_len))
3408                         ret = -EBADE;
3409 
3410                 kunmap_atomic(addr);
3411                 kunmap_atomic(dst_addr);
3412 
3413                 if (ret)
3414                         break;
3415 
3416                 len -= cmp_len;
3417                 i++;
3418         }
3419 
3420         return ret;
3421 }
3422 
3423 static int extent_same_check_offsets(struct inode *inode, u64 off, u64 *plen,
3424                                      u64 olen)
3425 {
3426         u64 len = *plen;
3427         u64 bs = BTRFS_I(inode)->root->fs_info->sb->s_blocksize;
3428 
3429         if (off + olen > inode->i_size || off + olen < off)
3430                 return -EINVAL;
3431 
3432         /* if we extend to eof, continue to block boundary */
3433         if (off + len == inode->i_size)
3434                 *plen = len = ALIGN(inode->i_size, bs) - off;
3435 
3436         /* Check that we are block aligned - btrfs_clone() requires this */
3437         if (!IS_ALIGNED(off, bs) || !IS_ALIGNED(off + len, bs))
3438                 return -EINVAL;
3439 
3440         return 0;
3441 }
3442 
3443 static int btrfs_extent_same_range(struct inode *src, u64 loff, u64 olen,
3444                                    struct inode *dst, u64 dst_loff,
3445                                    struct cmp_pages *cmp)
3446 {
3447         int ret;
3448         u64 len = olen;
3449         bool same_inode = (src == dst);
3450         u64 same_lock_start = 0;
3451         u64 same_lock_len = 0;
3452 
3453         ret = extent_same_check_offsets(src, loff, &len, olen);
3454         if (ret)
3455                 return ret;
3456 
3457         ret = extent_same_check_offsets(dst, dst_loff, &len, olen);
3458         if (ret)
3459                 return ret;
3460 
3461         if (same_inode) {
3462                 /*
3463                  * Single inode case wants the same checks, except we
3464                  * don't want our length pushed out past i_size as
3465                  * comparing that data range makes no sense.
3466                  *
3467                  * extent_same_check_offsets() will do this for an
3468                  * unaligned length at i_size, so catch it here and
3469                  * reject the request.
3470                  *
3471                  * This effectively means we require aligned extents
3472                  * for the single-inode case, whereas the other cases
3473                  * allow an unaligned length so long as it ends at
3474                  * i_size.
3475                  */
3476                 if (len != olen)
3477                         return -EINVAL;
3478 
3479                 /* Check for overlapping ranges */
3480                 if (dst_loff + len > loff && dst_loff < loff + len)
3481                         return -EINVAL;
3482 
3483                 same_lock_start = min_t(u64, loff, dst_loff);
3484                 same_lock_len = max_t(u64, loff, dst_loff) + len - same_lock_start;
3485         } else {
3486                 /*
3487                  * If the source and destination inodes are different, the
3488                  * source's range end offset matches the source's i_size, that
3489                  * i_size is not a multiple of the sector size, and the
3490                  * destination range does not go past the destination's i_size,
3491                  * we must round down the length to the nearest sector size
3492                  * multiple. If we don't do this adjustment we end replacing
3493                  * with zeroes the bytes in the range that starts at the
3494                  * deduplication range's end offset and ends at the next sector
3495                  * size multiple.
3496                  */
3497                 if (loff + olen == i_size_read(src) &&
3498                     dst_loff + len < i_size_read(dst)) {
3499                         const u64 sz = BTRFS_I(src)->root->fs_info->sectorsize;
3500 
3501                         len = round_down(i_size_read(src), sz) - loff;
3502                         if (len == 0)
3503                                 return 0;
3504                         olen = len;
3505                 }
3506         }
3507 
3508 again:
3509         ret = btrfs_cmp_data_prepare(src, loff, dst, dst_loff, olen, cmp);
3510         if (ret)
3511                 return ret;
3512 
3513         if (same_inode)
3514                 ret = lock_extent_range(src, same_lock_start, same_lock_len,
3515                                         false);
3516         else
3517                 ret = btrfs_double_extent_lock(src, loff, dst, dst_loff, len,
3518                                                false);
3519         /*
3520          * If one of the inodes has dirty pages in the respective range or
3521          * ordered extents, we need to flush dellaloc and wait for all ordered
3522          * extents in the range. We must unlock the pages and the ranges in the
3523          * io trees to avoid deadlocks when flushing delalloc (requires locking
3524          * pages) and when waiting for ordered extents to complete (they require
3525          * range locking).
3526          */
3527         if (ret == -EAGAIN) {
3528                 /*
3529                  * Ranges in the io trees already unlocked. Now unlock all
3530                  * pages before waiting for all IO to complete.
3531                  */
3532                 btrfs_cmp_data_free(cmp);
3533                 if (same_inode) {
3534                         btrfs_wait_ordered_range(src, same_lock_start,
3535                                                  same_lock_len);
3536                 } else {
3537                         btrfs_wait_ordered_range(src, loff, len);
3538                         btrfs_wait_ordered_range(dst, dst_loff, len);
3539                 }
3540                 goto again;
3541         }
3542         ASSERT(ret == 0);
3543         if (WARN_ON(ret)) {
3544                 /* ranges in the io trees already unlocked */
3545                 btrfs_cmp_data_free(cmp);
3546                 return ret;
3547         }
3548 
3549         /* pass original length for comparison so we stay within i_size */
3550         ret = btrfs_cmp_data(olen, cmp);
3551         if (ret == 0)
3552                 ret = btrfs_clone(src, dst, loff, olen, len, dst_loff, 1);
3553 
3554         if (same_inode)
3555                 unlock_extent(&BTRFS_I(src)->io_tree, same_lock_start,
3556                               same_lock_start + same_lock_len - 1);
3557         else
3558                 btrfs_double_extent_unlock(src, loff, dst, dst_loff, len);
3559 
3560         btrfs_cmp_data_free(cmp);
3561 
3562         return ret;
3563 }
3564 
3565 #define BTRFS_MAX_DEDUPE_LEN    SZ_16M
3566 
3567 static int btrfs_extent_same(struct inode *src, u64 loff, u64 olen,
3568                              struct inode *dst, u64 dst_loff)
3569 {
3570         int ret;
3571         struct cmp_pages cmp;
3572         int num_pages = PAGE_ALIGN(BTRFS_MAX_DEDUPE_LEN) >> PAGE_SHIFT;
3573         bool same_inode = (src == dst);
3574         u64 i, tail_len, chunk_count;
3575 
3576         if (olen == 0)
3577                 return 0;
3578 
3579         if (same_inode)
3580                 inode_lock(src);
3581         else
3582                 btrfs_double_inode_lock(src, dst);
3583 
3584         /* don't make the dst file partly checksummed */
3585         if ((BTRFS_I(src)->flags & BTRFS_INODE_NODATASUM) !=
3586             (BTRFS_I(dst)->flags & BTRFS_INODE_NODATASUM)) {
3587                 ret = -EINVAL;
3588                 goto out_unlock;
3589         }
3590 
3591         tail_len = olen % BTRFS_MAX_DEDUPE_LEN;
3592         chunk_count = div_u64(olen, BTRFS_MAX_DEDUPE_LEN);
3593         if (chunk_count == 0)
3594                 num_pages = PAGE_ALIGN(tail_len) >> PAGE_SHIFT;
3595 
3596         /*
3597          * If deduping ranges in the same inode, locking rules make it
3598          * mandatory to always lock pages in ascending order to avoid deadlocks
3599          * with concurrent tasks (such as starting writeback/delalloc).
3600          */
3601         if (same_inode && dst_loff < loff)
3602                 swap(loff, dst_loff);
3603 
3604         /*
3605          * We must gather up all the pages before we initiate our extent
3606          * locking. We use an array for the page pointers. Size of the array is
3607          * bounded by len, which is in turn bounded by BTRFS_MAX_DEDUPE_LEN.
3608          */
3609         cmp.src_pages = kvmalloc_array(num_pages, sizeof(struct page *),
3610                                        GFP_KERNEL | __GFP_ZERO);
3611         cmp.dst_pages = kvmalloc_array(num_pages, sizeof(struct page *),
3612                                        GFP_KERNEL | __GFP_ZERO);
3613         if (!cmp.src_pages || !cmp.dst_pages) {
3614                 ret = -ENOMEM;
3615                 goto out_free;
3616         }
3617 
3618         for (i = 0; i < chunk_count; i++) {
3619                 ret = btrfs_extent_same_range(src, loff, BTRFS_MAX_DEDUPE_LEN,
3620                                               dst, dst_loff, &cmp);
3621                 if (ret)
3622                         goto out_free;
3623 
3624                 loff += BTRFS_MAX_DEDUPE_LEN;
3625                 dst_loff += BTRFS_MAX_DEDUPE_LEN;
3626         }
3627 
3628         if (tail_len > 0)
3629                 ret = btrfs_extent_same_range(src, loff, tail_len, dst,
3630                                               dst_loff, &cmp);
3631 
3632 out_free:
3633         kvfree(cmp.src_pages);
3634         kvfree(cmp.dst_pages);
3635 
3636 out_unlock:
3637         if (same_inode)
3638                 inode_unlock(src);
3639         else
3640                 btrfs_double_inode_unlock(src, dst);
3641 
3642         return ret;
3643 }
3644 
3645 ssize_t btrfs_dedupe_file_range(struct file *src_file, u64 loff, u64 olen,
3646                                 struct file *dst_file, u64 dst_loff)
3647 {
3648         struct inode *src = file_inode(src_file);
3649         struct inode *dst = file_inode(dst_file);
3650         u64 bs = BTRFS_I(src)->root->fs_info->sb->s_blocksize;
3651         ssize_t res;
3652 
3653         if (WARN_ON_ONCE(bs < PAGE_SIZE)) {
3654                 /*
3655                  * Btrfs does not support blocksize < page_size. As a
3656                  * result, btrfs_cmp_data() won't correctly handle
3657                  * this situation without an update.
3658                  */
3659                 return -EINVAL;
3660         }
3661 
3662         res = btrfs_extent_same(src, loff, olen, dst, dst_loff);
3663         if (res)
3664                 return res;
3665         return olen;
3666 }
3667 
3668 static int clone_finish_inode_update(struct btrfs_trans_handle *trans,
3669                                      struct inode *inode,
3670                                      u64 endoff,
3671                                      const u64 destoff,
3672                                      const u64 olen,
3673                                      int no_time_update)
3674 {
3675         struct btrfs_root *root = BTRFS_I(inode)->root;
3676         int ret;
3677 
3678         inode_inc_iversion(inode);
3679         if (!no_time_update)
3680                 inode->i_mtime = inode->i_ctime = current_time(inode);
3681         /*
3682          * We round up to the block size at eof when determining which
3683          * extents to clone above, but shouldn't round up the file size.
3684          */
3685         if (endoff > destoff + olen)
3686                 endoff = destoff + olen;
3687         if (endoff > inode->i_size)
3688                 btrfs_i_size_write(BTRFS_I(inode), endoff);
3689 
3690         ret = btrfs_update_inode(trans, root, inode);
3691         if (ret) {
3692                 btrfs_abort_transaction(trans, ret);
3693                 btrfs_end_transaction(trans);
3694                 goto out;
3695         }
3696         ret = btrfs_end_transaction(trans);
3697 out:
3698         return ret;
3699 }
3700 
3701 static void clone_update_extent_map(struct btrfs_inode *inode,
3702                                     const struct btrfs_trans_handle *trans,
3703                                     const struct btrfs_path *path,
3704                                     const u64 hole_offset,
3705                                     const u64 hole_len)
3706 {
3707         struct extent_map_tree *em_tree = &inode->extent_tree;
3708         struct extent_map *em;
3709         int ret;
3710 
3711         em = alloc_extent_map();
3712         if (!em) {
3713                 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags);
3714                 return;
3715         }
3716 
3717         if (path) {
3718                 struct btrfs_file_extent_item *fi;
3719 
3720                 fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
3721                                     struct btrfs_file_extent_item);
3722                 btrfs_extent_item_to_extent_map(inode, path, fi, false, em);
3723                 em->generation = -1;
3724                 if (btrfs_file_extent_type(path->nodes[0], fi) ==
3725                     BTRFS_FILE_EXTENT_INLINE)
3726                         set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3727                                         &inode->runtime_flags);
3728         } else {
3729                 em->start = hole_offset;
3730                 em->len = hole_len;
3731                 em->ram_bytes = em->len;
3732                 em->orig_start = hole_offset;
3733                 em->block_start = EXTENT_MAP_HOLE;
3734                 em->block_len = 0;
3735                 em->orig_block_len = 0;
3736                 em->compress_type = BTRFS_COMPRESS_NONE;
3737                 em->generation = trans->transid;
3738         }
3739 
3740         while (1) {
3741                 write_lock(&em_tree->lock);
3742                 ret = add_extent_mapping(em_tree, em, 1);
3743                 write_unlock(&em_tree->lock);
3744                 if (ret != -EEXIST) {
3745                         free_extent_map(em);
3746                         break;
3747                 }
3748                 btrfs_drop_extent_cache(inode, em->start,
3749                                         em->start + em->len - 1, 0);
3750         }
3751 
3752         if (ret)
3753                 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags);
3754 }
3755 
3756 /*
3757  * Make sure we do not end up inserting an inline extent into a file that has
3758  * already other (non-inline) extents. If a file has an inline extent it can
3759  * not have any other extents and the (single) inline extent must start at the
3760  * file offset 0. Failing to respect these rules will lead to file corruption,
3761  * resulting in EIO errors on read/write operations, hitting BUG_ON's in mm, etc
3762  *
3763  * We can have extents that have been already written to disk or we can have
3764  * dirty ranges still in delalloc, in which case the extent maps and items are
3765  * created only when we run delalloc, and the delalloc ranges might fall outside
3766  * the range we are currently locking in the inode's io tree. So we check the
3767  * inode's i_size because of that (i_size updates are done while holding the
3768  * i_mutex, which we are holding here).
3769  * We also check to see if the inode has a size not greater than "datal" but has
3770  * extents beyond it, due to an fallocate with FALLOC_FL_KEEP_SIZE (and we are
3771  * protected against such concurrent fallocate calls by the i_mutex).
3772  *
3773  * If the file has no extents but a size greater than datal, do not allow the
3774  * copy because we would need turn the inline extent into a non-inline one (even
3775  * with NO_HOLES enabled). If we find our destination inode only has one inline
3776  * extent, just overwrite it with the source inline extent if its size is less
3777  * than the source extent's size, or we could copy the source inline extent's
3778  * data into the destination inode's inline extent if the later is greater then
3779  * the former.
3780  */
3781 static int clone_copy_inline_extent(struct inode *dst,
3782                                     struct btrfs_trans_handle *trans,
3783                                     struct btrfs_path *path,
3784                                     struct btrfs_key *new_key,
3785                                     const u64 drop_start,
3786                                     const u64 datal,
3787                                     const u64 skip,
3788                                     const u64 size,
3789                                     char *inline_data)
3790 {
3791         struct btrfs_fs_info *fs_info = btrfs_sb(dst->i_sb);
3792         struct btrfs_root *root = BTRFS_I(dst)->root;
3793         const u64 aligned_end = ALIGN(new_key->offset + datal,
3794                                       fs_info->sectorsize);
3795         int ret;
3796         struct btrfs_key key;
3797 
3798         if (new_key->offset > 0)
3799                 return -EOPNOTSUPP;
3800 
3801         key.objectid = btrfs_ino(BTRFS_I(dst));
3802         key.type = BTRFS_EXTENT_DATA_KEY;
3803         key.offset = 0;
3804         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3805         if (ret < 0) {
3806                 return ret;
3807         } else if (ret > 0) {
3808                 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
3809                         ret = btrfs_next_leaf(root, path);
3810                         if (ret < 0)
3811                                 return ret;
3812                         else if (ret > 0)
3813                                 goto copy_inline_extent;
3814                 }
3815                 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
3816                 if (key.objectid == btrfs_ino(BTRFS_I(dst)) &&
3817                     key.type == BTRFS_EXTENT_DATA_KEY) {
3818                         ASSERT(key.offset > 0);
3819                         return -EOPNOTSUPP;
3820                 }
3821         } else if (i_size_read(dst) <= datal) {
3822                 struct btrfs_file_extent_item *ei;
3823                 u64 ext_len;
3824 
3825                 /*
3826                  * If the file size is <= datal, make sure there are no other
3827                  * extents following (can happen do to an fallocate call with
3828                  * the flag FALLOC_FL_KEEP_SIZE).
3829                  */
3830                 ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
3831                                     struct btrfs_file_extent_item);
3832                 /*
3833                  * If it's an inline extent, it can not have other extents
3834                  * following it.
3835                  */
3836                 if (btrfs_file_extent_type(path->nodes[0], ei) ==
3837                     BTRFS_FILE_EXTENT_INLINE)
3838                         goto copy_inline_extent;
3839 
3840                 ext_len = btrfs_file_extent_num_bytes(path->nodes[0], ei);
3841                 if (ext_len > aligned_end)
3842                         return -EOPNOTSUPP;
3843 
3844                 ret = btrfs_next_item(root, path);
3845                 if (ret < 0) {
3846                         return ret;
3847                 } else if (ret == 0) {
3848                         btrfs_item_key_to_cpu(path->nodes[0], &key,
3849                                               path->slots[0]);
3850                         if (key.objectid == btrfs_ino(BTRFS_I(dst)) &&
3851                             key.type == BTRFS_EXTENT_DATA_KEY)
3852                                 return -EOPNOTSUPP;
3853                 }
3854         }
3855 
3856 copy_inline_extent:
3857         /*
3858          * We have no extent items, or we have an extent at offset 0 which may
3859          * or may not be inlined. All these cases are dealt the same way.
3860          */
3861         if (i_size_read(dst) > datal) {
3862                 /*
3863                  * If the destination inode has an inline extent...
3864                  * This would require copying the data from the source inline
3865                  * extent into the beginning of the destination's inline extent.
3866                  * But this is really complex, both extents can be compressed
3867                  * or just one of them, which would require decompressing and
3868                  * re-compressing data (which could increase the new compressed
3869                  * size, not allowing the compressed data to fit anymore in an
3870                  * inline extent).
3871                  * So just don't support this case for now (it should be rare,
3872                  * we are not really saving space when cloning inline extents).
3873                  */
3874                 return -EOPNOTSUPP;
3875         }
3876 
3877         btrfs_release_path(path);
3878         ret = btrfs_drop_extents(trans, root, dst, drop_start, aligned_end, 1);
3879         if (ret)
3880                 return ret;
3881         ret = btrfs_insert_empty_item(trans, root, path, new_key, size);
3882         if (ret)
3883                 return ret;
3884 
3885         if (skip) {
3886                 const u32 start = btrfs_file_extent_calc_inline_size(0);
3887 
3888                 memmove(inline_data + start, inline_data + start + skip, datal);
3889         }
3890 
3891         write_extent_buffer(path->nodes[0], inline_data,
3892                             btrfs_item_ptr_offset(path->nodes[0],
3893                                                   path->slots[0]),
3894                             size);
3895         inode_add_bytes(dst, datal);
3896 
3897         return 0;
3898 }
3899 
3900 /**
3901  * btrfs_clone() - clone a range from inode file to another
3902  *
3903  * @src: Inode to clone from
3904  * @inode: Inode to clone to
3905  * @off: Offset within source to start clone from
3906  * @olen: Original length, passed by user, of range to clone
3907  * @olen_aligned: Block-aligned value of olen
3908  * @destoff: Offset within @inode to start clone
3909  * @no_time_update: Whether to update mtime/ctime on the target inode
3910  */
3911 static int btrfs_clone(struct inode *src, struct inode *inode,
3912                        const u64 off, const u64 olen, const u64 olen_aligned,
3913                        const u64 destoff, int no_time_update)
3914 {
3915         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3916         struct btrfs_root *root = BTRFS_I(inode)->root;
3917         struct btrfs_path *path = NULL;
3918         struct extent_buffer *leaf;
3919         struct btrfs_trans_handle *trans;
3920         char *buf = NULL;
3921         struct btrfs_key key;
3922         u32 nritems;
3923         int slot;
3924         int ret;
3925         const u64 len = olen_aligned;
3926         u64 last_dest_end = destoff;
3927 
3928         ret = -ENOMEM;
3929         buf = kvmalloc(fs_info->nodesize, GFP_KERNEL);
3930         if (!buf)
3931                 return ret;
3932 
3933         path = btrfs_alloc_path();
3934         if (!path) {
3935                 kvfree(buf);
3936                 return ret;
3937         }
3938 
3939         path->reada = READA_FORWARD;
3940         /* clone data */
3941         key.objectid = btrfs_ino(BTRFS_I(src));
3942         key.type = BTRFS_EXTENT_DATA_KEY;
3943         key.offset = off;
3944 
3945         while (1) {
3946                 u64 next_key_min_offset = key.offset + 1;
3947 
3948                 /*
3949                  * note the key will change type as we walk through the
3950                  * tree.
3951                  */
3952                 path->leave_spinning = 1;
3953                 ret = btrfs_search_slot(NULL, BTRFS_I(src)->root, &key, path,
3954                                 0, 0);
3955                 if (ret < 0)
3956                         goto out;
3957                 /*
3958                  * First search, if no extent item that starts at offset off was
3959                  * found but the previous item is an extent item, it's possible
3960                  * it might overlap our target range, therefore process it.
3961                  */
3962                 if (key.offset == off && ret > 0 && path->slots[0] > 0) {
3963                         btrfs_item_key_to_cpu(path->nodes[0], &key,
3964                                               path->slots[0] - 1);
3965                         if (key.type == BTRFS_EXTENT_DATA_KEY)
3966                                 path->slots[0]--;
3967                 }
3968 
3969                 nritems = btrfs_header_nritems(path->nodes[0]);
3970 process_slot:
3971                 if (path->slots[0] >= nritems) {
3972                         ret = btrfs_next_leaf(BTRFS_I(src)->root, path);
3973                         if (ret < 0)
3974                                 goto out;
3975                         if (ret > 0)
3976                                 break;
3977                         nritems = btrfs_header_nritems(path->nodes[0]);
3978                 }
3979                 leaf = path->nodes[0];
3980                 slot = path->slots[0];
3981 
3982                 btrfs_item_key_to_cpu(leaf, &key, slot);
3983                 if (key.type > BTRFS_EXTENT_DATA_KEY ||
3984                     key.objectid != btrfs_ino(BTRFS_I(src)))
3985                         break;
3986 
3987                 if (key.type == BTRFS_EXTENT_DATA_KEY) {
3988                         struct btrfs_file_extent_item *extent;
3989                         int type;
3990                         u32 size;
3991                         struct btrfs_key new_key;
3992                         u64 disko = 0, diskl = 0;
3993                         u64 datao = 0, datal = 0;
3994                         u8 comp;
3995                         u64 drop_start;
3996 
3997                         extent = btrfs_item_ptr(leaf, slot,
3998                                                 struct btrfs_file_extent_item);
3999                         comp = btrfs_file_extent_compression(leaf, extent);
4000                         type = btrfs_file_extent_type(leaf, extent);
4001                         if (type == BTRFS_FILE_EXTENT_REG ||
4002                             type == BTRFS_FILE_EXTENT_PREALLOC) {
4003                                 disko = btrfs_file_extent_disk_bytenr(leaf,
4004                                                                       extent);
4005                                 diskl = btrfs_file_extent_disk_num_bytes(leaf,
4006                                                                  extent);
4007                                 datao = btrfs_file_extent_offset(leaf, extent);
4008                                 datal = btrfs_file_extent_num_bytes(leaf,
4009                                                                     extent);
4010                         } else if (type == BTRFS_FILE_EXTENT_INLINE) {
4011                                 /* take upper bound, may be compressed */
4012                                 datal = btrfs_file_extent_ram_bytes(leaf,
4013                                                                     extent);
4014                         }
4015 
4016                         /*
4017                          * The first search might have left us at an extent
4018                          * item that ends before our target range's start, can
4019                          * happen if we have holes and NO_HOLES feature enabled.
4020                          */
4021                         if (key.offset + datal <= off) {
4022                                 path->slots[0]++;
4023                                 goto process_slot;
4024                         } else if (key.offset >= off + len) {
4025                                 break;
4026                         }
4027                         next_key_min_offset = key.offset + datal;
4028                         size = btrfs_item_size_nr(leaf, slot);
4029                         read_extent_buffer(leaf, buf,
4030                                            btrfs_item_ptr_offset(leaf, slot),
4031                                            size);
4032 
4033                         btrfs_release_path(path);
4034                         path->leave_spinning = 0;
4035 
4036                         memcpy(&new_key, &key, sizeof(new_key));
4037                         new_key.objectid = btrfs_ino(BTRFS_I(inode));
4038                         if (off <= key.offset)
4039                                 new_key.offset = key.offset + destoff - off;
4040                         else
4041                                 new_key.offset = destoff;
4042 
4043                         /*
4044                          * Deal with a hole that doesn't have an extent item
4045                          * that represents it (NO_HOLES feature enabled).
4046                          * This hole is either in the middle of the cloning
4047                          * range or at the beginning (fully overlaps it or
4048                          * partially overlaps it).
4049                          */
4050                         if (new_key.offset != last_dest_end)
4051                                 drop_start = last_dest_end;
4052                         else
4053                                 drop_start = new_key.offset;
4054 
4055                         /*
4056                          * 1 - adjusting old extent (we may have to split it)
4057                          * 1 - add new extent
4058                          * 1 - inode update
4059                          */
4060                         trans = btrfs_start_transaction(root, 3);
4061                         if (IS_ERR(trans)) {
4062                                 ret = PTR_ERR(trans);
4063                                 goto out;
4064                         }
4065 
4066                         if (type == BTRFS_FILE_EXTENT_REG ||
4067                             type == BTRFS_FILE_EXTENT_PREALLOC) {
4068                                 /*
4069                                  *    a  | --- range to clone ---|  b
4070                                  * | ------------- extent ------------- |
4071                                  */
4072 
4073                                 /* subtract range b */
4074                                 if (key.offset + datal > off + len)
4075                                         datal = off + len - key.offset;
4076 
4077                                 /* subtract range a */
4078                                 if (off > key.offset) {
4079                                         datao += off - key.offset;
4080                                         datal -= off - key.offset;
4081                                 }
4082 
4083                                 ret = btrfs_drop_extents(trans, root, inode,
4084                                                          drop_start,
4085                                                          new_key.offset + datal,
4086                                                          1);
4087                                 if (ret) {
4088                                         if (ret != -EOPNOTSUPP)
4089                                                 btrfs_abort_transaction(trans,
4090                                                                         ret);
4091                                         btrfs_end_transaction(trans);
4092                                         goto out;
4093                                 }
4094 
4095                                 ret = btrfs_insert_empty_item(trans, root, path,
4096                                                               &new_key, size);
4097                                 if (ret) {
4098                                         btrfs_abort_transaction(trans, ret);
4099                                         btrfs_end_transaction(trans);
4100                                         goto out;
4101                                 }
4102 
4103                                 leaf = path->nodes[0];
4104                                 slot = path->slots[0];
4105                                 write_extent_buffer(leaf, buf,
4106                                             btrfs_item_ptr_offset(leaf, slot),
4107                                             size);
4108 
4109                                 extent = btrfs_item_ptr(leaf, slot,
4110                                                 struct btrfs_file_extent_item);
4111 
4112                                 /* disko == 0 means it's a hole */
4113                                 if (!disko)
4114                                         datao = 0;
4115 
4116                                 btrfs_set_file_extent_offset(leaf, extent,
4117                                                              datao);
4118                                 btrfs_set_file_extent_num_bytes(leaf, extent,
4119                                                                 datal);
4120 
4121                                 if (disko) {
4122                                         inode_add_bytes(inode, datal);
4123                                         ret = btrfs_inc_extent_ref(trans,
4124                                                         root,
4125                                                         disko, diskl, 0,
4126                                                         root->root_key.objectid,
4127                                                         btrfs_ino(BTRFS_I(inode)),
4128                                                         new_key.offset - datao);
4129                                         if (ret) {
4130                                                 btrfs_abort_transaction(trans,
4131                                                                         ret);
4132                                                 btrfs_end_transaction(trans);
4133                                                 goto out;
4134 
4135                                         }
4136                                 }
4137                         } else if (type == BTRFS_FILE_EXTENT_INLINE) {
4138                                 u64 skip = 0;
4139                                 u64 trim = 0;
4140 
4141                                 if (off > key.offset) {
4142                                         skip = off - key.offset;
4143                                         new_key.offset += skip;
4144                                 }
4145 
4146                                 if (key.offset + datal > off + len)
4147                                         trim = key.offset + datal - (off + len);
4148 
4149                                 if (comp && (skip || trim)) {
4150                                         ret = -EINVAL;
4151                                         btrfs_end_transaction(trans);
4152                                         goto out;
4153                                 }
4154                                 size -= skip + trim;
4155                                 datal -= skip + trim;
4156 
4157                                 ret = clone_copy_inline_extent(inode,
4158                                                                trans, path,
4159                                                                &new_key,
4160                                                                drop_start,
4161                                                                datal,
4162                                                                skip, size, buf);
4163                                 if (ret) {
4164                                         if (ret != -EOPNOTSUPP)
4165                                                 btrfs_abort_transaction(trans,
4166                                                                         ret);
4167                                         btrfs_end_transaction(trans);
4168                                         goto out;
4169                                 }
4170                                 leaf = path->nodes[0];
4171                                 slot = path->slots[0];
4172                         }
4173 
4174                         /* If we have an implicit hole (NO_HOLES feature). */
4175                         if (drop_start < new_key.offset)
4176                                 clone_update_extent_map(BTRFS_I(inode), trans,
4177                                                 NULL, drop_start,
4178                                                 new_key.offset - drop_start);
4179 
4180                         clone_update_extent_map(BTRFS_I(inode), trans,
4181                                         path, 0, 0);
4182 
4183                         btrfs_mark_buffer_dirty(leaf);
4184                         btrfs_release_path(path);
4185 
4186                         last_dest_end = ALIGN(new_key.offset + datal,
4187                                               fs_info->sectorsize);
4188                         ret = clone_finish_inode_update(trans, inode,
4189                                                         last_dest_end,
4190                                                         destoff, olen,
4191                                                         no_time_update);
4192                         if (ret)
4193                                 goto out;
4194                         if (new_key.offset + datal >= destoff + len)
4195                                 break;
4196                 }
4197                 btrfs_release_path(path);
4198                 key.offset = next_key_min_offset;
4199 
4200                 if (fatal_signal_pending(current)) {
4201                         ret = -EINTR;
4202                         goto out;
4203                 }
4204         }
4205         ret = 0;
4206 
4207         if (last_dest_end < destoff + len) {
4208                 /*
4209                  * We have an implicit hole (NO_HOLES feature is enabled) that
4210                  * fully or partially overlaps our cloning range at its end.
4211                  */
4212                 btrfs_release_path(path);
4213 
4214                 /*
4215                  * 1 - remove extent(s)
4216                  * 1 - inode update
4217                  */
4218                 trans = btrfs_start_transaction(root, 2);
4219                 if (IS_ERR(trans)) {
4220                         ret = PTR_ERR(trans);
4221                         goto out;
4222                 }
4223                 ret = btrfs_drop_extents(trans, root, inode,
4224                                          last_dest_end, destoff + len, 1);
4225                 if (ret) {
4226                         if (ret != -EOPNOTSUPP)
4227                                 btrfs_abort_transaction(trans, ret);
4228                         btrfs_end_transaction(trans);
4229                         goto out;
4230                 }
4231                 clone_update_extent_map(BTRFS_I(inode), trans, NULL,
4232                                 last_dest_end,
4233                                 destoff + len - last_dest_end);
4234                 ret = clone_finish_inode_update(trans, inode, destoff + len,
4235                                                 destoff, olen, no_time_update);
4236         }
4237 
4238 out:
4239         btrfs_free_path(path);
4240         kvfree(buf);
4241         return ret;
4242 }
4243 
4244 static noinline int btrfs_clone_files(struct file *file, struct file *file_src,
4245                                         u64 off, u64 olen, u64 destoff)
4246 {
4247         struct inode *inode = file_inode(file);
4248         struct inode *src = file_inode(file_src);
4249         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4250         struct btrfs_root *root = BTRFS_I(inode)->root;
4251         int ret;
4252         u64 len = olen;
4253         u64 bs = fs_info->sb->s_blocksize;
4254         int same_inode = src == inode;
4255 
4256         /*
4257          * TODO:
4258          * - split compressed inline extents.  annoying: we need to
4259          *   decompress into destination's address_space (the file offset
4260          *   may change, so source mapping won't do), then recompress (or
4261          *   otherwise reinsert) a subrange.
4262          *
4263          * - split destination inode's inline extents.  The inline extents can
4264          *   be either compressed or non-compressed.
4265          */
4266 
4267         if (btrfs_root_readonly(root))
4268                 return -EROFS;
4269 
4270         if (file_src->f_path.mnt != file->f_path.mnt ||
4271             src->i_sb != inode->i_sb)
4272                 return -EXDEV;
4273 
4274         if (S_ISDIR(src->i_mode) || S_ISDIR(inode->i_mode))
4275                 return -EISDIR;
4276 
4277         if (!same_inode) {
4278                 btrfs_double_inode_lock(src, inode);
4279         } else {
4280                 inode_lock(src);
4281         }
4282 
4283         /* don't make the dst file partly checksummed */
4284         if ((BTRFS_I(src)->flags & BTRFS_INODE_NODATASUM) !=
4285             (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
4286                 ret = -EINVAL;
4287                 goto out_unlock;
4288         }
4289 
4290         /* determine range to clone */
4291         ret = -EINVAL;
4292         if (off + len > src->i_size || off + len < off)
4293                 goto out_unlock;
4294         if (len == 0)
4295                 olen = len = src->i_size - off;
4296         /*
4297          * If we extend to eof, continue to block boundary if and only if the
4298          * destination end offset matches the destination file's size, otherwise
4299          * we would be corrupting data by placing the eof block into the middle
4300          * of a file.
4301          */
4302         if (off + len == src->i_size) {
4303                 if (!IS_ALIGNED(len, bs) && destoff + len < inode->i_size)
4304                         goto out_unlock;
4305                 len = ALIGN(src->i_size, bs) - off;
4306         }
4307 
4308         if (len == 0) {
4309                 ret = 0;
4310                 goto out_unlock;
4311         }
4312 
4313         /* verify the end result is block aligned */
4314         if (!IS_ALIGNED(off, bs) || !IS_ALIGNED(off + len, bs) ||
4315             !IS_ALIGNED(destoff, bs))
4316                 goto out_unlock;
4317 
4318         /* verify if ranges are overlapped within the same file */
4319         if (same_inode) {
4320                 if (destoff + len > off && destoff < off + len)
4321                         goto out_unlock;
4322         }
4323 
4324         if (destoff > inode->i_size) {
4325                 ret = btrfs_cont_expand(inode, inode->i_size, destoff);
4326                 if (ret)
4327                         goto out_unlock;
4328         }
4329 
4330         /*
4331          * Lock the target range too. Right after we replace the file extent
4332          * items in the fs tree (which now point to the cloned data), we might
4333          * have a worker replace them with extent items relative to a write
4334          * operation that was issued before this clone operation (i.e. confront
4335          * with inode.c:btrfs_finish_ordered_io).
4336          */
4337         if (same_inode) {
4338                 u64 lock_start = min_t(u64, off, destoff);
4339                 u64 lock_len = max_t(u64, off, destoff) + len - lock_start;
4340 
4341                 ret = lock_extent_range(src, lock_start, lock_len, true);
4342         } else {
4343                 ret = btrfs_double_extent_lock(src, off, inode, destoff, len,
4344                                                true);
4345         }
4346         ASSERT(ret == 0);
4347         if (WARN_ON(ret)) {
4348                 /* ranges in the io trees already unlocked */
4349                 goto out_unlock;
4350         }
4351 
4352         ret = btrfs_clone(src, inode, off, olen, len, destoff, 0);
4353 
4354         if (same_inode) {
4355                 u64 lock_start = min_t(u64, off, destoff);
4356                 u64 lock_end = max_t(u64, off, destoff) + len - 1;
4357 
4358                 unlock_extent(&BTRFS_I(src)->io_tree, lock_start, lock_end);
4359         } else {
4360                 btrfs_double_extent_unlock(src, off, inode, destoff, len);
4361         }
4362         /*
4363          * Truncate page cache pages so that future reads will see the cloned
4364          * data immediately and not the previous data.
4365          */
4366         truncate_inode_pages_range(&inode->i_data,
4367                                 round_down(destoff, PAGE_SIZE),
4368                                 round_up(destoff + len, PAGE_SIZE) - 1);
4369 out_unlock:
4370         if (!same_inode)
4371                 btrfs_double_inode_unlock(src, inode);
4372         else
4373                 inode_unlock(src);
4374         return ret;
4375 }
4376 
4377 int btrfs_clone_file_range(struct file *src_file, loff_t off,
4378                 struct file *dst_file, loff_t destoff, u64 len)
4379 {
4380         return btrfs_clone_files(dst_file, src_file, off, len, destoff);
4381 }
4382 
4383 static long btrfs_ioctl_default_subvol(struct file *file, void __user *argp)
4384 {
4385         struct inode *inode = file_inode(file);
4386         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4387         struct btrfs_root *root = BTRFS_I(inode)->root;
4388         struct btrfs_root *new_root;
4389         struct btrfs_dir_item *di;
4390         struct btrfs_trans_handle *trans;
4391         struct btrfs_path *path;
4392         struct btrfs_key location;
4393         struct btrfs_disk_key disk_key;
4394         u64 objectid = 0;
4395         u64 dir_id;
4396         int ret;
4397 
4398         if (!capable(CAP_SYS_ADMIN))
4399                 return -EPERM;
4400 
4401         ret = mnt_want_write_file(file);
4402         if (ret)
4403                 return ret;
4404 
4405         if (copy_from_user(&objectid, argp, sizeof(objectid))) {
4406                 ret = -EFAULT;
4407                 goto out;
4408         }
4409 
4410         if (!objectid)
4411                 objectid = BTRFS_FS_TREE_OBJECTID;
4412 
4413         location.objectid = objectid;
4414         location.type = BTRFS_ROOT_ITEM_KEY;
4415         location.offset = (u64)-1;
4416 
4417         new_root = btrfs_read_fs_root_no_name(fs_info, &location);
4418         if (IS_ERR(new_root)) {
4419                 ret = PTR_ERR(new_root);
4420                 goto out;
4421         }
4422         if (!is_fstree(new_root->objectid)) {
4423                 ret = -ENOENT;
4424                 goto out;
4425         }
4426 
4427         path = btrfs_alloc_path();
4428         if (!path) {
4429                 ret = -ENOMEM;
4430                 goto out;
4431         }
4432         path->leave_spinning = 1;
4433 
4434         trans = btrfs_start_transaction(root, 1);
4435         if (IS_ERR(trans)) {
4436                 btrfs_free_path(path);
4437                 ret = PTR_ERR(trans);
4438                 goto out;
4439         }
4440 
4441         dir_id = btrfs_super_root_dir(fs_info->super_copy);
4442         di = btrfs_lookup_dir_item(trans, fs_info->tree_root, path,
4443                                    dir_id, "default", 7, 1);
4444         if (IS_ERR_OR_NULL(di)) {
4445                 btrfs_free_path(path);
4446                 btrfs_end_transaction(trans);
4447                 btrfs_err(fs_info,
4448                           "Umm, you don't have the default diritem, this isn't going to work");
4449                 ret = -ENOENT;
4450                 goto out;
4451         }
4452 
4453         btrfs_cpu_key_to_disk(&disk_key, &new_root->root_key);
4454         btrfs_set_dir_item_key(path->nodes[0], di, &disk_key);
4455         btrfs_mark_buffer_dirty(path->nodes[0]);
4456         btrfs_free_path(path);
4457 
4458         btrfs_set_fs_incompat(fs_info, DEFAULT_SUBVOL);
4459         btrfs_end_transaction(trans);
4460 out:
4461         mnt_drop_write_file(file);
4462         return ret;
4463 }
4464 
4465 static void get_block_group_info(struct list_head *groups_list,
4466                                  struct btrfs_ioctl_space_info *space)
4467 {
4468         struct btrfs_block_group_cache *block_group;
4469 
4470         space->total_bytes = 0;
4471         space->used_bytes = 0;
4472         space->flags = 0;
4473         list_for_each_entry(block_group, groups_list, list) {
4474                 space->flags = block_group->flags;
4475                 space->total_bytes += block_group->key.offset;
4476                 space->used_bytes +=
4477                         btrfs_block_group_used(&block_group->item);
4478         }
4479 }
4480 
4481 static long btrfs_ioctl_space_info(struct btrfs_fs_info *fs_info,
4482                                    void __user *arg)
4483 {
4484         struct btrfs_ioctl_space_args space_args;
4485         struct btrfs_ioctl_space_info space;
4486         struct btrfs_ioctl_space_info *dest;
4487         struct btrfs_ioctl_space_info *dest_orig;
4488         struct btrfs_ioctl_space_info __user *user_dest;
4489         struct btrfs_space_info *info;
4490         static const u64 types[] = {
4491                 BTRFS_BLOCK_GROUP_DATA,
4492                 BTRFS_BLOCK_GROUP_SYSTEM,
4493                 BTRFS_BLOCK_GROUP_METADATA,
4494                 BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA
4495         };
4496         int num_types = 4;
4497         int alloc_size;
4498         int ret = 0;
4499         u64 slot_count = 0;
4500         int i, c;
4501 
4502         if (copy_from_user(&space_args,
4503                            (struct btrfs_ioctl_space_args __user *)arg,
4504                            sizeof(space_args)))
4505                 return -EFAULT;
4506 
4507         for (i = 0; i < num_types; i++) {
4508                 struct btrfs_space_info *tmp;
4509 
4510                 info = NULL;
4511                 rcu_read_lock();
4512                 list_for_each_entry_rcu(tmp, &fs_info->space_info,
4513                                         list) {
4514                         if (tmp->flags == types[i]) {
4515                                 info = tmp;
4516                                 break;
4517                         }
4518                 }
4519                 rcu_read_unlock();
4520 
4521                 if (!info)
4522                         continue;
4523 
4524                 down_read(&info->groups_sem);
4525                 for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
4526                         if (!list_empty(&info->block_groups[c]))
4527                                 slot_count++;
4528                 }
4529                 up_read(&info->groups_sem);
4530         }
4531 
4532         /*
4533          * Global block reserve, exported as a space_info
4534          */
4535         slot_count++;
4536 
4537         /* space_slots == 0 means they are asking for a count */
4538         if (space_args.space_slots == 0) {
4539                 space_args.total_spaces = slot_count;
4540                 goto out;
4541         }
4542 
4543         slot_count = min_t(u64, space_args.space_slots, slot_count);
4544 
4545         alloc_size = sizeof(*dest) * slot_count;
4546 
4547         /* we generally have at most 6 or so space infos, one for each raid
4548          * level.  So, a whole page should be more than enough for everyone
4549          */
4550         if (alloc_size > PAGE_SIZE)
4551                 return -ENOMEM;
4552 
4553         space_args.total_spaces = 0;
4554         dest = kmalloc(alloc_size, GFP_KERNEL);
4555         if (!dest)
4556                 return -ENOMEM;
4557         dest_orig = dest;
4558 
4559         /* now we have a buffer to copy into */
4560         for (i = 0; i < num_types; i++) {
4561                 struct btrfs_space_info *tmp;
4562 
4563                 if (!slot_count)
4564                         break;
4565 
4566                 info = NULL;
4567                 rcu_read_lock();
4568                 list_for_each_entry_rcu(tmp, &fs_info->space_info,
4569                                         list) {
4570                         if (tmp->flags == types[i]) {
4571                                 info = tmp;
4572                                 break;
4573                         }
4574                 }
4575                 rcu_read_unlock();
4576 
4577                 if (!info)
4578                         continue;
4579                 down_read(&info->groups_sem);
4580                 for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) {
4581                         if (!list_empty(&info->block_groups[c])) {
4582                                 get_block_group_info(&info->block_groups[c],
4583                                                      &space);
4584                                 memcpy(dest, &space, sizeof(space));
4585                                 dest++;
4586                                 space_args.total_spaces++;
4587                                 slot_count--;
4588                         }
4589                         if (!slot_count)
4590                                 break;
4591                 }
4592                 up_read(&info->groups_sem);
4593         }
4594 
4595         /*
4596          * Add global block reserve
4597          */
4598         if (slot_count) {
4599                 struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
4600 
4601                 spin_lock(&block_rsv->lock);
4602                 space.total_bytes = block_rsv->size;
4603                 space.used_bytes = block_rsv->size - block_rsv->reserved;
4604                 spin_unlock(&block_rsv->lock);
4605                 space.flags = BTRFS_SPACE_INFO_GLOBAL_RSV;
4606                 memcpy(dest, &space, sizeof(space));
4607                 space_args.total_spaces++;
4608         }
4609 
4610         user_dest = (struct btrfs_ioctl_space_info __user *)
4611                 (arg + sizeof(struct btrfs_ioctl_space_args));
4612 
4613         if (copy_to_user(user_dest, dest_orig, alloc_size))
4614                 ret = -EFAULT;
4615 
4616         kfree(dest_orig);
4617 out:
4618         if (ret == 0 && copy_to_user(arg, &space_args, sizeof(space_args)))
4619                 ret = -EFAULT;
4620 
4621         return ret;
4622 }
4623 
4624 static noinline long btrfs_ioctl_start_sync(struct btrfs_root *root,
4625                                             void __user *argp)
4626 {
4627         struct btrfs_trans_handle *trans;
4628         u64 transid;
4629         int ret;
4630 
4631         trans = btrfs_attach_transaction_barrier(root);
4632         if (IS_ERR(trans)) {
4633                 if (PTR_ERR(trans) != -ENOENT)
4634                         return PTR_ERR(trans);
4635 
4636                 /* No running transaction, don't bother */
4637                 transid = root->fs_info->last_trans_committed;
4638                 goto out;
4639         }
4640         transid = trans->transid;
4641         ret = btrfs_commit_transaction_async(trans, 0);
4642         if (ret) {
4643                 btrfs_end_transaction(trans);
4644                 return ret;
4645         }
4646 out:
4647         if (argp)
4648                 if (copy_to_user(argp, &transid, sizeof(transid)))
4649                         return -EFAULT;
4650         return 0;
4651 }
4652 
4653 static noinline long btrfs_ioctl_wait_sync(struct btrfs_fs_info *fs_info,
4654                                            void __user *argp)
4655 {
4656         u64 transid;
4657 
4658         if (argp) {
4659                 if (copy_from_user(&transid, argp, sizeof(transid)))
4660                         return -EFAULT;
4661         } else {
4662                 transid = 0;  /* current trans */
4663         }
4664         return btrfs_wait_for_commit(fs_info, transid);
4665 }
4666 
4667 static long btrfs_ioctl_scrub(struct file *file, void __user *arg)
4668 {
4669         struct btrfs_fs_info *fs_info = btrfs_sb(file_inode(file)->i_sb);
4670         struct btrfs_ioctl_scrub_args *sa;
4671         int ret;
4672 
4673         if (!capable(CAP_SYS_ADMIN))
4674                 return -EPERM;
4675 
4676         sa = memdup_user(arg, sizeof(*sa));
4677         if (IS_ERR(sa))
4678                 return PTR_ERR(sa);
4679 
4680         if (!(sa->flags & BTRFS_SCRUB_READONLY)) {
4681                 ret = mnt_want_write_file(file);
4682                 if (ret)
4683                         goto out;
4684         }
4685 
4686         ret = btrfs_scrub_dev(fs_info, sa->devid, sa->start, sa->end,
4687                               &sa->progress, sa->flags & BTRFS_SCRUB_READONLY,
4688                               0);
4689 
4690         if (copy_to_user(arg, sa, sizeof(*sa)))
4691                 ret = -EFAULT;
4692 
4693         if (!(sa->flags & BTRFS_SCRUB_READONLY))
4694                 mnt_drop_write_file(file);
4695 out:
4696         kfree(sa);
4697         return ret;
4698 }
4699 
4700 static long btrfs_ioctl_scrub_cancel(struct btrfs_fs_info *fs_info)
4701 {
4702         if (!capable(CAP_SYS_ADMIN))
4703                 return -EPERM;
4704 
4705         return btrfs_scrub_cancel(fs_info);
4706 }
4707 
4708 static long btrfs_ioctl_scrub_progress(struct btrfs_fs_info *fs_info,
4709                                        void __user *arg)
4710 {
4711         struct btrfs_ioctl_scrub_args *sa;
4712         int ret;
4713 
4714         if (!capable(CAP_SYS_ADMIN))
4715                 return -EPERM;
4716 
4717         sa = memdup_user(arg, sizeof(*sa));
4718         if (IS_ERR(sa))
4719                 return PTR_ERR(sa);
4720 
4721         ret = btrfs_scrub_progress(fs_info, sa->devid, &sa->progress);
4722 
4723         if (copy_to_user(arg, sa, sizeof(*sa)))
4724                 ret = -EFAULT;
4725 
4726         kfree(sa);
4727         return ret;
4728 }
4729 
4730 static long btrfs_ioctl_get_dev_stats(struct btrfs_fs_info *fs_info,
4731                                       void __user *arg)
4732 {
4733         struct btrfs_ioctl_get_dev_stats *sa;
4734         int ret;
4735 
4736         sa = memdup_user(arg, sizeof(*sa));
4737         if (IS_ERR(sa))
4738                 return PTR_ERR(sa);
4739 
4740         if ((sa->flags & BTRFS_DEV_STATS_RESET) && !capable(CAP_SYS_ADMIN)) {
4741                 kfree(sa);
4742                 return -EPERM;
4743         }
4744 
4745         ret = btrfs_get_dev_stats(fs_info, sa);
4746 
4747         if (copy_to_user(arg, sa, sizeof(*sa)))
4748                 ret = -EFAULT;
4749 
4750         kfree(sa);
4751         return ret;
4752 }
4753 
4754 static long btrfs_ioctl_dev_replace(struct btrfs_fs_info *fs_info,
4755                                     void __user *arg)
4756 {
4757         struct btrfs_ioctl_dev_replace_args *p;
4758         int ret;
4759 
4760         if (!capable(CAP_SYS_ADMIN))
4761                 return -EPERM;
4762 
4763         p = memdup_user(arg, sizeof(*p));
4764         if (IS_ERR(p))
4765                 return PTR_ERR(p);
4766 
4767         switch (p->cmd) {
4768         case BTRFS_IOCTL_DEV_REPLACE_CMD_START:
4769                 if (sb_rdonly(fs_info->sb)) {
4770                         ret = -EROFS;
4771                         goto out;
4772                 }
4773                 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
4774                         ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
4775                 } else {
4776                         ret = btrfs_dev_replace_by_ioctl(fs_info, p);
4777                         clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4778                 }
4779                 break;
4780         case BTRFS_IOCTL_DEV_REPLACE_CMD_STATUS:
4781                 btrfs_dev_replace_status(fs_info, p);
4782                 ret = 0;
4783                 break;
4784         case BTRFS_IOCTL_DEV_REPLACE_CMD_CANCEL:
4785                 p->result = btrfs_dev_replace_cancel(fs_info);
4786                 ret = 0;
4787                 break;
4788         default:
4789                 ret = -EINVAL;
4790                 break;
4791         }
4792 
4793         if (copy_to_user(arg, p, sizeof(*p)))
4794                 ret = -EFAULT;
4795 out:
4796         kfree(p);
4797         return ret;
4798 }
4799 
4800 static long btrfs_ioctl_ino_to_path(struct btrfs_root *root, void __user *arg)
4801 {
4802         int ret = 0;
4803         int i;
4804         u64 rel_ptr;
4805         int size;
4806         struct btrfs_ioctl_ino_path_args *ipa = NULL;
4807         struct inode_fs_paths *ipath = NULL;
4808         struct btrfs_path *path;
4809 
4810         if (!capable(CAP_DAC_READ_SEARCH))
4811                 return -EPERM;
4812 
4813         path = btrfs_alloc_path();
4814         if (!path) {
4815                 ret = -ENOMEM;
4816                 goto out;
4817         }
4818 
4819         ipa = memdup_user(arg, sizeof(*ipa));
4820         if (IS_ERR(ipa)) {
4821                 ret = PTR_ERR(ipa);
4822                 ipa = NULL;
4823                 goto out;
4824         }
4825 
4826         size = min_t(u32, ipa->size, 4096);
4827         ipath = init_ipath(size, root, path);
4828         if (IS_ERR(ipath)) {
4829                 ret = PTR_ERR(ipath);
4830                 ipath = NULL;
4831                 goto out;
4832         }
4833 
4834         ret = paths_from_inode(ipa->inum, ipath);
4835         if (ret < 0)
4836                 goto out;
4837 
4838         for (i = 0; i < ipath->fspath->elem_cnt; ++i) {
4839                 rel_ptr = ipath->fspath->val[i] -
4840                           (u64)(unsigned long)ipath->fspath->val;
4841                 ipath->fspath->val[i] = rel_ptr;
4842         }
4843 
4844         ret = copy_to_user((void __user *)(unsigned long)ipa->fspath,
4845                            ipath->fspath, size);
4846         if (ret) {
4847                 ret = -EFAULT;
4848                 goto out;
4849         }
4850 
4851 out:
4852         btrfs_free_path(path);
4853         free_ipath(ipath);
4854         kfree(ipa);
4855 
4856         return ret;
4857 }
4858 
4859 static int build_ino_list(u64 inum, u64 offset, u64 root, void *ctx)
4860 {
4861         struct btrfs_data_container *inodes = ctx;
4862         const size_t c = 3 * sizeof(u64);
4863 
4864         if (inodes->bytes_left >= c) {
4865                 inodes->bytes_left -= c;
4866                 inodes->val[inodes->elem_cnt] = inum;
4867                 inodes->val[inodes->elem_cnt + 1] = offset;
4868                 inodes->val[inodes->elem_cnt + 2] = root;
4869                 inodes->elem_cnt += 3;
4870         } else {
4871                 inodes->bytes_missing += c - inodes->bytes_left;
4872                 inodes->bytes_left = 0;
4873                 inodes->elem_missed += 3;
4874         }
4875 
4876         return 0;
4877 }
4878 
4879 static long btrfs_ioctl_logical_to_ino(struct btrfs_fs_info *fs_info,
4880                                         void __user *arg, int version)
4881 {
4882         int ret = 0;
4883         int size;
4884         struct btrfs_ioctl_logical_ino_args *loi;
4885         struct btrfs_data_container *inodes = NULL;
4886         struct btrfs_path *path = NULL;
4887         bool ignore_offset;
4888 
4889         if (!capable(CAP_SYS_ADMIN))
4890                 return -EPERM;
4891 
4892         loi = memdup_user(arg, sizeof(*loi));
4893         if (IS_ERR(loi))
4894                 return PTR_ERR(loi);
4895 
4896         if (version == 1) {
4897                 ignore_offset = false;
4898                 size = min_t(u32, loi->size, SZ_64K);
4899         } else {
4900                 /* All reserved bits must be 0 for now */
4901                 if (memchr_inv(loi->reserved, 0, sizeof(loi->reserved))) {
4902                         ret = -EINVAL;
4903                         goto out_loi;
4904                 }
4905                 /* Only accept flags we have defined so far */
4906                 if (loi->flags & ~(BTRFS_LOGICAL_INO_ARGS_IGNORE_OFFSET)) {
4907                         ret = -EINVAL;
4908                         goto out_loi;
4909                 }
4910                 ignore_offset = loi->flags & BTRFS_LOGICAL_INO_ARGS_IGNORE_OFFSET;
4911                 size = min_t(u32, loi->size, SZ_16M);
4912         }
4913 
4914         path = btrfs_alloc_path();
4915         if (!path) {
4916                 ret = -ENOMEM;
4917                 goto out;
4918         }
4919 
4920         inodes = init_data_container(size);
4921         if (IS_ERR(inodes)) {
4922                 ret = PTR_ERR(inodes);
4923                 inodes = NULL;
4924                 goto out;
4925         }
4926 
4927         ret = iterate_inodes_from_logical(loi->logical, fs_info, path,
4928                                           build_ino_list, inodes, ignore_offset);
4929         if (ret == -EINVAL)
4930                 ret = -ENOENT;
4931         if (ret < 0)
4932                 goto out;
4933 
4934         ret = copy_to_user((void __user *)(unsigned long)loi->inodes, inodes,
4935                            size);
4936         if (ret)
4937                 ret = -EFAULT;
4938 
4939 out:
4940         btrfs_free_path(path);
4941         kvfree(inodes);
4942 out_loi:
4943         kfree(loi);
4944 
4945         return ret;
4946 }
4947 
4948 void btrfs_update_ioctl_balance_args(struct btrfs_fs_info *fs_info,
4949                                struct btrfs_ioctl_balance_args *bargs)
4950 {
4951         struct btrfs_balance_control *bctl = fs_info->balance_ctl;
4952 
4953         bargs->flags = bctl->flags;
4954 
4955         if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags))
4956                 bargs->state |= BTRFS_BALANCE_STATE_RUNNING;
4957         if (atomic_read(&fs_info->balance_pause_req))
4958                 bargs->state |= BTRFS_BALANCE_STATE_PAUSE_REQ;
4959         if (atomic_read(&fs_info->balance_cancel_req))
4960                 bargs->state |= BTRFS_BALANCE_STATE_CANCEL_REQ;
4961 
4962         memcpy(&bargs->data, &bctl->data, sizeof(bargs->data));
4963         memcpy(&bargs->meta, &bctl->meta, sizeof(bargs->meta));
4964         memcpy(&bargs->sys, &bctl->sys, sizeof(bargs->sys));
4965 
4966         spin_lock(&fs_info->balance_lock);
4967         memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat));
4968         spin_unlock(&fs_info->balance_lock);
4969 }
4970 
4971 static long btrfs_ioctl_balance(struct file *file, void __user *arg)
4972 {
4973         struct btrfs_root *root = BTRFS_I(file_inode(file))->root;
4974         struct btrfs_fs_info *fs_info = root->fs_info;
4975         struct btrfs_ioctl_balance_args *bargs;
4976         struct btrfs_balance_control *bctl;
4977         bool need_unlock; /* for mut. excl. ops lock */
4978         int ret;
4979 
4980         if (!capable(CAP_SYS_ADMIN))
4981                 return -EPERM;
4982 
4983         ret = mnt_want_write_file(file);
4984         if (ret)
4985                 return ret;
4986 
4987 again:
4988         if (!test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
4989                 mutex_lock(&fs_info->balance_mutex);
4990                 need_unlock = true;
4991                 goto locked;
4992         }
4993 
4994         /*
4995          * mut. excl. ops lock is locked.  Three possibilities:
4996          *   (1) some other op is running
4997          *   (2) balance is running
4998          *   (3) balance is paused -- special case (think resume)
4999          */
5000         mutex_lock(&fs_info->balance_mutex);
5001         if (fs_info->balance_ctl) {
5002                 /* this is either (2) or (3) */
5003                 if (!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
5004                         mutex_unlock(&fs_info->balance_mutex);
5005                         /*
5006                          * Lock released to allow other waiters to continue,
5007                          * we'll reexamine the status again.
5008                          */
5009                         mutex_lock(&fs_info->balance_mutex);
5010 
5011                         if (fs_info->balance_ctl &&
5012                             !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
5013                                 /* this is (3) */
5014                                 need_unlock = false;
5015                                 goto locked;
5016                         }
5017 
5018                         mutex_unlock(&fs_info->balance_mutex);
5019                         goto again;
5020                 } else {
5021                         /* this is (2) */
5022                         mutex_unlock(&fs_info->balance_mutex);
5023                         ret = -EINPROGRESS;
5024                         goto out;
5025                 }
5026         } else {
5027                 /* this is (1) */
5028                 mutex_unlock(&fs_info->balance_mutex);
5029                 ret = BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS;
5030                 goto out;
5031         }
5032 
5033 locked:
5034         BUG_ON(!test_bit(BTRFS_FS_EXCL_OP, &fs_info->flags));
5035 
5036         if (arg) {
5037                 bargs = memdup_user(arg, sizeof(*bargs));
5038                 if (IS_ERR(bargs)) {
5039                         ret = PTR_ERR(bargs);
5040                         goto out_unlock;
5041                 }
5042 
5043                 if (bargs->flags & BTRFS_BALANCE_RESUME) {
5044                         if (!fs_info->balance_ctl) {
5045                                 ret = -ENOTCONN;
5046                                 goto out_bargs;
5047                         }
5048 
5049                         bctl = fs_info->balance_ctl;
5050                         spin_lock(&fs_info->balance_lock);
5051                         bctl->flags |= BTRFS_BALANCE_RESUME;
5052                         spin_unlock(&fs_info->balance_lock);
5053 
5054                         goto do_balance;
5055                 }
5056         } else {
5057                 bargs = NULL;
5058         }
5059 
5060         if (fs_info->balance_ctl) {
5061                 ret = -EINPROGRESS;
5062                 goto out_bargs;
5063         }
5064 
5065         bctl = kzalloc(sizeof(*bctl), GFP_KERNEL);
5066         if (!bctl) {
5067                 ret = -ENOMEM;
5068                 goto out_bargs;
5069         }
5070 
5071         if (arg) {
5072                 memcpy(&bctl->data, &bargs->data, sizeof(bctl->data));
5073                 memcpy(&bctl->meta, &bargs->meta, sizeof(bctl->meta));
5074                 memcpy(&bctl->sys, &bargs->sys, sizeof(bctl->sys));
5075 
5076                 bctl->flags = bargs->flags;
5077         } else {
5078                 /* balance everything - no filters */
5079                 bctl->flags |= BTRFS_BALANCE_TYPE_MASK;
5080         }
5081 
5082         if (bctl->flags & ~(BTRFS_BALANCE_ARGS_MASK | BTRFS_BALANCE_TYPE_MASK)) {
5083                 ret = -EINVAL;
5084                 goto out_bctl;
5085         }
5086 
5087 do_balance:
5088         /*
5089          * Ownership of bctl and filesystem flag BTRFS_FS_EXCL_OP goes to
5090          * btrfs_balance.  bctl is freed in reset_balance_state, or, if
5091          * restriper was paused all the way until unmount, in free_fs_info.
5092          * The flag should be cleared after reset_balance_state.
5093          */
5094         need_unlock = false;
5095 
5096         ret = btrfs_balance(fs_info, bctl, bargs);
5097         bctl = NULL;
5098 
5099         if (arg) {
5100                 if (copy_to_user(arg, bargs, sizeof(*bargs)))
5101                         ret = -EFAULT;
5102         }
5103 
5104 out_bctl:
5105         kfree(bctl);
5106 out_bargs:
5107         kfree(bargs);
5108 out_unlock:
5109         mutex_unlock(&fs_info->balance_mutex);
5110         if (need_unlock)
5111                 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
5112 out:
5113         mnt_drop_write_file(file);
5114         return ret;
5115 }
5116 
5117 static long btrfs_ioctl_balance_ctl(struct btrfs_fs_info *fs_info, int cmd)
5118 {
5119         if (!capable(CAP_SYS_ADMIN))
5120                 return -EPERM;
5121 
5122         switch (cmd) {
5123         case BTRFS_BALANCE_CTL_PAUSE:
5124                 return btrfs_pause_balance(fs_info);
5125         case BTRFS_BALANCE_CTL_CANCEL:
5126                 return btrfs_cancel_balance(fs_info);
5127         }
5128 
5129         return -EINVAL;
5130 }
5131 
5132 static long btrfs_ioctl_balance_progress(struct btrfs_fs_info *fs_info,
5133                                          void __user *arg)
5134 {
5135         struct btrfs_ioctl_balance_args *bargs;
5136         int ret = 0;
5137 
5138         if (!capable(CAP_SYS_ADMIN))
5139                 return -EPERM;
5140 
5141         mutex_lock(&fs_info->balance_mutex);
5142         if (!fs_info->balance_ctl) {
5143                 ret = -ENOTCONN;
5144                 goto out;
5145         }
5146 
5147         bargs = kzalloc(sizeof(*bargs), GFP_KERNEL);
5148         if (!bargs) {
5149                 ret = -ENOMEM;
5150                 goto out;
5151         }
5152 
5153         btrfs_update_ioctl_balance_args(fs_info, bargs);
5154 
5155         if (copy_to_user(arg, bargs, sizeof(*bargs)))
5156                 ret = -EFAULT;
5157 
5158         kfree(bargs);
5159 out:
5160         mutex_unlock(&fs_info->balance_mutex);
5161         return ret;
5162 }
5163 
5164 static long btrfs_ioctl_quota_ctl(struct file *file, void __user *arg)
5165 {
5166         struct inode *inode = file_inode(file);
5167         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5168         struct btrfs_ioctl_quota_ctl_args *sa;
5169         struct btrfs_trans_handle *trans = NULL;
5170         int ret;
5171         int err;
5172 
5173         if (!capable(CAP_SYS_ADMIN))
5174                 return -EPERM;
5175 
5176         ret = mnt_want_write_file(file);
5177         if (ret)
5178                 return ret;
5179 
5180         sa = memdup_user(arg, sizeof(*sa));
5181         if (IS_ERR(sa)) {
5182                 ret = PTR_ERR(sa);
5183                 goto drop_write;
5184         }
5185 
5186         down_write(&fs_info->subvol_sem);
5187         trans = btrfs_start_transaction(fs_info->tree_root, 2);
5188         if (IS_ERR(trans)) {
5189                 ret = PTR_ERR(trans);
5190                 goto out;
5191         }
5192 
5193         switch (sa->cmd) {
5194         case BTRFS_QUOTA_CTL_ENABLE:
5195                 ret = btrfs_quota_enable(trans, fs_info);
5196                 break;
5197         case BTRFS_QUOTA_CTL_DISABLE:
5198                 ret = btrfs_quota_disable(trans, fs_info);
5199                 break;
5200         default:
5201                 ret = -EINVAL;
5202                 break;
5203         }
5204 
5205         err = btrfs_commit_transaction(trans);
5206         if (err && !ret)
5207                 ret = err;
5208 out:
5209         kfree(sa);
5210         up_write(&fs_info->subvol_sem);
5211 drop_write:
5212         mnt_drop_write_file(file);
5213         return ret;
5214 }
5215 
5216 static long btrfs_ioctl_qgroup_assign(struct file *file, void __user *arg)
5217 {
5218         struct inode *inode = file_inode(file);
5219         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5220         struct btrfs_root *root = BTRFS_I(inode)->root;
5221         struct btrfs_ioctl_qgroup_assign_args *sa;
5222         struct btrfs_trans_handle *trans;
5223         int ret;
5224         int err;
5225 
5226         if (!capable(CAP_SYS_ADMIN))
5227                 return -EPERM;
5228 
5229         ret = mnt_want_write_file(file);
5230         if (ret)
5231                 return ret;
5232 
5233         sa = memdup_user(arg, sizeof(*sa));
5234         if (IS_ERR(sa)) {
5235                 ret = PTR_ERR(sa);
5236                 goto drop_write;
5237         }
5238 
5239         trans = btrfs_join_transaction(root);
5240         if (IS_ERR(trans)) {
5241                 ret = PTR_ERR(trans);
5242                 goto out;
5243         }
5244 
5245         if (sa->assign) {
5246                 ret = btrfs_add_qgroup_relation(trans, fs_info,
5247                                                 sa->src, sa->dst);
5248         } else {
5249                 ret = btrfs_del_qgroup_relation(trans, fs_info,
5250                                                 sa->src, sa->dst);
5251         }
5252 
5253         /* update qgroup status and info */
5254         err = btrfs_run_qgroups(trans, fs_info);
5255         if (err < 0)
5256                 btrfs_handle_fs_error(fs_info, err,
5257                                       "failed to update qgroup status and info");
5258         err = btrfs_end_transaction(trans);
5259         if (err && !ret)
5260                 ret = err;
5261 
5262 out:
5263         kfree(sa);
5264 drop_write:
5265         mnt_drop_write_file(file);
5266         return ret;
5267 }
5268 
5269 static long btrfs_ioctl_qgroup_create(struct file *file, void __user *arg)
5270 {
5271         struct inode *inode = file_inode(file);
5272         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5273         struct btrfs_root *root = BTRFS_I(inode)->root;
5274         struct btrfs_ioctl_qgroup_create_args *sa;
5275         struct btrfs_trans_handle *trans;
5276         int ret;
5277         int err;
5278 
5279         if (!capable(CAP_SYS_ADMIN))
5280                 return -EPERM;
5281 
5282         ret = mnt_want_write_file(file);
5283         if (ret)
5284                 return ret;
5285 
5286         sa = memdup_user(arg, sizeof(*sa));
5287         if (IS_ERR(sa)) {
5288                 ret = PTR_ERR(sa);
5289                 goto drop_write;
5290         }
5291 
5292         if (!sa->qgroupid) {
5293                 ret = -EINVAL;
5294                 goto out;
5295         }
5296 
5297         trans = btrfs_join_transaction(root);
5298         if (IS_ERR(trans)) {
5299                 ret = PTR_ERR(trans);
5300                 goto out;
5301         }
5302 
5303         if (sa->create) {
5304                 ret = btrfs_create_qgroup(trans, fs_info, sa->qgroupid);
5305         } else {
5306                 ret = btrfs_remove_qgroup(trans, fs_info, sa->qgroupid);
5307         }
5308 
5309         err = btrfs_end_transaction(trans);
5310         if (err && !ret)
5311                 ret = err;
5312 
5313 out:
5314         kfree(sa);
5315 drop_write:
5316         mnt_drop_write_file(file);
5317         return ret;
5318 }
5319 
5320 static long btrfs_ioctl_qgroup_limit(struct file *file, void __user *arg)
5321 {
5322         struct inode *inode = file_inode(file);
5323         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5324         struct btrfs_root *root = BTRFS_I(inode)->root;
5325         struct btrfs_ioctl_qgroup_limit_args *sa;
5326         struct btrfs_trans_handle *trans;
5327         int ret;
5328         int err;
5329         u64 qgroupid;
5330 
5331         if (!capable(CAP_SYS_ADMIN))
5332                 return -EPERM;
5333 
5334         ret = mnt_want_write_file(file);
5335         if (ret)
5336                 return ret;
5337 
5338         sa = memdup_user(arg, sizeof(*sa));
5339         if (IS_ERR(sa)) {
5340                 ret = PTR_ERR(sa);
5341                 goto drop_write;
5342         }
5343 
5344         trans = btrfs_join_transaction(root);
5345         if (IS_ERR(trans)) {
5346                 ret = PTR_ERR(trans);
5347                 goto out;
5348         }
5349 
5350         qgroupid = sa->qgroupid;
5351         if (!qgroupid) {
5352                 /* take the current subvol as qgroup */
5353                 qgroupid = root->root_key.objectid;
5354         }
5355 
5356         ret = btrfs_limit_qgroup(trans, fs_info, qgroupid, &sa->lim);
5357 
5358         err = btrfs_end_transaction(trans);
5359         if (err && !ret)
5360                 ret = err;
5361 
5362 out:
5363         kfree(sa);
5364 drop_write:
5365         mnt_drop_write_file(file);
5366         return ret;
5367 }
5368 
5369 static long btrfs_ioctl_quota_rescan(struct file *file, void __user *arg)
5370 {
5371         struct inode *inode = file_inode(file);
5372         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5373         struct btrfs_ioctl_quota_rescan_args *qsa;
5374         int ret;
5375 
5376         if (!capable(CAP_SYS_ADMIN))
5377                 return -EPERM;
5378 
5379         ret = mnt_want_write_file(file);
5380         if (ret)
5381                 return ret;
5382 
5383         qsa = memdup_user(arg, sizeof(*qsa));
5384         if (IS_ERR(qsa)) {
5385                 ret = PTR_ERR(qsa);
5386                 goto drop_write;
5387         }
5388 
5389         if (qsa->flags) {
5390                 ret = -EINVAL;
5391                 goto out;
5392         }
5393 
5394         ret = btrfs_qgroup_rescan(fs_info);
5395 
5396 out:
5397         kfree(qsa);
5398 drop_write:
5399         mnt_drop_write_file(file);
5400         return ret;
5401 }
5402 
5403 static long btrfs_ioctl_quota_rescan_status(struct file *file, void __user *arg)
5404 {
5405         struct inode *inode = file_inode(file);
5406         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5407         struct btrfs_ioctl_quota_rescan_args *qsa;
5408         int ret = 0;
5409 
5410         if (!capable(CAP_SYS_ADMIN))
5411                 return -EPERM;
5412 
5413         qsa = kzalloc(sizeof(*qsa), GFP_KERNEL);
5414         if (!qsa)
5415                 return -ENOMEM;
5416 
5417         if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
5418                 qsa->flags = 1;
5419                 qsa->progress = fs_info->qgroup_rescan_progress.objectid;
5420         }
5421 
5422         if (copy_to_user(arg, qsa, sizeof(*qsa)))
5423                 ret = -EFAULT;
5424 
5425         kfree(qsa);
5426         return ret;
5427 }
5428 
5429 static long btrfs_ioctl_quota_rescan_wait(struct file *file, void __user *arg)
5430 {
5431         struct inode *inode = file_inode(file);
5432         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5433 
5434         if (!capable(CAP_SYS_ADMIN))
5435                 return -EPERM;
5436 
5437         return btrfs_qgroup_wait_for_completion(fs_info, true);
5438 }
5439 
5440 static long _btrfs_ioctl_set_received_subvol(struct file *file,
5441                                             struct btrfs_ioctl_received_subvol_args *sa)
5442 {
5443         struct inode *inode = file_inode(file);
5444         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5445         struct btrfs_root *root = BTRFS_I(inode)->root;
5446         struct btrfs_root_item *root_item = &root->root_item;
5447         struct btrfs_trans_handle *trans;
5448         struct timespec64 ct = current_time(inode);
5449         int ret = 0;
5450         int received_uuid_changed;
5451 
5452         if (!inode_owner_or_capable(inode))
5453                 return -EPERM;
5454 
5455         ret = mnt_want_write_file(file);
5456         if (ret < 0)
5457                 return ret;
5458 
5459         down_write(&fs_info->subvol_sem);
5460 
5461         if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FIRST_FREE_OBJECTID) {
5462                 ret = -EINVAL;
5463                 goto out;
5464         }
5465 
5466         if (btrfs_root_readonly(root)) {
5467                 ret = -EROFS;
5468                 goto out;
5469         }
5470 
5471         /*
5472          * 1 - root item
5473          * 2 - uuid items (received uuid + subvol uuid)
5474          */
5475         trans = btrfs_start_transaction(root, 3);
5476         if (IS_ERR(trans)) {
5477                 ret = PTR_ERR(trans);
5478                 trans = NULL;
5479                 goto out;
5480         }
5481 
5482         sa->rtransid = trans->transid;
5483         sa->rtime.sec = ct.tv_sec;
5484         sa->rtime.nsec = ct.tv_nsec;
5485 
5486         received_uuid_changed = memcmp(root_item->received_uuid, sa->uuid,
5487                                        BTRFS_UUID_SIZE);
5488         if (received_uuid_changed &&
5489             !btrfs_is_empty_uuid(root_item->received_uuid)) {
5490                 ret = btrfs_uuid_tree_remove(trans, root_item->received_uuid,
5491                                           BTRFS_UUID_KEY_RECEIVED_SUBVOL,
5492                                           root->root_key.objectid);
5493                 if (ret && ret != -ENOENT) {
5494                         btrfs_abort_transaction(trans, ret);
5495                         btrfs_end_transaction(trans);
5496                         goto out;
5497                 }
5498         }
5499         memcpy(root_item->received_uuid, sa->uuid, BTRFS_UUID_SIZE);
5500         btrfs_set_root_stransid(root_item, sa->stransid);
5501         btrfs_set_root_rtransid(root_item, sa->rtransid);
5502         btrfs_set_stack_timespec_sec(&root_item->stime, sa->stime.sec);
5503         btrfs_set_stack_timespec_nsec(&root_item->stime, sa->stime.nsec);
5504         btrfs_set_stack_timespec_sec(&root_item->rtime, sa->rtime.sec);
5505         btrfs_set_stack_timespec_nsec(&root_item->rtime, sa->rtime.nsec);
5506 
5507         ret = btrfs_update_root(trans, fs_info->tree_root,
5508                                 &root->root_key, &root->root_item);
5509         if (ret < 0) {
5510                 btrfs_end_transaction(trans);
5511                 goto out;