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