GNU Linux-libre 4.19.264-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                                 btrfs_err(fs_info,
4960                         "send: IO error at offset %llu for inode %llu root %llu",
4961                                         page_offset(page), sctx->cur_ino,
4962                                         sctx->send_root->root_key.objectid);
4963                                 put_page(page);
4964                                 ret = -EIO;
4965                                 break;
4966                         }
4967                 }
4968
4969                 addr = kmap(page);
4970                 memcpy(sctx->read_buf + ret, addr + pg_offset, cur_len);
4971                 kunmap(page);
4972                 unlock_page(page);
4973                 put_page(page);
4974                 index++;
4975                 pg_offset = 0;
4976                 len -= cur_len;
4977                 ret += cur_len;
4978         }
4979 out:
4980         iput(inode);
4981         return ret;
4982 }
4983
4984 /*
4985  * Read some bytes from the current inode/file and send a write command to
4986  * user space.
4987  */
4988 static int send_write(struct send_ctx *sctx, u64 offset, u32 len)
4989 {
4990         struct btrfs_fs_info *fs_info = sctx->send_root->fs_info;
4991         int ret = 0;
4992         struct fs_path *p;
4993         ssize_t num_read = 0;
4994
4995         p = fs_path_alloc();
4996         if (!p)
4997                 return -ENOMEM;
4998
4999         btrfs_debug(fs_info, "send_write offset=%llu, len=%d", offset, len);
5000
5001         num_read = fill_read_buf(sctx, offset, len);
5002         if (num_read <= 0) {
5003                 if (num_read < 0)
5004                         ret = num_read;
5005                 goto out;
5006         }
5007
5008         ret = begin_cmd(sctx, BTRFS_SEND_C_WRITE);
5009         if (ret < 0)
5010                 goto out;
5011
5012         ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
5013         if (ret < 0)
5014                 goto out;
5015
5016         TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
5017         TLV_PUT_U64(sctx, BTRFS_SEND_A_FILE_OFFSET, offset);
5018         TLV_PUT(sctx, BTRFS_SEND_A_DATA, sctx->read_buf, num_read);
5019
5020         ret = send_cmd(sctx);
5021
5022 tlv_put_failure:
5023 out:
5024         fs_path_free(p);
5025         if (ret < 0)
5026                 return ret;
5027         return num_read;
5028 }
5029
5030 /*
5031  * Send a clone command to user space.
5032  */
5033 static int send_clone(struct send_ctx *sctx,
5034                       u64 offset, u32 len,
5035                       struct clone_root *clone_root)
5036 {
5037         int ret = 0;
5038         struct fs_path *p;
5039         u64 gen;
5040
5041         btrfs_debug(sctx->send_root->fs_info,
5042                     "send_clone offset=%llu, len=%d, clone_root=%llu, clone_inode=%llu, clone_offset=%llu",
5043                     offset, len, clone_root->root->objectid, clone_root->ino,
5044                     clone_root->offset);
5045
5046         p = fs_path_alloc();
5047         if (!p)
5048                 return -ENOMEM;
5049
5050         ret = begin_cmd(sctx, BTRFS_SEND_C_CLONE);
5051         if (ret < 0)
5052                 goto out;
5053
5054         ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
5055         if (ret < 0)
5056                 goto out;
5057
5058         TLV_PUT_U64(sctx, BTRFS_SEND_A_FILE_OFFSET, offset);
5059         TLV_PUT_U64(sctx, BTRFS_SEND_A_CLONE_LEN, len);
5060         TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
5061
5062         if (clone_root->root == sctx->send_root) {
5063                 ret = get_inode_info(sctx->send_root, clone_root->ino, NULL,
5064                                 &gen, NULL, NULL, NULL, NULL);
5065                 if (ret < 0)
5066                         goto out;
5067                 ret = get_cur_path(sctx, clone_root->ino, gen, p);
5068         } else {
5069                 ret = get_inode_path(clone_root->root, clone_root->ino, p);
5070         }
5071         if (ret < 0)
5072                 goto out;
5073
5074         /*
5075          * If the parent we're using has a received_uuid set then use that as
5076          * our clone source as that is what we will look for when doing a
5077          * receive.
5078          *
5079          * This covers the case that we create a snapshot off of a received
5080          * subvolume and then use that as the parent and try to receive on a
5081          * different host.
5082          */
5083         if (!btrfs_is_empty_uuid(clone_root->root->root_item.received_uuid))
5084                 TLV_PUT_UUID(sctx, BTRFS_SEND_A_CLONE_UUID,
5085                              clone_root->root->root_item.received_uuid);
5086         else
5087                 TLV_PUT_UUID(sctx, BTRFS_SEND_A_CLONE_UUID,
5088                              clone_root->root->root_item.uuid);
5089         TLV_PUT_U64(sctx, BTRFS_SEND_A_CLONE_CTRANSID,
5090                     le64_to_cpu(clone_root->root->root_item.ctransid));
5091         TLV_PUT_PATH(sctx, BTRFS_SEND_A_CLONE_PATH, p);
5092         TLV_PUT_U64(sctx, BTRFS_SEND_A_CLONE_OFFSET,
5093                         clone_root->offset);
5094
5095         ret = send_cmd(sctx);
5096
5097 tlv_put_failure:
5098 out:
5099         fs_path_free(p);
5100         return ret;
5101 }
5102
5103 /*
5104  * Send an update extent command to user space.
5105  */
5106 static int send_update_extent(struct send_ctx *sctx,
5107                               u64 offset, u32 len)
5108 {
5109         int ret = 0;
5110         struct fs_path *p;
5111
5112         p = fs_path_alloc();
5113         if (!p)
5114                 return -ENOMEM;
5115
5116         ret = begin_cmd(sctx, BTRFS_SEND_C_UPDATE_EXTENT);
5117         if (ret < 0)
5118                 goto out;
5119
5120         ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
5121         if (ret < 0)
5122                 goto out;
5123
5124         TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
5125         TLV_PUT_U64(sctx, BTRFS_SEND_A_FILE_OFFSET, offset);
5126         TLV_PUT_U64(sctx, BTRFS_SEND_A_SIZE, len);
5127
5128         ret = send_cmd(sctx);
5129
5130 tlv_put_failure:
5131 out:
5132         fs_path_free(p);
5133         return ret;
5134 }
5135
5136 static int send_hole(struct send_ctx *sctx, u64 end)
5137 {
5138         struct fs_path *p = NULL;
5139         u64 offset = sctx->cur_inode_last_extent;
5140         u64 len;
5141         int ret = 0;
5142
5143         /*
5144          * A hole that starts at EOF or beyond it. Since we do not yet support
5145          * fallocate (for extent preallocation and hole punching), sending a
5146          * write of zeroes starting at EOF or beyond would later require issuing
5147          * a truncate operation which would undo the write and achieve nothing.
5148          */
5149         if (offset >= sctx->cur_inode_size)
5150                 return 0;
5151
5152         /*
5153          * Don't go beyond the inode's i_size due to prealloc extents that start
5154          * after the i_size.
5155          */
5156         end = min_t(u64, end, sctx->cur_inode_size);
5157
5158         if (sctx->flags & BTRFS_SEND_FLAG_NO_FILE_DATA)
5159                 return send_update_extent(sctx, offset, end - offset);
5160
5161         p = fs_path_alloc();
5162         if (!p)
5163                 return -ENOMEM;
5164         ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
5165         if (ret < 0)
5166                 goto tlv_put_failure;
5167         memset(sctx->read_buf, 0, BTRFS_SEND_READ_SIZE);
5168         while (offset < end) {
5169                 len = min_t(u64, end - offset, BTRFS_SEND_READ_SIZE);
5170
5171                 ret = begin_cmd(sctx, BTRFS_SEND_C_WRITE);
5172                 if (ret < 0)
5173                         break;
5174                 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
5175                 TLV_PUT_U64(sctx, BTRFS_SEND_A_FILE_OFFSET, offset);
5176                 TLV_PUT(sctx, BTRFS_SEND_A_DATA, sctx->read_buf, len);
5177                 ret = send_cmd(sctx);
5178                 if (ret < 0)
5179                         break;
5180                 offset += len;
5181         }
5182         sctx->cur_inode_next_write_offset = offset;
5183 tlv_put_failure:
5184         fs_path_free(p);
5185         return ret;
5186 }
5187
5188 static int send_extent_data(struct send_ctx *sctx,
5189                             const u64 offset,
5190                             const u64 len)
5191 {
5192         u64 sent = 0;
5193
5194         if (sctx->flags & BTRFS_SEND_FLAG_NO_FILE_DATA)
5195                 return send_update_extent(sctx, offset, len);
5196
5197         while (sent < len) {
5198                 u64 size = len - sent;
5199                 int ret;
5200
5201                 if (size > BTRFS_SEND_READ_SIZE)
5202                         size = BTRFS_SEND_READ_SIZE;
5203                 ret = send_write(sctx, offset + sent, size);
5204                 if (ret < 0)
5205                         return ret;
5206                 if (!ret)
5207                         break;
5208                 sent += ret;
5209         }
5210         return 0;
5211 }
5212
5213 /*
5214  * Search for a capability xattr related to sctx->cur_ino. If the capability is
5215  * found, call send_set_xattr function to emit it.
5216  *
5217  * Return 0 if there isn't a capability, or when the capability was emitted
5218  * successfully, or < 0 if an error occurred.
5219  */
5220 static int send_capabilities(struct send_ctx *sctx)
5221 {
5222         struct fs_path *fspath = NULL;
5223         struct btrfs_path *path;
5224         struct btrfs_dir_item *di;
5225         struct extent_buffer *leaf;
5226         unsigned long data_ptr;
5227         char *buf = NULL;
5228         int buf_len;
5229         int ret = 0;
5230
5231         path = alloc_path_for_send();
5232         if (!path)
5233                 return -ENOMEM;
5234
5235         di = btrfs_lookup_xattr(NULL, sctx->send_root, path, sctx->cur_ino,
5236                                 XATTR_NAME_CAPS, strlen(XATTR_NAME_CAPS), 0);
5237         if (!di) {
5238                 /* There is no xattr for this inode */
5239                 goto out;
5240         } else if (IS_ERR(di)) {
5241                 ret = PTR_ERR(di);
5242                 goto out;
5243         }
5244
5245         leaf = path->nodes[0];
5246         buf_len = btrfs_dir_data_len(leaf, di);
5247
5248         fspath = fs_path_alloc();
5249         buf = kmalloc(buf_len, GFP_KERNEL);
5250         if (!fspath || !buf) {
5251                 ret = -ENOMEM;
5252                 goto out;
5253         }
5254
5255         ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, fspath);
5256         if (ret < 0)
5257                 goto out;
5258
5259         data_ptr = (unsigned long)(di + 1) + btrfs_dir_name_len(leaf, di);
5260         read_extent_buffer(leaf, buf, data_ptr, buf_len);
5261
5262         ret = send_set_xattr(sctx, fspath, XATTR_NAME_CAPS,
5263                         strlen(XATTR_NAME_CAPS), buf, buf_len);
5264 out:
5265         kfree(buf);
5266         fs_path_free(fspath);
5267         btrfs_free_path(path);
5268         return ret;
5269 }
5270
5271 static int clone_range(struct send_ctx *sctx,
5272                        struct clone_root *clone_root,
5273                        const u64 disk_byte,
5274                        u64 data_offset,
5275                        u64 offset,
5276                        u64 len)
5277 {
5278         struct btrfs_path *path;
5279         struct btrfs_key key;
5280         int ret;
5281
5282         /*
5283          * Prevent cloning from a zero offset with a length matching the sector
5284          * size because in some scenarios this will make the receiver fail.
5285          *
5286          * For example, if in the source filesystem the extent at offset 0
5287          * has a length of sectorsize and it was written using direct IO, then
5288          * it can never be an inline extent (even if compression is enabled).
5289          * Then this extent can be cloned in the original filesystem to a non
5290          * zero file offset, but it may not be possible to clone in the
5291          * destination filesystem because it can be inlined due to compression
5292          * on the destination filesystem (as the receiver's write operations are
5293          * always done using buffered IO). The same happens when the original
5294          * filesystem does not have compression enabled but the destination
5295          * filesystem has.
5296          */
5297         if (clone_root->offset == 0 &&
5298             len == sctx->send_root->fs_info->sectorsize)
5299                 return send_extent_data(sctx, offset, len);
5300
5301         path = alloc_path_for_send();
5302         if (!path)
5303                 return -ENOMEM;
5304
5305         /*
5306          * We can't send a clone operation for the entire range if we find
5307          * extent items in the respective range in the source file that
5308          * refer to different extents or if we find holes.
5309          * So check for that and do a mix of clone and regular write/copy
5310          * operations if needed.
5311          *
5312          * Example:
5313          *
5314          * mkfs.btrfs -f /dev/sda
5315          * mount /dev/sda /mnt
5316          * xfs_io -f -c "pwrite -S 0xaa 0K 100K" /mnt/foo
5317          * cp --reflink=always /mnt/foo /mnt/bar
5318          * xfs_io -c "pwrite -S 0xbb 50K 50K" /mnt/foo
5319          * btrfs subvolume snapshot -r /mnt /mnt/snap
5320          *
5321          * If when we send the snapshot and we are processing file bar (which
5322          * has a higher inode number than foo) we blindly send a clone operation
5323          * for the [0, 100K[ range from foo to bar, the receiver ends up getting
5324          * a file bar that matches the content of file foo - iow, doesn't match
5325          * the content from bar in the original filesystem.
5326          */
5327         key.objectid = clone_root->ino;
5328         key.type = BTRFS_EXTENT_DATA_KEY;
5329         key.offset = clone_root->offset;
5330         ret = btrfs_search_slot(NULL, clone_root->root, &key, path, 0, 0);
5331         if (ret < 0)
5332                 goto out;
5333         if (ret > 0 && path->slots[0] > 0) {
5334                 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0] - 1);
5335                 if (key.objectid == clone_root->ino &&
5336                     key.type == BTRFS_EXTENT_DATA_KEY)
5337                         path->slots[0]--;
5338         }
5339
5340         while (true) {
5341                 struct extent_buffer *leaf = path->nodes[0];
5342                 int slot = path->slots[0];
5343                 struct btrfs_file_extent_item *ei;
5344                 u8 type;
5345                 u64 ext_len;
5346                 u64 clone_len;
5347
5348                 if (slot >= btrfs_header_nritems(leaf)) {
5349                         ret = btrfs_next_leaf(clone_root->root, path);
5350                         if (ret < 0)
5351                                 goto out;
5352                         else if (ret > 0)
5353                                 break;
5354                         continue;
5355                 }
5356
5357                 btrfs_item_key_to_cpu(leaf, &key, slot);
5358
5359                 /*
5360                  * We might have an implicit trailing hole (NO_HOLES feature
5361                  * enabled). We deal with it after leaving this loop.
5362                  */
5363                 if (key.objectid != clone_root->ino ||
5364                     key.type != BTRFS_EXTENT_DATA_KEY)
5365                         break;
5366
5367                 ei = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
5368                 type = btrfs_file_extent_type(leaf, ei);
5369                 if (type == BTRFS_FILE_EXTENT_INLINE) {
5370                         ext_len = btrfs_file_extent_ram_bytes(leaf, ei);
5371                         ext_len = PAGE_ALIGN(ext_len);
5372                 } else {
5373                         ext_len = btrfs_file_extent_num_bytes(leaf, ei);
5374                 }
5375
5376                 if (key.offset + ext_len <= clone_root->offset)
5377                         goto next;
5378
5379                 if (key.offset > clone_root->offset) {
5380                         /* Implicit hole, NO_HOLES feature enabled. */
5381                         u64 hole_len = key.offset - clone_root->offset;
5382
5383                         if (hole_len > len)
5384                                 hole_len = len;
5385                         ret = send_extent_data(sctx, offset, hole_len);
5386                         if (ret < 0)
5387                                 goto out;
5388
5389                         len -= hole_len;
5390                         if (len == 0)
5391                                 break;
5392                         offset += hole_len;
5393                         clone_root->offset += hole_len;
5394                         data_offset += hole_len;
5395                 }
5396
5397                 if (key.offset >= clone_root->offset + len)
5398                         break;
5399
5400                 clone_len = min_t(u64, ext_len, len);
5401
5402                 if (btrfs_file_extent_disk_bytenr(leaf, ei) == disk_byte &&
5403                     btrfs_file_extent_offset(leaf, ei) == data_offset)
5404                         ret = send_clone(sctx, offset, clone_len, clone_root);
5405                 else
5406                         ret = send_extent_data(sctx, offset, clone_len);
5407
5408                 if (ret < 0)
5409                         goto out;
5410
5411                 len -= clone_len;
5412                 if (len == 0)
5413                         break;
5414                 offset += clone_len;
5415                 clone_root->offset += clone_len;
5416                 data_offset += clone_len;
5417 next:
5418                 path->slots[0]++;
5419         }
5420
5421         if (len > 0)
5422                 ret = send_extent_data(sctx, offset, len);
5423         else
5424                 ret = 0;
5425 out:
5426         btrfs_free_path(path);
5427         return ret;
5428 }
5429
5430 static int send_write_or_clone(struct send_ctx *sctx,
5431                                struct btrfs_path *path,
5432                                struct btrfs_key *key,
5433                                struct clone_root *clone_root)
5434 {
5435         int ret = 0;
5436         struct btrfs_file_extent_item *ei;
5437         u64 offset = key->offset;
5438         u64 len;
5439         u8 type;
5440         u64 bs = sctx->send_root->fs_info->sb->s_blocksize;
5441
5442         ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
5443                         struct btrfs_file_extent_item);
5444         type = btrfs_file_extent_type(path->nodes[0], ei);
5445         if (type == BTRFS_FILE_EXTENT_INLINE) {
5446                 len = btrfs_file_extent_ram_bytes(path->nodes[0], ei);
5447                 /*
5448                  * it is possible the inline item won't cover the whole page,
5449                  * but there may be items after this page.  Make
5450                  * sure to send the whole thing
5451                  */
5452                 len = PAGE_ALIGN(len);
5453         } else {
5454                 len = btrfs_file_extent_num_bytes(path->nodes[0], ei);
5455         }
5456
5457         if (offset >= sctx->cur_inode_size) {
5458                 ret = 0;
5459                 goto out;
5460         }
5461         if (offset + len > sctx->cur_inode_size)
5462                 len = sctx->cur_inode_size - offset;
5463         if (len == 0) {
5464                 ret = 0;
5465                 goto out;
5466         }
5467
5468         if (clone_root && IS_ALIGNED(offset + len, bs)) {
5469                 u64 disk_byte;
5470                 u64 data_offset;
5471
5472                 disk_byte = btrfs_file_extent_disk_bytenr(path->nodes[0], ei);
5473                 data_offset = btrfs_file_extent_offset(path->nodes[0], ei);
5474                 ret = clone_range(sctx, clone_root, disk_byte, data_offset,
5475                                   offset, len);
5476         } else {
5477                 ret = send_extent_data(sctx, offset, len);
5478         }
5479         sctx->cur_inode_next_write_offset = offset + len;
5480 out:
5481         return ret;
5482 }
5483
5484 static int is_extent_unchanged(struct send_ctx *sctx,
5485                                struct btrfs_path *left_path,
5486                                struct btrfs_key *ekey)
5487 {
5488         int ret = 0;
5489         struct btrfs_key key;
5490         struct btrfs_path *path = NULL;
5491         struct extent_buffer *eb;
5492         int slot;
5493         struct btrfs_key found_key;
5494         struct btrfs_file_extent_item *ei;
5495         u64 left_disknr;
5496         u64 right_disknr;
5497         u64 left_offset;
5498         u64 right_offset;
5499         u64 left_offset_fixed;
5500         u64 left_len;
5501         u64 right_len;
5502         u64 left_gen;
5503         u64 right_gen;
5504         u8 left_type;
5505         u8 right_type;
5506
5507         path = alloc_path_for_send();
5508         if (!path)
5509                 return -ENOMEM;
5510
5511         eb = left_path->nodes[0];
5512         slot = left_path->slots[0];
5513         ei = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
5514         left_type = btrfs_file_extent_type(eb, ei);
5515
5516         if (left_type != BTRFS_FILE_EXTENT_REG) {
5517                 ret = 0;
5518                 goto out;
5519         }
5520         left_disknr = btrfs_file_extent_disk_bytenr(eb, ei);
5521         left_len = btrfs_file_extent_num_bytes(eb, ei);
5522         left_offset = btrfs_file_extent_offset(eb, ei);
5523         left_gen = btrfs_file_extent_generation(eb, ei);
5524
5525         /*
5526          * Following comments will refer to these graphics. L is the left
5527          * extents which we are checking at the moment. 1-8 are the right
5528          * extents that we iterate.
5529          *
5530          *       |-----L-----|
5531          * |-1-|-2a-|-3-|-4-|-5-|-6-|
5532          *
5533          *       |-----L-----|
5534          * |--1--|-2b-|...(same as above)
5535          *
5536          * Alternative situation. Happens on files where extents got split.
5537          *       |-----L-----|
5538          * |-----------7-----------|-6-|
5539          *
5540          * Alternative situation. Happens on files which got larger.
5541          *       |-----L-----|
5542          * |-8-|
5543          * Nothing follows after 8.
5544          */
5545
5546         key.objectid = ekey->objectid;
5547         key.type = BTRFS_EXTENT_DATA_KEY;
5548         key.offset = ekey->offset;
5549         ret = btrfs_search_slot_for_read(sctx->parent_root, &key, path, 0, 0);
5550         if (ret < 0)
5551                 goto out;
5552         if (ret) {
5553                 ret = 0;
5554                 goto out;
5555         }
5556
5557         /*
5558          * Handle special case where the right side has no extents at all.
5559          */
5560         eb = path->nodes[0];
5561         slot = path->slots[0];
5562         btrfs_item_key_to_cpu(eb, &found_key, slot);
5563         if (found_key.objectid != key.objectid ||
5564             found_key.type != key.type) {
5565                 /* If we're a hole then just pretend nothing changed */
5566                 ret = (left_disknr) ? 0 : 1;
5567                 goto out;
5568         }
5569
5570         /*
5571          * We're now on 2a, 2b or 7.
5572          */
5573         key = found_key;
5574         while (key.offset < ekey->offset + left_len) {
5575                 ei = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
5576                 right_type = btrfs_file_extent_type(eb, ei);
5577                 if (right_type != BTRFS_FILE_EXTENT_REG &&
5578                     right_type != BTRFS_FILE_EXTENT_INLINE) {
5579                         ret = 0;
5580                         goto out;
5581                 }
5582
5583                 if (right_type == BTRFS_FILE_EXTENT_INLINE) {
5584                         right_len = btrfs_file_extent_ram_bytes(eb, ei);
5585                         right_len = PAGE_ALIGN(right_len);
5586                 } else {
5587                         right_len = btrfs_file_extent_num_bytes(eb, ei);
5588                 }
5589
5590                 /*
5591                  * Are we at extent 8? If yes, we know the extent is changed.
5592                  * This may only happen on the first iteration.
5593                  */
5594                 if (found_key.offset + right_len <= ekey->offset) {
5595                         /* If we're a hole just pretend nothing changed */
5596                         ret = (left_disknr) ? 0 : 1;
5597                         goto out;
5598                 }
5599
5600                 /*
5601                  * We just wanted to see if when we have an inline extent, what
5602                  * follows it is a regular extent (wanted to check the above
5603                  * condition for inline extents too). This should normally not
5604                  * happen but it's possible for example when we have an inline
5605                  * compressed extent representing data with a size matching
5606                  * the page size (currently the same as sector size).
5607                  */
5608                 if (right_type == BTRFS_FILE_EXTENT_INLINE) {
5609                         ret = 0;
5610                         goto out;
5611                 }
5612
5613                 right_disknr = btrfs_file_extent_disk_bytenr(eb, ei);
5614                 right_offset = btrfs_file_extent_offset(eb, ei);
5615                 right_gen = btrfs_file_extent_generation(eb, ei);
5616
5617                 left_offset_fixed = left_offset;
5618                 if (key.offset < ekey->offset) {
5619                         /* Fix the right offset for 2a and 7. */
5620                         right_offset += ekey->offset - key.offset;
5621                 } else {
5622                         /* Fix the left offset for all behind 2a and 2b */
5623                         left_offset_fixed += key.offset - ekey->offset;
5624                 }
5625
5626                 /*
5627                  * Check if we have the same extent.
5628                  */
5629                 if (left_disknr != right_disknr ||
5630                     left_offset_fixed != right_offset ||
5631                     left_gen != right_gen) {
5632                         ret = 0;
5633                         goto out;
5634                 }
5635
5636                 /*
5637                  * Go to the next extent.
5638                  */
5639                 ret = btrfs_next_item(sctx->parent_root, path);
5640                 if (ret < 0)
5641                         goto out;
5642                 if (!ret) {
5643                         eb = path->nodes[0];
5644                         slot = path->slots[0];
5645                         btrfs_item_key_to_cpu(eb, &found_key, slot);
5646                 }
5647                 if (ret || found_key.objectid != key.objectid ||
5648                     found_key.type != key.type) {
5649                         key.offset += right_len;
5650                         break;
5651                 }
5652                 if (found_key.offset != key.offset + right_len) {
5653                         ret = 0;
5654                         goto out;
5655                 }
5656                 key = found_key;
5657         }
5658
5659         /*
5660          * We're now behind the left extent (treat as unchanged) or at the end
5661          * of the right side (treat as changed).
5662          */
5663         if (key.offset >= ekey->offset + left_len)
5664                 ret = 1;
5665         else
5666                 ret = 0;
5667
5668
5669 out:
5670         btrfs_free_path(path);
5671         return ret;
5672 }
5673
5674 static int get_last_extent(struct send_ctx *sctx, u64 offset)
5675 {
5676         struct btrfs_path *path;
5677         struct btrfs_root *root = sctx->send_root;
5678         struct btrfs_file_extent_item *fi;
5679         struct btrfs_key key;
5680         u64 extent_end;
5681         u8 type;
5682         int ret;
5683
5684         path = alloc_path_for_send();
5685         if (!path)
5686                 return -ENOMEM;
5687
5688         sctx->cur_inode_last_extent = 0;
5689
5690         key.objectid = sctx->cur_ino;
5691         key.type = BTRFS_EXTENT_DATA_KEY;
5692         key.offset = offset;
5693         ret = btrfs_search_slot_for_read(root, &key, path, 0, 1);
5694         if (ret < 0)
5695                 goto out;
5696         ret = 0;
5697         btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
5698         if (key.objectid != sctx->cur_ino || key.type != BTRFS_EXTENT_DATA_KEY)
5699                 goto out;
5700
5701         fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
5702                             struct btrfs_file_extent_item);
5703         type = btrfs_file_extent_type(path->nodes[0], fi);
5704         if (type == BTRFS_FILE_EXTENT_INLINE) {
5705                 u64 size = btrfs_file_extent_ram_bytes(path->nodes[0], fi);
5706                 extent_end = ALIGN(key.offset + size,
5707                                    sctx->send_root->fs_info->sectorsize);
5708         } else {
5709                 extent_end = key.offset +
5710                         btrfs_file_extent_num_bytes(path->nodes[0], fi);
5711         }
5712         sctx->cur_inode_last_extent = extent_end;
5713 out:
5714         btrfs_free_path(path);
5715         return ret;
5716 }
5717
5718 static int range_is_hole_in_parent(struct send_ctx *sctx,
5719                                    const u64 start,
5720                                    const u64 end)
5721 {
5722         struct btrfs_path *path;
5723         struct btrfs_key key;
5724         struct btrfs_root *root = sctx->parent_root;
5725         u64 search_start = start;
5726         int ret;
5727
5728         path = alloc_path_for_send();
5729         if (!path)
5730                 return -ENOMEM;
5731
5732         key.objectid = sctx->cur_ino;
5733         key.type = BTRFS_EXTENT_DATA_KEY;
5734         key.offset = search_start;
5735         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5736         if (ret < 0)
5737                 goto out;
5738         if (ret > 0 && path->slots[0] > 0)
5739                 path->slots[0]--;
5740
5741         while (search_start < end) {
5742                 struct extent_buffer *leaf = path->nodes[0];
5743                 int slot = path->slots[0];
5744                 struct btrfs_file_extent_item *fi;
5745                 u64 extent_end;
5746
5747                 if (slot >= btrfs_header_nritems(leaf)) {
5748                         ret = btrfs_next_leaf(root, path);
5749                         if (ret < 0)
5750                                 goto out;
5751                         else if (ret > 0)
5752                                 break;
5753                         continue;
5754                 }
5755
5756                 btrfs_item_key_to_cpu(leaf, &key, slot);
5757                 if (key.objectid < sctx->cur_ino ||
5758                     key.type < BTRFS_EXTENT_DATA_KEY)
5759                         goto next;
5760                 if (key.objectid > sctx->cur_ino ||
5761                     key.type > BTRFS_EXTENT_DATA_KEY ||
5762                     key.offset >= end)
5763                         break;
5764
5765                 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
5766                 if (btrfs_file_extent_type(leaf, fi) ==
5767                     BTRFS_FILE_EXTENT_INLINE) {
5768                         u64 size = btrfs_file_extent_ram_bytes(leaf, fi);
5769
5770                         extent_end = ALIGN(key.offset + size,
5771                                            root->fs_info->sectorsize);
5772                 } else {
5773                         extent_end = key.offset +
5774                                 btrfs_file_extent_num_bytes(leaf, fi);
5775                 }
5776                 if (extent_end <= start)
5777                         goto next;
5778                 if (btrfs_file_extent_disk_bytenr(leaf, fi) == 0) {
5779                         search_start = extent_end;
5780                         goto next;
5781                 }
5782                 ret = 0;
5783                 goto out;
5784 next:
5785                 path->slots[0]++;
5786         }
5787         ret = 1;
5788 out:
5789         btrfs_free_path(path);
5790         return ret;
5791 }
5792
5793 static int maybe_send_hole(struct send_ctx *sctx, struct btrfs_path *path,
5794                            struct btrfs_key *key)
5795 {
5796         struct btrfs_file_extent_item *fi;
5797         u64 extent_end;
5798         u8 type;
5799         int ret = 0;
5800
5801         if (sctx->cur_ino != key->objectid || !need_send_hole(sctx))
5802                 return 0;
5803
5804         if (sctx->cur_inode_last_extent == (u64)-1) {
5805                 ret = get_last_extent(sctx, key->offset - 1);
5806                 if (ret)
5807                         return ret;
5808         }
5809
5810         fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
5811                             struct btrfs_file_extent_item);
5812         type = btrfs_file_extent_type(path->nodes[0], fi);
5813         if (type == BTRFS_FILE_EXTENT_INLINE) {
5814                 u64 size = btrfs_file_extent_ram_bytes(path->nodes[0], fi);
5815                 extent_end = ALIGN(key->offset + size,
5816                                    sctx->send_root->fs_info->sectorsize);
5817         } else {
5818                 extent_end = key->offset +
5819                         btrfs_file_extent_num_bytes(path->nodes[0], fi);
5820         }
5821
5822         if (path->slots[0] == 0 &&
5823             sctx->cur_inode_last_extent < key->offset) {
5824                 /*
5825                  * We might have skipped entire leafs that contained only
5826                  * file extent items for our current inode. These leafs have
5827                  * a generation number smaller (older) than the one in the
5828                  * current leaf and the leaf our last extent came from, and
5829                  * are located between these 2 leafs.
5830                  */
5831                 ret = get_last_extent(sctx, key->offset - 1);
5832                 if (ret)
5833                         return ret;
5834         }
5835
5836         if (sctx->cur_inode_last_extent < key->offset) {
5837                 ret = range_is_hole_in_parent(sctx,
5838                                               sctx->cur_inode_last_extent,
5839                                               key->offset);
5840                 if (ret < 0)
5841                         return ret;
5842                 else if (ret == 0)
5843                         ret = send_hole(sctx, key->offset);
5844                 else
5845                         ret = 0;
5846         }
5847         sctx->cur_inode_last_extent = extent_end;
5848         return ret;
5849 }
5850
5851 static int process_extent(struct send_ctx *sctx,
5852                           struct btrfs_path *path,
5853                           struct btrfs_key *key)
5854 {
5855         struct clone_root *found_clone = NULL;
5856         int ret = 0;
5857
5858         if (S_ISLNK(sctx->cur_inode_mode))
5859                 return 0;
5860
5861         if (sctx->parent_root && !sctx->cur_inode_new) {
5862                 ret = is_extent_unchanged(sctx, path, key);
5863                 if (ret < 0)
5864                         goto out;
5865                 if (ret) {
5866                         ret = 0;
5867                         goto out_hole;
5868                 }
5869         } else {
5870                 struct btrfs_file_extent_item *ei;
5871                 u8 type;
5872
5873                 ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
5874                                     struct btrfs_file_extent_item);
5875                 type = btrfs_file_extent_type(path->nodes[0], ei);
5876                 if (type == BTRFS_FILE_EXTENT_PREALLOC ||
5877                     type == BTRFS_FILE_EXTENT_REG) {
5878                         /*
5879                          * The send spec does not have a prealloc command yet,
5880                          * so just leave a hole for prealloc'ed extents until
5881                          * we have enough commands queued up to justify rev'ing
5882                          * the send spec.
5883                          */
5884                         if (type == BTRFS_FILE_EXTENT_PREALLOC) {
5885                                 ret = 0;
5886                                 goto out;
5887                         }
5888
5889                         /* Have a hole, just skip it. */
5890                         if (btrfs_file_extent_disk_bytenr(path->nodes[0], ei) == 0) {
5891                                 ret = 0;
5892                                 goto out;
5893                         }
5894                 }
5895         }
5896
5897         ret = find_extent_clone(sctx, path, key->objectid, key->offset,
5898                         sctx->cur_inode_size, &found_clone);
5899         if (ret != -ENOENT && ret < 0)
5900                 goto out;
5901
5902         ret = send_write_or_clone(sctx, path, key, found_clone);
5903         if (ret)
5904                 goto out;
5905 out_hole:
5906         ret = maybe_send_hole(sctx, path, key);
5907 out:
5908         return ret;
5909 }
5910
5911 static int process_all_extents(struct send_ctx *sctx)
5912 {
5913         int ret;
5914         struct btrfs_root *root;
5915         struct btrfs_path *path;
5916         struct btrfs_key key;
5917         struct btrfs_key found_key;
5918         struct extent_buffer *eb;
5919         int slot;
5920
5921         root = sctx->send_root;
5922         path = alloc_path_for_send();
5923         if (!path)
5924                 return -ENOMEM;
5925
5926         key.objectid = sctx->cmp_key->objectid;
5927         key.type = BTRFS_EXTENT_DATA_KEY;
5928         key.offset = 0;
5929         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5930         if (ret < 0)
5931                 goto out;
5932
5933         while (1) {
5934                 eb = path->nodes[0];
5935                 slot = path->slots[0];
5936
5937                 if (slot >= btrfs_header_nritems(eb)) {
5938                         ret = btrfs_next_leaf(root, path);
5939                         if (ret < 0) {
5940                                 goto out;
5941                         } else if (ret > 0) {
5942                                 ret = 0;
5943                                 break;
5944                         }
5945                         continue;
5946                 }
5947
5948                 btrfs_item_key_to_cpu(eb, &found_key, slot);
5949
5950                 if (found_key.objectid != key.objectid ||
5951                     found_key.type != key.type) {
5952                         ret = 0;
5953                         goto out;
5954                 }
5955
5956                 ret = process_extent(sctx, path, &found_key);
5957                 if (ret < 0)
5958                         goto out;
5959
5960                 path->slots[0]++;
5961         }
5962
5963 out:
5964         btrfs_free_path(path);
5965         return ret;
5966 }
5967
5968 static int process_recorded_refs_if_needed(struct send_ctx *sctx, int at_end,
5969                                            int *pending_move,
5970                                            int *refs_processed)
5971 {
5972         int ret = 0;
5973
5974         if (sctx->cur_ino == 0)
5975                 goto out;
5976         if (!at_end && sctx->cur_ino == sctx->cmp_key->objectid &&
5977             sctx->cmp_key->type <= BTRFS_INODE_EXTREF_KEY)
5978                 goto out;
5979         if (list_empty(&sctx->new_refs) && list_empty(&sctx->deleted_refs))
5980                 goto out;
5981
5982         ret = process_recorded_refs(sctx, pending_move);
5983         if (ret < 0)
5984                 goto out;
5985
5986         *refs_processed = 1;
5987 out:
5988         return ret;
5989 }
5990
5991 static int finish_inode_if_needed(struct send_ctx *sctx, int at_end)
5992 {
5993         int ret = 0;
5994         u64 left_mode;
5995         u64 left_uid;
5996         u64 left_gid;
5997         u64 right_mode;
5998         u64 right_uid;
5999         u64 right_gid;
6000         int need_chmod = 0;
6001         int need_chown = 0;
6002         int need_truncate = 1;
6003         int pending_move = 0;
6004         int refs_processed = 0;
6005
6006         if (sctx->ignore_cur_inode)
6007                 return 0;
6008
6009         ret = process_recorded_refs_if_needed(sctx, at_end, &pending_move,
6010                                               &refs_processed);
6011         if (ret < 0)
6012                 goto out;
6013
6014         /*
6015          * We have processed the refs and thus need to advance send_progress.
6016          * Now, calls to get_cur_xxx will take the updated refs of the current
6017          * inode into account.
6018          *
6019          * On the other hand, if our current inode is a directory and couldn't
6020          * be moved/renamed because its parent was renamed/moved too and it has
6021          * a higher inode number, we can only move/rename our current inode
6022          * after we moved/renamed its parent. Therefore in this case operate on
6023          * the old path (pre move/rename) of our current inode, and the
6024          * move/rename will be performed later.
6025          */
6026         if (refs_processed && !pending_move)
6027                 sctx->send_progress = sctx->cur_ino + 1;
6028
6029         if (sctx->cur_ino == 0 || sctx->cur_inode_deleted)
6030                 goto out;
6031         if (!at_end && sctx->cmp_key->objectid == sctx->cur_ino)
6032                 goto out;
6033
6034         ret = get_inode_info(sctx->send_root, sctx->cur_ino, NULL, NULL,
6035                         &left_mode, &left_uid, &left_gid, NULL);
6036         if (ret < 0)
6037                 goto out;
6038
6039         if (!sctx->parent_root || sctx->cur_inode_new) {
6040                 need_chown = 1;
6041                 if (!S_ISLNK(sctx->cur_inode_mode))
6042                         need_chmod = 1;
6043                 if (sctx->cur_inode_next_write_offset == sctx->cur_inode_size)
6044                         need_truncate = 0;
6045         } else {
6046                 u64 old_size;
6047
6048                 ret = get_inode_info(sctx->parent_root, sctx->cur_ino,
6049                                 &old_size, NULL, &right_mode, &right_uid,
6050                                 &right_gid, NULL);
6051                 if (ret < 0)
6052                         goto out;
6053
6054                 if (left_uid != right_uid || left_gid != right_gid)
6055                         need_chown = 1;
6056                 if (!S_ISLNK(sctx->cur_inode_mode) && left_mode != right_mode)
6057                         need_chmod = 1;
6058                 if ((old_size == sctx->cur_inode_size) ||
6059                     (sctx->cur_inode_size > old_size &&
6060                      sctx->cur_inode_next_write_offset == sctx->cur_inode_size))
6061                         need_truncate = 0;
6062         }
6063
6064         if (S_ISREG(sctx->cur_inode_mode)) {
6065                 if (need_send_hole(sctx)) {
6066                         if (sctx->cur_inode_last_extent == (u64)-1 ||
6067                             sctx->cur_inode_last_extent <
6068                             sctx->cur_inode_size) {
6069                                 ret = get_last_extent(sctx, (u64)-1);
6070                                 if (ret)
6071                                         goto out;
6072                         }
6073                         if (sctx->cur_inode_last_extent <
6074                             sctx->cur_inode_size) {
6075                                 ret = send_hole(sctx, sctx->cur_inode_size);
6076                                 if (ret)
6077                                         goto out;
6078                         }
6079                 }
6080                 if (need_truncate) {
6081                         ret = send_truncate(sctx, sctx->cur_ino,
6082                                             sctx->cur_inode_gen,
6083                                             sctx->cur_inode_size);
6084                         if (ret < 0)
6085                                 goto out;
6086                 }
6087         }
6088
6089         if (need_chown) {
6090                 ret = send_chown(sctx, sctx->cur_ino, sctx->cur_inode_gen,
6091                                 left_uid, left_gid);
6092                 if (ret < 0)
6093                         goto out;
6094         }
6095         if (need_chmod) {
6096                 ret = send_chmod(sctx, sctx->cur_ino, sctx->cur_inode_gen,
6097                                 left_mode);
6098                 if (ret < 0)
6099                         goto out;
6100         }
6101
6102         ret = send_capabilities(sctx);
6103         if (ret < 0)
6104                 goto out;
6105
6106         /*
6107          * If other directory inodes depended on our current directory
6108          * inode's move/rename, now do their move/rename operations.
6109          */
6110         if (!is_waiting_for_move(sctx, sctx->cur_ino)) {
6111                 ret = apply_children_dir_moves(sctx);
6112                 if (ret)
6113                         goto out;
6114                 /*
6115                  * Need to send that every time, no matter if it actually
6116                  * changed between the two trees as we have done changes to
6117                  * the inode before. If our inode is a directory and it's
6118                  * waiting to be moved/renamed, we will send its utimes when
6119                  * it's moved/renamed, therefore we don't need to do it here.
6120                  */
6121                 sctx->send_progress = sctx->cur_ino + 1;
6122                 ret = send_utimes(sctx, sctx->cur_ino, sctx->cur_inode_gen);
6123                 if (ret < 0)
6124                         goto out;
6125         }
6126
6127 out:
6128         return ret;
6129 }
6130
6131 struct parent_paths_ctx {
6132         struct list_head *refs;
6133         struct send_ctx *sctx;
6134 };
6135
6136 static int record_parent_ref(int num, u64 dir, int index, struct fs_path *name,
6137                              void *ctx)
6138 {
6139         struct parent_paths_ctx *ppctx = ctx;
6140
6141         return record_ref(ppctx->sctx->parent_root, dir, name, ppctx->sctx,
6142                           ppctx->refs);
6143 }
6144
6145 /*
6146  * Issue unlink operations for all paths of the current inode found in the
6147  * parent snapshot.
6148  */
6149 static int btrfs_unlink_all_paths(struct send_ctx *sctx)
6150 {
6151         LIST_HEAD(deleted_refs);
6152         struct btrfs_path *path;
6153         struct btrfs_key key;
6154         struct parent_paths_ctx ctx;
6155         int ret;
6156
6157         path = alloc_path_for_send();
6158         if (!path)
6159                 return -ENOMEM;
6160
6161         key.objectid = sctx->cur_ino;
6162         key.type = BTRFS_INODE_REF_KEY;
6163         key.offset = 0;
6164         ret = btrfs_search_slot(NULL, sctx->parent_root, &key, path, 0, 0);
6165         if (ret < 0)
6166                 goto out;
6167
6168         ctx.refs = &deleted_refs;
6169         ctx.sctx = sctx;
6170
6171         while (true) {
6172                 struct extent_buffer *eb = path->nodes[0];
6173                 int slot = path->slots[0];
6174
6175                 if (slot >= btrfs_header_nritems(eb)) {
6176                         ret = btrfs_next_leaf(sctx->parent_root, path);
6177                         if (ret < 0)
6178                                 goto out;
6179                         else if (ret > 0)
6180                                 break;
6181                         continue;
6182                 }
6183
6184                 btrfs_item_key_to_cpu(eb, &key, slot);
6185                 if (key.objectid != sctx->cur_ino)
6186                         break;
6187                 if (key.type != BTRFS_INODE_REF_KEY &&
6188                     key.type != BTRFS_INODE_EXTREF_KEY)
6189                         break;
6190
6191                 ret = iterate_inode_ref(sctx->parent_root, path, &key, 1,
6192                                         record_parent_ref, &ctx);
6193                 if (ret < 0)
6194                         goto out;
6195
6196                 path->slots[0]++;
6197         }
6198
6199         while (!list_empty(&deleted_refs)) {
6200                 struct recorded_ref *ref;
6201
6202                 ref = list_first_entry(&deleted_refs, struct recorded_ref, list);
6203                 ret = send_unlink(sctx, ref->full_path);
6204                 if (ret < 0)
6205                         goto out;
6206                 fs_path_free(ref->full_path);
6207                 list_del(&ref->list);
6208                 kfree(ref);
6209         }
6210         ret = 0;
6211 out:
6212         btrfs_free_path(path);
6213         if (ret)
6214                 __free_recorded_refs(&deleted_refs);
6215         return ret;
6216 }
6217
6218 static int changed_inode(struct send_ctx *sctx,
6219                          enum btrfs_compare_tree_result result)
6220 {
6221         int ret = 0;
6222         struct btrfs_key *key = sctx->cmp_key;
6223         struct btrfs_inode_item *left_ii = NULL;
6224         struct btrfs_inode_item *right_ii = NULL;
6225         u64 left_gen = 0;
6226         u64 right_gen = 0;
6227
6228         sctx->cur_ino = key->objectid;
6229         sctx->cur_inode_new_gen = 0;
6230         sctx->cur_inode_last_extent = (u64)-1;
6231         sctx->cur_inode_next_write_offset = 0;
6232         sctx->ignore_cur_inode = false;
6233
6234         /*
6235          * Set send_progress to current inode. This will tell all get_cur_xxx
6236          * functions that the current inode's refs are not updated yet. Later,
6237          * when process_recorded_refs is finished, it is set to cur_ino + 1.
6238          */
6239         sctx->send_progress = sctx->cur_ino;
6240
6241         if (result == BTRFS_COMPARE_TREE_NEW ||
6242             result == BTRFS_COMPARE_TREE_CHANGED) {
6243                 left_ii = btrfs_item_ptr(sctx->left_path->nodes[0],
6244                                 sctx->left_path->slots[0],
6245                                 struct btrfs_inode_item);
6246                 left_gen = btrfs_inode_generation(sctx->left_path->nodes[0],
6247                                 left_ii);
6248         } else {
6249                 right_ii = btrfs_item_ptr(sctx->right_path->nodes[0],
6250                                 sctx->right_path->slots[0],
6251                                 struct btrfs_inode_item);
6252                 right_gen = btrfs_inode_generation(sctx->right_path->nodes[0],
6253                                 right_ii);
6254         }
6255         if (result == BTRFS_COMPARE_TREE_CHANGED) {
6256                 right_ii = btrfs_item_ptr(sctx->right_path->nodes[0],
6257                                 sctx->right_path->slots[0],
6258                                 struct btrfs_inode_item);
6259
6260                 right_gen = btrfs_inode_generation(sctx->right_path->nodes[0],
6261                                 right_ii);
6262
6263                 /*
6264                  * The cur_ino = root dir case is special here. We can't treat
6265                  * the inode as deleted+reused because it would generate a
6266                  * stream that tries to delete/mkdir the root dir.
6267                  */
6268                 if (left_gen != right_gen &&
6269                     sctx->cur_ino != BTRFS_FIRST_FREE_OBJECTID)
6270                         sctx->cur_inode_new_gen = 1;
6271         }
6272
6273         /*
6274          * Normally we do not find inodes with a link count of zero (orphans)
6275          * because the most common case is to create a snapshot and use it
6276          * for a send operation. However other less common use cases involve
6277          * using a subvolume and send it after turning it to RO mode just
6278          * after deleting all hard links of a file while holding an open
6279          * file descriptor against it or turning a RO snapshot into RW mode,
6280          * keep an open file descriptor against a file, delete it and then
6281          * turn the snapshot back to RO mode before using it for a send
6282          * operation. So if we find such cases, ignore the inode and all its
6283          * items completely if it's a new inode, or if it's a changed inode
6284          * make sure all its previous paths (from the parent snapshot) are all
6285          * unlinked and all other the inode items are ignored.
6286          */
6287         if (result == BTRFS_COMPARE_TREE_NEW ||
6288             result == BTRFS_COMPARE_TREE_CHANGED) {
6289                 u32 nlinks;
6290
6291                 nlinks = btrfs_inode_nlink(sctx->left_path->nodes[0], left_ii);
6292                 if (nlinks == 0) {
6293                         sctx->ignore_cur_inode = true;
6294                         if (result == BTRFS_COMPARE_TREE_CHANGED)
6295                                 ret = btrfs_unlink_all_paths(sctx);
6296                         goto out;
6297                 }
6298         }
6299
6300         if (result == BTRFS_COMPARE_TREE_NEW) {
6301                 sctx->cur_inode_gen = left_gen;
6302                 sctx->cur_inode_new = 1;
6303                 sctx->cur_inode_deleted = 0;
6304                 sctx->cur_inode_size = btrfs_inode_size(
6305                                 sctx->left_path->nodes[0], left_ii);
6306                 sctx->cur_inode_mode = btrfs_inode_mode(
6307                                 sctx->left_path->nodes[0], left_ii);
6308                 sctx->cur_inode_rdev = btrfs_inode_rdev(
6309                                 sctx->left_path->nodes[0], left_ii);
6310                 if (sctx->cur_ino != BTRFS_FIRST_FREE_OBJECTID)
6311                         ret = send_create_inode_if_needed(sctx);
6312         } else if (result == BTRFS_COMPARE_TREE_DELETED) {
6313                 sctx->cur_inode_gen = right_gen;
6314                 sctx->cur_inode_new = 0;
6315                 sctx->cur_inode_deleted = 1;
6316                 sctx->cur_inode_size = btrfs_inode_size(
6317                                 sctx->right_path->nodes[0], right_ii);
6318                 sctx->cur_inode_mode = btrfs_inode_mode(
6319                                 sctx->right_path->nodes[0], right_ii);
6320         } else if (result == BTRFS_COMPARE_TREE_CHANGED) {
6321                 /*
6322                  * We need to do some special handling in case the inode was
6323                  * reported as changed with a changed generation number. This
6324                  * means that the original inode was deleted and new inode
6325                  * reused the same inum. So we have to treat the old inode as
6326                  * deleted and the new one as new.
6327                  */
6328                 if (sctx->cur_inode_new_gen) {
6329                         /*
6330                          * First, process the inode as if it was deleted.
6331                          */
6332                         sctx->cur_inode_gen = right_gen;
6333                         sctx->cur_inode_new = 0;
6334                         sctx->cur_inode_deleted = 1;
6335                         sctx->cur_inode_size = btrfs_inode_size(
6336                                         sctx->right_path->nodes[0], right_ii);
6337                         sctx->cur_inode_mode = btrfs_inode_mode(
6338                                         sctx->right_path->nodes[0], right_ii);
6339                         ret = process_all_refs(sctx,
6340                                         BTRFS_COMPARE_TREE_DELETED);
6341                         if (ret < 0)
6342                                 goto out;
6343
6344                         /*
6345                          * Now process the inode as if it was new.
6346                          */
6347                         sctx->cur_inode_gen = left_gen;
6348                         sctx->cur_inode_new = 1;
6349                         sctx->cur_inode_deleted = 0;
6350                         sctx->cur_inode_size = btrfs_inode_size(
6351                                         sctx->left_path->nodes[0], left_ii);
6352                         sctx->cur_inode_mode = btrfs_inode_mode(
6353                                         sctx->left_path->nodes[0], left_ii);
6354                         sctx->cur_inode_rdev = btrfs_inode_rdev(
6355                                         sctx->left_path->nodes[0], left_ii);
6356                         ret = send_create_inode_if_needed(sctx);
6357                         if (ret < 0)
6358                                 goto out;
6359
6360                         ret = process_all_refs(sctx, BTRFS_COMPARE_TREE_NEW);
6361                         if (ret < 0)
6362                                 goto out;
6363                         /*
6364                          * Advance send_progress now as we did not get into
6365                          * process_recorded_refs_if_needed in the new_gen case.
6366                          */
6367                         sctx->send_progress = sctx->cur_ino + 1;
6368
6369                         /*
6370                          * Now process all extents and xattrs of the inode as if
6371                          * they were all new.
6372                          */
6373                         ret = process_all_extents(sctx);
6374                         if (ret < 0)
6375                                 goto out;
6376                         ret = process_all_new_xattrs(sctx);
6377                         if (ret < 0)
6378                                 goto out;
6379                 } else {
6380                         sctx->cur_inode_gen = left_gen;
6381                         sctx->cur_inode_new = 0;
6382                         sctx->cur_inode_new_gen = 0;
6383                         sctx->cur_inode_deleted = 0;
6384                         sctx->cur_inode_size = btrfs_inode_size(
6385                                         sctx->left_path->nodes[0], left_ii);
6386                         sctx->cur_inode_mode = btrfs_inode_mode(
6387                                         sctx->left_path->nodes[0], left_ii);
6388                 }
6389         }
6390
6391 out:
6392         return ret;
6393 }
6394
6395 /*
6396  * We have to process new refs before deleted refs, but compare_trees gives us
6397  * the new and deleted refs mixed. To fix this, we record the new/deleted refs
6398  * first and later process them in process_recorded_refs.
6399  * For the cur_inode_new_gen case, we skip recording completely because
6400  * changed_inode did already initiate processing of refs. The reason for this is
6401  * that in this case, compare_tree actually compares the refs of 2 different
6402  * inodes. To fix this, process_all_refs is used in changed_inode to handle all
6403  * refs of the right tree as deleted and all refs of the left tree as new.
6404  */
6405 static int changed_ref(struct send_ctx *sctx,
6406                        enum btrfs_compare_tree_result result)
6407 {
6408         int ret = 0;
6409
6410         if (sctx->cur_ino != sctx->cmp_key->objectid) {
6411                 inconsistent_snapshot_error(sctx, result, "reference");
6412                 return -EIO;
6413         }
6414
6415         if (!sctx->cur_inode_new_gen &&
6416             sctx->cur_ino != BTRFS_FIRST_FREE_OBJECTID) {
6417                 if (result == BTRFS_COMPARE_TREE_NEW)
6418                         ret = record_new_ref(sctx);
6419                 else if (result == BTRFS_COMPARE_TREE_DELETED)
6420                         ret = record_deleted_ref(sctx);
6421                 else if (result == BTRFS_COMPARE_TREE_CHANGED)
6422                         ret = record_changed_ref(sctx);
6423         }
6424
6425         return ret;
6426 }
6427
6428 /*
6429  * Process new/deleted/changed xattrs. We skip processing in the
6430  * cur_inode_new_gen case because changed_inode did already initiate processing
6431  * of xattrs. The reason is the same as in changed_ref
6432  */
6433 static int changed_xattr(struct send_ctx *sctx,
6434                          enum btrfs_compare_tree_result result)
6435 {
6436         int ret = 0;
6437
6438         if (sctx->cur_ino != sctx->cmp_key->objectid) {
6439                 inconsistent_snapshot_error(sctx, result, "xattr");
6440                 return -EIO;
6441         }
6442
6443         if (!sctx->cur_inode_new_gen && !sctx->cur_inode_deleted) {
6444                 if (result == BTRFS_COMPARE_TREE_NEW)
6445                         ret = process_new_xattr(sctx);
6446                 else if (result == BTRFS_COMPARE_TREE_DELETED)
6447                         ret = process_deleted_xattr(sctx);
6448                 else if (result == BTRFS_COMPARE_TREE_CHANGED)
6449                         ret = process_changed_xattr(sctx);
6450         }
6451
6452         return ret;
6453 }
6454
6455 /*
6456  * Process new/deleted/changed extents. We skip processing in the
6457  * cur_inode_new_gen case because changed_inode did already initiate processing
6458  * of extents. The reason is the same as in changed_ref
6459  */
6460 static int changed_extent(struct send_ctx *sctx,
6461                           enum btrfs_compare_tree_result result)
6462 {
6463         int ret = 0;
6464
6465         /*
6466          * We have found an extent item that changed without the inode item
6467          * having changed. This can happen either after relocation (where the
6468          * disk_bytenr of an extent item is replaced at
6469          * relocation.c:replace_file_extents()) or after deduplication into a
6470          * file in both the parent and send snapshots (where an extent item can
6471          * get modified or replaced with a new one). Note that deduplication
6472          * updates the inode item, but it only changes the iversion (sequence
6473          * field in the inode item) of the inode, so if a file is deduplicated
6474          * the same amount of times in both the parent and send snapshots, its
6475          * iversion becames the same in both snapshots, whence the inode item is
6476          * the same on both snapshots.
6477          */
6478         if (sctx->cur_ino != sctx->cmp_key->objectid)
6479                 return 0;
6480
6481         if (!sctx->cur_inode_new_gen && !sctx->cur_inode_deleted) {
6482                 if (result != BTRFS_COMPARE_TREE_DELETED)
6483                         ret = process_extent(sctx, sctx->left_path,
6484                                         sctx->cmp_key);
6485         }
6486
6487         return ret;
6488 }
6489
6490 static int dir_changed(struct send_ctx *sctx, u64 dir)
6491 {
6492         u64 orig_gen, new_gen;
6493         int ret;
6494
6495         ret = get_inode_info(sctx->send_root, dir, NULL, &new_gen, NULL, NULL,
6496                              NULL, NULL);
6497         if (ret)
6498                 return ret;
6499
6500         ret = get_inode_info(sctx->parent_root, dir, NULL, &orig_gen, NULL,
6501                              NULL, NULL, NULL);
6502         if (ret)
6503                 return ret;
6504
6505         return (orig_gen != new_gen) ? 1 : 0;
6506 }
6507
6508 static int compare_refs(struct send_ctx *sctx, struct btrfs_path *path,
6509                         struct btrfs_key *key)
6510 {
6511         struct btrfs_inode_extref *extref;
6512         struct extent_buffer *leaf;
6513         u64 dirid = 0, last_dirid = 0;
6514         unsigned long ptr;
6515         u32 item_size;
6516         u32 cur_offset = 0;
6517         int ref_name_len;
6518         int ret = 0;
6519
6520         /* Easy case, just check this one dirid */
6521         if (key->type == BTRFS_INODE_REF_KEY) {
6522                 dirid = key->offset;
6523
6524                 ret = dir_changed(sctx, dirid);
6525                 goto out;
6526         }
6527
6528         leaf = path->nodes[0];
6529         item_size = btrfs_item_size_nr(leaf, path->slots[0]);
6530         ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
6531         while (cur_offset < item_size) {
6532                 extref = (struct btrfs_inode_extref *)(ptr +
6533                                                        cur_offset);
6534                 dirid = btrfs_inode_extref_parent(leaf, extref);
6535                 ref_name_len = btrfs_inode_extref_name_len(leaf, extref);
6536                 cur_offset += ref_name_len + sizeof(*extref);
6537                 if (dirid == last_dirid)
6538                         continue;
6539                 ret = dir_changed(sctx, dirid);
6540                 if (ret)
6541                         break;
6542                 last_dirid = dirid;
6543         }
6544 out:
6545         return ret;
6546 }
6547
6548 /*
6549  * Updates compare related fields in sctx and simply forwards to the actual
6550  * changed_xxx functions.
6551  */
6552 static int changed_cb(struct btrfs_path *left_path,
6553                       struct btrfs_path *right_path,
6554                       struct btrfs_key *key,
6555                       enum btrfs_compare_tree_result result,
6556                       void *ctx)
6557 {
6558         int ret = 0;
6559         struct send_ctx *sctx = ctx;
6560
6561         if (result == BTRFS_COMPARE_TREE_SAME) {
6562                 if (key->type == BTRFS_INODE_REF_KEY ||
6563                     key->type == BTRFS_INODE_EXTREF_KEY) {
6564                         ret = compare_refs(sctx, left_path, key);
6565                         if (!ret)
6566                                 return 0;
6567                         if (ret < 0)
6568                                 return ret;
6569                 } else if (key->type == BTRFS_EXTENT_DATA_KEY) {
6570                         return maybe_send_hole(sctx, left_path, key);
6571                 } else {
6572                         return 0;
6573                 }
6574                 result = BTRFS_COMPARE_TREE_CHANGED;
6575                 ret = 0;
6576         }
6577
6578         sctx->left_path = left_path;
6579         sctx->right_path = right_path;
6580         sctx->cmp_key = key;
6581
6582         ret = finish_inode_if_needed(sctx, 0);
6583         if (ret < 0)
6584                 goto out;
6585
6586         /* Ignore non-FS objects */
6587         if (key->objectid == BTRFS_FREE_INO_OBJECTID ||
6588             key->objectid == BTRFS_FREE_SPACE_OBJECTID)
6589                 goto out;
6590
6591         if (key->type == BTRFS_INODE_ITEM_KEY) {
6592                 ret = changed_inode(sctx, result);
6593         } else if (!sctx->ignore_cur_inode) {
6594                 if (key->type == BTRFS_INODE_REF_KEY ||
6595                     key->type == BTRFS_INODE_EXTREF_KEY)
6596                         ret = changed_ref(sctx, result);
6597                 else if (key->type == BTRFS_XATTR_ITEM_KEY)
6598                         ret = changed_xattr(sctx, result);
6599                 else if (key->type == BTRFS_EXTENT_DATA_KEY)
6600                         ret = changed_extent(sctx, result);
6601         }
6602
6603 out:
6604         return ret;
6605 }
6606
6607 static int full_send_tree(struct send_ctx *sctx)
6608 {
6609         int ret;
6610         struct btrfs_root *send_root = sctx->send_root;
6611         struct btrfs_key key;
6612         struct btrfs_path *path;
6613         struct extent_buffer *eb;
6614         int slot;
6615
6616         path = alloc_path_for_send();
6617         if (!path)
6618                 return -ENOMEM;
6619
6620         key.objectid = BTRFS_FIRST_FREE_OBJECTID;
6621         key.type = BTRFS_INODE_ITEM_KEY;
6622         key.offset = 0;
6623
6624         ret = btrfs_search_slot_for_read(send_root, &key, path, 1, 0);
6625         if (ret < 0)
6626                 goto out;
6627         if (ret)
6628                 goto out_finish;
6629
6630         while (1) {
6631                 eb = path->nodes[0];
6632                 slot = path->slots[0];
6633                 btrfs_item_key_to_cpu(eb, &key, slot);
6634
6635                 ret = changed_cb(path, NULL, &key,
6636                                  BTRFS_COMPARE_TREE_NEW, sctx);
6637                 if (ret < 0)
6638                         goto out;
6639
6640                 ret = btrfs_next_item(send_root, path);
6641                 if (ret < 0)
6642                         goto out;
6643                 if (ret) {
6644                         ret  = 0;
6645                         break;
6646                 }
6647         }
6648
6649 out_finish:
6650         ret = finish_inode_if_needed(sctx, 1);
6651
6652 out:
6653         btrfs_free_path(path);
6654         return ret;
6655 }
6656
6657 static int send_subvol(struct send_ctx *sctx)
6658 {
6659         int ret;
6660
6661         if (!(sctx->flags & BTRFS_SEND_FLAG_OMIT_STREAM_HEADER)) {
6662                 ret = send_header(sctx);
6663                 if (ret < 0)
6664                         goto out;
6665         }
6666
6667         ret = send_subvol_begin(sctx);
6668         if (ret < 0)
6669                 goto out;
6670
6671         if (sctx->parent_root) {
6672                 ret = btrfs_compare_trees(sctx->send_root, sctx->parent_root,
6673                                 changed_cb, sctx);
6674                 if (ret < 0)
6675                         goto out;
6676                 ret = finish_inode_if_needed(sctx, 1);
6677                 if (ret < 0)
6678                         goto out;
6679         } else {
6680                 ret = full_send_tree(sctx);
6681                 if (ret < 0)
6682                         goto out;
6683         }
6684
6685 out:
6686         free_recorded_refs(sctx);
6687         return ret;
6688 }
6689
6690 /*
6691  * If orphan cleanup did remove any orphans from a root, it means the tree
6692  * was modified and therefore the commit root is not the same as the current
6693  * root anymore. This is a problem, because send uses the commit root and
6694  * therefore can see inode items that don't exist in the current root anymore,
6695  * and for example make calls to btrfs_iget, which will do tree lookups based
6696  * on the current root and not on the commit root. Those lookups will fail,
6697  * returning a -ESTALE error, and making send fail with that error. So make
6698  * sure a send does not see any orphans we have just removed, and that it will
6699  * see the same inodes regardless of whether a transaction commit happened
6700  * before it started (meaning that the commit root will be the same as the
6701  * current root) or not.
6702  */
6703 static int ensure_commit_roots_uptodate(struct send_ctx *sctx)
6704 {
6705         int i;
6706         struct btrfs_trans_handle *trans = NULL;
6707
6708 again:
6709         if (sctx->parent_root &&
6710             sctx->parent_root->node != sctx->parent_root->commit_root)
6711                 goto commit_trans;
6712
6713         for (i = 0; i < sctx->clone_roots_cnt; i++)
6714                 if (sctx->clone_roots[i].root->node !=
6715                     sctx->clone_roots[i].root->commit_root)
6716                         goto commit_trans;
6717
6718         if (trans)
6719                 return btrfs_end_transaction(trans);
6720
6721         return 0;
6722
6723 commit_trans:
6724         /* Use any root, all fs roots will get their commit roots updated. */
6725         if (!trans) {
6726                 trans = btrfs_join_transaction(sctx->send_root);
6727                 if (IS_ERR(trans))
6728                         return PTR_ERR(trans);
6729                 goto again;
6730         }
6731
6732         return btrfs_commit_transaction(trans);
6733 }
6734
6735 /*
6736  * Make sure any existing dellaloc is flushed for any root used by a send
6737  * operation so that we do not miss any data and we do not race with writeback
6738  * finishing and changing a tree while send is using the tree. This could
6739  * happen if a subvolume is in RW mode, has delalloc, is turned to RO mode and
6740  * a send operation then uses the subvolume.
6741  * After flushing delalloc ensure_commit_roots_uptodate() must be called.
6742  */
6743 static int flush_delalloc_roots(struct send_ctx *sctx)
6744 {
6745         struct btrfs_root *root = sctx->parent_root;
6746         int ret;
6747         int i;
6748
6749         if (root) {
6750                 ret = btrfs_start_delalloc_snapshot(root);
6751                 if (ret)
6752                         return ret;
6753                 btrfs_wait_ordered_extents(root, U64_MAX, 0, U64_MAX);
6754         }
6755
6756         for (i = 0; i < sctx->clone_roots_cnt; i++) {
6757                 root = sctx->clone_roots[i].root;
6758                 ret = btrfs_start_delalloc_snapshot(root);
6759                 if (ret)
6760                         return ret;
6761                 btrfs_wait_ordered_extents(root, U64_MAX, 0, U64_MAX);
6762         }
6763
6764         return 0;
6765 }
6766
6767 static void btrfs_root_dec_send_in_progress(struct btrfs_root* root)
6768 {
6769         spin_lock(&root->root_item_lock);
6770         root->send_in_progress--;
6771         /*
6772          * Not much left to do, we don't know why it's unbalanced and
6773          * can't blindly reset it to 0.
6774          */
6775         if (root->send_in_progress < 0)
6776                 btrfs_err(root->fs_info,
6777                           "send_in_progress unbalanced %d root %llu",
6778                           root->send_in_progress, root->root_key.objectid);
6779         spin_unlock(&root->root_item_lock);
6780 }
6781
6782 long btrfs_ioctl_send(struct file *mnt_file, struct btrfs_ioctl_send_args *arg)
6783 {
6784         int ret = 0;
6785         struct btrfs_root *send_root = BTRFS_I(file_inode(mnt_file))->root;
6786         struct btrfs_fs_info *fs_info = send_root->fs_info;
6787         struct btrfs_root *clone_root;
6788         struct btrfs_key key;
6789         struct send_ctx *sctx = NULL;
6790         u32 i;
6791         u64 *clone_sources_tmp = NULL;
6792         int clone_sources_to_rollback = 0;
6793         unsigned alloc_size;
6794         int sort_clone_roots = 0;
6795         int index;
6796
6797         if (!capable(CAP_SYS_ADMIN))
6798                 return -EPERM;
6799
6800         /*
6801          * The subvolume must remain read-only during send, protect against
6802          * making it RW. This also protects against deletion.
6803          */
6804         spin_lock(&send_root->root_item_lock);
6805         send_root->send_in_progress++;
6806         spin_unlock(&send_root->root_item_lock);
6807
6808         /*
6809          * Userspace tools do the checks and warn the user if it's
6810          * not RO.
6811          */
6812         if (!btrfs_root_readonly(send_root)) {
6813                 ret = -EPERM;
6814                 goto out;
6815         }
6816
6817         /*
6818          * Check that we don't overflow at later allocations, we request
6819          * clone_sources_count + 1 items, and compare to unsigned long inside
6820          * access_ok.
6821          */
6822         if (arg->clone_sources_count >
6823             ULONG_MAX / sizeof(struct clone_root) - 1) {
6824                 ret = -EINVAL;
6825                 goto out;
6826         }
6827
6828         if (!access_ok(VERIFY_READ, arg->clone_sources,
6829                         sizeof(*arg->clone_sources) *
6830                         arg->clone_sources_count)) {
6831                 ret = -EFAULT;
6832                 goto out;
6833         }
6834
6835         if (arg->flags & ~BTRFS_SEND_FLAG_MASK) {
6836                 ret = -EINVAL;
6837                 goto out;
6838         }
6839
6840         sctx = kzalloc(sizeof(struct send_ctx), GFP_KERNEL);
6841         if (!sctx) {
6842                 ret = -ENOMEM;
6843                 goto out;
6844         }
6845
6846         INIT_LIST_HEAD(&sctx->new_refs);
6847         INIT_LIST_HEAD(&sctx->deleted_refs);
6848         INIT_RADIX_TREE(&sctx->name_cache, GFP_KERNEL);
6849         INIT_LIST_HEAD(&sctx->name_cache_list);
6850
6851         sctx->flags = arg->flags;
6852
6853         sctx->send_filp = fget(arg->send_fd);
6854         if (!sctx->send_filp) {
6855                 ret = -EBADF;
6856                 goto out;
6857         }
6858
6859         sctx->send_root = send_root;
6860         /*
6861          * Unlikely but possible, if the subvolume is marked for deletion but
6862          * is slow to remove the directory entry, send can still be started
6863          */
6864         if (btrfs_root_dead(sctx->send_root)) {
6865                 ret = -EPERM;
6866                 goto out;
6867         }
6868
6869         sctx->clone_roots_cnt = arg->clone_sources_count;
6870
6871         sctx->send_max_size = BTRFS_SEND_BUF_SIZE;
6872         sctx->send_buf = kvmalloc(sctx->send_max_size, GFP_KERNEL);
6873         if (!sctx->send_buf) {
6874                 ret = -ENOMEM;
6875                 goto out;
6876         }
6877
6878         sctx->read_buf = kvmalloc(BTRFS_SEND_READ_SIZE, GFP_KERNEL);
6879         if (!sctx->read_buf) {
6880                 ret = -ENOMEM;
6881                 goto out;
6882         }
6883
6884         sctx->pending_dir_moves = RB_ROOT;
6885         sctx->waiting_dir_moves = RB_ROOT;
6886         sctx->orphan_dirs = RB_ROOT;
6887
6888         alloc_size = sizeof(struct clone_root) * (arg->clone_sources_count + 1);
6889
6890         sctx->clone_roots = kvzalloc(alloc_size, GFP_KERNEL);
6891         if (!sctx->clone_roots) {
6892                 ret = -ENOMEM;
6893                 goto out;
6894         }
6895
6896         alloc_size = arg->clone_sources_count * sizeof(*arg->clone_sources);
6897
6898         if (arg->clone_sources_count) {
6899                 clone_sources_tmp = kvmalloc(alloc_size, GFP_KERNEL);
6900                 if (!clone_sources_tmp) {
6901                         ret = -ENOMEM;
6902                         goto out;
6903                 }
6904
6905                 ret = copy_from_user(clone_sources_tmp, arg->clone_sources,
6906                                 alloc_size);
6907                 if (ret) {
6908                         ret = -EFAULT;
6909                         goto out;
6910                 }
6911
6912                 for (i = 0; i < arg->clone_sources_count; i++) {
6913                         key.objectid = clone_sources_tmp[i];
6914                         key.type = BTRFS_ROOT_ITEM_KEY;
6915                         key.offset = (u64)-1;
6916
6917                         index = srcu_read_lock(&fs_info->subvol_srcu);
6918
6919                         clone_root = btrfs_read_fs_root_no_name(fs_info, &key);
6920                         if (IS_ERR(clone_root)) {
6921                                 srcu_read_unlock(&fs_info->subvol_srcu, index);
6922                                 ret = PTR_ERR(clone_root);
6923                                 goto out;
6924                         }
6925                         spin_lock(&clone_root->root_item_lock);
6926                         if (!btrfs_root_readonly(clone_root) ||
6927                             btrfs_root_dead(clone_root)) {
6928                                 spin_unlock(&clone_root->root_item_lock);
6929                                 srcu_read_unlock(&fs_info->subvol_srcu, index);
6930                                 ret = -EPERM;
6931                                 goto out;
6932                         }
6933                         clone_root->send_in_progress++;
6934                         spin_unlock(&clone_root->root_item_lock);
6935                         srcu_read_unlock(&fs_info->subvol_srcu, index);
6936
6937                         sctx->clone_roots[i].root = clone_root;
6938                         clone_sources_to_rollback = i + 1;
6939                 }
6940                 kvfree(clone_sources_tmp);
6941                 clone_sources_tmp = NULL;
6942         }
6943
6944         if (arg->parent_root) {
6945                 key.objectid = arg->parent_root;
6946                 key.type = BTRFS_ROOT_ITEM_KEY;
6947                 key.offset = (u64)-1;
6948
6949                 index = srcu_read_lock(&fs_info->subvol_srcu);
6950
6951                 sctx->parent_root = btrfs_read_fs_root_no_name(fs_info, &key);
6952                 if (IS_ERR(sctx->parent_root)) {
6953                         srcu_read_unlock(&fs_info->subvol_srcu, index);
6954                         ret = PTR_ERR(sctx->parent_root);
6955                         goto out;
6956                 }
6957
6958                 spin_lock(&sctx->parent_root->root_item_lock);
6959                 sctx->parent_root->send_in_progress++;
6960                 if (!btrfs_root_readonly(sctx->parent_root) ||
6961                                 btrfs_root_dead(sctx->parent_root)) {
6962                         spin_unlock(&sctx->parent_root->root_item_lock);
6963                         srcu_read_unlock(&fs_info->subvol_srcu, index);
6964                         ret = -EPERM;
6965                         goto out;
6966                 }
6967                 spin_unlock(&sctx->parent_root->root_item_lock);
6968
6969                 srcu_read_unlock(&fs_info->subvol_srcu, index);
6970         }
6971
6972         /*
6973          * Clones from send_root are allowed, but only if the clone source
6974          * is behind the current send position. This is checked while searching
6975          * for possible clone sources.
6976          */
6977         sctx->clone_roots[sctx->clone_roots_cnt++].root = sctx->send_root;
6978
6979         /* We do a bsearch later */
6980         sort(sctx->clone_roots, sctx->clone_roots_cnt,
6981                         sizeof(*sctx->clone_roots), __clone_root_cmp_sort,
6982                         NULL);
6983         sort_clone_roots = 1;
6984
6985         ret = flush_delalloc_roots(sctx);
6986         if (ret)
6987                 goto out;
6988
6989         ret = ensure_commit_roots_uptodate(sctx);
6990         if (ret)
6991                 goto out;
6992
6993         current->journal_info = BTRFS_SEND_TRANS_STUB;
6994         ret = send_subvol(sctx);
6995         current->journal_info = NULL;
6996         if (ret < 0)
6997                 goto out;
6998
6999         if (!(sctx->flags & BTRFS_SEND_FLAG_OMIT_END_CMD)) {
7000                 ret = begin_cmd(sctx, BTRFS_SEND_C_END);
7001                 if (ret < 0)
7002                         goto out;
7003                 ret = send_cmd(sctx);
7004                 if (ret < 0)
7005                         goto out;
7006         }
7007
7008 out:
7009         WARN_ON(sctx && !ret && !RB_EMPTY_ROOT(&sctx->pending_dir_moves));
7010         while (sctx && !RB_EMPTY_ROOT(&sctx->pending_dir_moves)) {
7011                 struct rb_node *n;
7012                 struct pending_dir_move *pm;
7013
7014                 n = rb_first(&sctx->pending_dir_moves);
7015                 pm = rb_entry(n, struct pending_dir_move, node);
7016                 while (!list_empty(&pm->list)) {
7017                         struct pending_dir_move *pm2;
7018
7019                         pm2 = list_first_entry(&pm->list,
7020                                                struct pending_dir_move, list);
7021                         free_pending_move(sctx, pm2);
7022                 }
7023                 free_pending_move(sctx, pm);
7024         }
7025
7026         WARN_ON(sctx && !ret && !RB_EMPTY_ROOT(&sctx->waiting_dir_moves));
7027         while (sctx && !RB_EMPTY_ROOT(&sctx->waiting_dir_moves)) {
7028                 struct rb_node *n;
7029                 struct waiting_dir_move *dm;
7030
7031                 n = rb_first(&sctx->waiting_dir_moves);
7032                 dm = rb_entry(n, struct waiting_dir_move, node);
7033                 rb_erase(&dm->node, &sctx->waiting_dir_moves);
7034                 kfree(dm);
7035         }
7036
7037         WARN_ON(sctx && !ret && !RB_EMPTY_ROOT(&sctx->orphan_dirs));
7038         while (sctx && !RB_EMPTY_ROOT(&sctx->orphan_dirs)) {
7039                 struct rb_node *n;
7040                 struct orphan_dir_info *odi;
7041
7042                 n = rb_first(&sctx->orphan_dirs);
7043                 odi = rb_entry(n, struct orphan_dir_info, node);
7044                 free_orphan_dir_info(sctx, odi);
7045         }
7046
7047         if (sort_clone_roots) {
7048                 for (i = 0; i < sctx->clone_roots_cnt; i++)
7049                         btrfs_root_dec_send_in_progress(
7050                                         sctx->clone_roots[i].root);
7051         } else {
7052                 for (i = 0; sctx && i < clone_sources_to_rollback; i++)
7053                         btrfs_root_dec_send_in_progress(
7054                                         sctx->clone_roots[i].root);
7055
7056                 btrfs_root_dec_send_in_progress(send_root);
7057         }
7058         if (sctx && !IS_ERR_OR_NULL(sctx->parent_root))
7059                 btrfs_root_dec_send_in_progress(sctx->parent_root);
7060
7061         kvfree(clone_sources_tmp);
7062
7063         if (sctx) {
7064                 if (sctx->send_filp)
7065                         fput(sctx->send_filp);
7066
7067                 kvfree(sctx->clone_roots);
7068                 kvfree(sctx->send_buf);
7069                 kvfree(sctx->read_buf);
7070
7071                 name_cache_free(sctx);
7072
7073                 kfree(sctx);
7074         }
7075
7076         return ret;
7077 }