blob: e1063ef3dece5f8a7c5ae7eba8a2104653f27748 [file] [log] [blame]
b.liue9582032025-04-17 19:18:16 +08001// SPDX-License-Identifier: GPL-2.0
2/*
3 * Copyright (C) 2012 Alexander Block. All rights reserved.
4 */
5
6#include <linux/bsearch.h>
7#include <linux/fs.h>
8#include <linux/file.h>
9#include <linux/sort.h>
10#include <linux/mount.h>
11#include <linux/xattr.h>
12#include <linux/posix_acl_xattr.h>
13#include <linux/radix-tree.h>
14#include <linux/vmalloc.h>
15#include <linux/string.h>
16#include <linux/compat.h>
17#include <linux/crc32c.h>
18
19#include "send.h"
20#include "backref.h"
21#include "locking.h"
22#include "disk-io.h"
23#include "btrfs_inode.h"
24#include "transaction.h"
25#include "compression.h"
26#include "xattr.h"
27
28/*
29 * Maximum number of references an extent can have in order for us to attempt to
30 * issue clone operations instead of write operations. This currently exists to
31 * avoid hitting limitations of the backreference walking code (taking a lot of
32 * time and using too much memory for extents with large number of references).
33 */
34#define SEND_MAX_EXTENT_REFS 64
35
36/*
37 * A fs_path is a helper to dynamically build path names with unknown size.
38 * It reallocates the internal buffer on demand.
39 * It allows fast adding of path elements on the right side (normal path) and
40 * fast adding to the left side (reversed path). A reversed path can also be
41 * unreversed if needed.
42 */
43struct fs_path {
44 union {
45 struct {
46 char *start;
47 char *end;
48
49 char *buf;
50 unsigned short buf_len:15;
51 unsigned short reversed:1;
52 char inline_buf[];
53 };
54 /*
55 * Average path length does not exceed 200 bytes, we'll have
56 * better packing in the slab and higher chance to satisfy
57 * a allocation later during send.
58 */
59 char pad[256];
60 };
61};
62#define FS_PATH_INLINE_SIZE \
63 (sizeof(struct fs_path) - offsetof(struct fs_path, inline_buf))
64
65
66/* reused for each extent */
67struct clone_root {
68 struct btrfs_root *root;
69 u64 ino;
70 u64 offset;
71
72 u64 found_refs;
73};
74
75#define SEND_CTX_MAX_NAME_CACHE_SIZE 128
76#define SEND_CTX_NAME_CACHE_CLEAN_SIZE (SEND_CTX_MAX_NAME_CACHE_SIZE * 2)
77
78struct send_ctx {
79 struct file *send_filp;
80 loff_t send_off;
81 char *send_buf;
82 u32 send_size;
83 u32 send_max_size;
84 u64 total_send_size;
85 u64 cmd_send_size[BTRFS_SEND_C_MAX + 1];
86 u64 flags; /* 'flags' member of btrfs_ioctl_send_args is u64 */
87
88 struct btrfs_root *send_root;
89 struct btrfs_root *parent_root;
90 struct clone_root *clone_roots;
91 int clone_roots_cnt;
92
93 /* current state of the compare_tree call */
94 struct btrfs_path *left_path;
95 struct btrfs_path *right_path;
96 struct btrfs_key *cmp_key;
97
98 /*
99 * infos of the currently processed inode. In case of deleted inodes,
100 * these are the values from the deleted inode.
101 */
102 u64 cur_ino;
103 u64 cur_inode_gen;
104 int cur_inode_new;
105 int cur_inode_new_gen;
106 int cur_inode_deleted;
107 u64 cur_inode_size;
108 u64 cur_inode_mode;
109 u64 cur_inode_rdev;
110 u64 cur_inode_last_extent;
111 u64 cur_inode_next_write_offset;
112 bool ignore_cur_inode;
113
114 u64 send_progress;
115
116 struct list_head new_refs;
117 struct list_head deleted_refs;
118
119 struct radix_tree_root name_cache;
120 struct list_head name_cache_list;
121 int name_cache_size;
122
123 struct file_ra_state ra;
124
125 char *read_buf;
126
127 /*
128 * We process inodes by their increasing order, so if before an
129 * incremental send we reverse the parent/child relationship of
130 * directories such that a directory with a lower inode number was
131 * the parent of a directory with a higher inode number, and the one
132 * becoming the new parent got renamed too, we can't rename/move the
133 * directory with lower inode number when we finish processing it - we
134 * must process the directory with higher inode number first, then
135 * rename/move it and then rename/move the directory with lower inode
136 * number. Example follows.
137 *
138 * Tree state when the first send was performed:
139 *
140 * .
141 * |-- a (ino 257)
142 * |-- b (ino 258)
143 * |
144 * |
145 * |-- c (ino 259)
146 * | |-- d (ino 260)
147 * |
148 * |-- c2 (ino 261)
149 *
150 * Tree state when the second (incremental) send is performed:
151 *
152 * .
153 * |-- a (ino 257)
154 * |-- b (ino 258)
155 * |-- c2 (ino 261)
156 * |-- d2 (ino 260)
157 * |-- cc (ino 259)
158 *
159 * The sequence of steps that lead to the second state was:
160 *
161 * mv /a/b/c/d /a/b/c2/d2
162 * mv /a/b/c /a/b/c2/d2/cc
163 *
164 * "c" has lower inode number, but we can't move it (2nd mv operation)
165 * before we move "d", which has higher inode number.
166 *
167 * So we just memorize which move/rename operations must be performed
168 * later when their respective parent is processed and moved/renamed.
169 */
170
171 /* Indexed by parent directory inode number. */
172 struct rb_root pending_dir_moves;
173
174 /*
175 * Reverse index, indexed by the inode number of a directory that
176 * is waiting for the move/rename of its immediate parent before its
177 * own move/rename can be performed.
178 */
179 struct rb_root waiting_dir_moves;
180
181 /*
182 * A directory that is going to be rm'ed might have a child directory
183 * which is in the pending directory moves index above. In this case,
184 * the directory can only be removed after the move/rename of its child
185 * is performed. Example:
186 *
187 * Parent snapshot:
188 *
189 * . (ino 256)
190 * |-- a/ (ino 257)
191 * |-- b/ (ino 258)
192 * |-- c/ (ino 259)
193 * | |-- x/ (ino 260)
194 * |
195 * |-- y/ (ino 261)
196 *
197 * Send snapshot:
198 *
199 * . (ino 256)
200 * |-- a/ (ino 257)
201 * |-- b/ (ino 258)
202 * |-- YY/ (ino 261)
203 * |-- x/ (ino 260)
204 *
205 * Sequence of steps that lead to the send snapshot:
206 * rm -f /a/b/c/foo.txt
207 * mv /a/b/y /a/b/YY
208 * mv /a/b/c/x /a/b/YY
209 * rmdir /a/b/c
210 *
211 * When the child is processed, its move/rename is delayed until its
212 * parent is processed (as explained above), but all other operations
213 * like update utimes, chown, chgrp, etc, are performed and the paths
214 * that it uses for those operations must use the orphanized name of
215 * its parent (the directory we're going to rm later), so we need to
216 * memorize that name.
217 *
218 * Indexed by the inode number of the directory to be deleted.
219 */
220 struct rb_root orphan_dirs;
221};
222
223struct pending_dir_move {
224 struct rb_node node;
225 struct list_head list;
226 u64 parent_ino;
227 u64 ino;
228 u64 gen;
229 struct list_head update_refs;
230};
231
232struct waiting_dir_move {
233 struct rb_node node;
234 u64 ino;
235 /*
236 * There might be some directory that could not be removed because it
237 * was waiting for this directory inode to be moved first. Therefore
238 * after this directory is moved, we can try to rmdir the ino rmdir_ino.
239 */
240 u64 rmdir_ino;
241 u64 rmdir_gen;
242 bool orphanized;
243};
244
245struct orphan_dir_info {
246 struct rb_node node;
247 u64 ino;
248 u64 gen;
249 u64 last_dir_index_offset;
250};
251
252struct name_cache_entry {
253 struct list_head list;
254 /*
255 * radix_tree has only 32bit entries but we need to handle 64bit inums.
256 * We use the lower 32bit of the 64bit inum to store it in the tree. If
257 * more then one inum would fall into the same entry, we use radix_list
258 * to store the additional entries. radix_list is also used to store
259 * entries where two entries have the same inum but different
260 * generations.
261 */
262 struct list_head radix_list;
263 u64 ino;
264 u64 gen;
265 u64 parent_ino;
266 u64 parent_gen;
267 int ret;
268 int need_later_update;
269 int name_len;
270 char name[];
271};
272
273#define ADVANCE 1
274#define ADVANCE_ONLY_NEXT -1
275
276enum btrfs_compare_tree_result {
277 BTRFS_COMPARE_TREE_NEW,
278 BTRFS_COMPARE_TREE_DELETED,
279 BTRFS_COMPARE_TREE_CHANGED,
280 BTRFS_COMPARE_TREE_SAME,
281};
282typedef int (*btrfs_changed_cb_t)(struct btrfs_path *left_path,
283 struct btrfs_path *right_path,
284 struct btrfs_key *key,
285 enum btrfs_compare_tree_result result,
286 void *ctx);
287
288__cold
289static void inconsistent_snapshot_error(struct send_ctx *sctx,
290 enum btrfs_compare_tree_result result,
291 const char *what)
292{
293 const char *result_string;
294
295 switch (result) {
296 case BTRFS_COMPARE_TREE_NEW:
297 result_string = "new";
298 break;
299 case BTRFS_COMPARE_TREE_DELETED:
300 result_string = "deleted";
301 break;
302 case BTRFS_COMPARE_TREE_CHANGED:
303 result_string = "updated";
304 break;
305 case BTRFS_COMPARE_TREE_SAME:
306 ASSERT(0);
307 result_string = "unchanged";
308 break;
309 default:
310 ASSERT(0);
311 result_string = "unexpected";
312 }
313
314 btrfs_err(sctx->send_root->fs_info,
315 "Send: inconsistent snapshot, found %s %s for inode %llu without updated inode item, send root is %llu, parent root is %llu",
316 result_string, what, sctx->cmp_key->objectid,
317 sctx->send_root->root_key.objectid,
318 (sctx->parent_root ?
319 sctx->parent_root->root_key.objectid : 0));
320}
321
322static int is_waiting_for_move(struct send_ctx *sctx, u64 ino);
323
324static struct waiting_dir_move *
325get_waiting_dir_move(struct send_ctx *sctx, u64 ino);
326
327static int is_waiting_for_rm(struct send_ctx *sctx, u64 dir_ino, u64 gen);
328
329static int need_send_hole(struct send_ctx *sctx)
330{
331 return (sctx->parent_root && !sctx->cur_inode_new &&
332 !sctx->cur_inode_new_gen && !sctx->cur_inode_deleted &&
333 S_ISREG(sctx->cur_inode_mode));
334}
335
336static void fs_path_reset(struct fs_path *p)
337{
338 if (p->reversed) {
339 p->start = p->buf + p->buf_len - 1;
340 p->end = p->start;
341 *p->start = 0;
342 } else {
343 p->start = p->buf;
344 p->end = p->start;
345 *p->start = 0;
346 }
347}
348
349static struct fs_path *fs_path_alloc(void)
350{
351 struct fs_path *p;
352
353 p = kmalloc(sizeof(*p), GFP_KERNEL);
354 if (!p)
355 return NULL;
356 p->reversed = 0;
357 p->buf = p->inline_buf;
358 p->buf_len = FS_PATH_INLINE_SIZE;
359 fs_path_reset(p);
360 return p;
361}
362
363static struct fs_path *fs_path_alloc_reversed(void)
364{
365 struct fs_path *p;
366
367 p = fs_path_alloc();
368 if (!p)
369 return NULL;
370 p->reversed = 1;
371 fs_path_reset(p);
372 return p;
373}
374
375static void fs_path_free(struct fs_path *p)
376{
377 if (!p)
378 return;
379 if (p->buf != p->inline_buf)
380 kfree(p->buf);
381 kfree(p);
382}
383
384static int fs_path_len(struct fs_path *p)
385{
386 return p->end - p->start;
387}
388
389static int fs_path_ensure_buf(struct fs_path *p, int len)
390{
391 char *tmp_buf;
392 int path_len;
393 int old_buf_len;
394
395 len++;
396
397 if (p->buf_len >= len)
398 return 0;
399
400 if (len > PATH_MAX) {
401 WARN_ON(1);
402 return -ENOMEM;
403 }
404
405 path_len = p->end - p->start;
406 old_buf_len = p->buf_len;
407
408 /*
409 * First time the inline_buf does not suffice
410 */
411 if (p->buf == p->inline_buf) {
412 tmp_buf = kmalloc(len, GFP_KERNEL);
413 if (tmp_buf)
414 memcpy(tmp_buf, p->buf, old_buf_len);
415 } else {
416 tmp_buf = krealloc(p->buf, len, GFP_KERNEL);
417 }
418 if (!tmp_buf)
419 return -ENOMEM;
420 p->buf = tmp_buf;
421 /*
422 * The real size of the buffer is bigger, this will let the fast path
423 * happen most of the time
424 */
425 p->buf_len = ksize(p->buf);
426
427 if (p->reversed) {
428 tmp_buf = p->buf + old_buf_len - path_len - 1;
429 p->end = p->buf + p->buf_len - 1;
430 p->start = p->end - path_len;
431 memmove(p->start, tmp_buf, path_len + 1);
432 } else {
433 p->start = p->buf;
434 p->end = p->start + path_len;
435 }
436 return 0;
437}
438
439static int fs_path_prepare_for_add(struct fs_path *p, int name_len,
440 char **prepared)
441{
442 int ret;
443 int new_len;
444
445 new_len = p->end - p->start + name_len;
446 if (p->start != p->end)
447 new_len++;
448 ret = fs_path_ensure_buf(p, new_len);
449 if (ret < 0)
450 goto out;
451
452 if (p->reversed) {
453 if (p->start != p->end)
454 *--p->start = '/';
455 p->start -= name_len;
456 *prepared = p->start;
457 } else {
458 if (p->start != p->end)
459 *p->end++ = '/';
460 *prepared = p->end;
461 p->end += name_len;
462 *p->end = 0;
463 }
464
465out:
466 return ret;
467}
468
469static int fs_path_add(struct fs_path *p, const char *name, int name_len)
470{
471 int ret;
472 char *prepared;
473
474 ret = fs_path_prepare_for_add(p, name_len, &prepared);
475 if (ret < 0)
476 goto out;
477 memcpy(prepared, name, name_len);
478
479out:
480 return ret;
481}
482
483static int fs_path_add_path(struct fs_path *p, struct fs_path *p2)
484{
485 int ret;
486 char *prepared;
487
488 ret = fs_path_prepare_for_add(p, p2->end - p2->start, &prepared);
489 if (ret < 0)
490 goto out;
491 memcpy(prepared, p2->start, p2->end - p2->start);
492
493out:
494 return ret;
495}
496
497static int fs_path_add_from_extent_buffer(struct fs_path *p,
498 struct extent_buffer *eb,
499 unsigned long off, int len)
500{
501 int ret;
502 char *prepared;
503
504 ret = fs_path_prepare_for_add(p, len, &prepared);
505 if (ret < 0)
506 goto out;
507
508 read_extent_buffer(eb, prepared, off, len);
509
510out:
511 return ret;
512}
513
514static int fs_path_copy(struct fs_path *p, struct fs_path *from)
515{
516 int ret;
517
518 p->reversed = from->reversed;
519 fs_path_reset(p);
520
521 ret = fs_path_add_path(p, from);
522
523 return ret;
524}
525
526
527static void fs_path_unreverse(struct fs_path *p)
528{
529 char *tmp;
530 int len;
531
532 if (!p->reversed)
533 return;
534
535 tmp = p->start;
536 len = p->end - p->start;
537 p->start = p->buf;
538 p->end = p->start + len;
539 memmove(p->start, tmp, len + 1);
540 p->reversed = 0;
541}
542
543static struct btrfs_path *alloc_path_for_send(void)
544{
545 struct btrfs_path *path;
546
547 path = btrfs_alloc_path();
548 if (!path)
549 return NULL;
550 path->search_commit_root = 1;
551 path->skip_locking = 1;
552 path->need_commit_sem = 1;
553 return path;
554}
555
556static int write_buf(struct file *filp, const void *buf, u32 len, loff_t *off)
557{
558 int ret;
559 u32 pos = 0;
560
561 while (pos < len) {
562 ret = kernel_write(filp, buf + pos, len - pos, off);
563 /* TODO handle that correctly */
564 /*if (ret == -ERESTARTSYS) {
565 continue;
566 }*/
567 if (ret < 0)
568 return ret;
569 if (ret == 0) {
570 return -EIO;
571 }
572 pos += ret;
573 }
574
575 return 0;
576}
577
578static int tlv_put(struct send_ctx *sctx, u16 attr, const void *data, int len)
579{
580 struct btrfs_tlv_header *hdr;
581 int total_len = sizeof(*hdr) + len;
582 int left = sctx->send_max_size - sctx->send_size;
583
584 if (unlikely(left < total_len))
585 return -EOVERFLOW;
586
587 hdr = (struct btrfs_tlv_header *) (sctx->send_buf + sctx->send_size);
588 hdr->tlv_type = cpu_to_le16(attr);
589 hdr->tlv_len = cpu_to_le16(len);
590 memcpy(hdr + 1, data, len);
591 sctx->send_size += total_len;
592
593 return 0;
594}
595
596#define TLV_PUT_DEFINE_INT(bits) \
597 static int tlv_put_u##bits(struct send_ctx *sctx, \
598 u##bits attr, u##bits value) \
599 { \
600 __le##bits __tmp = cpu_to_le##bits(value); \
601 return tlv_put(sctx, attr, &__tmp, sizeof(__tmp)); \
602 }
603
604TLV_PUT_DEFINE_INT(64)
605
606static int tlv_put_string(struct send_ctx *sctx, u16 attr,
607 const char *str, int len)
608{
609 if (len == -1)
610 len = strlen(str);
611 return tlv_put(sctx, attr, str, len);
612}
613
614static int tlv_put_uuid(struct send_ctx *sctx, u16 attr,
615 const u8 *uuid)
616{
617 return tlv_put(sctx, attr, uuid, BTRFS_UUID_SIZE);
618}
619
620static int tlv_put_btrfs_timespec(struct send_ctx *sctx, u16 attr,
621 struct extent_buffer *eb,
622 struct btrfs_timespec *ts)
623{
624 struct btrfs_timespec bts;
625 read_extent_buffer(eb, &bts, (unsigned long)ts, sizeof(bts));
626 return tlv_put(sctx, attr, &bts, sizeof(bts));
627}
628
629
630#define TLV_PUT(sctx, attrtype, data, attrlen) \
631 do { \
632 ret = tlv_put(sctx, attrtype, data, attrlen); \
633 if (ret < 0) \
634 goto tlv_put_failure; \
635 } while (0)
636
637#define TLV_PUT_INT(sctx, attrtype, bits, value) \
638 do { \
639 ret = tlv_put_u##bits(sctx, attrtype, value); \
640 if (ret < 0) \
641 goto tlv_put_failure; \
642 } while (0)
643
644#define TLV_PUT_U8(sctx, attrtype, data) TLV_PUT_INT(sctx, attrtype, 8, data)
645#define TLV_PUT_U16(sctx, attrtype, data) TLV_PUT_INT(sctx, attrtype, 16, data)
646#define TLV_PUT_U32(sctx, attrtype, data) TLV_PUT_INT(sctx, attrtype, 32, data)
647#define TLV_PUT_U64(sctx, attrtype, data) TLV_PUT_INT(sctx, attrtype, 64, data)
648#define TLV_PUT_STRING(sctx, attrtype, str, len) \
649 do { \
650 ret = tlv_put_string(sctx, attrtype, str, len); \
651 if (ret < 0) \
652 goto tlv_put_failure; \
653 } while (0)
654#define TLV_PUT_PATH(sctx, attrtype, p) \
655 do { \
656 ret = tlv_put_string(sctx, attrtype, p->start, \
657 p->end - p->start); \
658 if (ret < 0) \
659 goto tlv_put_failure; \
660 } while(0)
661#define TLV_PUT_UUID(sctx, attrtype, uuid) \
662 do { \
663 ret = tlv_put_uuid(sctx, attrtype, uuid); \
664 if (ret < 0) \
665 goto tlv_put_failure; \
666 } while (0)
667#define TLV_PUT_BTRFS_TIMESPEC(sctx, attrtype, eb, ts) \
668 do { \
669 ret = tlv_put_btrfs_timespec(sctx, attrtype, eb, ts); \
670 if (ret < 0) \
671 goto tlv_put_failure; \
672 } while (0)
673
674static int send_header(struct send_ctx *sctx)
675{
676 struct btrfs_stream_header hdr;
677
678 strcpy(hdr.magic, BTRFS_SEND_STREAM_MAGIC);
679 hdr.version = cpu_to_le32(BTRFS_SEND_STREAM_VERSION);
680
681 return write_buf(sctx->send_filp, &hdr, sizeof(hdr),
682 &sctx->send_off);
683}
684
685/*
686 * For each command/item we want to send to userspace, we call this function.
687 */
688static int begin_cmd(struct send_ctx *sctx, int cmd)
689{
690 struct btrfs_cmd_header *hdr;
691
692 if (WARN_ON(!sctx->send_buf))
693 return -EINVAL;
694
695 if (unlikely(sctx->send_size != 0)) {
696 btrfs_err(sctx->send_root->fs_info,
697 "send: command header buffer not empty cmd %d offset %llu",
698 cmd, sctx->send_off);
699 return -EINVAL;
700 }
701
702 sctx->send_size += sizeof(*hdr);
703 hdr = (struct btrfs_cmd_header *)sctx->send_buf;
704 hdr->cmd = cpu_to_le16(cmd);
705
706 return 0;
707}
708
709static int send_cmd(struct send_ctx *sctx)
710{
711 int ret;
712 struct btrfs_cmd_header *hdr;
713 u32 crc;
714
715 hdr = (struct btrfs_cmd_header *)sctx->send_buf;
716 hdr->len = cpu_to_le32(sctx->send_size - sizeof(*hdr));
717 hdr->crc = 0;
718
719 crc = btrfs_crc32c(0, (unsigned char *)sctx->send_buf, sctx->send_size);
720 hdr->crc = cpu_to_le32(crc);
721
722 ret = write_buf(sctx->send_filp, sctx->send_buf, sctx->send_size,
723 &sctx->send_off);
724
725 sctx->total_send_size += sctx->send_size;
726 sctx->cmd_send_size[le16_to_cpu(hdr->cmd)] += sctx->send_size;
727 sctx->send_size = 0;
728
729 return ret;
730}
731
732/*
733 * Sends a move instruction to user space
734 */
735static int send_rename(struct send_ctx *sctx,
736 struct fs_path *from, struct fs_path *to)
737{
738 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
739 int ret;
740
741 btrfs_debug(fs_info, "send_rename %s -> %s", from->start, to->start);
742
743 ret = begin_cmd(sctx, BTRFS_SEND_C_RENAME);
744 if (ret < 0)
745 goto out;
746
747 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, from);
748 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH_TO, to);
749
750 ret = send_cmd(sctx);
751
752tlv_put_failure:
753out:
754 return ret;
755}
756
757/*
758 * Sends a link instruction to user space
759 */
760static int send_link(struct send_ctx *sctx,
761 struct fs_path *path, struct fs_path *lnk)
762{
763 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
764 int ret;
765
766 btrfs_debug(fs_info, "send_link %s -> %s", path->start, lnk->start);
767
768 ret = begin_cmd(sctx, BTRFS_SEND_C_LINK);
769 if (ret < 0)
770 goto out;
771
772 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, path);
773 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH_LINK, lnk);
774
775 ret = send_cmd(sctx);
776
777tlv_put_failure:
778out:
779 return ret;
780}
781
782/*
783 * Sends an unlink instruction to user space
784 */
785static int send_unlink(struct send_ctx *sctx, struct fs_path *path)
786{
787 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
788 int ret;
789
790 btrfs_debug(fs_info, "send_unlink %s", path->start);
791
792 ret = begin_cmd(sctx, BTRFS_SEND_C_UNLINK);
793 if (ret < 0)
794 goto out;
795
796 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, path);
797
798 ret = send_cmd(sctx);
799
800tlv_put_failure:
801out:
802 return ret;
803}
804
805/*
806 * Sends a rmdir instruction to user space
807 */
808static int send_rmdir(struct send_ctx *sctx, struct fs_path *path)
809{
810 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
811 int ret;
812
813 btrfs_debug(fs_info, "send_rmdir %s", path->start);
814
815 ret = begin_cmd(sctx, BTRFS_SEND_C_RMDIR);
816 if (ret < 0)
817 goto out;
818
819 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, path);
820
821 ret = send_cmd(sctx);
822
823tlv_put_failure:
824out:
825 return ret;
826}
827
828/*
829 * Helper function to retrieve some fields from an inode item.
830 */
831static int __get_inode_info(struct btrfs_root *root, struct btrfs_path *path,
832 u64 ino, u64 *size, u64 *gen, u64 *mode, u64 *uid,
833 u64 *gid, u64 *rdev)
834{
835 int ret;
836 struct btrfs_inode_item *ii;
837 struct btrfs_key key;
838
839 key.objectid = ino;
840 key.type = BTRFS_INODE_ITEM_KEY;
841 key.offset = 0;
842 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
843 if (ret) {
844 if (ret > 0)
845 ret = -ENOENT;
846 return ret;
847 }
848
849 ii = btrfs_item_ptr(path->nodes[0], path->slots[0],
850 struct btrfs_inode_item);
851 if (size)
852 *size = btrfs_inode_size(path->nodes[0], ii);
853 if (gen)
854 *gen = btrfs_inode_generation(path->nodes[0], ii);
855 if (mode)
856 *mode = btrfs_inode_mode(path->nodes[0], ii);
857 if (uid)
858 *uid = btrfs_inode_uid(path->nodes[0], ii);
859 if (gid)
860 *gid = btrfs_inode_gid(path->nodes[0], ii);
861 if (rdev)
862 *rdev = btrfs_inode_rdev(path->nodes[0], ii);
863
864 return ret;
865}
866
867static int get_inode_info(struct btrfs_root *root,
868 u64 ino, u64 *size, u64 *gen,
869 u64 *mode, u64 *uid, u64 *gid,
870 u64 *rdev)
871{
872 struct btrfs_path *path;
873 int ret;
874
875 path = alloc_path_for_send();
876 if (!path)
877 return -ENOMEM;
878 ret = __get_inode_info(root, path, ino, size, gen, mode, uid, gid,
879 rdev);
880 btrfs_free_path(path);
881 return ret;
882}
883
884typedef int (*iterate_inode_ref_t)(int num, u64 dir, int index,
885 struct fs_path *p,
886 void *ctx);
887
888/*
889 * Helper function to iterate the entries in ONE btrfs_inode_ref or
890 * btrfs_inode_extref.
891 * The iterate callback may return a non zero value to stop iteration. This can
892 * be a negative value for error codes or 1 to simply stop it.
893 *
894 * path must point to the INODE_REF or INODE_EXTREF when called.
895 */
896static int iterate_inode_ref(struct btrfs_root *root, struct btrfs_path *path,
897 struct btrfs_key *found_key, int resolve,
898 iterate_inode_ref_t iterate, void *ctx)
899{
900 struct extent_buffer *eb = path->nodes[0];
901 struct btrfs_item *item;
902 struct btrfs_inode_ref *iref;
903 struct btrfs_inode_extref *extref;
904 struct btrfs_path *tmp_path;
905 struct fs_path *p;
906 u32 cur = 0;
907 u32 total;
908 int slot = path->slots[0];
909 u32 name_len;
910 char *start;
911 int ret = 0;
912 int num = 0;
913 int index;
914 u64 dir;
915 unsigned long name_off;
916 unsigned long elem_size;
917 unsigned long ptr;
918
919 p = fs_path_alloc_reversed();
920 if (!p)
921 return -ENOMEM;
922
923 tmp_path = alloc_path_for_send();
924 if (!tmp_path) {
925 fs_path_free(p);
926 return -ENOMEM;
927 }
928
929
930 if (found_key->type == BTRFS_INODE_REF_KEY) {
931 ptr = (unsigned long)btrfs_item_ptr(eb, slot,
932 struct btrfs_inode_ref);
933 item = btrfs_item_nr(slot);
934 total = btrfs_item_size(eb, item);
935 elem_size = sizeof(*iref);
936 } else {
937 ptr = btrfs_item_ptr_offset(eb, slot);
938 total = btrfs_item_size_nr(eb, slot);
939 elem_size = sizeof(*extref);
940 }
941
942 while (cur < total) {
943 fs_path_reset(p);
944
945 if (found_key->type == BTRFS_INODE_REF_KEY) {
946 iref = (struct btrfs_inode_ref *)(ptr + cur);
947 name_len = btrfs_inode_ref_name_len(eb, iref);
948 name_off = (unsigned long)(iref + 1);
949 index = btrfs_inode_ref_index(eb, iref);
950 dir = found_key->offset;
951 } else {
952 extref = (struct btrfs_inode_extref *)(ptr + cur);
953 name_len = btrfs_inode_extref_name_len(eb, extref);
954 name_off = (unsigned long)&extref->name;
955 index = btrfs_inode_extref_index(eb, extref);
956 dir = btrfs_inode_extref_parent(eb, extref);
957 }
958
959 if (resolve) {
960 start = btrfs_ref_to_path(root, tmp_path, name_len,
961 name_off, eb, dir,
962 p->buf, p->buf_len);
963 if (IS_ERR(start)) {
964 ret = PTR_ERR(start);
965 goto out;
966 }
967 if (start < p->buf) {
968 /* overflow , try again with larger buffer */
969 ret = fs_path_ensure_buf(p,
970 p->buf_len + p->buf - start);
971 if (ret < 0)
972 goto out;
973 start = btrfs_ref_to_path(root, tmp_path,
974 name_len, name_off,
975 eb, dir,
976 p->buf, p->buf_len);
977 if (IS_ERR(start)) {
978 ret = PTR_ERR(start);
979 goto out;
980 }
981 if (unlikely(start < p->buf)) {
982 btrfs_err(root->fs_info,
983 "send: path ref buffer underflow for key (%llu %u %llu)",
984 found_key->objectid,
985 found_key->type,
986 found_key->offset);
987 ret = -EINVAL;
988 goto out;
989 }
990 }
991 p->start = start;
992 } else {
993 ret = fs_path_add_from_extent_buffer(p, eb, name_off,
994 name_len);
995 if (ret < 0)
996 goto out;
997 }
998
999 cur += elem_size + name_len;
1000 ret = iterate(num, dir, index, p, ctx);
1001 if (ret)
1002 goto out;
1003 num++;
1004 }
1005
1006out:
1007 btrfs_free_path(tmp_path);
1008 fs_path_free(p);
1009 return ret;
1010}
1011
1012typedef int (*iterate_dir_item_t)(int num, struct btrfs_key *di_key,
1013 const char *name, int name_len,
1014 const char *data, int data_len,
1015 u8 type, void *ctx);
1016
1017/*
1018 * Helper function to iterate the entries in ONE btrfs_dir_item.
1019 * The iterate callback may return a non zero value to stop iteration. This can
1020 * be a negative value for error codes or 1 to simply stop it.
1021 *
1022 * path must point to the dir item when called.
1023 */
1024static int iterate_dir_item(struct btrfs_root *root, struct btrfs_path *path,
1025 iterate_dir_item_t iterate, void *ctx)
1026{
1027 int ret = 0;
1028 struct extent_buffer *eb;
1029 struct btrfs_item *item;
1030 struct btrfs_dir_item *di;
1031 struct btrfs_key di_key;
1032 char *buf = NULL;
1033 int buf_len;
1034 u32 name_len;
1035 u32 data_len;
1036 u32 cur;
1037 u32 len;
1038 u32 total;
1039 int slot;
1040 int num;
1041 u8 type;
1042
1043 /*
1044 * Start with a small buffer (1 page). If later we end up needing more
1045 * space, which can happen for xattrs on a fs with a leaf size greater
1046 * then the page size, attempt to increase the buffer. Typically xattr
1047 * values are small.
1048 */
1049 buf_len = PATH_MAX;
1050 buf = kmalloc(buf_len, GFP_KERNEL);
1051 if (!buf) {
1052 ret = -ENOMEM;
1053 goto out;
1054 }
1055
1056 eb = path->nodes[0];
1057 slot = path->slots[0];
1058 item = btrfs_item_nr(slot);
1059 di = btrfs_item_ptr(eb, slot, struct btrfs_dir_item);
1060 cur = 0;
1061 len = 0;
1062 total = btrfs_item_size(eb, item);
1063
1064 num = 0;
1065 while (cur < total) {
1066 name_len = btrfs_dir_name_len(eb, di);
1067 data_len = btrfs_dir_data_len(eb, di);
1068 type = btrfs_dir_type(eb, di);
1069 btrfs_dir_item_key_to_cpu(eb, di, &di_key);
1070
1071 if (type == BTRFS_FT_XATTR) {
1072 if (name_len > XATTR_NAME_MAX) {
1073 ret = -ENAMETOOLONG;
1074 goto out;
1075 }
1076 if (name_len + data_len >
1077 BTRFS_MAX_XATTR_SIZE(root->fs_info)) {
1078 ret = -E2BIG;
1079 goto out;
1080 }
1081 } else {
1082 /*
1083 * Path too long
1084 */
1085 if (name_len + data_len > PATH_MAX) {
1086 ret = -ENAMETOOLONG;
1087 goto out;
1088 }
1089 }
1090
1091 if (name_len + data_len > buf_len) {
1092 buf_len = name_len + data_len;
1093 if (is_vmalloc_addr(buf)) {
1094 vfree(buf);
1095 buf = NULL;
1096 } else {
1097 char *tmp = krealloc(buf, buf_len,
1098 GFP_KERNEL | __GFP_NOWARN);
1099
1100 if (!tmp)
1101 kfree(buf);
1102 buf = tmp;
1103 }
1104 if (!buf) {
1105 buf = kvmalloc(buf_len, GFP_KERNEL);
1106 if (!buf) {
1107 ret = -ENOMEM;
1108 goto out;
1109 }
1110 }
1111 }
1112
1113 read_extent_buffer(eb, buf, (unsigned long)(di + 1),
1114 name_len + data_len);
1115
1116 len = sizeof(*di) + name_len + data_len;
1117 di = (struct btrfs_dir_item *)((char *)di + len);
1118 cur += len;
1119
1120 ret = iterate(num, &di_key, buf, name_len, buf + name_len,
1121 data_len, type, ctx);
1122 if (ret < 0)
1123 goto out;
1124 if (ret) {
1125 ret = 0;
1126 goto out;
1127 }
1128
1129 num++;
1130 }
1131
1132out:
1133 kvfree(buf);
1134 return ret;
1135}
1136
1137static int __copy_first_ref(int num, u64 dir, int index,
1138 struct fs_path *p, void *ctx)
1139{
1140 int ret;
1141 struct fs_path *pt = ctx;
1142
1143 ret = fs_path_copy(pt, p);
1144 if (ret < 0)
1145 return ret;
1146
1147 /* we want the first only */
1148 return 1;
1149}
1150
1151/*
1152 * Retrieve the first path of an inode. If an inode has more then one
1153 * ref/hardlink, this is ignored.
1154 */
1155static int get_inode_path(struct btrfs_root *root,
1156 u64 ino, struct fs_path *path)
1157{
1158 int ret;
1159 struct btrfs_key key, found_key;
1160 struct btrfs_path *p;
1161
1162 p = alloc_path_for_send();
1163 if (!p)
1164 return -ENOMEM;
1165
1166 fs_path_reset(path);
1167
1168 key.objectid = ino;
1169 key.type = BTRFS_INODE_REF_KEY;
1170 key.offset = 0;
1171
1172 ret = btrfs_search_slot_for_read(root, &key, p, 1, 0);
1173 if (ret < 0)
1174 goto out;
1175 if (ret) {
1176 ret = 1;
1177 goto out;
1178 }
1179 btrfs_item_key_to_cpu(p->nodes[0], &found_key, p->slots[0]);
1180 if (found_key.objectid != ino ||
1181 (found_key.type != BTRFS_INODE_REF_KEY &&
1182 found_key.type != BTRFS_INODE_EXTREF_KEY)) {
1183 ret = -ENOENT;
1184 goto out;
1185 }
1186
1187 ret = iterate_inode_ref(root, p, &found_key, 1,
1188 __copy_first_ref, path);
1189 if (ret < 0)
1190 goto out;
1191 ret = 0;
1192
1193out:
1194 btrfs_free_path(p);
1195 return ret;
1196}
1197
1198struct backref_ctx {
1199 struct send_ctx *sctx;
1200
1201 /* number of total found references */
1202 u64 found;
1203
1204 /*
1205 * used for clones found in send_root. clones found behind cur_objectid
1206 * and cur_offset are not considered as allowed clones.
1207 */
1208 u64 cur_objectid;
1209 u64 cur_offset;
1210
1211 /* may be truncated in case it's the last extent in a file */
1212 u64 extent_len;
1213
1214 /* data offset in the file extent item */
1215 u64 data_offset;
1216
1217 /* Just to check for bugs in backref resolving */
1218 int found_itself;
1219};
1220
1221static int __clone_root_cmp_bsearch(const void *key, const void *elt)
1222{
1223 u64 root = (u64)(uintptr_t)key;
1224 struct clone_root *cr = (struct clone_root *)elt;
1225
1226 if (root < cr->root->root_key.objectid)
1227 return -1;
1228 if (root > cr->root->root_key.objectid)
1229 return 1;
1230 return 0;
1231}
1232
1233static int __clone_root_cmp_sort(const void *e1, const void *e2)
1234{
1235 struct clone_root *cr1 = (struct clone_root *)e1;
1236 struct clone_root *cr2 = (struct clone_root *)e2;
1237
1238 if (cr1->root->root_key.objectid < cr2->root->root_key.objectid)
1239 return -1;
1240 if (cr1->root->root_key.objectid > cr2->root->root_key.objectid)
1241 return 1;
1242 return 0;
1243}
1244
1245/*
1246 * Called for every backref that is found for the current extent.
1247 * Results are collected in sctx->clone_roots->ino/offset/found_refs
1248 */
1249static int __iterate_backrefs(u64 ino, u64 offset, u64 root, void *ctx_)
1250{
1251 struct backref_ctx *bctx = ctx_;
1252 struct clone_root *found;
1253
1254 /* First check if the root is in the list of accepted clone sources */
1255 found = bsearch((void *)(uintptr_t)root, bctx->sctx->clone_roots,
1256 bctx->sctx->clone_roots_cnt,
1257 sizeof(struct clone_root),
1258 __clone_root_cmp_bsearch);
1259 if (!found)
1260 return 0;
1261
1262 if (found->root == bctx->sctx->send_root &&
1263 ino == bctx->cur_objectid &&
1264 offset == bctx->cur_offset) {
1265 bctx->found_itself = 1;
1266 }
1267
1268 /*
1269 * Make sure we don't consider clones from send_root that are
1270 * behind the current inode/offset.
1271 */
1272 if (found->root == bctx->sctx->send_root) {
1273 /*
1274 * If the source inode was not yet processed we can't issue a
1275 * clone operation, as the source extent does not exist yet at
1276 * the destination of the stream.
1277 */
1278 if (ino > bctx->cur_objectid)
1279 return 0;
1280 /*
1281 * We clone from the inode currently being sent as long as the
1282 * source extent is already processed, otherwise we could try
1283 * to clone from an extent that does not exist yet at the
1284 * destination of the stream.
1285 */
1286 if (ino == bctx->cur_objectid &&
1287 offset + bctx->extent_len >
1288 bctx->sctx->cur_inode_next_write_offset)
1289 return 0;
1290 }
1291
1292 bctx->found++;
1293 found->found_refs++;
1294 if (ino < found->ino) {
1295 found->ino = ino;
1296 found->offset = offset;
1297 } else if (found->ino == ino) {
1298 /*
1299 * same extent found more then once in the same file.
1300 */
1301 if (found->offset > offset + bctx->extent_len)
1302 found->offset = offset;
1303 }
1304
1305 return 0;
1306}
1307
1308/*
1309 * Given an inode, offset and extent item, it finds a good clone for a clone
1310 * instruction. Returns -ENOENT when none could be found. The function makes
1311 * sure that the returned clone is usable at the point where sending is at the
1312 * moment. This means, that no clones are accepted which lie behind the current
1313 * inode+offset.
1314 *
1315 * path must point to the extent item when called.
1316 */
1317static int find_extent_clone(struct send_ctx *sctx,
1318 struct btrfs_path *path,
1319 u64 ino, u64 data_offset,
1320 u64 ino_size,
1321 struct clone_root **found)
1322{
1323 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
1324 int ret;
1325 int extent_type;
1326 u64 logical;
1327 u64 disk_byte;
1328 u64 num_bytes;
1329 u64 extent_item_pos;
1330 u64 flags = 0;
1331 struct btrfs_file_extent_item *fi;
1332 struct extent_buffer *eb = path->nodes[0];
1333 struct backref_ctx *backref_ctx = NULL;
1334 struct clone_root *cur_clone_root;
1335 struct btrfs_key found_key;
1336 struct btrfs_path *tmp_path;
1337 struct btrfs_extent_item *ei;
1338 int compressed;
1339 u32 i;
1340
1341 tmp_path = alloc_path_for_send();
1342 if (!tmp_path)
1343 return -ENOMEM;
1344
1345 /* We only use this path under the commit sem */
1346 tmp_path->need_commit_sem = 0;
1347
1348 backref_ctx = kmalloc(sizeof(*backref_ctx), GFP_KERNEL);
1349 if (!backref_ctx) {
1350 ret = -ENOMEM;
1351 goto out;
1352 }
1353
1354 if (data_offset >= ino_size) {
1355 /*
1356 * There may be extents that lie behind the file's size.
1357 * I at least had this in combination with snapshotting while
1358 * writing large files.
1359 */
1360 ret = 0;
1361 goto out;
1362 }
1363
1364 fi = btrfs_item_ptr(eb, path->slots[0],
1365 struct btrfs_file_extent_item);
1366 extent_type = btrfs_file_extent_type(eb, fi);
1367 if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1368 ret = -ENOENT;
1369 goto out;
1370 }
1371 compressed = btrfs_file_extent_compression(eb, fi);
1372
1373 num_bytes = btrfs_file_extent_num_bytes(eb, fi);
1374 disk_byte = btrfs_file_extent_disk_bytenr(eb, fi);
1375 if (disk_byte == 0) {
1376 ret = -ENOENT;
1377 goto out;
1378 }
1379 logical = disk_byte + btrfs_file_extent_offset(eb, fi);
1380
1381 down_read(&fs_info->commit_root_sem);
1382 ret = extent_from_logical(fs_info, disk_byte, tmp_path,
1383 &found_key, &flags);
1384 up_read(&fs_info->commit_root_sem);
1385
1386 if (ret < 0)
1387 goto out;
1388 if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
1389 ret = -EIO;
1390 goto out;
1391 }
1392
1393 ei = btrfs_item_ptr(tmp_path->nodes[0], tmp_path->slots[0],
1394 struct btrfs_extent_item);
1395 /*
1396 * Backreference walking (iterate_extent_inodes() below) is currently
1397 * too expensive when an extent has a large number of references, both
1398 * in time spent and used memory. So for now just fallback to write
1399 * operations instead of clone operations when an extent has more than
1400 * a certain amount of references.
1401 */
1402 if (btrfs_extent_refs(tmp_path->nodes[0], ei) > SEND_MAX_EXTENT_REFS) {
1403 ret = -ENOENT;
1404 goto out;
1405 }
1406 btrfs_release_path(tmp_path);
1407
1408 /*
1409 * Setup the clone roots.
1410 */
1411 for (i = 0; i < sctx->clone_roots_cnt; i++) {
1412 cur_clone_root = sctx->clone_roots + i;
1413 cur_clone_root->ino = (u64)-1;
1414 cur_clone_root->offset = 0;
1415 cur_clone_root->found_refs = 0;
1416 }
1417
1418 backref_ctx->sctx = sctx;
1419 backref_ctx->found = 0;
1420 backref_ctx->cur_objectid = ino;
1421 backref_ctx->cur_offset = data_offset;
1422 backref_ctx->found_itself = 0;
1423 backref_ctx->extent_len = num_bytes;
1424 /*
1425 * For non-compressed extents iterate_extent_inodes() gives us extent
1426 * offsets that already take into account the data offset, but not for
1427 * compressed extents, since the offset is logical and not relative to
1428 * the physical extent locations. We must take this into account to
1429 * avoid sending clone offsets that go beyond the source file's size,
1430 * which would result in the clone ioctl failing with -EINVAL on the
1431 * receiving end.
1432 */
1433 if (compressed == BTRFS_COMPRESS_NONE)
1434 backref_ctx->data_offset = 0;
1435 else
1436 backref_ctx->data_offset = btrfs_file_extent_offset(eb, fi);
1437
1438 /*
1439 * The last extent of a file may be too large due to page alignment.
1440 * We need to adjust extent_len in this case so that the checks in
1441 * __iterate_backrefs work.
1442 */
1443 if (data_offset + num_bytes >= ino_size)
1444 backref_ctx->extent_len = ino_size - data_offset;
1445
1446 /*
1447 * Now collect all backrefs.
1448 */
1449 if (compressed == BTRFS_COMPRESS_NONE)
1450 extent_item_pos = logical - found_key.objectid;
1451 else
1452 extent_item_pos = 0;
1453 ret = iterate_extent_inodes(fs_info, found_key.objectid,
1454 extent_item_pos, 1, __iterate_backrefs,
1455 backref_ctx, false);
1456
1457 if (ret < 0)
1458 goto out;
1459
1460 if (!backref_ctx->found_itself) {
1461 /* found a bug in backref code? */
1462 ret = -EIO;
1463 btrfs_err(fs_info,
1464 "did not find backref in send_root. inode=%llu, offset=%llu, disk_byte=%llu found extent=%llu",
1465 ino, data_offset, disk_byte, found_key.objectid);
1466 goto out;
1467 }
1468
1469 btrfs_debug(fs_info,
1470 "find_extent_clone: data_offset=%llu, ino=%llu, num_bytes=%llu, logical=%llu",
1471 data_offset, ino, num_bytes, logical);
1472
1473 if (!backref_ctx->found)
1474 btrfs_debug(fs_info, "no clones found");
1475
1476 cur_clone_root = NULL;
1477 for (i = 0; i < sctx->clone_roots_cnt; i++) {
1478 if (sctx->clone_roots[i].found_refs) {
1479 if (!cur_clone_root)
1480 cur_clone_root = sctx->clone_roots + i;
1481 else if (sctx->clone_roots[i].root == sctx->send_root)
1482 /* prefer clones from send_root over others */
1483 cur_clone_root = sctx->clone_roots + i;
1484 }
1485
1486 }
1487
1488 if (cur_clone_root) {
1489 *found = cur_clone_root;
1490 ret = 0;
1491 } else {
1492 ret = -ENOENT;
1493 }
1494
1495out:
1496 btrfs_free_path(tmp_path);
1497 kfree(backref_ctx);
1498 return ret;
1499}
1500
1501static int read_symlink(struct btrfs_root *root,
1502 u64 ino,
1503 struct fs_path *dest)
1504{
1505 int ret;
1506 struct btrfs_path *path;
1507 struct btrfs_key key;
1508 struct btrfs_file_extent_item *ei;
1509 u8 type;
1510 u8 compression;
1511 unsigned long off;
1512 int len;
1513
1514 path = alloc_path_for_send();
1515 if (!path)
1516 return -ENOMEM;
1517
1518 key.objectid = ino;
1519 key.type = BTRFS_EXTENT_DATA_KEY;
1520 key.offset = 0;
1521 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1522 if (ret < 0)
1523 goto out;
1524 if (ret) {
1525 /*
1526 * An empty symlink inode. Can happen in rare error paths when
1527 * creating a symlink (transaction committed before the inode
1528 * eviction handler removed the symlink inode items and a crash
1529 * happened in between or the subvol was snapshoted in between).
1530 * Print an informative message to dmesg/syslog so that the user
1531 * can delete the symlink.
1532 */
1533 btrfs_err(root->fs_info,
1534 "Found empty symlink inode %llu at root %llu",
1535 ino, root->root_key.objectid);
1536 ret = -EIO;
1537 goto out;
1538 }
1539
1540 ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
1541 struct btrfs_file_extent_item);
1542 type = btrfs_file_extent_type(path->nodes[0], ei);
1543 compression = btrfs_file_extent_compression(path->nodes[0], ei);
1544 BUG_ON(type != BTRFS_FILE_EXTENT_INLINE);
1545 BUG_ON(compression);
1546
1547 off = btrfs_file_extent_inline_start(ei);
1548 len = btrfs_file_extent_ram_bytes(path->nodes[0], ei);
1549
1550 ret = fs_path_add_from_extent_buffer(dest, path->nodes[0], off, len);
1551
1552out:
1553 btrfs_free_path(path);
1554 return ret;
1555}
1556
1557/*
1558 * Helper function to generate a file name that is unique in the root of
1559 * send_root and parent_root. This is used to generate names for orphan inodes.
1560 */
1561static int gen_unique_name(struct send_ctx *sctx,
1562 u64 ino, u64 gen,
1563 struct fs_path *dest)
1564{
1565 int ret = 0;
1566 struct btrfs_path *path;
1567 struct btrfs_dir_item *di;
1568 char tmp[64];
1569 int len;
1570 u64 idx = 0;
1571
1572 path = alloc_path_for_send();
1573 if (!path)
1574 return -ENOMEM;
1575
1576 while (1) {
1577 len = snprintf(tmp, sizeof(tmp), "o%llu-%llu-%llu",
1578 ino, gen, idx);
1579 ASSERT(len < sizeof(tmp));
1580
1581 di = btrfs_lookup_dir_item(NULL, sctx->send_root,
1582 path, BTRFS_FIRST_FREE_OBJECTID,
1583 tmp, strlen(tmp), 0);
1584 btrfs_release_path(path);
1585 if (IS_ERR(di)) {
1586 ret = PTR_ERR(di);
1587 goto out;
1588 }
1589 if (di) {
1590 /* not unique, try again */
1591 idx++;
1592 continue;
1593 }
1594
1595 if (!sctx->parent_root) {
1596 /* unique */
1597 ret = 0;
1598 break;
1599 }
1600
1601 di = btrfs_lookup_dir_item(NULL, sctx->parent_root,
1602 path, BTRFS_FIRST_FREE_OBJECTID,
1603 tmp, strlen(tmp), 0);
1604 btrfs_release_path(path);
1605 if (IS_ERR(di)) {
1606 ret = PTR_ERR(di);
1607 goto out;
1608 }
1609 if (di) {
1610 /* not unique, try again */
1611 idx++;
1612 continue;
1613 }
1614 /* unique */
1615 break;
1616 }
1617
1618 ret = fs_path_add(dest, tmp, strlen(tmp));
1619
1620out:
1621 btrfs_free_path(path);
1622 return ret;
1623}
1624
1625enum inode_state {
1626 inode_state_no_change,
1627 inode_state_will_create,
1628 inode_state_did_create,
1629 inode_state_will_delete,
1630 inode_state_did_delete,
1631};
1632
1633static int get_cur_inode_state(struct send_ctx *sctx, u64 ino, u64 gen)
1634{
1635 int ret;
1636 int left_ret;
1637 int right_ret;
1638 u64 left_gen;
1639 u64 right_gen;
1640
1641 ret = get_inode_info(sctx->send_root, ino, NULL, &left_gen, NULL, NULL,
1642 NULL, NULL);
1643 if (ret < 0 && ret != -ENOENT)
1644 goto out;
1645 left_ret = ret;
1646
1647 if (!sctx->parent_root) {
1648 right_ret = -ENOENT;
1649 } else {
1650 ret = get_inode_info(sctx->parent_root, ino, NULL, &right_gen,
1651 NULL, NULL, NULL, NULL);
1652 if (ret < 0 && ret != -ENOENT)
1653 goto out;
1654 right_ret = ret;
1655 }
1656
1657 if (!left_ret && !right_ret) {
1658 if (left_gen == gen && right_gen == gen) {
1659 ret = inode_state_no_change;
1660 } else if (left_gen == gen) {
1661 if (ino < sctx->send_progress)
1662 ret = inode_state_did_create;
1663 else
1664 ret = inode_state_will_create;
1665 } else if (right_gen == gen) {
1666 if (ino < sctx->send_progress)
1667 ret = inode_state_did_delete;
1668 else
1669 ret = inode_state_will_delete;
1670 } else {
1671 ret = -ENOENT;
1672 }
1673 } else if (!left_ret) {
1674 if (left_gen == gen) {
1675 if (ino < sctx->send_progress)
1676 ret = inode_state_did_create;
1677 else
1678 ret = inode_state_will_create;
1679 } else {
1680 ret = -ENOENT;
1681 }
1682 } else if (!right_ret) {
1683 if (right_gen == gen) {
1684 if (ino < sctx->send_progress)
1685 ret = inode_state_did_delete;
1686 else
1687 ret = inode_state_will_delete;
1688 } else {
1689 ret = -ENOENT;
1690 }
1691 } else {
1692 ret = -ENOENT;
1693 }
1694
1695out:
1696 return ret;
1697}
1698
1699static int is_inode_existent(struct send_ctx *sctx, u64 ino, u64 gen)
1700{
1701 int ret;
1702
1703 if (ino == BTRFS_FIRST_FREE_OBJECTID)
1704 return 1;
1705
1706 ret = get_cur_inode_state(sctx, ino, gen);
1707 if (ret < 0)
1708 goto out;
1709
1710 if (ret == inode_state_no_change ||
1711 ret == inode_state_did_create ||
1712 ret == inode_state_will_delete)
1713 ret = 1;
1714 else
1715 ret = 0;
1716
1717out:
1718 return ret;
1719}
1720
1721/*
1722 * Helper function to lookup a dir item in a dir.
1723 */
1724static int lookup_dir_item_inode(struct btrfs_root *root,
1725 u64 dir, const char *name, int name_len,
1726 u64 *found_inode,
1727 u8 *found_type)
1728{
1729 int ret = 0;
1730 struct btrfs_dir_item *di;
1731 struct btrfs_key key;
1732 struct btrfs_path *path;
1733
1734 path = alloc_path_for_send();
1735 if (!path)
1736 return -ENOMEM;
1737
1738 di = btrfs_lookup_dir_item(NULL, root, path,
1739 dir, name, name_len, 0);
1740 if (IS_ERR_OR_NULL(di)) {
1741 ret = di ? PTR_ERR(di) : -ENOENT;
1742 goto out;
1743 }
1744 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
1745 if (key.type == BTRFS_ROOT_ITEM_KEY) {
1746 ret = -ENOENT;
1747 goto out;
1748 }
1749 *found_inode = key.objectid;
1750 *found_type = btrfs_dir_type(path->nodes[0], di);
1751
1752out:
1753 btrfs_free_path(path);
1754 return ret;
1755}
1756
1757/*
1758 * Looks up the first btrfs_inode_ref of a given ino. It returns the parent dir,
1759 * generation of the parent dir and the name of the dir entry.
1760 */
1761static int get_first_ref(struct btrfs_root *root, u64 ino,
1762 u64 *dir, u64 *dir_gen, struct fs_path *name)
1763{
1764 int ret;
1765 struct btrfs_key key;
1766 struct btrfs_key found_key;
1767 struct btrfs_path *path;
1768 int len;
1769 u64 parent_dir;
1770
1771 path = alloc_path_for_send();
1772 if (!path)
1773 return -ENOMEM;
1774
1775 key.objectid = ino;
1776 key.type = BTRFS_INODE_REF_KEY;
1777 key.offset = 0;
1778
1779 ret = btrfs_search_slot_for_read(root, &key, path, 1, 0);
1780 if (ret < 0)
1781 goto out;
1782 if (!ret)
1783 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1784 path->slots[0]);
1785 if (ret || found_key.objectid != ino ||
1786 (found_key.type != BTRFS_INODE_REF_KEY &&
1787 found_key.type != BTRFS_INODE_EXTREF_KEY)) {
1788 ret = -ENOENT;
1789 goto out;
1790 }
1791
1792 if (found_key.type == BTRFS_INODE_REF_KEY) {
1793 struct btrfs_inode_ref *iref;
1794 iref = btrfs_item_ptr(path->nodes[0], path->slots[0],
1795 struct btrfs_inode_ref);
1796 len = btrfs_inode_ref_name_len(path->nodes[0], iref);
1797 ret = fs_path_add_from_extent_buffer(name, path->nodes[0],
1798 (unsigned long)(iref + 1),
1799 len);
1800 parent_dir = found_key.offset;
1801 } else {
1802 struct btrfs_inode_extref *extref;
1803 extref = btrfs_item_ptr(path->nodes[0], path->slots[0],
1804 struct btrfs_inode_extref);
1805 len = btrfs_inode_extref_name_len(path->nodes[0], extref);
1806 ret = fs_path_add_from_extent_buffer(name, path->nodes[0],
1807 (unsigned long)&extref->name, len);
1808 parent_dir = btrfs_inode_extref_parent(path->nodes[0], extref);
1809 }
1810 if (ret < 0)
1811 goto out;
1812 btrfs_release_path(path);
1813
1814 if (dir_gen) {
1815 ret = get_inode_info(root, parent_dir, NULL, dir_gen, NULL,
1816 NULL, NULL, NULL);
1817 if (ret < 0)
1818 goto out;
1819 }
1820
1821 *dir = parent_dir;
1822
1823out:
1824 btrfs_free_path(path);
1825 return ret;
1826}
1827
1828static int is_first_ref(struct btrfs_root *root,
1829 u64 ino, u64 dir,
1830 const char *name, int name_len)
1831{
1832 int ret;
1833 struct fs_path *tmp_name;
1834 u64 tmp_dir;
1835
1836 tmp_name = fs_path_alloc();
1837 if (!tmp_name)
1838 return -ENOMEM;
1839
1840 ret = get_first_ref(root, ino, &tmp_dir, NULL, tmp_name);
1841 if (ret < 0)
1842 goto out;
1843
1844 if (dir != tmp_dir || name_len != fs_path_len(tmp_name)) {
1845 ret = 0;
1846 goto out;
1847 }
1848
1849 ret = !memcmp(tmp_name->start, name, name_len);
1850
1851out:
1852 fs_path_free(tmp_name);
1853 return ret;
1854}
1855
1856/*
1857 * Used by process_recorded_refs to determine if a new ref would overwrite an
1858 * already existing ref. In case it detects an overwrite, it returns the
1859 * inode/gen in who_ino/who_gen.
1860 * When an overwrite is detected, process_recorded_refs does proper orphanizing
1861 * to make sure later references to the overwritten inode are possible.
1862 * Orphanizing is however only required for the first ref of an inode.
1863 * process_recorded_refs does an additional is_first_ref check to see if
1864 * orphanizing is really required.
1865 */
1866static int will_overwrite_ref(struct send_ctx *sctx, u64 dir, u64 dir_gen,
1867 const char *name, int name_len,
1868 u64 *who_ino, u64 *who_gen, u64 *who_mode)
1869{
1870 int ret = 0;
1871 u64 gen;
1872 u64 other_inode = 0;
1873 u8 other_type = 0;
1874
1875 if (!sctx->parent_root)
1876 goto out;
1877
1878 ret = is_inode_existent(sctx, dir, dir_gen);
1879 if (ret <= 0)
1880 goto out;
1881
1882 /*
1883 * If we have a parent root we need to verify that the parent dir was
1884 * not deleted and then re-created, if it was then we have no overwrite
1885 * and we can just unlink this entry.
1886 */
1887 if (sctx->parent_root && dir != BTRFS_FIRST_FREE_OBJECTID) {
1888 ret = get_inode_info(sctx->parent_root, dir, NULL, &gen, NULL,
1889 NULL, NULL, NULL);
1890 if (ret < 0 && ret != -ENOENT)
1891 goto out;
1892 if (ret) {
1893 ret = 0;
1894 goto out;
1895 }
1896 if (gen != dir_gen)
1897 goto out;
1898 }
1899
1900 ret = lookup_dir_item_inode(sctx->parent_root, dir, name, name_len,
1901 &other_inode, &other_type);
1902 if (ret < 0 && ret != -ENOENT)
1903 goto out;
1904 if (ret) {
1905 ret = 0;
1906 goto out;
1907 }
1908
1909 /*
1910 * Check if the overwritten ref was already processed. If yes, the ref
1911 * was already unlinked/moved, so we can safely assume that we will not
1912 * overwrite anything at this point in time.
1913 */
1914 if (other_inode > sctx->send_progress ||
1915 is_waiting_for_move(sctx, other_inode)) {
1916 ret = get_inode_info(sctx->parent_root, other_inode, NULL,
1917 who_gen, who_mode, NULL, NULL, NULL);
1918 if (ret < 0)
1919 goto out;
1920
1921 ret = 1;
1922 *who_ino = other_inode;
1923 } else {
1924 ret = 0;
1925 }
1926
1927out:
1928 return ret;
1929}
1930
1931/*
1932 * Checks if the ref was overwritten by an already processed inode. This is
1933 * used by __get_cur_name_and_parent to find out if the ref was orphanized and
1934 * thus the orphan name needs be used.
1935 * process_recorded_refs also uses it to avoid unlinking of refs that were
1936 * overwritten.
1937 */
1938static int did_overwrite_ref(struct send_ctx *sctx,
1939 u64 dir, u64 dir_gen,
1940 u64 ino, u64 ino_gen,
1941 const char *name, int name_len)
1942{
1943 int ret = 0;
1944 u64 gen;
1945 u64 ow_inode;
1946 u8 other_type;
1947
1948 if (!sctx->parent_root)
1949 goto out;
1950
1951 ret = is_inode_existent(sctx, dir, dir_gen);
1952 if (ret <= 0)
1953 goto out;
1954
1955 if (dir != BTRFS_FIRST_FREE_OBJECTID) {
1956 ret = get_inode_info(sctx->send_root, dir, NULL, &gen, NULL,
1957 NULL, NULL, NULL);
1958 if (ret < 0 && ret != -ENOENT)
1959 goto out;
1960 if (ret) {
1961 ret = 0;
1962 goto out;
1963 }
1964 if (gen != dir_gen)
1965 goto out;
1966 }
1967
1968 /* check if the ref was overwritten by another ref */
1969 ret = lookup_dir_item_inode(sctx->send_root, dir, name, name_len,
1970 &ow_inode, &other_type);
1971 if (ret < 0 && ret != -ENOENT)
1972 goto out;
1973 if (ret) {
1974 /* was never and will never be overwritten */
1975 ret = 0;
1976 goto out;
1977 }
1978
1979 ret = get_inode_info(sctx->send_root, ow_inode, NULL, &gen, NULL, NULL,
1980 NULL, NULL);
1981 if (ret < 0)
1982 goto out;
1983
1984 if (ow_inode == ino && gen == ino_gen) {
1985 ret = 0;
1986 goto out;
1987 }
1988
1989 /*
1990 * We know that it is or will be overwritten. Check this now.
1991 * The current inode being processed might have been the one that caused
1992 * inode 'ino' to be orphanized, therefore check if ow_inode matches
1993 * the current inode being processed.
1994 */
1995 if ((ow_inode < sctx->send_progress) ||
1996 (ino != sctx->cur_ino && ow_inode == sctx->cur_ino &&
1997 gen == sctx->cur_inode_gen))
1998 ret = 1;
1999 else
2000 ret = 0;
2001
2002out:
2003 return ret;
2004}
2005
2006/*
2007 * Same as did_overwrite_ref, but also checks if it is the first ref of an inode
2008 * that got overwritten. This is used by process_recorded_refs to determine
2009 * if it has to use the path as returned by get_cur_path or the orphan name.
2010 */
2011static int did_overwrite_first_ref(struct send_ctx *sctx, u64 ino, u64 gen)
2012{
2013 int ret = 0;
2014 struct fs_path *name = NULL;
2015 u64 dir;
2016 u64 dir_gen;
2017
2018 if (!sctx->parent_root)
2019 goto out;
2020
2021 name = fs_path_alloc();
2022 if (!name)
2023 return -ENOMEM;
2024
2025 ret = get_first_ref(sctx->parent_root, ino, &dir, &dir_gen, name);
2026 if (ret < 0)
2027 goto out;
2028
2029 ret = did_overwrite_ref(sctx, dir, dir_gen, ino, gen,
2030 name->start, fs_path_len(name));
2031
2032out:
2033 fs_path_free(name);
2034 return ret;
2035}
2036
2037/*
2038 * Insert a name cache entry. On 32bit kernels the radix tree index is 32bit,
2039 * so we need to do some special handling in case we have clashes. This function
2040 * takes care of this with the help of name_cache_entry::radix_list.
2041 * In case of error, nce is kfreed.
2042 */
2043static int name_cache_insert(struct send_ctx *sctx,
2044 struct name_cache_entry *nce)
2045{
2046 int ret = 0;
2047 struct list_head *nce_head;
2048
2049 nce_head = radix_tree_lookup(&sctx->name_cache,
2050 (unsigned long)nce->ino);
2051 if (!nce_head) {
2052 nce_head = kmalloc(sizeof(*nce_head), GFP_KERNEL);
2053 if (!nce_head) {
2054 kfree(nce);
2055 return -ENOMEM;
2056 }
2057 INIT_LIST_HEAD(nce_head);
2058
2059 ret = radix_tree_insert(&sctx->name_cache, nce->ino, nce_head);
2060 if (ret < 0) {
2061 kfree(nce_head);
2062 kfree(nce);
2063 return ret;
2064 }
2065 }
2066 list_add_tail(&nce->radix_list, nce_head);
2067 list_add_tail(&nce->list, &sctx->name_cache_list);
2068 sctx->name_cache_size++;
2069
2070 return ret;
2071}
2072
2073static void name_cache_delete(struct send_ctx *sctx,
2074 struct name_cache_entry *nce)
2075{
2076 struct list_head *nce_head;
2077
2078 nce_head = radix_tree_lookup(&sctx->name_cache,
2079 (unsigned long)nce->ino);
2080 if (!nce_head) {
2081 btrfs_err(sctx->send_root->fs_info,
2082 "name_cache_delete lookup failed ino %llu cache size %d, leaking memory",
2083 nce->ino, sctx->name_cache_size);
2084 }
2085
2086 list_del(&nce->radix_list);
2087 list_del(&nce->list);
2088 sctx->name_cache_size--;
2089
2090 /*
2091 * We may not get to the final release of nce_head if the lookup fails
2092 */
2093 if (nce_head && list_empty(nce_head)) {
2094 radix_tree_delete(&sctx->name_cache, (unsigned long)nce->ino);
2095 kfree(nce_head);
2096 }
2097}
2098
2099static struct name_cache_entry *name_cache_search(struct send_ctx *sctx,
2100 u64 ino, u64 gen)
2101{
2102 struct list_head *nce_head;
2103 struct name_cache_entry *cur;
2104
2105 nce_head = radix_tree_lookup(&sctx->name_cache, (unsigned long)ino);
2106 if (!nce_head)
2107 return NULL;
2108
2109 list_for_each_entry(cur, nce_head, radix_list) {
2110 if (cur->ino == ino && cur->gen == gen)
2111 return cur;
2112 }
2113 return NULL;
2114}
2115
2116/*
2117 * Removes the entry from the list and adds it back to the end. This marks the
2118 * entry as recently used so that name_cache_clean_unused does not remove it.
2119 */
2120static void name_cache_used(struct send_ctx *sctx, struct name_cache_entry *nce)
2121{
2122 list_del(&nce->list);
2123 list_add_tail(&nce->list, &sctx->name_cache_list);
2124}
2125
2126/*
2127 * Remove some entries from the beginning of name_cache_list.
2128 */
2129static void name_cache_clean_unused(struct send_ctx *sctx)
2130{
2131 struct name_cache_entry *nce;
2132
2133 if (sctx->name_cache_size < SEND_CTX_NAME_CACHE_CLEAN_SIZE)
2134 return;
2135
2136 while (sctx->name_cache_size > SEND_CTX_MAX_NAME_CACHE_SIZE) {
2137 nce = list_entry(sctx->name_cache_list.next,
2138 struct name_cache_entry, list);
2139 name_cache_delete(sctx, nce);
2140 kfree(nce);
2141 }
2142}
2143
2144static void name_cache_free(struct send_ctx *sctx)
2145{
2146 struct name_cache_entry *nce;
2147
2148 while (!list_empty(&sctx->name_cache_list)) {
2149 nce = list_entry(sctx->name_cache_list.next,
2150 struct name_cache_entry, list);
2151 name_cache_delete(sctx, nce);
2152 kfree(nce);
2153 }
2154}
2155
2156/*
2157 * Used by get_cur_path for each ref up to the root.
2158 * Returns 0 if it succeeded.
2159 * Returns 1 if the inode is not existent or got overwritten. In that case, the
2160 * name is an orphan name. This instructs get_cur_path to stop iterating. If 1
2161 * is returned, parent_ino/parent_gen are not guaranteed to be valid.
2162 * Returns <0 in case of error.
2163 */
2164static int __get_cur_name_and_parent(struct send_ctx *sctx,
2165 u64 ino, u64 gen,
2166 u64 *parent_ino,
2167 u64 *parent_gen,
2168 struct fs_path *dest)
2169{
2170 int ret;
2171 int nce_ret;
2172 struct name_cache_entry *nce = NULL;
2173
2174 /*
2175 * First check if we already did a call to this function with the same
2176 * ino/gen. If yes, check if the cache entry is still up-to-date. If yes
2177 * return the cached result.
2178 */
2179 nce = name_cache_search(sctx, ino, gen);
2180 if (nce) {
2181 if (ino < sctx->send_progress && nce->need_later_update) {
2182 name_cache_delete(sctx, nce);
2183 kfree(nce);
2184 nce = NULL;
2185 } else {
2186 name_cache_used(sctx, nce);
2187 *parent_ino = nce->parent_ino;
2188 *parent_gen = nce->parent_gen;
2189 ret = fs_path_add(dest, nce->name, nce->name_len);
2190 if (ret < 0)
2191 goto out;
2192 ret = nce->ret;
2193 goto out;
2194 }
2195 }
2196
2197 /*
2198 * If the inode is not existent yet, add the orphan name and return 1.
2199 * This should only happen for the parent dir that we determine in
2200 * __record_new_ref
2201 */
2202 ret = is_inode_existent(sctx, ino, gen);
2203 if (ret < 0)
2204 goto out;
2205
2206 if (!ret) {
2207 ret = gen_unique_name(sctx, ino, gen, dest);
2208 if (ret < 0)
2209 goto out;
2210 ret = 1;
2211 goto out_cache;
2212 }
2213
2214 /*
2215 * Depending on whether the inode was already processed or not, use
2216 * send_root or parent_root for ref lookup.
2217 */
2218 if (ino < sctx->send_progress)
2219 ret = get_first_ref(sctx->send_root, ino,
2220 parent_ino, parent_gen, dest);
2221 else
2222 ret = get_first_ref(sctx->parent_root, ino,
2223 parent_ino, parent_gen, dest);
2224 if (ret < 0)
2225 goto out;
2226
2227 /*
2228 * Check if the ref was overwritten by an inode's ref that was processed
2229 * earlier. If yes, treat as orphan and return 1.
2230 */
2231 ret = did_overwrite_ref(sctx, *parent_ino, *parent_gen, ino, gen,
2232 dest->start, dest->end - dest->start);
2233 if (ret < 0)
2234 goto out;
2235 if (ret) {
2236 fs_path_reset(dest);
2237 ret = gen_unique_name(sctx, ino, gen, dest);
2238 if (ret < 0)
2239 goto out;
2240 ret = 1;
2241 }
2242
2243out_cache:
2244 /*
2245 * Store the result of the lookup in the name cache.
2246 */
2247 nce = kmalloc(sizeof(*nce) + fs_path_len(dest) + 1, GFP_KERNEL);
2248 if (!nce) {
2249 ret = -ENOMEM;
2250 goto out;
2251 }
2252
2253 nce->ino = ino;
2254 nce->gen = gen;
2255 nce->parent_ino = *parent_ino;
2256 nce->parent_gen = *parent_gen;
2257 nce->name_len = fs_path_len(dest);
2258 nce->ret = ret;
2259 strcpy(nce->name, dest->start);
2260
2261 if (ino < sctx->send_progress)
2262 nce->need_later_update = 0;
2263 else
2264 nce->need_later_update = 1;
2265
2266 nce_ret = name_cache_insert(sctx, nce);
2267 if (nce_ret < 0)
2268 ret = nce_ret;
2269 name_cache_clean_unused(sctx);
2270
2271out:
2272 return ret;
2273}
2274
2275/*
2276 * Magic happens here. This function returns the first ref to an inode as it
2277 * would look like while receiving the stream at this point in time.
2278 * We walk the path up to the root. For every inode in between, we check if it
2279 * was already processed/sent. If yes, we continue with the parent as found
2280 * in send_root. If not, we continue with the parent as found in parent_root.
2281 * If we encounter an inode that was deleted at this point in time, we use the
2282 * inodes "orphan" name instead of the real name and stop. Same with new inodes
2283 * that were not created yet and overwritten inodes/refs.
2284 *
2285 * When do we have orphan inodes:
2286 * 1. When an inode is freshly created and thus no valid refs are available yet
2287 * 2. When a directory lost all it's refs (deleted) but still has dir items
2288 * inside which were not processed yet (pending for move/delete). If anyone
2289 * tried to get the path to the dir items, it would get a path inside that
2290 * orphan directory.
2291 * 3. When an inode is moved around or gets new links, it may overwrite the ref
2292 * of an unprocessed inode. If in that case the first ref would be
2293 * overwritten, the overwritten inode gets "orphanized". Later when we
2294 * process this overwritten inode, it is restored at a new place by moving
2295 * the orphan inode.
2296 *
2297 * sctx->send_progress tells this function at which point in time receiving
2298 * would be.
2299 */
2300static int get_cur_path(struct send_ctx *sctx, u64 ino, u64 gen,
2301 struct fs_path *dest)
2302{
2303 int ret = 0;
2304 struct fs_path *name = NULL;
2305 u64 parent_inode = 0;
2306 u64 parent_gen = 0;
2307 int stop = 0;
2308
2309 name = fs_path_alloc();
2310 if (!name) {
2311 ret = -ENOMEM;
2312 goto out;
2313 }
2314
2315 dest->reversed = 1;
2316 fs_path_reset(dest);
2317
2318 while (!stop && ino != BTRFS_FIRST_FREE_OBJECTID) {
2319 struct waiting_dir_move *wdm;
2320
2321 fs_path_reset(name);
2322
2323 if (is_waiting_for_rm(sctx, ino, gen)) {
2324 ret = gen_unique_name(sctx, ino, gen, name);
2325 if (ret < 0)
2326 goto out;
2327 ret = fs_path_add_path(dest, name);
2328 break;
2329 }
2330
2331 wdm = get_waiting_dir_move(sctx, ino);
2332 if (wdm && wdm->orphanized) {
2333 ret = gen_unique_name(sctx, ino, gen, name);
2334 stop = 1;
2335 } else if (wdm) {
2336 ret = get_first_ref(sctx->parent_root, ino,
2337 &parent_inode, &parent_gen, name);
2338 } else {
2339 ret = __get_cur_name_and_parent(sctx, ino, gen,
2340 &parent_inode,
2341 &parent_gen, name);
2342 if (ret)
2343 stop = 1;
2344 }
2345
2346 if (ret < 0)
2347 goto out;
2348
2349 ret = fs_path_add_path(dest, name);
2350 if (ret < 0)
2351 goto out;
2352
2353 ino = parent_inode;
2354 gen = parent_gen;
2355 }
2356
2357out:
2358 fs_path_free(name);
2359 if (!ret)
2360 fs_path_unreverse(dest);
2361 return ret;
2362}
2363
2364/*
2365 * Sends a BTRFS_SEND_C_SUBVOL command/item to userspace
2366 */
2367static int send_subvol_begin(struct send_ctx *sctx)
2368{
2369 int ret;
2370 struct btrfs_root *send_root = sctx->send_root;
2371 struct btrfs_root *parent_root = sctx->parent_root;
2372 struct btrfs_path *path;
2373 struct btrfs_key key;
2374 struct btrfs_root_ref *ref;
2375 struct extent_buffer *leaf;
2376 char *name = NULL;
2377 int namelen;
2378
2379 path = btrfs_alloc_path();
2380 if (!path)
2381 return -ENOMEM;
2382
2383 name = kmalloc(BTRFS_PATH_NAME_MAX, GFP_KERNEL);
2384 if (!name) {
2385 btrfs_free_path(path);
2386 return -ENOMEM;
2387 }
2388
2389 key.objectid = send_root->root_key.objectid;
2390 key.type = BTRFS_ROOT_BACKREF_KEY;
2391 key.offset = 0;
2392
2393 ret = btrfs_search_slot_for_read(send_root->fs_info->tree_root,
2394 &key, path, 1, 0);
2395 if (ret < 0)
2396 goto out;
2397 if (ret) {
2398 ret = -ENOENT;
2399 goto out;
2400 }
2401
2402 leaf = path->nodes[0];
2403 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2404 if (key.type != BTRFS_ROOT_BACKREF_KEY ||
2405 key.objectid != send_root->root_key.objectid) {
2406 ret = -ENOENT;
2407 goto out;
2408 }
2409 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
2410 namelen = btrfs_root_ref_name_len(leaf, ref);
2411 read_extent_buffer(leaf, name, (unsigned long)(ref + 1), namelen);
2412 btrfs_release_path(path);
2413
2414 if (parent_root) {
2415 ret = begin_cmd(sctx, BTRFS_SEND_C_SNAPSHOT);
2416 if (ret < 0)
2417 goto out;
2418 } else {
2419 ret = begin_cmd(sctx, BTRFS_SEND_C_SUBVOL);
2420 if (ret < 0)
2421 goto out;
2422 }
2423
2424 TLV_PUT_STRING(sctx, BTRFS_SEND_A_PATH, name, namelen);
2425
2426 if (!btrfs_is_empty_uuid(sctx->send_root->root_item.received_uuid))
2427 TLV_PUT_UUID(sctx, BTRFS_SEND_A_UUID,
2428 sctx->send_root->root_item.received_uuid);
2429 else
2430 TLV_PUT_UUID(sctx, BTRFS_SEND_A_UUID,
2431 sctx->send_root->root_item.uuid);
2432
2433 TLV_PUT_U64(sctx, BTRFS_SEND_A_CTRANSID,
2434 le64_to_cpu(sctx->send_root->root_item.ctransid));
2435 if (parent_root) {
2436 if (!btrfs_is_empty_uuid(parent_root->root_item.received_uuid))
2437 TLV_PUT_UUID(sctx, BTRFS_SEND_A_CLONE_UUID,
2438 parent_root->root_item.received_uuid);
2439 else
2440 TLV_PUT_UUID(sctx, BTRFS_SEND_A_CLONE_UUID,
2441 parent_root->root_item.uuid);
2442 TLV_PUT_U64(sctx, BTRFS_SEND_A_CLONE_CTRANSID,
2443 le64_to_cpu(sctx->parent_root->root_item.ctransid));
2444 }
2445
2446 ret = send_cmd(sctx);
2447
2448tlv_put_failure:
2449out:
2450 btrfs_free_path(path);
2451 kfree(name);
2452 return ret;
2453}
2454
2455static int send_truncate(struct send_ctx *sctx, u64 ino, u64 gen, u64 size)
2456{
2457 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
2458 int ret = 0;
2459 struct fs_path *p;
2460
2461 btrfs_debug(fs_info, "send_truncate %llu size=%llu", ino, size);
2462
2463 p = fs_path_alloc();
2464 if (!p)
2465 return -ENOMEM;
2466
2467 ret = begin_cmd(sctx, BTRFS_SEND_C_TRUNCATE);
2468 if (ret < 0)
2469 goto out;
2470
2471 ret = get_cur_path(sctx, ino, gen, p);
2472 if (ret < 0)
2473 goto out;
2474 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
2475 TLV_PUT_U64(sctx, BTRFS_SEND_A_SIZE, size);
2476
2477 ret = send_cmd(sctx);
2478
2479tlv_put_failure:
2480out:
2481 fs_path_free(p);
2482 return ret;
2483}
2484
2485static int send_chmod(struct send_ctx *sctx, u64 ino, u64 gen, u64 mode)
2486{
2487 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
2488 int ret = 0;
2489 struct fs_path *p;
2490
2491 btrfs_debug(fs_info, "send_chmod %llu mode=%llu", ino, mode);
2492
2493 p = fs_path_alloc();
2494 if (!p)
2495 return -ENOMEM;
2496
2497 ret = begin_cmd(sctx, BTRFS_SEND_C_CHMOD);
2498 if (ret < 0)
2499 goto out;
2500
2501 ret = get_cur_path(sctx, ino, gen, p);
2502 if (ret < 0)
2503 goto out;
2504 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
2505 TLV_PUT_U64(sctx, BTRFS_SEND_A_MODE, mode & 07777);
2506
2507 ret = send_cmd(sctx);
2508
2509tlv_put_failure:
2510out:
2511 fs_path_free(p);
2512 return ret;
2513}
2514
2515static int send_chown(struct send_ctx *sctx, u64 ino, u64 gen, u64 uid, u64 gid)
2516{
2517 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
2518 int ret = 0;
2519 struct fs_path *p;
2520
2521 btrfs_debug(fs_info, "send_chown %llu uid=%llu, gid=%llu",
2522 ino, uid, gid);
2523
2524 p = fs_path_alloc();
2525 if (!p)
2526 return -ENOMEM;
2527
2528 ret = begin_cmd(sctx, BTRFS_SEND_C_CHOWN);
2529 if (ret < 0)
2530 goto out;
2531
2532 ret = get_cur_path(sctx, ino, gen, p);
2533 if (ret < 0)
2534 goto out;
2535 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
2536 TLV_PUT_U64(sctx, BTRFS_SEND_A_UID, uid);
2537 TLV_PUT_U64(sctx, BTRFS_SEND_A_GID, gid);
2538
2539 ret = send_cmd(sctx);
2540
2541tlv_put_failure:
2542out:
2543 fs_path_free(p);
2544 return ret;
2545}
2546
2547static int send_utimes(struct send_ctx *sctx, u64 ino, u64 gen)
2548{
2549 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
2550 int ret = 0;
2551 struct fs_path *p = NULL;
2552 struct btrfs_inode_item *ii;
2553 struct btrfs_path *path = NULL;
2554 struct extent_buffer *eb;
2555 struct btrfs_key key;
2556 int slot;
2557
2558 btrfs_debug(fs_info, "send_utimes %llu", ino);
2559
2560 p = fs_path_alloc();
2561 if (!p)
2562 return -ENOMEM;
2563
2564 path = alloc_path_for_send();
2565 if (!path) {
2566 ret = -ENOMEM;
2567 goto out;
2568 }
2569
2570 key.objectid = ino;
2571 key.type = BTRFS_INODE_ITEM_KEY;
2572 key.offset = 0;
2573 ret = btrfs_search_slot(NULL, sctx->send_root, &key, path, 0, 0);
2574 if (ret > 0)
2575 ret = -ENOENT;
2576 if (ret < 0)
2577 goto out;
2578
2579 eb = path->nodes[0];
2580 slot = path->slots[0];
2581 ii = btrfs_item_ptr(eb, slot, struct btrfs_inode_item);
2582
2583 ret = begin_cmd(sctx, BTRFS_SEND_C_UTIMES);
2584 if (ret < 0)
2585 goto out;
2586
2587 ret = get_cur_path(sctx, ino, gen, p);
2588 if (ret < 0)
2589 goto out;
2590 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
2591 TLV_PUT_BTRFS_TIMESPEC(sctx, BTRFS_SEND_A_ATIME, eb, &ii->atime);
2592 TLV_PUT_BTRFS_TIMESPEC(sctx, BTRFS_SEND_A_MTIME, eb, &ii->mtime);
2593 TLV_PUT_BTRFS_TIMESPEC(sctx, BTRFS_SEND_A_CTIME, eb, &ii->ctime);
2594 /* TODO Add otime support when the otime patches get into upstream */
2595
2596 ret = send_cmd(sctx);
2597
2598tlv_put_failure:
2599out:
2600 fs_path_free(p);
2601 btrfs_free_path(path);
2602 return ret;
2603}
2604
2605/*
2606 * Sends a BTRFS_SEND_C_MKXXX or SYMLINK command to user space. We don't have
2607 * a valid path yet because we did not process the refs yet. So, the inode
2608 * is created as orphan.
2609 */
2610static int send_create_inode(struct send_ctx *sctx, u64 ino)
2611{
2612 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
2613 int ret = 0;
2614 struct fs_path *p;
2615 int cmd;
2616 u64 gen;
2617 u64 mode;
2618 u64 rdev;
2619
2620 btrfs_debug(fs_info, "send_create_inode %llu", ino);
2621
2622 p = fs_path_alloc();
2623 if (!p)
2624 return -ENOMEM;
2625
2626 if (ino != sctx->cur_ino) {
2627 ret = get_inode_info(sctx->send_root, ino, NULL, &gen, &mode,
2628 NULL, NULL, &rdev);
2629 if (ret < 0)
2630 goto out;
2631 } else {
2632 gen = sctx->cur_inode_gen;
2633 mode = sctx->cur_inode_mode;
2634 rdev = sctx->cur_inode_rdev;
2635 }
2636
2637 if (S_ISREG(mode)) {
2638 cmd = BTRFS_SEND_C_MKFILE;
2639 } else if (S_ISDIR(mode)) {
2640 cmd = BTRFS_SEND_C_MKDIR;
2641 } else if (S_ISLNK(mode)) {
2642 cmd = BTRFS_SEND_C_SYMLINK;
2643 } else if (S_ISCHR(mode) || S_ISBLK(mode)) {
2644 cmd = BTRFS_SEND_C_MKNOD;
2645 } else if (S_ISFIFO(mode)) {
2646 cmd = BTRFS_SEND_C_MKFIFO;
2647 } else if (S_ISSOCK(mode)) {
2648 cmd = BTRFS_SEND_C_MKSOCK;
2649 } else {
2650 btrfs_warn(sctx->send_root->fs_info, "unexpected inode type %o",
2651 (int)(mode & S_IFMT));
2652 ret = -EOPNOTSUPP;
2653 goto out;
2654 }
2655
2656 ret = begin_cmd(sctx, cmd);
2657 if (ret < 0)
2658 goto out;
2659
2660 ret = gen_unique_name(sctx, ino, gen, p);
2661 if (ret < 0)
2662 goto out;
2663
2664 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
2665 TLV_PUT_U64(sctx, BTRFS_SEND_A_INO, ino);
2666
2667 if (S_ISLNK(mode)) {
2668 fs_path_reset(p);
2669 ret = read_symlink(sctx->send_root, ino, p);
2670 if (ret < 0)
2671 goto out;
2672 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH_LINK, p);
2673 } else if (S_ISCHR(mode) || S_ISBLK(mode) ||
2674 S_ISFIFO(mode) || S_ISSOCK(mode)) {
2675 TLV_PUT_U64(sctx, BTRFS_SEND_A_RDEV, new_encode_dev(rdev));
2676 TLV_PUT_U64(sctx, BTRFS_SEND_A_MODE, mode);
2677 }
2678
2679 ret = send_cmd(sctx);
2680 if (ret < 0)
2681 goto out;
2682
2683
2684tlv_put_failure:
2685out:
2686 fs_path_free(p);
2687 return ret;
2688}
2689
2690/*
2691 * We need some special handling for inodes that get processed before the parent
2692 * directory got created. See process_recorded_refs for details.
2693 * This function does the check if we already created the dir out of order.
2694 */
2695static int did_create_dir(struct send_ctx *sctx, u64 dir)
2696{
2697 int ret = 0;
2698 struct btrfs_path *path = NULL;
2699 struct btrfs_key key;
2700 struct btrfs_key found_key;
2701 struct btrfs_key di_key;
2702 struct extent_buffer *eb;
2703 struct btrfs_dir_item *di;
2704 int slot;
2705
2706 path = alloc_path_for_send();
2707 if (!path) {
2708 ret = -ENOMEM;
2709 goto out;
2710 }
2711
2712 key.objectid = dir;
2713 key.type = BTRFS_DIR_INDEX_KEY;
2714 key.offset = 0;
2715 ret = btrfs_search_slot(NULL, sctx->send_root, &key, path, 0, 0);
2716 if (ret < 0)
2717 goto out;
2718
2719 while (1) {
2720 eb = path->nodes[0];
2721 slot = path->slots[0];
2722 if (slot >= btrfs_header_nritems(eb)) {
2723 ret = btrfs_next_leaf(sctx->send_root, path);
2724 if (ret < 0) {
2725 goto out;
2726 } else if (ret > 0) {
2727 ret = 0;
2728 break;
2729 }
2730 continue;
2731 }
2732
2733 btrfs_item_key_to_cpu(eb, &found_key, slot);
2734 if (found_key.objectid != key.objectid ||
2735 found_key.type != key.type) {
2736 ret = 0;
2737 goto out;
2738 }
2739
2740 di = btrfs_item_ptr(eb, slot, struct btrfs_dir_item);
2741 btrfs_dir_item_key_to_cpu(eb, di, &di_key);
2742
2743 if (di_key.type != BTRFS_ROOT_ITEM_KEY &&
2744 di_key.objectid < sctx->send_progress) {
2745 ret = 1;
2746 goto out;
2747 }
2748
2749 path->slots[0]++;
2750 }
2751
2752out:
2753 btrfs_free_path(path);
2754 return ret;
2755}
2756
2757/*
2758 * Only creates the inode if it is:
2759 * 1. Not a directory
2760 * 2. Or a directory which was not created already due to out of order
2761 * directories. See did_create_dir and process_recorded_refs for details.
2762 */
2763static int send_create_inode_if_needed(struct send_ctx *sctx)
2764{
2765 int ret;
2766
2767 if (S_ISDIR(sctx->cur_inode_mode)) {
2768 ret = did_create_dir(sctx, sctx->cur_ino);
2769 if (ret < 0)
2770 goto out;
2771 if (ret) {
2772 ret = 0;
2773 goto out;
2774 }
2775 }
2776
2777 ret = send_create_inode(sctx, sctx->cur_ino);
2778 if (ret < 0)
2779 goto out;
2780
2781out:
2782 return ret;
2783}
2784
2785struct recorded_ref {
2786 struct list_head list;
2787 char *name;
2788 struct fs_path *full_path;
2789 u64 dir;
2790 u64 dir_gen;
2791 int name_len;
2792};
2793
2794static void set_ref_path(struct recorded_ref *ref, struct fs_path *path)
2795{
2796 ref->full_path = path;
2797 ref->name = (char *)kbasename(ref->full_path->start);
2798 ref->name_len = ref->full_path->end - ref->name;
2799}
2800
2801/*
2802 * We need to process new refs before deleted refs, but compare_tree gives us
2803 * everything mixed. So we first record all refs and later process them.
2804 * This function is a helper to record one ref.
2805 */
2806static int __record_ref(struct list_head *head, u64 dir,
2807 u64 dir_gen, struct fs_path *path)
2808{
2809 struct recorded_ref *ref;
2810
2811 ref = kmalloc(sizeof(*ref), GFP_KERNEL);
2812 if (!ref)
2813 return -ENOMEM;
2814
2815 ref->dir = dir;
2816 ref->dir_gen = dir_gen;
2817 set_ref_path(ref, path);
2818 list_add_tail(&ref->list, head);
2819 return 0;
2820}
2821
2822static int dup_ref(struct recorded_ref *ref, struct list_head *list)
2823{
2824 struct recorded_ref *new;
2825
2826 new = kmalloc(sizeof(*ref), GFP_KERNEL);
2827 if (!new)
2828 return -ENOMEM;
2829
2830 new->dir = ref->dir;
2831 new->dir_gen = ref->dir_gen;
2832 new->full_path = NULL;
2833 INIT_LIST_HEAD(&new->list);
2834 list_add_tail(&new->list, list);
2835 return 0;
2836}
2837
2838static void __free_recorded_refs(struct list_head *head)
2839{
2840 struct recorded_ref *cur;
2841
2842 while (!list_empty(head)) {
2843 cur = list_entry(head->next, struct recorded_ref, list);
2844 fs_path_free(cur->full_path);
2845 list_del(&cur->list);
2846 kfree(cur);
2847 }
2848}
2849
2850static void free_recorded_refs(struct send_ctx *sctx)
2851{
2852 __free_recorded_refs(&sctx->new_refs);
2853 __free_recorded_refs(&sctx->deleted_refs);
2854}
2855
2856/*
2857 * Renames/moves a file/dir to its orphan name. Used when the first
2858 * ref of an unprocessed inode gets overwritten and for all non empty
2859 * directories.
2860 */
2861static int orphanize_inode(struct send_ctx *sctx, u64 ino, u64 gen,
2862 struct fs_path *path)
2863{
2864 int ret;
2865 struct fs_path *orphan;
2866
2867 orphan = fs_path_alloc();
2868 if (!orphan)
2869 return -ENOMEM;
2870
2871 ret = gen_unique_name(sctx, ino, gen, orphan);
2872 if (ret < 0)
2873 goto out;
2874
2875 ret = send_rename(sctx, path, orphan);
2876
2877out:
2878 fs_path_free(orphan);
2879 return ret;
2880}
2881
2882static struct orphan_dir_info *add_orphan_dir_info(struct send_ctx *sctx,
2883 u64 dir_ino, u64 dir_gen)
2884{
2885 struct rb_node **p = &sctx->orphan_dirs.rb_node;
2886 struct rb_node *parent = NULL;
2887 struct orphan_dir_info *entry, *odi;
2888
2889 while (*p) {
2890 parent = *p;
2891 entry = rb_entry(parent, struct orphan_dir_info, node);
2892 if (dir_ino < entry->ino)
2893 p = &(*p)->rb_left;
2894 else if (dir_ino > entry->ino)
2895 p = &(*p)->rb_right;
2896 else if (dir_gen < entry->gen)
2897 p = &(*p)->rb_left;
2898 else if (dir_gen > entry->gen)
2899 p = &(*p)->rb_right;
2900 else
2901 return entry;
2902 }
2903
2904 odi = kmalloc(sizeof(*odi), GFP_KERNEL);
2905 if (!odi)
2906 return ERR_PTR(-ENOMEM);
2907 odi->ino = dir_ino;
2908 odi->gen = dir_gen;
2909 odi->last_dir_index_offset = 0;
2910
2911 rb_link_node(&odi->node, parent, p);
2912 rb_insert_color(&odi->node, &sctx->orphan_dirs);
2913 return odi;
2914}
2915
2916static struct orphan_dir_info *get_orphan_dir_info(struct send_ctx *sctx,
2917 u64 dir_ino, u64 gen)
2918{
2919 struct rb_node *n = sctx->orphan_dirs.rb_node;
2920 struct orphan_dir_info *entry;
2921
2922 while (n) {
2923 entry = rb_entry(n, struct orphan_dir_info, node);
2924 if (dir_ino < entry->ino)
2925 n = n->rb_left;
2926 else if (dir_ino > entry->ino)
2927 n = n->rb_right;
2928 else if (gen < entry->gen)
2929 n = n->rb_left;
2930 else if (gen > entry->gen)
2931 n = n->rb_right;
2932 else
2933 return entry;
2934 }
2935 return NULL;
2936}
2937
2938static int is_waiting_for_rm(struct send_ctx *sctx, u64 dir_ino, u64 gen)
2939{
2940 struct orphan_dir_info *odi = get_orphan_dir_info(sctx, dir_ino, gen);
2941
2942 return odi != NULL;
2943}
2944
2945static void free_orphan_dir_info(struct send_ctx *sctx,
2946 struct orphan_dir_info *odi)
2947{
2948 if (!odi)
2949 return;
2950 rb_erase(&odi->node, &sctx->orphan_dirs);
2951 kfree(odi);
2952}
2953
2954/*
2955 * Returns 1 if a directory can be removed at this point in time.
2956 * We check this by iterating all dir items and checking if the inode behind
2957 * the dir item was already processed.
2958 */
2959static int can_rmdir(struct send_ctx *sctx, u64 dir, u64 dir_gen,
2960 u64 send_progress)
2961{
2962 int ret = 0;
2963 struct btrfs_root *root = sctx->parent_root;
2964 struct btrfs_path *path;
2965 struct btrfs_key key;
2966 struct btrfs_key found_key;
2967 struct btrfs_key loc;
2968 struct btrfs_dir_item *di;
2969 struct orphan_dir_info *odi = NULL;
2970
2971 /*
2972 * Don't try to rmdir the top/root subvolume dir.
2973 */
2974 if (dir == BTRFS_FIRST_FREE_OBJECTID)
2975 return 0;
2976
2977 path = alloc_path_for_send();
2978 if (!path)
2979 return -ENOMEM;
2980
2981 key.objectid = dir;
2982 key.type = BTRFS_DIR_INDEX_KEY;
2983 key.offset = 0;
2984
2985 odi = get_orphan_dir_info(sctx, dir, dir_gen);
2986 if (odi)
2987 key.offset = odi->last_dir_index_offset;
2988
2989 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2990 if (ret < 0)
2991 goto out;
2992
2993 while (1) {
2994 struct waiting_dir_move *dm;
2995
2996 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
2997 ret = btrfs_next_leaf(root, path);
2998 if (ret < 0)
2999 goto out;
3000 else if (ret > 0)
3001 break;
3002 continue;
3003 }
3004 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
3005 path->slots[0]);
3006 if (found_key.objectid != key.objectid ||
3007 found_key.type != key.type)
3008 break;
3009
3010 di = btrfs_item_ptr(path->nodes[0], path->slots[0],
3011 struct btrfs_dir_item);
3012 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &loc);
3013
3014 dm = get_waiting_dir_move(sctx, loc.objectid);
3015 if (dm) {
3016 odi = add_orphan_dir_info(sctx, dir, dir_gen);
3017 if (IS_ERR(odi)) {
3018 ret = PTR_ERR(odi);
3019 goto out;
3020 }
3021 odi->gen = dir_gen;
3022 odi->last_dir_index_offset = found_key.offset;
3023 dm->rmdir_ino = dir;
3024 dm->rmdir_gen = dir_gen;
3025 ret = 0;
3026 goto out;
3027 }
3028
3029 if (loc.objectid > send_progress) {
3030 odi = add_orphan_dir_info(sctx, dir, dir_gen);
3031 if (IS_ERR(odi)) {
3032 ret = PTR_ERR(odi);
3033 goto out;
3034 }
3035 odi->gen = dir_gen;
3036 odi->last_dir_index_offset = found_key.offset;
3037 ret = 0;
3038 goto out;
3039 }
3040
3041 path->slots[0]++;
3042 }
3043 free_orphan_dir_info(sctx, odi);
3044
3045 ret = 1;
3046
3047out:
3048 btrfs_free_path(path);
3049 return ret;
3050}
3051
3052static int is_waiting_for_move(struct send_ctx *sctx, u64 ino)
3053{
3054 struct waiting_dir_move *entry = get_waiting_dir_move(sctx, ino);
3055
3056 return entry != NULL;
3057}
3058
3059static int add_waiting_dir_move(struct send_ctx *sctx, u64 ino, bool orphanized)
3060{
3061 struct rb_node **p = &sctx->waiting_dir_moves.rb_node;
3062 struct rb_node *parent = NULL;
3063 struct waiting_dir_move *entry, *dm;
3064
3065 dm = kmalloc(sizeof(*dm), GFP_KERNEL);
3066 if (!dm)
3067 return -ENOMEM;
3068 dm->ino = ino;
3069 dm->rmdir_ino = 0;
3070 dm->rmdir_gen = 0;
3071 dm->orphanized = orphanized;
3072
3073 while (*p) {
3074 parent = *p;
3075 entry = rb_entry(parent, struct waiting_dir_move, node);
3076 if (ino < entry->ino) {
3077 p = &(*p)->rb_left;
3078 } else if (ino > entry->ino) {
3079 p = &(*p)->rb_right;
3080 } else {
3081 kfree(dm);
3082 return -EEXIST;
3083 }
3084 }
3085
3086 rb_link_node(&dm->node, parent, p);
3087 rb_insert_color(&dm->node, &sctx->waiting_dir_moves);
3088 return 0;
3089}
3090
3091static struct waiting_dir_move *
3092get_waiting_dir_move(struct send_ctx *sctx, u64 ino)
3093{
3094 struct rb_node *n = sctx->waiting_dir_moves.rb_node;
3095 struct waiting_dir_move *entry;
3096
3097 while (n) {
3098 entry = rb_entry(n, struct waiting_dir_move, node);
3099 if (ino < entry->ino)
3100 n = n->rb_left;
3101 else if (ino > entry->ino)
3102 n = n->rb_right;
3103 else
3104 return entry;
3105 }
3106 return NULL;
3107}
3108
3109static void free_waiting_dir_move(struct send_ctx *sctx,
3110 struct waiting_dir_move *dm)
3111{
3112 if (!dm)
3113 return;
3114 rb_erase(&dm->node, &sctx->waiting_dir_moves);
3115 kfree(dm);
3116}
3117
3118static int add_pending_dir_move(struct send_ctx *sctx,
3119 u64 ino,
3120 u64 ino_gen,
3121 u64 parent_ino,
3122 struct list_head *new_refs,
3123 struct list_head *deleted_refs,
3124 const bool is_orphan)
3125{
3126 struct rb_node **p = &sctx->pending_dir_moves.rb_node;
3127 struct rb_node *parent = NULL;
3128 struct pending_dir_move *entry = NULL, *pm;
3129 struct recorded_ref *cur;
3130 int exists = 0;
3131 int ret;
3132
3133 pm = kmalloc(sizeof(*pm), GFP_KERNEL);
3134 if (!pm)
3135 return -ENOMEM;
3136 pm->parent_ino = parent_ino;
3137 pm->ino = ino;
3138 pm->gen = ino_gen;
3139 INIT_LIST_HEAD(&pm->list);
3140 INIT_LIST_HEAD(&pm->update_refs);
3141 RB_CLEAR_NODE(&pm->node);
3142
3143 while (*p) {
3144 parent = *p;
3145 entry = rb_entry(parent, struct pending_dir_move, node);
3146 if (parent_ino < entry->parent_ino) {
3147 p = &(*p)->rb_left;
3148 } else if (parent_ino > entry->parent_ino) {
3149 p = &(*p)->rb_right;
3150 } else {
3151 exists = 1;
3152 break;
3153 }
3154 }
3155
3156 list_for_each_entry(cur, deleted_refs, list) {
3157 ret = dup_ref(cur, &pm->update_refs);
3158 if (ret < 0)
3159 goto out;
3160 }
3161 list_for_each_entry(cur, new_refs, list) {
3162 ret = dup_ref(cur, &pm->update_refs);
3163 if (ret < 0)
3164 goto out;
3165 }
3166
3167 ret = add_waiting_dir_move(sctx, pm->ino, is_orphan);
3168 if (ret)
3169 goto out;
3170
3171 if (exists) {
3172 list_add_tail(&pm->list, &entry->list);
3173 } else {
3174 rb_link_node(&pm->node, parent, p);
3175 rb_insert_color(&pm->node, &sctx->pending_dir_moves);
3176 }
3177 ret = 0;
3178out:
3179 if (ret) {
3180 __free_recorded_refs(&pm->update_refs);
3181 kfree(pm);
3182 }
3183 return ret;
3184}
3185
3186static struct pending_dir_move *get_pending_dir_moves(struct send_ctx *sctx,
3187 u64 parent_ino)
3188{
3189 struct rb_node *n = sctx->pending_dir_moves.rb_node;
3190 struct pending_dir_move *entry;
3191
3192 while (n) {
3193 entry = rb_entry(n, struct pending_dir_move, node);
3194 if (parent_ino < entry->parent_ino)
3195 n = n->rb_left;
3196 else if (parent_ino > entry->parent_ino)
3197 n = n->rb_right;
3198 else
3199 return entry;
3200 }
3201 return NULL;
3202}
3203
3204static int path_loop(struct send_ctx *sctx, struct fs_path *name,
3205 u64 ino, u64 gen, u64 *ancestor_ino)
3206{
3207 int ret = 0;
3208 u64 parent_inode = 0;
3209 u64 parent_gen = 0;
3210 u64 start_ino = ino;
3211
3212 *ancestor_ino = 0;
3213 while (ino != BTRFS_FIRST_FREE_OBJECTID) {
3214 fs_path_reset(name);
3215
3216 if (is_waiting_for_rm(sctx, ino, gen))
3217 break;
3218 if (is_waiting_for_move(sctx, ino)) {
3219 if (*ancestor_ino == 0)
3220 *ancestor_ino = ino;
3221 ret = get_first_ref(sctx->parent_root, ino,
3222 &parent_inode, &parent_gen, name);
3223 } else {
3224 ret = __get_cur_name_and_parent(sctx, ino, gen,
3225 &parent_inode,
3226 &parent_gen, name);
3227 if (ret > 0) {
3228 ret = 0;
3229 break;
3230 }
3231 }
3232 if (ret < 0)
3233 break;
3234 if (parent_inode == start_ino) {
3235 ret = 1;
3236 if (*ancestor_ino == 0)
3237 *ancestor_ino = ino;
3238 break;
3239 }
3240 ino = parent_inode;
3241 gen = parent_gen;
3242 }
3243 return ret;
3244}
3245
3246static int apply_dir_move(struct send_ctx *sctx, struct pending_dir_move *pm)
3247{
3248 struct fs_path *from_path = NULL;
3249 struct fs_path *to_path = NULL;
3250 struct fs_path *name = NULL;
3251 u64 orig_progress = sctx->send_progress;
3252 struct recorded_ref *cur;
3253 u64 parent_ino, parent_gen;
3254 struct waiting_dir_move *dm = NULL;
3255 u64 rmdir_ino = 0;
3256 u64 rmdir_gen;
3257 u64 ancestor;
3258 bool is_orphan;
3259 int ret;
3260
3261 name = fs_path_alloc();
3262 from_path = fs_path_alloc();
3263 if (!name || !from_path) {
3264 ret = -ENOMEM;
3265 goto out;
3266 }
3267
3268 dm = get_waiting_dir_move(sctx, pm->ino);
3269 ASSERT(dm);
3270 rmdir_ino = dm->rmdir_ino;
3271 rmdir_gen = dm->rmdir_gen;
3272 is_orphan = dm->orphanized;
3273 free_waiting_dir_move(sctx, dm);
3274
3275 if (is_orphan) {
3276 ret = gen_unique_name(sctx, pm->ino,
3277 pm->gen, from_path);
3278 } else {
3279 ret = get_first_ref(sctx->parent_root, pm->ino,
3280 &parent_ino, &parent_gen, name);
3281 if (ret < 0)
3282 goto out;
3283 ret = get_cur_path(sctx, parent_ino, parent_gen,
3284 from_path);
3285 if (ret < 0)
3286 goto out;
3287 ret = fs_path_add_path(from_path, name);
3288 }
3289 if (ret < 0)
3290 goto out;
3291
3292 sctx->send_progress = sctx->cur_ino + 1;
3293 ret = path_loop(sctx, name, pm->ino, pm->gen, &ancestor);
3294 if (ret < 0)
3295 goto out;
3296 if (ret) {
3297 LIST_HEAD(deleted_refs);
3298 ASSERT(ancestor > BTRFS_FIRST_FREE_OBJECTID);
3299 ret = add_pending_dir_move(sctx, pm->ino, pm->gen, ancestor,
3300 &pm->update_refs, &deleted_refs,
3301 is_orphan);
3302 if (ret < 0)
3303 goto out;
3304 if (rmdir_ino) {
3305 dm = get_waiting_dir_move(sctx, pm->ino);
3306 ASSERT(dm);
3307 dm->rmdir_ino = rmdir_ino;
3308 dm->rmdir_gen = rmdir_gen;
3309 }
3310 goto out;
3311 }
3312 fs_path_reset(name);
3313 to_path = name;
3314 name = NULL;
3315 ret = get_cur_path(sctx, pm->ino, pm->gen, to_path);
3316 if (ret < 0)
3317 goto out;
3318
3319 ret = send_rename(sctx, from_path, to_path);
3320 if (ret < 0)
3321 goto out;
3322
3323 if (rmdir_ino) {
3324 struct orphan_dir_info *odi;
3325 u64 gen;
3326
3327 odi = get_orphan_dir_info(sctx, rmdir_ino, rmdir_gen);
3328 if (!odi) {
3329 /* already deleted */
3330 goto finish;
3331 }
3332 gen = odi->gen;
3333
3334 ret = can_rmdir(sctx, rmdir_ino, gen, sctx->cur_ino);
3335 if (ret < 0)
3336 goto out;
3337 if (!ret)
3338 goto finish;
3339
3340 name = fs_path_alloc();
3341 if (!name) {
3342 ret = -ENOMEM;
3343 goto out;
3344 }
3345 ret = get_cur_path(sctx, rmdir_ino, gen, name);
3346 if (ret < 0)
3347 goto out;
3348 ret = send_rmdir(sctx, name);
3349 if (ret < 0)
3350 goto out;
3351 }
3352
3353finish:
3354 ret = send_utimes(sctx, pm->ino, pm->gen);
3355 if (ret < 0)
3356 goto out;
3357
3358 /*
3359 * After rename/move, need to update the utimes of both new parent(s)
3360 * and old parent(s).
3361 */
3362 list_for_each_entry(cur, &pm->update_refs, list) {
3363 /*
3364 * The parent inode might have been deleted in the send snapshot
3365 */
3366 ret = get_inode_info(sctx->send_root, cur->dir, NULL,
3367 NULL, NULL, NULL, NULL, NULL);
3368 if (ret == -ENOENT) {
3369 ret = 0;
3370 continue;
3371 }
3372 if (ret < 0)
3373 goto out;
3374
3375 ret = send_utimes(sctx, cur->dir, cur->dir_gen);
3376 if (ret < 0)
3377 goto out;
3378 }
3379
3380out:
3381 fs_path_free(name);
3382 fs_path_free(from_path);
3383 fs_path_free(to_path);
3384 sctx->send_progress = orig_progress;
3385
3386 return ret;
3387}
3388
3389static void free_pending_move(struct send_ctx *sctx, struct pending_dir_move *m)
3390{
3391 if (!list_empty(&m->list))
3392 list_del(&m->list);
3393 if (!RB_EMPTY_NODE(&m->node))
3394 rb_erase(&m->node, &sctx->pending_dir_moves);
3395 __free_recorded_refs(&m->update_refs);
3396 kfree(m);
3397}
3398
3399static void tail_append_pending_moves(struct send_ctx *sctx,
3400 struct pending_dir_move *moves,
3401 struct list_head *stack)
3402{
3403 if (list_empty(&moves->list)) {
3404 list_add_tail(&moves->list, stack);
3405 } else {
3406 LIST_HEAD(list);
3407 list_splice_init(&moves->list, &list);
3408 list_add_tail(&moves->list, stack);
3409 list_splice_tail(&list, stack);
3410 }
3411 if (!RB_EMPTY_NODE(&moves->node)) {
3412 rb_erase(&moves->node, &sctx->pending_dir_moves);
3413 RB_CLEAR_NODE(&moves->node);
3414 }
3415}
3416
3417static int apply_children_dir_moves(struct send_ctx *sctx)
3418{
3419 struct pending_dir_move *pm;
3420 struct list_head stack;
3421 u64 parent_ino = sctx->cur_ino;
3422 int ret = 0;
3423
3424 pm = get_pending_dir_moves(sctx, parent_ino);
3425 if (!pm)
3426 return 0;
3427
3428 INIT_LIST_HEAD(&stack);
3429 tail_append_pending_moves(sctx, pm, &stack);
3430
3431 while (!list_empty(&stack)) {
3432 pm = list_first_entry(&stack, struct pending_dir_move, list);
3433 parent_ino = pm->ino;
3434 ret = apply_dir_move(sctx, pm);
3435 free_pending_move(sctx, pm);
3436 if (ret)
3437 goto out;
3438 pm = get_pending_dir_moves(sctx, parent_ino);
3439 if (pm)
3440 tail_append_pending_moves(sctx, pm, &stack);
3441 }
3442 return 0;
3443
3444out:
3445 while (!list_empty(&stack)) {
3446 pm = list_first_entry(&stack, struct pending_dir_move, list);
3447 free_pending_move(sctx, pm);
3448 }
3449 return ret;
3450}
3451
3452/*
3453 * We might need to delay a directory rename even when no ancestor directory
3454 * (in the send root) with a higher inode number than ours (sctx->cur_ino) was
3455 * renamed. This happens when we rename a directory to the old name (the name
3456 * in the parent root) of some other unrelated directory that got its rename
3457 * delayed due to some ancestor with higher number that got renamed.
3458 *
3459 * Example:
3460 *
3461 * Parent snapshot:
3462 * . (ino 256)
3463 * |---- a/ (ino 257)
3464 * | |---- file (ino 260)
3465 * |
3466 * |---- b/ (ino 258)
3467 * |---- c/ (ino 259)
3468 *
3469 * Send snapshot:
3470 * . (ino 256)
3471 * |---- a/ (ino 258)
3472 * |---- x/ (ino 259)
3473 * |---- y/ (ino 257)
3474 * |----- file (ino 260)
3475 *
3476 * Here we can not rename 258 from 'b' to 'a' without the rename of inode 257
3477 * from 'a' to 'x/y' happening first, which in turn depends on the rename of
3478 * inode 259 from 'c' to 'x'. So the order of rename commands the send stream
3479 * must issue is:
3480 *
3481 * 1 - rename 259 from 'c' to 'x'
3482 * 2 - rename 257 from 'a' to 'x/y'
3483 * 3 - rename 258 from 'b' to 'a'
3484 *
3485 * Returns 1 if the rename of sctx->cur_ino needs to be delayed, 0 if it can
3486 * be done right away and < 0 on error.
3487 */
3488static int wait_for_dest_dir_move(struct send_ctx *sctx,
3489 struct recorded_ref *parent_ref,
3490 const bool is_orphan)
3491{
3492 struct btrfs_fs_info *fs_info = sctx->parent_root->fs_info;
3493 struct btrfs_path *path;
3494 struct btrfs_key key;
3495 struct btrfs_key di_key;
3496 struct btrfs_dir_item *di;
3497 u64 left_gen;
3498 u64 right_gen;
3499 int ret = 0;
3500 struct waiting_dir_move *wdm;
3501
3502 if (RB_EMPTY_ROOT(&sctx->waiting_dir_moves))
3503 return 0;
3504
3505 path = alloc_path_for_send();
3506 if (!path)
3507 return -ENOMEM;
3508
3509 key.objectid = parent_ref->dir;
3510 key.type = BTRFS_DIR_ITEM_KEY;
3511 key.offset = btrfs_name_hash(parent_ref->name, parent_ref->name_len);
3512
3513 ret = btrfs_search_slot(NULL, sctx->parent_root, &key, path, 0, 0);
3514 if (ret < 0) {
3515 goto out;
3516 } else if (ret > 0) {
3517 ret = 0;
3518 goto out;
3519 }
3520
3521 di = btrfs_match_dir_item_name(fs_info, path, parent_ref->name,
3522 parent_ref->name_len);
3523 if (!di) {
3524 ret = 0;
3525 goto out;
3526 }
3527 /*
3528 * di_key.objectid has the number of the inode that has a dentry in the
3529 * parent directory with the same name that sctx->cur_ino is being
3530 * renamed to. We need to check if that inode is in the send root as
3531 * well and if it is currently marked as an inode with a pending rename,
3532 * if it is, we need to delay the rename of sctx->cur_ino as well, so
3533 * that it happens after that other inode is renamed.
3534 */
3535 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &di_key);
3536 if (di_key.type != BTRFS_INODE_ITEM_KEY) {
3537 ret = 0;
3538 goto out;
3539 }
3540
3541 ret = get_inode_info(sctx->parent_root, di_key.objectid, NULL,
3542 &left_gen, NULL, NULL, NULL, NULL);
3543 if (ret < 0)
3544 goto out;
3545 ret = get_inode_info(sctx->send_root, di_key.objectid, NULL,
3546 &right_gen, NULL, NULL, NULL, NULL);
3547 if (ret < 0) {
3548 if (ret == -ENOENT)
3549 ret = 0;
3550 goto out;
3551 }
3552
3553 /* Different inode, no need to delay the rename of sctx->cur_ino */
3554 if (right_gen != left_gen) {
3555 ret = 0;
3556 goto out;
3557 }
3558
3559 wdm = get_waiting_dir_move(sctx, di_key.objectid);
3560 if (wdm && !wdm->orphanized) {
3561 ret = add_pending_dir_move(sctx,
3562 sctx->cur_ino,
3563 sctx->cur_inode_gen,
3564 di_key.objectid,
3565 &sctx->new_refs,
3566 &sctx->deleted_refs,
3567 is_orphan);
3568 if (!ret)
3569 ret = 1;
3570 }
3571out:
3572 btrfs_free_path(path);
3573 return ret;
3574}
3575
3576/*
3577 * Check if inode ino2, or any of its ancestors, is inode ino1.
3578 * Return 1 if true, 0 if false and < 0 on error.
3579 */
3580static int check_ino_in_path(struct btrfs_root *root,
3581 const u64 ino1,
3582 const u64 ino1_gen,
3583 const u64 ino2,
3584 const u64 ino2_gen,
3585 struct fs_path *fs_path)
3586{
3587 u64 ino = ino2;
3588
3589 if (ino1 == ino2)
3590 return ino1_gen == ino2_gen;
3591
3592 while (ino > BTRFS_FIRST_FREE_OBJECTID) {
3593 u64 parent;
3594 u64 parent_gen;
3595 int ret;
3596
3597 fs_path_reset(fs_path);
3598 ret = get_first_ref(root, ino, &parent, &parent_gen, fs_path);
3599 if (ret < 0)
3600 return ret;
3601 if (parent == ino1)
3602 return parent_gen == ino1_gen;
3603 ino = parent;
3604 }
3605 return 0;
3606}
3607
3608/*
3609 * Check if ino ino1 is an ancestor of inode ino2 in the given root for any
3610 * possible path (in case ino2 is not a directory and has multiple hard links).
3611 * Return 1 if true, 0 if false and < 0 on error.
3612 */
3613static int is_ancestor(struct btrfs_root *root,
3614 const u64 ino1,
3615 const u64 ino1_gen,
3616 const u64 ino2,
3617 struct fs_path *fs_path)
3618{
3619 bool free_fs_path = false;
3620 int ret = 0;
3621 struct btrfs_path *path = NULL;
3622 struct btrfs_key key;
3623
3624 if (!fs_path) {
3625 fs_path = fs_path_alloc();
3626 if (!fs_path)
3627 return -ENOMEM;
3628 free_fs_path = true;
3629 }
3630
3631 path = alloc_path_for_send();
3632 if (!path) {
3633 ret = -ENOMEM;
3634 goto out;
3635 }
3636
3637 key.objectid = ino2;
3638 key.type = BTRFS_INODE_REF_KEY;
3639 key.offset = 0;
3640
3641 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3642 if (ret < 0)
3643 goto out;
3644
3645 while (true) {
3646 struct extent_buffer *leaf = path->nodes[0];
3647 int slot = path->slots[0];
3648 u32 cur_offset = 0;
3649 u32 item_size;
3650
3651 if (slot >= btrfs_header_nritems(leaf)) {
3652 ret = btrfs_next_leaf(root, path);
3653 if (ret < 0)
3654 goto out;
3655 if (ret > 0)
3656 break;
3657 continue;
3658 }
3659
3660 btrfs_item_key_to_cpu(leaf, &key, slot);
3661 if (key.objectid != ino2)
3662 break;
3663 if (key.type != BTRFS_INODE_REF_KEY &&
3664 key.type != BTRFS_INODE_EXTREF_KEY)
3665 break;
3666
3667 item_size = btrfs_item_size_nr(leaf, slot);
3668 while (cur_offset < item_size) {
3669 u64 parent;
3670 u64 parent_gen;
3671
3672 if (key.type == BTRFS_INODE_EXTREF_KEY) {
3673 unsigned long ptr;
3674 struct btrfs_inode_extref *extref;
3675
3676 ptr = btrfs_item_ptr_offset(leaf, slot);
3677 extref = (struct btrfs_inode_extref *)
3678 (ptr + cur_offset);
3679 parent = btrfs_inode_extref_parent(leaf,
3680 extref);
3681 cur_offset += sizeof(*extref);
3682 cur_offset += btrfs_inode_extref_name_len(leaf,
3683 extref);
3684 } else {
3685 parent = key.offset;
3686 cur_offset = item_size;
3687 }
3688
3689 ret = get_inode_info(root, parent, NULL, &parent_gen,
3690 NULL, NULL, NULL, NULL);
3691 if (ret < 0)
3692 goto out;
3693 ret = check_ino_in_path(root, ino1, ino1_gen,
3694 parent, parent_gen, fs_path);
3695 if (ret)
3696 goto out;
3697 }
3698 path->slots[0]++;
3699 }
3700 ret = 0;
3701 out:
3702 btrfs_free_path(path);
3703 if (free_fs_path)
3704 fs_path_free(fs_path);
3705 return ret;
3706}
3707
3708static int wait_for_parent_move(struct send_ctx *sctx,
3709 struct recorded_ref *parent_ref,
3710 const bool is_orphan)
3711{
3712 int ret = 0;
3713 u64 ino = parent_ref->dir;
3714 u64 ino_gen = parent_ref->dir_gen;
3715 u64 parent_ino_before, parent_ino_after;
3716 struct fs_path *path_before = NULL;
3717 struct fs_path *path_after = NULL;
3718 int len1, len2;
3719
3720 path_after = fs_path_alloc();
3721 path_before = fs_path_alloc();
3722 if (!path_after || !path_before) {
3723 ret = -ENOMEM;
3724 goto out;
3725 }
3726
3727 /*
3728 * Our current directory inode may not yet be renamed/moved because some
3729 * ancestor (immediate or not) has to be renamed/moved first. So find if
3730 * such ancestor exists and make sure our own rename/move happens after
3731 * that ancestor is processed to avoid path build infinite loops (done
3732 * at get_cur_path()).
3733 */
3734 while (ino > BTRFS_FIRST_FREE_OBJECTID) {
3735 u64 parent_ino_after_gen;
3736
3737 if (is_waiting_for_move(sctx, ino)) {
3738 /*
3739 * If the current inode is an ancestor of ino in the
3740 * parent root, we need to delay the rename of the
3741 * current inode, otherwise don't delayed the rename
3742 * because we can end up with a circular dependency
3743 * of renames, resulting in some directories never
3744 * getting the respective rename operations issued in
3745 * the send stream or getting into infinite path build
3746 * loops.
3747 */
3748 ret = is_ancestor(sctx->parent_root,
3749 sctx->cur_ino, sctx->cur_inode_gen,
3750 ino, path_before);
3751 if (ret)
3752 break;
3753 }
3754
3755 fs_path_reset(path_before);
3756 fs_path_reset(path_after);
3757
3758 ret = get_first_ref(sctx->send_root, ino, &parent_ino_after,
3759 &parent_ino_after_gen, path_after);
3760 if (ret < 0)
3761 goto out;
3762 ret = get_first_ref(sctx->parent_root, ino, &parent_ino_before,
3763 NULL, path_before);
3764 if (ret < 0 && ret != -ENOENT) {
3765 goto out;
3766 } else if (ret == -ENOENT) {
3767 ret = 0;
3768 break;
3769 }
3770
3771 len1 = fs_path_len(path_before);
3772 len2 = fs_path_len(path_after);
3773 if (ino > sctx->cur_ino &&
3774 (parent_ino_before != parent_ino_after || len1 != len2 ||
3775 memcmp(path_before->start, path_after->start, len1))) {
3776 u64 parent_ino_gen;
3777
3778 ret = get_inode_info(sctx->parent_root, ino, NULL,
3779 &parent_ino_gen, NULL, NULL, NULL,
3780 NULL);
3781 if (ret < 0)
3782 goto out;
3783 if (ino_gen == parent_ino_gen) {
3784 ret = 1;
3785 break;
3786 }
3787 }
3788 ino = parent_ino_after;
3789 ino_gen = parent_ino_after_gen;
3790 }
3791
3792out:
3793 fs_path_free(path_before);
3794 fs_path_free(path_after);
3795
3796 if (ret == 1) {
3797 ret = add_pending_dir_move(sctx,
3798 sctx->cur_ino,
3799 sctx->cur_inode_gen,
3800 ino,
3801 &sctx->new_refs,
3802 &sctx->deleted_refs,
3803 is_orphan);
3804 if (!ret)
3805 ret = 1;
3806 }
3807
3808 return ret;
3809}
3810
3811static int update_ref_path(struct send_ctx *sctx, struct recorded_ref *ref)
3812{
3813 int ret;
3814 struct fs_path *new_path;
3815
3816 /*
3817 * Our reference's name member points to its full_path member string, so
3818 * we use here a new path.
3819 */
3820 new_path = fs_path_alloc();
3821 if (!new_path)
3822 return -ENOMEM;
3823
3824 ret = get_cur_path(sctx, ref->dir, ref->dir_gen, new_path);
3825 if (ret < 0) {
3826 fs_path_free(new_path);
3827 return ret;
3828 }
3829 ret = fs_path_add(new_path, ref->name, ref->name_len);
3830 if (ret < 0) {
3831 fs_path_free(new_path);
3832 return ret;
3833 }
3834
3835 fs_path_free(ref->full_path);
3836 set_ref_path(ref, new_path);
3837
3838 return 0;
3839}
3840
3841/*
3842 * When processing the new references for an inode we may orphanize an existing
3843 * directory inode because its old name conflicts with one of the new references
3844 * of the current inode. Later, when processing another new reference of our
3845 * inode, we might need to orphanize another inode, but the path we have in the
3846 * reference reflects the pre-orphanization name of the directory we previously
3847 * orphanized. For example:
3848 *
3849 * parent snapshot looks like:
3850 *
3851 * . (ino 256)
3852 * |----- f1 (ino 257)
3853 * |----- f2 (ino 258)
3854 * |----- d1/ (ino 259)
3855 * |----- d2/ (ino 260)
3856 *
3857 * send snapshot looks like:
3858 *
3859 * . (ino 256)
3860 * |----- d1 (ino 258)
3861 * |----- f2/ (ino 259)
3862 * |----- f2_link/ (ino 260)
3863 * | |----- f1 (ino 257)
3864 * |
3865 * |----- d2 (ino 258)
3866 *
3867 * When processing inode 257 we compute the name for inode 259 as "d1", and we
3868 * cache it in the name cache. Later when we start processing inode 258, when
3869 * collecting all its new references we set a full path of "d1/d2" for its new
3870 * reference with name "d2". When we start processing the new references we
3871 * start by processing the new reference with name "d1", and this results in
3872 * orphanizing inode 259, since its old reference causes a conflict. Then we
3873 * move on the next new reference, with name "d2", and we find out we must
3874 * orphanize inode 260, as its old reference conflicts with ours - but for the
3875 * orphanization we use a source path corresponding to the path we stored in the
3876 * new reference, which is "d1/d2" and not "o259-6-0/d2" - this makes the
3877 * receiver fail since the path component "d1/" no longer exists, it was renamed
3878 * to "o259-6-0/" when processing the previous new reference. So in this case we
3879 * must recompute the path in the new reference and use it for the new
3880 * orphanization operation.
3881 */
3882static int refresh_ref_path(struct send_ctx *sctx, struct recorded_ref *ref)
3883{
3884 char *name;
3885 int ret;
3886
3887 name = kmemdup(ref->name, ref->name_len, GFP_KERNEL);
3888 if (!name)
3889 return -ENOMEM;
3890
3891 fs_path_reset(ref->full_path);
3892 ret = get_cur_path(sctx, ref->dir, ref->dir_gen, ref->full_path);
3893 if (ret < 0)
3894 goto out;
3895
3896 ret = fs_path_add(ref->full_path, name, ref->name_len);
3897 if (ret < 0)
3898 goto out;
3899
3900 /* Update the reference's base name pointer. */
3901 set_ref_path(ref, ref->full_path);
3902out:
3903 kfree(name);
3904 return ret;
3905}
3906
3907/*
3908 * This does all the move/link/unlink/rmdir magic.
3909 */
3910static int process_recorded_refs(struct send_ctx *sctx, int *pending_move)
3911{
3912 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
3913 int ret = 0;
3914 struct recorded_ref *cur;
3915 struct recorded_ref *cur2;
3916 struct list_head check_dirs;
3917 struct fs_path *valid_path = NULL;
3918 u64 ow_inode = 0;
3919 u64 ow_gen;
3920 u64 ow_mode;
3921 int did_overwrite = 0;
3922 int is_orphan = 0;
3923 u64 last_dir_ino_rm = 0;
3924 bool can_rename = true;
3925 bool orphanized_dir = false;
3926 bool orphanized_ancestor = false;
3927
3928 btrfs_debug(fs_info, "process_recorded_refs %llu", sctx->cur_ino);
3929
3930 /*
3931 * This should never happen as the root dir always has the same ref
3932 * which is always '..'
3933 */
3934 BUG_ON(sctx->cur_ino <= BTRFS_FIRST_FREE_OBJECTID);
3935 INIT_LIST_HEAD(&check_dirs);
3936
3937 valid_path = fs_path_alloc();
3938 if (!valid_path) {
3939 ret = -ENOMEM;
3940 goto out;
3941 }
3942
3943 /*
3944 * First, check if the first ref of the current inode was overwritten
3945 * before. If yes, we know that the current inode was already orphanized
3946 * and thus use the orphan name. If not, we can use get_cur_path to
3947 * get the path of the first ref as it would like while receiving at
3948 * this point in time.
3949 * New inodes are always orphan at the beginning, so force to use the
3950 * orphan name in this case.
3951 * The first ref is stored in valid_path and will be updated if it
3952 * gets moved around.
3953 */
3954 if (!sctx->cur_inode_new) {
3955 ret = did_overwrite_first_ref(sctx, sctx->cur_ino,
3956 sctx->cur_inode_gen);
3957 if (ret < 0)
3958 goto out;
3959 if (ret)
3960 did_overwrite = 1;
3961 }
3962 if (sctx->cur_inode_new || did_overwrite) {
3963 ret = gen_unique_name(sctx, sctx->cur_ino,
3964 sctx->cur_inode_gen, valid_path);
3965 if (ret < 0)
3966 goto out;
3967 is_orphan = 1;
3968 } else {
3969 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen,
3970 valid_path);
3971 if (ret < 0)
3972 goto out;
3973 }
3974
3975 /*
3976 * Before doing any rename and link operations, do a first pass on the
3977 * new references to orphanize any unprocessed inodes that may have a
3978 * reference that conflicts with one of the new references of the current
3979 * inode. This needs to happen first because a new reference may conflict
3980 * with the old reference of a parent directory, so we must make sure
3981 * that the path used for link and rename commands don't use an
3982 * orphanized name when an ancestor was not yet orphanized.
3983 *
3984 * Example:
3985 *
3986 * Parent snapshot:
3987 *
3988 * . (ino 256)
3989 * |----- testdir/ (ino 259)
3990 * | |----- a (ino 257)
3991 * |
3992 * |----- b (ino 258)
3993 *
3994 * Send snapshot:
3995 *
3996 * . (ino 256)
3997 * |----- testdir_2/ (ino 259)
3998 * | |----- a (ino 260)
3999 * |
4000 * |----- testdir (ino 257)
4001 * |----- b (ino 257)
4002 * |----- b2 (ino 258)
4003 *
4004 * Processing the new reference for inode 257 with name "b" may happen
4005 * before processing the new reference with name "testdir". If so, we
4006 * must make sure that by the time we send a link command to create the
4007 * hard link "b", inode 259 was already orphanized, since the generated
4008 * path in "valid_path" already contains the orphanized name for 259.
4009 * We are processing inode 257, so only later when processing 259 we do
4010 * the rename operation to change its temporary (orphanized) name to
4011 * "testdir_2".
4012 */
4013 list_for_each_entry(cur, &sctx->new_refs, list) {
4014 ret = get_cur_inode_state(sctx, cur->dir, cur->dir_gen);
4015 if (ret < 0)
4016 goto out;
4017 if (ret == inode_state_will_create)
4018 continue;
4019
4020 /*
4021 * Check if this new ref would overwrite the first ref of another
4022 * unprocessed inode. If yes, orphanize the overwritten inode.
4023 * If we find an overwritten ref that is not the first ref,
4024 * simply unlink it.
4025 */
4026 ret = will_overwrite_ref(sctx, cur->dir, cur->dir_gen,
4027 cur->name, cur->name_len,
4028 &ow_inode, &ow_gen, &ow_mode);
4029 if (ret < 0)
4030 goto out;
4031 if (ret) {
4032 ret = is_first_ref(sctx->parent_root,
4033 ow_inode, cur->dir, cur->name,
4034 cur->name_len);
4035 if (ret < 0)
4036 goto out;
4037 if (ret) {
4038 struct name_cache_entry *nce;
4039 struct waiting_dir_move *wdm;
4040
4041 if (orphanized_dir) {
4042 ret = refresh_ref_path(sctx, cur);
4043 if (ret < 0)
4044 goto out;
4045 }
4046
4047 ret = orphanize_inode(sctx, ow_inode, ow_gen,
4048 cur->full_path);
4049 if (ret < 0)
4050 goto out;
4051 if (S_ISDIR(ow_mode))
4052 orphanized_dir = true;
4053
4054 /*
4055 * If ow_inode has its rename operation delayed
4056 * make sure that its orphanized name is used in
4057 * the source path when performing its rename
4058 * operation.
4059 */
4060 if (is_waiting_for_move(sctx, ow_inode)) {
4061 wdm = get_waiting_dir_move(sctx,
4062 ow_inode);
4063 ASSERT(wdm);
4064 wdm->orphanized = true;
4065 }
4066
4067 /*
4068 * Make sure we clear our orphanized inode's
4069 * name from the name cache. This is because the
4070 * inode ow_inode might be an ancestor of some
4071 * other inode that will be orphanized as well
4072 * later and has an inode number greater than
4073 * sctx->send_progress. We need to prevent
4074 * future name lookups from using the old name
4075 * and get instead the orphan name.
4076 */
4077 nce = name_cache_search(sctx, ow_inode, ow_gen);
4078 if (nce) {
4079 name_cache_delete(sctx, nce);
4080 kfree(nce);
4081 }
4082
4083 /*
4084 * ow_inode might currently be an ancestor of
4085 * cur_ino, therefore compute valid_path (the
4086 * current path of cur_ino) again because it
4087 * might contain the pre-orphanization name of
4088 * ow_inode, which is no longer valid.
4089 */
4090 ret = is_ancestor(sctx->parent_root,
4091 ow_inode, ow_gen,
4092 sctx->cur_ino, NULL);
4093 if (ret > 0) {
4094 orphanized_ancestor = true;
4095 fs_path_reset(valid_path);
4096 ret = get_cur_path(sctx, sctx->cur_ino,
4097 sctx->cur_inode_gen,
4098 valid_path);
4099 }
4100 if (ret < 0)
4101 goto out;
4102 } else {
4103 /*
4104 * If we previously orphanized a directory that
4105 * collided with a new reference that we already
4106 * processed, recompute the current path because
4107 * that directory may be part of the path.
4108 */
4109 if (orphanized_dir) {
4110 ret = refresh_ref_path(sctx, cur);
4111 if (ret < 0)
4112 goto out;
4113 }
4114 ret = send_unlink(sctx, cur->full_path);
4115 if (ret < 0)
4116 goto out;
4117 }
4118 }
4119
4120 }
4121
4122 list_for_each_entry(cur, &sctx->new_refs, list) {
4123 /*
4124 * We may have refs where the parent directory does not exist
4125 * yet. This happens if the parent directories inum is higher
4126 * than the current inum. To handle this case, we create the
4127 * parent directory out of order. But we need to check if this
4128 * did already happen before due to other refs in the same dir.
4129 */
4130 ret = get_cur_inode_state(sctx, cur->dir, cur->dir_gen);
4131 if (ret < 0)
4132 goto out;
4133 if (ret == inode_state_will_create) {
4134 ret = 0;
4135 /*
4136 * First check if any of the current inodes refs did
4137 * already create the dir.
4138 */
4139 list_for_each_entry(cur2, &sctx->new_refs, list) {
4140 if (cur == cur2)
4141 break;
4142 if (cur2->dir == cur->dir) {
4143 ret = 1;
4144 break;
4145 }
4146 }
4147
4148 /*
4149 * If that did not happen, check if a previous inode
4150 * did already create the dir.
4151 */
4152 if (!ret)
4153 ret = did_create_dir(sctx, cur->dir);
4154 if (ret < 0)
4155 goto out;
4156 if (!ret) {
4157 ret = send_create_inode(sctx, cur->dir);
4158 if (ret < 0)
4159 goto out;
4160 }
4161 }
4162
4163 if (S_ISDIR(sctx->cur_inode_mode) && sctx->parent_root) {
4164 ret = wait_for_dest_dir_move(sctx, cur, is_orphan);
4165 if (ret < 0)
4166 goto out;
4167 if (ret == 1) {
4168 can_rename = false;
4169 *pending_move = 1;
4170 }
4171 }
4172
4173 if (S_ISDIR(sctx->cur_inode_mode) && sctx->parent_root &&
4174 can_rename) {
4175 ret = wait_for_parent_move(sctx, cur, is_orphan);
4176 if (ret < 0)
4177 goto out;
4178 if (ret == 1) {
4179 can_rename = false;
4180 *pending_move = 1;
4181 }
4182 }
4183
4184 /*
4185 * link/move the ref to the new place. If we have an orphan
4186 * inode, move it and update valid_path. If not, link or move
4187 * it depending on the inode mode.
4188 */
4189 if (is_orphan && can_rename) {
4190 ret = send_rename(sctx, valid_path, cur->full_path);
4191 if (ret < 0)
4192 goto out;
4193 is_orphan = 0;
4194 ret = fs_path_copy(valid_path, cur->full_path);
4195 if (ret < 0)
4196 goto out;
4197 } else if (can_rename) {
4198 if (S_ISDIR(sctx->cur_inode_mode)) {
4199 /*
4200 * Dirs can't be linked, so move it. For moved
4201 * dirs, we always have one new and one deleted
4202 * ref. The deleted ref is ignored later.
4203 */
4204 ret = send_rename(sctx, valid_path,
4205 cur->full_path);
4206 if (!ret)
4207 ret = fs_path_copy(valid_path,
4208 cur->full_path);
4209 if (ret < 0)
4210 goto out;
4211 } else {
4212 /*
4213 * We might have previously orphanized an inode
4214 * which is an ancestor of our current inode,
4215 * so our reference's full path, which was
4216 * computed before any such orphanizations, must
4217 * be updated.
4218 */
4219 if (orphanized_dir) {
4220 ret = update_ref_path(sctx, cur);
4221 if (ret < 0)
4222 goto out;
4223 }
4224 ret = send_link(sctx, cur->full_path,
4225 valid_path);
4226 if (ret < 0)
4227 goto out;
4228 }
4229 }
4230 ret = dup_ref(cur, &check_dirs);
4231 if (ret < 0)
4232 goto out;
4233 }
4234
4235 if (S_ISDIR(sctx->cur_inode_mode) && sctx->cur_inode_deleted) {
4236 /*
4237 * Check if we can already rmdir the directory. If not,
4238 * orphanize it. For every dir item inside that gets deleted
4239 * later, we do this check again and rmdir it then if possible.
4240 * See the use of check_dirs for more details.
4241 */
4242 ret = can_rmdir(sctx, sctx->cur_ino, sctx->cur_inode_gen,
4243 sctx->cur_ino);
4244 if (ret < 0)
4245 goto out;
4246 if (ret) {
4247 ret = send_rmdir(sctx, valid_path);
4248 if (ret < 0)
4249 goto out;
4250 } else if (!is_orphan) {
4251 ret = orphanize_inode(sctx, sctx->cur_ino,
4252 sctx->cur_inode_gen, valid_path);
4253 if (ret < 0)
4254 goto out;
4255 is_orphan = 1;
4256 }
4257
4258 list_for_each_entry(cur, &sctx->deleted_refs, list) {
4259 ret = dup_ref(cur, &check_dirs);
4260 if (ret < 0)
4261 goto out;
4262 }
4263 } else if (S_ISDIR(sctx->cur_inode_mode) &&
4264 !list_empty(&sctx->deleted_refs)) {
4265 /*
4266 * We have a moved dir. Add the old parent to check_dirs
4267 */
4268 cur = list_entry(sctx->deleted_refs.next, struct recorded_ref,
4269 list);
4270 ret = dup_ref(cur, &check_dirs);
4271 if (ret < 0)
4272 goto out;
4273 } else if (!S_ISDIR(sctx->cur_inode_mode)) {
4274 /*
4275 * We have a non dir inode. Go through all deleted refs and
4276 * unlink them if they were not already overwritten by other
4277 * inodes.
4278 */
4279 list_for_each_entry(cur, &sctx->deleted_refs, list) {
4280 ret = did_overwrite_ref(sctx, cur->dir, cur->dir_gen,
4281 sctx->cur_ino, sctx->cur_inode_gen,
4282 cur->name, cur->name_len);
4283 if (ret < 0)
4284 goto out;
4285 if (!ret) {
4286 /*
4287 * If we orphanized any ancestor before, we need
4288 * to recompute the full path for deleted names,
4289 * since any such path was computed before we
4290 * processed any references and orphanized any
4291 * ancestor inode.
4292 */
4293 if (orphanized_ancestor) {
4294 ret = update_ref_path(sctx, cur);
4295 if (ret < 0)
4296 goto out;
4297 }
4298 ret = send_unlink(sctx, cur->full_path);
4299 if (ret < 0)
4300 goto out;
4301 }
4302 ret = dup_ref(cur, &check_dirs);
4303 if (ret < 0)
4304 goto out;
4305 }
4306 /*
4307 * If the inode is still orphan, unlink the orphan. This may
4308 * happen when a previous inode did overwrite the first ref
4309 * of this inode and no new refs were added for the current
4310 * inode. Unlinking does not mean that the inode is deleted in
4311 * all cases. There may still be links to this inode in other
4312 * places.
4313 */
4314 if (is_orphan) {
4315 ret = send_unlink(sctx, valid_path);
4316 if (ret < 0)
4317 goto out;
4318 }
4319 }
4320
4321 /*
4322 * We did collect all parent dirs where cur_inode was once located. We
4323 * now go through all these dirs and check if they are pending for
4324 * deletion and if it's finally possible to perform the rmdir now.
4325 * We also update the inode stats of the parent dirs here.
4326 */
4327 list_for_each_entry(cur, &check_dirs, list) {
4328 /*
4329 * In case we had refs into dirs that were not processed yet,
4330 * we don't need to do the utime and rmdir logic for these dirs.
4331 * The dir will be processed later.
4332 */
4333 if (cur->dir > sctx->cur_ino)
4334 continue;
4335
4336 ret = get_cur_inode_state(sctx, cur->dir, cur->dir_gen);
4337 if (ret < 0)
4338 goto out;
4339
4340 if (ret == inode_state_did_create ||
4341 ret == inode_state_no_change) {
4342 /* TODO delayed utimes */
4343 ret = send_utimes(sctx, cur->dir, cur->dir_gen);
4344 if (ret < 0)
4345 goto out;
4346 } else if (ret == inode_state_did_delete &&
4347 cur->dir != last_dir_ino_rm) {
4348 ret = can_rmdir(sctx, cur->dir, cur->dir_gen,
4349 sctx->cur_ino);
4350 if (ret < 0)
4351 goto out;
4352 if (ret) {
4353 ret = get_cur_path(sctx, cur->dir,
4354 cur->dir_gen, valid_path);
4355 if (ret < 0)
4356 goto out;
4357 ret = send_rmdir(sctx, valid_path);
4358 if (ret < 0)
4359 goto out;
4360 last_dir_ino_rm = cur->dir;
4361 }
4362 }
4363 }
4364
4365 ret = 0;
4366
4367out:
4368 __free_recorded_refs(&check_dirs);
4369 free_recorded_refs(sctx);
4370 fs_path_free(valid_path);
4371 return ret;
4372}
4373
4374static int record_ref(struct btrfs_root *root, u64 dir, struct fs_path *name,
4375 void *ctx, struct list_head *refs)
4376{
4377 int ret = 0;
4378 struct send_ctx *sctx = ctx;
4379 struct fs_path *p;
4380 u64 gen;
4381
4382 p = fs_path_alloc();
4383 if (!p)
4384 return -ENOMEM;
4385
4386 ret = get_inode_info(root, dir, NULL, &gen, NULL, NULL,
4387 NULL, NULL);
4388 if (ret < 0)
4389 goto out;
4390
4391 ret = get_cur_path(sctx, dir, gen, p);
4392 if (ret < 0)
4393 goto out;
4394 ret = fs_path_add_path(p, name);
4395 if (ret < 0)
4396 goto out;
4397
4398 ret = __record_ref(refs, dir, gen, p);
4399
4400out:
4401 if (ret)
4402 fs_path_free(p);
4403 return ret;
4404}
4405
4406static int __record_new_ref(int num, u64 dir, int index,
4407 struct fs_path *name,
4408 void *ctx)
4409{
4410 struct send_ctx *sctx = ctx;
4411 return record_ref(sctx->send_root, dir, name, ctx, &sctx->new_refs);
4412}
4413
4414
4415static int __record_deleted_ref(int num, u64 dir, int index,
4416 struct fs_path *name,
4417 void *ctx)
4418{
4419 struct send_ctx *sctx = ctx;
4420 return record_ref(sctx->parent_root, dir, name, ctx,
4421 &sctx->deleted_refs);
4422}
4423
4424static int record_new_ref(struct send_ctx *sctx)
4425{
4426 int ret;
4427
4428 ret = iterate_inode_ref(sctx->send_root, sctx->left_path,
4429 sctx->cmp_key, 0, __record_new_ref, sctx);
4430 if (ret < 0)
4431 goto out;
4432 ret = 0;
4433
4434out:
4435 return ret;
4436}
4437
4438static int record_deleted_ref(struct send_ctx *sctx)
4439{
4440 int ret;
4441
4442 ret = iterate_inode_ref(sctx->parent_root, sctx->right_path,
4443 sctx->cmp_key, 0, __record_deleted_ref, sctx);
4444 if (ret < 0)
4445 goto out;
4446 ret = 0;
4447
4448out:
4449 return ret;
4450}
4451
4452struct find_ref_ctx {
4453 u64 dir;
4454 u64 dir_gen;
4455 struct btrfs_root *root;
4456 struct fs_path *name;
4457 int found_idx;
4458};
4459
4460static int __find_iref(int num, u64 dir, int index,
4461 struct fs_path *name,
4462 void *ctx_)
4463{
4464 struct find_ref_ctx *ctx = ctx_;
4465 u64 dir_gen;
4466 int ret;
4467
4468 if (dir == ctx->dir && fs_path_len(name) == fs_path_len(ctx->name) &&
4469 strncmp(name->start, ctx->name->start, fs_path_len(name)) == 0) {
4470 /*
4471 * To avoid doing extra lookups we'll only do this if everything
4472 * else matches.
4473 */
4474 ret = get_inode_info(ctx->root, dir, NULL, &dir_gen, NULL,
4475 NULL, NULL, NULL);
4476 if (ret)
4477 return ret;
4478 if (dir_gen != ctx->dir_gen)
4479 return 0;
4480 ctx->found_idx = num;
4481 return 1;
4482 }
4483 return 0;
4484}
4485
4486static int find_iref(struct btrfs_root *root,
4487 struct btrfs_path *path,
4488 struct btrfs_key *key,
4489 u64 dir, u64 dir_gen, struct fs_path *name)
4490{
4491 int ret;
4492 struct find_ref_ctx ctx;
4493
4494 ctx.dir = dir;
4495 ctx.name = name;
4496 ctx.dir_gen = dir_gen;
4497 ctx.found_idx = -1;
4498 ctx.root = root;
4499
4500 ret = iterate_inode_ref(root, path, key, 0, __find_iref, &ctx);
4501 if (ret < 0)
4502 return ret;
4503
4504 if (ctx.found_idx == -1)
4505 return -ENOENT;
4506
4507 return ctx.found_idx;
4508}
4509
4510static int __record_changed_new_ref(int num, u64 dir, int index,
4511 struct fs_path *name,
4512 void *ctx)
4513{
4514 u64 dir_gen;
4515 int ret;
4516 struct send_ctx *sctx = ctx;
4517
4518 ret = get_inode_info(sctx->send_root, dir, NULL, &dir_gen, NULL,
4519 NULL, NULL, NULL);
4520 if (ret)
4521 return ret;
4522
4523 ret = find_iref(sctx->parent_root, sctx->right_path,
4524 sctx->cmp_key, dir, dir_gen, name);
4525 if (ret == -ENOENT)
4526 ret = __record_new_ref(num, dir, index, name, sctx);
4527 else if (ret > 0)
4528 ret = 0;
4529
4530 return ret;
4531}
4532
4533static int __record_changed_deleted_ref(int num, u64 dir, int index,
4534 struct fs_path *name,
4535 void *ctx)
4536{
4537 u64 dir_gen;
4538 int ret;
4539 struct send_ctx *sctx = ctx;
4540
4541 ret = get_inode_info(sctx->parent_root, dir, NULL, &dir_gen, NULL,
4542 NULL, NULL, NULL);
4543 if (ret)
4544 return ret;
4545
4546 ret = find_iref(sctx->send_root, sctx->left_path, sctx->cmp_key,
4547 dir, dir_gen, name);
4548 if (ret == -ENOENT)
4549 ret = __record_deleted_ref(num, dir, index, name, sctx);
4550 else if (ret > 0)
4551 ret = 0;
4552
4553 return ret;
4554}
4555
4556static int record_changed_ref(struct send_ctx *sctx)
4557{
4558 int ret = 0;
4559
4560 ret = iterate_inode_ref(sctx->send_root, sctx->left_path,
4561 sctx->cmp_key, 0, __record_changed_new_ref, sctx);
4562 if (ret < 0)
4563 goto out;
4564 ret = iterate_inode_ref(sctx->parent_root, sctx->right_path,
4565 sctx->cmp_key, 0, __record_changed_deleted_ref, sctx);
4566 if (ret < 0)
4567 goto out;
4568 ret = 0;
4569
4570out:
4571 return ret;
4572}
4573
4574/*
4575 * Record and process all refs at once. Needed when an inode changes the
4576 * generation number, which means that it was deleted and recreated.
4577 */
4578static int process_all_refs(struct send_ctx *sctx,
4579 enum btrfs_compare_tree_result cmd)
4580{
4581 int ret;
4582 struct btrfs_root *root;
4583 struct btrfs_path *path;
4584 struct btrfs_key key;
4585 struct btrfs_key found_key;
4586 struct extent_buffer *eb;
4587 int slot;
4588 iterate_inode_ref_t cb;
4589 int pending_move = 0;
4590
4591 path = alloc_path_for_send();
4592 if (!path)
4593 return -ENOMEM;
4594
4595 if (cmd == BTRFS_COMPARE_TREE_NEW) {
4596 root = sctx->send_root;
4597 cb = __record_new_ref;
4598 } else if (cmd == BTRFS_COMPARE_TREE_DELETED) {
4599 root = sctx->parent_root;
4600 cb = __record_deleted_ref;
4601 } else {
4602 btrfs_err(sctx->send_root->fs_info,
4603 "Wrong command %d in process_all_refs", cmd);
4604 ret = -EINVAL;
4605 goto out;
4606 }
4607
4608 key.objectid = sctx->cmp_key->objectid;
4609 key.type = BTRFS_INODE_REF_KEY;
4610 key.offset = 0;
4611 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4612 if (ret < 0)
4613 goto out;
4614
4615 while (1) {
4616 eb = path->nodes[0];
4617 slot = path->slots[0];
4618 if (slot >= btrfs_header_nritems(eb)) {
4619 ret = btrfs_next_leaf(root, path);
4620 if (ret < 0)
4621 goto out;
4622 else if (ret > 0)
4623 break;
4624 continue;
4625 }
4626
4627 btrfs_item_key_to_cpu(eb, &found_key, slot);
4628
4629 if (found_key.objectid != key.objectid ||
4630 (found_key.type != BTRFS_INODE_REF_KEY &&
4631 found_key.type != BTRFS_INODE_EXTREF_KEY))
4632 break;
4633
4634 ret = iterate_inode_ref(root, path, &found_key, 0, cb, sctx);
4635 if (ret < 0)
4636 goto out;
4637
4638 path->slots[0]++;
4639 }
4640 btrfs_release_path(path);
4641
4642 /*
4643 * We don't actually care about pending_move as we are simply
4644 * re-creating this inode and will be rename'ing it into place once we
4645 * rename the parent directory.
4646 */
4647 ret = process_recorded_refs(sctx, &pending_move);
4648out:
4649 btrfs_free_path(path);
4650 return ret;
4651}
4652
4653static int send_set_xattr(struct send_ctx *sctx,
4654 struct fs_path *path,
4655 const char *name, int name_len,
4656 const char *data, int data_len)
4657{
4658 int ret = 0;
4659
4660 ret = begin_cmd(sctx, BTRFS_SEND_C_SET_XATTR);
4661 if (ret < 0)
4662 goto out;
4663
4664 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, path);
4665 TLV_PUT_STRING(sctx, BTRFS_SEND_A_XATTR_NAME, name, name_len);
4666 TLV_PUT(sctx, BTRFS_SEND_A_XATTR_DATA, data, data_len);
4667
4668 ret = send_cmd(sctx);
4669
4670tlv_put_failure:
4671out:
4672 return ret;
4673}
4674
4675static int send_remove_xattr(struct send_ctx *sctx,
4676 struct fs_path *path,
4677 const char *name, int name_len)
4678{
4679 int ret = 0;
4680
4681 ret = begin_cmd(sctx, BTRFS_SEND_C_REMOVE_XATTR);
4682 if (ret < 0)
4683 goto out;
4684
4685 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, path);
4686 TLV_PUT_STRING(sctx, BTRFS_SEND_A_XATTR_NAME, name, name_len);
4687
4688 ret = send_cmd(sctx);
4689
4690tlv_put_failure:
4691out:
4692 return ret;
4693}
4694
4695static int __process_new_xattr(int num, struct btrfs_key *di_key,
4696 const char *name, int name_len,
4697 const char *data, int data_len,
4698 u8 type, void *ctx)
4699{
4700 int ret;
4701 struct send_ctx *sctx = ctx;
4702 struct fs_path *p;
4703 struct posix_acl_xattr_header dummy_acl;
4704
4705 /* Capabilities are emitted by finish_inode_if_needed */
4706 if (!strncmp(name, XATTR_NAME_CAPS, name_len))
4707 return 0;
4708
4709 p = fs_path_alloc();
4710 if (!p)
4711 return -ENOMEM;
4712
4713 /*
4714 * This hack is needed because empty acls are stored as zero byte
4715 * data in xattrs. Problem with that is, that receiving these zero byte
4716 * acls will fail later. To fix this, we send a dummy acl list that
4717 * only contains the version number and no entries.
4718 */
4719 if (!strncmp(name, XATTR_NAME_POSIX_ACL_ACCESS, name_len) ||
4720 !strncmp(name, XATTR_NAME_POSIX_ACL_DEFAULT, name_len)) {
4721 if (data_len == 0) {
4722 dummy_acl.a_version =
4723 cpu_to_le32(POSIX_ACL_XATTR_VERSION);
4724 data = (char *)&dummy_acl;
4725 data_len = sizeof(dummy_acl);
4726 }
4727 }
4728
4729 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
4730 if (ret < 0)
4731 goto out;
4732
4733 ret = send_set_xattr(sctx, p, name, name_len, data, data_len);
4734
4735out:
4736 fs_path_free(p);
4737 return ret;
4738}
4739
4740static int __process_deleted_xattr(int num, struct btrfs_key *di_key,
4741 const char *name, int name_len,
4742 const char *data, int data_len,
4743 u8 type, void *ctx)
4744{
4745 int ret;
4746 struct send_ctx *sctx = ctx;
4747 struct fs_path *p;
4748
4749 p = fs_path_alloc();
4750 if (!p)
4751 return -ENOMEM;
4752
4753 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
4754 if (ret < 0)
4755 goto out;
4756
4757 ret = send_remove_xattr(sctx, p, name, name_len);
4758
4759out:
4760 fs_path_free(p);
4761 return ret;
4762}
4763
4764static int process_new_xattr(struct send_ctx *sctx)
4765{
4766 int ret = 0;
4767
4768 ret = iterate_dir_item(sctx->send_root, sctx->left_path,
4769 __process_new_xattr, sctx);
4770
4771 return ret;
4772}
4773
4774static int process_deleted_xattr(struct send_ctx *sctx)
4775{
4776 return iterate_dir_item(sctx->parent_root, sctx->right_path,
4777 __process_deleted_xattr, sctx);
4778}
4779
4780struct find_xattr_ctx {
4781 const char *name;
4782 int name_len;
4783 int found_idx;
4784 char *found_data;
4785 int found_data_len;
4786};
4787
4788static int __find_xattr(int num, struct btrfs_key *di_key,
4789 const char *name, int name_len,
4790 const char *data, int data_len,
4791 u8 type, void *vctx)
4792{
4793 struct find_xattr_ctx *ctx = vctx;
4794
4795 if (name_len == ctx->name_len &&
4796 strncmp(name, ctx->name, name_len) == 0) {
4797 ctx->found_idx = num;
4798 ctx->found_data_len = data_len;
4799 ctx->found_data = kmemdup(data, data_len, GFP_KERNEL);
4800 if (!ctx->found_data)
4801 return -ENOMEM;
4802 return 1;
4803 }
4804 return 0;
4805}
4806
4807static int find_xattr(struct btrfs_root *root,
4808 struct btrfs_path *path,
4809 struct btrfs_key *key,
4810 const char *name, int name_len,
4811 char **data, int *data_len)
4812{
4813 int ret;
4814 struct find_xattr_ctx ctx;
4815
4816 ctx.name = name;
4817 ctx.name_len = name_len;
4818 ctx.found_idx = -1;
4819 ctx.found_data = NULL;
4820 ctx.found_data_len = 0;
4821
4822 ret = iterate_dir_item(root, path, __find_xattr, &ctx);
4823 if (ret < 0)
4824 return ret;
4825
4826 if (ctx.found_idx == -1)
4827 return -ENOENT;
4828 if (data) {
4829 *data = ctx.found_data;
4830 *data_len = ctx.found_data_len;
4831 } else {
4832 kfree(ctx.found_data);
4833 }
4834 return ctx.found_idx;
4835}
4836
4837
4838static int __process_changed_new_xattr(int num, struct btrfs_key *di_key,
4839 const char *name, int name_len,
4840 const char *data, int data_len,
4841 u8 type, void *ctx)
4842{
4843 int ret;
4844 struct send_ctx *sctx = ctx;
4845 char *found_data = NULL;
4846 int found_data_len = 0;
4847
4848 ret = find_xattr(sctx->parent_root, sctx->right_path,
4849 sctx->cmp_key, name, name_len, &found_data,
4850 &found_data_len);
4851 if (ret == -ENOENT) {
4852 ret = __process_new_xattr(num, di_key, name, name_len, data,
4853 data_len, type, ctx);
4854 } else if (ret >= 0) {
4855 if (data_len != found_data_len ||
4856 memcmp(data, found_data, data_len)) {
4857 ret = __process_new_xattr(num, di_key, name, name_len,
4858 data, data_len, type, ctx);
4859 } else {
4860 ret = 0;
4861 }
4862 }
4863
4864 kfree(found_data);
4865 return ret;
4866}
4867
4868static int __process_changed_deleted_xattr(int num, struct btrfs_key *di_key,
4869 const char *name, int name_len,
4870 const char *data, int data_len,
4871 u8 type, void *ctx)
4872{
4873 int ret;
4874 struct send_ctx *sctx = ctx;
4875
4876 ret = find_xattr(sctx->send_root, sctx->left_path, sctx->cmp_key,
4877 name, name_len, NULL, NULL);
4878 if (ret == -ENOENT)
4879 ret = __process_deleted_xattr(num, di_key, name, name_len, data,
4880 data_len, type, ctx);
4881 else if (ret >= 0)
4882 ret = 0;
4883
4884 return ret;
4885}
4886
4887static int process_changed_xattr(struct send_ctx *sctx)
4888{
4889 int ret = 0;
4890
4891 ret = iterate_dir_item(sctx->send_root, sctx->left_path,
4892 __process_changed_new_xattr, sctx);
4893 if (ret < 0)
4894 goto out;
4895 ret = iterate_dir_item(sctx->parent_root, sctx->right_path,
4896 __process_changed_deleted_xattr, sctx);
4897
4898out:
4899 return ret;
4900}
4901
4902static int process_all_new_xattrs(struct send_ctx *sctx)
4903{
4904 int ret;
4905 struct btrfs_root *root;
4906 struct btrfs_path *path;
4907 struct btrfs_key key;
4908 struct btrfs_key found_key;
4909 struct extent_buffer *eb;
4910 int slot;
4911
4912 path = alloc_path_for_send();
4913 if (!path)
4914 return -ENOMEM;
4915
4916 root = sctx->send_root;
4917
4918 key.objectid = sctx->cmp_key->objectid;
4919 key.type = BTRFS_XATTR_ITEM_KEY;
4920 key.offset = 0;
4921 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4922 if (ret < 0)
4923 goto out;
4924
4925 while (1) {
4926 eb = path->nodes[0];
4927 slot = path->slots[0];
4928 if (slot >= btrfs_header_nritems(eb)) {
4929 ret = btrfs_next_leaf(root, path);
4930 if (ret < 0) {
4931 goto out;
4932 } else if (ret > 0) {
4933 ret = 0;
4934 break;
4935 }
4936 continue;
4937 }
4938
4939 btrfs_item_key_to_cpu(eb, &found_key, slot);
4940 if (found_key.objectid != key.objectid ||
4941 found_key.type != key.type) {
4942 ret = 0;
4943 goto out;
4944 }
4945
4946 ret = iterate_dir_item(root, path, __process_new_xattr, sctx);
4947 if (ret < 0)
4948 goto out;
4949
4950 path->slots[0]++;
4951 }
4952
4953out:
4954 btrfs_free_path(path);
4955 return ret;
4956}
4957
4958static ssize_t fill_read_buf(struct send_ctx *sctx, u64 offset, u32 len)
4959{
4960 struct btrfs_root *root = sctx->send_root;
4961 struct btrfs_fs_info *fs_info = root->fs_info;
4962 struct inode *inode;
4963 struct page *page;
4964 char *addr;
4965 struct btrfs_key key;
4966 pgoff_t index = offset >> PAGE_SHIFT;
4967 pgoff_t last_index;
4968 unsigned pg_offset = offset_in_page(offset);
4969 ssize_t ret = 0;
4970
4971 key.objectid = sctx->cur_ino;
4972 key.type = BTRFS_INODE_ITEM_KEY;
4973 key.offset = 0;
4974
4975 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
4976 if (IS_ERR(inode))
4977 return PTR_ERR(inode);
4978
4979 if (offset + len > i_size_read(inode)) {
4980 if (offset > i_size_read(inode))
4981 len = 0;
4982 else
4983 len = offset - i_size_read(inode);
4984 }
4985 if (len == 0)
4986 goto out;
4987
4988 last_index = (offset + len - 1) >> PAGE_SHIFT;
4989
4990 /* initial readahead */
4991 memset(&sctx->ra, 0, sizeof(struct file_ra_state));
4992 file_ra_state_init(&sctx->ra, inode->i_mapping);
4993
4994 while (index <= last_index) {
4995 unsigned cur_len = min_t(unsigned, len,
4996 PAGE_SIZE - pg_offset);
4997
4998 page = find_lock_page(inode->i_mapping, index);
4999 if (!page) {
5000 page_cache_sync_readahead(inode->i_mapping, &sctx->ra,
5001 NULL, index, last_index + 1 - index);
5002
5003 page = find_or_create_page(inode->i_mapping, index,
5004 GFP_KERNEL);
5005 if (!page) {
5006 ret = -ENOMEM;
5007 break;
5008 }
5009 }
5010
5011 if (PageReadahead(page)) {
5012 page_cache_async_readahead(inode->i_mapping, &sctx->ra,
5013 NULL, page, index, last_index + 1 - index);
5014 }
5015
5016 if (!PageUptodate(page)) {
5017 btrfs_readpage(NULL, page);
5018 lock_page(page);
5019 if (!PageUptodate(page)) {
5020 unlock_page(page);
5021 btrfs_err(fs_info,
5022 "send: IO error at offset %llu for inode %llu root %llu",
5023 page_offset(page), sctx->cur_ino,
5024 sctx->send_root->root_key.objectid);
5025 put_page(page);
5026 ret = -EIO;
5027 break;
5028 }
5029 }
5030
5031 addr = kmap(page);
5032 memcpy(sctx->read_buf + ret, addr + pg_offset, cur_len);
5033 kunmap(page);
5034 unlock_page(page);
5035 put_page(page);
5036 index++;
5037 pg_offset = 0;
5038 len -= cur_len;
5039 ret += cur_len;
5040 }
5041out:
5042 iput(inode);
5043 return ret;
5044}
5045
5046/*
5047 * Read some bytes from the current inode/file and send a write command to
5048 * user space.
5049 */
5050static int send_write(struct send_ctx *sctx, u64 offset, u32 len)
5051{
5052 struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
5053 int ret = 0;
5054 struct fs_path *p;
5055 ssize_t num_read = 0;
5056
5057 p = fs_path_alloc();
5058 if (!p)
5059 return -ENOMEM;
5060
5061 btrfs_debug(fs_info, "send_write offset=%llu, len=%d", offset, len);
5062
5063 num_read = fill_read_buf(sctx, offset, len);
5064 if (num_read <= 0) {
5065 if (num_read < 0)
5066 ret = num_read;
5067 goto out;
5068 }
5069
5070 ret = begin_cmd(sctx, BTRFS_SEND_C_WRITE);
5071 if (ret < 0)
5072 goto out;
5073
5074 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
5075 if (ret < 0)
5076 goto out;
5077
5078 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
5079 TLV_PUT_U64(sctx, BTRFS_SEND_A_FILE_OFFSET, offset);
5080 TLV_PUT(sctx, BTRFS_SEND_A_DATA, sctx->read_buf, num_read);
5081
5082 ret = send_cmd(sctx);
5083
5084tlv_put_failure:
5085out:
5086 fs_path_free(p);
5087 if (ret < 0)
5088 return ret;
5089 return num_read;
5090}
5091
5092/*
5093 * Send a clone command to user space.
5094 */
5095static int send_clone(struct send_ctx *sctx,
5096 u64 offset, u32 len,
5097 struct clone_root *clone_root)
5098{
5099 int ret = 0;
5100 struct fs_path *p;
5101 u64 gen;
5102
5103 btrfs_debug(sctx->send_root->fs_info,
5104 "send_clone offset=%llu, len=%d, clone_root=%llu, clone_inode=%llu, clone_offset=%llu",
5105 offset, len, clone_root->root->root_key.objectid,
5106 clone_root->ino, clone_root->offset);
5107
5108 p = fs_path_alloc();
5109 if (!p)
5110 return -ENOMEM;
5111
5112 ret = begin_cmd(sctx, BTRFS_SEND_C_CLONE);
5113 if (ret < 0)
5114 goto out;
5115
5116 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
5117 if (ret < 0)
5118 goto out;
5119
5120 TLV_PUT_U64(sctx, BTRFS_SEND_A_FILE_OFFSET, offset);
5121 TLV_PUT_U64(sctx, BTRFS_SEND_A_CLONE_LEN, len);
5122 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
5123
5124 if (clone_root->root == sctx->send_root) {
5125 ret = get_inode_info(sctx->send_root, clone_root->ino, NULL,
5126 &gen, NULL, NULL, NULL, NULL);
5127 if (ret < 0)
5128 goto out;
5129 ret = get_cur_path(sctx, clone_root->ino, gen, p);
5130 } else {
5131 ret = get_inode_path(clone_root->root, clone_root->ino, p);
5132 }
5133 if (ret < 0)
5134 goto out;
5135
5136 /*
5137 * If the parent we're using has a received_uuid set then use that as
5138 * our clone source as that is what we will look for when doing a
5139 * receive.
5140 *
5141 * This covers the case that we create a snapshot off of a received
5142 * subvolume and then use that as the parent and try to receive on a
5143 * different host.
5144 */
5145 if (!btrfs_is_empty_uuid(clone_root->root->root_item.received_uuid))
5146 TLV_PUT_UUID(sctx, BTRFS_SEND_A_CLONE_UUID,
5147 clone_root->root->root_item.received_uuid);
5148 else
5149 TLV_PUT_UUID(sctx, BTRFS_SEND_A_CLONE_UUID,
5150 clone_root->root->root_item.uuid);
5151 TLV_PUT_U64(sctx, BTRFS_SEND_A_CLONE_CTRANSID,
5152 le64_to_cpu(clone_root->root->root_item.ctransid));
5153 TLV_PUT_PATH(sctx, BTRFS_SEND_A_CLONE_PATH, p);
5154 TLV_PUT_U64(sctx, BTRFS_SEND_A_CLONE_OFFSET,
5155 clone_root->offset);
5156
5157 ret = send_cmd(sctx);
5158
5159tlv_put_failure:
5160out:
5161 fs_path_free(p);
5162 return ret;
5163}
5164
5165/*
5166 * Send an update extent command to user space.
5167 */
5168static int send_update_extent(struct send_ctx *sctx,
5169 u64 offset, u32 len)
5170{
5171 int ret = 0;
5172 struct fs_path *p;
5173
5174 p = fs_path_alloc();
5175 if (!p)
5176 return -ENOMEM;
5177
5178 ret = begin_cmd(sctx, BTRFS_SEND_C_UPDATE_EXTENT);
5179 if (ret < 0)
5180 goto out;
5181
5182 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
5183 if (ret < 0)
5184 goto out;
5185
5186 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
5187 TLV_PUT_U64(sctx, BTRFS_SEND_A_FILE_OFFSET, offset);
5188 TLV_PUT_U64(sctx, BTRFS_SEND_A_SIZE, len);
5189
5190 ret = send_cmd(sctx);
5191
5192tlv_put_failure:
5193out:
5194 fs_path_free(p);
5195 return ret;
5196}
5197
5198static int send_hole(struct send_ctx *sctx, u64 end)
5199{
5200 struct fs_path *p = NULL;
5201 u64 offset = sctx->cur_inode_last_extent;
5202 u64 len;
5203 int ret = 0;
5204
5205 /*
5206 * A hole that starts at EOF or beyond it. Since we do not yet support
5207 * fallocate (for extent preallocation and hole punching), sending a
5208 * write of zeroes starting at EOF or beyond would later require issuing
5209 * a truncate operation which would undo the write and achieve nothing.
5210 */
5211 if (offset >= sctx->cur_inode_size)
5212 return 0;
5213
5214 /*
5215 * Don't go beyond the inode's i_size due to prealloc extents that start
5216 * after the i_size.
5217 */
5218 end = min_t(u64, end, sctx->cur_inode_size);
5219
5220 if (sctx->flags & BTRFS_SEND_FLAG_NO_FILE_DATA)
5221 return send_update_extent(sctx, offset, end - offset);
5222
5223 p = fs_path_alloc();
5224 if (!p)
5225 return -ENOMEM;
5226 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
5227 if (ret < 0)
5228 goto tlv_put_failure;
5229 memset(sctx->read_buf, 0, BTRFS_SEND_READ_SIZE);
5230 while (offset < end) {
5231 len = min_t(u64, end - offset, BTRFS_SEND_READ_SIZE);
5232
5233 ret = begin_cmd(sctx, BTRFS_SEND_C_WRITE);
5234 if (ret < 0)
5235 break;
5236 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
5237 TLV_PUT_U64(sctx, BTRFS_SEND_A_FILE_OFFSET, offset);
5238 TLV_PUT(sctx, BTRFS_SEND_A_DATA, sctx->read_buf, len);
5239 ret = send_cmd(sctx);
5240 if (ret < 0)
5241 break;
5242 offset += len;
5243 }
5244 sctx->cur_inode_next_write_offset = offset;
5245tlv_put_failure:
5246 fs_path_free(p);
5247 return ret;
5248}
5249
5250static int send_extent_data(struct send_ctx *sctx,
5251 const u64 offset,
5252 const u64 len)
5253{
5254 u64 sent = 0;
5255
5256 if (sctx->flags & BTRFS_SEND_FLAG_NO_FILE_DATA)
5257 return send_update_extent(sctx, offset, len);
5258
5259 while (sent < len) {
5260 u64 size = len - sent;
5261 int ret;
5262
5263 if (size > BTRFS_SEND_READ_SIZE)
5264 size = BTRFS_SEND_READ_SIZE;
5265 ret = send_write(sctx, offset + sent, size);
5266 if (ret < 0)
5267 return ret;
5268 if (!ret)
5269 break;
5270 sent += ret;
5271 }
5272 return 0;
5273}
5274
5275/*
5276 * Search for a capability xattr related to sctx->cur_ino. If the capability is
5277 * found, call send_set_xattr function to emit it.
5278 *
5279 * Return 0 if there isn't a capability, or when the capability was emitted
5280 * successfully, or < 0 if an error occurred.
5281 */
5282static int send_capabilities(struct send_ctx *sctx)
5283{
5284 struct fs_path *fspath = NULL;
5285 struct btrfs_path *path;
5286 struct btrfs_dir_item *di;
5287 struct extent_buffer *leaf;
5288 unsigned long data_ptr;
5289 char *buf = NULL;
5290 int buf_len;
5291 int ret = 0;
5292
5293 path = alloc_path_for_send();
5294 if (!path)
5295 return -ENOMEM;
5296
5297 di = btrfs_lookup_xattr(NULL, sctx->send_root, path, sctx->cur_ino,
5298 XATTR_NAME_CAPS, strlen(XATTR_NAME_CAPS), 0);
5299 if (!di) {
5300 /* There is no xattr for this inode */
5301 goto out;
5302 } else if (IS_ERR(di)) {
5303 ret = PTR_ERR(di);
5304 goto out;
5305 }
5306
5307 leaf = path->nodes[0];
5308 buf_len = btrfs_dir_data_len(leaf, di);
5309
5310 fspath = fs_path_alloc();
5311 buf = kmalloc(buf_len, GFP_KERNEL);
5312 if (!fspath || !buf) {
5313 ret = -ENOMEM;
5314 goto out;
5315 }
5316
5317 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, fspath);
5318 if (ret < 0)
5319 goto out;
5320
5321 data_ptr = (unsigned long)(di + 1) + btrfs_dir_name_len(leaf, di);
5322 read_extent_buffer(leaf, buf, data_ptr, buf_len);
5323
5324 ret = send_set_xattr(sctx, fspath, XATTR_NAME_CAPS,
5325 strlen(XATTR_NAME_CAPS), buf, buf_len);
5326out:
5327 kfree(buf);
5328 fs_path_free(fspath);
5329 btrfs_free_path(path);
5330 return ret;
5331}
5332
5333static int clone_range(struct send_ctx *sctx,
5334 struct clone_root *clone_root,
5335 const u64 disk_byte,
5336 u64 data_offset,
5337 u64 offset,
5338 u64 len)
5339{
5340 struct btrfs_path *path;
5341 struct btrfs_key key;
5342 int ret;
5343 u64 clone_src_i_size = 0;
5344
5345 /*
5346 * Prevent cloning from a zero offset with a length matching the sector
5347 * size because in some scenarios this will make the receiver fail.
5348 *
5349 * For example, if in the source filesystem the extent at offset 0
5350 * has a length of sectorsize and it was written using direct IO, then
5351 * it can never be an inline extent (even if compression is enabled).
5352 * Then this extent can be cloned in the original filesystem to a non
5353 * zero file offset, but it may not be possible to clone in the
5354 * destination filesystem because it can be inlined due to compression
5355 * on the destination filesystem (as the receiver's write operations are
5356 * always done using buffered IO). The same happens when the original
5357 * filesystem does not have compression enabled but the destination
5358 * filesystem has.
5359 */
5360 if (clone_root->offset == 0 &&
5361 len == sctx->send_root->fs_info->sectorsize)
5362 return send_extent_data(sctx, offset, len);
5363
5364 path = alloc_path_for_send();
5365 if (!path)
5366 return -ENOMEM;
5367
5368 /*
5369 * There are inodes that have extents that lie behind its i_size. Don't
5370 * accept clones from these extents.
5371 */
5372 ret = __get_inode_info(clone_root->root, path, clone_root->ino,
5373 &clone_src_i_size, NULL, NULL, NULL, NULL, NULL);
5374 btrfs_release_path(path);
5375 if (ret < 0)
5376 goto out;
5377
5378 /*
5379 * We can't send a clone operation for the entire range if we find
5380 * extent items in the respective range in the source file that
5381 * refer to different extents or if we find holes.
5382 * So check for that and do a mix of clone and regular write/copy
5383 * operations if needed.
5384 *
5385 * Example:
5386 *
5387 * mkfs.btrfs -f /dev/sda
5388 * mount /dev/sda /mnt
5389 * xfs_io -f -c "pwrite -S 0xaa 0K 100K" /mnt/foo
5390 * cp --reflink=always /mnt/foo /mnt/bar
5391 * xfs_io -c "pwrite -S 0xbb 50K 50K" /mnt/foo
5392 * btrfs subvolume snapshot -r /mnt /mnt/snap
5393 *
5394 * If when we send the snapshot and we are processing file bar (which
5395 * has a higher inode number than foo) we blindly send a clone operation
5396 * for the [0, 100K[ range from foo to bar, the receiver ends up getting
5397 * a file bar that matches the content of file foo - iow, doesn't match
5398 * the content from bar in the original filesystem.
5399 */
5400 key.objectid = clone_root->ino;
5401 key.type = BTRFS_EXTENT_DATA_KEY;
5402 key.offset = clone_root->offset;
5403 ret = btrfs_search_slot(NULL, clone_root->root, &key, path, 0, 0);
5404 if (ret < 0)
5405 goto out;
5406 if (ret > 0 && path->slots[0] > 0) {
5407 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0] - 1);
5408 if (key.objectid == clone_root->ino &&
5409 key.type == BTRFS_EXTENT_DATA_KEY)
5410 path->slots[0]--;
5411 }
5412
5413 while (true) {
5414 struct extent_buffer *leaf = path->nodes[0];
5415 int slot = path->slots[0];
5416 struct btrfs_file_extent_item *ei;
5417 u8 type;
5418 u64 ext_len;
5419 u64 clone_len;
5420 u64 clone_data_offset;
5421 bool crossed_src_i_size = false;
5422
5423 if (slot >= btrfs_header_nritems(leaf)) {
5424 ret = btrfs_next_leaf(clone_root->root, path);
5425 if (ret < 0)
5426 goto out;
5427 else if (ret > 0)
5428 break;
5429 continue;
5430 }
5431
5432 btrfs_item_key_to_cpu(leaf, &key, slot);
5433
5434 /*
5435 * We might have an implicit trailing hole (NO_HOLES feature
5436 * enabled). We deal with it after leaving this loop.
5437 */
5438 if (key.objectid != clone_root->ino ||
5439 key.type != BTRFS_EXTENT_DATA_KEY)
5440 break;
5441
5442 ei = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
5443 type = btrfs_file_extent_type(leaf, ei);
5444 if (type == BTRFS_FILE_EXTENT_INLINE) {
5445 ext_len = btrfs_file_extent_ram_bytes(leaf, ei);
5446 ext_len = PAGE_ALIGN(ext_len);
5447 } else {
5448 ext_len = btrfs_file_extent_num_bytes(leaf, ei);
5449 }
5450
5451 if (key.offset + ext_len <= clone_root->offset)
5452 goto next;
5453
5454 if (key.offset > clone_root->offset) {
5455 /* Implicit hole, NO_HOLES feature enabled. */
5456 u64 hole_len = key.offset - clone_root->offset;
5457
5458 if (hole_len > len)
5459 hole_len = len;
5460 ret = send_extent_data(sctx, offset, hole_len);
5461 if (ret < 0)
5462 goto out;
5463
5464 len -= hole_len;
5465 if (len == 0)
5466 break;
5467 offset += hole_len;
5468 clone_root->offset += hole_len;
5469 data_offset += hole_len;
5470 }
5471
5472 if (key.offset >= clone_root->offset + len)
5473 break;
5474
5475 if (key.offset >= clone_src_i_size)
5476 break;
5477
5478 if (key.offset + ext_len > clone_src_i_size) {
5479 ext_len = clone_src_i_size - key.offset;
5480 crossed_src_i_size = true;
5481 }
5482
5483 clone_data_offset = btrfs_file_extent_offset(leaf, ei);
5484 if (btrfs_file_extent_disk_bytenr(leaf, ei) == disk_byte) {
5485 clone_root->offset = key.offset;
5486 if (clone_data_offset < data_offset &&
5487 clone_data_offset + ext_len > data_offset) {
5488 u64 extent_offset;
5489
5490 extent_offset = data_offset - clone_data_offset;
5491 ext_len -= extent_offset;
5492 clone_data_offset += extent_offset;
5493 clone_root->offset += extent_offset;
5494 }
5495 }
5496
5497 clone_len = min_t(u64, ext_len, len);
5498
5499 if (btrfs_file_extent_disk_bytenr(leaf, ei) == disk_byte &&
5500 clone_data_offset == data_offset) {
5501 const u64 src_end = clone_root->offset + clone_len;
5502 const u64 sectorsize = SZ_64K;
5503
5504 /*
5505 * We can't clone the last block, when its size is not
5506 * sector size aligned, into the middle of a file. If we
5507 * do so, the receiver will get a failure (-EINVAL) when
5508 * trying to clone or will silently corrupt the data in
5509 * the destination file if it's on a kernel without the
5510 * fix introduced by commit ac765f83f1397646
5511 * ("Btrfs: fix data corruption due to cloning of eof
5512 * block).
5513 *
5514 * So issue a clone of the aligned down range plus a
5515 * regular write for the eof block, if we hit that case.
5516 *
5517 * Also, we use the maximum possible sector size, 64K,
5518 * because we don't know what's the sector size of the
5519 * filesystem that receives the stream, so we have to
5520 * assume the largest possible sector size.
5521 */
5522 if (src_end == clone_src_i_size &&
5523 !IS_ALIGNED(src_end, sectorsize) &&
5524 offset + clone_len < sctx->cur_inode_size) {
5525 u64 slen;
5526
5527 slen = ALIGN_DOWN(src_end - clone_root->offset,
5528 sectorsize);
5529 if (slen > 0) {
5530 ret = send_clone(sctx, offset, slen,
5531 clone_root);
5532 if (ret < 0)
5533 goto out;
5534 }
5535 ret = send_extent_data(sctx, offset + slen,
5536 clone_len - slen);
5537 } else {
5538 ret = send_clone(sctx, offset, clone_len,
5539 clone_root);
5540 }
5541 } else if (crossed_src_i_size && clone_len < len) {
5542 /*
5543 * If we are at i_size of the clone source inode and we
5544 * can not clone from it, terminate the loop. This is
5545 * to avoid sending two write operations, one with a
5546 * length matching clone_len and the final one after
5547 * this loop with a length of len - clone_len.
5548 *
5549 * When using encoded writes (BTRFS_SEND_FLAG_COMPRESSED
5550 * was passed to the send ioctl), this helps avoid
5551 * sending an encoded write for an offset that is not
5552 * sector size aligned, in case the i_size of the source
5553 * inode is not sector size aligned. That will make the
5554 * receiver fallback to decompression of the data and
5555 * writing it using regular buffered IO, therefore while
5556 * not incorrect, it's not optimal due decompression and
5557 * possible re-compression at the receiver.
5558 */
5559 break;
5560 } else {
5561 ret = send_extent_data(sctx, offset, clone_len);
5562 }
5563
5564 if (ret < 0)
5565 goto out;
5566
5567 len -= clone_len;
5568 if (len == 0)
5569 break;
5570 offset += clone_len;
5571 clone_root->offset += clone_len;
5572
5573 /*
5574 * If we are cloning from the file we are currently processing,
5575 * and using the send root as the clone root, we must stop once
5576 * the current clone offset reaches the current eof of the file
5577 * at the receiver, otherwise we would issue an invalid clone
5578 * operation (source range going beyond eof) and cause the
5579 * receiver to fail. So if we reach the current eof, bail out
5580 * and fallback to a regular write.
5581 */
5582 if (clone_root->root == sctx->send_root &&
5583 clone_root->ino == sctx->cur_ino &&
5584 clone_root->offset >= sctx->cur_inode_next_write_offset)
5585 break;
5586
5587 data_offset += clone_len;
5588next:
5589 path->slots[0]++;
5590 }
5591
5592 if (len > 0)
5593 ret = send_extent_data(sctx, offset, len);
5594 else
5595 ret = 0;
5596out:
5597 btrfs_free_path(path);
5598 return ret;
5599}
5600
5601static int send_write_or_clone(struct send_ctx *sctx,
5602 struct btrfs_path *path,
5603 struct btrfs_key *key,
5604 struct clone_root *clone_root)
5605{
5606 int ret = 0;
5607 struct btrfs_file_extent_item *ei;
5608 u64 offset = key->offset;
5609 u64 len;
5610 u8 type;
5611 u64 bs = sctx->send_root->fs_info->sb->s_blocksize;
5612
5613 ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
5614 struct btrfs_file_extent_item);
5615 type = btrfs_file_extent_type(path->nodes[0], ei);
5616 if (type == BTRFS_FILE_EXTENT_INLINE) {
5617 len = btrfs_file_extent_ram_bytes(path->nodes[0], ei);
5618 /*
5619 * it is possible the inline item won't cover the whole page,
5620 * but there may be items after this page. Make
5621 * sure to send the whole thing
5622 */
5623 len = PAGE_ALIGN(len);
5624 } else {
5625 len = btrfs_file_extent_num_bytes(path->nodes[0], ei);
5626 }
5627
5628 if (offset >= sctx->cur_inode_size) {
5629 ret = 0;
5630 goto out;
5631 }
5632 if (offset + len > sctx->cur_inode_size)
5633 len = sctx->cur_inode_size - offset;
5634 if (len == 0) {
5635 ret = 0;
5636 goto out;
5637 }
5638
5639 if (clone_root && IS_ALIGNED(offset + len, bs)) {
5640 u64 disk_byte;
5641 u64 data_offset;
5642
5643 disk_byte = btrfs_file_extent_disk_bytenr(path->nodes[0], ei);
5644 data_offset = btrfs_file_extent_offset(path->nodes[0], ei);
5645 ret = clone_range(sctx, clone_root, disk_byte, data_offset,
5646 offset, len);
5647 } else {
5648 ret = send_extent_data(sctx, offset, len);
5649 }
5650 sctx->cur_inode_next_write_offset = offset + len;
5651out:
5652 return ret;
5653}
5654
5655static int is_extent_unchanged(struct send_ctx *sctx,
5656 struct btrfs_path *left_path,
5657 struct btrfs_key *ekey)
5658{
5659 int ret = 0;
5660 struct btrfs_key key;
5661 struct btrfs_path *path = NULL;
5662 struct extent_buffer *eb;
5663 int slot;
5664 struct btrfs_key found_key;
5665 struct btrfs_file_extent_item *ei;
5666 u64 left_disknr;
5667 u64 right_disknr;
5668 u64 left_offset;
5669 u64 right_offset;
5670 u64 left_offset_fixed;
5671 u64 left_len;
5672 u64 right_len;
5673 u64 left_gen;
5674 u64 right_gen;
5675 u8 left_type;
5676 u8 right_type;
5677
5678 path = alloc_path_for_send();
5679 if (!path)
5680 return -ENOMEM;
5681
5682 eb = left_path->nodes[0];
5683 slot = left_path->slots[0];
5684 ei = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
5685 left_type = btrfs_file_extent_type(eb, ei);
5686
5687 if (left_type != BTRFS_FILE_EXTENT_REG) {
5688 ret = 0;
5689 goto out;
5690 }
5691 left_disknr = btrfs_file_extent_disk_bytenr(eb, ei);
5692 left_len = btrfs_file_extent_num_bytes(eb, ei);
5693 left_offset = btrfs_file_extent_offset(eb, ei);
5694 left_gen = btrfs_file_extent_generation(eb, ei);
5695
5696 /*
5697 * Following comments will refer to these graphics. L is the left
5698 * extents which we are checking at the moment. 1-8 are the right
5699 * extents that we iterate.
5700 *
5701 * |-----L-----|
5702 * |-1-|-2a-|-3-|-4-|-5-|-6-|
5703 *
5704 * |-----L-----|
5705 * |--1--|-2b-|...(same as above)
5706 *
5707 * Alternative situation. Happens on files where extents got split.
5708 * |-----L-----|
5709 * |-----------7-----------|-6-|
5710 *
5711 * Alternative situation. Happens on files which got larger.
5712 * |-----L-----|
5713 * |-8-|
5714 * Nothing follows after 8.
5715 */
5716
5717 key.objectid = ekey->objectid;
5718 key.type = BTRFS_EXTENT_DATA_KEY;
5719 key.offset = ekey->offset;
5720 ret = btrfs_search_slot_for_read(sctx->parent_root, &key, path, 0, 0);
5721 if (ret < 0)
5722 goto out;
5723 if (ret) {
5724 ret = 0;
5725 goto out;
5726 }
5727
5728 /*
5729 * Handle special case where the right side has no extents at all.
5730 */
5731 eb = path->nodes[0];
5732 slot = path->slots[0];
5733 btrfs_item_key_to_cpu(eb, &found_key, slot);
5734 if (found_key.objectid != key.objectid ||
5735 found_key.type != key.type) {
5736 /* If we're a hole then just pretend nothing changed */
5737 ret = (left_disknr) ? 0 : 1;
5738 goto out;
5739 }
5740
5741 /*
5742 * We're now on 2a, 2b or 7.
5743 */
5744 key = found_key;
5745 while (key.offset < ekey->offset + left_len) {
5746 ei = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
5747 right_type = btrfs_file_extent_type(eb, ei);
5748 if (right_type != BTRFS_FILE_EXTENT_REG &&
5749 right_type != BTRFS_FILE_EXTENT_INLINE) {
5750 ret = 0;
5751 goto out;
5752 }
5753
5754 if (right_type == BTRFS_FILE_EXTENT_INLINE) {
5755 right_len = btrfs_file_extent_ram_bytes(eb, ei);
5756 right_len = PAGE_ALIGN(right_len);
5757 } else {
5758 right_len = btrfs_file_extent_num_bytes(eb, ei);
5759 }
5760
5761 /*
5762 * Are we at extent 8? If yes, we know the extent is changed.
5763 * This may only happen on the first iteration.
5764 */
5765 if (found_key.offset + right_len <= ekey->offset) {
5766 /* If we're a hole just pretend nothing changed */
5767 ret = (left_disknr) ? 0 : 1;
5768 goto out;
5769 }
5770
5771 /*
5772 * We just wanted to see if when we have an inline extent, what
5773 * follows it is a regular extent (wanted to check the above
5774 * condition for inline extents too). This should normally not
5775 * happen but it's possible for example when we have an inline
5776 * compressed extent representing data with a size matching
5777 * the page size (currently the same as sector size).
5778 */
5779 if (right_type == BTRFS_FILE_EXTENT_INLINE) {
5780 ret = 0;
5781 goto out;
5782 }
5783
5784 right_disknr = btrfs_file_extent_disk_bytenr(eb, ei);
5785 right_offset = btrfs_file_extent_offset(eb, ei);
5786 right_gen = btrfs_file_extent_generation(eb, ei);
5787
5788 left_offset_fixed = left_offset;
5789 if (key.offset < ekey->offset) {
5790 /* Fix the right offset for 2a and 7. */
5791 right_offset += ekey->offset - key.offset;
5792 } else {
5793 /* Fix the left offset for all behind 2a and 2b */
5794 left_offset_fixed += key.offset - ekey->offset;
5795 }
5796
5797 /*
5798 * Check if we have the same extent.
5799 */
5800 if (left_disknr != right_disknr ||
5801 left_offset_fixed != right_offset ||
5802 left_gen != right_gen) {
5803 ret = 0;
5804 goto out;
5805 }
5806
5807 /*
5808 * Go to the next extent.
5809 */
5810 ret = btrfs_next_item(sctx->parent_root, path);
5811 if (ret < 0)
5812 goto out;
5813 if (!ret) {
5814 eb = path->nodes[0];
5815 slot = path->slots[0];
5816 btrfs_item_key_to_cpu(eb, &found_key, slot);
5817 }
5818 if (ret || found_key.objectid != key.objectid ||
5819 found_key.type != key.type) {
5820 key.offset += right_len;
5821 break;
5822 }
5823 if (found_key.offset != key.offset + right_len) {
5824 ret = 0;
5825 goto out;
5826 }
5827 key = found_key;
5828 }
5829
5830 /*
5831 * We're now behind the left extent (treat as unchanged) or at the end
5832 * of the right side (treat as changed).
5833 */
5834 if (key.offset >= ekey->offset + left_len)
5835 ret = 1;
5836 else
5837 ret = 0;
5838
5839
5840out:
5841 btrfs_free_path(path);
5842 return ret;
5843}
5844
5845static int get_last_extent(struct send_ctx *sctx, u64 offset)
5846{
5847 struct btrfs_path *path;
5848 struct btrfs_root *root = sctx->send_root;
5849 struct btrfs_file_extent_item *fi;
5850 struct btrfs_key key;
5851 u64 extent_end;
5852 u8 type;
5853 int ret;
5854
5855 path = alloc_path_for_send();
5856 if (!path)
5857 return -ENOMEM;
5858
5859 sctx->cur_inode_last_extent = 0;
5860
5861 key.objectid = sctx->cur_ino;
5862 key.type = BTRFS_EXTENT_DATA_KEY;
5863 key.offset = offset;
5864 ret = btrfs_search_slot_for_read(root, &key, path, 0, 1);
5865 if (ret < 0)
5866 goto out;
5867 ret = 0;
5868 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
5869 if (key.objectid != sctx->cur_ino || key.type != BTRFS_EXTENT_DATA_KEY)
5870 goto out;
5871
5872 fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
5873 struct btrfs_file_extent_item);
5874 type = btrfs_file_extent_type(path->nodes[0], fi);
5875 if (type == BTRFS_FILE_EXTENT_INLINE) {
5876 u64 size = btrfs_file_extent_ram_bytes(path->nodes[0], fi);
5877 extent_end = ALIGN(key.offset + size,
5878 sctx->send_root->fs_info->sectorsize);
5879 } else {
5880 extent_end = key.offset +
5881 btrfs_file_extent_num_bytes(path->nodes[0], fi);
5882 }
5883 sctx->cur_inode_last_extent = extent_end;
5884out:
5885 btrfs_free_path(path);
5886 return ret;
5887}
5888
5889static int range_is_hole_in_parent(struct send_ctx *sctx,
5890 const u64 start,
5891 const u64 end)
5892{
5893 struct btrfs_path *path;
5894 struct btrfs_key key;
5895 struct btrfs_root *root = sctx->parent_root;
5896 u64 search_start = start;
5897 int ret;
5898
5899 path = alloc_path_for_send();
5900 if (!path)
5901 return -ENOMEM;
5902
5903 key.objectid = sctx->cur_ino;
5904 key.type = BTRFS_EXTENT_DATA_KEY;
5905 key.offset = search_start;
5906 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5907 if (ret < 0)
5908 goto out;
5909 if (ret > 0 && path->slots[0] > 0)
5910 path->slots[0]--;
5911
5912 while (search_start < end) {
5913 struct extent_buffer *leaf = path->nodes[0];
5914 int slot = path->slots[0];
5915 struct btrfs_file_extent_item *fi;
5916 u64 extent_end;
5917
5918 if (slot >= btrfs_header_nritems(leaf)) {
5919 ret = btrfs_next_leaf(root, path);
5920 if (ret < 0)
5921 goto out;
5922 else if (ret > 0)
5923 break;
5924 continue;
5925 }
5926
5927 btrfs_item_key_to_cpu(leaf, &key, slot);
5928 if (key.objectid < sctx->cur_ino ||
5929 key.type < BTRFS_EXTENT_DATA_KEY)
5930 goto next;
5931 if (key.objectid > sctx->cur_ino ||
5932 key.type > BTRFS_EXTENT_DATA_KEY ||
5933 key.offset >= end)
5934 break;
5935
5936 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
5937 if (btrfs_file_extent_type(leaf, fi) ==
5938 BTRFS_FILE_EXTENT_INLINE) {
5939 u64 size = btrfs_file_extent_ram_bytes(leaf, fi);
5940
5941 extent_end = ALIGN(key.offset + size,
5942 root->fs_info->sectorsize);
5943 } else {
5944 extent_end = key.offset +
5945 btrfs_file_extent_num_bytes(leaf, fi);
5946 }
5947 if (extent_end <= start)
5948 goto next;
5949 if (btrfs_file_extent_disk_bytenr(leaf, fi) == 0) {
5950 search_start = extent_end;
5951 goto next;
5952 }
5953 ret = 0;
5954 goto out;
5955next:
5956 path->slots[0]++;
5957 }
5958 ret = 1;
5959out:
5960 btrfs_free_path(path);
5961 return ret;
5962}
5963
5964static int maybe_send_hole(struct send_ctx *sctx, struct btrfs_path *path,
5965 struct btrfs_key *key)
5966{
5967 struct btrfs_file_extent_item *fi;
5968 u64 extent_end;
5969 u8 type;
5970 int ret = 0;
5971
5972 if (sctx->cur_ino != key->objectid || !need_send_hole(sctx))
5973 return 0;
5974
5975 if (sctx->cur_inode_last_extent == (u64)-1) {
5976 ret = get_last_extent(sctx, key->offset - 1);
5977 if (ret)
5978 return ret;
5979 }
5980
5981 fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
5982 struct btrfs_file_extent_item);
5983 type = btrfs_file_extent_type(path->nodes[0], fi);
5984 if (type == BTRFS_FILE_EXTENT_INLINE) {
5985 u64 size = btrfs_file_extent_ram_bytes(path->nodes[0], fi);
5986 extent_end = ALIGN(key->offset + size,
5987 sctx->send_root->fs_info->sectorsize);
5988 } else {
5989 extent_end = key->offset +
5990 btrfs_file_extent_num_bytes(path->nodes[0], fi);
5991 }
5992
5993 if (path->slots[0] == 0 &&
5994 sctx->cur_inode_last_extent < key->offset) {
5995 /*
5996 * We might have skipped entire leafs that contained only
5997 * file extent items for our current inode. These leafs have
5998 * a generation number smaller (older) than the one in the
5999 * current leaf and the leaf our last extent came from, and
6000 * are located between these 2 leafs.
6001 */
6002 ret = get_last_extent(sctx, key->offset - 1);
6003 if (ret)
6004 return ret;
6005 }
6006
6007 if (sctx->cur_inode_last_extent < key->offset) {
6008 ret = range_is_hole_in_parent(sctx,
6009 sctx->cur_inode_last_extent,
6010 key->offset);
6011 if (ret < 0)
6012 return ret;
6013 else if (ret == 0)
6014 ret = send_hole(sctx, key->offset);
6015 else
6016 ret = 0;
6017 }
6018 sctx->cur_inode_last_extent = extent_end;
6019 return ret;
6020}
6021
6022static int process_extent(struct send_ctx *sctx,
6023 struct btrfs_path *path,
6024 struct btrfs_key *key)
6025{
6026 struct clone_root *found_clone = NULL;
6027 int ret = 0;
6028
6029 if (S_ISLNK(sctx->cur_inode_mode))
6030 return 0;
6031
6032 if (sctx->parent_root && !sctx->cur_inode_new) {
6033 ret = is_extent_unchanged(sctx, path, key);
6034 if (ret < 0)
6035 goto out;
6036 if (ret) {
6037 ret = 0;
6038 goto out_hole;
6039 }
6040 } else {
6041 struct btrfs_file_extent_item *ei;
6042 u8 type;
6043
6044 ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
6045 struct btrfs_file_extent_item);
6046 type = btrfs_file_extent_type(path->nodes[0], ei);
6047 if (type == BTRFS_FILE_EXTENT_PREALLOC ||
6048 type == BTRFS_FILE_EXTENT_REG) {
6049 /*
6050 * The send spec does not have a prealloc command yet,
6051 * so just leave a hole for prealloc'ed extents until
6052 * we have enough commands queued up to justify rev'ing
6053 * the send spec.
6054 */
6055 if (type == BTRFS_FILE_EXTENT_PREALLOC) {
6056 ret = 0;
6057 goto out;
6058 }
6059
6060 /* Have a hole, just skip it. */
6061 if (btrfs_file_extent_disk_bytenr(path->nodes[0], ei) == 0) {
6062 ret = 0;
6063 goto out;
6064 }
6065 }
6066 }
6067
6068 ret = find_extent_clone(sctx, path, key->objectid, key->offset,
6069 sctx->cur_inode_size, &found_clone);
6070 if (ret != -ENOENT && ret < 0)
6071 goto out;
6072
6073 ret = send_write_or_clone(sctx, path, key, found_clone);
6074 if (ret)
6075 goto out;
6076out_hole:
6077 ret = maybe_send_hole(sctx, path, key);
6078out:
6079 return ret;
6080}
6081
6082static int process_all_extents(struct send_ctx *sctx)
6083{
6084 int ret;
6085 struct btrfs_root *root;
6086 struct btrfs_path *path;
6087 struct btrfs_key key;
6088 struct btrfs_key found_key;
6089 struct extent_buffer *eb;
6090 int slot;
6091
6092 root = sctx->send_root;
6093 path = alloc_path_for_send();
6094 if (!path)
6095 return -ENOMEM;
6096
6097 key.objectid = sctx->cmp_key->objectid;
6098 key.type = BTRFS_EXTENT_DATA_KEY;
6099 key.offset = 0;
6100 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6101 if (ret < 0)
6102 goto out;
6103
6104 while (1) {
6105 eb = path->nodes[0];
6106 slot = path->slots[0];
6107
6108 if (slot >= btrfs_header_nritems(eb)) {
6109 ret = btrfs_next_leaf(root, path);
6110 if (ret < 0) {
6111 goto out;
6112 } else if (ret > 0) {
6113 ret = 0;
6114 break;
6115 }
6116 continue;
6117 }
6118
6119 btrfs_item_key_to_cpu(eb, &found_key, slot);
6120
6121 if (found_key.objectid != key.objectid ||
6122 found_key.type != key.type) {
6123 ret = 0;
6124 goto out;
6125 }
6126
6127 ret = process_extent(sctx, path, &found_key);
6128 if (ret < 0)
6129 goto out;
6130
6131 path->slots[0]++;
6132 }
6133
6134out:
6135 btrfs_free_path(path);
6136 return ret;
6137}
6138
6139static int process_recorded_refs_if_needed(struct send_ctx *sctx, int at_end,
6140 int *pending_move,
6141 int *refs_processed)
6142{
6143 int ret = 0;
6144
6145 if (sctx->cur_ino == 0)
6146 goto out;
6147 if (!at_end && sctx->cur_ino == sctx->cmp_key->objectid &&
6148 sctx->cmp_key->type <= BTRFS_INODE_EXTREF_KEY)
6149 goto out;
6150 if (list_empty(&sctx->new_refs) && list_empty(&sctx->deleted_refs))
6151 goto out;
6152
6153 ret = process_recorded_refs(sctx, pending_move);
6154 if (ret < 0)
6155 goto out;
6156
6157 *refs_processed = 1;
6158out:
6159 return ret;
6160}
6161
6162static int finish_inode_if_needed(struct send_ctx *sctx, int at_end)
6163{
6164 int ret = 0;
6165 u64 left_mode;
6166 u64 left_uid;
6167 u64 left_gid;
6168 u64 right_mode;
6169 u64 right_uid;
6170 u64 right_gid;
6171 int need_chmod = 0;
6172 int need_chown = 0;
6173 int need_truncate = 1;
6174 int pending_move = 0;
6175 int refs_processed = 0;
6176
6177 if (sctx->ignore_cur_inode)
6178 return 0;
6179
6180 ret = process_recorded_refs_if_needed(sctx, at_end, &pending_move,
6181 &refs_processed);
6182 if (ret < 0)
6183 goto out;
6184
6185 /*
6186 * We have processed the refs and thus need to advance send_progress.
6187 * Now, calls to get_cur_xxx will take the updated refs of the current
6188 * inode into account.
6189 *
6190 * On the other hand, if our current inode is a directory and couldn't
6191 * be moved/renamed because its parent was renamed/moved too and it has
6192 * a higher inode number, we can only move/rename our current inode
6193 * after we moved/renamed its parent. Therefore in this case operate on
6194 * the old path (pre move/rename) of our current inode, and the
6195 * move/rename will be performed later.
6196 */
6197 if (refs_processed && !pending_move)
6198 sctx->send_progress = sctx->cur_ino + 1;
6199
6200 if (sctx->cur_ino == 0 || sctx->cur_inode_deleted)
6201 goto out;
6202 if (!at_end && sctx->cmp_key->objectid == sctx->cur_ino)
6203 goto out;
6204
6205 ret = get_inode_info(sctx->send_root, sctx->cur_ino, NULL, NULL,
6206 &left_mode, &left_uid, &left_gid, NULL);
6207 if (ret < 0)
6208 goto out;
6209
6210 if (!sctx->parent_root || sctx->cur_inode_new) {
6211 need_chown = 1;
6212 if (!S_ISLNK(sctx->cur_inode_mode))
6213 need_chmod = 1;
6214 if (sctx->cur_inode_next_write_offset == sctx->cur_inode_size)
6215 need_truncate = 0;
6216 } else {
6217 u64 old_size;
6218
6219 ret = get_inode_info(sctx->parent_root, sctx->cur_ino,
6220 &old_size, NULL, &right_mode, &right_uid,
6221 &right_gid, NULL);
6222 if (ret < 0)
6223 goto out;
6224
6225 if (left_uid != right_uid || left_gid != right_gid)
6226 need_chown = 1;
6227 if (!S_ISLNK(sctx->cur_inode_mode) && left_mode != right_mode)
6228 need_chmod = 1;
6229 if ((old_size == sctx->cur_inode_size) ||
6230 (sctx->cur_inode_size > old_size &&
6231 sctx->cur_inode_next_write_offset == sctx->cur_inode_size))
6232 need_truncate = 0;
6233 }
6234
6235 if (S_ISREG(sctx->cur_inode_mode)) {
6236 if (need_send_hole(sctx)) {
6237 if (sctx->cur_inode_last_extent == (u64)-1 ||
6238 sctx->cur_inode_last_extent <
6239 sctx->cur_inode_size) {
6240 ret = get_last_extent(sctx, (u64)-1);
6241 if (ret)
6242 goto out;
6243 }
6244 if (sctx->cur_inode_last_extent <
6245 sctx->cur_inode_size) {
6246 ret = send_hole(sctx, sctx->cur_inode_size);
6247 if (ret)
6248 goto out;
6249 }
6250 }
6251 if (need_truncate) {
6252 ret = send_truncate(sctx, sctx->cur_ino,
6253 sctx->cur_inode_gen,
6254 sctx->cur_inode_size);
6255 if (ret < 0)
6256 goto out;
6257 }
6258 }
6259
6260 if (need_chown) {
6261 ret = send_chown(sctx, sctx->cur_ino, sctx->cur_inode_gen,
6262 left_uid, left_gid);
6263 if (ret < 0)
6264 goto out;
6265 }
6266 if (need_chmod) {
6267 ret = send_chmod(sctx, sctx->cur_ino, sctx->cur_inode_gen,
6268 left_mode);
6269 if (ret < 0)
6270 goto out;
6271 }
6272
6273 ret = send_capabilities(sctx);
6274 if (ret < 0)
6275 goto out;
6276
6277 /*
6278 * If other directory inodes depended on our current directory
6279 * inode's move/rename, now do their move/rename operations.
6280 */
6281 if (!is_waiting_for_move(sctx, sctx->cur_ino)) {
6282 ret = apply_children_dir_moves(sctx);
6283 if (ret)
6284 goto out;
6285 /*
6286 * Need to send that every time, no matter if it actually
6287 * changed between the two trees as we have done changes to
6288 * the inode before. If our inode is a directory and it's
6289 * waiting to be moved/renamed, we will send its utimes when
6290 * it's moved/renamed, therefore we don't need to do it here.
6291 */
6292 sctx->send_progress = sctx->cur_ino + 1;
6293 ret = send_utimes(sctx, sctx->cur_ino, sctx->cur_inode_gen);
6294 if (ret < 0)
6295 goto out;
6296 }
6297
6298out:
6299 return ret;
6300}
6301
6302struct parent_paths_ctx {
6303 struct list_head *refs;
6304 struct send_ctx *sctx;
6305};
6306
6307static int record_parent_ref(int num, u64 dir, int index, struct fs_path *name,
6308 void *ctx)
6309{
6310 struct parent_paths_ctx *ppctx = ctx;
6311
6312 return record_ref(ppctx->sctx->parent_root, dir, name, ppctx->sctx,
6313 ppctx->refs);
6314}
6315
6316/*
6317 * Issue unlink operations for all paths of the current inode found in the
6318 * parent snapshot.
6319 */
6320static int btrfs_unlink_all_paths(struct send_ctx *sctx)
6321{
6322 LIST_HEAD(deleted_refs);
6323 struct btrfs_path *path;
6324 struct btrfs_key key;
6325 struct parent_paths_ctx ctx;
6326 int ret;
6327
6328 path = alloc_path_for_send();
6329 if (!path)
6330 return -ENOMEM;
6331
6332 key.objectid = sctx->cur_ino;
6333 key.type = BTRFS_INODE_REF_KEY;
6334 key.offset = 0;
6335 ret = btrfs_search_slot(NULL, sctx->parent_root, &key, path, 0, 0);
6336 if (ret < 0)
6337 goto out;
6338
6339 ctx.refs = &deleted_refs;
6340 ctx.sctx = sctx;
6341
6342 while (true) {
6343 struct extent_buffer *eb = path->nodes[0];
6344 int slot = path->slots[0];
6345
6346 if (slot >= btrfs_header_nritems(eb)) {
6347 ret = btrfs_next_leaf(sctx->parent_root, path);
6348 if (ret < 0)
6349 goto out;
6350 else if (ret > 0)
6351 break;
6352 continue;
6353 }
6354
6355 btrfs_item_key_to_cpu(eb, &key, slot);
6356 if (key.objectid != sctx->cur_ino)
6357 break;
6358 if (key.type != BTRFS_INODE_REF_KEY &&
6359 key.type != BTRFS_INODE_EXTREF_KEY)
6360 break;
6361
6362 ret = iterate_inode_ref(sctx->parent_root, path, &key, 1,
6363 record_parent_ref, &ctx);
6364 if (ret < 0)
6365 goto out;
6366
6367 path->slots[0]++;
6368 }
6369
6370 while (!list_empty(&deleted_refs)) {
6371 struct recorded_ref *ref;
6372
6373 ref = list_first_entry(&deleted_refs, struct recorded_ref, list);
6374 ret = send_unlink(sctx, ref->full_path);
6375 if (ret < 0)
6376 goto out;
6377 fs_path_free(ref->full_path);
6378 list_del(&ref->list);
6379 kfree(ref);
6380 }
6381 ret = 0;
6382out:
6383 btrfs_free_path(path);
6384 if (ret)
6385 __free_recorded_refs(&deleted_refs);
6386 return ret;
6387}
6388
6389static int changed_inode(struct send_ctx *sctx,
6390 enum btrfs_compare_tree_result result)
6391{
6392 int ret = 0;
6393 struct btrfs_key *key = sctx->cmp_key;
6394 struct btrfs_inode_item *left_ii = NULL;
6395 struct btrfs_inode_item *right_ii = NULL;
6396 u64 left_gen = 0;
6397 u64 right_gen = 0;
6398
6399 sctx->cur_ino = key->objectid;
6400 sctx->cur_inode_new_gen = 0;
6401 sctx->cur_inode_last_extent = (u64)-1;
6402 sctx->cur_inode_next_write_offset = 0;
6403 sctx->ignore_cur_inode = false;
6404
6405 /*
6406 * Set send_progress to current inode. This will tell all get_cur_xxx
6407 * functions that the current inode's refs are not updated yet. Later,
6408 * when process_recorded_refs is finished, it is set to cur_ino + 1.
6409 */
6410 sctx->send_progress = sctx->cur_ino;
6411
6412 if (result == BTRFS_COMPARE_TREE_NEW ||
6413 result == BTRFS_COMPARE_TREE_CHANGED) {
6414 left_ii = btrfs_item_ptr(sctx->left_path->nodes[0],
6415 sctx->left_path->slots[0],
6416 struct btrfs_inode_item);
6417 left_gen = btrfs_inode_generation(sctx->left_path->nodes[0],
6418 left_ii);
6419 } else {
6420 right_ii = btrfs_item_ptr(sctx->right_path->nodes[0],
6421 sctx->right_path->slots[0],
6422 struct btrfs_inode_item);
6423 right_gen = btrfs_inode_generation(sctx->right_path->nodes[0],
6424 right_ii);
6425 }
6426 if (result == BTRFS_COMPARE_TREE_CHANGED) {
6427 right_ii = btrfs_item_ptr(sctx->right_path->nodes[0],
6428 sctx->right_path->slots[0],
6429 struct btrfs_inode_item);
6430
6431 right_gen = btrfs_inode_generation(sctx->right_path->nodes[0],
6432 right_ii);
6433
6434 /*
6435 * The cur_ino = root dir case is special here. We can't treat
6436 * the inode as deleted+reused because it would generate a
6437 * stream that tries to delete/mkdir the root dir.
6438 */
6439 if (left_gen != right_gen &&
6440 sctx->cur_ino != BTRFS_FIRST_FREE_OBJECTID)
6441 sctx->cur_inode_new_gen = 1;
6442 }
6443
6444 /*
6445 * Normally we do not find inodes with a link count of zero (orphans)
6446 * because the most common case is to create a snapshot and use it
6447 * for a send operation. However other less common use cases involve
6448 * using a subvolume and send it after turning it to RO mode just
6449 * after deleting all hard links of a file while holding an open
6450 * file descriptor against it or turning a RO snapshot into RW mode,
6451 * keep an open file descriptor against a file, delete it and then
6452 * turn the snapshot back to RO mode before using it for a send
6453 * operation. So if we find such cases, ignore the inode and all its
6454 * items completely if it's a new inode, or if it's a changed inode
6455 * make sure all its previous paths (from the parent snapshot) are all
6456 * unlinked and all other the inode items are ignored.
6457 */
6458 if (result == BTRFS_COMPARE_TREE_NEW ||
6459 result == BTRFS_COMPARE_TREE_CHANGED) {
6460 u32 nlinks;
6461
6462 nlinks = btrfs_inode_nlink(sctx->left_path->nodes[0], left_ii);
6463 if (nlinks == 0) {
6464 sctx->ignore_cur_inode = true;
6465 if (result == BTRFS_COMPARE_TREE_CHANGED)
6466 ret = btrfs_unlink_all_paths(sctx);
6467 goto out;
6468 }
6469 }
6470
6471 if (result == BTRFS_COMPARE_TREE_NEW) {
6472 sctx->cur_inode_gen = left_gen;
6473 sctx->cur_inode_new = 1;
6474 sctx->cur_inode_deleted = 0;
6475 sctx->cur_inode_size = btrfs_inode_size(
6476 sctx->left_path->nodes[0], left_ii);
6477 sctx->cur_inode_mode = btrfs_inode_mode(
6478 sctx->left_path->nodes[0], left_ii);
6479 sctx->cur_inode_rdev = btrfs_inode_rdev(
6480 sctx->left_path->nodes[0], left_ii);
6481 if (sctx->cur_ino != BTRFS_FIRST_FREE_OBJECTID)
6482 ret = send_create_inode_if_needed(sctx);
6483 } else if (result == BTRFS_COMPARE_TREE_DELETED) {
6484 sctx->cur_inode_gen = right_gen;
6485 sctx->cur_inode_new = 0;
6486 sctx->cur_inode_deleted = 1;
6487 sctx->cur_inode_size = btrfs_inode_size(
6488 sctx->right_path->nodes[0], right_ii);
6489 sctx->cur_inode_mode = btrfs_inode_mode(
6490 sctx->right_path->nodes[0], right_ii);
6491 } else if (result == BTRFS_COMPARE_TREE_CHANGED) {
6492 /*
6493 * We need to do some special handling in case the inode was
6494 * reported as changed with a changed generation number. This
6495 * means that the original inode was deleted and new inode
6496 * reused the same inum. So we have to treat the old inode as
6497 * deleted and the new one as new.
6498 */
6499 if (sctx->cur_inode_new_gen) {
6500 /*
6501 * First, process the inode as if it was deleted.
6502 */
6503 sctx->cur_inode_gen = right_gen;
6504 sctx->cur_inode_new = 0;
6505 sctx->cur_inode_deleted = 1;
6506 sctx->cur_inode_size = btrfs_inode_size(
6507 sctx->right_path->nodes[0], right_ii);
6508 sctx->cur_inode_mode = btrfs_inode_mode(
6509 sctx->right_path->nodes[0], right_ii);
6510 ret = process_all_refs(sctx,
6511 BTRFS_COMPARE_TREE_DELETED);
6512 if (ret < 0)
6513 goto out;
6514
6515 /*
6516 * Now process the inode as if it was new.
6517 */
6518 sctx->cur_inode_gen = left_gen;
6519 sctx->cur_inode_new = 1;
6520 sctx->cur_inode_deleted = 0;
6521 sctx->cur_inode_size = btrfs_inode_size(
6522 sctx->left_path->nodes[0], left_ii);
6523 sctx->cur_inode_mode = btrfs_inode_mode(
6524 sctx->left_path->nodes[0], left_ii);
6525 sctx->cur_inode_rdev = btrfs_inode_rdev(
6526 sctx->left_path->nodes[0], left_ii);
6527 ret = send_create_inode_if_needed(sctx);
6528 if (ret < 0)
6529 goto out;
6530
6531 ret = process_all_refs(sctx, BTRFS_COMPARE_TREE_NEW);
6532 if (ret < 0)
6533 goto out;
6534 /*
6535 * Advance send_progress now as we did not get into
6536 * process_recorded_refs_if_needed in the new_gen case.
6537 */
6538 sctx->send_progress = sctx->cur_ino + 1;
6539
6540 /*
6541 * Now process all extents and xattrs of the inode as if
6542 * they were all new.
6543 */
6544 ret = process_all_extents(sctx);
6545 if (ret < 0)
6546 goto out;
6547 ret = process_all_new_xattrs(sctx);
6548 if (ret < 0)
6549 goto out;
6550 } else {
6551 sctx->cur_inode_gen = left_gen;
6552 sctx->cur_inode_new = 0;
6553 sctx->cur_inode_new_gen = 0;
6554 sctx->cur_inode_deleted = 0;
6555 sctx->cur_inode_size = btrfs_inode_size(
6556 sctx->left_path->nodes[0], left_ii);
6557 sctx->cur_inode_mode = btrfs_inode_mode(
6558 sctx->left_path->nodes[0], left_ii);
6559 }
6560 }
6561
6562out:
6563 return ret;
6564}
6565
6566/*
6567 * We have to process new refs before deleted refs, but compare_trees gives us
6568 * the new and deleted refs mixed. To fix this, we record the new/deleted refs
6569 * first and later process them in process_recorded_refs.
6570 * For the cur_inode_new_gen case, we skip recording completely because
6571 * changed_inode did already initiate processing of refs. The reason for this is
6572 * that in this case, compare_tree actually compares the refs of 2 different
6573 * inodes. To fix this, process_all_refs is used in changed_inode to handle all
6574 * refs of the right tree as deleted and all refs of the left tree as new.
6575 */
6576static int changed_ref(struct send_ctx *sctx,
6577 enum btrfs_compare_tree_result result)
6578{
6579 int ret = 0;
6580
6581 if (sctx->cur_ino != sctx->cmp_key->objectid) {
6582 inconsistent_snapshot_error(sctx, result, "reference");
6583 return -EIO;
6584 }
6585
6586 if (!sctx->cur_inode_new_gen &&
6587 sctx->cur_ino != BTRFS_FIRST_FREE_OBJECTID) {
6588 if (result == BTRFS_COMPARE_TREE_NEW)
6589 ret = record_new_ref(sctx);
6590 else if (result == BTRFS_COMPARE_TREE_DELETED)
6591 ret = record_deleted_ref(sctx);
6592 else if (result == BTRFS_COMPARE_TREE_CHANGED)
6593 ret = record_changed_ref(sctx);
6594 }
6595
6596 return ret;
6597}
6598
6599/*
6600 * Process new/deleted/changed xattrs. We skip processing in the
6601 * cur_inode_new_gen case because changed_inode did already initiate processing
6602 * of xattrs. The reason is the same as in changed_ref
6603 */
6604static int changed_xattr(struct send_ctx *sctx,
6605 enum btrfs_compare_tree_result result)
6606{
6607 int ret = 0;
6608
6609 if (sctx->cur_ino != sctx->cmp_key->objectid) {
6610 inconsistent_snapshot_error(sctx, result, "xattr");
6611 return -EIO;
6612 }
6613
6614 if (!sctx->cur_inode_new_gen && !sctx->cur_inode_deleted) {
6615 if (result == BTRFS_COMPARE_TREE_NEW)
6616 ret = process_new_xattr(sctx);
6617 else if (result == BTRFS_COMPARE_TREE_DELETED)
6618 ret = process_deleted_xattr(sctx);
6619 else if (result == BTRFS_COMPARE_TREE_CHANGED)
6620 ret = process_changed_xattr(sctx);
6621 }
6622
6623 return ret;
6624}
6625
6626/*
6627 * Process new/deleted/changed extents. We skip processing in the
6628 * cur_inode_new_gen case because changed_inode did already initiate processing
6629 * of extents. The reason is the same as in changed_ref
6630 */
6631static int changed_extent(struct send_ctx *sctx,
6632 enum btrfs_compare_tree_result result)
6633{
6634 int ret = 0;
6635
6636 /*
6637 * We have found an extent item that changed without the inode item
6638 * having changed. This can happen either after relocation (where the
6639 * disk_bytenr of an extent item is replaced at
6640 * relocation.c:replace_file_extents()) or after deduplication into a
6641 * file in both the parent and send snapshots (where an extent item can
6642 * get modified or replaced with a new one). Note that deduplication
6643 * updates the inode item, but it only changes the iversion (sequence
6644 * field in the inode item) of the inode, so if a file is deduplicated
6645 * the same amount of times in both the parent and send snapshots, its
6646 * iversion becames the same in both snapshots, whence the inode item is
6647 * the same on both snapshots.
6648 */
6649 if (sctx->cur_ino != sctx->cmp_key->objectid)
6650 return 0;
6651
6652 if (!sctx->cur_inode_new_gen && !sctx->cur_inode_deleted) {
6653 if (result != BTRFS_COMPARE_TREE_DELETED)
6654 ret = process_extent(sctx, sctx->left_path,
6655 sctx->cmp_key);
6656 }
6657
6658 return ret;
6659}
6660
6661static int dir_changed(struct send_ctx *sctx, u64 dir)
6662{
6663 u64 orig_gen, new_gen;
6664 int ret;
6665
6666 ret = get_inode_info(sctx->send_root, dir, NULL, &new_gen, NULL, NULL,
6667 NULL, NULL);
6668 if (ret)
6669 return ret;
6670
6671 ret = get_inode_info(sctx->parent_root, dir, NULL, &orig_gen, NULL,
6672 NULL, NULL, NULL);
6673 if (ret)
6674 return ret;
6675
6676 return (orig_gen != new_gen) ? 1 : 0;
6677}
6678
6679static int compare_refs(struct send_ctx *sctx, struct btrfs_path *path,
6680 struct btrfs_key *key)
6681{
6682 struct btrfs_inode_extref *extref;
6683 struct extent_buffer *leaf;
6684 u64 dirid = 0, last_dirid = 0;
6685 unsigned long ptr;
6686 u32 item_size;
6687 u32 cur_offset = 0;
6688 int ref_name_len;
6689 int ret = 0;
6690
6691 /* Easy case, just check this one dirid */
6692 if (key->type == BTRFS_INODE_REF_KEY) {
6693 dirid = key->offset;
6694
6695 ret = dir_changed(sctx, dirid);
6696 goto out;
6697 }
6698
6699 leaf = path->nodes[0];
6700 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
6701 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
6702 while (cur_offset < item_size) {
6703 extref = (struct btrfs_inode_extref *)(ptr +
6704 cur_offset);
6705 dirid = btrfs_inode_extref_parent(leaf, extref);
6706 ref_name_len = btrfs_inode_extref_name_len(leaf, extref);
6707 cur_offset += ref_name_len + sizeof(*extref);
6708 if (dirid == last_dirid)
6709 continue;
6710 ret = dir_changed(sctx, dirid);
6711 if (ret)
6712 break;
6713 last_dirid = dirid;
6714 }
6715out:
6716 return ret;
6717}
6718
6719/*
6720 * Updates compare related fields in sctx and simply forwards to the actual
6721 * changed_xxx functions.
6722 */
6723static int changed_cb(struct btrfs_path *left_path,
6724 struct btrfs_path *right_path,
6725 struct btrfs_key *key,
6726 enum btrfs_compare_tree_result result,
6727 void *ctx)
6728{
6729 int ret = 0;
6730 struct send_ctx *sctx = ctx;
6731
6732 if (result == BTRFS_COMPARE_TREE_SAME) {
6733 if (key->type == BTRFS_INODE_REF_KEY ||
6734 key->type == BTRFS_INODE_EXTREF_KEY) {
6735 ret = compare_refs(sctx, left_path, key);
6736 if (!ret)
6737 return 0;
6738 if (ret < 0)
6739 return ret;
6740 } else if (key->type == BTRFS_EXTENT_DATA_KEY) {
6741 return maybe_send_hole(sctx, left_path, key);
6742 } else {
6743 return 0;
6744 }
6745 result = BTRFS_COMPARE_TREE_CHANGED;
6746 ret = 0;
6747 }
6748
6749 sctx->left_path = left_path;
6750 sctx->right_path = right_path;
6751 sctx->cmp_key = key;
6752
6753 ret = finish_inode_if_needed(sctx, 0);
6754 if (ret < 0)
6755 goto out;
6756
6757 /* Ignore non-FS objects */
6758 if (key->objectid == BTRFS_FREE_INO_OBJECTID ||
6759 key->objectid == BTRFS_FREE_SPACE_OBJECTID)
6760 goto out;
6761
6762 if (key->type == BTRFS_INODE_ITEM_KEY) {
6763 ret = changed_inode(sctx, result);
6764 } else if (!sctx->ignore_cur_inode) {
6765 if (key->type == BTRFS_INODE_REF_KEY ||
6766 key->type == BTRFS_INODE_EXTREF_KEY)
6767 ret = changed_ref(sctx, result);
6768 else if (key->type == BTRFS_XATTR_ITEM_KEY)
6769 ret = changed_xattr(sctx, result);
6770 else if (key->type == BTRFS_EXTENT_DATA_KEY)
6771 ret = changed_extent(sctx, result);
6772 }
6773
6774out:
6775 return ret;
6776}
6777
6778static int full_send_tree(struct send_ctx *sctx)
6779{
6780 int ret;
6781 struct btrfs_root *send_root = sctx->send_root;
6782 struct btrfs_key key;
6783 struct btrfs_path *path;
6784 struct extent_buffer *eb;
6785 int slot;
6786
6787 path = alloc_path_for_send();
6788 if (!path)
6789 return -ENOMEM;
6790
6791 key.objectid = BTRFS_FIRST_FREE_OBJECTID;
6792 key.type = BTRFS_INODE_ITEM_KEY;
6793 key.offset = 0;
6794
6795 ret = btrfs_search_slot_for_read(send_root, &key, path, 1, 0);
6796 if (ret < 0)
6797 goto out;
6798 if (ret)
6799 goto out_finish;
6800
6801 while (1) {
6802 eb = path->nodes[0];
6803 slot = path->slots[0];
6804 btrfs_item_key_to_cpu(eb, &key, slot);
6805
6806 ret = changed_cb(path, NULL, &key,
6807 BTRFS_COMPARE_TREE_NEW, sctx);
6808 if (ret < 0)
6809 goto out;
6810
6811 ret = btrfs_next_item(send_root, path);
6812 if (ret < 0)
6813 goto out;
6814 if (ret) {
6815 ret = 0;
6816 break;
6817 }
6818 }
6819
6820out_finish:
6821 ret = finish_inode_if_needed(sctx, 1);
6822
6823out:
6824 btrfs_free_path(path);
6825 return ret;
6826}
6827
6828static int tree_move_down(struct btrfs_path *path, int *level)
6829{
6830 struct extent_buffer *eb;
6831
6832 BUG_ON(*level == 0);
6833 eb = btrfs_read_node_slot(path->nodes[*level], path->slots[*level]);
6834 if (IS_ERR(eb))
6835 return PTR_ERR(eb);
6836
6837 path->nodes[*level - 1] = eb;
6838 path->slots[*level - 1] = 0;
6839 (*level)--;
6840 return 0;
6841}
6842
6843static int tree_move_next_or_upnext(struct btrfs_path *path,
6844 int *level, int root_level)
6845{
6846 int ret = 0;
6847 int nritems;
6848 nritems = btrfs_header_nritems(path->nodes[*level]);
6849
6850 path->slots[*level]++;
6851
6852 while (path->slots[*level] >= nritems) {
6853 if (*level == root_level)
6854 return -1;
6855
6856 /* move upnext */
6857 path->slots[*level] = 0;
6858 free_extent_buffer(path->nodes[*level]);
6859 path->nodes[*level] = NULL;
6860 (*level)++;
6861 path->slots[*level]++;
6862
6863 nritems = btrfs_header_nritems(path->nodes[*level]);
6864 ret = 1;
6865 }
6866 return ret;
6867}
6868
6869/*
6870 * Returns 1 if it had to move up and next. 0 is returned if it moved only next
6871 * or down.
6872 */
6873static int tree_advance(struct btrfs_path *path,
6874 int *level, int root_level,
6875 int allow_down,
6876 struct btrfs_key *key)
6877{
6878 int ret;
6879
6880 if (*level == 0 || !allow_down) {
6881 ret = tree_move_next_or_upnext(path, level, root_level);
6882 } else {
6883 ret = tree_move_down(path, level);
6884 }
6885 if (ret >= 0) {
6886 if (*level == 0)
6887 btrfs_item_key_to_cpu(path->nodes[*level], key,
6888 path->slots[*level]);
6889 else
6890 btrfs_node_key_to_cpu(path->nodes[*level], key,
6891 path->slots[*level]);
6892 }
6893 return ret;
6894}
6895
6896static int tree_compare_item(struct btrfs_path *left_path,
6897 struct btrfs_path *right_path,
6898 char *tmp_buf)
6899{
6900 int cmp;
6901 int len1, len2;
6902 unsigned long off1, off2;
6903
6904 len1 = btrfs_item_size_nr(left_path->nodes[0], left_path->slots[0]);
6905 len2 = btrfs_item_size_nr(right_path->nodes[0], right_path->slots[0]);
6906 if (len1 != len2)
6907 return 1;
6908
6909 off1 = btrfs_item_ptr_offset(left_path->nodes[0], left_path->slots[0]);
6910 off2 = btrfs_item_ptr_offset(right_path->nodes[0],
6911 right_path->slots[0]);
6912
6913 read_extent_buffer(left_path->nodes[0], tmp_buf, off1, len1);
6914
6915 cmp = memcmp_extent_buffer(right_path->nodes[0], tmp_buf, off2, len1);
6916 if (cmp)
6917 return 1;
6918 return 0;
6919}
6920
6921/*
6922 * This function compares two trees and calls the provided callback for
6923 * every changed/new/deleted item it finds.
6924 * If shared tree blocks are encountered, whole subtrees are skipped, making
6925 * the compare pretty fast on snapshotted subvolumes.
6926 *
6927 * This currently works on commit roots only. As commit roots are read only,
6928 * we don't do any locking. The commit roots are protected with transactions.
6929 * Transactions are ended and rejoined when a commit is tried in between.
6930 *
6931 * This function checks for modifications done to the trees while comparing.
6932 * If it detects a change, it aborts immediately.
6933 */
6934static int btrfs_compare_trees(struct btrfs_root *left_root,
6935 struct btrfs_root *right_root,
6936 btrfs_changed_cb_t changed_cb, void *ctx)
6937{
6938 struct btrfs_fs_info *fs_info = left_root->fs_info;
6939 int ret;
6940 int cmp;
6941 struct btrfs_path *left_path = NULL;
6942 struct btrfs_path *right_path = NULL;
6943 struct btrfs_key left_key;
6944 struct btrfs_key right_key;
6945 char *tmp_buf = NULL;
6946 int left_root_level;
6947 int right_root_level;
6948 int left_level;
6949 int right_level;
6950 int left_end_reached;
6951 int right_end_reached;
6952 int advance_left;
6953 int advance_right;
6954 u64 left_blockptr;
6955 u64 right_blockptr;
6956 u64 left_gen;
6957 u64 right_gen;
6958
6959 left_path = btrfs_alloc_path();
6960 if (!left_path) {
6961 ret = -ENOMEM;
6962 goto out;
6963 }
6964 right_path = btrfs_alloc_path();
6965 if (!right_path) {
6966 ret = -ENOMEM;
6967 goto out;
6968 }
6969
6970 tmp_buf = kvmalloc(fs_info->nodesize, GFP_KERNEL);
6971 if (!tmp_buf) {
6972 ret = -ENOMEM;
6973 goto out;
6974 }
6975
6976 left_path->search_commit_root = 1;
6977 left_path->skip_locking = 1;
6978 right_path->search_commit_root = 1;
6979 right_path->skip_locking = 1;
6980
6981 /*
6982 * Strategy: Go to the first items of both trees. Then do
6983 *
6984 * If both trees are at level 0
6985 * Compare keys of current items
6986 * If left < right treat left item as new, advance left tree
6987 * and repeat
6988 * If left > right treat right item as deleted, advance right tree
6989 * and repeat
6990 * If left == right do deep compare of items, treat as changed if
6991 * needed, advance both trees and repeat
6992 * If both trees are at the same level but not at level 0
6993 * Compare keys of current nodes/leafs
6994 * If left < right advance left tree and repeat
6995 * If left > right advance right tree and repeat
6996 * If left == right compare blockptrs of the next nodes/leafs
6997 * If they match advance both trees but stay at the same level
6998 * and repeat
6999 * If they don't match advance both trees while allowing to go
7000 * deeper and repeat
7001 * If tree levels are different
7002 * Advance the tree that needs it and repeat
7003 *
7004 * Advancing a tree means:
7005 * If we are at level 0, try to go to the next slot. If that's not
7006 * possible, go one level up and repeat. Stop when we found a level
7007 * where we could go to the next slot. We may at this point be on a
7008 * node or a leaf.
7009 *
7010 * If we are not at level 0 and not on shared tree blocks, go one
7011 * level deeper.
7012 *
7013 * If we are not at level 0 and on shared tree blocks, go one slot to
7014 * the right if possible or go up and right.
7015 */
7016
7017 down_read(&fs_info->commit_root_sem);
7018 left_level = btrfs_header_level(left_root->commit_root);
7019 left_root_level = left_level;
7020 left_path->nodes[left_level] =
7021 btrfs_clone_extent_buffer(left_root->commit_root);
7022 if (!left_path->nodes[left_level]) {
7023 up_read(&fs_info->commit_root_sem);
7024 ret = -ENOMEM;
7025 goto out;
7026 }
7027
7028 right_level = btrfs_header_level(right_root->commit_root);
7029 right_root_level = right_level;
7030 right_path->nodes[right_level] =
7031 btrfs_clone_extent_buffer(right_root->commit_root);
7032 if (!right_path->nodes[right_level]) {
7033 up_read(&fs_info->commit_root_sem);
7034 ret = -ENOMEM;
7035 goto out;
7036 }
7037 up_read(&fs_info->commit_root_sem);
7038
7039 if (left_level == 0)
7040 btrfs_item_key_to_cpu(left_path->nodes[left_level],
7041 &left_key, left_path->slots[left_level]);
7042 else
7043 btrfs_node_key_to_cpu(left_path->nodes[left_level],
7044 &left_key, left_path->slots[left_level]);
7045 if (right_level == 0)
7046 btrfs_item_key_to_cpu(right_path->nodes[right_level],
7047 &right_key, right_path->slots[right_level]);
7048 else
7049 btrfs_node_key_to_cpu(right_path->nodes[right_level],
7050 &right_key, right_path->slots[right_level]);
7051
7052 left_end_reached = right_end_reached = 0;
7053 advance_left = advance_right = 0;
7054
7055 while (1) {
7056 cond_resched();
7057 if (advance_left && !left_end_reached) {
7058 ret = tree_advance(left_path, &left_level,
7059 left_root_level,
7060 advance_left != ADVANCE_ONLY_NEXT,
7061 &left_key);
7062 if (ret == -1)
7063 left_end_reached = ADVANCE;
7064 else if (ret < 0)
7065 goto out;
7066 advance_left = 0;
7067 }
7068 if (advance_right && !right_end_reached) {
7069 ret = tree_advance(right_path, &right_level,
7070 right_root_level,
7071 advance_right != ADVANCE_ONLY_NEXT,
7072 &right_key);
7073 if (ret == -1)
7074 right_end_reached = ADVANCE;
7075 else if (ret < 0)
7076 goto out;
7077 advance_right = 0;
7078 }
7079
7080 if (left_end_reached && right_end_reached) {
7081 ret = 0;
7082 goto out;
7083 } else if (left_end_reached) {
7084 if (right_level == 0) {
7085 ret = changed_cb(left_path, right_path,
7086 &right_key,
7087 BTRFS_COMPARE_TREE_DELETED,
7088 ctx);
7089 if (ret < 0)
7090 goto out;
7091 }
7092 advance_right = ADVANCE;
7093 continue;
7094 } else if (right_end_reached) {
7095 if (left_level == 0) {
7096 ret = changed_cb(left_path, right_path,
7097 &left_key,
7098 BTRFS_COMPARE_TREE_NEW,
7099 ctx);
7100 if (ret < 0)
7101 goto out;
7102 }
7103 advance_left = ADVANCE;
7104 continue;
7105 }
7106
7107 if (left_level == 0 && right_level == 0) {
7108 cmp = btrfs_comp_cpu_keys(&left_key, &right_key);
7109 if (cmp < 0) {
7110 ret = changed_cb(left_path, right_path,
7111 &left_key,
7112 BTRFS_COMPARE_TREE_NEW,
7113 ctx);
7114 if (ret < 0)
7115 goto out;
7116 advance_left = ADVANCE;
7117 } else if (cmp > 0) {
7118 ret = changed_cb(left_path, right_path,
7119 &right_key,
7120 BTRFS_COMPARE_TREE_DELETED,
7121 ctx);
7122 if (ret < 0)
7123 goto out;
7124 advance_right = ADVANCE;
7125 } else {
7126 enum btrfs_compare_tree_result result;
7127
7128 WARN_ON(!extent_buffer_uptodate(left_path->nodes[0]));
7129 ret = tree_compare_item(left_path, right_path,
7130 tmp_buf);
7131 if (ret)
7132 result = BTRFS_COMPARE_TREE_CHANGED;
7133 else
7134 result = BTRFS_COMPARE_TREE_SAME;
7135 ret = changed_cb(left_path, right_path,
7136 &left_key, result, ctx);
7137 if (ret < 0)
7138 goto out;
7139 advance_left = ADVANCE;
7140 advance_right = ADVANCE;
7141 }
7142 } else if (left_level == right_level) {
7143 cmp = btrfs_comp_cpu_keys(&left_key, &right_key);
7144 if (cmp < 0) {
7145 advance_left = ADVANCE;
7146 } else if (cmp > 0) {
7147 advance_right = ADVANCE;
7148 } else {
7149 left_blockptr = btrfs_node_blockptr(
7150 left_path->nodes[left_level],
7151 left_path->slots[left_level]);
7152 right_blockptr = btrfs_node_blockptr(
7153 right_path->nodes[right_level],
7154 right_path->slots[right_level]);
7155 left_gen = btrfs_node_ptr_generation(
7156 left_path->nodes[left_level],
7157 left_path->slots[left_level]);
7158 right_gen = btrfs_node_ptr_generation(
7159 right_path->nodes[right_level],
7160 right_path->slots[right_level]);
7161 if (left_blockptr == right_blockptr &&
7162 left_gen == right_gen) {
7163 /*
7164 * As we're on a shared block, don't
7165 * allow to go deeper.
7166 */
7167 advance_left = ADVANCE_ONLY_NEXT;
7168 advance_right = ADVANCE_ONLY_NEXT;
7169 } else {
7170 advance_left = ADVANCE;
7171 advance_right = ADVANCE;
7172 }
7173 }
7174 } else if (left_level < right_level) {
7175 advance_right = ADVANCE;
7176 } else {
7177 advance_left = ADVANCE;
7178 }
7179 }
7180
7181out:
7182 btrfs_free_path(left_path);
7183 btrfs_free_path(right_path);
7184 kvfree(tmp_buf);
7185 return ret;
7186}
7187
7188static int send_subvol(struct send_ctx *sctx)
7189{
7190 int ret;
7191
7192 if (!(sctx->flags & BTRFS_SEND_FLAG_OMIT_STREAM_HEADER)) {
7193 ret = send_header(sctx);
7194 if (ret < 0)
7195 goto out;
7196 }
7197
7198 ret = send_subvol_begin(sctx);
7199 if (ret < 0)
7200 goto out;
7201
7202 if (sctx->parent_root) {
7203 ret = btrfs_compare_trees(sctx->send_root, sctx->parent_root,
7204 changed_cb, sctx);
7205 if (ret < 0)
7206 goto out;
7207 ret = finish_inode_if_needed(sctx, 1);
7208 if (ret < 0)
7209 goto out;
7210 } else {
7211 ret = full_send_tree(sctx);
7212 if (ret < 0)
7213 goto out;
7214 }
7215
7216out:
7217 free_recorded_refs(sctx);
7218 return ret;
7219}
7220
7221/*
7222 * If orphan cleanup did remove any orphans from a root, it means the tree
7223 * was modified and therefore the commit root is not the same as the current
7224 * root anymore. This is a problem, because send uses the commit root and
7225 * therefore can see inode items that don't exist in the current root anymore,
7226 * and for example make calls to btrfs_iget, which will do tree lookups based
7227 * on the current root and not on the commit root. Those lookups will fail,
7228 * returning a -ESTALE error, and making send fail with that error. So make
7229 * sure a send does not see any orphans we have just removed, and that it will
7230 * see the same inodes regardless of whether a transaction commit happened
7231 * before it started (meaning that the commit root will be the same as the
7232 * current root) or not.
7233 */
7234static int ensure_commit_roots_uptodate(struct send_ctx *sctx)
7235{
7236 int i;
7237 struct btrfs_trans_handle *trans = NULL;
7238
7239again:
7240 if (sctx->parent_root &&
7241 sctx->parent_root->node != sctx->parent_root->commit_root)
7242 goto commit_trans;
7243
7244 for (i = 0; i < sctx->clone_roots_cnt; i++)
7245 if (sctx->clone_roots[i].root->node !=
7246 sctx->clone_roots[i].root->commit_root)
7247 goto commit_trans;
7248
7249 if (trans)
7250 return btrfs_end_transaction(trans);
7251
7252 return 0;
7253
7254commit_trans:
7255 /* Use any root, all fs roots will get their commit roots updated. */
7256 if (!trans) {
7257 trans = btrfs_join_transaction(sctx->send_root);
7258 if (IS_ERR(trans))
7259 return PTR_ERR(trans);
7260 goto again;
7261 }
7262
7263 return btrfs_commit_transaction(trans);
7264}
7265
7266/*
7267 * Make sure any existing dellaloc is flushed for any root used by a send
7268 * operation so that we do not miss any data and we do not race with writeback
7269 * finishing and changing a tree while send is using the tree. This could
7270 * happen if a subvolume is in RW mode, has delalloc, is turned to RO mode and
7271 * a send operation then uses the subvolume.
7272 * After flushing delalloc ensure_commit_roots_uptodate() must be called.
7273 */
7274static int flush_delalloc_roots(struct send_ctx *sctx)
7275{
7276 struct btrfs_root *root = sctx->parent_root;
7277 int ret;
7278 int i;
7279
7280 if (root) {
7281 ret = btrfs_start_delalloc_snapshot(root);
7282 if (ret)
7283 return ret;
7284 btrfs_wait_ordered_extents(root, U64_MAX, 0, U64_MAX);
7285 }
7286
7287 for (i = 0; i < sctx->clone_roots_cnt; i++) {
7288 root = sctx->clone_roots[i].root;
7289 ret = btrfs_start_delalloc_snapshot(root);
7290 if (ret)
7291 return ret;
7292 btrfs_wait_ordered_extents(root, U64_MAX, 0, U64_MAX);
7293 }
7294
7295 return 0;
7296}
7297
7298static void btrfs_root_dec_send_in_progress(struct btrfs_root* root)
7299{
7300 spin_lock(&root->root_item_lock);
7301 root->send_in_progress--;
7302 /*
7303 * Not much left to do, we don't know why it's unbalanced and
7304 * can't blindly reset it to 0.
7305 */
7306 if (root->send_in_progress < 0)
7307 btrfs_err(root->fs_info,
7308 "send_in_progress unbalanced %d root %llu",
7309 root->send_in_progress, root->root_key.objectid);
7310 spin_unlock(&root->root_item_lock);
7311}
7312
7313static void dedupe_in_progress_warn(const struct btrfs_root *root)
7314{
7315 btrfs_warn_rl(root->fs_info,
7316"cannot use root %llu for send while deduplications on it are in progress (%d in progress)",
7317 root->root_key.objectid, root->dedupe_in_progress);
7318}
7319
7320long btrfs_ioctl_send(struct file *mnt_file, struct btrfs_ioctl_send_args *arg)
7321{
7322 int ret = 0;
7323 struct btrfs_root *send_root = BTRFS_I(file_inode(mnt_file))->root;
7324 struct btrfs_fs_info *fs_info = send_root->fs_info;
7325 struct btrfs_root *clone_root;
7326 struct btrfs_key key;
7327 struct send_ctx *sctx = NULL;
7328 u32 i;
7329 u64 *clone_sources_tmp = NULL;
7330 int clone_sources_to_rollback = 0;
7331 unsigned alloc_size;
7332 int sort_clone_roots = 0;
7333 int index;
7334
7335 if (!capable(CAP_SYS_ADMIN))
7336 return -EPERM;
7337
7338 /*
7339 * The subvolume must remain read-only during send, protect against
7340 * making it RW. This also protects against deletion.
7341 */
7342 spin_lock(&send_root->root_item_lock);
7343 if (btrfs_root_readonly(send_root) && send_root->dedupe_in_progress) {
7344 dedupe_in_progress_warn(send_root);
7345 spin_unlock(&send_root->root_item_lock);
7346 return -EAGAIN;
7347 }
7348 send_root->send_in_progress++;
7349 spin_unlock(&send_root->root_item_lock);
7350
7351 /*
7352 * Userspace tools do the checks and warn the user if it's
7353 * not RO.
7354 */
7355 if (!btrfs_root_readonly(send_root)) {
7356 ret = -EPERM;
7357 goto out;
7358 }
7359
7360 /*
7361 * Check that we don't overflow at later allocations, we request
7362 * clone_sources_count + 1 items, and compare to unsigned long inside
7363 * access_ok. Also set an upper limit for allocation size so this can't
7364 * easily exhaust memory. Max number of clone sources is about 200K.
7365 */
7366 if (arg->clone_sources_count > SZ_8M / sizeof(struct clone_root)) {
7367 ret = -EINVAL;
7368 goto out;
7369 }
7370
7371 if (!access_ok(arg->clone_sources,
7372 sizeof(*arg->clone_sources) *
7373 arg->clone_sources_count)) {
7374 ret = -EFAULT;
7375 goto out;
7376 }
7377
7378 if (arg->flags & ~BTRFS_SEND_FLAG_MASK) {
7379 ret = -EOPNOTSUPP;
7380 goto out;
7381 }
7382
7383 sctx = kzalloc(sizeof(struct send_ctx), GFP_KERNEL);
7384 if (!sctx) {
7385 ret = -ENOMEM;
7386 goto out;
7387 }
7388
7389 INIT_LIST_HEAD(&sctx->new_refs);
7390 INIT_LIST_HEAD(&sctx->deleted_refs);
7391 INIT_RADIX_TREE(&sctx->name_cache, GFP_KERNEL);
7392 INIT_LIST_HEAD(&sctx->name_cache_list);
7393
7394 sctx->flags = arg->flags;
7395
7396 sctx->send_filp = fget(arg->send_fd);
7397 if (!sctx->send_filp || !(sctx->send_filp->f_mode & FMODE_WRITE)) {
7398 ret = -EBADF;
7399 goto out;
7400 }
7401
7402 sctx->send_root = send_root;
7403 /*
7404 * Unlikely but possible, if the subvolume is marked for deletion but
7405 * is slow to remove the directory entry, send can still be started
7406 */
7407 if (btrfs_root_dead(sctx->send_root)) {
7408 ret = -EPERM;
7409 goto out;
7410 }
7411
7412 sctx->clone_roots_cnt = arg->clone_sources_count;
7413
7414 sctx->send_max_size = BTRFS_SEND_BUF_SIZE;
7415 sctx->send_buf = kvmalloc(sctx->send_max_size, GFP_KERNEL);
7416 if (!sctx->send_buf) {
7417 ret = -ENOMEM;
7418 goto out;
7419 }
7420
7421 sctx->read_buf = kvmalloc(BTRFS_SEND_READ_SIZE, GFP_KERNEL);
7422 if (!sctx->read_buf) {
7423 ret = -ENOMEM;
7424 goto out;
7425 }
7426
7427 sctx->pending_dir_moves = RB_ROOT;
7428 sctx->waiting_dir_moves = RB_ROOT;
7429 sctx->orphan_dirs = RB_ROOT;
7430
7431 alloc_size = sizeof(struct clone_root) * (arg->clone_sources_count + 1);
7432
7433 sctx->clone_roots = kvzalloc(alloc_size, GFP_KERNEL);
7434 if (!sctx->clone_roots) {
7435 ret = -ENOMEM;
7436 goto out;
7437 }
7438
7439 alloc_size = arg->clone_sources_count * sizeof(*arg->clone_sources);
7440
7441 if (arg->clone_sources_count) {
7442 clone_sources_tmp = kvmalloc(alloc_size, GFP_KERNEL);
7443 if (!clone_sources_tmp) {
7444 ret = -ENOMEM;
7445 goto out;
7446 }
7447
7448 ret = copy_from_user(clone_sources_tmp, arg->clone_sources,
7449 alloc_size);
7450 if (ret) {
7451 ret = -EFAULT;
7452 goto out;
7453 }
7454
7455 for (i = 0; i < arg->clone_sources_count; i++) {
7456 key.objectid = clone_sources_tmp[i];
7457 key.type = BTRFS_ROOT_ITEM_KEY;
7458 key.offset = (u64)-1;
7459
7460 index = srcu_read_lock(&fs_info->subvol_srcu);
7461
7462 clone_root = btrfs_read_fs_root_no_name(fs_info, &key);
7463 if (IS_ERR(clone_root)) {
7464 srcu_read_unlock(&fs_info->subvol_srcu, index);
7465 ret = PTR_ERR(clone_root);
7466 goto out;
7467 }
7468 spin_lock(&clone_root->root_item_lock);
7469 if (!btrfs_root_readonly(clone_root) ||
7470 btrfs_root_dead(clone_root)) {
7471 spin_unlock(&clone_root->root_item_lock);
7472 srcu_read_unlock(&fs_info->subvol_srcu, index);
7473 ret = -EPERM;
7474 goto out;
7475 }
7476 if (clone_root->dedupe_in_progress) {
7477 dedupe_in_progress_warn(clone_root);
7478 spin_unlock(&clone_root->root_item_lock);
7479 srcu_read_unlock(&fs_info->subvol_srcu, index);
7480 ret = -EAGAIN;
7481 goto out;
7482 }
7483 clone_root->send_in_progress++;
7484 spin_unlock(&clone_root->root_item_lock);
7485 srcu_read_unlock(&fs_info->subvol_srcu, index);
7486
7487 sctx->clone_roots[i].root = clone_root;
7488 clone_sources_to_rollback = i + 1;
7489 }
7490 kvfree(clone_sources_tmp);
7491 clone_sources_tmp = NULL;
7492 }
7493
7494 if (arg->parent_root) {
7495 key.objectid = arg->parent_root;
7496 key.type = BTRFS_ROOT_ITEM_KEY;
7497 key.offset = (u64)-1;
7498
7499 index = srcu_read_lock(&fs_info->subvol_srcu);
7500
7501 sctx->parent_root = btrfs_read_fs_root_no_name(fs_info, &key);
7502 if (IS_ERR(sctx->parent_root)) {
7503 srcu_read_unlock(&fs_info->subvol_srcu, index);
7504 ret = PTR_ERR(sctx->parent_root);
7505 goto out;
7506 }
7507
7508 spin_lock(&sctx->parent_root->root_item_lock);
7509 sctx->parent_root->send_in_progress++;
7510 if (!btrfs_root_readonly(sctx->parent_root) ||
7511 btrfs_root_dead(sctx->parent_root)) {
7512 spin_unlock(&sctx->parent_root->root_item_lock);
7513 srcu_read_unlock(&fs_info->subvol_srcu, index);
7514 ret = -EPERM;
7515 goto out;
7516 }
7517 if (sctx->parent_root->dedupe_in_progress) {
7518 dedupe_in_progress_warn(sctx->parent_root);
7519 spin_unlock(&sctx->parent_root->root_item_lock);
7520 srcu_read_unlock(&fs_info->subvol_srcu, index);
7521 ret = -EAGAIN;
7522 goto out;
7523 }
7524 spin_unlock(&sctx->parent_root->root_item_lock);
7525
7526 srcu_read_unlock(&fs_info->subvol_srcu, index);
7527 }
7528
7529 /*
7530 * Clones from send_root are allowed, but only if the clone source
7531 * is behind the current send position. This is checked while searching
7532 * for possible clone sources.
7533 */
7534 sctx->clone_roots[sctx->clone_roots_cnt++].root = sctx->send_root;
7535
7536 /* We do a bsearch later */
7537 sort(sctx->clone_roots, sctx->clone_roots_cnt,
7538 sizeof(*sctx->clone_roots), __clone_root_cmp_sort,
7539 NULL);
7540 sort_clone_roots = 1;
7541
7542 ret = flush_delalloc_roots(sctx);
7543 if (ret)
7544 goto out;
7545
7546 ret = ensure_commit_roots_uptodate(sctx);
7547 if (ret)
7548 goto out;
7549
7550 mutex_lock(&fs_info->balance_mutex);
7551 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
7552 mutex_unlock(&fs_info->balance_mutex);
7553 btrfs_warn_rl(fs_info,
7554 "cannot run send because a balance operation is in progress");
7555 ret = -EAGAIN;
7556 goto out;
7557 }
7558 fs_info->send_in_progress++;
7559 mutex_unlock(&fs_info->balance_mutex);
7560
7561 current->journal_info = BTRFS_SEND_TRANS_STUB;
7562 ret = send_subvol(sctx);
7563 current->journal_info = NULL;
7564 mutex_lock(&fs_info->balance_mutex);
7565 fs_info->send_in_progress--;
7566 mutex_unlock(&fs_info->balance_mutex);
7567 if (ret < 0)
7568 goto out;
7569
7570 if (!(sctx->flags & BTRFS_SEND_FLAG_OMIT_END_CMD)) {
7571 ret = begin_cmd(sctx, BTRFS_SEND_C_END);
7572 if (ret < 0)
7573 goto out;
7574 ret = send_cmd(sctx);
7575 if (ret < 0)
7576 goto out;
7577 }
7578
7579out:
7580 WARN_ON(sctx && !ret && !RB_EMPTY_ROOT(&sctx->pending_dir_moves));
7581 while (sctx && !RB_EMPTY_ROOT(&sctx->pending_dir_moves)) {
7582 struct rb_node *n;
7583 struct pending_dir_move *pm;
7584
7585 n = rb_first(&sctx->pending_dir_moves);
7586 pm = rb_entry(n, struct pending_dir_move, node);
7587 while (!list_empty(&pm->list)) {
7588 struct pending_dir_move *pm2;
7589
7590 pm2 = list_first_entry(&pm->list,
7591 struct pending_dir_move, list);
7592 free_pending_move(sctx, pm2);
7593 }
7594 free_pending_move(sctx, pm);
7595 }
7596
7597 WARN_ON(sctx && !ret && !RB_EMPTY_ROOT(&sctx->waiting_dir_moves));
7598 while (sctx && !RB_EMPTY_ROOT(&sctx->waiting_dir_moves)) {
7599 struct rb_node *n;
7600 struct waiting_dir_move *dm;
7601
7602 n = rb_first(&sctx->waiting_dir_moves);
7603 dm = rb_entry(n, struct waiting_dir_move, node);
7604 rb_erase(&dm->node, &sctx->waiting_dir_moves);
7605 kfree(dm);
7606 }
7607
7608 WARN_ON(sctx && !ret && !RB_EMPTY_ROOT(&sctx->orphan_dirs));
7609 while (sctx && !RB_EMPTY_ROOT(&sctx->orphan_dirs)) {
7610 struct rb_node *n;
7611 struct orphan_dir_info *odi;
7612
7613 n = rb_first(&sctx->orphan_dirs);
7614 odi = rb_entry(n, struct orphan_dir_info, node);
7615 free_orphan_dir_info(sctx, odi);
7616 }
7617
7618 if (sort_clone_roots) {
7619 for (i = 0; i < sctx->clone_roots_cnt; i++)
7620 btrfs_root_dec_send_in_progress(
7621 sctx->clone_roots[i].root);
7622 } else {
7623 for (i = 0; sctx && i < clone_sources_to_rollback; i++)
7624 btrfs_root_dec_send_in_progress(
7625 sctx->clone_roots[i].root);
7626
7627 btrfs_root_dec_send_in_progress(send_root);
7628 }
7629 if (sctx && !IS_ERR_OR_NULL(sctx->parent_root))
7630 btrfs_root_dec_send_in_progress(sctx->parent_root);
7631
7632 kvfree(clone_sources_tmp);
7633
7634 if (sctx) {
7635 if (sctx->send_filp)
7636 fput(sctx->send_filp);
7637
7638 kvfree(sctx->clone_roots);
7639 kvfree(sctx->send_buf);
7640 kvfree(sctx->read_buf);
7641
7642 name_cache_free(sctx);
7643
7644 kfree(sctx);
7645 }
7646
7647 return ret;
7648}