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