d2a4ee9125df84afc685fc49d81d53e481c75439
[firefly-linux-kernel-4.4.55.git] / fs / btrfs / send.c
1 /*
2  * Copyright (C) 2012 Alexander Block.  All rights reserved.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public
6  * License v2 as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public
14  * License along with this program; if not, write to the
15  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16  * Boston, MA 021110-1307, USA.
17  */
18
19 #include <linux/bsearch.h>
20 #include <linux/fs.h>
21 #include <linux/file.h>
22 #include <linux/sort.h>
23 #include <linux/mount.h>
24 #include <linux/xattr.h>
25 #include <linux/posix_acl_xattr.h>
26 #include <linux/radix-tree.h>
27 #include <linux/crc32c.h>
28 #include <linux/vmalloc.h>
29
30 #include "send.h"
31 #include "backref.h"
32 #include "locking.h"
33 #include "disk-io.h"
34 #include "btrfs_inode.h"
35 #include "transaction.h"
36
37 static int g_verbose = 0;
38
39 #define verbose_printk(...) if (g_verbose) printk(__VA_ARGS__)
40
41 /*
42  * A fs_path is a helper to dynamically build path names with unknown size.
43  * It reallocates the internal buffer on demand.
44  * It allows fast adding of path elements on the right side (normal path) and
45  * fast adding to the left side (reversed path). A reversed path can also be
46  * unreversed if needed.
47  */
48 struct fs_path {
49         union {
50                 struct {
51                         char *start;
52                         char *end;
53                         char *prepared;
54
55                         char *buf;
56                         int buf_len;
57                         int reversed:1;
58                         int virtual_mem:1;
59                         char inline_buf[];
60                 };
61                 char pad[PAGE_SIZE];
62         };
63 };
64 #define FS_PATH_INLINE_SIZE \
65         (sizeof(struct fs_path) - offsetof(struct fs_path, inline_buf))
66
67
68 /* reused for each extent */
69 struct clone_root {
70         struct btrfs_root *root;
71         u64 ino;
72         u64 offset;
73
74         u64 found_refs;
75 };
76
77 #define SEND_CTX_MAX_NAME_CACHE_SIZE 128
78 #define SEND_CTX_NAME_CACHE_CLEAN_SIZE (SEND_CTX_MAX_NAME_CACHE_SIZE * 2)
79
80 struct send_ctx {
81         struct file *send_filp;
82         loff_t send_off;
83         char *send_buf;
84         u32 send_size;
85         u32 send_max_size;
86         u64 total_send_size;
87         u64 cmd_send_size[BTRFS_SEND_C_MAX + 1];
88
89         struct vfsmount *mnt;
90
91         struct btrfs_root *send_root;
92         struct btrfs_root *parent_root;
93         struct clone_root *clone_roots;
94         int clone_roots_cnt;
95
96         /* current state of the compare_tree call */
97         struct btrfs_path *left_path;
98         struct btrfs_path *right_path;
99         struct btrfs_key *cmp_key;
100
101         /*
102          * infos of the currently processed inode. In case of deleted inodes,
103          * these are the values from the deleted inode.
104          */
105         u64 cur_ino;
106         u64 cur_inode_gen;
107         int cur_inode_new;
108         int cur_inode_new_gen;
109         int cur_inode_deleted;
110         u64 cur_inode_size;
111         u64 cur_inode_mode;
112
113         u64 send_progress;
114
115         struct list_head new_refs;
116         struct list_head deleted_refs;
117
118         struct radix_tree_root name_cache;
119         struct list_head name_cache_list;
120         int name_cache_size;
121
122         struct file *cur_inode_filp;
123         char *read_buf;
124 };
125
126 struct name_cache_entry {
127         struct list_head list;
128         u64 ino;
129         u64 gen;
130         u64 parent_ino;
131         u64 parent_gen;
132         int ret;
133         int need_later_update;
134         int name_len;
135         char name[];
136 };
137
138 static void fs_path_reset(struct fs_path *p)
139 {
140         if (p->reversed) {
141                 p->start = p->buf + p->buf_len - 1;
142                 p->end = p->start;
143                 *p->start = 0;
144         } else {
145                 p->start = p->buf;
146                 p->end = p->start;
147                 *p->start = 0;
148         }
149 }
150
151 static struct fs_path *fs_path_alloc(struct send_ctx *sctx)
152 {
153         struct fs_path *p;
154
155         p = kmalloc(sizeof(*p), GFP_NOFS);
156         if (!p)
157                 return NULL;
158         p->reversed = 0;
159         p->virtual_mem = 0;
160         p->buf = p->inline_buf;
161         p->buf_len = FS_PATH_INLINE_SIZE;
162         fs_path_reset(p);
163         return p;
164 }
165
166 static struct fs_path *fs_path_alloc_reversed(struct send_ctx *sctx)
167 {
168         struct fs_path *p;
169
170         p = fs_path_alloc(sctx);
171         if (!p)
172                 return NULL;
173         p->reversed = 1;
174         fs_path_reset(p);
175         return p;
176 }
177
178 static void fs_path_free(struct send_ctx *sctx, struct fs_path *p)
179 {
180         if (!p)
181                 return;
182         if (p->buf != p->inline_buf) {
183                 if (p->virtual_mem)
184                         vfree(p->buf);
185                 else
186                         kfree(p->buf);
187         }
188         kfree(p);
189 }
190
191 static int fs_path_len(struct fs_path *p)
192 {
193         return p->end - p->start;
194 }
195
196 static int fs_path_ensure_buf(struct fs_path *p, int len)
197 {
198         char *tmp_buf;
199         int path_len;
200         int old_buf_len;
201
202         len++;
203
204         if (p->buf_len >= len)
205                 return 0;
206
207         path_len = p->end - p->start;
208         old_buf_len = p->buf_len;
209         len = PAGE_ALIGN(len);
210
211         if (p->buf == p->inline_buf) {
212                 tmp_buf = kmalloc(len, GFP_NOFS);
213                 if (!tmp_buf) {
214                         tmp_buf = vmalloc(len);
215                         if (!tmp_buf)
216                                 return -ENOMEM;
217                         p->virtual_mem = 1;
218                 }
219                 memcpy(tmp_buf, p->buf, p->buf_len);
220                 p->buf = tmp_buf;
221                 p->buf_len = len;
222         } else {
223                 if (p->virtual_mem) {
224                         tmp_buf = vmalloc(len);
225                         if (!tmp_buf)
226                                 return -ENOMEM;
227                         memcpy(tmp_buf, p->buf, p->buf_len);
228                         vfree(p->buf);
229                 } else {
230                         tmp_buf = krealloc(p->buf, len, GFP_NOFS);
231                         if (!tmp_buf) {
232                                 tmp_buf = vmalloc(len);
233                                 if (!tmp_buf)
234                                         return -ENOMEM;
235                                 memcpy(tmp_buf, p->buf, p->buf_len);
236                                 kfree(p->buf);
237                                 p->virtual_mem = 1;
238                         }
239                 }
240                 p->buf = tmp_buf;
241                 p->buf_len = len;
242         }
243         if (p->reversed) {
244                 tmp_buf = p->buf + old_buf_len - path_len - 1;
245                 p->end = p->buf + p->buf_len - 1;
246                 p->start = p->end - path_len;
247                 memmove(p->start, tmp_buf, path_len + 1);
248         } else {
249                 p->start = p->buf;
250                 p->end = p->start + path_len;
251         }
252         return 0;
253 }
254
255 static int fs_path_prepare_for_add(struct fs_path *p, int name_len)
256 {
257         int ret;
258         int new_len;
259
260         new_len = p->end - p->start + name_len;
261         if (p->start != p->end)
262                 new_len++;
263         ret = fs_path_ensure_buf(p, new_len);
264         if (ret < 0)
265                 goto out;
266
267         if (p->reversed) {
268                 if (p->start != p->end)
269                         *--p->start = '/';
270                 p->start -= name_len;
271                 p->prepared = p->start;
272         } else {
273                 if (p->start != p->end)
274                         *p->end++ = '/';
275                 p->prepared = p->end;
276                 p->end += name_len;
277                 *p->end = 0;
278         }
279
280 out:
281         return ret;
282 }
283
284 static int fs_path_add(struct fs_path *p, const char *name, int name_len)
285 {
286         int ret;
287
288         ret = fs_path_prepare_for_add(p, name_len);
289         if (ret < 0)
290                 goto out;
291         memcpy(p->prepared, name, name_len);
292         p->prepared = NULL;
293
294 out:
295         return ret;
296 }
297
298 static int fs_path_add_path(struct fs_path *p, struct fs_path *p2)
299 {
300         int ret;
301
302         ret = fs_path_prepare_for_add(p, p2->end - p2->start);
303         if (ret < 0)
304                 goto out;
305         memcpy(p->prepared, p2->start, p2->end - p2->start);
306         p->prepared = NULL;
307
308 out:
309         return ret;
310 }
311
312 static int fs_path_add_from_extent_buffer(struct fs_path *p,
313                                           struct extent_buffer *eb,
314                                           unsigned long off, int len)
315 {
316         int ret;
317
318         ret = fs_path_prepare_for_add(p, len);
319         if (ret < 0)
320                 goto out;
321
322         read_extent_buffer(eb, p->prepared, off, len);
323         p->prepared = NULL;
324
325 out:
326         return ret;
327 }
328
329 #if 0
330 static void fs_path_remove(struct fs_path *p)
331 {
332         BUG_ON(p->reversed);
333         while (p->start != p->end && *p->end != '/')
334                 p->end--;
335         *p->end = 0;
336 }
337 #endif
338
339 static int fs_path_copy(struct fs_path *p, struct fs_path *from)
340 {
341         int ret;
342
343         p->reversed = from->reversed;
344         fs_path_reset(p);
345
346         ret = fs_path_add_path(p, from);
347
348         return ret;
349 }
350
351
352 static void fs_path_unreverse(struct fs_path *p)
353 {
354         char *tmp;
355         int len;
356
357         if (!p->reversed)
358                 return;
359
360         tmp = p->start;
361         len = p->end - p->start;
362         p->start = p->buf;
363         p->end = p->start + len;
364         memmove(p->start, tmp, len + 1);
365         p->reversed = 0;
366 }
367
368 static struct btrfs_path *alloc_path_for_send(void)
369 {
370         struct btrfs_path *path;
371
372         path = btrfs_alloc_path();
373         if (!path)
374                 return NULL;
375         path->search_commit_root = 1;
376         path->skip_locking = 1;
377         return path;
378 }
379
380 static int write_buf(struct send_ctx *sctx, const void *buf, u32 len)
381 {
382         int ret;
383         mm_segment_t old_fs;
384         u32 pos = 0;
385
386         old_fs = get_fs();
387         set_fs(KERNEL_DS);
388
389         while (pos < len) {
390                 ret = vfs_write(sctx->send_filp, (char *)buf + pos, len - pos,
391                                 &sctx->send_off);
392                 /* TODO handle that correctly */
393                 /*if (ret == -ERESTARTSYS) {
394                         continue;
395                 }*/
396                 if (ret < 0)
397                         goto out;
398                 if (ret == 0) {
399                         ret = -EIO;
400                         goto out;
401                 }
402                 pos += ret;
403         }
404
405         ret = 0;
406
407 out:
408         set_fs(old_fs);
409         return ret;
410 }
411
412 static int tlv_put(struct send_ctx *sctx, u16 attr, const void *data, int len)
413 {
414         struct btrfs_tlv_header *hdr;
415         int total_len = sizeof(*hdr) + len;
416         int left = sctx->send_max_size - sctx->send_size;
417
418         if (unlikely(left < total_len))
419                 return -EOVERFLOW;
420
421         hdr = (struct btrfs_tlv_header *) (sctx->send_buf + sctx->send_size);
422         hdr->tlv_type = cpu_to_le16(attr);
423         hdr->tlv_len = cpu_to_le16(len);
424         memcpy(hdr + 1, data, len);
425         sctx->send_size += total_len;
426
427         return 0;
428 }
429
430 #if 0
431 static int tlv_put_u8(struct send_ctx *sctx, u16 attr, u8 value)
432 {
433         return tlv_put(sctx, attr, &value, sizeof(value));
434 }
435
436 static int tlv_put_u16(struct send_ctx *sctx, u16 attr, u16 value)
437 {
438         __le16 tmp = cpu_to_le16(value);
439         return tlv_put(sctx, attr, &tmp, sizeof(tmp));
440 }
441
442 static int tlv_put_u32(struct send_ctx *sctx, u16 attr, u32 value)
443 {
444         __le32 tmp = cpu_to_le32(value);
445         return tlv_put(sctx, attr, &tmp, sizeof(tmp));
446 }
447 #endif
448
449 static int tlv_put_u64(struct send_ctx *sctx, u16 attr, u64 value)
450 {
451         __le64 tmp = cpu_to_le64(value);
452         return tlv_put(sctx, attr, &tmp, sizeof(tmp));
453 }
454
455 static int tlv_put_string(struct send_ctx *sctx, u16 attr,
456                           const char *str, int len)
457 {
458         if (len == -1)
459                 len = strlen(str);
460         return tlv_put(sctx, attr, str, len);
461 }
462
463 static int tlv_put_uuid(struct send_ctx *sctx, u16 attr,
464                         const u8 *uuid)
465 {
466         return tlv_put(sctx, attr, uuid, BTRFS_UUID_SIZE);
467 }
468
469 #if 0
470 static int tlv_put_timespec(struct send_ctx *sctx, u16 attr,
471                             struct timespec *ts)
472 {
473         struct btrfs_timespec bts;
474         bts.sec = cpu_to_le64(ts->tv_sec);
475         bts.nsec = cpu_to_le32(ts->tv_nsec);
476         return tlv_put(sctx, attr, &bts, sizeof(bts));
477 }
478 #endif
479
480 static int tlv_put_btrfs_timespec(struct send_ctx *sctx, u16 attr,
481                                   struct extent_buffer *eb,
482                                   struct btrfs_timespec *ts)
483 {
484         struct btrfs_timespec bts;
485         read_extent_buffer(eb, &bts, (unsigned long)ts, sizeof(bts));
486         return tlv_put(sctx, attr, &bts, sizeof(bts));
487 }
488
489
490 #define TLV_PUT(sctx, attrtype, attrlen, data) \
491         do { \
492                 ret = tlv_put(sctx, attrtype, attrlen, data); \
493                 if (ret < 0) \
494                         goto tlv_put_failure; \
495         } while (0)
496
497 #define TLV_PUT_INT(sctx, attrtype, bits, value) \
498         do { \
499                 ret = tlv_put_u##bits(sctx, attrtype, value); \
500                 if (ret < 0) \
501                         goto tlv_put_failure; \
502         } while (0)
503
504 #define TLV_PUT_U8(sctx, attrtype, data) TLV_PUT_INT(sctx, attrtype, 8, data)
505 #define TLV_PUT_U16(sctx, attrtype, data) TLV_PUT_INT(sctx, attrtype, 16, data)
506 #define TLV_PUT_U32(sctx, attrtype, data) TLV_PUT_INT(sctx, attrtype, 32, data)
507 #define TLV_PUT_U64(sctx, attrtype, data) TLV_PUT_INT(sctx, attrtype, 64, data)
508 #define TLV_PUT_STRING(sctx, attrtype, str, len) \
509         do { \
510                 ret = tlv_put_string(sctx, attrtype, str, len); \
511                 if (ret < 0) \
512                         goto tlv_put_failure; \
513         } while (0)
514 #define TLV_PUT_PATH(sctx, attrtype, p) \
515         do { \
516                 ret = tlv_put_string(sctx, attrtype, p->start, \
517                         p->end - p->start); \
518                 if (ret < 0) \
519                         goto tlv_put_failure; \
520         } while(0)
521 #define TLV_PUT_UUID(sctx, attrtype, uuid) \
522         do { \
523                 ret = tlv_put_uuid(sctx, attrtype, uuid); \
524                 if (ret < 0) \
525                         goto tlv_put_failure; \
526         } while (0)
527 #define TLV_PUT_TIMESPEC(sctx, attrtype, ts) \
528         do { \
529                 ret = tlv_put_timespec(sctx, attrtype, ts); \
530                 if (ret < 0) \
531                         goto tlv_put_failure; \
532         } while (0)
533 #define TLV_PUT_BTRFS_TIMESPEC(sctx, attrtype, eb, ts) \
534         do { \
535                 ret = tlv_put_btrfs_timespec(sctx, attrtype, eb, ts); \
536                 if (ret < 0) \
537                         goto tlv_put_failure; \
538         } while (0)
539
540 static int send_header(struct send_ctx *sctx)
541 {
542         struct btrfs_stream_header hdr;
543
544         strcpy(hdr.magic, BTRFS_SEND_STREAM_MAGIC);
545         hdr.version = cpu_to_le32(BTRFS_SEND_STREAM_VERSION);
546
547         return write_buf(sctx, &hdr, sizeof(hdr));
548 }
549
550 /*
551  * For each command/item we want to send to userspace, we call this function.
552  */
553 static int begin_cmd(struct send_ctx *sctx, int cmd)
554 {
555         struct btrfs_cmd_header *hdr;
556
557         if (!sctx->send_buf) {
558                 WARN_ON(1);
559                 return -EINVAL;
560         }
561
562         BUG_ON(sctx->send_size);
563
564         sctx->send_size += sizeof(*hdr);
565         hdr = (struct btrfs_cmd_header *)sctx->send_buf;
566         hdr->cmd = cpu_to_le16(cmd);
567
568         return 0;
569 }
570
571 static int send_cmd(struct send_ctx *sctx)
572 {
573         int ret;
574         struct btrfs_cmd_header *hdr;
575         u32 crc;
576
577         hdr = (struct btrfs_cmd_header *)sctx->send_buf;
578         hdr->len = cpu_to_le32(sctx->send_size - sizeof(*hdr));
579         hdr->crc = 0;
580
581         crc = crc32c(0, (unsigned char *)sctx->send_buf, sctx->send_size);
582         hdr->crc = cpu_to_le32(crc);
583
584         ret = write_buf(sctx, sctx->send_buf, sctx->send_size);
585
586         sctx->total_send_size += sctx->send_size;
587         sctx->cmd_send_size[le16_to_cpu(hdr->cmd)] += sctx->send_size;
588         sctx->send_size = 0;
589
590         return ret;
591 }
592
593 /*
594  * Sends a move instruction to user space
595  */
596 static int send_rename(struct send_ctx *sctx,
597                      struct fs_path *from, struct fs_path *to)
598 {
599         int ret;
600
601 verbose_printk("btrfs: send_rename %s -> %s\n", from->start, to->start);
602
603         ret = begin_cmd(sctx, BTRFS_SEND_C_RENAME);
604         if (ret < 0)
605                 goto out;
606
607         TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, from);
608         TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH_TO, to);
609
610         ret = send_cmd(sctx);
611
612 tlv_put_failure:
613 out:
614         return ret;
615 }
616
617 /*
618  * Sends a link instruction to user space
619  */
620 static int send_link(struct send_ctx *sctx,
621                      struct fs_path *path, struct fs_path *lnk)
622 {
623         int ret;
624
625 verbose_printk("btrfs: send_link %s -> %s\n", path->start, lnk->start);
626
627         ret = begin_cmd(sctx, BTRFS_SEND_C_LINK);
628         if (ret < 0)
629                 goto out;
630
631         TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, path);
632         TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH_LINK, lnk);
633
634         ret = send_cmd(sctx);
635
636 tlv_put_failure:
637 out:
638         return ret;
639 }
640
641 /*
642  * Sends an unlink instruction to user space
643  */
644 static int send_unlink(struct send_ctx *sctx, struct fs_path *path)
645 {
646         int ret;
647
648 verbose_printk("btrfs: send_unlink %s\n", path->start);
649
650         ret = begin_cmd(sctx, BTRFS_SEND_C_UNLINK);
651         if (ret < 0)
652                 goto out;
653
654         TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, path);
655
656         ret = send_cmd(sctx);
657
658 tlv_put_failure:
659 out:
660         return ret;
661 }
662
663 /*
664  * Sends a rmdir instruction to user space
665  */
666 static int send_rmdir(struct send_ctx *sctx, struct fs_path *path)
667 {
668         int ret;
669
670 verbose_printk("btrfs: send_rmdir %s\n", path->start);
671
672         ret = begin_cmd(sctx, BTRFS_SEND_C_RMDIR);
673         if (ret < 0)
674                 goto out;
675
676         TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, path);
677
678         ret = send_cmd(sctx);
679
680 tlv_put_failure:
681 out:
682         return ret;
683 }
684
685 /*
686  * Helper function to retrieve some fields from an inode item.
687  */
688 static int get_inode_info(struct btrfs_root *root,
689                           u64 ino, u64 *size, u64 *gen,
690                           u64 *mode, u64 *uid, u64 *gid,
691                           u64 *rdev)
692 {
693         int ret;
694         struct btrfs_inode_item *ii;
695         struct btrfs_key key;
696         struct btrfs_path *path;
697
698         path = alloc_path_for_send();
699         if (!path)
700                 return -ENOMEM;
701
702         key.objectid = ino;
703         key.type = BTRFS_INODE_ITEM_KEY;
704         key.offset = 0;
705         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
706         if (ret < 0)
707                 goto out;
708         if (ret) {
709                 ret = -ENOENT;
710                 goto out;
711         }
712
713         ii = btrfs_item_ptr(path->nodes[0], path->slots[0],
714                         struct btrfs_inode_item);
715         if (size)
716                 *size = btrfs_inode_size(path->nodes[0], ii);
717         if (gen)
718                 *gen = btrfs_inode_generation(path->nodes[0], ii);
719         if (mode)
720                 *mode = btrfs_inode_mode(path->nodes[0], ii);
721         if (uid)
722                 *uid = btrfs_inode_uid(path->nodes[0], ii);
723         if (gid)
724                 *gid = btrfs_inode_gid(path->nodes[0], ii);
725         if (rdev)
726                 *rdev = btrfs_inode_rdev(path->nodes[0], ii);
727
728 out:
729         btrfs_free_path(path);
730         return ret;
731 }
732
733 typedef int (*iterate_inode_ref_t)(int num, u64 dir, int index,
734                                    struct fs_path *p,
735                                    void *ctx);
736
737 /*
738  * Helper function to iterate the entries in ONE btrfs_inode_ref.
739  * The iterate callback may return a non zero value to stop iteration. This can
740  * be a negative value for error codes or 1 to simply stop it.
741  *
742  * path must point to the INODE_REF when called.
743  */
744 static int iterate_inode_ref(struct send_ctx *sctx,
745                              struct btrfs_root *root, struct btrfs_path *path,
746                              struct btrfs_key *found_key, int resolve,
747                              iterate_inode_ref_t iterate, void *ctx)
748 {
749         struct extent_buffer *eb;
750         struct btrfs_item *item;
751         struct btrfs_inode_ref *iref;
752         struct btrfs_path *tmp_path;
753         struct fs_path *p;
754         u32 cur;
755         u32 len;
756         u32 total;
757         int slot;
758         u32 name_len;
759         char *start;
760         int ret = 0;
761         int num;
762         int index;
763
764         p = fs_path_alloc_reversed(sctx);
765         if (!p)
766                 return -ENOMEM;
767
768         tmp_path = alloc_path_for_send();
769         if (!tmp_path) {
770                 fs_path_free(sctx, p);
771                 return -ENOMEM;
772         }
773
774         eb = path->nodes[0];
775         slot = path->slots[0];
776         item = btrfs_item_nr(eb, slot);
777         iref = btrfs_item_ptr(eb, slot, struct btrfs_inode_ref);
778         cur = 0;
779         len = 0;
780         total = btrfs_item_size(eb, item);
781
782         num = 0;
783         while (cur < total) {
784                 fs_path_reset(p);
785
786                 name_len = btrfs_inode_ref_name_len(eb, iref);
787                 index = btrfs_inode_ref_index(eb, iref);
788                 if (resolve) {
789                         start = btrfs_iref_to_path(root, tmp_path, iref, eb,
790                                                 found_key->offset, p->buf,
791                                                 p->buf_len);
792                         if (IS_ERR(start)) {
793                                 ret = PTR_ERR(start);
794                                 goto out;
795                         }
796                         if (start < p->buf) {
797                                 /* overflow , try again with larger buffer */
798                                 ret = fs_path_ensure_buf(p,
799                                                 p->buf_len + p->buf - start);
800                                 if (ret < 0)
801                                         goto out;
802                                 start = btrfs_iref_to_path(root, tmp_path, iref,
803                                                 eb, found_key->offset, p->buf,
804                                                 p->buf_len);
805                                 if (IS_ERR(start)) {
806                                         ret = PTR_ERR(start);
807                                         goto out;
808                                 }
809                                 BUG_ON(start < p->buf);
810                         }
811                         p->start = start;
812                 } else {
813                         ret = fs_path_add_from_extent_buffer(p, eb,
814                                         (unsigned long)(iref + 1), name_len);
815                         if (ret < 0)
816                                 goto out;
817                 }
818
819
820                 len = sizeof(*iref) + name_len;
821                 iref = (struct btrfs_inode_ref *)((char *)iref + len);
822                 cur += len;
823
824                 ret = iterate(num, found_key->offset, index, p, ctx);
825                 if (ret)
826                         goto out;
827
828                 num++;
829         }
830
831 out:
832         btrfs_free_path(tmp_path);
833         fs_path_free(sctx, p);
834         return ret;
835 }
836
837 typedef int (*iterate_dir_item_t)(int num, struct btrfs_key *di_key,
838                                   const char *name, int name_len,
839                                   const char *data, int data_len,
840                                   u8 type, void *ctx);
841
842 /*
843  * Helper function to iterate the entries in ONE btrfs_dir_item.
844  * The iterate callback may return a non zero value to stop iteration. This can
845  * be a negative value for error codes or 1 to simply stop it.
846  *
847  * path must point to the dir item when called.
848  */
849 static int iterate_dir_item(struct send_ctx *sctx,
850                             struct btrfs_root *root, struct btrfs_path *path,
851                             struct btrfs_key *found_key,
852                             iterate_dir_item_t iterate, void *ctx)
853 {
854         int ret = 0;
855         struct extent_buffer *eb;
856         struct btrfs_item *item;
857         struct btrfs_dir_item *di;
858         struct btrfs_path *tmp_path = NULL;
859         struct btrfs_key di_key;
860         char *buf = NULL;
861         char *buf2 = NULL;
862         int buf_len;
863         int buf_virtual = 0;
864         u32 name_len;
865         u32 data_len;
866         u32 cur;
867         u32 len;
868         u32 total;
869         int slot;
870         int num;
871         u8 type;
872
873         buf_len = PAGE_SIZE;
874         buf = kmalloc(buf_len, GFP_NOFS);
875         if (!buf) {
876                 ret = -ENOMEM;
877                 goto out;
878         }
879
880         tmp_path = alloc_path_for_send();
881         if (!tmp_path) {
882                 ret = -ENOMEM;
883                 goto out;
884         }
885
886         eb = path->nodes[0];
887         slot = path->slots[0];
888         item = btrfs_item_nr(eb, slot);
889         di = btrfs_item_ptr(eb, slot, struct btrfs_dir_item);
890         cur = 0;
891         len = 0;
892         total = btrfs_item_size(eb, item);
893
894         num = 0;
895         while (cur < total) {
896                 name_len = btrfs_dir_name_len(eb, di);
897                 data_len = btrfs_dir_data_len(eb, di);
898                 type = btrfs_dir_type(eb, di);
899                 btrfs_dir_item_key_to_cpu(eb, di, &di_key);
900
901                 if (name_len + data_len > buf_len) {
902                         buf_len = PAGE_ALIGN(name_len + data_len);
903                         if (buf_virtual) {
904                                 buf2 = vmalloc(buf_len);
905                                 if (!buf2) {
906                                         ret = -ENOMEM;
907                                         goto out;
908                                 }
909                                 vfree(buf);
910                         } else {
911                                 buf2 = krealloc(buf, buf_len, GFP_NOFS);
912                                 if (!buf2) {
913                                         buf2 = vmalloc(buf_len);
914                                         if (!buf2) {
915                                                 ret = -ENOMEM;
916                                                 goto out;
917                                         }
918                                         kfree(buf);
919                                         buf_virtual = 1;
920                                 }
921                         }
922
923                         buf = buf2;
924                         buf2 = NULL;
925                 }
926
927                 read_extent_buffer(eb, buf, (unsigned long)(di + 1),
928                                 name_len + data_len);
929
930                 len = sizeof(*di) + name_len + data_len;
931                 di = (struct btrfs_dir_item *)((char *)di + len);
932                 cur += len;
933
934                 ret = iterate(num, &di_key, buf, name_len, buf + name_len,
935                                 data_len, type, ctx);
936                 if (ret < 0)
937                         goto out;
938                 if (ret) {
939                         ret = 0;
940                         goto out;
941                 }
942
943                 num++;
944         }
945
946 out:
947         btrfs_free_path(tmp_path);
948         if (buf_virtual)
949                 vfree(buf);
950         else
951                 kfree(buf);
952         return ret;
953 }
954
955 static int __copy_first_ref(int num, u64 dir, int index,
956                             struct fs_path *p, void *ctx)
957 {
958         int ret;
959         struct fs_path *pt = ctx;
960
961         ret = fs_path_copy(pt, p);
962         if (ret < 0)
963                 return ret;
964
965         /* we want the first only */
966         return 1;
967 }
968
969 /*
970  * Retrieve the first path of an inode. If an inode has more then one
971  * ref/hardlink, this is ignored.
972  */
973 static int get_inode_path(struct send_ctx *sctx, struct btrfs_root *root,
974                           u64 ino, struct fs_path *path)
975 {
976         int ret;
977         struct btrfs_key key, found_key;
978         struct btrfs_path *p;
979
980         p = alloc_path_for_send();
981         if (!p)
982                 return -ENOMEM;
983
984         fs_path_reset(path);
985
986         key.objectid = ino;
987         key.type = BTRFS_INODE_REF_KEY;
988         key.offset = 0;
989
990         ret = btrfs_search_slot_for_read(root, &key, p, 1, 0);
991         if (ret < 0)
992                 goto out;
993         if (ret) {
994                 ret = 1;
995                 goto out;
996         }
997         btrfs_item_key_to_cpu(p->nodes[0], &found_key, p->slots[0]);
998         if (found_key.objectid != ino ||
999                 found_key.type != BTRFS_INODE_REF_KEY) {
1000                 ret = -ENOENT;
1001                 goto out;
1002         }
1003
1004         ret = iterate_inode_ref(sctx, root, p, &found_key, 1,
1005                         __copy_first_ref, path);
1006         if (ret < 0)
1007                 goto out;
1008         ret = 0;
1009
1010 out:
1011         btrfs_free_path(p);
1012         return ret;
1013 }
1014
1015 struct backref_ctx {
1016         struct send_ctx *sctx;
1017
1018         /* number of total found references */
1019         u64 found;
1020
1021         /*
1022          * used for clones found in send_root. clones found behind cur_objectid
1023          * and cur_offset are not considered as allowed clones.
1024          */
1025         u64 cur_objectid;
1026         u64 cur_offset;
1027
1028         /* may be truncated in case it's the last extent in a file */
1029         u64 extent_len;
1030
1031         /* Just to check for bugs in backref resolving */
1032         int found_itself;
1033 };
1034
1035 static int __clone_root_cmp_bsearch(const void *key, const void *elt)
1036 {
1037         u64 root = (u64)key;
1038         struct clone_root *cr = (struct clone_root *)elt;
1039
1040         if (root < cr->root->objectid)
1041                 return -1;
1042         if (root > cr->root->objectid)
1043                 return 1;
1044         return 0;
1045 }
1046
1047 static int __clone_root_cmp_sort(const void *e1, const void *e2)
1048 {
1049         struct clone_root *cr1 = (struct clone_root *)e1;
1050         struct clone_root *cr2 = (struct clone_root *)e2;
1051
1052         if (cr1->root->objectid < cr2->root->objectid)
1053                 return -1;
1054         if (cr1->root->objectid > cr2->root->objectid)
1055                 return 1;
1056         return 0;
1057 }
1058
1059 /*
1060  * Called for every backref that is found for the current extent.
1061  */
1062 static int __iterate_backrefs(u64 ino, u64 offset, u64 root, void *ctx_)
1063 {
1064         struct backref_ctx *bctx = ctx_;
1065         struct clone_root *found;
1066         int ret;
1067         u64 i_size;
1068
1069         /* First check if the root is in the list of accepted clone sources */
1070         found = bsearch((void *)root, bctx->sctx->clone_roots,
1071                         bctx->sctx->clone_roots_cnt,
1072                         sizeof(struct clone_root),
1073                         __clone_root_cmp_bsearch);
1074         if (!found)
1075                 return 0;
1076
1077         if (found->root == bctx->sctx->send_root &&
1078             ino == bctx->cur_objectid &&
1079             offset == bctx->cur_offset) {
1080                 bctx->found_itself = 1;
1081         }
1082
1083         /*
1084          * There are inodes that have extents that lie behind it's i_size. Don't
1085          * accept clones from these extents.
1086          */
1087         ret = get_inode_info(found->root, ino, &i_size, NULL, NULL, NULL, NULL,
1088                         NULL);
1089         if (ret < 0)
1090                 return ret;
1091
1092         if (offset + bctx->extent_len > i_size)
1093                 return 0;
1094
1095         /*
1096          * Make sure we don't consider clones from send_root that are
1097          * behind the current inode/offset.
1098          */
1099         if (found->root == bctx->sctx->send_root) {
1100                 /*
1101                  * TODO for the moment we don't accept clones from the inode
1102                  * that is currently send. We may change this when
1103                  * BTRFS_IOC_CLONE_RANGE supports cloning from and to the same
1104                  * file.
1105                  */
1106                 if (ino >= bctx->cur_objectid)
1107                         return 0;
1108                 /*if (ino > ctx->cur_objectid)
1109                         return 0;
1110                 if (offset + ctx->extent_len > ctx->cur_offset)
1111                         return 0;*/
1112         }
1113
1114         bctx->found++;
1115         found->found_refs++;
1116         if (ino < found->ino) {
1117                 found->ino = ino;
1118                 found->offset = offset;
1119         } else if (found->ino == ino) {
1120                 /*
1121                  * same extent found more then once in the same file.
1122                  */
1123                 if (found->offset > offset + bctx->extent_len)
1124                         found->offset = offset;
1125         }
1126
1127         return 0;
1128 }
1129
1130 /*
1131  * path must point to the extent item when called.
1132  */
1133 static int find_extent_clone(struct send_ctx *sctx,
1134                              struct btrfs_path *path,
1135                              u64 ino, u64 data_offset,
1136                              u64 ino_size,
1137                              struct clone_root **found)
1138 {
1139         int ret;
1140         int extent_type;
1141         u64 logical;
1142         u64 num_bytes;
1143         u64 extent_item_pos;
1144         struct btrfs_file_extent_item *fi;
1145         struct extent_buffer *eb = path->nodes[0];
1146         struct backref_ctx *backref_ctx = NULL;
1147         struct clone_root *cur_clone_root;
1148         struct btrfs_key found_key;
1149         struct btrfs_path *tmp_path;
1150         u32 i;
1151
1152         tmp_path = alloc_path_for_send();
1153         if (!tmp_path)
1154                 return -ENOMEM;
1155
1156         backref_ctx = kmalloc(sizeof(*backref_ctx), GFP_NOFS);
1157         if (!backref_ctx) {
1158                 ret = -ENOMEM;
1159                 goto out;
1160         }
1161
1162         if (data_offset >= ino_size) {
1163                 /*
1164                  * There may be extents that lie behind the file's size.
1165                  * I at least had this in combination with snapshotting while
1166                  * writing large files.
1167                  */
1168                 ret = 0;
1169                 goto out;
1170         }
1171
1172         fi = btrfs_item_ptr(eb, path->slots[0],
1173                         struct btrfs_file_extent_item);
1174         extent_type = btrfs_file_extent_type(eb, fi);
1175         if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1176                 ret = -ENOENT;
1177                 goto out;
1178         }
1179
1180         num_bytes = btrfs_file_extent_num_bytes(eb, fi);
1181         logical = btrfs_file_extent_disk_bytenr(eb, fi);
1182         if (logical == 0) {
1183                 ret = -ENOENT;
1184                 goto out;
1185         }
1186         logical += btrfs_file_extent_offset(eb, fi);
1187
1188         ret = extent_from_logical(sctx->send_root->fs_info,
1189                         logical, tmp_path, &found_key);
1190         btrfs_release_path(tmp_path);
1191
1192         if (ret < 0)
1193                 goto out;
1194         if (ret & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
1195                 ret = -EIO;
1196                 goto out;
1197         }
1198
1199         /*
1200          * Setup the clone roots.
1201          */
1202         for (i = 0; i < sctx->clone_roots_cnt; i++) {
1203                 cur_clone_root = sctx->clone_roots + i;
1204                 cur_clone_root->ino = (u64)-1;
1205                 cur_clone_root->offset = 0;
1206                 cur_clone_root->found_refs = 0;
1207         }
1208
1209         backref_ctx->sctx = sctx;
1210         backref_ctx->found = 0;
1211         backref_ctx->cur_objectid = ino;
1212         backref_ctx->cur_offset = data_offset;
1213         backref_ctx->found_itself = 0;
1214         backref_ctx->extent_len = num_bytes;
1215
1216         /*
1217          * The last extent of a file may be too large due to page alignment.
1218          * We need to adjust extent_len in this case so that the checks in
1219          * __iterate_backrefs work.
1220          */
1221         if (data_offset + num_bytes >= ino_size)
1222                 backref_ctx->extent_len = ino_size - data_offset;
1223
1224         /*
1225          * Now collect all backrefs.
1226          */
1227         extent_item_pos = logical - found_key.objectid;
1228         ret = iterate_extent_inodes(sctx->send_root->fs_info,
1229                                         found_key.objectid, extent_item_pos, 1,
1230                                         __iterate_backrefs, backref_ctx);
1231         if (ret < 0)
1232                 goto out;
1233
1234         if (!backref_ctx->found_itself) {
1235                 /* found a bug in backref code? */
1236                 ret = -EIO;
1237                 printk(KERN_ERR "btrfs: ERROR did not find backref in "
1238                                 "send_root. inode=%llu, offset=%llu, "
1239                                 "logical=%llu\n",
1240                                 ino, data_offset, logical);
1241                 goto out;
1242         }
1243
1244 verbose_printk(KERN_DEBUG "btrfs: find_extent_clone: data_offset=%llu, "
1245                 "ino=%llu, "
1246                 "num_bytes=%llu, logical=%llu\n",
1247                 data_offset, ino, num_bytes, logical);
1248
1249         if (!backref_ctx->found)
1250                 verbose_printk("btrfs:    no clones found\n");
1251
1252         cur_clone_root = NULL;
1253         for (i = 0; i < sctx->clone_roots_cnt; i++) {
1254                 if (sctx->clone_roots[i].found_refs) {
1255                         if (!cur_clone_root)
1256                                 cur_clone_root = sctx->clone_roots + i;
1257                         else if (sctx->clone_roots[i].root == sctx->send_root)
1258                                 /* prefer clones from send_root over others */
1259                                 cur_clone_root = sctx->clone_roots + i;
1260                         break;
1261                 }
1262
1263         }
1264
1265         if (cur_clone_root) {
1266                 *found = cur_clone_root;
1267                 ret = 0;
1268         } else {
1269                 ret = -ENOENT;
1270         }
1271
1272 out:
1273         btrfs_free_path(tmp_path);
1274         kfree(backref_ctx);
1275         return ret;
1276 }
1277
1278 static int read_symlink(struct send_ctx *sctx,
1279                         struct btrfs_root *root,
1280                         u64 ino,
1281                         struct fs_path *dest)
1282 {
1283         int ret;
1284         struct btrfs_path *path;
1285         struct btrfs_key key;
1286         struct btrfs_file_extent_item *ei;
1287         u8 type;
1288         u8 compression;
1289         unsigned long off;
1290         int len;
1291
1292         path = alloc_path_for_send();
1293         if (!path)
1294                 return -ENOMEM;
1295
1296         key.objectid = ino;
1297         key.type = BTRFS_EXTENT_DATA_KEY;
1298         key.offset = 0;
1299         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1300         if (ret < 0)
1301                 goto out;
1302         BUG_ON(ret);
1303
1304         ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
1305                         struct btrfs_file_extent_item);
1306         type = btrfs_file_extent_type(path->nodes[0], ei);
1307         compression = btrfs_file_extent_compression(path->nodes[0], ei);
1308         BUG_ON(type != BTRFS_FILE_EXTENT_INLINE);
1309         BUG_ON(compression);
1310
1311         off = btrfs_file_extent_inline_start(ei);
1312         len = btrfs_file_extent_inline_len(path->nodes[0], ei);
1313
1314         ret = fs_path_add_from_extent_buffer(dest, path->nodes[0], off, len);
1315         if (ret < 0)
1316                 goto out;
1317
1318 out:
1319         btrfs_free_path(path);
1320         return ret;
1321 }
1322
1323 /*
1324  * Helper function to generate a file name that is unique in the root of
1325  * send_root and parent_root. This is used to generate names for orphan inodes.
1326  */
1327 static int gen_unique_name(struct send_ctx *sctx,
1328                            u64 ino, u64 gen,
1329                            struct fs_path *dest)
1330 {
1331         int ret = 0;
1332         struct btrfs_path *path;
1333         struct btrfs_dir_item *di;
1334         char tmp[64];
1335         int len;
1336         u64 idx = 0;
1337
1338         path = alloc_path_for_send();
1339         if (!path)
1340                 return -ENOMEM;
1341
1342         while (1) {
1343                 len = snprintf(tmp, sizeof(tmp) - 1, "o%llu-%llu-%llu",
1344                                 ino, gen, idx);
1345                 if (len >= sizeof(tmp)) {
1346                         /* should really not happen */
1347                         ret = -EOVERFLOW;
1348                         goto out;
1349                 }
1350
1351                 di = btrfs_lookup_dir_item(NULL, sctx->send_root,
1352                                 path, BTRFS_FIRST_FREE_OBJECTID,
1353                                 tmp, strlen(tmp), 0);
1354                 btrfs_release_path(path);
1355                 if (IS_ERR(di)) {
1356                         ret = PTR_ERR(di);
1357                         goto out;
1358                 }
1359                 if (di) {
1360                         /* not unique, try again */
1361                         idx++;
1362                         continue;
1363                 }
1364
1365                 if (!sctx->parent_root) {
1366                         /* unique */
1367                         ret = 0;
1368                         break;
1369                 }
1370
1371                 di = btrfs_lookup_dir_item(NULL, sctx->parent_root,
1372                                 path, BTRFS_FIRST_FREE_OBJECTID,
1373                                 tmp, strlen(tmp), 0);
1374                 btrfs_release_path(path);
1375                 if (IS_ERR(di)) {
1376                         ret = PTR_ERR(di);
1377                         goto out;
1378                 }
1379                 if (di) {
1380                         /* not unique, try again */
1381                         idx++;
1382                         continue;
1383                 }
1384                 /* unique */
1385                 break;
1386         }
1387
1388         ret = fs_path_add(dest, tmp, strlen(tmp));
1389
1390 out:
1391         btrfs_free_path(path);
1392         return ret;
1393 }
1394
1395 enum inode_state {
1396         inode_state_no_change,
1397         inode_state_will_create,
1398         inode_state_did_create,
1399         inode_state_will_delete,
1400         inode_state_did_delete,
1401 };
1402
1403 static int get_cur_inode_state(struct send_ctx *sctx, u64 ino, u64 gen)
1404 {
1405         int ret;
1406         int left_ret;
1407         int right_ret;
1408         u64 left_gen;
1409         u64 right_gen;
1410
1411         ret = get_inode_info(sctx->send_root, ino, NULL, &left_gen, NULL, NULL,
1412                         NULL, NULL);
1413         if (ret < 0 && ret != -ENOENT)
1414                 goto out;
1415         left_ret = ret;
1416
1417         if (!sctx->parent_root) {
1418                 right_ret = -ENOENT;
1419         } else {
1420                 ret = get_inode_info(sctx->parent_root, ino, NULL, &right_gen,
1421                                 NULL, NULL, NULL, NULL);
1422                 if (ret < 0 && ret != -ENOENT)
1423                         goto out;
1424                 right_ret = ret;
1425         }
1426
1427         if (!left_ret && !right_ret) {
1428                 if (left_gen == gen && right_gen == gen)
1429                         ret = inode_state_no_change;
1430                 else if (left_gen == gen) {
1431                         if (ino < sctx->send_progress)
1432                                 ret = inode_state_did_create;
1433                         else
1434                                 ret = inode_state_will_create;
1435                 } else if (right_gen == gen) {
1436                         if (ino < sctx->send_progress)
1437                                 ret = inode_state_did_delete;
1438                         else
1439                                 ret = inode_state_will_delete;
1440                 } else  {
1441                         ret = -ENOENT;
1442                 }
1443         } else if (!left_ret) {
1444                 if (left_gen == gen) {
1445                         if (ino < sctx->send_progress)
1446                                 ret = inode_state_did_create;
1447                         else
1448                                 ret = inode_state_will_create;
1449                 } else {
1450                         ret = -ENOENT;
1451                 }
1452         } else if (!right_ret) {
1453                 if (right_gen == gen) {
1454                         if (ino < sctx->send_progress)
1455                                 ret = inode_state_did_delete;
1456                         else
1457                                 ret = inode_state_will_delete;
1458                 } else {
1459                         ret = -ENOENT;
1460                 }
1461         } else {
1462                 ret = -ENOENT;
1463         }
1464
1465 out:
1466         return ret;
1467 }
1468
1469 static int is_inode_existent(struct send_ctx *sctx, u64 ino, u64 gen)
1470 {
1471         int ret;
1472
1473         ret = get_cur_inode_state(sctx, ino, gen);
1474         if (ret < 0)
1475                 goto out;
1476
1477         if (ret == inode_state_no_change ||
1478             ret == inode_state_did_create ||
1479             ret == inode_state_will_delete)
1480                 ret = 1;
1481         else
1482                 ret = 0;
1483
1484 out:
1485         return ret;
1486 }
1487
1488 /*
1489  * Helper function to lookup a dir item in a dir.
1490  */
1491 static int lookup_dir_item_inode(struct btrfs_root *root,
1492                                  u64 dir, const char *name, int name_len,
1493                                  u64 *found_inode,
1494                                  u8 *found_type)
1495 {
1496         int ret = 0;
1497         struct btrfs_dir_item *di;
1498         struct btrfs_key key;
1499         struct btrfs_path *path;
1500
1501         path = alloc_path_for_send();
1502         if (!path)
1503                 return -ENOMEM;
1504
1505         di = btrfs_lookup_dir_item(NULL, root, path,
1506                         dir, name, name_len, 0);
1507         if (!di) {
1508                 ret = -ENOENT;
1509                 goto out;
1510         }
1511         if (IS_ERR(di)) {
1512                 ret = PTR_ERR(di);
1513                 goto out;
1514         }
1515         btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
1516         *found_inode = key.objectid;
1517         *found_type = btrfs_dir_type(path->nodes[0], di);
1518
1519 out:
1520         btrfs_free_path(path);
1521         return ret;
1522 }
1523
1524 static int get_first_ref(struct send_ctx *sctx,
1525                          struct btrfs_root *root, u64 ino,
1526                          u64 *dir, u64 *dir_gen, struct fs_path *name)
1527 {
1528         int ret;
1529         struct btrfs_key key;
1530         struct btrfs_key found_key;
1531         struct btrfs_path *path;
1532         struct btrfs_inode_ref *iref;
1533         int len;
1534
1535         path = alloc_path_for_send();
1536         if (!path)
1537                 return -ENOMEM;
1538
1539         key.objectid = ino;
1540         key.type = BTRFS_INODE_REF_KEY;
1541         key.offset = 0;
1542
1543         ret = btrfs_search_slot_for_read(root, &key, path, 1, 0);
1544         if (ret < 0)
1545                 goto out;
1546         if (!ret)
1547                 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1548                                 path->slots[0]);
1549         if (ret || found_key.objectid != key.objectid ||
1550             found_key.type != key.type) {
1551                 ret = -ENOENT;
1552                 goto out;
1553         }
1554
1555         iref = btrfs_item_ptr(path->nodes[0], path->slots[0],
1556                         struct btrfs_inode_ref);
1557         len = btrfs_inode_ref_name_len(path->nodes[0], iref);
1558         ret = fs_path_add_from_extent_buffer(name, path->nodes[0],
1559                         (unsigned long)(iref + 1), len);
1560         if (ret < 0)
1561                 goto out;
1562         btrfs_release_path(path);
1563
1564         ret = get_inode_info(root, found_key.offset, NULL, dir_gen, NULL, NULL,
1565                         NULL, NULL);
1566         if (ret < 0)
1567                 goto out;
1568
1569         *dir = found_key.offset;
1570
1571 out:
1572         btrfs_free_path(path);
1573         return ret;
1574 }
1575
1576 static int is_first_ref(struct send_ctx *sctx,
1577                         struct btrfs_root *root,
1578                         u64 ino, u64 dir,
1579                         const char *name, int name_len)
1580 {
1581         int ret;
1582         struct fs_path *tmp_name;
1583         u64 tmp_dir;
1584         u64 tmp_dir_gen;
1585
1586         tmp_name = fs_path_alloc(sctx);
1587         if (!tmp_name)
1588                 return -ENOMEM;
1589
1590         ret = get_first_ref(sctx, root, ino, &tmp_dir, &tmp_dir_gen, tmp_name);
1591         if (ret < 0)
1592                 goto out;
1593
1594         if (dir != tmp_dir || name_len != fs_path_len(tmp_name)) {
1595                 ret = 0;
1596                 goto out;
1597         }
1598
1599         ret = memcmp(tmp_name->start, name, name_len);
1600         if (ret)
1601                 ret = 0;
1602         else
1603                 ret = 1;
1604
1605 out:
1606         fs_path_free(sctx, tmp_name);
1607         return ret;
1608 }
1609
1610 static int will_overwrite_ref(struct send_ctx *sctx, u64 dir, u64 dir_gen,
1611                               const char *name, int name_len,
1612                               u64 *who_ino, u64 *who_gen)
1613 {
1614         int ret = 0;
1615         u64 other_inode = 0;
1616         u8 other_type = 0;
1617
1618         if (!sctx->parent_root)
1619                 goto out;
1620
1621         ret = is_inode_existent(sctx, dir, dir_gen);
1622         if (ret <= 0)
1623                 goto out;
1624
1625         ret = lookup_dir_item_inode(sctx->parent_root, dir, name, name_len,
1626                         &other_inode, &other_type);
1627         if (ret < 0 && ret != -ENOENT)
1628                 goto out;
1629         if (ret) {
1630                 ret = 0;
1631                 goto out;
1632         }
1633
1634         if (other_inode > sctx->send_progress) {
1635                 ret = get_inode_info(sctx->parent_root, other_inode, NULL,
1636                                 who_gen, NULL, NULL, NULL, NULL);
1637                 if (ret < 0)
1638                         goto out;
1639
1640                 ret = 1;
1641                 *who_ino = other_inode;
1642         } else {
1643                 ret = 0;
1644         }
1645
1646 out:
1647         return ret;
1648 }
1649
1650 static int did_overwrite_ref(struct send_ctx *sctx,
1651                             u64 dir, u64 dir_gen,
1652                             u64 ino, u64 ino_gen,
1653                             const char *name, int name_len)
1654 {
1655         int ret = 0;
1656         u64 gen;
1657         u64 ow_inode;
1658         u8 other_type;
1659
1660         if (!sctx->parent_root)
1661                 goto out;
1662
1663         ret = is_inode_existent(sctx, dir, dir_gen);
1664         if (ret <= 0)
1665                 goto out;
1666
1667         /* check if the ref was overwritten by another ref */
1668         ret = lookup_dir_item_inode(sctx->send_root, dir, name, name_len,
1669                         &ow_inode, &other_type);
1670         if (ret < 0 && ret != -ENOENT)
1671                 goto out;
1672         if (ret) {
1673                 /* was never and will never be overwritten */
1674                 ret = 0;
1675                 goto out;
1676         }
1677
1678         ret = get_inode_info(sctx->send_root, ow_inode, NULL, &gen, NULL, NULL,
1679                         NULL, NULL);
1680         if (ret < 0)
1681                 goto out;
1682
1683         if (ow_inode == ino && gen == ino_gen) {
1684                 ret = 0;
1685                 goto out;
1686         }
1687
1688         /* we know that it is or will be overwritten. check this now */
1689         if (ow_inode < sctx->send_progress)
1690                 ret = 1;
1691         else
1692                 ret = 0;
1693
1694 out:
1695         return ret;
1696 }
1697
1698 static int did_overwrite_first_ref(struct send_ctx *sctx, u64 ino, u64 gen)
1699 {
1700         int ret = 0;
1701         struct fs_path *name = NULL;
1702         u64 dir;
1703         u64 dir_gen;
1704
1705         if (!sctx->parent_root)
1706                 goto out;
1707
1708         name = fs_path_alloc(sctx);
1709         if (!name)
1710                 return -ENOMEM;
1711
1712         ret = get_first_ref(sctx, sctx->parent_root, ino, &dir, &dir_gen, name);
1713         if (ret < 0)
1714                 goto out;
1715
1716         ret = did_overwrite_ref(sctx, dir, dir_gen, ino, gen,
1717                         name->start, fs_path_len(name));
1718         if (ret < 0)
1719                 goto out;
1720
1721 out:
1722         fs_path_free(sctx, name);
1723         return ret;
1724 }
1725
1726 static int name_cache_insert(struct send_ctx *sctx,
1727                              struct name_cache_entry *nce)
1728 {
1729         int ret = 0;
1730         struct name_cache_entry **ncea;
1731
1732         ncea = radix_tree_lookup(&sctx->name_cache, nce->ino);
1733         if (ncea) {
1734                 if (!ncea[0])
1735                         ncea[0] = nce;
1736                 else if (!ncea[1])
1737                         ncea[1] = nce;
1738                 else
1739                         BUG();
1740         } else {
1741                 ncea = kmalloc(sizeof(void *) * 2, GFP_NOFS);
1742                 if (!ncea)
1743                         return -ENOMEM;
1744
1745                 ncea[0] = nce;
1746                 ncea[1] = NULL;
1747                 ret = radix_tree_insert(&sctx->name_cache, nce->ino, ncea);
1748                 if (ret < 0)
1749                         return ret;
1750         }
1751         list_add_tail(&nce->list, &sctx->name_cache_list);
1752         sctx->name_cache_size++;
1753
1754         return ret;
1755 }
1756
1757 static void name_cache_delete(struct send_ctx *sctx,
1758                               struct name_cache_entry *nce)
1759 {
1760         struct name_cache_entry **ncea;
1761
1762         ncea = radix_tree_lookup(&sctx->name_cache, nce->ino);
1763         BUG_ON(!ncea);
1764
1765         if (ncea[0] == nce)
1766                 ncea[0] = NULL;
1767         else if (ncea[1] == nce)
1768                 ncea[1] = NULL;
1769         else
1770                 BUG();
1771
1772         if (!ncea[0] && !ncea[1]) {
1773                 radix_tree_delete(&sctx->name_cache, nce->ino);
1774                 kfree(ncea);
1775         }
1776
1777         list_del(&nce->list);
1778
1779         sctx->name_cache_size--;
1780 }
1781
1782 static struct name_cache_entry *name_cache_search(struct send_ctx *sctx,
1783                                                     u64 ino, u64 gen)
1784 {
1785         struct name_cache_entry **ncea;
1786
1787         ncea = radix_tree_lookup(&sctx->name_cache, ino);
1788         if (!ncea)
1789                 return NULL;
1790
1791         if (ncea[0] && ncea[0]->gen == gen)
1792                 return ncea[0];
1793         else if (ncea[1] && ncea[1]->gen == gen)
1794                 return ncea[1];
1795         return NULL;
1796 }
1797
1798 static void name_cache_used(struct send_ctx *sctx, struct name_cache_entry *nce)
1799 {
1800         list_del(&nce->list);
1801         list_add_tail(&nce->list, &sctx->name_cache_list);
1802 }
1803
1804 static void name_cache_clean_unused(struct send_ctx *sctx)
1805 {
1806         struct name_cache_entry *nce;
1807
1808         if (sctx->name_cache_size < SEND_CTX_NAME_CACHE_CLEAN_SIZE)
1809                 return;
1810
1811         while (sctx->name_cache_size > SEND_CTX_MAX_NAME_CACHE_SIZE) {
1812                 nce = list_entry(sctx->name_cache_list.next,
1813                                 struct name_cache_entry, list);
1814                 name_cache_delete(sctx, nce);
1815                 kfree(nce);
1816         }
1817 }
1818
1819 static void name_cache_free(struct send_ctx *sctx)
1820 {
1821         struct name_cache_entry *nce;
1822         struct name_cache_entry *tmp;
1823
1824         list_for_each_entry_safe(nce, tmp, &sctx->name_cache_list, list) {
1825                 name_cache_delete(sctx, nce);
1826         }
1827 }
1828
1829 static int __get_cur_name_and_parent(struct send_ctx *sctx,
1830                                      u64 ino, u64 gen,
1831                                      u64 *parent_ino,
1832                                      u64 *parent_gen,
1833                                      struct fs_path *dest)
1834 {
1835         int ret;
1836         int nce_ret;
1837         struct btrfs_path *path = NULL;
1838         struct name_cache_entry *nce = NULL;
1839
1840         nce = name_cache_search(sctx, ino, gen);
1841         if (nce) {
1842                 if (ino < sctx->send_progress && nce->need_later_update) {
1843                         name_cache_delete(sctx, nce);
1844                         kfree(nce);
1845                         nce = NULL;
1846                 } else {
1847                         name_cache_used(sctx, nce);
1848                         *parent_ino = nce->parent_ino;
1849                         *parent_gen = nce->parent_gen;
1850                         ret = fs_path_add(dest, nce->name, nce->name_len);
1851                         if (ret < 0)
1852                                 goto out;
1853                         ret = nce->ret;
1854                         goto out;
1855                 }
1856         }
1857
1858         path = alloc_path_for_send();
1859         if (!path)
1860                 return -ENOMEM;
1861
1862         ret = is_inode_existent(sctx, ino, gen);
1863         if (ret < 0)
1864                 goto out;
1865
1866         if (!ret) {
1867                 ret = gen_unique_name(sctx, ino, gen, dest);
1868                 if (ret < 0)
1869                         goto out;
1870                 ret = 1;
1871                 goto out_cache;
1872         }
1873
1874         if (ino < sctx->send_progress)
1875                 ret = get_first_ref(sctx, sctx->send_root, ino,
1876                                 parent_ino, parent_gen, dest);
1877         else
1878                 ret = get_first_ref(sctx, sctx->parent_root, ino,
1879                                 parent_ino, parent_gen, dest);
1880         if (ret < 0)
1881                 goto out;
1882
1883         ret = did_overwrite_ref(sctx, *parent_ino, *parent_gen, ino, gen,
1884                         dest->start, dest->end - dest->start);
1885         if (ret < 0)
1886                 goto out;
1887         if (ret) {
1888                 fs_path_reset(dest);
1889                 ret = gen_unique_name(sctx, ino, gen, dest);
1890                 if (ret < 0)
1891                         goto out;
1892                 ret = 1;
1893         }
1894
1895 out_cache:
1896         nce = kmalloc(sizeof(*nce) + fs_path_len(dest) + 1, GFP_NOFS);
1897         if (!nce) {
1898                 ret = -ENOMEM;
1899                 goto out;
1900         }
1901
1902         nce->ino = ino;
1903         nce->gen = gen;
1904         nce->parent_ino = *parent_ino;
1905         nce->parent_gen = *parent_gen;
1906         nce->name_len = fs_path_len(dest);
1907         nce->ret = ret;
1908         strcpy(nce->name, dest->start);
1909
1910         if (ino < sctx->send_progress)
1911                 nce->need_later_update = 0;
1912         else
1913                 nce->need_later_update = 1;
1914
1915         nce_ret = name_cache_insert(sctx, nce);
1916         if (nce_ret < 0)
1917                 ret = nce_ret;
1918         name_cache_clean_unused(sctx);
1919
1920 out:
1921         btrfs_free_path(path);
1922         return ret;
1923 }
1924
1925 /*
1926  * Magic happens here. This function returns the first ref to an inode as it
1927  * would look like while receiving the stream at this point in time.
1928  * We walk the path up to the root. For every inode in between, we check if it
1929  * was already processed/sent. If yes, we continue with the parent as found
1930  * in send_root. If not, we continue with the parent as found in parent_root.
1931  * If we encounter an inode that was deleted at this point in time, we use the
1932  * inodes "orphan" name instead of the real name and stop. Same with new inodes
1933  * that were not created yet and overwritten inodes/refs.
1934  *
1935  * When do we have have orphan inodes:
1936  * 1. When an inode is freshly created and thus no valid refs are available yet
1937  * 2. When a directory lost all it's refs (deleted) but still has dir items
1938  *    inside which were not processed yet (pending for move/delete). If anyone
1939  *    tried to get the path to the dir items, it would get a path inside that
1940  *    orphan directory.
1941  * 3. When an inode is moved around or gets new links, it may overwrite the ref
1942  *    of an unprocessed inode. If in that case the first ref would be
1943  *    overwritten, the overwritten inode gets "orphanized". Later when we
1944  *    process this overwritten inode, it is restored at a new place by moving
1945  *    the orphan inode.
1946  *
1947  * sctx->send_progress tells this function at which point in time receiving
1948  * would be.
1949  */
1950 static int get_cur_path(struct send_ctx *sctx, u64 ino, u64 gen,
1951                         struct fs_path *dest)
1952 {
1953         int ret = 0;
1954         struct fs_path *name = NULL;
1955         u64 parent_inode = 0;
1956         u64 parent_gen = 0;
1957         int stop = 0;
1958
1959         name = fs_path_alloc(sctx);
1960         if (!name) {
1961                 ret = -ENOMEM;
1962                 goto out;
1963         }
1964
1965         dest->reversed = 1;
1966         fs_path_reset(dest);
1967
1968         while (!stop && ino != BTRFS_FIRST_FREE_OBJECTID) {
1969                 fs_path_reset(name);
1970
1971                 ret = __get_cur_name_and_parent(sctx, ino, gen,
1972                                 &parent_inode, &parent_gen, name);
1973                 if (ret < 0)
1974                         goto out;
1975                 if (ret)
1976                         stop = 1;
1977
1978                 ret = fs_path_add_path(dest, name);
1979                 if (ret < 0)
1980                         goto out;
1981
1982                 ino = parent_inode;
1983                 gen = parent_gen;
1984         }
1985
1986 out:
1987         fs_path_free(sctx, name);
1988         if (!ret)
1989                 fs_path_unreverse(dest);
1990         return ret;
1991 }
1992
1993 /*
1994  * Called for regular files when sending extents data. Opens a struct file
1995  * to read from the file.
1996  */
1997 static int open_cur_inode_file(struct send_ctx *sctx)
1998 {
1999         int ret = 0;
2000         struct btrfs_key key;
2001         struct path path;
2002         struct inode *inode;
2003         struct dentry *dentry;
2004         struct file *filp;
2005         int new = 0;
2006
2007         if (sctx->cur_inode_filp)
2008                 goto out;
2009
2010         key.objectid = sctx->cur_ino;
2011         key.type = BTRFS_INODE_ITEM_KEY;
2012         key.offset = 0;
2013
2014         inode = btrfs_iget(sctx->send_root->fs_info->sb, &key, sctx->send_root,
2015                         &new);
2016         if (IS_ERR(inode)) {
2017                 ret = PTR_ERR(inode);
2018                 goto out;
2019         }
2020
2021         dentry = d_obtain_alias(inode);
2022         inode = NULL;
2023         if (IS_ERR(dentry)) {
2024                 ret = PTR_ERR(dentry);
2025                 goto out;
2026         }
2027
2028         path.mnt = sctx->mnt;
2029         path.dentry = dentry;
2030         filp = dentry_open(&path, O_RDONLY | O_LARGEFILE, current_cred());
2031         dput(dentry);
2032         dentry = NULL;
2033         if (IS_ERR(filp)) {
2034                 ret = PTR_ERR(filp);
2035                 goto out;
2036         }
2037         sctx->cur_inode_filp = filp;
2038
2039 out:
2040         /*
2041          * no xxxput required here as every vfs op
2042          * does it by itself on failure
2043          */
2044         return ret;
2045 }
2046
2047 /*
2048  * Closes the struct file that was created in open_cur_inode_file
2049  */
2050 static int close_cur_inode_file(struct send_ctx *sctx)
2051 {
2052         int ret = 0;
2053
2054         if (!sctx->cur_inode_filp)
2055                 goto out;
2056
2057         ret = filp_close(sctx->cur_inode_filp, NULL);
2058         sctx->cur_inode_filp = NULL;
2059
2060 out:
2061         return ret;
2062 }
2063
2064 /*
2065  * Sends a BTRFS_SEND_C_SUBVOL command/item to userspace
2066  */
2067 static int send_subvol_begin(struct send_ctx *sctx)
2068 {
2069         int ret;
2070         struct btrfs_root *send_root = sctx->send_root;
2071         struct btrfs_root *parent_root = sctx->parent_root;
2072         struct btrfs_path *path;
2073         struct btrfs_key key;
2074         struct btrfs_root_ref *ref;
2075         struct extent_buffer *leaf;
2076         char *name = NULL;
2077         int namelen;
2078
2079         path = alloc_path_for_send();
2080         if (!path)
2081                 return -ENOMEM;
2082
2083         name = kmalloc(BTRFS_PATH_NAME_MAX, GFP_NOFS);
2084         if (!name) {
2085                 btrfs_free_path(path);
2086                 return -ENOMEM;
2087         }
2088
2089         key.objectid = send_root->objectid;
2090         key.type = BTRFS_ROOT_BACKREF_KEY;
2091         key.offset = 0;
2092
2093         ret = btrfs_search_slot_for_read(send_root->fs_info->tree_root,
2094                                 &key, path, 1, 0);
2095         if (ret < 0)
2096                 goto out;
2097         if (ret) {
2098                 ret = -ENOENT;
2099                 goto out;
2100         }
2101
2102         leaf = path->nodes[0];
2103         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2104         if (key.type != BTRFS_ROOT_BACKREF_KEY ||
2105             key.objectid != send_root->objectid) {
2106                 ret = -ENOENT;
2107                 goto out;
2108         }
2109         ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
2110         namelen = btrfs_root_ref_name_len(leaf, ref);
2111         read_extent_buffer(leaf, name, (unsigned long)(ref + 1), namelen);
2112         btrfs_release_path(path);
2113
2114         if (ret < 0)
2115                 goto out;
2116
2117         if (parent_root) {
2118                 ret = begin_cmd(sctx, BTRFS_SEND_C_SNAPSHOT);
2119                 if (ret < 0)
2120                         goto out;
2121         } else {
2122                 ret = begin_cmd(sctx, BTRFS_SEND_C_SUBVOL);
2123                 if (ret < 0)
2124                         goto out;
2125         }
2126
2127         TLV_PUT_STRING(sctx, BTRFS_SEND_A_PATH, name, namelen);
2128         TLV_PUT_UUID(sctx, BTRFS_SEND_A_UUID,
2129                         sctx->send_root->root_item.uuid);
2130         TLV_PUT_U64(sctx, BTRFS_SEND_A_CTRANSID,
2131                         sctx->send_root->root_item.ctransid);
2132         if (parent_root) {
2133                 TLV_PUT_UUID(sctx, BTRFS_SEND_A_CLONE_UUID,
2134                                 sctx->parent_root->root_item.uuid);
2135                 TLV_PUT_U64(sctx, BTRFS_SEND_A_CLONE_CTRANSID,
2136                                 sctx->parent_root->root_item.ctransid);
2137         }
2138
2139         ret = send_cmd(sctx);
2140
2141 tlv_put_failure:
2142 out:
2143         btrfs_free_path(path);
2144         kfree(name);
2145         return ret;
2146 }
2147
2148 static int send_truncate(struct send_ctx *sctx, u64 ino, u64 gen, u64 size)
2149 {
2150         int ret = 0;
2151         struct fs_path *p;
2152
2153 verbose_printk("btrfs: send_truncate %llu size=%llu\n", ino, size);
2154
2155         p = fs_path_alloc(sctx);
2156         if (!p)
2157                 return -ENOMEM;
2158
2159         ret = begin_cmd(sctx, BTRFS_SEND_C_TRUNCATE);
2160         if (ret < 0)
2161                 goto out;
2162
2163         ret = get_cur_path(sctx, ino, gen, p);
2164         if (ret < 0)
2165                 goto out;
2166         TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
2167         TLV_PUT_U64(sctx, BTRFS_SEND_A_SIZE, size);
2168
2169         ret = send_cmd(sctx);
2170
2171 tlv_put_failure:
2172 out:
2173         fs_path_free(sctx, p);
2174         return ret;
2175 }
2176
2177 static int send_chmod(struct send_ctx *sctx, u64 ino, u64 gen, u64 mode)
2178 {
2179         int ret = 0;
2180         struct fs_path *p;
2181
2182 verbose_printk("btrfs: send_chmod %llu mode=%llu\n", ino, mode);
2183
2184         p = fs_path_alloc(sctx);
2185         if (!p)
2186                 return -ENOMEM;
2187
2188         ret = begin_cmd(sctx, BTRFS_SEND_C_CHMOD);
2189         if (ret < 0)
2190                 goto out;
2191
2192         ret = get_cur_path(sctx, ino, gen, p);
2193         if (ret < 0)
2194                 goto out;
2195         TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
2196         TLV_PUT_U64(sctx, BTRFS_SEND_A_MODE, mode & 07777);
2197
2198         ret = send_cmd(sctx);
2199
2200 tlv_put_failure:
2201 out:
2202         fs_path_free(sctx, p);
2203         return ret;
2204 }
2205
2206 static int send_chown(struct send_ctx *sctx, u64 ino, u64 gen, u64 uid, u64 gid)
2207 {
2208         int ret = 0;
2209         struct fs_path *p;
2210
2211 verbose_printk("btrfs: send_chown %llu uid=%llu, gid=%llu\n", ino, uid, gid);
2212
2213         p = fs_path_alloc(sctx);
2214         if (!p)
2215                 return -ENOMEM;
2216
2217         ret = begin_cmd(sctx, BTRFS_SEND_C_CHOWN);
2218         if (ret < 0)
2219                 goto out;
2220
2221         ret = get_cur_path(sctx, ino, gen, p);
2222         if (ret < 0)
2223                 goto out;
2224         TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
2225         TLV_PUT_U64(sctx, BTRFS_SEND_A_UID, uid);
2226         TLV_PUT_U64(sctx, BTRFS_SEND_A_GID, gid);
2227
2228         ret = send_cmd(sctx);
2229
2230 tlv_put_failure:
2231 out:
2232         fs_path_free(sctx, p);
2233         return ret;
2234 }
2235
2236 static int send_utimes(struct send_ctx *sctx, u64 ino, u64 gen)
2237 {
2238         int ret = 0;
2239         struct fs_path *p = NULL;
2240         struct btrfs_inode_item *ii;
2241         struct btrfs_path *path = NULL;
2242         struct extent_buffer *eb;
2243         struct btrfs_key key;
2244         int slot;
2245
2246 verbose_printk("btrfs: send_utimes %llu\n", ino);
2247
2248         p = fs_path_alloc(sctx);
2249         if (!p)
2250                 return -ENOMEM;
2251
2252         path = alloc_path_for_send();
2253         if (!path) {
2254                 ret = -ENOMEM;
2255                 goto out;
2256         }
2257
2258         key.objectid = ino;
2259         key.type = BTRFS_INODE_ITEM_KEY;
2260         key.offset = 0;
2261         ret = btrfs_search_slot(NULL, sctx->send_root, &key, path, 0, 0);
2262         if (ret < 0)
2263                 goto out;
2264
2265         eb = path->nodes[0];
2266         slot = path->slots[0];
2267         ii = btrfs_item_ptr(eb, slot, struct btrfs_inode_item);
2268
2269         ret = begin_cmd(sctx, BTRFS_SEND_C_UTIMES);
2270         if (ret < 0)
2271                 goto out;
2272
2273         ret = get_cur_path(sctx, ino, gen, p);
2274         if (ret < 0)
2275                 goto out;
2276         TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
2277         TLV_PUT_BTRFS_TIMESPEC(sctx, BTRFS_SEND_A_ATIME, eb,
2278                         btrfs_inode_atime(ii));
2279         TLV_PUT_BTRFS_TIMESPEC(sctx, BTRFS_SEND_A_MTIME, eb,
2280                         btrfs_inode_mtime(ii));
2281         TLV_PUT_BTRFS_TIMESPEC(sctx, BTRFS_SEND_A_CTIME, eb,
2282                         btrfs_inode_ctime(ii));
2283         /* TODO otime? */
2284
2285         ret = send_cmd(sctx);
2286
2287 tlv_put_failure:
2288 out:
2289         fs_path_free(sctx, p);
2290         btrfs_free_path(path);
2291         return ret;
2292 }
2293
2294 /*
2295  * Sends a BTRFS_SEND_C_MKXXX or SYMLINK command to user space. We don't have
2296  * a valid path yet because we did not process the refs yet. So, the inode
2297  * is created as orphan.
2298  */
2299 static int send_create_inode(struct send_ctx *sctx, u64 ino)
2300 {
2301         int ret = 0;
2302         struct fs_path *p;
2303         int cmd;
2304         u64 gen;
2305         u64 mode;
2306         u64 rdev;
2307
2308 verbose_printk("btrfs: send_create_inode %llu\n", ino);
2309
2310         p = fs_path_alloc(sctx);
2311         if (!p)
2312                 return -ENOMEM;
2313
2314         ret = get_inode_info(sctx->send_root, ino, NULL, &gen, &mode, NULL,
2315                         NULL, &rdev);
2316         if (ret < 0)
2317                 goto out;
2318
2319         if (S_ISREG(mode))
2320                 cmd = BTRFS_SEND_C_MKFILE;
2321         else if (S_ISDIR(mode))
2322                 cmd = BTRFS_SEND_C_MKDIR;
2323         else if (S_ISLNK(mode))
2324                 cmd = BTRFS_SEND_C_SYMLINK;
2325         else if (S_ISCHR(mode) || S_ISBLK(mode))
2326                 cmd = BTRFS_SEND_C_MKNOD;
2327         else if (S_ISFIFO(mode))
2328                 cmd = BTRFS_SEND_C_MKFIFO;
2329         else if (S_ISSOCK(mode))
2330                 cmd = BTRFS_SEND_C_MKSOCK;
2331         else {
2332                 printk(KERN_WARNING "btrfs: unexpected inode type %o",
2333                                 (int)(mode & S_IFMT));
2334                 ret = -ENOTSUPP;
2335                 goto out;
2336         }
2337
2338         ret = begin_cmd(sctx, cmd);
2339         if (ret < 0)
2340                 goto out;
2341
2342         ret = gen_unique_name(sctx, ino, gen, p);
2343         if (ret < 0)
2344                 goto out;
2345
2346         TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
2347         TLV_PUT_U64(sctx, BTRFS_SEND_A_INO, ino);
2348
2349         if (S_ISLNK(mode)) {
2350                 fs_path_reset(p);
2351                 ret = read_symlink(sctx, sctx->send_root, ino, p);
2352                 if (ret < 0)
2353                         goto out;
2354                 TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH_LINK, p);
2355         } else if (S_ISCHR(mode) || S_ISBLK(mode) ||
2356                    S_ISFIFO(mode) || S_ISSOCK(mode)) {
2357                 TLV_PUT_U64(sctx, BTRFS_SEND_A_RDEV, rdev);
2358         }
2359
2360         ret = send_cmd(sctx);
2361         if (ret < 0)
2362                 goto out;
2363
2364
2365 tlv_put_failure:
2366 out:
2367         fs_path_free(sctx, p);
2368         return ret;
2369 }
2370
2371 /*
2372  * We need some special handling for inodes that get processed before the parent
2373  * directory got created. See process_recorded_refs for details.
2374  * This function does the check if we already created the dir out of order.
2375  */
2376 static int did_create_dir(struct send_ctx *sctx, u64 dir)
2377 {
2378         int ret = 0;
2379         struct btrfs_path *path = NULL;
2380         struct btrfs_key key;
2381         struct btrfs_key found_key;
2382         struct btrfs_key di_key;
2383         struct extent_buffer *eb;
2384         struct btrfs_dir_item *di;
2385         int slot;
2386
2387         path = alloc_path_for_send();
2388         if (!path) {
2389                 ret = -ENOMEM;
2390                 goto out;
2391         }
2392
2393         key.objectid = dir;
2394         key.type = BTRFS_DIR_INDEX_KEY;
2395         key.offset = 0;
2396         while (1) {
2397                 ret = btrfs_search_slot_for_read(sctx->send_root, &key, path,
2398                                 1, 0);
2399                 if (ret < 0)
2400                         goto out;
2401                 if (!ret) {
2402                         eb = path->nodes[0];
2403                         slot = path->slots[0];
2404                         btrfs_item_key_to_cpu(eb, &found_key, slot);
2405                 }
2406                 if (ret || found_key.objectid != key.objectid ||
2407                     found_key.type != key.type) {
2408                         ret = 0;
2409                         goto out;
2410                 }
2411
2412                 di = btrfs_item_ptr(eb, slot, struct btrfs_dir_item);
2413                 btrfs_dir_item_key_to_cpu(eb, di, &di_key);
2414
2415                 if (di_key.objectid < sctx->send_progress) {
2416                         ret = 1;
2417                         goto out;
2418                 }
2419
2420                 key.offset = found_key.offset + 1;
2421                 btrfs_release_path(path);
2422         }
2423
2424 out:
2425         btrfs_free_path(path);
2426         return ret;
2427 }
2428
2429 /*
2430  * Only creates the inode if it is:
2431  * 1. Not a directory
2432  * 2. Or a directory which was not created already due to out of order
2433  *    directories. See did_create_dir and process_recorded_refs for details.
2434  */
2435 static int send_create_inode_if_needed(struct send_ctx *sctx)
2436 {
2437         int ret;
2438
2439         if (S_ISDIR(sctx->cur_inode_mode)) {
2440                 ret = did_create_dir(sctx, sctx->cur_ino);
2441                 if (ret < 0)
2442                         goto out;
2443                 if (ret) {
2444                         ret = 0;
2445                         goto out;
2446                 }
2447         }
2448
2449         ret = send_create_inode(sctx, sctx->cur_ino);
2450         if (ret < 0)
2451                 goto out;
2452
2453 out:
2454         return ret;
2455 }
2456
2457 struct recorded_ref {
2458         struct list_head list;
2459         char *dir_path;
2460         char *name;
2461         struct fs_path *full_path;
2462         u64 dir;
2463         u64 dir_gen;
2464         int dir_path_len;
2465         int name_len;
2466 };
2467
2468 /*
2469  * We need to process new refs before deleted refs, but compare_tree gives us
2470  * everything mixed. So we first record all refs and later process them.
2471  * This function is a helper to record one ref.
2472  */
2473 static int record_ref(struct list_head *head, u64 dir,
2474                       u64 dir_gen, struct fs_path *path)
2475 {
2476         struct recorded_ref *ref;
2477         char *tmp;
2478
2479         ref = kmalloc(sizeof(*ref), GFP_NOFS);
2480         if (!ref)
2481                 return -ENOMEM;
2482
2483         ref->dir = dir;
2484         ref->dir_gen = dir_gen;
2485         ref->full_path = path;
2486
2487         tmp = strrchr(ref->full_path->start, '/');
2488         if (!tmp) {
2489                 ref->name_len = ref->full_path->end - ref->full_path->start;
2490                 ref->name = ref->full_path->start;
2491                 ref->dir_path_len = 0;
2492                 ref->dir_path = ref->full_path->start;
2493         } else {
2494                 tmp++;
2495                 ref->name_len = ref->full_path->end - tmp;
2496                 ref->name = tmp;
2497                 ref->dir_path = ref->full_path->start;
2498                 ref->dir_path_len = ref->full_path->end -
2499                                 ref->full_path->start - 1 - ref->name_len;
2500         }
2501
2502         list_add_tail(&ref->list, head);
2503         return 0;
2504 }
2505
2506 static void __free_recorded_refs(struct send_ctx *sctx, struct list_head *head)
2507 {
2508         struct recorded_ref *cur;
2509         struct recorded_ref *tmp;
2510
2511         list_for_each_entry_safe(cur, tmp, head, list) {
2512                 fs_path_free(sctx, cur->full_path);
2513                 kfree(cur);
2514         }
2515         INIT_LIST_HEAD(head);
2516 }
2517
2518 static void free_recorded_refs(struct send_ctx *sctx)
2519 {
2520         __free_recorded_refs(sctx, &sctx->new_refs);
2521         __free_recorded_refs(sctx, &sctx->deleted_refs);
2522 }
2523
2524 /*
2525  * Renames/moves a file/dir to it's orphan name. Used when the first
2526  * ref of an unprocessed inode gets overwritten and for all non empty
2527  * directories.
2528  */
2529 static int orphanize_inode(struct send_ctx *sctx, u64 ino, u64 gen,
2530                           struct fs_path *path)
2531 {
2532         int ret;
2533         struct fs_path *orphan;
2534
2535         orphan = fs_path_alloc(sctx);
2536         if (!orphan)
2537                 return -ENOMEM;
2538
2539         ret = gen_unique_name(sctx, ino, gen, orphan);
2540         if (ret < 0)
2541                 goto out;
2542
2543         ret = send_rename(sctx, path, orphan);
2544
2545 out:
2546         fs_path_free(sctx, orphan);
2547         return ret;
2548 }
2549
2550 /*
2551  * Returns 1 if a directory can be removed at this point in time.
2552  * We check this by iterating all dir items and checking if the inode behind
2553  * the dir item was already processed.
2554  */
2555 static int can_rmdir(struct send_ctx *sctx, u64 dir, u64 send_progress)
2556 {
2557         int ret = 0;
2558         struct btrfs_root *root = sctx->parent_root;
2559         struct btrfs_path *path;
2560         struct btrfs_key key;
2561         struct btrfs_key found_key;
2562         struct btrfs_key loc;
2563         struct btrfs_dir_item *di;
2564
2565         path = alloc_path_for_send();
2566         if (!path)
2567                 return -ENOMEM;
2568
2569         key.objectid = dir;
2570         key.type = BTRFS_DIR_INDEX_KEY;
2571         key.offset = 0;
2572
2573         while (1) {
2574                 ret = btrfs_search_slot_for_read(root, &key, path, 1, 0);
2575                 if (ret < 0)
2576                         goto out;
2577                 if (!ret) {
2578                         btrfs_item_key_to_cpu(path->nodes[0], &found_key,
2579                                         path->slots[0]);
2580                 }
2581                 if (ret || found_key.objectid != key.objectid ||
2582                     found_key.type != key.type) {
2583                         break;
2584                 }
2585
2586                 di = btrfs_item_ptr(path->nodes[0], path->slots[0],
2587                                 struct btrfs_dir_item);
2588                 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &loc);
2589
2590                 if (loc.objectid > send_progress) {
2591                         ret = 0;
2592                         goto out;
2593                 }
2594
2595                 btrfs_release_path(path);
2596                 key.offset = found_key.offset + 1;
2597         }
2598
2599         ret = 1;
2600
2601 out:
2602         btrfs_free_path(path);
2603         return ret;
2604 }
2605
2606 /*
2607  * This does all the move/link/unlink/rmdir magic.
2608  */
2609 static int process_recorded_refs(struct send_ctx *sctx)
2610 {
2611         int ret = 0;
2612         struct recorded_ref *cur;
2613         struct recorded_ref *cur2;
2614         struct ulist *check_dirs = NULL;
2615         struct ulist_iterator uit;
2616         struct ulist_node *un;
2617         struct fs_path *valid_path = NULL;
2618         u64 ow_inode = 0;
2619         u64 ow_gen;
2620         int did_overwrite = 0;
2621         int is_orphan = 0;
2622
2623 verbose_printk("btrfs: process_recorded_refs %llu\n", sctx->cur_ino);
2624
2625         valid_path = fs_path_alloc(sctx);
2626         if (!valid_path) {
2627                 ret = -ENOMEM;
2628                 goto out;
2629         }
2630
2631         check_dirs = ulist_alloc(GFP_NOFS);
2632         if (!check_dirs) {
2633                 ret = -ENOMEM;
2634                 goto out;
2635         }
2636
2637         /*
2638          * First, check if the first ref of the current inode was overwritten
2639          * before. If yes, we know that the current inode was already orphanized
2640          * and thus use the orphan name. If not, we can use get_cur_path to
2641          * get the path of the first ref as it would like while receiving at
2642          * this point in time.
2643          * New inodes are always orphan at the beginning, so force to use the
2644          * orphan name in this case.
2645          * The first ref is stored in valid_path and will be updated if it
2646          * gets moved around.
2647          */
2648         if (!sctx->cur_inode_new) {
2649                 ret = did_overwrite_first_ref(sctx, sctx->cur_ino,
2650                                 sctx->cur_inode_gen);
2651                 if (ret < 0)
2652                         goto out;
2653                 if (ret)
2654                         did_overwrite = 1;
2655         }
2656         if (sctx->cur_inode_new || did_overwrite) {
2657                 ret = gen_unique_name(sctx, sctx->cur_ino,
2658                                 sctx->cur_inode_gen, valid_path);
2659                 if (ret < 0)
2660                         goto out;
2661                 is_orphan = 1;
2662         } else {
2663                 ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen,
2664                                 valid_path);
2665                 if (ret < 0)
2666                         goto out;
2667         }
2668
2669         list_for_each_entry(cur, &sctx->new_refs, list) {
2670                 /*
2671                  * We may have refs where the parent directory does not exist
2672                  * yet. This happens if the parent directories inum is higher
2673                  * the the current inum. To handle this case, we create the
2674                  * parent directory out of order. But we need to check if this
2675                  * did already happen before due to other refs in the same dir.
2676                  */
2677                 ret = get_cur_inode_state(sctx, cur->dir, cur->dir_gen);
2678                 if (ret < 0)
2679                         goto out;
2680                 if (ret == inode_state_will_create) {
2681                         ret = 0;
2682                         /*
2683                          * First check if any of the current inodes refs did
2684                          * already create the dir.
2685                          */
2686                         list_for_each_entry(cur2, &sctx->new_refs, list) {
2687                                 if (cur == cur2)
2688                                         break;
2689                                 if (cur2->dir == cur->dir) {
2690                                         ret = 1;
2691                                         break;
2692                                 }
2693                         }
2694
2695                         /*
2696                          * If that did not happen, check if a previous inode
2697                          * did already create the dir.
2698                          */
2699                         if (!ret)
2700                                 ret = did_create_dir(sctx, cur->dir);
2701                         if (ret < 0)
2702                                 goto out;
2703                         if (!ret) {
2704                                 ret = send_create_inode(sctx, cur->dir);
2705                                 if (ret < 0)
2706                                         goto out;
2707                         }
2708                 }
2709
2710                 /*
2711                  * Check if this new ref would overwrite the first ref of
2712                  * another unprocessed inode. If yes, orphanize the
2713                  * overwritten inode. If we find an overwritten ref that is
2714                  * not the first ref, simply unlink it.
2715                  */
2716                 ret = will_overwrite_ref(sctx, cur->dir, cur->dir_gen,
2717                                 cur->name, cur->name_len,
2718                                 &ow_inode, &ow_gen);
2719                 if (ret < 0)
2720                         goto out;
2721                 if (ret) {
2722                         ret = is_first_ref(sctx, sctx->parent_root,
2723                                         ow_inode, cur->dir, cur->name,
2724                                         cur->name_len);
2725                         if (ret < 0)
2726                                 goto out;
2727                         if (ret) {
2728                                 ret = orphanize_inode(sctx, ow_inode, ow_gen,
2729                                                 cur->full_path);
2730                                 if (ret < 0)
2731                                         goto out;
2732                         } else {
2733                                 ret = send_unlink(sctx, cur->full_path);
2734                                 if (ret < 0)
2735                                         goto out;
2736                         }
2737                 }
2738
2739                 /*
2740                  * link/move the ref to the new place. If we have an orphan
2741                  * inode, move it and update valid_path. If not, link or move
2742                  * it depending on the inode mode.
2743                  */
2744                 if (is_orphan) {
2745                         ret = send_rename(sctx, valid_path, cur->full_path);
2746                         if (ret < 0)
2747                                 goto out;
2748                         is_orphan = 0;
2749                         ret = fs_path_copy(valid_path, cur->full_path);
2750                         if (ret < 0)
2751                                 goto out;
2752                 } else {
2753                         if (S_ISDIR(sctx->cur_inode_mode)) {
2754                                 /*
2755                                  * Dirs can't be linked, so move it. For moved
2756                                  * dirs, we always have one new and one deleted
2757                                  * ref. The deleted ref is ignored later.
2758                                  */
2759                                 ret = send_rename(sctx, valid_path,
2760                                                 cur->full_path);
2761                                 if (ret < 0)
2762                                         goto out;
2763                                 ret = fs_path_copy(valid_path, cur->full_path);
2764                                 if (ret < 0)
2765                                         goto out;
2766                         } else {
2767                                 ret = send_link(sctx, cur->full_path,
2768                                                 valid_path);
2769                                 if (ret < 0)
2770                                         goto out;
2771                         }
2772                 }
2773                 ret = ulist_add(check_dirs, cur->dir, cur->dir_gen,
2774                                 GFP_NOFS);
2775                 if (ret < 0)
2776                         goto out;
2777         }
2778
2779         if (S_ISDIR(sctx->cur_inode_mode) && sctx->cur_inode_deleted) {
2780                 /*
2781                  * Check if we can already rmdir the directory. If not,
2782                  * orphanize it. For every dir item inside that gets deleted
2783                  * later, we do this check again and rmdir it then if possible.
2784                  * See the use of check_dirs for more details.
2785                  */
2786                 ret = can_rmdir(sctx, sctx->cur_ino, sctx->cur_ino);
2787                 if (ret < 0)
2788                         goto out;
2789                 if (ret) {
2790                         ret = send_rmdir(sctx, valid_path);
2791                         if (ret < 0)
2792                                 goto out;
2793                 } else if (!is_orphan) {
2794                         ret = orphanize_inode(sctx, sctx->cur_ino,
2795                                         sctx->cur_inode_gen, valid_path);
2796                         if (ret < 0)
2797                                 goto out;
2798                         is_orphan = 1;
2799                 }
2800
2801                 list_for_each_entry(cur, &sctx->deleted_refs, list) {
2802                         ret = ulist_add(check_dirs, cur->dir, cur->dir_gen,
2803                                         GFP_NOFS);
2804                         if (ret < 0)
2805                                 goto out;
2806                 }
2807         } else if (S_ISDIR(sctx->cur_inode_mode) &&
2808                    !list_empty(&sctx->deleted_refs)) {
2809                 /*
2810                  * We have a moved dir. Add the old parent to check_dirs
2811                  */
2812                 cur = list_entry(sctx->deleted_refs.next, struct recorded_ref,
2813                                 list);
2814                 ret = ulist_add(check_dirs, cur->dir, cur->dir_gen,
2815                                 GFP_NOFS);
2816                 if (ret < 0)
2817                         goto out;
2818         } else if (!S_ISDIR(sctx->cur_inode_mode)) {
2819                 /*
2820                  * We have a non dir inode. Go through all deleted refs and
2821                  * unlink them if they were not already overwritten by other
2822                  * inodes.
2823                  */
2824                 list_for_each_entry(cur, &sctx->deleted_refs, list) {
2825                         ret = did_overwrite_ref(sctx, cur->dir, cur->dir_gen,
2826                                         sctx->cur_ino, sctx->cur_inode_gen,
2827                                         cur->name, cur->name_len);
2828                         if (ret < 0)
2829                                 goto out;
2830                         if (!ret) {
2831                                 ret = send_unlink(sctx, cur->full_path);
2832                                 if (ret < 0)
2833                                         goto out;
2834                         }
2835                         ret = ulist_add(check_dirs, cur->dir, cur->dir_gen,
2836                                         GFP_NOFS);
2837                         if (ret < 0)
2838                                 goto out;
2839                 }
2840
2841                 /*
2842                  * If the inode is still orphan, unlink the orphan. This may
2843                  * happen when a previous inode did overwrite the first ref
2844                  * of this inode and no new refs were added for the current
2845                  * inode.
2846                  */
2847                 if (is_orphan) {
2848                         ret = send_unlink(sctx, valid_path);
2849                         if (ret < 0)
2850                                 goto out;
2851                 }
2852         }
2853
2854         /*
2855          * We did collect all parent dirs where cur_inode was once located. We
2856          * now go through all these dirs and check if they are pending for
2857          * deletion and if it's finally possible to perform the rmdir now.
2858          * We also update the inode stats of the parent dirs here.
2859          */
2860         ULIST_ITER_INIT(&uit);
2861         while ((un = ulist_next(check_dirs, &uit))) {
2862                 if (un->val > sctx->cur_ino)
2863                         continue;
2864
2865                 ret = get_cur_inode_state(sctx, un->val, un->aux);
2866                 if (ret < 0)
2867                         goto out;
2868
2869                 if (ret == inode_state_did_create ||
2870                     ret == inode_state_no_change) {
2871                         /* TODO delayed utimes */
2872                         ret = send_utimes(sctx, un->val, un->aux);
2873                         if (ret < 0)
2874                                 goto out;
2875                 } else if (ret == inode_state_did_delete) {
2876                         ret = can_rmdir(sctx, un->val, sctx->cur_ino);
2877                         if (ret < 0)
2878                                 goto out;
2879                         if (ret) {
2880                                 ret = get_cur_path(sctx, un->val, un->aux,
2881                                                 valid_path);
2882                                 if (ret < 0)
2883                                         goto out;
2884                                 ret = send_rmdir(sctx, valid_path);
2885                                 if (ret < 0)
2886                                         goto out;
2887                         }
2888                 }
2889         }
2890
2891         /*
2892          * Current inode is now at it's new position, so we must increase
2893          * send_progress
2894          */
2895         sctx->send_progress = sctx->cur_ino + 1;
2896
2897         ret = 0;
2898
2899 out:
2900         free_recorded_refs(sctx);
2901         ulist_free(check_dirs);
2902         fs_path_free(sctx, valid_path);
2903         return ret;
2904 }
2905
2906 static int __record_new_ref(int num, u64 dir, int index,
2907                             struct fs_path *name,
2908                             void *ctx)
2909 {
2910         int ret = 0;
2911         struct send_ctx *sctx = ctx;
2912         struct fs_path *p;
2913         u64 gen;
2914
2915         p = fs_path_alloc(sctx);
2916         if (!p)
2917                 return -ENOMEM;
2918
2919         ret = get_inode_info(sctx->send_root, dir, NULL, &gen, NULL, NULL,
2920                         NULL, NULL);
2921         if (ret < 0)
2922                 goto out;
2923
2924         ret = get_cur_path(sctx, dir, gen, p);
2925         if (ret < 0)
2926                 goto out;
2927         ret = fs_path_add_path(p, name);
2928         if (ret < 0)
2929                 goto out;
2930
2931         ret = record_ref(&sctx->new_refs, dir, gen, p);
2932
2933 out:
2934         if (ret)
2935                 fs_path_free(sctx, p);
2936         return ret;
2937 }
2938
2939 static int __record_deleted_ref(int num, u64 dir, int index,
2940                                 struct fs_path *name,
2941                                 void *ctx)
2942 {
2943         int ret = 0;
2944         struct send_ctx *sctx = ctx;
2945         struct fs_path *p;
2946         u64 gen;
2947
2948         p = fs_path_alloc(sctx);
2949         if (!p)
2950                 return -ENOMEM;
2951
2952         ret = get_inode_info(sctx->parent_root, dir, NULL, &gen, NULL, NULL,
2953                         NULL, NULL);
2954         if (ret < 0)
2955                 goto out;
2956
2957         ret = get_cur_path(sctx, dir, gen, p);
2958         if (ret < 0)
2959                 goto out;
2960         ret = fs_path_add_path(p, name);
2961         if (ret < 0)
2962                 goto out;
2963
2964         ret = record_ref(&sctx->deleted_refs, dir, gen, p);
2965
2966 out:
2967         if (ret)
2968                 fs_path_free(sctx, p);
2969         return ret;
2970 }
2971
2972 static int record_new_ref(struct send_ctx *sctx)
2973 {
2974         int ret;
2975
2976         ret = iterate_inode_ref(sctx, sctx->send_root, sctx->left_path,
2977                         sctx->cmp_key, 0, __record_new_ref, sctx);
2978         if (ret < 0)
2979                 goto out;
2980         ret = 0;
2981
2982 out:
2983         return ret;
2984 }
2985
2986 static int record_deleted_ref(struct send_ctx *sctx)
2987 {
2988         int ret;
2989
2990         ret = iterate_inode_ref(sctx, sctx->parent_root, sctx->right_path,
2991                         sctx->cmp_key, 0, __record_deleted_ref, sctx);
2992         if (ret < 0)
2993                 goto out;
2994         ret = 0;
2995
2996 out:
2997         return ret;
2998 }
2999
3000 struct find_ref_ctx {
3001         u64 dir;
3002         struct fs_path *name;
3003         int found_idx;
3004 };
3005
3006 static int __find_iref(int num, u64 dir, int index,
3007                        struct fs_path *name,
3008                        void *ctx_)
3009 {
3010         struct find_ref_ctx *ctx = ctx_;
3011
3012         if (dir == ctx->dir && fs_path_len(name) == fs_path_len(ctx->name) &&
3013             strncmp(name->start, ctx->name->start, fs_path_len(name)) == 0) {
3014                 ctx->found_idx = num;
3015                 return 1;
3016         }
3017         return 0;
3018 }
3019
3020 static int find_iref(struct send_ctx *sctx,
3021                      struct btrfs_root *root,
3022                      struct btrfs_path *path,
3023                      struct btrfs_key *key,
3024                      u64 dir, struct fs_path *name)
3025 {
3026         int ret;
3027         struct find_ref_ctx ctx;
3028
3029         ctx.dir = dir;
3030         ctx.name = name;
3031         ctx.found_idx = -1;
3032
3033         ret = iterate_inode_ref(sctx, root, path, key, 0, __find_iref, &ctx);
3034         if (ret < 0)
3035                 return ret;
3036
3037         if (ctx.found_idx == -1)
3038                 return -ENOENT;
3039
3040         return ctx.found_idx;
3041 }
3042
3043 static int __record_changed_new_ref(int num, u64 dir, int index,
3044                                     struct fs_path *name,
3045                                     void *ctx)
3046 {
3047         int ret;
3048         struct send_ctx *sctx = ctx;
3049
3050         ret = find_iref(sctx, sctx->parent_root, sctx->right_path,
3051                         sctx->cmp_key, dir, name);
3052         if (ret == -ENOENT)
3053                 ret = __record_new_ref(num, dir, index, name, sctx);
3054         else if (ret > 0)
3055                 ret = 0;
3056
3057         return ret;
3058 }
3059
3060 static int __record_changed_deleted_ref(int num, u64 dir, int index,
3061                                         struct fs_path *name,
3062                                         void *ctx)
3063 {
3064         int ret;
3065         struct send_ctx *sctx = ctx;
3066
3067         ret = find_iref(sctx, sctx->send_root, sctx->left_path, sctx->cmp_key,
3068                         dir, name);
3069         if (ret == -ENOENT)
3070                 ret = __record_deleted_ref(num, dir, index, name, sctx);
3071         else if (ret > 0)
3072                 ret = 0;
3073
3074         return ret;
3075 }
3076
3077 static int record_changed_ref(struct send_ctx *sctx)
3078 {
3079         int ret = 0;
3080
3081         ret = iterate_inode_ref(sctx, sctx->send_root, sctx->left_path,
3082                         sctx->cmp_key, 0, __record_changed_new_ref, sctx);
3083         if (ret < 0)
3084                 goto out;
3085         ret = iterate_inode_ref(sctx, sctx->parent_root, sctx->right_path,
3086                         sctx->cmp_key, 0, __record_changed_deleted_ref, sctx);
3087         if (ret < 0)
3088                 goto out;
3089         ret = 0;
3090
3091 out:
3092         return ret;
3093 }
3094
3095 /*
3096  * Record and process all refs at once. Needed when an inode changes the
3097  * generation number, which means that it was deleted and recreated.
3098  */
3099 static int process_all_refs(struct send_ctx *sctx,
3100                             enum btrfs_compare_tree_result cmd)
3101 {
3102         int ret;
3103         struct btrfs_root *root;
3104         struct btrfs_path *path;
3105         struct btrfs_key key;
3106         struct btrfs_key found_key;
3107         struct extent_buffer *eb;
3108         int slot;
3109         iterate_inode_ref_t cb;
3110
3111         path = alloc_path_for_send();
3112         if (!path)
3113                 return -ENOMEM;
3114
3115         if (cmd == BTRFS_COMPARE_TREE_NEW) {
3116                 root = sctx->send_root;
3117                 cb = __record_new_ref;
3118         } else if (cmd == BTRFS_COMPARE_TREE_DELETED) {
3119                 root = sctx->parent_root;
3120                 cb = __record_deleted_ref;
3121         } else {
3122                 BUG();
3123         }
3124
3125         key.objectid = sctx->cmp_key->objectid;
3126         key.type = BTRFS_INODE_REF_KEY;
3127         key.offset = 0;
3128         while (1) {
3129                 ret = btrfs_search_slot_for_read(root, &key, path, 1, 0);
3130                 if (ret < 0) {
3131                         btrfs_release_path(path);
3132                         goto out;
3133                 }
3134                 if (ret) {
3135                         btrfs_release_path(path);
3136                         break;
3137                 }
3138
3139                 eb = path->nodes[0];
3140                 slot = path->slots[0];
3141                 btrfs_item_key_to_cpu(eb, &found_key, slot);
3142
3143                 if (found_key.objectid != key.objectid ||
3144                     found_key.type != key.type) {
3145                         btrfs_release_path(path);
3146                         break;
3147                 }
3148
3149                 ret = iterate_inode_ref(sctx, sctx->parent_root, path,
3150                                 &found_key, 0, cb, sctx);
3151                 btrfs_release_path(path);
3152                 if (ret < 0)
3153                         goto out;
3154
3155                 key.offset = found_key.offset + 1;
3156         }
3157
3158         ret = process_recorded_refs(sctx);
3159
3160 out:
3161         btrfs_free_path(path);
3162         return ret;
3163 }
3164
3165 static int send_set_xattr(struct send_ctx *sctx,
3166                           struct fs_path *path,
3167                           const char *name, int name_len,
3168                           const char *data, int data_len)
3169 {
3170         int ret = 0;
3171
3172         ret = begin_cmd(sctx, BTRFS_SEND_C_SET_XATTR);
3173         if (ret < 0)
3174                 goto out;
3175
3176         TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, path);
3177         TLV_PUT_STRING(sctx, BTRFS_SEND_A_XATTR_NAME, name, name_len);
3178         TLV_PUT(sctx, BTRFS_SEND_A_XATTR_DATA, data, data_len);
3179
3180         ret = send_cmd(sctx);
3181
3182 tlv_put_failure:
3183 out:
3184         return ret;
3185 }
3186
3187 static int send_remove_xattr(struct send_ctx *sctx,
3188                           struct fs_path *path,
3189                           const char *name, int name_len)
3190 {
3191         int ret = 0;
3192
3193         ret = begin_cmd(sctx, BTRFS_SEND_C_REMOVE_XATTR);
3194         if (ret < 0)
3195                 goto out;
3196
3197         TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, path);
3198         TLV_PUT_STRING(sctx, BTRFS_SEND_A_XATTR_NAME, name, name_len);
3199
3200         ret = send_cmd(sctx);
3201
3202 tlv_put_failure:
3203 out:
3204         return ret;
3205 }
3206
3207 static int __process_new_xattr(int num, struct btrfs_key *di_key,
3208                                const char *name, int name_len,
3209                                const char *data, int data_len,
3210                                u8 type, void *ctx)
3211 {
3212         int ret;
3213         struct send_ctx *sctx = ctx;
3214         struct fs_path *p;
3215         posix_acl_xattr_header dummy_acl;
3216
3217         p = fs_path_alloc(sctx);
3218         if (!p)
3219                 return -ENOMEM;
3220
3221         /*
3222          * This hack is needed because empty acl's are stored as zero byte
3223          * data in xattrs. Problem with that is, that receiving these zero byte
3224          * acl's will fail later. To fix this, we send a dummy acl list that
3225          * only contains the version number and no entries.
3226          */
3227         if (!strncmp(name, XATTR_NAME_POSIX_ACL_ACCESS, name_len) ||
3228             !strncmp(name, XATTR_NAME_POSIX_ACL_DEFAULT, name_len)) {
3229                 if (data_len == 0) {
3230                         dummy_acl.a_version =
3231                                         cpu_to_le32(POSIX_ACL_XATTR_VERSION);
3232                         data = (char *)&dummy_acl;
3233                         data_len = sizeof(dummy_acl);
3234                 }
3235         }
3236
3237         ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
3238         if (ret < 0)
3239                 goto out;
3240
3241         ret = send_set_xattr(sctx, p, name, name_len, data, data_len);
3242
3243 out:
3244         fs_path_free(sctx, p);
3245         return ret;
3246 }
3247
3248 static int __process_deleted_xattr(int num, struct btrfs_key *di_key,
3249                                    const char *name, int name_len,
3250                                    const char *data, int data_len,
3251                                    u8 type, void *ctx)
3252 {
3253         int ret;
3254         struct send_ctx *sctx = ctx;
3255         struct fs_path *p;
3256
3257         p = fs_path_alloc(sctx);
3258         if (!p)
3259                 return -ENOMEM;
3260
3261         ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
3262         if (ret < 0)
3263                 goto out;
3264
3265         ret = send_remove_xattr(sctx, p, name, name_len);
3266
3267 out:
3268         fs_path_free(sctx, p);
3269         return ret;
3270 }
3271
3272 static int process_new_xattr(struct send_ctx *sctx)
3273 {
3274         int ret = 0;
3275
3276         ret = iterate_dir_item(sctx, sctx->send_root, sctx->left_path,
3277                         sctx->cmp_key, __process_new_xattr, sctx);
3278
3279         return ret;
3280 }
3281
3282 static int process_deleted_xattr(struct send_ctx *sctx)
3283 {
3284         int ret;
3285
3286         ret = iterate_dir_item(sctx, sctx->parent_root, sctx->right_path,
3287                         sctx->cmp_key, __process_deleted_xattr, sctx);
3288
3289         return ret;
3290 }
3291
3292 struct find_xattr_ctx {
3293         const char *name;
3294         int name_len;
3295         int found_idx;
3296         char *found_data;
3297         int found_data_len;
3298 };
3299
3300 static int __find_xattr(int num, struct btrfs_key *di_key,
3301                         const char *name, int name_len,
3302                         const char *data, int data_len,
3303                         u8 type, void *vctx)
3304 {
3305         struct find_xattr_ctx *ctx = vctx;
3306
3307         if (name_len == ctx->name_len &&
3308             strncmp(name, ctx->name, name_len) == 0) {
3309                 ctx->found_idx = num;
3310                 ctx->found_data_len = data_len;
3311                 ctx->found_data = kmalloc(data_len, GFP_NOFS);
3312                 if (!ctx->found_data)
3313                         return -ENOMEM;
3314                 memcpy(ctx->found_data, data, data_len);
3315                 return 1;
3316         }
3317         return 0;
3318 }
3319
3320 static int find_xattr(struct send_ctx *sctx,
3321                       struct btrfs_root *root,
3322                       struct btrfs_path *path,
3323                       struct btrfs_key *key,
3324                       const char *name, int name_len,
3325                       char **data, int *data_len)
3326 {
3327         int ret;
3328         struct find_xattr_ctx ctx;
3329
3330         ctx.name = name;
3331         ctx.name_len = name_len;
3332         ctx.found_idx = -1;
3333         ctx.found_data = NULL;
3334         ctx.found_data_len = 0;
3335
3336         ret = iterate_dir_item(sctx, root, path, key, __find_xattr, &ctx);
3337         if (ret < 0)
3338                 return ret;
3339
3340         if (ctx.found_idx == -1)
3341                 return -ENOENT;
3342         if (data) {
3343                 *data = ctx.found_data;
3344                 *data_len = ctx.found_data_len;
3345         } else {
3346                 kfree(ctx.found_data);
3347         }
3348         return ctx.found_idx;
3349 }
3350
3351
3352 static int __process_changed_new_xattr(int num, struct btrfs_key *di_key,
3353                                        const char *name, int name_len,
3354                                        const char *data, int data_len,
3355                                        u8 type, void *ctx)
3356 {
3357         int ret;
3358         struct send_ctx *sctx = ctx;
3359         char *found_data = NULL;
3360         int found_data_len  = 0;
3361         struct fs_path *p = NULL;
3362
3363         ret = find_xattr(sctx, sctx->parent_root, sctx->right_path,
3364                         sctx->cmp_key, name, name_len, &found_data,
3365                         &found_data_len);
3366         if (ret == -ENOENT) {
3367                 ret = __process_new_xattr(num, di_key, name, name_len, data,
3368                                 data_len, type, ctx);
3369         } else if (ret >= 0) {
3370                 if (data_len != found_data_len ||
3371                     memcmp(data, found_data, data_len)) {
3372                         ret = __process_new_xattr(num, di_key, name, name_len,
3373                                         data, data_len, type, ctx);
3374                 } else {
3375                         ret = 0;
3376                 }
3377         }
3378
3379         kfree(found_data);
3380         fs_path_free(sctx, p);
3381         return ret;
3382 }
3383
3384 static int __process_changed_deleted_xattr(int num, struct btrfs_key *di_key,
3385                                            const char *name, int name_len,
3386                                            const char *data, int data_len,
3387                                            u8 type, void *ctx)
3388 {
3389         int ret;
3390         struct send_ctx *sctx = ctx;
3391
3392         ret = find_xattr(sctx, sctx->send_root, sctx->left_path, sctx->cmp_key,
3393                         name, name_len, NULL, NULL);
3394         if (ret == -ENOENT)
3395                 ret = __process_deleted_xattr(num, di_key, name, name_len, data,
3396                                 data_len, type, ctx);
3397         else if (ret >= 0)
3398                 ret = 0;
3399
3400         return ret;
3401 }
3402
3403 static int process_changed_xattr(struct send_ctx *sctx)
3404 {
3405         int ret = 0;
3406
3407         ret = iterate_dir_item(sctx, sctx->send_root, sctx->left_path,
3408                         sctx->cmp_key, __process_changed_new_xattr, sctx);
3409         if (ret < 0)
3410                 goto out;
3411         ret = iterate_dir_item(sctx, sctx->parent_root, sctx->right_path,
3412                         sctx->cmp_key, __process_changed_deleted_xattr, sctx);
3413
3414 out:
3415         return ret;
3416 }
3417
3418 static int process_all_new_xattrs(struct send_ctx *sctx)
3419 {
3420         int ret;
3421         struct btrfs_root *root;
3422         struct btrfs_path *path;
3423         struct btrfs_key key;
3424         struct btrfs_key found_key;
3425         struct extent_buffer *eb;
3426         int slot;
3427
3428         path = alloc_path_for_send();
3429         if (!path)
3430                 return -ENOMEM;
3431
3432         root = sctx->send_root;
3433
3434         key.objectid = sctx->cmp_key->objectid;
3435         key.type = BTRFS_XATTR_ITEM_KEY;
3436         key.offset = 0;
3437         while (1) {
3438                 ret = btrfs_search_slot_for_read(root, &key, path, 1, 0);
3439                 if (ret < 0)
3440                         goto out;
3441                 if (ret) {
3442                         ret = 0;
3443                         goto out;
3444                 }
3445
3446                 eb = path->nodes[0];
3447                 slot = path->slots[0];
3448                 btrfs_item_key_to_cpu(eb, &found_key, slot);
3449
3450                 if (found_key.objectid != key.objectid ||
3451                     found_key.type != key.type) {
3452                         ret = 0;
3453                         goto out;
3454                 }
3455
3456                 ret = iterate_dir_item(sctx, root, path, &found_key,
3457                                 __process_new_xattr, sctx);
3458                 if (ret < 0)
3459                         goto out;
3460
3461                 btrfs_release_path(path);
3462                 key.offset = found_key.offset + 1;
3463         }
3464
3465 out:
3466         btrfs_free_path(path);
3467         return ret;
3468 }
3469
3470 /*
3471  * Read some bytes from the current inode/file and send a write command to
3472  * user space.
3473  */
3474 static int send_write(struct send_ctx *sctx, u64 offset, u32 len)
3475 {
3476         int ret = 0;
3477         struct fs_path *p;
3478         loff_t pos = offset;
3479         int readed = 0;
3480         mm_segment_t old_fs;
3481
3482         p = fs_path_alloc(sctx);
3483         if (!p)
3484                 return -ENOMEM;
3485
3486         /*
3487          * vfs normally only accepts user space buffers for security reasons.
3488          * we only read from the file and also only provide the read_buf buffer
3489          * to vfs. As this buffer does not come from a user space call, it's
3490          * ok to temporary allow kernel space buffers.
3491          */
3492         old_fs = get_fs();
3493         set_fs(KERNEL_DS);
3494
3495 verbose_printk("btrfs: send_write offset=%llu, len=%d\n", offset, len);
3496
3497         ret = open_cur_inode_file(sctx);
3498         if (ret < 0)
3499                 goto out;
3500
3501         ret = vfs_read(sctx->cur_inode_filp, sctx->read_buf, len, &pos);
3502         if (ret < 0)
3503                 goto out;
3504         readed = ret;
3505         if (!readed)
3506                 goto out;
3507
3508         ret = begin_cmd(sctx, BTRFS_SEND_C_WRITE);
3509         if (ret < 0)
3510                 goto out;
3511
3512         ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
3513         if (ret < 0)
3514                 goto out;
3515
3516         TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
3517         TLV_PUT_U64(sctx, BTRFS_SEND_A_FILE_OFFSET, offset);
3518         TLV_PUT(sctx, BTRFS_SEND_A_DATA, sctx->read_buf, readed);
3519
3520         ret = send_cmd(sctx);
3521
3522 tlv_put_failure:
3523 out:
3524         fs_path_free(sctx, p);
3525         set_fs(old_fs);
3526         if (ret < 0)
3527                 return ret;
3528         return readed;
3529 }
3530
3531 /*
3532  * Send a clone command to user space.
3533  */
3534 static int send_clone(struct send_ctx *sctx,
3535                       u64 offset, u32 len,
3536                       struct clone_root *clone_root)
3537 {
3538         int ret = 0;
3539         struct btrfs_root *clone_root2 = clone_root->root;
3540         struct fs_path *p;
3541         u64 gen;
3542
3543 verbose_printk("btrfs: send_clone offset=%llu, len=%d, clone_root=%llu, "
3544                "clone_inode=%llu, clone_offset=%llu\n", offset, len,
3545                 clone_root->root->objectid, clone_root->ino,
3546                 clone_root->offset);
3547
3548         p = fs_path_alloc(sctx);
3549         if (!p)
3550                 return -ENOMEM;
3551
3552         ret = begin_cmd(sctx, BTRFS_SEND_C_CLONE);
3553         if (ret < 0)
3554                 goto out;
3555
3556         ret = get_cur_path(sctx, sctx->cur_ino, sctx->cur_inode_gen, p);
3557         if (ret < 0)
3558                 goto out;
3559
3560         TLV_PUT_U64(sctx, BTRFS_SEND_A_FILE_OFFSET, offset);
3561         TLV_PUT_U64(sctx, BTRFS_SEND_A_CLONE_LEN, len);
3562         TLV_PUT_PATH(sctx, BTRFS_SEND_A_PATH, p);
3563
3564         if (clone_root2 == sctx->send_root) {
3565                 ret = get_inode_info(sctx->send_root, clone_root->ino, NULL,
3566                                 &gen, NULL, NULL, NULL, NULL);
3567                 if (ret < 0)
3568                         goto out;
3569                 ret = get_cur_path(sctx, clone_root->ino, gen, p);
3570         } else {
3571                 ret = get_inode_path(sctx, clone_root2, clone_root->ino, p);
3572         }
3573         if (ret < 0)
3574                 goto out;
3575
3576         TLV_PUT_UUID(sctx, BTRFS_SEND_A_CLONE_UUID,
3577                         clone_root2->root_item.uuid);
3578         TLV_PUT_U64(sctx, BTRFS_SEND_A_CLONE_CTRANSID,
3579                         clone_root2->root_item.ctransid);
3580         TLV_PUT_PATH(sctx, BTRFS_SEND_A_CLONE_PATH, p);
3581         TLV_PUT_U64(sctx, BTRFS_SEND_A_CLONE_OFFSET,
3582                         clone_root->offset);
3583
3584         ret = send_cmd(sctx);
3585
3586 tlv_put_failure:
3587 out:
3588         fs_path_free(sctx, p);
3589         return ret;
3590 }
3591
3592 static int send_write_or_clone(struct send_ctx *sctx,
3593                                struct btrfs_path *path,
3594                                struct btrfs_key *key,
3595                                struct clone_root *clone_root)
3596 {
3597         int ret = 0;
3598         struct btrfs_file_extent_item *ei;
3599         u64 offset = key->offset;
3600         u64 pos = 0;
3601         u64 len;
3602         u32 l;
3603         u8 type;
3604
3605         ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
3606                         struct btrfs_file_extent_item);
3607         type = btrfs_file_extent_type(path->nodes[0], ei);
3608         if (type == BTRFS_FILE_EXTENT_INLINE)
3609                 len = btrfs_file_extent_inline_len(path->nodes[0], ei);
3610         else
3611                 len = btrfs_file_extent_num_bytes(path->nodes[0], ei);
3612
3613         if (offset + len > sctx->cur_inode_size)
3614                 len = sctx->cur_inode_size - offset;
3615         if (len == 0) {
3616                 ret = 0;
3617                 goto out;
3618         }
3619
3620         if (!clone_root) {
3621                 while (pos < len) {
3622                         l = len - pos;
3623                         if (l > BTRFS_SEND_READ_SIZE)
3624                                 l = BTRFS_SEND_READ_SIZE;
3625                         ret = send_write(sctx, pos + offset, l);
3626                         if (ret < 0)
3627                                 goto out;
3628                         if (!ret)
3629                                 break;
3630                         pos += ret;
3631                 }
3632                 ret = 0;
3633         } else {
3634                 ret = send_clone(sctx, offset, len, clone_root);
3635         }
3636
3637 out:
3638         return ret;
3639 }
3640
3641 static int is_extent_unchanged(struct send_ctx *sctx,
3642                                struct btrfs_path *left_path,
3643                                struct btrfs_key *ekey)
3644 {
3645         int ret = 0;
3646         struct btrfs_key key;
3647         struct btrfs_path *path = NULL;
3648         struct extent_buffer *eb;
3649         int slot;
3650         struct btrfs_key found_key;
3651         struct btrfs_file_extent_item *ei;
3652         u64 left_disknr;
3653         u64 right_disknr;
3654         u64 left_offset;
3655         u64 right_offset;
3656         u64 left_offset_fixed;
3657         u64 left_len;
3658         u64 right_len;
3659         u8 left_type;
3660         u8 right_type;
3661
3662         path = alloc_path_for_send();
3663         if (!path)
3664                 return -ENOMEM;
3665
3666         eb = left_path->nodes[0];
3667         slot = left_path->slots[0];
3668
3669         ei = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
3670         left_type = btrfs_file_extent_type(eb, ei);
3671         left_disknr = btrfs_file_extent_disk_bytenr(eb, ei);
3672         left_len = btrfs_file_extent_num_bytes(eb, ei);
3673         left_offset = btrfs_file_extent_offset(eb, ei);
3674
3675         if (left_type != BTRFS_FILE_EXTENT_REG) {
3676                 ret = 0;
3677                 goto out;
3678         }
3679
3680         /*
3681          * Following comments will refer to these graphics. L is the left
3682          * extents which we are checking at the moment. 1-8 are the right
3683          * extents that we iterate.
3684          *
3685          *       |-----L-----|
3686          * |-1-|-2a-|-3-|-4-|-5-|-6-|
3687          *
3688          *       |-----L-----|
3689          * |--1--|-2b-|...(same as above)
3690          *
3691          * Alternative situation. Happens on files where extents got split.
3692          *       |-----L-----|
3693          * |-----------7-----------|-6-|
3694          *
3695          * Alternative situation. Happens on files which got larger.
3696          *       |-----L-----|
3697          * |-8-|
3698          * Nothing follows after 8.
3699          */
3700
3701         key.objectid = ekey->objectid;
3702         key.type = BTRFS_EXTENT_DATA_KEY;
3703         key.offset = ekey->offset;
3704         ret = btrfs_search_slot_for_read(sctx->parent_root, &key, path, 0, 0);
3705         if (ret < 0)
3706                 goto out;
3707         if (ret) {
3708                 ret = 0;
3709                 goto out;
3710         }
3711
3712         /*
3713          * Handle special case where the right side has no extents at all.
3714          */
3715         eb = path->nodes[0];
3716         slot = path->slots[0];
3717         btrfs_item_key_to_cpu(eb, &found_key, slot);
3718         if (found_key.objectid != key.objectid ||
3719             found_key.type != key.type) {
3720                 ret = 0;
3721                 goto out;
3722         }
3723
3724         /*
3725          * We're now on 2a, 2b or 7.
3726          */
3727         key = found_key;
3728         while (key.offset < ekey->offset + left_len) {
3729                 ei = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
3730                 right_type = btrfs_file_extent_type(eb, ei);
3731                 right_disknr = btrfs_file_extent_disk_bytenr(eb, ei);
3732                 right_len = btrfs_file_extent_num_bytes(eb, ei);
3733                 right_offset = btrfs_file_extent_offset(eb, ei);
3734
3735                 if (right_type != BTRFS_FILE_EXTENT_REG) {
3736                         ret = 0;
3737                         goto out;
3738                 }
3739
3740                 /*
3741                  * Are we at extent 8? If yes, we know the extent is changed.
3742                  * This may only happen on the first iteration.
3743                  */
3744                 if (found_key.offset + right_len < ekey->offset) {
3745                         ret = 0;
3746                         goto out;
3747                 }
3748
3749                 left_offset_fixed = left_offset;
3750                 if (key.offset < ekey->offset) {
3751                         /* Fix the right offset for 2a and 7. */
3752                         right_offset += ekey->offset - key.offset;
3753                 } else {
3754                         /* Fix the left offset for all behind 2a and 2b */
3755                         left_offset_fixed += key.offset - ekey->offset;
3756                 }
3757
3758                 /*
3759                  * Check if we have the same extent.
3760                  */
3761                 if (left_disknr + left_offset_fixed !=
3762                                 right_disknr + right_offset) {
3763                         ret = 0;
3764                         goto out;
3765                 }
3766
3767                 /*
3768                  * Go to the next extent.
3769                  */
3770                 ret = btrfs_next_item(sctx->parent_root, path);
3771                 if (ret < 0)
3772                         goto out;
3773                 if (!ret) {
3774                         eb = path->nodes[0];
3775                         slot = path->slots[0];
3776                         btrfs_item_key_to_cpu(eb, &found_key, slot);
3777                 }
3778                 if (ret || found_key.objectid != key.objectid ||
3779                     found_key.type != key.type) {
3780                         key.offset += right_len;
3781                         break;
3782                 } else {
3783                         if (found_key.offset != key.offset + right_len) {
3784                                 /* Should really not happen */
3785                                 ret = -EIO;
3786                                 goto out;
3787                         }
3788                 }
3789                 key = found_key;
3790         }
3791
3792         /*
3793          * We're now behind the left extent (treat as unchanged) or at the end
3794          * of the right side (treat as changed).
3795          */
3796         if (key.offset >= ekey->offset + left_len)
3797                 ret = 1;
3798         else
3799                 ret = 0;
3800
3801
3802 out:
3803         btrfs_free_path(path);
3804         return ret;
3805 }
3806
3807 static int process_extent(struct send_ctx *sctx,
3808                           struct btrfs_path *path,
3809                           struct btrfs_key *key)
3810 {
3811         int ret = 0;
3812         struct clone_root *found_clone = NULL;
3813
3814         if (S_ISLNK(sctx->cur_inode_mode))
3815                 return 0;
3816
3817         if (sctx->parent_root && !sctx->cur_inode_new) {
3818                 ret = is_extent_unchanged(sctx, path, key);
3819                 if (ret < 0)
3820                         goto out;
3821                 if (ret) {
3822                         ret = 0;
3823                         goto out;
3824                 }
3825         }
3826
3827         ret = find_extent_clone(sctx, path, key->objectid, key->offset,
3828                         sctx->cur_inode_size, &found_clone);
3829         if (ret != -ENOENT && ret < 0)
3830                 goto out;
3831
3832         ret = send_write_or_clone(sctx, path, key, found_clone);
3833
3834 out:
3835         return ret;
3836 }
3837
3838 static int process_all_extents(struct send_ctx *sctx)
3839 {
3840         int ret;
3841         struct btrfs_root *root;
3842         struct btrfs_path *path;
3843         struct btrfs_key key;
3844         struct btrfs_key found_key;
3845         struct extent_buffer *eb;
3846         int slot;
3847
3848         root = sctx->send_root;
3849         path = alloc_path_for_send();
3850         if (!path)
3851                 return -ENOMEM;
3852
3853         key.objectid = sctx->cmp_key->objectid;
3854         key.type = BTRFS_EXTENT_DATA_KEY;
3855         key.offset = 0;
3856         while (1) {
3857                 ret = btrfs_search_slot_for_read(root, &key, path, 1, 0);
3858                 if (ret < 0)
3859                         goto out;
3860                 if (ret) {
3861                         ret = 0;
3862                         goto out;
3863                 }
3864
3865                 eb = path->nodes[0];
3866                 slot = path->slots[0];
3867                 btrfs_item_key_to_cpu(eb, &found_key, slot);
3868
3869                 if (found_key.objectid != key.objectid ||
3870                     found_key.type != key.type) {
3871                         ret = 0;
3872                         goto out;
3873                 }
3874
3875                 ret = process_extent(sctx, path, &found_key);
3876                 if (ret < 0)
3877                         goto out;
3878
3879                 btrfs_release_path(path);
3880                 key.offset = found_key.offset + 1;
3881         }
3882
3883 out:
3884         btrfs_free_path(path);
3885         return ret;
3886 }
3887
3888 static int process_recorded_refs_if_needed(struct send_ctx *sctx, int at_end)
3889 {
3890         int ret = 0;
3891
3892         if (sctx->cur_ino == 0)
3893                 goto out;
3894         if (!at_end && sctx->cur_ino == sctx->cmp_key->objectid &&
3895             sctx->cmp_key->type <= BTRFS_INODE_REF_KEY)
3896                 goto out;
3897         if (list_empty(&sctx->new_refs) && list_empty(&sctx->deleted_refs))
3898                 goto out;
3899
3900         ret = process_recorded_refs(sctx);
3901
3902 out:
3903         return ret;
3904 }
3905
3906 static int finish_inode_if_needed(struct send_ctx *sctx, int at_end)
3907 {
3908         int ret = 0;
3909         u64 left_mode;
3910         u64 left_uid;
3911         u64 left_gid;
3912         u64 right_mode;
3913         u64 right_uid;
3914         u64 right_gid;
3915         int need_chmod = 0;
3916         int need_chown = 0;
3917
3918         ret = process_recorded_refs_if_needed(sctx, at_end);
3919         if (ret < 0)
3920                 goto out;
3921
3922         if (sctx->cur_ino == 0 || sctx->cur_inode_deleted)
3923                 goto out;
3924         if (!at_end && sctx->cmp_key->objectid == sctx->cur_ino)
3925                 goto out;
3926
3927         ret = get_inode_info(sctx->send_root, sctx->cur_ino, NULL, NULL,
3928                         &left_mode, &left_uid, &left_gid, NULL);
3929         if (ret < 0)
3930                 goto out;
3931
3932         if (!S_ISLNK(sctx->cur_inode_mode)) {
3933                 if (!sctx->parent_root || sctx->cur_inode_new) {
3934                         need_chmod = 1;
3935                         need_chown = 1;
3936                 } else {
3937                         ret = get_inode_info(sctx->parent_root, sctx->cur_ino,
3938                                         NULL, NULL, &right_mode, &right_uid,
3939                                         &right_gid, NULL);
3940                         if (ret < 0)
3941                                 goto out;
3942
3943                         if (left_uid != right_uid || left_gid != right_gid)
3944                                 need_chown = 1;
3945                         if (left_mode != right_mode)
3946                                 need_chmod = 1;
3947                 }
3948         }
3949
3950         if (S_ISREG(sctx->cur_inode_mode)) {
3951                 ret = send_truncate(sctx, sctx->cur_ino, sctx->cur_inode_gen,
3952                                 sctx->cur_inode_size);
3953                 if (ret < 0)
3954                         goto out;
3955         }
3956
3957         if (need_chown) {
3958                 ret = send_chown(sctx, sctx->cur_ino, sctx->cur_inode_gen,
3959                                 left_uid, left_gid);
3960                 if (ret < 0)
3961                         goto out;
3962         }
3963         if (need_chmod) {
3964                 ret = send_chmod(sctx, sctx->cur_ino, sctx->cur_inode_gen,
3965                                 left_mode);
3966                 if (ret < 0)
3967                         goto out;
3968         }
3969
3970         /*
3971          * Need to send that every time, no matter if it actually changed
3972          * between the two trees as we have done changes to the inode before.
3973          */
3974         ret = send_utimes(sctx, sctx->cur_ino, sctx->cur_inode_gen);
3975         if (ret < 0)
3976                 goto out;
3977
3978 out:
3979         return ret;
3980 }
3981
3982 static int changed_inode(struct send_ctx *sctx,
3983                          enum btrfs_compare_tree_result result)
3984 {
3985         int ret = 0;
3986         struct btrfs_key *key = sctx->cmp_key;
3987         struct btrfs_inode_item *left_ii = NULL;
3988         struct btrfs_inode_item *right_ii = NULL;
3989         u64 left_gen = 0;
3990         u64 right_gen = 0;
3991
3992         ret = close_cur_inode_file(sctx);
3993         if (ret < 0)
3994                 goto out;
3995
3996         sctx->cur_ino = key->objectid;
3997         sctx->cur_inode_new_gen = 0;
3998         sctx->send_progress = sctx->cur_ino;
3999
4000         if (result == BTRFS_COMPARE_TREE_NEW ||
4001             result == BTRFS_COMPARE_TREE_CHANGED) {
4002                 left_ii = btrfs_item_ptr(sctx->left_path->nodes[0],
4003                                 sctx->left_path->slots[0],
4004                                 struct btrfs_inode_item);
4005                 left_gen = btrfs_inode_generation(sctx->left_path->nodes[0],
4006                                 left_ii);
4007         } else {
4008                 right_ii = btrfs_item_ptr(sctx->right_path->nodes[0],
4009                                 sctx->right_path->slots[0],
4010                                 struct btrfs_inode_item);
4011                 right_gen = btrfs_inode_generation(sctx->right_path->nodes[0],
4012                                 right_ii);
4013         }
4014         if (result == BTRFS_COMPARE_TREE_CHANGED) {
4015                 right_ii = btrfs_item_ptr(sctx->right_path->nodes[0],
4016                                 sctx->right_path->slots[0],
4017                                 struct btrfs_inode_item);
4018
4019                 right_gen = btrfs_inode_generation(sctx->right_path->nodes[0],
4020                                 right_ii);
4021                 if (left_gen != right_gen)
4022                         sctx->cur_inode_new_gen = 1;
4023         }
4024
4025         if (result == BTRFS_COMPARE_TREE_NEW) {
4026                 sctx->cur_inode_gen = left_gen;
4027                 sctx->cur_inode_new = 1;
4028                 sctx->cur_inode_deleted = 0;
4029                 sctx->cur_inode_size = btrfs_inode_size(
4030                                 sctx->left_path->nodes[0], left_ii);
4031                 sctx->cur_inode_mode = btrfs_inode_mode(
4032                                 sctx->left_path->nodes[0], left_ii);
4033                 if (sctx->cur_ino != BTRFS_FIRST_FREE_OBJECTID)
4034                         ret = send_create_inode_if_needed(sctx);
4035         } else if (result == BTRFS_COMPARE_TREE_DELETED) {
4036                 sctx->cur_inode_gen = right_gen;
4037                 sctx->cur_inode_new = 0;
4038                 sctx->cur_inode_deleted = 1;
4039                 sctx->cur_inode_size = btrfs_inode_size(
4040                                 sctx->right_path->nodes[0], right_ii);
4041                 sctx->cur_inode_mode = btrfs_inode_mode(
4042                                 sctx->right_path->nodes[0], right_ii);
4043         } else if (result == BTRFS_COMPARE_TREE_CHANGED) {
4044                 if (sctx->cur_inode_new_gen) {
4045                         sctx->cur_inode_gen = right_gen;
4046                         sctx->cur_inode_new = 0;
4047                         sctx->cur_inode_deleted = 1;
4048                         sctx->cur_inode_size = btrfs_inode_size(
4049                                         sctx->right_path->nodes[0], right_ii);
4050                         sctx->cur_inode_mode = btrfs_inode_mode(
4051                                         sctx->right_path->nodes[0], right_ii);
4052                         ret = process_all_refs(sctx,
4053                                         BTRFS_COMPARE_TREE_DELETED);
4054                         if (ret < 0)
4055                                 goto out;
4056
4057                         sctx->cur_inode_gen = left_gen;
4058                         sctx->cur_inode_new = 1;
4059                         sctx->cur_inode_deleted = 0;
4060                         sctx->cur_inode_size = btrfs_inode_size(
4061                                         sctx->left_path->nodes[0], left_ii);
4062                         sctx->cur_inode_mode = btrfs_inode_mode(
4063                                         sctx->left_path->nodes[0], left_ii);
4064                         ret = send_create_inode_if_needed(sctx);
4065                         if (ret < 0)
4066                                 goto out;
4067
4068                         ret = process_all_refs(sctx, BTRFS_COMPARE_TREE_NEW);
4069                         if (ret < 0)
4070                                 goto out;
4071                         ret = process_all_extents(sctx);
4072                         if (ret < 0)
4073                                 goto out;
4074                         ret = process_all_new_xattrs(sctx);
4075                         if (ret < 0)
4076                                 goto out;
4077                 } else {
4078                         sctx->cur_inode_gen = left_gen;
4079                         sctx->cur_inode_new = 0;
4080                         sctx->cur_inode_new_gen = 0;
4081                         sctx->cur_inode_deleted = 0;
4082                         sctx->cur_inode_size = btrfs_inode_size(
4083                                         sctx->left_path->nodes[0], left_ii);
4084                         sctx->cur_inode_mode = btrfs_inode_mode(
4085                                         sctx->left_path->nodes[0], left_ii);
4086                 }
4087         }
4088
4089 out:
4090         return ret;
4091 }
4092
4093 static int changed_ref(struct send_ctx *sctx,
4094                        enum btrfs_compare_tree_result result)
4095 {
4096         int ret = 0;
4097
4098         BUG_ON(sctx->cur_ino != sctx->cmp_key->objectid);
4099
4100         if (!sctx->cur_inode_new_gen &&
4101             sctx->cur_ino != BTRFS_FIRST_FREE_OBJECTID) {
4102                 if (result == BTRFS_COMPARE_TREE_NEW)
4103                         ret = record_new_ref(sctx);
4104                 else if (result == BTRFS_COMPARE_TREE_DELETED)
4105                         ret = record_deleted_ref(sctx);
4106                 else if (result == BTRFS_COMPARE_TREE_CHANGED)
4107                         ret = record_changed_ref(sctx);
4108         }
4109
4110         return ret;
4111 }
4112
4113 static int changed_xattr(struct send_ctx *sctx,
4114                          enum btrfs_compare_tree_result result)
4115 {
4116         int ret = 0;
4117
4118         BUG_ON(sctx->cur_ino != sctx->cmp_key->objectid);
4119
4120         if (!sctx->cur_inode_new_gen && !sctx->cur_inode_deleted) {
4121                 if (result == BTRFS_COMPARE_TREE_NEW)
4122                         ret = process_new_xattr(sctx);
4123                 else if (result == BTRFS_COMPARE_TREE_DELETED)
4124                         ret = process_deleted_xattr(sctx);
4125                 else if (result == BTRFS_COMPARE_TREE_CHANGED)
4126                         ret = process_changed_xattr(sctx);
4127         }
4128
4129         return ret;
4130 }
4131
4132 static int changed_extent(struct send_ctx *sctx,
4133                           enum btrfs_compare_tree_result result)
4134 {
4135         int ret = 0;
4136
4137         BUG_ON(sctx->cur_ino != sctx->cmp_key->objectid);
4138
4139         if (!sctx->cur_inode_new_gen && !sctx->cur_inode_deleted) {
4140                 if (result != BTRFS_COMPARE_TREE_DELETED)
4141                         ret = process_extent(sctx, sctx->left_path,
4142                                         sctx->cmp_key);
4143         }
4144
4145         return ret;
4146 }
4147
4148
4149 static int changed_cb(struct btrfs_root *left_root,
4150                       struct btrfs_root *right_root,
4151                       struct btrfs_path *left_path,
4152                       struct btrfs_path *right_path,
4153                       struct btrfs_key *key,
4154                       enum btrfs_compare_tree_result result,
4155                       void *ctx)
4156 {
4157         int ret = 0;
4158         struct send_ctx *sctx = ctx;
4159
4160         sctx->left_path = left_path;
4161         sctx->right_path = right_path;
4162         sctx->cmp_key = key;
4163
4164         ret = finish_inode_if_needed(sctx, 0);
4165         if (ret < 0)
4166                 goto out;
4167
4168         if (key->type == BTRFS_INODE_ITEM_KEY)
4169                 ret = changed_inode(sctx, result);
4170         else if (key->type == BTRFS_INODE_REF_KEY)
4171                 ret = changed_ref(sctx, result);
4172         else if (key->type == BTRFS_XATTR_ITEM_KEY)
4173                 ret = changed_xattr(sctx, result);
4174         else if (key->type == BTRFS_EXTENT_DATA_KEY)
4175                 ret = changed_extent(sctx, result);
4176
4177 out:
4178         return ret;
4179 }
4180
4181 static int full_send_tree(struct send_ctx *sctx)
4182 {
4183         int ret;
4184         struct btrfs_trans_handle *trans = NULL;
4185         struct btrfs_root *send_root = sctx->send_root;
4186         struct btrfs_key key;
4187         struct btrfs_key found_key;
4188         struct btrfs_path *path;
4189         struct extent_buffer *eb;
4190         int slot;
4191         u64 start_ctransid;
4192         u64 ctransid;
4193
4194         path = alloc_path_for_send();
4195         if (!path)
4196                 return -ENOMEM;
4197
4198         spin_lock(&send_root->root_times_lock);
4199         start_ctransid = btrfs_root_ctransid(&send_root->root_item);
4200         spin_unlock(&send_root->root_times_lock);
4201
4202         key.objectid = BTRFS_FIRST_FREE_OBJECTID;
4203         key.type = BTRFS_INODE_ITEM_KEY;
4204         key.offset = 0;
4205
4206 join_trans:
4207         /*
4208          * We need to make sure the transaction does not get committed
4209          * while we do anything on commit roots. Join a transaction to prevent
4210          * this.
4211          */
4212         trans = btrfs_join_transaction(send_root);
4213         if (IS_ERR(trans)) {
4214                 ret = PTR_ERR(trans);
4215                 trans = NULL;
4216                 goto out;
4217         }
4218
4219         /*
4220          * Make sure the tree has not changed
4221          */
4222         spin_lock(&send_root->root_times_lock);
4223         ctransid = btrfs_root_ctransid(&send_root->root_item);
4224         spin_unlock(&send_root->root_times_lock);
4225
4226         if (ctransid != start_ctransid) {
4227                 WARN(1, KERN_WARNING "btrfs: the root that you're trying to "
4228                                      "send was modified in between. This is "
4229                                      "probably a bug.\n");
4230                 ret = -EIO;
4231                 goto out;
4232         }
4233
4234         ret = btrfs_search_slot_for_read(send_root, &key, path, 1, 0);
4235         if (ret < 0)
4236                 goto out;
4237         if (ret)
4238                 goto out_finish;
4239
4240         while (1) {
4241                 /*
4242                  * When someone want to commit while we iterate, end the
4243                  * joined transaction and rejoin.
4244                  */
4245                 if (btrfs_should_end_transaction(trans, send_root)) {
4246                         ret = btrfs_end_transaction(trans, send_root);
4247                         trans = NULL;
4248                         if (ret < 0)
4249                                 goto out;
4250                         btrfs_release_path(path);
4251                         goto join_trans;
4252                 }
4253
4254                 eb = path->nodes[0];
4255                 slot = path->slots[0];
4256                 btrfs_item_key_to_cpu(eb, &found_key, slot);
4257
4258                 ret = changed_cb(send_root, NULL, path, NULL,
4259                                 &found_key, BTRFS_COMPARE_TREE_NEW, sctx);
4260                 if (ret < 0)
4261                         goto out;
4262
4263                 key.objectid = found_key.objectid;
4264                 key.type = found_key.type;
4265                 key.offset = found_key.offset + 1;
4266
4267                 ret = btrfs_next_item(send_root, path);
4268                 if (ret < 0)
4269                         goto out;
4270                 if (ret) {
4271                         ret  = 0;
4272                         break;
4273                 }
4274         }
4275
4276 out_finish:
4277         ret = finish_inode_if_needed(sctx, 1);
4278
4279 out:
4280         btrfs_free_path(path);
4281         if (trans) {
4282                 if (!ret)
4283                         ret = btrfs_end_transaction(trans, send_root);
4284                 else
4285                         btrfs_end_transaction(trans, send_root);
4286         }
4287         return ret;
4288 }
4289
4290 static int send_subvol(struct send_ctx *sctx)
4291 {
4292         int ret;
4293
4294         ret = send_header(sctx);
4295         if (ret < 0)
4296                 goto out;
4297
4298         ret = send_subvol_begin(sctx);
4299         if (ret < 0)
4300                 goto out;
4301
4302         if (sctx->parent_root) {
4303                 ret = btrfs_compare_trees(sctx->send_root, sctx->parent_root,
4304                                 changed_cb, sctx);
4305                 if (ret < 0)
4306                         goto out;
4307                 ret = finish_inode_if_needed(sctx, 1);
4308                 if (ret < 0)
4309                         goto out;
4310         } else {
4311                 ret = full_send_tree(sctx);
4312                 if (ret < 0)
4313                         goto out;
4314         }
4315
4316 out:
4317         if (!ret)
4318                 ret = close_cur_inode_file(sctx);
4319         else
4320                 close_cur_inode_file(sctx);
4321
4322         free_recorded_refs(sctx);
4323         return ret;
4324 }
4325
4326 long btrfs_ioctl_send(struct file *mnt_file, void __user *arg_)
4327 {
4328         int ret = 0;
4329         struct btrfs_root *send_root;
4330         struct btrfs_root *clone_root;
4331         struct btrfs_fs_info *fs_info;
4332         struct btrfs_ioctl_send_args *arg = NULL;
4333         struct btrfs_key key;
4334         struct file *filp = NULL;
4335         struct send_ctx *sctx = NULL;
4336         u32 i;
4337         u64 *clone_sources_tmp = NULL;
4338
4339         if (!capable(CAP_SYS_ADMIN))
4340                 return -EPERM;
4341
4342         send_root = BTRFS_I(fdentry(mnt_file)->d_inode)->root;
4343         fs_info = send_root->fs_info;
4344
4345         arg = memdup_user(arg_, sizeof(*arg));
4346         if (IS_ERR(arg)) {
4347                 ret = PTR_ERR(arg);
4348                 arg = NULL;
4349                 goto out;
4350         }
4351
4352         if (!access_ok(VERIFY_READ, arg->clone_sources,
4353                         sizeof(*arg->clone_sources *
4354                         arg->clone_sources_count))) {
4355                 ret = -EFAULT;
4356                 goto out;
4357         }
4358
4359         sctx = kzalloc(sizeof(struct send_ctx), GFP_NOFS);
4360         if (!sctx) {
4361                 ret = -ENOMEM;
4362                 goto out;
4363         }
4364
4365         INIT_LIST_HEAD(&sctx->new_refs);
4366         INIT_LIST_HEAD(&sctx->deleted_refs);
4367         INIT_RADIX_TREE(&sctx->name_cache, GFP_NOFS);
4368         INIT_LIST_HEAD(&sctx->name_cache_list);
4369
4370         sctx->send_filp = fget(arg->send_fd);
4371         if (IS_ERR(sctx->send_filp)) {
4372                 ret = PTR_ERR(sctx->send_filp);
4373                 goto out;
4374         }
4375
4376         sctx->mnt = mnt_file->f_path.mnt;
4377
4378         sctx->send_root = send_root;
4379         sctx->clone_roots_cnt = arg->clone_sources_count;
4380
4381         sctx->send_max_size = BTRFS_SEND_BUF_SIZE;
4382         sctx->send_buf = vmalloc(sctx->send_max_size);
4383         if (!sctx->send_buf) {
4384                 ret = -ENOMEM;
4385                 goto out;
4386         }
4387
4388         sctx->read_buf = vmalloc(BTRFS_SEND_READ_SIZE);
4389         if (!sctx->read_buf) {
4390                 ret = -ENOMEM;
4391                 goto out;
4392         }
4393
4394         sctx->clone_roots = vzalloc(sizeof(struct clone_root) *
4395                         (arg->clone_sources_count + 1));
4396         if (!sctx->clone_roots) {
4397                 ret = -ENOMEM;
4398                 goto out;
4399         }
4400
4401         if (arg->clone_sources_count) {
4402                 clone_sources_tmp = vmalloc(arg->clone_sources_count *
4403                                 sizeof(*arg->clone_sources));
4404                 if (!clone_sources_tmp) {
4405                         ret = -ENOMEM;
4406                         goto out;
4407                 }
4408
4409                 ret = copy_from_user(clone_sources_tmp, arg->clone_sources,
4410                                 arg->clone_sources_count *
4411                                 sizeof(*arg->clone_sources));
4412                 if (ret) {
4413                         ret = -EFAULT;
4414                         goto out;
4415                 }
4416
4417                 for (i = 0; i < arg->clone_sources_count; i++) {
4418                         key.objectid = clone_sources_tmp[i];
4419                         key.type = BTRFS_ROOT_ITEM_KEY;
4420                         key.offset = (u64)-1;
4421                         clone_root = btrfs_read_fs_root_no_name(fs_info, &key);
4422                         if (!clone_root) {
4423                                 ret = -EINVAL;
4424                                 goto out;
4425                         }
4426                         if (IS_ERR(clone_root)) {
4427                                 ret = PTR_ERR(clone_root);
4428                                 goto out;
4429                         }
4430                         sctx->clone_roots[i].root = clone_root;
4431                 }
4432                 vfree(clone_sources_tmp);
4433                 clone_sources_tmp = NULL;
4434         }
4435
4436         if (arg->parent_root) {
4437                 key.objectid = arg->parent_root;
4438                 key.type = BTRFS_ROOT_ITEM_KEY;
4439                 key.offset = (u64)-1;
4440                 sctx->parent_root = btrfs_read_fs_root_no_name(fs_info, &key);
4441                 if (!sctx->parent_root) {
4442                         ret = -EINVAL;
4443                         goto out;
4444                 }
4445         }
4446
4447         /*
4448          * Clones from send_root are allowed, but only if the clone source
4449          * is behind the current send position. This is checked while searching
4450          * for possible clone sources.
4451          */
4452         sctx->clone_roots[sctx->clone_roots_cnt++].root = sctx->send_root;
4453
4454         /* We do a bsearch later */
4455         sort(sctx->clone_roots, sctx->clone_roots_cnt,
4456                         sizeof(*sctx->clone_roots), __clone_root_cmp_sort,
4457                         NULL);
4458
4459         ret = send_subvol(sctx);
4460         if (ret < 0)
4461                 goto out;
4462
4463         ret = begin_cmd(sctx, BTRFS_SEND_C_END);
4464         if (ret < 0)
4465                 goto out;
4466         ret = send_cmd(sctx);
4467         if (ret < 0)
4468                 goto out;
4469
4470 out:
4471         if (filp)
4472                 fput(filp);
4473         kfree(arg);
4474         vfree(clone_sources_tmp);
4475
4476         if (sctx) {
4477                 if (sctx->send_filp)
4478                         fput(sctx->send_filp);
4479
4480                 vfree(sctx->clone_roots);
4481                 vfree(sctx->send_buf);
4482                 vfree(sctx->read_buf);
4483
4484                 name_cache_free(sctx);
4485
4486                 kfree(sctx);
4487         }
4488
4489         return ret;
4490 }