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