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