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