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