]> git.karo-electronics.de Git - karo-tx-linux.git/blob - fs/btrfs/send.c
Btrfs: fix csum tree corruption, duplicate and outdated checksums
[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         if (key.type == BTRFS_ROOT_ITEM_KEY) {
1593                 ret = -ENOENT;
1594                 goto out;
1595         }
1596         *found_inode = key.objectid;
1597         *found_type = btrfs_dir_type(path->nodes[0], di);
1598
1599 out:
1600         btrfs_free_path(path);
1601         return ret;
1602 }
1603
1604 /*
1605  * Looks up the first btrfs_inode_ref of a given ino. It returns the parent dir,
1606  * generation of the parent dir and the name of the dir entry.
1607  */
1608 static int get_first_ref(struct btrfs_root *root, u64 ino,
1609                          u64 *dir, u64 *dir_gen, struct fs_path *name)
1610 {
1611         int ret;
1612         struct btrfs_key key;
1613         struct btrfs_key found_key;
1614         struct btrfs_path *path;
1615         int len;
1616         u64 parent_dir;
1617
1618         path = alloc_path_for_send();
1619         if (!path)
1620                 return -ENOMEM;
1621
1622         key.objectid = ino;
1623         key.type = BTRFS_INODE_REF_KEY;
1624         key.offset = 0;
1625
1626         ret = btrfs_search_slot_for_read(root, &key, path, 1, 0);
1627         if (ret < 0)
1628                 goto out;
1629         if (!ret)
1630                 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1631                                 path->slots[0]);
1632         if (ret || found_key.objectid != ino ||
1633             (found_key.type != BTRFS_INODE_REF_KEY &&
1634              found_key.type != BTRFS_INODE_EXTREF_KEY)) {
1635                 ret = -ENOENT;
1636                 goto out;
1637         }
1638
1639         if (key.type == BTRFS_INODE_REF_KEY) {
1640                 struct btrfs_inode_ref *iref;
1641                 iref = btrfs_item_ptr(path->nodes[0], path->slots[0],
1642                                       struct btrfs_inode_ref);
1643                 len = btrfs_inode_ref_name_len(path->nodes[0], iref);
1644                 ret = fs_path_add_from_extent_buffer(name, path->nodes[0],
1645                                                      (unsigned long)(iref + 1),
1646                                                      len);
1647                 parent_dir = found_key.offset;
1648         } else {
1649                 struct btrfs_inode_extref *extref;
1650                 extref = btrfs_item_ptr(path->nodes[0], path->slots[0],
1651                                         struct btrfs_inode_extref);
1652                 len = btrfs_inode_extref_name_len(path->nodes[0], extref);
1653                 ret = fs_path_add_from_extent_buffer(name, path->nodes[0],
1654                                         (unsigned long)&extref->name, len);
1655                 parent_dir = btrfs_inode_extref_parent(path->nodes[0], extref);
1656         }
1657         if (ret < 0)
1658                 goto out;
1659         btrfs_release_path(path);
1660
1661         ret = get_inode_info(root, parent_dir, NULL, dir_gen, NULL, NULL,
1662                         NULL, NULL);
1663         if (ret < 0)
1664                 goto out;
1665
1666         *dir = parent_dir;
1667
1668 out:
1669         btrfs_free_path(path);
1670         return ret;
1671 }
1672
1673 static int is_first_ref(struct btrfs_root *root,
1674                         u64 ino, u64 dir,
1675                         const char *name, int name_len)
1676 {
1677         int ret;
1678         struct fs_path *tmp_name;
1679         u64 tmp_dir;
1680         u64 tmp_dir_gen;
1681
1682         tmp_name = fs_path_alloc();
1683         if (!tmp_name)
1684                 return -ENOMEM;
1685
1686         ret = get_first_ref(root, ino, &tmp_dir, &tmp_dir_gen, tmp_name);
1687         if (ret < 0)
1688                 goto out;
1689
1690         if (dir != tmp_dir || name_len != fs_path_len(tmp_name)) {
1691                 ret = 0;
1692                 goto out;
1693         }
1694
1695         ret = !memcmp(tmp_name->start, name, name_len);
1696
1697 out:
1698         fs_path_free(tmp_name);
1699         return ret;
1700 }
1701
1702 /*
1703  * Used by process_recorded_refs to determine if a new ref would overwrite an
1704  * already existing ref. In case it detects an overwrite, it returns the
1705  * inode/gen in who_ino/who_gen.
1706  * When an overwrite is detected, process_recorded_refs does proper orphanizing
1707  * to make sure later references to the overwritten inode are possible.
1708  * Orphanizing is however only required for the first ref of an inode.
1709  * process_recorded_refs does an additional is_first_ref check to see if
1710  * orphanizing is really required.
1711  */
1712 static int will_overwrite_ref(struct send_ctx *sctx, u64 dir, u64 dir_gen,
1713                               const char *name, int name_len,
1714                               u64 *who_ino, u64 *who_gen)
1715 {
1716         int ret = 0;
1717         u64 gen;
1718         u64 other_inode = 0;
1719         u8 other_type = 0;
1720
1721         if (!sctx->parent_root)
1722                 goto out;
1723
1724         ret = is_inode_existent(sctx, dir, dir_gen);
1725         if (ret <= 0)
1726                 goto out;
1727
1728         /*
1729          * If we have a parent root we need to verify that the parent dir was
1730          * not delted and then re-created, if it was then we have no overwrite
1731          * and we can just unlink this entry.
1732          */
1733         if (sctx->parent_root) {
1734                 ret = get_inode_info(sctx->parent_root, dir, NULL, &gen, NULL,
1735                                      NULL, NULL, NULL);
1736                 if (ret < 0 && ret != -ENOENT)
1737                         goto out;
1738                 if (ret) {
1739                         ret = 0;
1740                         goto out;
1741                 }
1742                 if (gen != dir_gen)
1743                         goto out;
1744         }
1745
1746         ret = lookup_dir_item_inode(sctx->parent_root, dir, name, name_len,
1747                         &other_inode, &other_type);
1748         if (ret < 0 && ret != -ENOENT)
1749                 goto out;
1750         if (ret) {
1751                 ret = 0;
1752                 goto out;
1753         }
1754
1755         /*
1756          * Check if the overwritten ref was already processed. If yes, the ref
1757          * was already unlinked/moved, so we can safely assume that we will not
1758          * overwrite anything at this point in time.
1759          */
1760         if (other_inode > sctx->send_progress) {
1761                 ret = get_inode_info(sctx->parent_root, other_inode, NULL,
1762                                 who_gen, NULL, NULL, NULL, NULL);
1763                 if (ret < 0)
1764                         goto out;
1765
1766                 ret = 1;
1767                 *who_ino = other_inode;
1768         } else {
1769                 ret = 0;
1770         }
1771
1772 out:
1773         return ret;
1774 }
1775
1776 /*
1777  * Checks if the ref was overwritten by an already processed inode. This is
1778  * used by __get_cur_name_and_parent to find out if the ref was orphanized and
1779  * thus the orphan name needs be used.
1780  * process_recorded_refs also uses it to avoid unlinking of refs that were
1781  * overwritten.
1782  */
1783 static int did_overwrite_ref(struct send_ctx *sctx,
1784                             u64 dir, u64 dir_gen,
1785                             u64 ino, u64 ino_gen,
1786                             const char *name, int name_len)
1787 {
1788         int ret = 0;
1789         u64 gen;
1790         u64 ow_inode;
1791         u8 other_type;
1792
1793         if (!sctx->parent_root)
1794                 goto out;
1795
1796         ret = is_inode_existent(sctx, dir, dir_gen);
1797         if (ret <= 0)
1798                 goto out;
1799
1800         /* check if the ref was overwritten by another ref */
1801         ret = lookup_dir_item_inode(sctx->send_root, dir, name, name_len,
1802                         &ow_inode, &other_type);
1803         if (ret < 0 && ret != -ENOENT)
1804                 goto out;
1805         if (ret) {
1806                 /* was never and will never be overwritten */
1807                 ret = 0;
1808                 goto out;
1809         }
1810
1811         ret = get_inode_info(sctx->send_root, ow_inode, NULL, &gen, NULL, NULL,
1812                         NULL, NULL);
1813         if (ret < 0)
1814                 goto out;
1815
1816         if (ow_inode == ino && gen == ino_gen) {
1817                 ret = 0;
1818                 goto out;
1819         }
1820
1821         /* we know that it is or will be overwritten. check this now */
1822         if (ow_inode < sctx->send_progress)
1823                 ret = 1;
1824         else
1825                 ret = 0;
1826
1827 out:
1828         return ret;
1829 }
1830
1831 /*
1832  * Same as did_overwrite_ref, but also checks if it is the first ref of an inode
1833  * that got overwritten. This is used by process_recorded_refs to determine
1834  * if it has to use the path as returned by get_cur_path or the orphan name.
1835  */
1836 static int did_overwrite_first_ref(struct send_ctx *sctx, u64 ino, u64 gen)
1837 {
1838         int ret = 0;
1839         struct fs_path *name = NULL;
1840         u64 dir;
1841         u64 dir_gen;
1842
1843         if (!sctx->parent_root)
1844                 goto out;
1845
1846         name = fs_path_alloc();
1847         if (!name)
1848                 return -ENOMEM;
1849
1850         ret = get_first_ref(sctx->parent_root, ino, &dir, &dir_gen, name);
1851         if (ret < 0)
1852                 goto out;
1853
1854         ret = did_overwrite_ref(sctx, dir, dir_gen, ino, gen,
1855                         name->start, fs_path_len(name));
1856
1857 out:
1858         fs_path_free(name);
1859         return ret;
1860 }
1861
1862 /*
1863  * Insert a name cache entry. On 32bit kernels the radix tree index is 32bit,
1864  * so we need to do some special handling in case we have clashes. This function
1865  * takes care of this with the help of name_cache_entry::radix_list.
1866  * In case of error, nce is kfreed.
1867  */
1868 static int name_cache_insert(struct send_ctx *sctx,
1869                              struct name_cache_entry *nce)
1870 {
1871         int ret = 0;
1872         struct list_head *nce_head;
1873
1874         nce_head = radix_tree_lookup(&sctx->name_cache,
1875                         (unsigned long)nce->ino);
1876         if (!nce_head) {
1877                 nce_head = kmalloc(sizeof(*nce_head), GFP_NOFS);
1878                 if (!nce_head) {
1879                         kfree(nce);
1880                         return -ENOMEM;
1881                 }
1882                 INIT_LIST_HEAD(nce_head);
1883
1884                 ret = radix_tree_insert(&sctx->name_cache, nce->ino, nce_head);
1885                 if (ret < 0) {
1886                         kfree(nce_head);
1887                         kfree(nce);
1888                         return ret;
1889                 }
1890         }
1891         list_add_tail(&nce->radix_list, nce_head);
1892         list_add_tail(&nce->list, &sctx->name_cache_list);
1893         sctx->name_cache_size++;
1894
1895         return ret;
1896 }
1897
1898 static void name_cache_delete(struct send_ctx *sctx,
1899                               struct name_cache_entry *nce)
1900 {
1901         struct list_head *nce_head;
1902
1903         nce_head = radix_tree_lookup(&sctx->name_cache,
1904                         (unsigned long)nce->ino);
1905         BUG_ON(!nce_head);
1906
1907         list_del(&nce->radix_list);
1908         list_del(&nce->list);
1909         sctx->name_cache_size--;
1910
1911         if (list_empty(nce_head)) {
1912                 radix_tree_delete(&sctx->name_cache, (unsigned long)nce->ino);
1913                 kfree(nce_head);
1914         }
1915 }
1916
1917 static struct name_cache_entry *name_cache_search(struct send_ctx *sctx,
1918                                                     u64 ino, u64 gen)
1919 {
1920         struct list_head *nce_head;
1921         struct name_cache_entry *cur;
1922
1923         nce_head = radix_tree_lookup(&sctx->name_cache, (unsigned long)ino);
1924         if (!nce_head)
1925                 return NULL;
1926
1927         list_for_each_entry(cur, nce_head, radix_list) {
1928                 if (cur->ino == ino && cur->gen == gen)
1929                         return cur;
1930         }
1931         return NULL;
1932 }
1933
1934 /*
1935  * Removes the entry from the list and adds it back to the end. This marks the
1936  * entry as recently used so that name_cache_clean_unused does not remove it.
1937  */
1938 static void name_cache_used(struct send_ctx *sctx, struct name_cache_entry *nce)
1939 {
1940         list_del(&nce->list);
1941         list_add_tail(&nce->list, &sctx->name_cache_list);
1942 }
1943
1944 /*
1945  * Remove some entries from the beginning of name_cache_list.
1946  */
1947 static void name_cache_clean_unused(struct send_ctx *sctx)
1948 {
1949         struct name_cache_entry *nce;
1950
1951         if (sctx->name_cache_size < SEND_CTX_NAME_CACHE_CLEAN_SIZE)
1952                 return;
1953
1954         while (sctx->name_cache_size > SEND_CTX_MAX_NAME_CACHE_SIZE) {
1955                 nce = list_entry(sctx->name_cache_list.next,
1956                                 struct name_cache_entry, list);
1957                 name_cache_delete(sctx, nce);
1958                 kfree(nce);
1959         }
1960 }
1961
1962 static void name_cache_free(struct send_ctx *sctx)
1963 {
1964         struct name_cache_entry *nce;
1965
1966         while (!list_empty(&sctx->name_cache_list)) {
1967                 nce = list_entry(sctx->name_cache_list.next,
1968                                 struct name_cache_entry, list);
1969                 name_cache_delete(sctx, nce);
1970                 kfree(nce);
1971         }
1972 }
1973
1974 /*
1975  * Used by get_cur_path for each ref up to the root.
1976  * Returns 0 if it succeeded.
1977  * Returns 1 if the inode is not existent or got overwritten. In that case, the
1978  * name is an orphan name. This instructs get_cur_path to stop iterating. If 1
1979  * is returned, parent_ino/parent_gen are not guaranteed to be valid.
1980  * Returns <0 in case of error.
1981  */
1982 static int __get_cur_name_and_parent(struct send_ctx *sctx,
1983                                      u64 ino, u64 gen,
1984                                      int skip_name_cache,
1985                                      u64 *parent_ino,
1986                                      u64 *parent_gen,
1987                                      struct fs_path *dest)
1988 {
1989         int ret;
1990         int nce_ret;
1991         struct btrfs_path *path = NULL;
1992         struct name_cache_entry *nce = NULL;
1993
1994         if (skip_name_cache)
1995                 goto get_ref;
1996         /*
1997          * First check if we already did a call to this function with the same
1998          * ino/gen. If yes, check if the cache entry is still up-to-date. If yes
1999          * return the cached result.
2000          */
2001         nce = name_cache_search(sctx, ino, gen);
2002         if (nce) {
2003                 if (ino < sctx->send_progress && nce->need_later_update) {
2004                         name_cache_delete(sctx, nce);
2005                         kfree(nce);
2006                         nce = NULL;
2007                 } else {
2008                         name_cache_used(sctx, nce);
2009                         *parent_ino = nce->parent_ino;
2010                         *parent_gen = nce->parent_gen;
2011                         ret = fs_path_add(dest, nce->name, nce->name_len);
2012                         if (ret < 0)
2013                                 goto out;
2014                         ret = nce->ret;
2015                         goto out;
2016                 }
2017         }
2018
2019         path = alloc_path_for_send();
2020         if (!path)
2021                 return -ENOMEM;
2022
2023         /*
2024          * If the inode is not existent yet, add the orphan name and return 1.
2025          * This should only happen for the parent dir that we determine in
2026          * __record_new_ref
2027          */
2028         ret = is_inode_existent(sctx, ino, gen);
2029         if (ret < 0)
2030                 goto out;
2031
2032         if (!ret) {
2033                 ret = gen_unique_name(sctx, ino, gen, dest);
2034                 if (ret < 0)
2035                         goto out;
2036                 ret = 1;
2037                 goto out_cache;
2038         }
2039
2040 get_ref:
2041         /*
2042          * Depending on whether the inode was already processed or not, use
2043          * send_root or parent_root for ref lookup.
2044          */
2045         if (ino < sctx->send_progress && !skip_name_cache)
2046                 ret = get_first_ref(sctx->send_root, ino,
2047                                     parent_ino, parent_gen, dest);
2048         else
2049                 ret = get_first_ref(sctx->parent_root, ino,
2050                                     parent_ino, parent_gen, dest);
2051         if (ret < 0)
2052                 goto out;
2053
2054         /*
2055          * Check if the ref was overwritten by an inode's ref that was processed
2056          * earlier. If yes, treat as orphan and return 1.
2057          */
2058         ret = did_overwrite_ref(sctx, *parent_ino, *parent_gen, ino, gen,
2059                         dest->start, dest->end - dest->start);
2060         if (ret < 0)
2061                 goto out;
2062         if (ret) {
2063                 fs_path_reset(dest);
2064                 ret = gen_unique_name(sctx, ino, gen, dest);
2065                 if (ret < 0)
2066                         goto out;
2067                 ret = 1;
2068         }
2069         if (skip_name_cache)
2070                 goto out;
2071
2072 out_cache:
2073         /*
2074          * Store the result of the lookup in the name cache.
2075          */
2076         nce = kmalloc(sizeof(*nce) + fs_path_len(dest) + 1, GFP_NOFS);
2077         if (!nce) {
2078                 ret = -ENOMEM;
2079                 goto out;
2080         }
2081
2082         nce->ino = ino;
2083         nce->gen = gen;
2084         nce->parent_ino = *parent_ino;
2085         nce->parent_gen = *parent_gen;
2086         nce->name_len = fs_path_len(dest);
2087         nce->ret = ret;
2088         strcpy(nce->name, dest->start);
2089
2090         if (ino < sctx->send_progress)
2091                 nce->need_later_update = 0;
2092         else
2093                 nce->need_later_update = 1;
2094
2095         nce_ret = name_cache_insert(sctx, nce);
2096         if (nce_ret < 0)
2097                 ret = nce_ret;
2098         name_cache_clean_unused(sctx);
2099
2100 out:
2101         btrfs_free_path(path);
2102         return ret;
2103 }
2104
2105 /*
2106  * Magic happens here. This function returns the first ref to an inode as it
2107  * would look like while receiving the stream at this point in time.
2108  * We walk the path up to the root. For every inode in between, we check if it
2109  * was already processed/sent. If yes, we continue with the parent as found
2110  * in send_root. If not, we continue with the parent as found in parent_root.
2111  * If we encounter an inode that was deleted at this point in time, we use the
2112  * inodes "orphan" name instead of the real name and stop. Same with new inodes
2113  * that were not created yet and overwritten inodes/refs.
2114  *
2115  * When do we have have orphan inodes:
2116  * 1. When an inode is freshly created and thus no valid refs are available yet
2117  * 2. When a directory lost all it's refs (deleted) but still has dir items
2118  *    inside which were not processed yet (pending for move/delete). If anyone
2119  *    tried to get the path to the dir items, it would get a path inside that
2120  *    orphan directory.
2121  * 3. When an inode is moved around or gets new links, it may overwrite the ref
2122  *    of an unprocessed inode. If in that case the first ref would be
2123  *    overwritten, the overwritten inode gets "orphanized". Later when we
2124  *    process this overwritten inode, it is restored at a new place by moving
2125  *    the orphan inode.
2126  *
2127  * sctx->send_progress tells this function at which point in time receiving
2128  * would be.
2129  */
2130 static int get_cur_path(struct send_ctx *sctx, u64 ino, u64 gen,
2131                         struct fs_path *dest)
2132 {
2133         int ret = 0;
2134         struct fs_path *name = NULL;
2135         u64 parent_inode = 0;
2136         u64 parent_gen = 0;
2137         int stop = 0;
2138         u64 start_ino = ino;
2139         u64 start_gen = gen;
2140         int skip_name_cache = 0;
2141
2142         name = fs_path_alloc();
2143         if (!name) {
2144                 ret = -ENOMEM;
2145                 goto out;
2146         }
2147
2148         if (is_waiting_for_move(sctx, ino))
2149                 skip_name_cache = 1;
2150
2151 again:
2152         dest->reversed = 1;
2153         fs_path_reset(dest);
2154
2155         while (!stop && ino != BTRFS_FIRST_FREE_OBJECTID) {
2156                 fs_path_reset(name);
2157
2158                 ret = __get_cur_name_and_parent(sctx, ino, gen, skip_name_cache,
2159                                 &parent_inode, &parent_gen, name);
2160                 if (ret < 0)
2161                         goto out;
2162                 if (ret)
2163                         stop = 1;
2164
2165                 if (!skip_name_cache &&
2166                     is_waiting_for_move(sctx, parent_inode)) {
2167                         ino = start_ino;
2168                         gen = start_gen;
2169                         stop = 0;
2170                         skip_name_cache = 1;
2171                         goto again;
2172                 }
2173
2174                 ret = fs_path_add_path(dest, name);
2175                 if (ret < 0)
2176                         goto out;
2177
2178                 ino = parent_inode;
2179                 gen = parent_gen;
2180         }
2181
2182 out:
2183         fs_path_free(name);
2184         if (!ret)
2185                 fs_path_unreverse(dest);
2186         return ret;
2187 }
2188
2189 /*
2190  * Sends a BTRFS_SEND_C_SUBVOL command/item to userspace
2191  */
2192 static int send_subvol_begin(struct send_ctx *sctx)
2193 {
2194         int ret;
2195         struct btrfs_root *send_root = sctx->send_root;
2196         struct btrfs_root *parent_root = sctx->parent_root;
2197         struct btrfs_path *path;
2198         struct btrfs_key key;
2199         struct btrfs_root_ref *ref;
2200         struct extent_buffer *leaf;
2201         char *name = NULL;
2202         int namelen;
2203
2204         path = btrfs_alloc_path();
2205         if (!path)
2206                 return -ENOMEM;
2207
2208         name = kmalloc(BTRFS_PATH_NAME_MAX, GFP_NOFS);
2209         if (!name) {
2210                 btrfs_free_path(path);
2211                 return -ENOMEM;
2212         }
2213
2214         key.objectid = send_root->objectid;
2215         key.type = BTRFS_ROOT_BACKREF_KEY;
2216         key.offset = 0;
2217
2218         ret = btrfs_search_slot_for_read(send_root->fs_info->tree_root,
2219                                 &key, path, 1, 0);
2220         if (ret < 0)
2221                 goto out;
2222         if (ret) {
2223                 ret = -ENOENT;
2224                 goto out;
2225         }
2226
2227         leaf = path->nodes[0];
2228         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2229         if (key.type != BTRFS_ROOT_BACKREF_KEY ||
2230             key.objectid != send_root->objectid) {
2231                 ret = -ENOENT;
2232                 goto out;
2233         }
2234         ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
2235         namelen = btrfs_root_ref_name_len(leaf, ref);
2236         read_extent_buffer(leaf, name, (unsigned long)(ref + 1), namelen);
2237         btrfs_release_path(path);
2238
2239         if (parent_root) {
2240                 ret = begin_cmd(sctx, BTRFS_SEND_C_SNAPSHOT);
2241                 if (ret < 0)
2242                         goto out;
2243         } else {
2244                 ret = begin_cmd(sctx, BTRFS_SEND_C_SUBVOL);
2245                 if (ret < 0)
2246                         goto out;
2247         }
2248
2249         TLV_PUT_STRING(sctx, BTRFS_SEND_A_PATH, name, namelen);
2250         TLV_PUT_UUID(sctx, BTRFS_SEND_A_UUID,
2251                         sctx->send_root->root_item.uuid);
2252         TLV_PUT_U64(sctx, BTRFS_SEND_A_CTRANSID,
2253                     le64_to_cpu(sctx->send_root->root_item.ctransid));
2254         if (parent_root) {
2255                 TLV_PUT_UUID(sctx, BTRFS_SEND_A_CLONE_UUID,
2256                                 sctx->parent_root->root_item.uuid);
2257                 TLV_PUT_U64(sctx, BTRFS_SEND_A_CLONE_CTRANSID,
2258                             le64_to_cpu(sctx->parent_root->root_item.ctransid));
2259         }
2260
2261         ret = send_cmd(sctx);
2262
2263 tlv_put_failure:
2264 out:
2265         btrfs_free_path(path);
2266         kfree(name);
2267         return ret;
2268 }
2269
2270 static int send_truncate(struct send_ctx *sctx, u64 ino, u64 gen, u64 size)
2271 {
2272         int ret = 0;
2273         struct fs_path *p;
2274
2275 verbose_printk("btrfs: send_truncate %llu size=%llu\n", ino, size);
2276
2277         p = fs_path_alloc();
2278         if (!p)
2279                 return -ENOMEM;
2280
2281         ret = begin_cmd(sctx, BTRFS_SEND_C_TRUNCATE);
2282         if (ret < 0)
2283                 goto out;
2284
2285         ret = get_cur_path(sctx, ino, gen, p);
2286         if (ret < 0)
2287                 goto out;
2288         TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
2289         TLV_PUT_U64(sctx, BTRFS_SEND_A_SIZE, size);
2290
2291         ret = send_cmd(sctx);
2292
2293 tlv_put_failure:
2294 out:
2295         fs_path_free(p);
2296         return ret;
2297 }
2298
2299 static int send_chmod(struct send_ctx *sctx, u64 ino, u64 gen, u64 mode)
2300 {
2301         int ret = 0;
2302         struct fs_path *p;
2303
2304 verbose_printk("btrfs: send_chmod %llu mode=%llu\n", ino, mode);
2305
2306         p = fs_path_alloc();
2307         if (!p)
2308                 return -ENOMEM;
2309
2310         ret = begin_cmd(sctx, BTRFS_SEND_C_CHMOD);
2311         if (ret < 0)
2312                 goto out;
2313
2314         ret = get_cur_path(sctx, ino, gen, p);
2315         if (ret < 0)
2316                 goto out;
2317         TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
2318         TLV_PUT_U64(sctx, BTRFS_SEND_A_MODE, mode & 07777);
2319
2320         ret = send_cmd(sctx);
2321
2322 tlv_put_failure:
2323 out:
2324         fs_path_free(p);
2325         return ret;
2326 }
2327
2328 static int send_chown(struct send_ctx *sctx, u64 ino, u64 gen, u64 uid, u64 gid)
2329 {
2330         int ret = 0;
2331         struct fs_path *p;
2332
2333 verbose_printk("btrfs: send_chown %llu uid=%llu, gid=%llu\n", ino, uid, gid);
2334
2335         p = fs_path_alloc();
2336         if (!p)
2337                 return -ENOMEM;
2338
2339         ret = begin_cmd(sctx, BTRFS_SEND_C_CHOWN);
2340         if (ret < 0)
2341                 goto out;
2342
2343         ret = get_cur_path(sctx, ino, gen, p);
2344         if (ret < 0)
2345                 goto out;
2346         TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
2347         TLV_PUT_U64(sctx, BTRFS_SEND_A_UID, uid);
2348         TLV_PUT_U64(sctx, BTRFS_SEND_A_GID, gid);
2349
2350         ret = send_cmd(sctx);
2351
2352 tlv_put_failure:
2353 out:
2354         fs_path_free(p);
2355         return ret;
2356 }
2357
2358 static int send_utimes(struct send_ctx *sctx, u64 ino, u64 gen)
2359 {
2360         int ret = 0;
2361         struct fs_path *p = NULL;
2362         struct btrfs_inode_item *ii;
2363         struct btrfs_path *path = NULL;
2364         struct extent_buffer *eb;
2365         struct btrfs_key key;
2366         int slot;
2367
2368 verbose_printk("btrfs: send_utimes %llu\n", ino);
2369
2370         p = fs_path_alloc();
2371         if (!p)
2372                 return -ENOMEM;
2373
2374         path = alloc_path_for_send();
2375         if (!path) {
2376                 ret = -ENOMEM;
2377                 goto out;
2378         }
2379
2380         key.objectid = ino;
2381         key.type = BTRFS_INODE_ITEM_KEY;
2382         key.offset = 0;
2383         ret = btrfs_search_slot(NULL, sctx->send_root, &key, path, 0, 0);
2384         if (ret < 0)
2385                 goto out;
2386
2387         eb = path->nodes[0];
2388         slot = path->slots[0];
2389         ii = btrfs_item_ptr(eb, slot, struct btrfs_inode_item);
2390
2391         ret = begin_cmd(sctx, BTRFS_SEND_C_UTIMES);
2392         if (ret < 0)
2393                 goto out;
2394
2395         ret = get_cur_path(sctx, ino, gen, p);
2396         if (ret < 0)
2397                 goto out;
2398         TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
2399         TLV_PUT_BTRFS_TIMESPEC(sctx, BTRFS_SEND_A_ATIME, eb,
2400                         btrfs_inode_atime(ii));
2401         TLV_PUT_BTRFS_TIMESPEC(sctx, BTRFS_SEND_A_MTIME, eb,
2402                         btrfs_inode_mtime(ii));
2403         TLV_PUT_BTRFS_TIMESPEC(sctx, BTRFS_SEND_A_CTIME, eb,
2404                         btrfs_inode_ctime(ii));
2405         /* TODO Add otime support when the otime patches get into upstream */
2406
2407         ret = send_cmd(sctx);
2408
2409 tlv_put_failure:
2410 out:
2411         fs_path_free(p);
2412         btrfs_free_path(path);
2413         return ret;
2414 }
2415
2416 /*
2417  * Sends a BTRFS_SEND_C_MKXXX or SYMLINK command to user space. We don't have
2418  * a valid path yet because we did not process the refs yet. So, the inode
2419  * is created as orphan.
2420  */
2421 static int send_create_inode(struct send_ctx *sctx, u64 ino)
2422 {
2423         int ret = 0;
2424         struct fs_path *p;
2425         int cmd;
2426         u64 gen;
2427         u64 mode;
2428         u64 rdev;
2429
2430 verbose_printk("btrfs: send_create_inode %llu\n", ino);
2431
2432         p = fs_path_alloc();
2433         if (!p)
2434                 return -ENOMEM;
2435
2436         ret = get_inode_info(sctx->send_root, ino, NULL, &gen, &mode, NULL,
2437                         NULL, &rdev);
2438         if (ret < 0)
2439                 goto out;
2440
2441         if (S_ISREG(mode)) {
2442                 cmd = BTRFS_SEND_C_MKFILE;
2443         } else if (S_ISDIR(mode)) {
2444                 cmd = BTRFS_SEND_C_MKDIR;
2445         } else if (S_ISLNK(mode)) {
2446                 cmd = BTRFS_SEND_C_SYMLINK;
2447         } else if (S_ISCHR(mode) || S_ISBLK(mode)) {
2448                 cmd = BTRFS_SEND_C_MKNOD;
2449         } else if (S_ISFIFO(mode)) {
2450                 cmd = BTRFS_SEND_C_MKFIFO;
2451         } else if (S_ISSOCK(mode)) {
2452                 cmd = BTRFS_SEND_C_MKSOCK;
2453         } else {
2454                 printk(KERN_WARNING "btrfs: unexpected inode type %o",
2455                                 (int)(mode & S_IFMT));
2456                 ret = -ENOTSUPP;
2457                 goto out;
2458         }
2459
2460         ret = begin_cmd(sctx, cmd);
2461         if (ret < 0)
2462                 goto out;
2463
2464         ret = gen_unique_name(sctx, ino, gen, p);
2465         if (ret < 0)
2466                 goto out;
2467
2468         TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
2469         TLV_PUT_U64(sctx, BTRFS_SEND_A_INO, ino);
2470
2471         if (S_ISLNK(mode)) {
2472                 fs_path_reset(p);
2473                 ret = read_symlink(sctx->send_root, ino, p);
2474                 if (ret < 0)
2475                         goto out;
2476                 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH_LINK, p);
2477         } else if (S_ISCHR(mode) || S_ISBLK(mode) ||
2478                    S_ISFIFO(mode) || S_ISSOCK(mode)) {
2479                 TLV_PUT_U64(sctx, BTRFS_SEND_A_RDEV, new_encode_dev(rdev));
2480                 TLV_PUT_U64(sctx, BTRFS_SEND_A_MODE, mode);
2481         }
2482
2483         ret = send_cmd(sctx);
2484         if (ret < 0)
2485                 goto out;
2486
2487
2488 tlv_put_failure:
2489 out:
2490         fs_path_free(p);
2491         return ret;
2492 }
2493
2494 /*
2495  * We need some special handling for inodes that get processed before the parent
2496  * directory got created. See process_recorded_refs for details.
2497  * This function does the check if we already created the dir out of order.
2498  */
2499 static int did_create_dir(struct send_ctx *sctx, u64 dir)
2500 {
2501         int ret = 0;
2502         struct btrfs_path *path = NULL;
2503         struct btrfs_key key;
2504         struct btrfs_key found_key;
2505         struct btrfs_key di_key;
2506         struct extent_buffer *eb;
2507         struct btrfs_dir_item *di;
2508         int slot;
2509
2510         path = alloc_path_for_send();
2511         if (!path) {
2512                 ret = -ENOMEM;
2513                 goto out;
2514         }
2515
2516         key.objectid = dir;
2517         key.type = BTRFS_DIR_INDEX_KEY;
2518         key.offset = 0;
2519         while (1) {
2520                 ret = btrfs_search_slot_for_read(sctx->send_root, &key, path,
2521                                 1, 0);
2522                 if (ret < 0)
2523                         goto out;
2524                 if (!ret) {
2525                         eb = path->nodes[0];
2526                         slot = path->slots[0];
2527                         btrfs_item_key_to_cpu(eb, &found_key, slot);
2528                 }
2529                 if (ret || found_key.objectid != key.objectid ||
2530                     found_key.type != key.type) {
2531                         ret = 0;
2532                         goto out;
2533                 }
2534
2535                 di = btrfs_item_ptr(eb, slot, struct btrfs_dir_item);
2536                 btrfs_dir_item_key_to_cpu(eb, di, &di_key);
2537
2538                 if (di_key.type != BTRFS_ROOT_ITEM_KEY &&
2539                     di_key.objectid < sctx->send_progress) {
2540                         ret = 1;
2541                         goto out;
2542                 }
2543
2544                 key.offset = found_key.offset + 1;
2545                 btrfs_release_path(path);
2546         }
2547
2548 out:
2549         btrfs_free_path(path);
2550         return ret;
2551 }
2552
2553 /*
2554  * Only creates the inode if it is:
2555  * 1. Not a directory
2556  * 2. Or a directory which was not created already due to out of order
2557  *    directories. See did_create_dir and process_recorded_refs for details.
2558  */
2559 static int send_create_inode_if_needed(struct send_ctx *sctx)
2560 {
2561         int ret;
2562
2563         if (S_ISDIR(sctx->cur_inode_mode)) {
2564                 ret = did_create_dir(sctx, sctx->cur_ino);
2565                 if (ret < 0)
2566                         goto out;
2567                 if (ret) {
2568                         ret = 0;
2569                         goto out;
2570                 }
2571         }
2572
2573         ret = send_create_inode(sctx, sctx->cur_ino);
2574         if (ret < 0)
2575                 goto out;
2576
2577 out:
2578         return ret;
2579 }
2580
2581 struct recorded_ref {
2582         struct list_head list;
2583         char *dir_path;
2584         char *name;
2585         struct fs_path *full_path;
2586         u64 dir;
2587         u64 dir_gen;
2588         int dir_path_len;
2589         int name_len;
2590 };
2591
2592 /*
2593  * We need to process new refs before deleted refs, but compare_tree gives us
2594  * everything mixed. So we first record all refs and later process them.
2595  * This function is a helper to record one ref.
2596  */
2597 static int record_ref(struct list_head *head, u64 dir,
2598                       u64 dir_gen, struct fs_path *path)
2599 {
2600         struct recorded_ref *ref;
2601
2602         ref = kmalloc(sizeof(*ref), GFP_NOFS);
2603         if (!ref)
2604                 return -ENOMEM;
2605
2606         ref->dir = dir;
2607         ref->dir_gen = dir_gen;
2608         ref->full_path = path;
2609
2610         ref->name = (char *)kbasename(ref->full_path->start);
2611         ref->name_len = ref->full_path->end - ref->name;
2612         ref->dir_path = ref->full_path->start;
2613         if (ref->name == ref->full_path->start)
2614                 ref->dir_path_len = 0;
2615         else
2616                 ref->dir_path_len = ref->full_path->end -
2617                                 ref->full_path->start - 1 - ref->name_len;
2618
2619         list_add_tail(&ref->list, head);
2620         return 0;
2621 }
2622
2623 static int dup_ref(struct recorded_ref *ref, struct list_head *list)
2624 {
2625         struct recorded_ref *new;
2626
2627         new = kmalloc(sizeof(*ref), GFP_NOFS);
2628         if (!new)
2629                 return -ENOMEM;
2630
2631         new->dir = ref->dir;
2632         new->dir_gen = ref->dir_gen;
2633         new->full_path = NULL;
2634         INIT_LIST_HEAD(&new->list);
2635         list_add_tail(&new->list, list);
2636         return 0;
2637 }
2638
2639 static void __free_recorded_refs(struct list_head *head)
2640 {
2641         struct recorded_ref *cur;
2642
2643         while (!list_empty(head)) {
2644                 cur = list_entry(head->next, struct recorded_ref, list);
2645                 fs_path_free(cur->full_path);
2646                 list_del(&cur->list);
2647                 kfree(cur);
2648         }
2649 }
2650
2651 static void free_recorded_refs(struct send_ctx *sctx)
2652 {
2653         __free_recorded_refs(&sctx->new_refs);
2654         __free_recorded_refs(&sctx->deleted_refs);
2655 }
2656
2657 /*
2658  * Renames/moves a file/dir to its orphan name. Used when the first
2659  * ref of an unprocessed inode gets overwritten and for all non empty
2660  * directories.
2661  */
2662 static int orphanize_inode(struct send_ctx *sctx, u64 ino, u64 gen,
2663                           struct fs_path *path)
2664 {
2665         int ret;
2666         struct fs_path *orphan;
2667
2668         orphan = fs_path_alloc();
2669         if (!orphan)
2670                 return -ENOMEM;
2671
2672         ret = gen_unique_name(sctx, ino, gen, orphan);
2673         if (ret < 0)
2674                 goto out;
2675
2676         ret = send_rename(sctx, path, orphan);
2677
2678 out:
2679         fs_path_free(orphan);
2680         return ret;
2681 }
2682
2683 /*
2684  * Returns 1 if a directory can be removed at this point in time.
2685  * We check this by iterating all dir items and checking if the inode behind
2686  * the dir item was already processed.
2687  */
2688 static int can_rmdir(struct send_ctx *sctx, u64 dir, u64 send_progress)
2689 {
2690         int ret = 0;
2691         struct btrfs_root *root = sctx->parent_root;
2692         struct btrfs_path *path;
2693         struct btrfs_key key;
2694         struct btrfs_key found_key;
2695         struct btrfs_key loc;
2696         struct btrfs_dir_item *di;
2697
2698         /*
2699          * Don't try to rmdir the top/root subvolume dir.
2700          */
2701         if (dir == BTRFS_FIRST_FREE_OBJECTID)
2702                 return 0;
2703
2704         path = alloc_path_for_send();
2705         if (!path)
2706                 return -ENOMEM;
2707
2708         key.objectid = dir;
2709         key.type = BTRFS_DIR_INDEX_KEY;
2710         key.offset = 0;
2711
2712         while (1) {
2713                 ret = btrfs_search_slot_for_read(root, &key, path, 1, 0);
2714                 if (ret < 0)
2715                         goto out;
2716                 if (!ret) {
2717                         btrfs_item_key_to_cpu(path->nodes[0], &found_key,
2718                                         path->slots[0]);
2719                 }
2720                 if (ret || found_key.objectid != key.objectid ||
2721                     found_key.type != key.type) {
2722                         break;
2723                 }
2724
2725                 di = btrfs_item_ptr(path->nodes[0], path->slots[0],
2726                                 struct btrfs_dir_item);
2727                 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &loc);
2728
2729                 if (loc.objectid > send_progress) {
2730                         ret = 0;
2731                         goto out;
2732                 }
2733
2734                 btrfs_release_path(path);
2735                 key.offset = found_key.offset + 1;
2736         }
2737
2738         ret = 1;
2739
2740 out:
2741         btrfs_free_path(path);
2742         return ret;
2743 }
2744
2745 static int is_waiting_for_move(struct send_ctx *sctx, u64 ino)
2746 {
2747         struct rb_node *n = sctx->waiting_dir_moves.rb_node;
2748         struct waiting_dir_move *entry;
2749
2750         while (n) {
2751                 entry = rb_entry(n, struct waiting_dir_move, node);
2752                 if (ino < entry->ino)
2753                         n = n->rb_left;
2754                 else if (ino > entry->ino)
2755                         n = n->rb_right;
2756                 else
2757                         return 1;
2758         }
2759         return 0;
2760 }
2761
2762 static int add_waiting_dir_move(struct send_ctx *sctx, u64 ino)
2763 {
2764         struct rb_node **p = &sctx->waiting_dir_moves.rb_node;
2765         struct rb_node *parent = NULL;
2766         struct waiting_dir_move *entry, *dm;
2767
2768         dm = kmalloc(sizeof(*dm), GFP_NOFS);
2769         if (!dm)
2770                 return -ENOMEM;
2771         dm->ino = ino;
2772
2773         while (*p) {
2774                 parent = *p;
2775                 entry = rb_entry(parent, struct waiting_dir_move, node);
2776                 if (ino < entry->ino) {
2777                         p = &(*p)->rb_left;
2778                 } else if (ino > entry->ino) {
2779                         p = &(*p)->rb_right;
2780                 } else {
2781                         kfree(dm);
2782                         return -EEXIST;
2783                 }
2784         }
2785
2786         rb_link_node(&dm->node, parent, p);
2787         rb_insert_color(&dm->node, &sctx->waiting_dir_moves);
2788         return 0;
2789 }
2790
2791 static int del_waiting_dir_move(struct send_ctx *sctx, u64 ino)
2792 {
2793         struct rb_node *n = sctx->waiting_dir_moves.rb_node;
2794         struct waiting_dir_move *entry;
2795
2796         while (n) {
2797                 entry = rb_entry(n, struct waiting_dir_move, node);
2798                 if (ino < entry->ino) {
2799                         n = n->rb_left;
2800                 } else if (ino > entry->ino) {
2801                         n = n->rb_right;
2802                 } else {
2803                         rb_erase(&entry->node, &sctx->waiting_dir_moves);
2804                         kfree(entry);
2805                         return 0;
2806                 }
2807         }
2808         return -ENOENT;
2809 }
2810
2811 static int add_pending_dir_move(struct send_ctx *sctx, u64 parent_ino)
2812 {
2813         struct rb_node **p = &sctx->pending_dir_moves.rb_node;
2814         struct rb_node *parent = NULL;
2815         struct pending_dir_move *entry, *pm;
2816         struct recorded_ref *cur;
2817         int exists = 0;
2818         int ret;
2819
2820         pm = kmalloc(sizeof(*pm), GFP_NOFS);
2821         if (!pm)
2822                 return -ENOMEM;
2823         pm->parent_ino = parent_ino;
2824         pm->ino = sctx->cur_ino;
2825         pm->gen = sctx->cur_inode_gen;
2826         INIT_LIST_HEAD(&pm->list);
2827         INIT_LIST_HEAD(&pm->update_refs);
2828         RB_CLEAR_NODE(&pm->node);
2829
2830         while (*p) {
2831                 parent = *p;
2832                 entry = rb_entry(parent, struct pending_dir_move, node);
2833                 if (parent_ino < entry->parent_ino) {
2834                         p = &(*p)->rb_left;
2835                 } else if (parent_ino > entry->parent_ino) {
2836                         p = &(*p)->rb_right;
2837                 } else {
2838                         exists = 1;
2839                         break;
2840                 }
2841         }
2842
2843         list_for_each_entry(cur, &sctx->deleted_refs, list) {
2844                 ret = dup_ref(cur, &pm->update_refs);
2845                 if (ret < 0)
2846                         goto out;
2847         }
2848         list_for_each_entry(cur, &sctx->new_refs, list) {
2849                 ret = dup_ref(cur, &pm->update_refs);
2850                 if (ret < 0)
2851                         goto out;
2852         }
2853
2854         ret = add_waiting_dir_move(sctx, pm->ino);
2855         if (ret)
2856                 goto out;
2857
2858         if (exists) {
2859                 list_add_tail(&pm->list, &entry->list);
2860         } else {
2861                 rb_link_node(&pm->node, parent, p);
2862                 rb_insert_color(&pm->node, &sctx->pending_dir_moves);
2863         }
2864         ret = 0;
2865 out:
2866         if (ret) {
2867                 __free_recorded_refs(&pm->update_refs);
2868                 kfree(pm);
2869         }
2870         return ret;
2871 }
2872
2873 static struct pending_dir_move *get_pending_dir_moves(struct send_ctx *sctx,
2874                                                       u64 parent_ino)
2875 {
2876         struct rb_node *n = sctx->pending_dir_moves.rb_node;
2877         struct pending_dir_move *entry;
2878
2879         while (n) {
2880                 entry = rb_entry(n, struct pending_dir_move, node);
2881                 if (parent_ino < entry->parent_ino)
2882                         n = n->rb_left;
2883                 else if (parent_ino > entry->parent_ino)
2884                         n = n->rb_right;
2885                 else
2886                         return entry;
2887         }
2888         return NULL;
2889 }
2890
2891 static int apply_dir_move(struct send_ctx *sctx, struct pending_dir_move *pm)
2892 {
2893         struct fs_path *from_path = NULL;
2894         struct fs_path *to_path = NULL;
2895         u64 orig_progress = sctx->send_progress;
2896         struct recorded_ref *cur;
2897         int ret;
2898
2899         from_path = fs_path_alloc();
2900         if (!from_path)
2901                 return -ENOMEM;
2902
2903         sctx->send_progress = pm->ino;
2904         ret = get_cur_path(sctx, pm->ino, pm->gen, from_path);
2905         if (ret < 0)
2906                 goto out;
2907
2908         to_path = fs_path_alloc();
2909         if (!to_path) {
2910                 ret = -ENOMEM;
2911                 goto out;
2912         }
2913
2914         sctx->send_progress = sctx->cur_ino + 1;
2915         ret = del_waiting_dir_move(sctx, pm->ino);
2916         ASSERT(ret == 0);
2917
2918         ret = get_cur_path(sctx, pm->ino, pm->gen, to_path);
2919         if (ret < 0)
2920                 goto out;
2921
2922         ret = send_rename(sctx, from_path, to_path);
2923         if (ret < 0)
2924                 goto out;
2925
2926         ret = send_utimes(sctx, pm->ino, pm->gen);
2927         if (ret < 0)
2928                 goto out;
2929
2930         /*
2931          * After rename/move, need to update the utimes of both new parent(s)
2932          * and old parent(s).
2933          */
2934         list_for_each_entry(cur, &pm->update_refs, list) {
2935                 ret = send_utimes(sctx, cur->dir, cur->dir_gen);
2936                 if (ret < 0)
2937                         goto out;
2938         }
2939
2940 out:
2941         fs_path_free(from_path);
2942         fs_path_free(to_path);
2943         sctx->send_progress = orig_progress;
2944
2945         return ret;
2946 }
2947
2948 static void free_pending_move(struct send_ctx *sctx, struct pending_dir_move *m)
2949 {
2950         if (!list_empty(&m->list))
2951                 list_del(&m->list);
2952         if (!RB_EMPTY_NODE(&m->node))
2953                 rb_erase(&m->node, &sctx->pending_dir_moves);
2954         __free_recorded_refs(&m->update_refs);
2955         kfree(m);
2956 }
2957
2958 static void tail_append_pending_moves(struct pending_dir_move *moves,
2959                                       struct list_head *stack)
2960 {
2961         if (list_empty(&moves->list)) {
2962                 list_add_tail(&moves->list, stack);
2963         } else {
2964                 LIST_HEAD(list);
2965                 list_splice_init(&moves->list, &list);
2966                 list_add_tail(&moves->list, stack);
2967                 list_splice_tail(&list, stack);
2968         }
2969 }
2970
2971 static int apply_children_dir_moves(struct send_ctx *sctx)
2972 {
2973         struct pending_dir_move *pm;
2974         struct list_head stack;
2975         u64 parent_ino = sctx->cur_ino;
2976         int ret = 0;
2977
2978         pm = get_pending_dir_moves(sctx, parent_ino);
2979         if (!pm)
2980                 return 0;
2981
2982         INIT_LIST_HEAD(&stack);
2983         tail_append_pending_moves(pm, &stack);
2984
2985         while (!list_empty(&stack)) {
2986                 pm = list_first_entry(&stack, struct pending_dir_move, list);
2987                 parent_ino = pm->ino;
2988                 ret = apply_dir_move(sctx, pm);
2989                 free_pending_move(sctx, pm);
2990                 if (ret)
2991                         goto out;
2992                 pm = get_pending_dir_moves(sctx, parent_ino);
2993                 if (pm)
2994                         tail_append_pending_moves(pm, &stack);
2995         }
2996         return 0;
2997
2998 out:
2999         while (!list_empty(&stack)) {
3000                 pm = list_first_entry(&stack, struct pending_dir_move, list);
3001                 free_pending_move(sctx, pm);
3002         }
3003         return ret;
3004 }
3005
3006 static int wait_for_parent_move(struct send_ctx *sctx,
3007                                 struct recorded_ref *parent_ref)
3008 {
3009         int ret;
3010         u64 ino = parent_ref->dir;
3011         u64 parent_ino_before, parent_ino_after;
3012         u64 new_gen, old_gen;
3013         struct fs_path *path_before = NULL;
3014         struct fs_path *path_after = NULL;
3015         int len1, len2;
3016
3017         if (parent_ref->dir <= sctx->cur_ino)
3018                 return 0;
3019
3020         if (is_waiting_for_move(sctx, ino))
3021                 return 1;
3022
3023         ret = get_inode_info(sctx->parent_root, ino, NULL, &old_gen,
3024                              NULL, NULL, NULL, NULL);
3025         if (ret == -ENOENT)
3026                 return 0;
3027         else if (ret < 0)
3028                 return ret;
3029
3030         ret = get_inode_info(sctx->send_root, ino, NULL, &new_gen,
3031                              NULL, NULL, NULL, NULL);
3032         if (ret < 0)
3033                 return ret;
3034
3035         if (new_gen != old_gen)
3036                 return 0;
3037
3038         path_before = fs_path_alloc();
3039         if (!path_before)
3040                 return -ENOMEM;
3041
3042         ret = get_first_ref(sctx->parent_root, ino, &parent_ino_before,
3043                             NULL, path_before);
3044         if (ret == -ENOENT) {
3045                 ret = 0;
3046                 goto out;
3047         } else if (ret < 0) {
3048                 goto out;
3049         }
3050
3051         path_after = fs_path_alloc();
3052         if (!path_after) {
3053                 ret = -ENOMEM;
3054                 goto out;
3055         }
3056
3057         ret = get_first_ref(sctx->send_root, ino, &parent_ino_after,
3058                             NULL, path_after);
3059         if (ret == -ENOENT) {
3060                 ret = 0;
3061                 goto out;
3062         } else if (ret < 0) {
3063                 goto out;
3064         }
3065
3066         len1 = fs_path_len(path_before);
3067         len2 = fs_path_len(path_after);
3068         if ((parent_ino_before != parent_ino_after) && (len1 != len2 ||
3069              memcmp(path_before->start, path_after->start, len1))) {
3070                 ret = 1;
3071                 goto out;
3072         }
3073         ret = 0;
3074
3075 out:
3076         fs_path_free(path_before);
3077         fs_path_free(path_after);
3078
3079         return ret;
3080 }
3081
3082 /*
3083  * This does all the move/link/unlink/rmdir magic.
3084  */
3085 static int process_recorded_refs(struct send_ctx *sctx, int *pending_move)
3086 {
3087         int ret = 0;
3088         struct recorded_ref *cur;
3089         struct recorded_ref *cur2;
3090         struct list_head check_dirs;
3091         struct fs_path *valid_path = NULL;
3092         u64 ow_inode = 0;
3093         u64 ow_gen;
3094         int did_overwrite = 0;
3095         int is_orphan = 0;
3096
3097 verbose_printk("btrfs: process_recorded_refs %llu\n", sctx->cur_ino);
3098
3099         /*
3100          * This should never happen as the root dir always has the same ref
3101          * which is always '..'
3102          */
3103         BUG_ON(sctx->cur_ino <= BTRFS_FIRST_FREE_OBJECTID);
3104         INIT_LIST_HEAD(&check_dirs);
3105
3106         valid_path = fs_path_alloc();
3107         if (!valid_path) {
3108                 ret = -ENOMEM;
3109                 goto out;
3110         }
3111
3112         /*
3113          * First, check if the first ref of the current inode was overwritten
3114          * before. If yes, we know that the current inode was already orphanized
3115          * and thus use the orphan name. If not, we can use get_cur_path to
3116          * get the path of the first ref as it would like while receiving at
3117          * this point in time.
3118          * New inodes are always orphan at the beginning, so force to use the
3119          * orphan name in this case.
3120          * The first ref is stored in valid_path and will be updated if it
3121          * gets moved around.
3122          */
3123         if (!sctx->cur_inode_new) {
3124                 ret = did_overwrite_first_ref(sctx, sctx->cur_ino,
3125                                 sctx->cur_inode_gen);
3126                 if (ret < 0)
3127                         goto out;
3128                 if (ret)
3129                         did_overwrite = 1;
3130         }
3131         if (sctx->cur_inode_new || did_overwrite) {
3132                 ret = gen_unique_name(sctx, sctx->cur_ino,
3133                                 sctx->cur_inode_gen, valid_path);
3134                 if (ret < 0)
3135                         goto out;
3136                 is_orphan = 1;
3137         } else {
3138                 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen,
3139                                 valid_path);
3140                 if (ret < 0)
3141                         goto out;
3142         }
3143
3144         list_for_each_entry(cur, &sctx->new_refs, list) {
3145                 /*
3146                  * We may have refs where the parent directory does not exist
3147                  * yet. This happens if the parent directories inum is higher
3148                  * the the current inum. To handle this case, we create the
3149                  * parent directory out of order. But we need to check if this
3150                  * did already happen before due to other refs in the same dir.
3151                  */
3152                 ret = get_cur_inode_state(sctx, cur->dir, cur->dir_gen);
3153                 if (ret < 0)
3154                         goto out;
3155                 if (ret == inode_state_will_create) {
3156                         ret = 0;
3157                         /*
3158                          * First check if any of the current inodes refs did
3159                          * already create the dir.
3160                          */
3161                         list_for_each_entry(cur2, &sctx->new_refs, list) {
3162                                 if (cur == cur2)
3163                                         break;
3164                                 if (cur2->dir == cur->dir) {
3165                                         ret = 1;
3166                                         break;
3167                                 }
3168                         }
3169
3170                         /*
3171                          * If that did not happen, check if a previous inode
3172                          * did already create the dir.
3173                          */
3174                         if (!ret)
3175                                 ret = did_create_dir(sctx, cur->dir);
3176                         if (ret < 0)
3177                                 goto out;
3178                         if (!ret) {
3179                                 ret = send_create_inode(sctx, cur->dir);
3180                                 if (ret < 0)
3181                                         goto out;
3182                         }
3183                 }
3184
3185                 /*
3186                  * Check if this new ref would overwrite the first ref of
3187                  * another unprocessed inode. If yes, orphanize the
3188                  * overwritten inode. If we find an overwritten ref that is
3189                  * not the first ref, simply unlink it.
3190                  */
3191                 ret = will_overwrite_ref(sctx, cur->dir, cur->dir_gen,
3192                                 cur->name, cur->name_len,
3193                                 &ow_inode, &ow_gen);
3194                 if (ret < 0)
3195                         goto out;
3196                 if (ret) {
3197                         ret = is_first_ref(sctx->parent_root,
3198                                            ow_inode, cur->dir, cur->name,
3199                                            cur->name_len);
3200                         if (ret < 0)
3201                                 goto out;
3202                         if (ret) {
3203                                 ret = orphanize_inode(sctx, ow_inode, ow_gen,
3204                                                 cur->full_path);
3205                                 if (ret < 0)
3206                                         goto out;
3207                         } else {
3208                                 ret = send_unlink(sctx, cur->full_path);
3209                                 if (ret < 0)
3210                                         goto out;
3211                         }
3212                 }
3213
3214                 /*
3215                  * link/move the ref to the new place. If we have an orphan
3216                  * inode, move it and update valid_path. If not, link or move
3217                  * it depending on the inode mode.
3218                  */
3219                 if (is_orphan) {
3220                         ret = send_rename(sctx, valid_path, cur->full_path);
3221                         if (ret < 0)
3222                                 goto out;
3223                         is_orphan = 0;
3224                         ret = fs_path_copy(valid_path, cur->full_path);
3225                         if (ret < 0)
3226                                 goto out;
3227                 } else {
3228                         if (S_ISDIR(sctx->cur_inode_mode)) {
3229                                 /*
3230                                  * Dirs can't be linked, so move it. For moved
3231                                  * dirs, we always have one new and one deleted
3232                                  * ref. The deleted ref is ignored later.
3233                                  */
3234                                 if (wait_for_parent_move(sctx, cur)) {
3235                                         ret = add_pending_dir_move(sctx,
3236                                                                    cur->dir);
3237                                         *pending_move = 1;
3238                                 } else {
3239                                         ret = send_rename(sctx, valid_path,
3240                                                           cur->full_path);
3241                                         if (!ret)
3242                                                 ret = fs_path_copy(valid_path,
3243                                                                cur->full_path);
3244                                 }
3245                                 if (ret < 0)
3246                                         goto out;
3247                         } else {
3248                                 ret = send_link(sctx, cur->full_path,
3249                                                 valid_path);
3250                                 if (ret < 0)
3251                                         goto out;
3252                         }
3253                 }
3254                 ret = dup_ref(cur, &check_dirs);
3255                 if (ret < 0)
3256                         goto out;
3257         }
3258
3259         if (S_ISDIR(sctx->cur_inode_mode) && sctx->cur_inode_deleted) {
3260                 /*
3261                  * Check if we can already rmdir the directory. If not,
3262                  * orphanize it. For every dir item inside that gets deleted
3263                  * later, we do this check again and rmdir it then if possible.
3264                  * See the use of check_dirs for more details.
3265                  */
3266                 ret = can_rmdir(sctx, sctx->cur_ino, sctx->cur_ino);
3267                 if (ret < 0)
3268                         goto out;
3269                 if (ret) {
3270                         ret = send_rmdir(sctx, valid_path);
3271                         if (ret < 0)
3272                                 goto out;
3273                 } else if (!is_orphan) {
3274                         ret = orphanize_inode(sctx, sctx->cur_ino,
3275                                         sctx->cur_inode_gen, valid_path);
3276                         if (ret < 0)
3277                                 goto out;
3278                         is_orphan = 1;
3279                 }
3280
3281                 list_for_each_entry(cur, &sctx->deleted_refs, list) {
3282                         ret = dup_ref(cur, &check_dirs);
3283                         if (ret < 0)
3284                                 goto out;
3285                 }
3286         } else if (S_ISDIR(sctx->cur_inode_mode) &&
3287                    !list_empty(&sctx->deleted_refs)) {
3288                 /*
3289                  * We have a moved dir. Add the old parent to check_dirs
3290                  */
3291                 cur = list_entry(sctx->deleted_refs.next, struct recorded_ref,
3292                                 list);
3293                 ret = dup_ref(cur, &check_dirs);
3294                 if (ret < 0)
3295                         goto out;
3296         } else if (!S_ISDIR(sctx->cur_inode_mode)) {
3297                 /*
3298                  * We have a non dir inode. Go through all deleted refs and
3299                  * unlink them if they were not already overwritten by other
3300                  * inodes.
3301                  */
3302                 list_for_each_entry(cur, &sctx->deleted_refs, list) {
3303                         ret = did_overwrite_ref(sctx, cur->dir, cur->dir_gen,
3304                                         sctx->cur_ino, sctx->cur_inode_gen,
3305                                         cur->name, cur->name_len);
3306                         if (ret < 0)
3307                                 goto out;
3308                         if (!ret) {
3309                                 ret = send_unlink(sctx, cur->full_path);
3310                                 if (ret < 0)
3311                                         goto out;
3312                         }
3313                         ret = dup_ref(cur, &check_dirs);
3314                         if (ret < 0)
3315                                 goto out;
3316                 }
3317                 /*
3318                  * If the inode is still orphan, unlink the orphan. This may
3319                  * happen when a previous inode did overwrite the first ref
3320                  * of this inode and no new refs were added for the current
3321                  * inode. Unlinking does not mean that the inode is deleted in
3322                  * all cases. There may still be links to this inode in other
3323                  * places.
3324                  */
3325                 if (is_orphan) {
3326                         ret = send_unlink(sctx, valid_path);
3327                         if (ret < 0)
3328                                 goto out;
3329                 }
3330         }
3331
3332         /*
3333          * We did collect all parent dirs where cur_inode was once located. We
3334          * now go through all these dirs and check if they are pending for
3335          * deletion and if it's finally possible to perform the rmdir now.
3336          * We also update the inode stats of the parent dirs here.
3337          */
3338         list_for_each_entry(cur, &check_dirs, list) {
3339                 /*
3340                  * In case we had refs into dirs that were not processed yet,
3341                  * we don't need to do the utime and rmdir logic for these dirs.
3342                  * The dir will be processed later.
3343                  */
3344                 if (cur->dir > sctx->cur_ino)
3345                         continue;
3346
3347                 ret = get_cur_inode_state(sctx, cur->dir, cur->dir_gen);
3348                 if (ret < 0)
3349                         goto out;
3350
3351                 if (ret == inode_state_did_create ||
3352                     ret == inode_state_no_change) {
3353                         /* TODO delayed utimes */
3354                         ret = send_utimes(sctx, cur->dir, cur->dir_gen);
3355                         if (ret < 0)
3356                                 goto out;
3357                 } else if (ret == inode_state_did_delete) {
3358                         ret = can_rmdir(sctx, cur->dir, sctx->cur_ino);
3359                         if (ret < 0)
3360                                 goto out;
3361                         if (ret) {
3362                                 ret = get_cur_path(sctx, cur->dir,
3363                                                    cur->dir_gen, valid_path);
3364                                 if (ret < 0)
3365                                         goto out;
3366                                 ret = send_rmdir(sctx, valid_path);
3367                                 if (ret < 0)
3368                                         goto out;
3369                         }
3370                 }
3371         }
3372
3373         ret = 0;
3374
3375 out:
3376         __free_recorded_refs(&check_dirs);
3377         free_recorded_refs(sctx);
3378         fs_path_free(valid_path);
3379         return ret;
3380 }
3381
3382 static int __record_new_ref(int num, u64 dir, int index,
3383                             struct fs_path *name,
3384                             void *ctx)
3385 {
3386         int ret = 0;
3387         struct send_ctx *sctx = ctx;
3388         struct fs_path *p;
3389         u64 gen;
3390
3391         p = fs_path_alloc();
3392         if (!p)
3393                 return -ENOMEM;
3394
3395         ret = get_inode_info(sctx->send_root, dir, NULL, &gen, NULL, NULL,
3396                         NULL, NULL);
3397         if (ret < 0)
3398                 goto out;
3399
3400         ret = get_cur_path(sctx, dir, gen, p);
3401         if (ret < 0)
3402                 goto out;
3403         ret = fs_path_add_path(p, name);
3404         if (ret < 0)
3405                 goto out;
3406
3407         ret = record_ref(&sctx->new_refs, dir, gen, p);
3408
3409 out:
3410         if (ret)
3411                 fs_path_free(p);
3412         return ret;
3413 }
3414
3415 static int __record_deleted_ref(int num, u64 dir, int index,
3416                                 struct fs_path *name,
3417                                 void *ctx)
3418 {
3419         int ret = 0;
3420         struct send_ctx *sctx = ctx;
3421         struct fs_path *p;
3422         u64 gen;
3423
3424         p = fs_path_alloc();
3425         if (!p)
3426                 return -ENOMEM;
3427
3428         ret = get_inode_info(sctx->parent_root, dir, NULL, &gen, NULL, NULL,
3429                         NULL, NULL);
3430         if (ret < 0)
3431                 goto out;
3432
3433         ret = get_cur_path(sctx, dir, gen, p);
3434         if (ret < 0)
3435                 goto out;
3436         ret = fs_path_add_path(p, name);
3437         if (ret < 0)
3438                 goto out;
3439
3440         ret = record_ref(&sctx->deleted_refs, dir, gen, p);
3441
3442 out:
3443         if (ret)
3444                 fs_path_free(p);
3445         return ret;
3446 }
3447
3448 static int record_new_ref(struct send_ctx *sctx)
3449 {
3450         int ret;
3451
3452         ret = iterate_inode_ref(sctx->send_root, sctx->left_path,
3453                                 sctx->cmp_key, 0, __record_new_ref, sctx);
3454         if (ret < 0)
3455                 goto out;
3456         ret = 0;
3457
3458 out:
3459         return ret;
3460 }
3461
3462 static int record_deleted_ref(struct send_ctx *sctx)
3463 {
3464         int ret;
3465
3466         ret = iterate_inode_ref(sctx->parent_root, sctx->right_path,
3467                                 sctx->cmp_key, 0, __record_deleted_ref, sctx);
3468         if (ret < 0)
3469                 goto out;
3470         ret = 0;
3471
3472 out:
3473         return ret;
3474 }
3475
3476 struct find_ref_ctx {
3477         u64 dir;
3478         u64 dir_gen;
3479         struct btrfs_root *root;
3480         struct fs_path *name;
3481         int found_idx;
3482 };
3483
3484 static int __find_iref(int num, u64 dir, int index,
3485                        struct fs_path *name,
3486                        void *ctx_)
3487 {
3488         struct find_ref_ctx *ctx = ctx_;
3489         u64 dir_gen;
3490         int ret;
3491
3492         if (dir == ctx->dir && fs_path_len(name) == fs_path_len(ctx->name) &&
3493             strncmp(name->start, ctx->name->start, fs_path_len(name)) == 0) {
3494                 /*
3495                  * To avoid doing extra lookups we'll only do this if everything
3496                  * else matches.
3497                  */
3498                 ret = get_inode_info(ctx->root, dir, NULL, &dir_gen, NULL,
3499                                      NULL, NULL, NULL);
3500                 if (ret)
3501                         return ret;
3502                 if (dir_gen != ctx->dir_gen)
3503                         return 0;
3504                 ctx->found_idx = num;
3505                 return 1;
3506         }
3507         return 0;
3508 }
3509
3510 static int find_iref(struct btrfs_root *root,
3511                      struct btrfs_path *path,
3512                      struct btrfs_key *key,
3513                      u64 dir, u64 dir_gen, struct fs_path *name)
3514 {
3515         int ret;
3516         struct find_ref_ctx ctx;
3517
3518         ctx.dir = dir;
3519         ctx.name = name;
3520         ctx.dir_gen = dir_gen;
3521         ctx.found_idx = -1;
3522         ctx.root = root;
3523
3524         ret = iterate_inode_ref(root, path, key, 0, __find_iref, &ctx);
3525         if (ret < 0)
3526                 return ret;
3527
3528         if (ctx.found_idx == -1)
3529                 return -ENOENT;
3530
3531         return ctx.found_idx;
3532 }
3533
3534 static int __record_changed_new_ref(int num, u64 dir, int index,
3535                                     struct fs_path *name,
3536                                     void *ctx)
3537 {
3538         u64 dir_gen;
3539         int ret;
3540         struct send_ctx *sctx = ctx;
3541
3542         ret = get_inode_info(sctx->send_root, dir, NULL, &dir_gen, NULL,
3543                              NULL, NULL, NULL);
3544         if (ret)
3545                 return ret;
3546
3547         ret = find_iref(sctx->parent_root, sctx->right_path,
3548                         sctx->cmp_key, dir, dir_gen, name);
3549         if (ret == -ENOENT)
3550                 ret = __record_new_ref(num, dir, index, name, sctx);
3551         else if (ret > 0)
3552                 ret = 0;
3553
3554         return ret;
3555 }
3556
3557 static int __record_changed_deleted_ref(int num, u64 dir, int index,
3558                                         struct fs_path *name,
3559                                         void *ctx)
3560 {
3561         u64 dir_gen;
3562         int ret;
3563         struct send_ctx *sctx = ctx;
3564
3565         ret = get_inode_info(sctx->parent_root, dir, NULL, &dir_gen, NULL,
3566                              NULL, NULL, NULL);
3567         if (ret)
3568                 return ret;
3569
3570         ret = find_iref(sctx->send_root, sctx->left_path, sctx->cmp_key,
3571                         dir, dir_gen, name);
3572         if (ret == -ENOENT)
3573                 ret = __record_deleted_ref(num, dir, index, name, sctx);
3574         else if (ret > 0)
3575                 ret = 0;
3576
3577         return ret;
3578 }
3579
3580 static int record_changed_ref(struct send_ctx *sctx)
3581 {
3582         int ret = 0;
3583
3584         ret = iterate_inode_ref(sctx->send_root, sctx->left_path,
3585                         sctx->cmp_key, 0, __record_changed_new_ref, sctx);
3586         if (ret < 0)
3587                 goto out;
3588         ret = iterate_inode_ref(sctx->parent_root, sctx->right_path,
3589                         sctx->cmp_key, 0, __record_changed_deleted_ref, sctx);
3590         if (ret < 0)
3591                 goto out;
3592         ret = 0;
3593
3594 out:
3595         return ret;
3596 }
3597
3598 /*
3599  * Record and process all refs at once. Needed when an inode changes the
3600  * generation number, which means that it was deleted and recreated.
3601  */
3602 static int process_all_refs(struct send_ctx *sctx,
3603                             enum btrfs_compare_tree_result cmd)
3604 {
3605         int ret;
3606         struct btrfs_root *root;
3607         struct btrfs_path *path;
3608         struct btrfs_key key;
3609         struct btrfs_key found_key;
3610         struct extent_buffer *eb;
3611         int slot;
3612         iterate_inode_ref_t cb;
3613         int pending_move = 0;
3614
3615         path = alloc_path_for_send();
3616         if (!path)
3617                 return -ENOMEM;
3618
3619         if (cmd == BTRFS_COMPARE_TREE_NEW) {
3620                 root = sctx->send_root;
3621                 cb = __record_new_ref;
3622         } else if (cmd == BTRFS_COMPARE_TREE_DELETED) {
3623                 root = sctx->parent_root;
3624                 cb = __record_deleted_ref;
3625         } else {
3626                 BUG();
3627         }
3628
3629         key.objectid = sctx->cmp_key->objectid;
3630         key.type = BTRFS_INODE_REF_KEY;
3631         key.offset = 0;
3632         while (1) {
3633                 ret = btrfs_search_slot_for_read(root, &key, path, 1, 0);
3634                 if (ret < 0)
3635                         goto out;
3636                 if (ret)
3637                         break;
3638
3639                 eb = path->nodes[0];
3640                 slot = path->slots[0];
3641                 btrfs_item_key_to_cpu(eb, &found_key, slot);
3642
3643                 if (found_key.objectid != key.objectid ||
3644                     (found_key.type != BTRFS_INODE_REF_KEY &&
3645                      found_key.type != BTRFS_INODE_EXTREF_KEY))
3646                         break;
3647
3648                 ret = iterate_inode_ref(root, path, &found_key, 0, cb, sctx);
3649                 btrfs_release_path(path);
3650                 if (ret < 0)
3651                         goto out;
3652
3653                 key.offset = found_key.offset + 1;
3654         }
3655         btrfs_release_path(path);
3656
3657         ret = process_recorded_refs(sctx, &pending_move);
3658         /* Only applicable to an incremental send. */
3659         ASSERT(pending_move == 0);
3660
3661 out:
3662         btrfs_free_path(path);
3663         return ret;
3664 }
3665
3666 static int send_set_xattr(struct send_ctx *sctx,
3667                           struct fs_path *path,
3668                           const char *name, int name_len,
3669                           const char *data, int data_len)
3670 {
3671         int ret = 0;
3672
3673         ret = begin_cmd(sctx, BTRFS_SEND_C_SET_XATTR);
3674         if (ret < 0)
3675                 goto out;
3676
3677         TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, path);
3678         TLV_PUT_STRING(sctx, BTRFS_SEND_A_XATTR_NAME, name, name_len);
3679         TLV_PUT(sctx, BTRFS_SEND_A_XATTR_DATA, data, data_len);
3680
3681         ret = send_cmd(sctx);
3682
3683 tlv_put_failure:
3684 out:
3685         return ret;
3686 }
3687
3688 static int send_remove_xattr(struct send_ctx *sctx,
3689                           struct fs_path *path,
3690                           const char *name, int name_len)
3691 {
3692         int ret = 0;
3693
3694         ret = begin_cmd(sctx, BTRFS_SEND_C_REMOVE_XATTR);
3695         if (ret < 0)
3696                 goto out;
3697
3698         TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, path);
3699         TLV_PUT_STRING(sctx, BTRFS_SEND_A_XATTR_NAME, name, name_len);
3700
3701         ret = send_cmd(sctx);
3702
3703 tlv_put_failure:
3704 out:
3705         return ret;
3706 }
3707
3708 static int __process_new_xattr(int num, struct btrfs_key *di_key,
3709                                const char *name, int name_len,
3710                                const char *data, int data_len,
3711                                u8 type, void *ctx)
3712 {
3713         int ret;
3714         struct send_ctx *sctx = ctx;
3715         struct fs_path *p;
3716         posix_acl_xattr_header dummy_acl;
3717
3718         p = fs_path_alloc();
3719         if (!p)
3720                 return -ENOMEM;
3721
3722         /*
3723          * This hack is needed because empty acl's are stored as zero byte
3724          * data in xattrs. Problem with that is, that receiving these zero byte
3725          * acl's will fail later. To fix this, we send a dummy acl list that
3726          * only contains the version number and no entries.
3727          */
3728         if (!strncmp(name, XATTR_NAME_POSIX_ACL_ACCESS, name_len) ||
3729             !strncmp(name, XATTR_NAME_POSIX_ACL_DEFAULT, name_len)) {
3730                 if (data_len == 0) {
3731                         dummy_acl.a_version =
3732                                         cpu_to_le32(POSIX_ACL_XATTR_VERSION);
3733                         data = (char *)&dummy_acl;
3734                         data_len = sizeof(dummy_acl);
3735                 }
3736         }
3737
3738         ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
3739         if (ret < 0)
3740                 goto out;
3741
3742         ret = send_set_xattr(sctx, p, name, name_len, data, data_len);
3743
3744 out:
3745         fs_path_free(p);
3746         return ret;
3747 }
3748
3749 static int __process_deleted_xattr(int num, struct btrfs_key *di_key,
3750                                    const char *name, int name_len,
3751                                    const char *data, int data_len,
3752                                    u8 type, void *ctx)
3753 {
3754         int ret;
3755         struct send_ctx *sctx = ctx;
3756         struct fs_path *p;
3757
3758         p = fs_path_alloc();
3759         if (!p)
3760                 return -ENOMEM;
3761
3762         ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
3763         if (ret < 0)
3764                 goto out;
3765
3766         ret = send_remove_xattr(sctx, p, name, name_len);
3767
3768 out:
3769         fs_path_free(p);
3770         return ret;
3771 }
3772
3773 static int process_new_xattr(struct send_ctx *sctx)
3774 {
3775         int ret = 0;
3776
3777         ret = iterate_dir_item(sctx->send_root, sctx->left_path,
3778                                sctx->cmp_key, __process_new_xattr, sctx);
3779
3780         return ret;
3781 }
3782
3783 static int process_deleted_xattr(struct send_ctx *sctx)
3784 {
3785         int ret;
3786
3787         ret = iterate_dir_item(sctx->parent_root, sctx->right_path,
3788                                sctx->cmp_key, __process_deleted_xattr, sctx);
3789
3790         return ret;
3791 }
3792
3793 struct find_xattr_ctx {
3794         const char *name;
3795         int name_len;
3796         int found_idx;
3797         char *found_data;
3798         int found_data_len;
3799 };
3800
3801 static int __find_xattr(int num, struct btrfs_key *di_key,
3802                         const char *name, int name_len,
3803                         const char *data, int data_len,
3804                         u8 type, void *vctx)
3805 {
3806         struct find_xattr_ctx *ctx = vctx;
3807
3808         if (name_len == ctx->name_len &&
3809             strncmp(name, ctx->name, name_len) == 0) {
3810                 ctx->found_idx = num;
3811                 ctx->found_data_len = data_len;
3812                 ctx->found_data = kmemdup(data, data_len, GFP_NOFS);
3813                 if (!ctx->found_data)
3814                         return -ENOMEM;
3815                 return 1;
3816         }
3817         return 0;
3818 }
3819
3820 static int find_xattr(struct btrfs_root *root,
3821                       struct btrfs_path *path,
3822                       struct btrfs_key *key,
3823                       const char *name, int name_len,
3824                       char **data, int *data_len)
3825 {
3826         int ret;
3827         struct find_xattr_ctx ctx;
3828
3829         ctx.name = name;
3830         ctx.name_len = name_len;
3831         ctx.found_idx = -1;
3832         ctx.found_data = NULL;
3833         ctx.found_data_len = 0;
3834
3835         ret = iterate_dir_item(root, path, key, __find_xattr, &ctx);
3836         if (ret < 0)
3837                 return ret;
3838
3839         if (ctx.found_idx == -1)
3840                 return -ENOENT;
3841         if (data) {
3842                 *data = ctx.found_data;
3843                 *data_len = ctx.found_data_len;
3844         } else {
3845                 kfree(ctx.found_data);
3846         }
3847         return ctx.found_idx;
3848 }
3849
3850
3851 static int __process_changed_new_xattr(int num, struct btrfs_key *di_key,
3852                                        const char *name, int name_len,
3853                                        const char *data, int data_len,
3854                                        u8 type, void *ctx)
3855 {
3856         int ret;
3857         struct send_ctx *sctx = ctx;
3858         char *found_data = NULL;
3859         int found_data_len  = 0;
3860
3861         ret = find_xattr(sctx->parent_root, sctx->right_path,
3862                          sctx->cmp_key, name, name_len, &found_data,
3863                          &found_data_len);
3864         if (ret == -ENOENT) {
3865                 ret = __process_new_xattr(num, di_key, name, name_len, data,
3866                                 data_len, type, ctx);
3867         } else if (ret >= 0) {
3868                 if (data_len != found_data_len ||
3869                     memcmp(data, found_data, data_len)) {
3870                         ret = __process_new_xattr(num, di_key, name, name_len,
3871                                         data, data_len, type, ctx);
3872                 } else {
3873                         ret = 0;
3874                 }
3875         }
3876
3877         kfree(found_data);
3878         return ret;
3879 }
3880
3881 static int __process_changed_deleted_xattr(int num, struct btrfs_key *di_key,
3882                                            const char *name, int name_len,
3883                                            const char *data, int data_len,
3884                                            u8 type, void *ctx)
3885 {
3886         int ret;
3887         struct send_ctx *sctx = ctx;
3888
3889         ret = find_xattr(sctx->send_root, sctx->left_path, sctx->cmp_key,
3890                          name, name_len, NULL, NULL);
3891         if (ret == -ENOENT)
3892                 ret = __process_deleted_xattr(num, di_key, name, name_len, data,
3893                                 data_len, type, ctx);
3894         else if (ret >= 0)
3895                 ret = 0;
3896
3897         return ret;
3898 }
3899
3900 static int process_changed_xattr(struct send_ctx *sctx)
3901 {
3902         int ret = 0;
3903
3904         ret = iterate_dir_item(sctx->send_root, sctx->left_path,
3905                         sctx->cmp_key, __process_changed_new_xattr, sctx);
3906         if (ret < 0)
3907                 goto out;
3908         ret = iterate_dir_item(sctx->parent_root, sctx->right_path,
3909                         sctx->cmp_key, __process_changed_deleted_xattr, sctx);
3910
3911 out:
3912         return ret;
3913 }
3914
3915 static int process_all_new_xattrs(struct send_ctx *sctx)
3916 {
3917         int ret;
3918         struct btrfs_root *root;
3919         struct btrfs_path *path;
3920         struct btrfs_key key;
3921         struct btrfs_key found_key;
3922         struct extent_buffer *eb;
3923         int slot;
3924
3925         path = alloc_path_for_send();
3926         if (!path)
3927                 return -ENOMEM;
3928
3929         root = sctx->send_root;
3930
3931         key.objectid = sctx->cmp_key->objectid;
3932         key.type = BTRFS_XATTR_ITEM_KEY;
3933         key.offset = 0;
3934         while (1) {
3935                 ret = btrfs_search_slot_for_read(root, &key, path, 1, 0);
3936                 if (ret < 0)
3937                         goto out;
3938                 if (ret) {
3939                         ret = 0;
3940                         goto out;
3941                 }
3942
3943                 eb = path->nodes[0];
3944                 slot = path->slots[0];
3945                 btrfs_item_key_to_cpu(eb, &found_key, slot);
3946
3947                 if (found_key.objectid != key.objectid ||
3948                     found_key.type != key.type) {
3949                         ret = 0;
3950                         goto out;
3951                 }
3952
3953                 ret = iterate_dir_item(root, path, &found_key,
3954                                        __process_new_xattr, sctx);
3955                 if (ret < 0)
3956                         goto out;
3957
3958                 btrfs_release_path(path);
3959                 key.offset = found_key.offset + 1;
3960         }
3961
3962 out:
3963         btrfs_free_path(path);
3964         return ret;
3965 }
3966
3967 static ssize_t fill_read_buf(struct send_ctx *sctx, u64 offset, u32 len)
3968 {
3969         struct btrfs_root *root = sctx->send_root;
3970         struct btrfs_fs_info *fs_info = root->fs_info;
3971         struct inode *inode;
3972         struct page *page;
3973         char *addr;
3974         struct btrfs_key key;
3975         pgoff_t index = offset >> PAGE_CACHE_SHIFT;
3976         pgoff_t last_index;
3977         unsigned pg_offset = offset & ~PAGE_CACHE_MASK;
3978         ssize_t ret = 0;
3979
3980         key.objectid = sctx->cur_ino;
3981         key.type = BTRFS_INODE_ITEM_KEY;
3982         key.offset = 0;
3983
3984         inode = btrfs_iget(fs_info->sb, &key, root, NULL);
3985         if (IS_ERR(inode))
3986                 return PTR_ERR(inode);
3987
3988         if (offset + len > i_size_read(inode)) {
3989                 if (offset > i_size_read(inode))
3990                         len = 0;
3991                 else
3992                         len = offset - i_size_read(inode);
3993         }
3994         if (len == 0)
3995                 goto out;
3996
3997         last_index = (offset + len - 1) >> PAGE_CACHE_SHIFT;
3998         while (index <= last_index) {
3999                 unsigned cur_len = min_t(unsigned, len,
4000                                          PAGE_CACHE_SIZE - pg_offset);
4001                 page = find_or_create_page(inode->i_mapping, index, GFP_NOFS);
4002                 if (!page) {
4003                         ret = -ENOMEM;
4004                         break;
4005                 }
4006
4007                 if (!PageUptodate(page)) {
4008                         btrfs_readpage(NULL, page);
4009                         lock_page(page);
4010                         if (!PageUptodate(page)) {
4011                                 unlock_page(page);
4012                                 page_cache_release(page);
4013                                 ret = -EIO;
4014                                 break;
4015                         }
4016                 }
4017
4018                 addr = kmap(page);
4019                 memcpy(sctx->read_buf + ret, addr + pg_offset, cur_len);
4020                 kunmap(page);
4021                 unlock_page(page);
4022                 page_cache_release(page);
4023                 index++;
4024                 pg_offset = 0;
4025                 len -= cur_len;
4026                 ret += cur_len;
4027         }
4028 out:
4029         iput(inode);
4030         return ret;
4031 }
4032
4033 /*
4034  * Read some bytes from the current inode/file and send a write command to
4035  * user space.
4036  */
4037 static int send_write(struct send_ctx *sctx, u64 offset, u32 len)
4038 {
4039         int ret = 0;
4040         struct fs_path *p;
4041         ssize_t num_read = 0;
4042
4043         p = fs_path_alloc();
4044         if (!p)
4045                 return -ENOMEM;
4046
4047 verbose_printk("btrfs: send_write offset=%llu, len=%d\n", offset, len);
4048
4049         num_read = fill_read_buf(sctx, offset, len);
4050         if (num_read <= 0) {
4051                 if (num_read < 0)
4052                         ret = num_read;
4053                 goto out;
4054         }
4055
4056         ret = begin_cmd(sctx, BTRFS_SEND_C_WRITE);
4057         if (ret < 0)
4058                 goto out;
4059
4060         ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
4061         if (ret < 0)
4062                 goto out;
4063
4064         TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
4065         TLV_PUT_U64(sctx, BTRFS_SEND_A_FILE_OFFSET, offset);
4066         TLV_PUT(sctx, BTRFS_SEND_A_DATA, sctx->read_buf, num_read);
4067
4068         ret = send_cmd(sctx);
4069
4070 tlv_put_failure:
4071 out:
4072         fs_path_free(p);
4073         if (ret < 0)
4074                 return ret;
4075         return num_read;
4076 }
4077
4078 /*
4079  * Send a clone command to user space.
4080  */
4081 static int send_clone(struct send_ctx *sctx,
4082                       u64 offset, u32 len,
4083                       struct clone_root *clone_root)
4084 {
4085         int ret = 0;
4086         struct fs_path *p;
4087         u64 gen;
4088
4089 verbose_printk("btrfs: send_clone offset=%llu, len=%d, clone_root=%llu, "
4090                "clone_inode=%llu, clone_offset=%llu\n", offset, len,
4091                 clone_root->root->objectid, clone_root->ino,
4092                 clone_root->offset);
4093
4094         p = fs_path_alloc();
4095         if (!p)
4096                 return -ENOMEM;
4097
4098         ret = begin_cmd(sctx, BTRFS_SEND_C_CLONE);
4099         if (ret < 0)
4100                 goto out;
4101
4102         ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
4103         if (ret < 0)
4104                 goto out;
4105
4106         TLV_PUT_U64(sctx, BTRFS_SEND_A_FILE_OFFSET, offset);
4107         TLV_PUT_U64(sctx, BTRFS_SEND_A_CLONE_LEN, len);
4108         TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
4109
4110         if (clone_root->root == sctx->send_root) {
4111                 ret = get_inode_info(sctx->send_root, clone_root->ino, NULL,
4112                                 &gen, NULL, NULL, NULL, NULL);
4113                 if (ret < 0)
4114                         goto out;
4115                 ret = get_cur_path(sctx, clone_root->ino, gen, p);
4116         } else {
4117                 ret = get_inode_path(clone_root->root, clone_root->ino, p);
4118         }
4119         if (ret < 0)
4120                 goto out;
4121
4122         TLV_PUT_UUID(sctx, BTRFS_SEND_A_CLONE_UUID,
4123                         clone_root->root->root_item.uuid);
4124         TLV_PUT_U64(sctx, BTRFS_SEND_A_CLONE_CTRANSID,
4125                     le64_to_cpu(clone_root->root->root_item.ctransid));
4126         TLV_PUT_PATH(sctx, BTRFS_SEND_A_CLONE_PATH, p);
4127         TLV_PUT_U64(sctx, BTRFS_SEND_A_CLONE_OFFSET,
4128                         clone_root->offset);
4129
4130         ret = send_cmd(sctx);
4131
4132 tlv_put_failure:
4133 out:
4134         fs_path_free(p);
4135         return ret;
4136 }
4137
4138 /*
4139  * Send an update extent command to user space.
4140  */
4141 static int send_update_extent(struct send_ctx *sctx,
4142                               u64 offset, u32 len)
4143 {
4144         int ret = 0;
4145         struct fs_path *p;
4146
4147         p = fs_path_alloc();
4148         if (!p)
4149                 return -ENOMEM;
4150
4151         ret = begin_cmd(sctx, BTRFS_SEND_C_UPDATE_EXTENT);
4152         if (ret < 0)
4153                 goto out;
4154
4155         ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
4156         if (ret < 0)
4157                 goto out;
4158
4159         TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
4160         TLV_PUT_U64(sctx, BTRFS_SEND_A_FILE_OFFSET, offset);
4161         TLV_PUT_U64(sctx, BTRFS_SEND_A_SIZE, len);
4162
4163         ret = send_cmd(sctx);
4164
4165 tlv_put_failure:
4166 out:
4167         fs_path_free(p);
4168         return ret;
4169 }
4170
4171 static int send_hole(struct send_ctx *sctx, u64 end)
4172 {
4173         struct fs_path *p = NULL;
4174         u64 offset = sctx->cur_inode_last_extent;
4175         u64 len;
4176         int ret = 0;
4177
4178         p = fs_path_alloc();
4179         if (!p)
4180                 return -ENOMEM;
4181         memset(sctx->read_buf, 0, BTRFS_SEND_READ_SIZE);
4182         while (offset < end) {
4183                 len = min_t(u64, end - offset, BTRFS_SEND_READ_SIZE);
4184
4185                 ret = begin_cmd(sctx, BTRFS_SEND_C_WRITE);
4186                 if (ret < 0)
4187                         break;
4188                 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
4189                 if (ret < 0)
4190                         break;
4191                 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
4192                 TLV_PUT_U64(sctx, BTRFS_SEND_A_FILE_OFFSET, offset);
4193                 TLV_PUT(sctx, BTRFS_SEND_A_DATA, sctx->read_buf, len);
4194                 ret = send_cmd(sctx);
4195                 if (ret < 0)
4196                         break;
4197                 offset += len;
4198         }
4199 tlv_put_failure:
4200         fs_path_free(p);
4201         return ret;
4202 }
4203
4204 static int send_write_or_clone(struct send_ctx *sctx,
4205                                struct btrfs_path *path,
4206                                struct btrfs_key *key,
4207                                struct clone_root *clone_root)
4208 {
4209         int ret = 0;
4210         struct btrfs_file_extent_item *ei;
4211         u64 offset = key->offset;
4212         u64 pos = 0;
4213         u64 len;
4214         u32 l;
4215         u8 type;
4216         u64 bs = sctx->send_root->fs_info->sb->s_blocksize;
4217
4218         ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
4219                         struct btrfs_file_extent_item);
4220         type = btrfs_file_extent_type(path->nodes[0], ei);
4221         if (type == BTRFS_FILE_EXTENT_INLINE) {
4222                 len = btrfs_file_extent_inline_len(path->nodes[0],
4223                                                    path->slots[0], ei);
4224                 /*
4225                  * it is possible the inline item won't cover the whole page,
4226                  * but there may be items after this page.  Make
4227                  * sure to send the whole thing
4228                  */
4229                 len = PAGE_CACHE_ALIGN(len);
4230         } else {
4231                 len = btrfs_file_extent_num_bytes(path->nodes[0], ei);
4232         }
4233
4234         if (offset + len > sctx->cur_inode_size)
4235                 len = sctx->cur_inode_size - offset;
4236         if (len == 0) {
4237                 ret = 0;
4238                 goto out;
4239         }
4240
4241         if (clone_root && IS_ALIGNED(offset + len, bs)) {
4242                 ret = send_clone(sctx, offset, len, clone_root);
4243         } else if (sctx->flags & BTRFS_SEND_FLAG_NO_FILE_DATA) {
4244                 ret = send_update_extent(sctx, offset, len);
4245         } else {
4246                 while (pos < len) {
4247                         l = len - pos;
4248                         if (l > BTRFS_SEND_READ_SIZE)
4249                                 l = BTRFS_SEND_READ_SIZE;
4250                         ret = send_write(sctx, pos + offset, l);
4251                         if (ret < 0)
4252                                 goto out;
4253                         if (!ret)
4254                                 break;
4255                         pos += ret;
4256                 }
4257                 ret = 0;
4258         }
4259 out:
4260         return ret;
4261 }
4262
4263 static int is_extent_unchanged(struct send_ctx *sctx,
4264                                struct btrfs_path *left_path,
4265                                struct btrfs_key *ekey)
4266 {
4267         int ret = 0;
4268         struct btrfs_key key;
4269         struct btrfs_path *path = NULL;
4270         struct extent_buffer *eb;
4271         int slot;
4272         struct btrfs_key found_key;
4273         struct btrfs_file_extent_item *ei;
4274         u64 left_disknr;
4275         u64 right_disknr;
4276         u64 left_offset;
4277         u64 right_offset;
4278         u64 left_offset_fixed;
4279         u64 left_len;
4280         u64 right_len;
4281         u64 left_gen;
4282         u64 right_gen;
4283         u8 left_type;
4284         u8 right_type;
4285
4286         path = alloc_path_for_send();
4287         if (!path)
4288                 return -ENOMEM;
4289
4290         eb = left_path->nodes[0];
4291         slot = left_path->slots[0];
4292         ei = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
4293         left_type = btrfs_file_extent_type(eb, ei);
4294
4295         if (left_type != BTRFS_FILE_EXTENT_REG) {
4296                 ret = 0;
4297                 goto out;
4298         }
4299         left_disknr = btrfs_file_extent_disk_bytenr(eb, ei);
4300         left_len = btrfs_file_extent_num_bytes(eb, ei);
4301         left_offset = btrfs_file_extent_offset(eb, ei);
4302         left_gen = btrfs_file_extent_generation(eb, ei);
4303
4304         /*
4305          * Following comments will refer to these graphics. L is the left
4306          * extents which we are checking at the moment. 1-8 are the right
4307          * extents that we iterate.
4308          *
4309          *       |-----L-----|
4310          * |-1-|-2a-|-3-|-4-|-5-|-6-|
4311          *
4312          *       |-----L-----|
4313          * |--1--|-2b-|...(same as above)
4314          *
4315          * Alternative situation. Happens on files where extents got split.
4316          *       |-----L-----|
4317          * |-----------7-----------|-6-|
4318          *
4319          * Alternative situation. Happens on files which got larger.
4320          *       |-----L-----|
4321          * |-8-|
4322          * Nothing follows after 8.
4323          */
4324
4325         key.objectid = ekey->objectid;
4326         key.type = BTRFS_EXTENT_DATA_KEY;
4327         key.offset = ekey->offset;
4328         ret = btrfs_search_slot_for_read(sctx->parent_root, &key, path, 0, 0);
4329         if (ret < 0)
4330                 goto out;
4331         if (ret) {
4332                 ret = 0;
4333                 goto out;
4334         }
4335
4336         /*
4337          * Handle special case where the right side has no extents at all.
4338          */
4339         eb = path->nodes[0];
4340         slot = path->slots[0];
4341         btrfs_item_key_to_cpu(eb, &found_key, slot);
4342         if (found_key.objectid != key.objectid ||
4343             found_key.type != key.type) {
4344                 /* If we're a hole then just pretend nothing changed */
4345                 ret = (left_disknr) ? 0 : 1;
4346                 goto out;
4347         }
4348
4349         /*
4350          * We're now on 2a, 2b or 7.
4351          */
4352         key = found_key;
4353         while (key.offset < ekey->offset + left_len) {
4354                 ei = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
4355                 right_type = btrfs_file_extent_type(eb, ei);
4356                 if (right_type != BTRFS_FILE_EXTENT_REG) {
4357                         ret = 0;
4358                         goto out;
4359                 }
4360
4361                 right_disknr = btrfs_file_extent_disk_bytenr(eb, ei);
4362                 right_len = btrfs_file_extent_num_bytes(eb, ei);
4363                 right_offset = btrfs_file_extent_offset(eb, ei);
4364                 right_gen = btrfs_file_extent_generation(eb, ei);
4365
4366                 /*
4367                  * Are we at extent 8? If yes, we know the extent is changed.
4368                  * This may only happen on the first iteration.
4369                  */
4370                 if (found_key.offset + right_len <= ekey->offset) {
4371                         /* If we're a hole just pretend nothing changed */
4372                         ret = (left_disknr) ? 0 : 1;
4373                         goto out;
4374                 }
4375
4376                 left_offset_fixed = left_offset;
4377                 if (key.offset < ekey->offset) {
4378                         /* Fix the right offset for 2a and 7. */
4379                         right_offset += ekey->offset - key.offset;
4380                 } else {
4381                         /* Fix the left offset for all behind 2a and 2b */
4382                         left_offset_fixed += key.offset - ekey->offset;
4383                 }
4384
4385                 /*
4386                  * Check if we have the same extent.
4387                  */
4388                 if (left_disknr != right_disknr ||
4389                     left_offset_fixed != right_offset ||
4390                     left_gen != right_gen) {
4391                         ret = 0;
4392                         goto out;
4393                 }
4394
4395                 /*
4396                  * Go to the next extent.
4397                  */
4398                 ret = btrfs_next_item(sctx->parent_root, path);
4399                 if (ret < 0)
4400                         goto out;
4401                 if (!ret) {
4402                         eb = path->nodes[0];
4403                         slot = path->slots[0];
4404                         btrfs_item_key_to_cpu(eb, &found_key, slot);
4405                 }
4406                 if (ret || found_key.objectid != key.objectid ||
4407                     found_key.type != key.type) {
4408                         key.offset += right_len;
4409                         break;
4410                 }
4411                 if (found_key.offset != key.offset + right_len) {
4412                         ret = 0;
4413                         goto out;
4414                 }
4415                 key = found_key;
4416         }
4417
4418         /*
4419          * We're now behind the left extent (treat as unchanged) or at the end
4420          * of the right side (treat as changed).
4421          */
4422         if (key.offset >= ekey->offset + left_len)
4423                 ret = 1;
4424         else
4425                 ret = 0;
4426
4427
4428 out:
4429         btrfs_free_path(path);
4430         return ret;
4431 }
4432
4433 static int get_last_extent(struct send_ctx *sctx, u64 offset)
4434 {
4435         struct btrfs_path *path;
4436         struct btrfs_root *root = sctx->send_root;
4437         struct btrfs_file_extent_item *fi;
4438         struct btrfs_key key;
4439         u64 extent_end;
4440         u8 type;
4441         int ret;
4442
4443         path = alloc_path_for_send();
4444         if (!path)
4445                 return -ENOMEM;
4446
4447         sctx->cur_inode_last_extent = 0;
4448
4449         key.objectid = sctx->cur_ino;
4450         key.type = BTRFS_EXTENT_DATA_KEY;
4451         key.offset = offset;
4452         ret = btrfs_search_slot_for_read(root, &key, path, 0, 1);
4453         if (ret < 0)
4454                 goto out;
4455         ret = 0;
4456         btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
4457         if (key.objectid != sctx->cur_ino || key.type != BTRFS_EXTENT_DATA_KEY)
4458                 goto out;
4459
4460         fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
4461                             struct btrfs_file_extent_item);
4462         type = btrfs_file_extent_type(path->nodes[0], fi);
4463         if (type == BTRFS_FILE_EXTENT_INLINE) {
4464                 u64 size = btrfs_file_extent_inline_len(path->nodes[0],
4465                                                         path->slots[0], fi);
4466                 extent_end = ALIGN(key.offset + size,
4467                                    sctx->send_root->sectorsize);
4468         } else {
4469                 extent_end = key.offset +
4470                         btrfs_file_extent_num_bytes(path->nodes[0], fi);
4471         }
4472         sctx->cur_inode_last_extent = extent_end;
4473 out:
4474         btrfs_free_path(path);
4475         return ret;
4476 }
4477
4478 static int maybe_send_hole(struct send_ctx *sctx, struct btrfs_path *path,
4479                            struct btrfs_key *key)
4480 {
4481         struct btrfs_file_extent_item *fi;
4482         u64 extent_end;
4483         u8 type;
4484         int ret = 0;
4485
4486         if (sctx->cur_ino != key->objectid || !need_send_hole(sctx))
4487                 return 0;
4488
4489         if (sctx->cur_inode_last_extent == (u64)-1) {
4490                 ret = get_last_extent(sctx, key->offset - 1);
4491                 if (ret)
4492                         return ret;
4493         }
4494
4495         fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
4496                             struct btrfs_file_extent_item);
4497         type = btrfs_file_extent_type(path->nodes[0], fi);
4498         if (type == BTRFS_FILE_EXTENT_INLINE) {
4499                 u64 size = btrfs_file_extent_inline_len(path->nodes[0],
4500                                                         path->slots[0], fi);
4501                 extent_end = ALIGN(key->offset + size,
4502                                    sctx->send_root->sectorsize);
4503         } else {
4504                 extent_end = key->offset +
4505                         btrfs_file_extent_num_bytes(path->nodes[0], fi);
4506         }
4507
4508         if (path->slots[0] == 0 &&
4509             sctx->cur_inode_last_extent < key->offset) {
4510                 /*
4511                  * We might have skipped entire leafs that contained only
4512                  * file extent items for our current inode. These leafs have
4513                  * a generation number smaller (older) than the one in the
4514                  * current leaf and the leaf our last extent came from, and
4515                  * are located between these 2 leafs.
4516                  */
4517                 ret = get_last_extent(sctx, key->offset - 1);
4518                 if (ret)
4519                         return ret;
4520         }
4521
4522         if (sctx->cur_inode_last_extent < key->offset)
4523                 ret = send_hole(sctx, key->offset);
4524         sctx->cur_inode_last_extent = extent_end;
4525         return ret;
4526 }
4527
4528 static int process_extent(struct send_ctx *sctx,
4529                           struct btrfs_path *path,
4530                           struct btrfs_key *key)
4531 {
4532         struct clone_root *found_clone = NULL;
4533         int ret = 0;
4534
4535         if (S_ISLNK(sctx->cur_inode_mode))
4536                 return 0;
4537
4538         if (sctx->parent_root && !sctx->cur_inode_new) {
4539                 ret = is_extent_unchanged(sctx, path, key);
4540                 if (ret < 0)
4541                         goto out;
4542                 if (ret) {
4543                         ret = 0;
4544                         goto out_hole;
4545                 }
4546         } else {
4547                 struct btrfs_file_extent_item *ei;
4548                 u8 type;
4549
4550                 ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
4551                                     struct btrfs_file_extent_item);
4552                 type = btrfs_file_extent_type(path->nodes[0], ei);
4553                 if (type == BTRFS_FILE_EXTENT_PREALLOC ||
4554                     type == BTRFS_FILE_EXTENT_REG) {
4555                         /*
4556                          * The send spec does not have a prealloc command yet,
4557                          * so just leave a hole for prealloc'ed extents until
4558                          * we have enough commands queued up to justify rev'ing
4559                          * the send spec.
4560                          */
4561                         if (type == BTRFS_FILE_EXTENT_PREALLOC) {
4562                                 ret = 0;
4563                                 goto out;
4564                         }
4565
4566                         /* Have a hole, just skip it. */
4567                         if (btrfs_file_extent_disk_bytenr(path->nodes[0], ei) == 0) {
4568                                 ret = 0;
4569                                 goto out;
4570                         }
4571                 }
4572         }
4573
4574         ret = find_extent_clone(sctx, path, key->objectid, key->offset,
4575                         sctx->cur_inode_size, &found_clone);
4576         if (ret != -ENOENT && ret < 0)
4577                 goto out;
4578
4579         ret = send_write_or_clone(sctx, path, key, found_clone);
4580         if (ret)
4581                 goto out;
4582 out_hole:
4583         ret = maybe_send_hole(sctx, path, key);
4584 out:
4585         return ret;
4586 }
4587
4588 static int process_all_extents(struct send_ctx *sctx)
4589 {
4590         int ret;
4591         struct btrfs_root *root;
4592         struct btrfs_path *path;
4593         struct btrfs_key key;
4594         struct btrfs_key found_key;
4595         struct extent_buffer *eb;
4596         int slot;
4597
4598         root = sctx->send_root;
4599         path = alloc_path_for_send();
4600         if (!path)
4601                 return -ENOMEM;
4602
4603         key.objectid = sctx->cmp_key->objectid;
4604         key.type = BTRFS_EXTENT_DATA_KEY;
4605         key.offset = 0;
4606         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4607         if (ret < 0)
4608                 goto out;
4609
4610         while (1) {
4611                 eb = path->nodes[0];
4612                 slot = path->slots[0];
4613
4614                 if (slot >= btrfs_header_nritems(eb)) {
4615                         ret = btrfs_next_leaf(root, path);
4616                         if (ret < 0) {
4617                                 goto out;
4618                         } else if (ret > 0) {
4619                                 ret = 0;
4620                                 break;
4621                         }
4622                         continue;
4623                 }
4624
4625                 btrfs_item_key_to_cpu(eb, &found_key, slot);
4626
4627                 if (found_key.objectid != key.objectid ||
4628                     found_key.type != key.type) {
4629                         ret = 0;
4630                         goto out;
4631                 }
4632
4633                 ret = process_extent(sctx, path, &found_key);
4634                 if (ret < 0)
4635                         goto out;
4636
4637                 path->slots[0]++;
4638         }
4639
4640 out:
4641         btrfs_free_path(path);
4642         return ret;
4643 }
4644
4645 static int process_recorded_refs_if_needed(struct send_ctx *sctx, int at_end,
4646                                            int *pending_move,
4647                                            int *refs_processed)
4648 {
4649         int ret = 0;
4650
4651         if (sctx->cur_ino == 0)
4652                 goto out;
4653         if (!at_end && sctx->cur_ino == sctx->cmp_key->objectid &&
4654             sctx->cmp_key->type <= BTRFS_INODE_EXTREF_KEY)
4655                 goto out;
4656         if (list_empty(&sctx->new_refs) && list_empty(&sctx->deleted_refs))
4657                 goto out;
4658
4659         ret = process_recorded_refs(sctx, pending_move);
4660         if (ret < 0)
4661                 goto out;
4662
4663         *refs_processed = 1;
4664 out:
4665         return ret;
4666 }
4667
4668 static int finish_inode_if_needed(struct send_ctx *sctx, int at_end)
4669 {
4670         int ret = 0;
4671         u64 left_mode;
4672         u64 left_uid;
4673         u64 left_gid;
4674         u64 right_mode;
4675         u64 right_uid;
4676         u64 right_gid;
4677         int need_chmod = 0;
4678         int need_chown = 0;
4679         int pending_move = 0;
4680         int refs_processed = 0;
4681
4682         ret = process_recorded_refs_if_needed(sctx, at_end, &pending_move,
4683                                               &refs_processed);
4684         if (ret < 0)
4685                 goto out;
4686
4687         /*
4688          * We have processed the refs and thus need to advance send_progress.
4689          * Now, calls to get_cur_xxx will take the updated refs of the current
4690          * inode into account.
4691          *
4692          * On the other hand, if our current inode is a directory and couldn't
4693          * be moved/renamed because its parent was renamed/moved too and it has
4694          * a higher inode number, we can only move/rename our current inode
4695          * after we moved/renamed its parent. Therefore in this case operate on
4696          * the old path (pre move/rename) of our current inode, and the
4697          * move/rename will be performed later.
4698          */
4699         if (refs_processed && !pending_move)
4700                 sctx->send_progress = sctx->cur_ino + 1;
4701
4702         if (sctx->cur_ino == 0 || sctx->cur_inode_deleted)
4703                 goto out;
4704         if (!at_end && sctx->cmp_key->objectid == sctx->cur_ino)
4705                 goto out;
4706
4707         ret = get_inode_info(sctx->send_root, sctx->cur_ino, NULL, NULL,
4708                         &left_mode, &left_uid, &left_gid, NULL);
4709         if (ret < 0)
4710                 goto out;
4711
4712         if (!sctx->parent_root || sctx->cur_inode_new) {
4713                 need_chown = 1;
4714                 if (!S_ISLNK(sctx->cur_inode_mode))
4715                         need_chmod = 1;
4716         } else {
4717                 ret = get_inode_info(sctx->parent_root, sctx->cur_ino,
4718                                 NULL, NULL, &right_mode, &right_uid,
4719                                 &right_gid, NULL);
4720                 if (ret < 0)
4721                         goto out;
4722
4723                 if (left_uid != right_uid || left_gid != right_gid)
4724                         need_chown = 1;
4725                 if (!S_ISLNK(sctx->cur_inode_mode) && left_mode != right_mode)
4726                         need_chmod = 1;
4727         }
4728
4729         if (S_ISREG(sctx->cur_inode_mode)) {
4730                 if (need_send_hole(sctx)) {
4731                         if (sctx->cur_inode_last_extent == (u64)-1) {
4732                                 ret = get_last_extent(sctx, (u64)-1);
4733                                 if (ret)
4734                                         goto out;
4735                         }
4736                         if (sctx->cur_inode_last_extent <
4737                             sctx->cur_inode_size) {
4738                                 ret = send_hole(sctx, sctx->cur_inode_size);
4739                                 if (ret)
4740                                         goto out;
4741                         }
4742                 }
4743                 ret = send_truncate(sctx, sctx->cur_ino, sctx->cur_inode_gen,
4744                                 sctx->cur_inode_size);
4745                 if (ret < 0)
4746                         goto out;
4747         }
4748
4749         if (need_chown) {
4750                 ret = send_chown(sctx, sctx->cur_ino, sctx->cur_inode_gen,
4751                                 left_uid, left_gid);
4752                 if (ret < 0)
4753                         goto out;
4754         }
4755         if (need_chmod) {
4756                 ret = send_chmod(sctx, sctx->cur_ino, sctx->cur_inode_gen,
4757                                 left_mode);
4758                 if (ret < 0)
4759                         goto out;
4760         }
4761
4762         /*
4763          * If other directory inodes depended on our current directory
4764          * inode's move/rename, now do their move/rename operations.
4765          */
4766         if (!is_waiting_for_move(sctx, sctx->cur_ino)) {
4767                 ret = apply_children_dir_moves(sctx);
4768                 if (ret)
4769                         goto out;
4770         }
4771
4772         /*
4773          * Need to send that every time, no matter if it actually
4774          * changed between the two trees as we have done changes to
4775          * the inode before.
4776          */
4777         sctx->send_progress = sctx->cur_ino + 1;
4778         ret = send_utimes(sctx, sctx->cur_ino, sctx->cur_inode_gen);
4779         if (ret < 0)
4780                 goto out;
4781
4782 out:
4783         return ret;
4784 }
4785
4786 static int changed_inode(struct send_ctx *sctx,
4787                          enum btrfs_compare_tree_result result)
4788 {
4789         int ret = 0;
4790         struct btrfs_key *key = sctx->cmp_key;
4791         struct btrfs_inode_item *left_ii = NULL;
4792         struct btrfs_inode_item *right_ii = NULL;
4793         u64 left_gen = 0;
4794         u64 right_gen = 0;
4795
4796         sctx->cur_ino = key->objectid;
4797         sctx->cur_inode_new_gen = 0;
4798         sctx->cur_inode_last_extent = (u64)-1;
4799
4800         /*
4801          * Set send_progress to current inode. This will tell all get_cur_xxx
4802          * functions that the current inode's refs are not updated yet. Later,
4803          * when process_recorded_refs is finished, it is set to cur_ino + 1.
4804          */
4805         sctx->send_progress = sctx->cur_ino;
4806
4807         if (result == BTRFS_COMPARE_TREE_NEW ||
4808             result == BTRFS_COMPARE_TREE_CHANGED) {
4809                 left_ii = btrfs_item_ptr(sctx->left_path->nodes[0],
4810                                 sctx->left_path->slots[0],
4811                                 struct btrfs_inode_item);
4812                 left_gen = btrfs_inode_generation(sctx->left_path->nodes[0],
4813                                 left_ii);
4814         } else {
4815                 right_ii = btrfs_item_ptr(sctx->right_path->nodes[0],
4816                                 sctx->right_path->slots[0],
4817                                 struct btrfs_inode_item);
4818                 right_gen = btrfs_inode_generation(sctx->right_path->nodes[0],
4819                                 right_ii);
4820         }
4821         if (result == BTRFS_COMPARE_TREE_CHANGED) {
4822                 right_ii = btrfs_item_ptr(sctx->right_path->nodes[0],
4823                                 sctx->right_path->slots[0],
4824                                 struct btrfs_inode_item);
4825
4826                 right_gen = btrfs_inode_generation(sctx->right_path->nodes[0],
4827                                 right_ii);
4828
4829                 /*
4830                  * The cur_ino = root dir case is special here. We can't treat
4831                  * the inode as deleted+reused because it would generate a
4832                  * stream that tries to delete/mkdir the root dir.
4833                  */
4834                 if (left_gen != right_gen &&
4835                     sctx->cur_ino != BTRFS_FIRST_FREE_OBJECTID)
4836                         sctx->cur_inode_new_gen = 1;
4837         }
4838
4839         if (result == BTRFS_COMPARE_TREE_NEW) {
4840                 sctx->cur_inode_gen = left_gen;
4841                 sctx->cur_inode_new = 1;
4842                 sctx->cur_inode_deleted = 0;
4843                 sctx->cur_inode_size = btrfs_inode_size(
4844                                 sctx->left_path->nodes[0], left_ii);
4845                 sctx->cur_inode_mode = btrfs_inode_mode(
4846                                 sctx->left_path->nodes[0], left_ii);
4847                 if (sctx->cur_ino != BTRFS_FIRST_FREE_OBJECTID)
4848                         ret = send_create_inode_if_needed(sctx);
4849         } else if (result == BTRFS_COMPARE_TREE_DELETED) {
4850                 sctx->cur_inode_gen = right_gen;
4851                 sctx->cur_inode_new = 0;
4852                 sctx->cur_inode_deleted = 1;
4853                 sctx->cur_inode_size = btrfs_inode_size(
4854                                 sctx->right_path->nodes[0], right_ii);
4855                 sctx->cur_inode_mode = btrfs_inode_mode(
4856                                 sctx->right_path->nodes[0], right_ii);
4857         } else if (result == BTRFS_COMPARE_TREE_CHANGED) {
4858                 /*
4859                  * We need to do some special handling in case the inode was
4860                  * reported as changed with a changed generation number. This
4861                  * means that the original inode was deleted and new inode
4862                  * reused the same inum. So we have to treat the old inode as
4863                  * deleted and the new one as new.
4864                  */
4865                 if (sctx->cur_inode_new_gen) {
4866                         /*
4867                          * First, process the inode as if it was deleted.
4868                          */
4869                         sctx->cur_inode_gen = right_gen;
4870                         sctx->cur_inode_new = 0;
4871                         sctx->cur_inode_deleted = 1;
4872                         sctx->cur_inode_size = btrfs_inode_size(
4873                                         sctx->right_path->nodes[0], right_ii);
4874                         sctx->cur_inode_mode = btrfs_inode_mode(
4875                                         sctx->right_path->nodes[0], right_ii);
4876                         ret = process_all_refs(sctx,
4877                                         BTRFS_COMPARE_TREE_DELETED);
4878                         if (ret < 0)
4879                                 goto out;
4880
4881                         /*
4882                          * Now process the inode as if it was new.
4883                          */
4884                         sctx->cur_inode_gen = left_gen;
4885                         sctx->cur_inode_new = 1;
4886                         sctx->cur_inode_deleted = 0;
4887                         sctx->cur_inode_size = btrfs_inode_size(
4888                                         sctx->left_path->nodes[0], left_ii);
4889                         sctx->cur_inode_mode = btrfs_inode_mode(
4890                                         sctx->left_path->nodes[0], left_ii);
4891                         ret = send_create_inode_if_needed(sctx);
4892                         if (ret < 0)
4893                                 goto out;
4894
4895                         ret = process_all_refs(sctx, BTRFS_COMPARE_TREE_NEW);
4896                         if (ret < 0)
4897                                 goto out;
4898                         /*
4899                          * Advance send_progress now as we did not get into
4900                          * process_recorded_refs_if_needed in the new_gen case.
4901                          */
4902                         sctx->send_progress = sctx->cur_ino + 1;
4903
4904                         /*
4905                          * Now process all extents and xattrs of the inode as if
4906                          * they were all new.
4907                          */
4908                         ret = process_all_extents(sctx);
4909                         if (ret < 0)
4910                                 goto out;
4911                         ret = process_all_new_xattrs(sctx);
4912                         if (ret < 0)
4913                                 goto out;
4914                 } else {
4915                         sctx->cur_inode_gen = left_gen;
4916                         sctx->cur_inode_new = 0;
4917                         sctx->cur_inode_new_gen = 0;
4918                         sctx->cur_inode_deleted = 0;
4919                         sctx->cur_inode_size = btrfs_inode_size(
4920                                         sctx->left_path->nodes[0], left_ii);
4921                         sctx->cur_inode_mode = btrfs_inode_mode(
4922                                         sctx->left_path->nodes[0], left_ii);
4923                 }
4924         }
4925
4926 out:
4927         return ret;
4928 }
4929
4930 /*
4931  * We have to process new refs before deleted refs, but compare_trees gives us
4932  * the new and deleted refs mixed. To fix this, we record the new/deleted refs
4933  * first and later process them in process_recorded_refs.
4934  * For the cur_inode_new_gen case, we skip recording completely because
4935  * changed_inode did already initiate processing of refs. The reason for this is
4936  * that in this case, compare_tree actually compares the refs of 2 different
4937  * inodes. To fix this, process_all_refs is used in changed_inode to handle all
4938  * refs of the right tree as deleted and all refs of the left tree as new.
4939  */
4940 static int changed_ref(struct send_ctx *sctx,
4941                        enum btrfs_compare_tree_result result)
4942 {
4943         int ret = 0;
4944
4945         BUG_ON(sctx->cur_ino != sctx->cmp_key->objectid);
4946
4947         if (!sctx->cur_inode_new_gen &&
4948             sctx->cur_ino != BTRFS_FIRST_FREE_OBJECTID) {
4949                 if (result == BTRFS_COMPARE_TREE_NEW)
4950                         ret = record_new_ref(sctx);
4951                 else if (result == BTRFS_COMPARE_TREE_DELETED)
4952                         ret = record_deleted_ref(sctx);
4953                 else if (result == BTRFS_COMPARE_TREE_CHANGED)
4954                         ret = record_changed_ref(sctx);
4955         }
4956
4957         return ret;
4958 }
4959
4960 /*
4961  * Process new/deleted/changed xattrs. We skip processing in the
4962  * cur_inode_new_gen case because changed_inode did already initiate processing
4963  * of xattrs. The reason is the same as in changed_ref
4964  */
4965 static int changed_xattr(struct send_ctx *sctx,
4966                          enum btrfs_compare_tree_result result)
4967 {
4968         int ret = 0;
4969
4970         BUG_ON(sctx->cur_ino != sctx->cmp_key->objectid);
4971
4972         if (!sctx->cur_inode_new_gen && !sctx->cur_inode_deleted) {
4973                 if (result == BTRFS_COMPARE_TREE_NEW)
4974                         ret = process_new_xattr(sctx);
4975                 else if (result == BTRFS_COMPARE_TREE_DELETED)
4976                         ret = process_deleted_xattr(sctx);
4977                 else if (result == BTRFS_COMPARE_TREE_CHANGED)
4978                         ret = process_changed_xattr(sctx);
4979         }
4980
4981         return ret;
4982 }
4983
4984 /*
4985  * Process new/deleted/changed extents. We skip processing in the
4986  * cur_inode_new_gen case because changed_inode did already initiate processing
4987  * of extents. The reason is the same as in changed_ref
4988  */
4989 static int changed_extent(struct send_ctx *sctx,
4990                           enum btrfs_compare_tree_result result)
4991 {
4992         int ret = 0;
4993
4994         BUG_ON(sctx->cur_ino != sctx->cmp_key->objectid);
4995
4996         if (!sctx->cur_inode_new_gen && !sctx->cur_inode_deleted) {
4997                 if (result != BTRFS_COMPARE_TREE_DELETED)
4998                         ret = process_extent(sctx, sctx->left_path,
4999                                         sctx->cmp_key);
5000         }
5001
5002         return ret;
5003 }
5004
5005 static int dir_changed(struct send_ctx *sctx, u64 dir)
5006 {
5007         u64 orig_gen, new_gen;
5008         int ret;
5009
5010         ret = get_inode_info(sctx->send_root, dir, NULL, &new_gen, NULL, NULL,
5011                              NULL, NULL);
5012         if (ret)
5013                 return ret;
5014
5015         ret = get_inode_info(sctx->parent_root, dir, NULL, &orig_gen, NULL,
5016                              NULL, NULL, NULL);
5017         if (ret)
5018                 return ret;
5019
5020         return (orig_gen != new_gen) ? 1 : 0;
5021 }
5022
5023 static int compare_refs(struct send_ctx *sctx, struct btrfs_path *path,
5024                         struct btrfs_key *key)
5025 {
5026         struct btrfs_inode_extref *extref;
5027         struct extent_buffer *leaf;
5028         u64 dirid = 0, last_dirid = 0;
5029         unsigned long ptr;
5030         u32 item_size;
5031         u32 cur_offset = 0;
5032         int ref_name_len;
5033         int ret = 0;
5034
5035         /* Easy case, just check this one dirid */
5036         if (key->type == BTRFS_INODE_REF_KEY) {
5037                 dirid = key->offset;
5038
5039                 ret = dir_changed(sctx, dirid);
5040                 goto out;
5041         }
5042
5043         leaf = path->nodes[0];
5044         item_size = btrfs_item_size_nr(leaf, path->slots[0]);
5045         ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
5046         while (cur_offset < item_size) {
5047                 extref = (struct btrfs_inode_extref *)(ptr +
5048                                                        cur_offset);
5049                 dirid = btrfs_inode_extref_parent(leaf, extref);
5050                 ref_name_len = btrfs_inode_extref_name_len(leaf, extref);
5051                 cur_offset += ref_name_len + sizeof(*extref);
5052                 if (dirid == last_dirid)
5053                         continue;
5054                 ret = dir_changed(sctx, dirid);
5055                 if (ret)
5056                         break;
5057                 last_dirid = dirid;
5058         }
5059 out:
5060         return ret;
5061 }
5062
5063 /*
5064  * Updates compare related fields in sctx and simply forwards to the actual
5065  * changed_xxx functions.
5066  */
5067 static int changed_cb(struct btrfs_root *left_root,
5068                       struct btrfs_root *right_root,
5069                       struct btrfs_path *left_path,
5070                       struct btrfs_path *right_path,
5071                       struct btrfs_key *key,
5072                       enum btrfs_compare_tree_result result,
5073                       void *ctx)
5074 {
5075         int ret = 0;
5076         struct send_ctx *sctx = ctx;
5077
5078         if (result == BTRFS_COMPARE_TREE_SAME) {
5079                 if (key->type == BTRFS_INODE_REF_KEY ||
5080                     key->type == BTRFS_INODE_EXTREF_KEY) {
5081                         ret = compare_refs(sctx, left_path, key);
5082                         if (!ret)
5083                                 return 0;
5084                         if (ret < 0)
5085                                 return ret;
5086                 } else if (key->type == BTRFS_EXTENT_DATA_KEY) {
5087                         return maybe_send_hole(sctx, left_path, key);
5088                 } else {
5089                         return 0;
5090                 }
5091                 result = BTRFS_COMPARE_TREE_CHANGED;
5092                 ret = 0;
5093         }
5094
5095         sctx->left_path = left_path;
5096         sctx->right_path = right_path;
5097         sctx->cmp_key = key;
5098
5099         ret = finish_inode_if_needed(sctx, 0);
5100         if (ret < 0)
5101                 goto out;
5102
5103         /* Ignore non-FS objects */
5104         if (key->objectid == BTRFS_FREE_INO_OBJECTID ||
5105             key->objectid == BTRFS_FREE_SPACE_OBJECTID)
5106                 goto out;
5107
5108         if (key->type == BTRFS_INODE_ITEM_KEY)
5109                 ret = changed_inode(sctx, result);
5110         else if (key->type == BTRFS_INODE_REF_KEY ||
5111                  key->type == BTRFS_INODE_EXTREF_KEY)
5112                 ret = changed_ref(sctx, result);
5113         else if (key->type == BTRFS_XATTR_ITEM_KEY)
5114                 ret = changed_xattr(sctx, result);
5115         else if (key->type == BTRFS_EXTENT_DATA_KEY)
5116                 ret = changed_extent(sctx, result);
5117
5118 out:
5119         return ret;
5120 }
5121
5122 static int full_send_tree(struct send_ctx *sctx)
5123 {
5124         int ret;
5125         struct btrfs_root *send_root = sctx->send_root;
5126         struct btrfs_key key;
5127         struct btrfs_key found_key;
5128         struct btrfs_path *path;
5129         struct extent_buffer *eb;
5130         int slot;
5131         u64 start_ctransid;
5132         u64 ctransid;
5133
5134         path = alloc_path_for_send();
5135         if (!path)
5136                 return -ENOMEM;
5137
5138         spin_lock(&send_root->root_item_lock);
5139         start_ctransid = btrfs_root_ctransid(&send_root->root_item);
5140         spin_unlock(&send_root->root_item_lock);
5141
5142         key.objectid = BTRFS_FIRST_FREE_OBJECTID;
5143         key.type = BTRFS_INODE_ITEM_KEY;
5144         key.offset = 0;
5145
5146         /*
5147          * Make sure the tree has not changed after re-joining. We detect this
5148          * by comparing start_ctransid and ctransid. They should always match.
5149          */
5150         spin_lock(&send_root->root_item_lock);
5151         ctransid = btrfs_root_ctransid(&send_root->root_item);
5152         spin_unlock(&send_root->root_item_lock);
5153
5154         if (ctransid != start_ctransid) {
5155                 WARN(1, KERN_WARNING "BTRFS: the root that you're trying to "
5156                                      "send was modified in between. This is "
5157                                      "probably a bug.\n");
5158                 ret = -EIO;
5159                 goto out;
5160         }
5161
5162         ret = btrfs_search_slot_for_read(send_root, &key, path, 1, 0);
5163         if (ret < 0)
5164                 goto out;
5165         if (ret)
5166                 goto out_finish;
5167
5168         while (1) {
5169                 eb = path->nodes[0];
5170                 slot = path->slots[0];
5171                 btrfs_item_key_to_cpu(eb, &found_key, slot);
5172
5173                 ret = changed_cb(send_root, NULL, path, NULL,
5174                                 &found_key, BTRFS_COMPARE_TREE_NEW, sctx);
5175                 if (ret < 0)
5176                         goto out;
5177
5178                 key.objectid = found_key.objectid;
5179                 key.type = found_key.type;
5180                 key.offset = found_key.offset + 1;
5181
5182                 ret = btrfs_next_item(send_root, path);
5183                 if (ret < 0)
5184                         goto out;
5185                 if (ret) {
5186                         ret  = 0;
5187                         break;
5188                 }
5189         }
5190
5191 out_finish:
5192         ret = finish_inode_if_needed(sctx, 1);
5193
5194 out:
5195         btrfs_free_path(path);
5196         return ret;
5197 }
5198
5199 static int send_subvol(struct send_ctx *sctx)
5200 {
5201         int ret;
5202
5203         if (!(sctx->flags & BTRFS_SEND_FLAG_OMIT_STREAM_HEADER)) {
5204                 ret = send_header(sctx);
5205                 if (ret < 0)
5206                         goto out;
5207         }
5208
5209         ret = send_subvol_begin(sctx);
5210         if (ret < 0)
5211                 goto out;
5212
5213         if (sctx->parent_root) {
5214                 ret = btrfs_compare_trees(sctx->send_root, sctx->parent_root,
5215                                 changed_cb, sctx);
5216                 if (ret < 0)
5217                         goto out;
5218                 ret = finish_inode_if_needed(sctx, 1);
5219                 if (ret < 0)
5220                         goto out;
5221         } else {
5222                 ret = full_send_tree(sctx);
5223                 if (ret < 0)
5224                         goto out;
5225         }
5226
5227 out:
5228         free_recorded_refs(sctx);
5229         return ret;
5230 }
5231
5232 static void btrfs_root_dec_send_in_progress(struct btrfs_root* root)
5233 {
5234         spin_lock(&root->root_item_lock);
5235         root->send_in_progress--;
5236         /*
5237          * Not much left to do, we don't know why it's unbalanced and
5238          * can't blindly reset it to 0.
5239          */
5240         if (root->send_in_progress < 0)
5241                 btrfs_err(root->fs_info,
5242                         "send_in_progres unbalanced %d root %llu\n",
5243                         root->send_in_progress, root->root_key.objectid);
5244         spin_unlock(&root->root_item_lock);
5245 }
5246
5247 long btrfs_ioctl_send(struct file *mnt_file, void __user *arg_)
5248 {
5249         int ret = 0;
5250         struct btrfs_root *send_root;
5251         struct btrfs_root *clone_root;
5252         struct btrfs_fs_info *fs_info;
5253         struct btrfs_ioctl_send_args *arg = NULL;
5254         struct btrfs_key key;
5255         struct send_ctx *sctx = NULL;
5256         u32 i;
5257         u64 *clone_sources_tmp = NULL;
5258         int clone_sources_to_rollback = 0;
5259         int sort_clone_roots = 0;
5260         int index;
5261
5262         if (!capable(CAP_SYS_ADMIN))
5263                 return -EPERM;
5264
5265         send_root = BTRFS_I(file_inode(mnt_file))->root;
5266         fs_info = send_root->fs_info;
5267
5268         /*
5269          * The subvolume must remain read-only during send, protect against
5270          * making it RW.
5271          */
5272         spin_lock(&send_root->root_item_lock);
5273         send_root->send_in_progress++;
5274         spin_unlock(&send_root->root_item_lock);
5275
5276         /*
5277          * This is done when we lookup the root, it should already be complete
5278          * by the time we get here.
5279          */
5280         WARN_ON(send_root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE);
5281
5282         /*
5283          * Userspace tools do the checks and warn the user if it's
5284          * not RO.
5285          */
5286         if (!btrfs_root_readonly(send_root)) {
5287                 ret = -EPERM;
5288                 goto out;
5289         }
5290
5291         arg = memdup_user(arg_, sizeof(*arg));
5292         if (IS_ERR(arg)) {
5293                 ret = PTR_ERR(arg);
5294                 arg = NULL;
5295                 goto out;
5296         }
5297
5298         if (!access_ok(VERIFY_READ, arg->clone_sources,
5299                         sizeof(*arg->clone_sources) *
5300                         arg->clone_sources_count)) {
5301                 ret = -EFAULT;
5302                 goto out;
5303         }
5304
5305         if (arg->flags & ~BTRFS_SEND_FLAG_MASK) {
5306                 ret = -EINVAL;
5307                 goto out;
5308         }
5309
5310         sctx = kzalloc(sizeof(struct send_ctx), GFP_NOFS);
5311         if (!sctx) {
5312                 ret = -ENOMEM;
5313                 goto out;
5314         }
5315
5316         INIT_LIST_HEAD(&sctx->new_refs);
5317         INIT_LIST_HEAD(&sctx->deleted_refs);
5318         INIT_RADIX_TREE(&sctx->name_cache, GFP_NOFS);
5319         INIT_LIST_HEAD(&sctx->name_cache_list);
5320
5321         sctx->flags = arg->flags;
5322
5323         sctx->send_filp = fget(arg->send_fd);
5324         if (!sctx->send_filp) {
5325                 ret = -EBADF;
5326                 goto out;
5327         }
5328
5329         sctx->send_root = send_root;
5330         sctx->clone_roots_cnt = arg->clone_sources_count;
5331
5332         sctx->send_max_size = BTRFS_SEND_BUF_SIZE;
5333         sctx->send_buf = vmalloc(sctx->send_max_size);
5334         if (!sctx->send_buf) {
5335                 ret = -ENOMEM;
5336                 goto out;
5337         }
5338
5339         sctx->read_buf = vmalloc(BTRFS_SEND_READ_SIZE);
5340         if (!sctx->read_buf) {
5341                 ret = -ENOMEM;
5342                 goto out;
5343         }
5344
5345         sctx->pending_dir_moves = RB_ROOT;
5346         sctx->waiting_dir_moves = RB_ROOT;
5347
5348         sctx->clone_roots = vzalloc(sizeof(struct clone_root) *
5349                         (arg->clone_sources_count + 1));
5350         if (!sctx->clone_roots) {
5351                 ret = -ENOMEM;
5352                 goto out;
5353         }
5354
5355         if (arg->clone_sources_count) {
5356                 clone_sources_tmp = vmalloc(arg->clone_sources_count *
5357                                 sizeof(*arg->clone_sources));
5358                 if (!clone_sources_tmp) {
5359                         ret = -ENOMEM;
5360                         goto out;
5361                 }
5362
5363                 ret = copy_from_user(clone_sources_tmp, arg->clone_sources,
5364                                 arg->clone_sources_count *
5365                                 sizeof(*arg->clone_sources));
5366                 if (ret) {
5367                         ret = -EFAULT;
5368                         goto out;
5369                 }
5370
5371                 for (i = 0; i < arg->clone_sources_count; i++) {
5372                         key.objectid = clone_sources_tmp[i];
5373                         key.type = BTRFS_ROOT_ITEM_KEY;
5374                         key.offset = (u64)-1;
5375
5376                         index = srcu_read_lock(&fs_info->subvol_srcu);
5377
5378                         clone_root = btrfs_read_fs_root_no_name(fs_info, &key);
5379                         if (IS_ERR(clone_root)) {
5380                                 srcu_read_unlock(&fs_info->subvol_srcu, index);
5381                                 ret = PTR_ERR(clone_root);
5382                                 goto out;
5383                         }
5384                         clone_sources_to_rollback = i + 1;
5385                         spin_lock(&clone_root->root_item_lock);
5386                         clone_root->send_in_progress++;
5387                         if (!btrfs_root_readonly(clone_root)) {
5388                                 spin_unlock(&clone_root->root_item_lock);
5389                                 srcu_read_unlock(&fs_info->subvol_srcu, index);
5390                                 ret = -EPERM;
5391                                 goto out;
5392                         }
5393                         spin_unlock(&clone_root->root_item_lock);
5394                         srcu_read_unlock(&fs_info->subvol_srcu, index);
5395
5396                         sctx->clone_roots[i].root = clone_root;
5397                 }
5398                 vfree(clone_sources_tmp);
5399                 clone_sources_tmp = NULL;
5400         }
5401
5402         if (arg->parent_root) {
5403                 key.objectid = arg->parent_root;
5404                 key.type = BTRFS_ROOT_ITEM_KEY;
5405                 key.offset = (u64)-1;
5406
5407                 index = srcu_read_lock(&fs_info->subvol_srcu);
5408
5409                 sctx->parent_root = btrfs_read_fs_root_no_name(fs_info, &key);
5410                 if (IS_ERR(sctx->parent_root)) {
5411                         srcu_read_unlock(&fs_info->subvol_srcu, index);
5412                         ret = PTR_ERR(sctx->parent_root);
5413                         goto out;
5414                 }
5415
5416                 spin_lock(&sctx->parent_root->root_item_lock);
5417                 sctx->parent_root->send_in_progress++;
5418                 if (!btrfs_root_readonly(sctx->parent_root)) {
5419                         spin_unlock(&sctx->parent_root->root_item_lock);
5420                         srcu_read_unlock(&fs_info->subvol_srcu, index);
5421                         ret = -EPERM;
5422                         goto out;
5423                 }
5424                 spin_unlock(&sctx->parent_root->root_item_lock);
5425
5426                 srcu_read_unlock(&fs_info->subvol_srcu, index);
5427         }
5428
5429         /*
5430          * Clones from send_root are allowed, but only if the clone source
5431          * is behind the current send position. This is checked while searching
5432          * for possible clone sources.
5433          */
5434         sctx->clone_roots[sctx->clone_roots_cnt++].root = sctx->send_root;
5435
5436         /* We do a bsearch later */
5437         sort(sctx->clone_roots, sctx->clone_roots_cnt,
5438                         sizeof(*sctx->clone_roots), __clone_root_cmp_sort,
5439                         NULL);
5440         sort_clone_roots = 1;
5441
5442         ret = send_subvol(sctx);
5443         if (ret < 0)
5444                 goto out;
5445
5446         if (!(sctx->flags & BTRFS_SEND_FLAG_OMIT_END_CMD)) {
5447                 ret = begin_cmd(sctx, BTRFS_SEND_C_END);
5448                 if (ret < 0)
5449                         goto out;
5450                 ret = send_cmd(sctx);
5451                 if (ret < 0)
5452                         goto out;
5453         }
5454
5455 out:
5456         WARN_ON(sctx && !ret && !RB_EMPTY_ROOT(&sctx->pending_dir_moves));
5457         while (sctx && !RB_EMPTY_ROOT(&sctx->pending_dir_moves)) {
5458                 struct rb_node *n;
5459                 struct pending_dir_move *pm;
5460
5461                 n = rb_first(&sctx->pending_dir_moves);
5462                 pm = rb_entry(n, struct pending_dir_move, node);
5463                 while (!list_empty(&pm->list)) {
5464                         struct pending_dir_move *pm2;
5465
5466                         pm2 = list_first_entry(&pm->list,
5467                                                struct pending_dir_move, list);
5468                         free_pending_move(sctx, pm2);
5469                 }
5470                 free_pending_move(sctx, pm);
5471         }
5472
5473         WARN_ON(sctx && !ret && !RB_EMPTY_ROOT(&sctx->waiting_dir_moves));
5474         while (sctx && !RB_EMPTY_ROOT(&sctx->waiting_dir_moves)) {
5475                 struct rb_node *n;
5476                 struct waiting_dir_move *dm;
5477
5478                 n = rb_first(&sctx->waiting_dir_moves);
5479                 dm = rb_entry(n, struct waiting_dir_move, node);
5480                 rb_erase(&dm->node, &sctx->waiting_dir_moves);
5481                 kfree(dm);
5482         }
5483
5484         if (sort_clone_roots) {
5485                 for (i = 0; i < sctx->clone_roots_cnt; i++)
5486                         btrfs_root_dec_send_in_progress(
5487                                         sctx->clone_roots[i].root);
5488         } else {
5489                 for (i = 0; sctx && i < clone_sources_to_rollback; i++)
5490                         btrfs_root_dec_send_in_progress(
5491                                         sctx->clone_roots[i].root);
5492
5493                 btrfs_root_dec_send_in_progress(send_root);
5494         }
5495         if (sctx && !IS_ERR_OR_NULL(sctx->parent_root))
5496                 btrfs_root_dec_send_in_progress(sctx->parent_root);
5497
5498         kfree(arg);
5499         vfree(clone_sources_tmp);
5500
5501         if (sctx) {
5502                 if (sctx->send_filp)
5503                         fput(sctx->send_filp);
5504
5505                 vfree(sctx->clone_roots);
5506                 vfree(sctx->send_buf);
5507                 vfree(sctx->read_buf);
5508
5509                 name_cache_free(sctx);
5510
5511                 kfree(sctx);
5512         }
5513
5514         return ret;
5515 }