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