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