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