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