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