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