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