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