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