~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/fs/btrfs/send.c

Version: ~ [ linux-5.19-rc3 ] ~ [ linux-5.18.5 ] ~ [ linux-5.17.15 ] ~ [ linux-5.16.20 ] ~ [ linux-5.15.48 ] ~ [ linux-5.14.21 ] ~ [ linux-5.13.19 ] ~ [ linux-5.12.19 ] ~ [ linux-5.11.22 ] ~ [ linux-5.10.123 ] ~ [ linux-5.9.16 ] ~ [ linux-5.8.18 ] ~ [ linux-5.7.19 ] ~ [ linux-5.6.19 ] ~ [ linux-5.5.19 ] ~ [ linux-5.4.199 ] ~ [ linux-5.3.18 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.248 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.284 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.319 ] ~ [ linux-4.8.17 ] ~ [ linux-4.7.10 ] ~ [ linux-4.6.7 ] ~ [ linux-4.5.7 ] ~ [ linux-4.4.302 ] ~ [ linux-4.3.6 ] ~ [ linux-4.2.8 ] ~ [ linux-4.1.52 ] ~ [ linux-4.0.9 ] ~ [ linux-3.10.108 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.9 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

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