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