]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/cddl/contrib/opensolaris/uts/common/fs/zfs/dmu_send.c
MFC r297509: MFV r297506: 6738 zfs send stream padding needs documentation
[FreeBSD/stable/10.git] / sys / cddl / contrib / opensolaris / uts / common / fs / zfs / dmu_send.c
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23  * Copyright 2011 Nexenta Systems, Inc. All rights reserved.
24  * Copyright (c) 2011, 2015 by Delphix. All rights reserved.
25  * Copyright (c) 2014, Joyent, Inc. All rights reserved.
26  * Copyright (c) 2012, Martin Matuska <mm@FreeBSD.org>. All rights reserved.
27  * Copyright 2014 HybridCluster. All rights reserved.
28  * Copyright 2016 RackTop Systems.
29  * Copyright (c) 2014 Integros [integros.com]
30  */
31
32 #include <sys/dmu.h>
33 #include <sys/dmu_impl.h>
34 #include <sys/dmu_tx.h>
35 #include <sys/dbuf.h>
36 #include <sys/dnode.h>
37 #include <sys/zfs_context.h>
38 #include <sys/dmu_objset.h>
39 #include <sys/dmu_traverse.h>
40 #include <sys/dsl_dataset.h>
41 #include <sys/dsl_dir.h>
42 #include <sys/dsl_prop.h>
43 #include <sys/dsl_pool.h>
44 #include <sys/dsl_synctask.h>
45 #include <sys/zfs_ioctl.h>
46 #include <sys/zap.h>
47 #include <sys/zio_checksum.h>
48 #include <sys/zfs_znode.h>
49 #include <zfs_fletcher.h>
50 #include <sys/avl.h>
51 #include <sys/ddt.h>
52 #include <sys/zfs_onexit.h>
53 #include <sys/dmu_send.h>
54 #include <sys/dsl_destroy.h>
55 #include <sys/blkptr.h>
56 #include <sys/dsl_bookmark.h>
57 #include <sys/zfeature.h>
58 #include <sys/bqueue.h>
59
60 #ifdef __FreeBSD__
61 #undef dump_write
62 #define dump_write dmu_dump_write
63 #endif
64
65 /* Set this tunable to TRUE to replace corrupt data with 0x2f5baddb10c */
66 int zfs_send_corrupt_data = B_FALSE;
67 int zfs_send_queue_length = 16 * 1024 * 1024;
68 int zfs_recv_queue_length = 16 * 1024 * 1024;
69 /* Set this tunable to FALSE to disable setting of DRR_FLAG_FREERECORDS */
70 int zfs_send_set_freerecords_bit = B_TRUE;
71
72 #ifdef _KERNEL
73 TUNABLE_INT("vfs.zfs.send_set_freerecords_bit", &zfs_send_set_freerecords_bit);
74 #endif
75
76 static char *dmu_recv_tag = "dmu_recv_tag";
77 const char *recv_clone_name = "%recv";
78
79 #define BP_SPAN(datablkszsec, indblkshift, level) \
80         (((uint64_t)datablkszsec) << (SPA_MINBLOCKSHIFT + \
81         (level) * (indblkshift - SPA_BLKPTRSHIFT)))
82
83 static void byteswap_record(dmu_replay_record_t *drr);
84
85 struct send_thread_arg {
86         bqueue_t        q;
87         dsl_dataset_t   *ds;            /* Dataset to traverse */
88         uint64_t        fromtxg;        /* Traverse from this txg */
89         int             flags;          /* flags to pass to traverse_dataset */
90         int             error_code;
91         boolean_t       cancel;
92         zbookmark_phys_t resume;
93 };
94
95 struct send_block_record {
96         boolean_t               eos_marker; /* Marks the end of the stream */
97         blkptr_t                bp;
98         zbookmark_phys_t        zb;
99         uint8_t                 indblkshift;
100         uint16_t                datablkszsec;
101         bqueue_node_t           ln;
102 };
103
104 static int
105 dump_bytes(dmu_sendarg_t *dsp, void *buf, int len)
106 {
107         dsl_dataset_t *ds = dmu_objset_ds(dsp->dsa_os);
108         struct uio auio;
109         struct iovec aiov;
110
111         /*
112          * The code does not rely on this (len being a multiple of 8).  We keep
113          * this assertion because of the corresponding assertion in
114          * receive_read().  Keeping this assertion ensures that we do not
115          * inadvertently break backwards compatibility (causing the assertion
116          * in receive_read() to trigger on old software).
117          *
118          * Removing the assertions could be rolled into a new feature that uses
119          * data that isn't 8-byte aligned; if the assertions were removed, a
120          * feature flag would have to be added.
121          */
122
123         ASSERT0(len % 8);
124
125         aiov.iov_base = buf;
126         aiov.iov_len = len;
127         auio.uio_iov = &aiov;
128         auio.uio_iovcnt = 1;
129         auio.uio_resid = len;
130         auio.uio_segflg = UIO_SYSSPACE;
131         auio.uio_rw = UIO_WRITE;
132         auio.uio_offset = (off_t)-1;
133         auio.uio_td = dsp->dsa_td;
134 #ifdef _KERNEL
135         if (dsp->dsa_fp->f_type == DTYPE_VNODE)
136                 bwillwrite();
137         dsp->dsa_err = fo_write(dsp->dsa_fp, &auio, dsp->dsa_td->td_ucred, 0,
138             dsp->dsa_td);
139 #else
140         fprintf(stderr, "%s: returning EOPNOTSUPP\n", __func__);
141         dsp->dsa_err = EOPNOTSUPP;
142 #endif
143         mutex_enter(&ds->ds_sendstream_lock);
144         *dsp->dsa_off += len;
145         mutex_exit(&ds->ds_sendstream_lock);
146
147         return (dsp->dsa_err);
148 }
149
150 /*
151  * For all record types except BEGIN, fill in the checksum (overlaid in
152  * drr_u.drr_checksum.drr_checksum).  The checksum verifies everything
153  * up to the start of the checksum itself.
154  */
155 static int
156 dump_record(dmu_sendarg_t *dsp, void *payload, int payload_len)
157 {
158         ASSERT3U(offsetof(dmu_replay_record_t, drr_u.drr_checksum.drr_checksum),
159             ==, sizeof (dmu_replay_record_t) - sizeof (zio_cksum_t));
160         fletcher_4_incremental_native(dsp->dsa_drr,
161             offsetof(dmu_replay_record_t, drr_u.drr_checksum.drr_checksum),
162             &dsp->dsa_zc);
163         if (dsp->dsa_drr->drr_type != DRR_BEGIN) {
164                 ASSERT(ZIO_CHECKSUM_IS_ZERO(&dsp->dsa_drr->drr_u.
165                     drr_checksum.drr_checksum));
166                 dsp->dsa_drr->drr_u.drr_checksum.drr_checksum = dsp->dsa_zc;
167         }
168         fletcher_4_incremental_native(&dsp->dsa_drr->
169             drr_u.drr_checksum.drr_checksum,
170             sizeof (zio_cksum_t), &dsp->dsa_zc);
171         if (dump_bytes(dsp, dsp->dsa_drr, sizeof (dmu_replay_record_t)) != 0)
172                 return (SET_ERROR(EINTR));
173         if (payload_len != 0) {
174                 fletcher_4_incremental_native(payload, payload_len,
175                     &dsp->dsa_zc);
176                 if (dump_bytes(dsp, payload, payload_len) != 0)
177                         return (SET_ERROR(EINTR));
178         }
179         return (0);
180 }
181
182 /*
183  * Fill in the drr_free struct, or perform aggregation if the previous record is
184  * also a free record, and the two are adjacent.
185  *
186  * Note that we send free records even for a full send, because we want to be
187  * able to receive a full send as a clone, which requires a list of all the free
188  * and freeobject records that were generated on the source.
189  */
190 static int
191 dump_free(dmu_sendarg_t *dsp, uint64_t object, uint64_t offset,
192     uint64_t length)
193 {
194         struct drr_free *drrf = &(dsp->dsa_drr->drr_u.drr_free);
195
196         /*
197          * When we receive a free record, dbuf_free_range() assumes
198          * that the receiving system doesn't have any dbufs in the range
199          * being freed.  This is always true because there is a one-record
200          * constraint: we only send one WRITE record for any given
201          * object,offset.  We know that the one-record constraint is
202          * true because we always send data in increasing order by
203          * object,offset.
204          *
205          * If the increasing-order constraint ever changes, we should find
206          * another way to assert that the one-record constraint is still
207          * satisfied.
208          */
209         ASSERT(object > dsp->dsa_last_data_object ||
210             (object == dsp->dsa_last_data_object &&
211             offset > dsp->dsa_last_data_offset));
212
213         if (length != -1ULL && offset + length < offset)
214                 length = -1ULL;
215
216         /*
217          * If there is a pending op, but it's not PENDING_FREE, push it out,
218          * since free block aggregation can only be done for blocks of the
219          * same type (i.e., DRR_FREE records can only be aggregated with
220          * other DRR_FREE records.  DRR_FREEOBJECTS records can only be
221          * aggregated with other DRR_FREEOBJECTS records.
222          */
223         if (dsp->dsa_pending_op != PENDING_NONE &&
224             dsp->dsa_pending_op != PENDING_FREE) {
225                 if (dump_record(dsp, NULL, 0) != 0)
226                         return (SET_ERROR(EINTR));
227                 dsp->dsa_pending_op = PENDING_NONE;
228         }
229
230         if (dsp->dsa_pending_op == PENDING_FREE) {
231                 /*
232                  * There should never be a PENDING_FREE if length is -1
233                  * (because dump_dnode is the only place where this
234                  * function is called with a -1, and only after flushing
235                  * any pending record).
236                  */
237                 ASSERT(length != -1ULL);
238                 /*
239                  * Check to see whether this free block can be aggregated
240                  * with pending one.
241                  */
242                 if (drrf->drr_object == object && drrf->drr_offset +
243                     drrf->drr_length == offset) {
244                         drrf->drr_length += length;
245                         return (0);
246                 } else {
247                         /* not a continuation.  Push out pending record */
248                         if (dump_record(dsp, NULL, 0) != 0)
249                                 return (SET_ERROR(EINTR));
250                         dsp->dsa_pending_op = PENDING_NONE;
251                 }
252         }
253         /* create a FREE record and make it pending */
254         bzero(dsp->dsa_drr, sizeof (dmu_replay_record_t));
255         dsp->dsa_drr->drr_type = DRR_FREE;
256         drrf->drr_object = object;
257         drrf->drr_offset = offset;
258         drrf->drr_length = length;
259         drrf->drr_toguid = dsp->dsa_toguid;
260         if (length == -1ULL) {
261                 if (dump_record(dsp, NULL, 0) != 0)
262                         return (SET_ERROR(EINTR));
263         } else {
264                 dsp->dsa_pending_op = PENDING_FREE;
265         }
266
267         return (0);
268 }
269
270 static int
271 dump_write(dmu_sendarg_t *dsp, dmu_object_type_t type,
272     uint64_t object, uint64_t offset, int blksz, const blkptr_t *bp, void *data)
273 {
274         struct drr_write *drrw = &(dsp->dsa_drr->drr_u.drr_write);
275
276         /*
277          * We send data in increasing object, offset order.
278          * See comment in dump_free() for details.
279          */
280         ASSERT(object > dsp->dsa_last_data_object ||
281             (object == dsp->dsa_last_data_object &&
282             offset > dsp->dsa_last_data_offset));
283         dsp->dsa_last_data_object = object;
284         dsp->dsa_last_data_offset = offset + blksz - 1;
285
286         /*
287          * If there is any kind of pending aggregation (currently either
288          * a grouping of free objects or free blocks), push it out to
289          * the stream, since aggregation can't be done across operations
290          * of different types.
291          */
292         if (dsp->dsa_pending_op != PENDING_NONE) {
293                 if (dump_record(dsp, NULL, 0) != 0)
294                         return (SET_ERROR(EINTR));
295                 dsp->dsa_pending_op = PENDING_NONE;
296         }
297         /* write a WRITE record */
298         bzero(dsp->dsa_drr, sizeof (dmu_replay_record_t));
299         dsp->dsa_drr->drr_type = DRR_WRITE;
300         drrw->drr_object = object;
301         drrw->drr_type = type;
302         drrw->drr_offset = offset;
303         drrw->drr_length = blksz;
304         drrw->drr_toguid = dsp->dsa_toguid;
305         if (bp == NULL || BP_IS_EMBEDDED(bp)) {
306                 /*
307                  * There's no pre-computed checksum for partial-block
308                  * writes or embedded BP's, so (like
309                  * fletcher4-checkummed blocks) userland will have to
310                  * compute a dedup-capable checksum itself.
311                  */
312                 drrw->drr_checksumtype = ZIO_CHECKSUM_OFF;
313         } else {
314                 drrw->drr_checksumtype = BP_GET_CHECKSUM(bp);
315                 if (zio_checksum_table[drrw->drr_checksumtype].ci_flags &
316                     ZCHECKSUM_FLAG_DEDUP)
317                         drrw->drr_checksumflags |= DRR_CHECKSUM_DEDUP;
318                 DDK_SET_LSIZE(&drrw->drr_key, BP_GET_LSIZE(bp));
319                 DDK_SET_PSIZE(&drrw->drr_key, BP_GET_PSIZE(bp));
320                 DDK_SET_COMPRESS(&drrw->drr_key, BP_GET_COMPRESS(bp));
321                 drrw->drr_key.ddk_cksum = bp->blk_cksum;
322         }
323
324         if (dump_record(dsp, data, blksz) != 0)
325                 return (SET_ERROR(EINTR));
326         return (0);
327 }
328
329 static int
330 dump_write_embedded(dmu_sendarg_t *dsp, uint64_t object, uint64_t offset,
331     int blksz, const blkptr_t *bp)
332 {
333         char buf[BPE_PAYLOAD_SIZE];
334         struct drr_write_embedded *drrw =
335             &(dsp->dsa_drr->drr_u.drr_write_embedded);
336
337         if (dsp->dsa_pending_op != PENDING_NONE) {
338                 if (dump_record(dsp, NULL, 0) != 0)
339                         return (EINTR);
340                 dsp->dsa_pending_op = PENDING_NONE;
341         }
342
343         ASSERT(BP_IS_EMBEDDED(bp));
344
345         bzero(dsp->dsa_drr, sizeof (dmu_replay_record_t));
346         dsp->dsa_drr->drr_type = DRR_WRITE_EMBEDDED;
347         drrw->drr_object = object;
348         drrw->drr_offset = offset;
349         drrw->drr_length = blksz;
350         drrw->drr_toguid = dsp->dsa_toguid;
351         drrw->drr_compression = BP_GET_COMPRESS(bp);
352         drrw->drr_etype = BPE_GET_ETYPE(bp);
353         drrw->drr_lsize = BPE_GET_LSIZE(bp);
354         drrw->drr_psize = BPE_GET_PSIZE(bp);
355
356         decode_embedded_bp_compressed(bp, buf);
357
358         if (dump_record(dsp, buf, P2ROUNDUP(drrw->drr_psize, 8)) != 0)
359                 return (EINTR);
360         return (0);
361 }
362
363 static int
364 dump_spill(dmu_sendarg_t *dsp, uint64_t object, int blksz, void *data)
365 {
366         struct drr_spill *drrs = &(dsp->dsa_drr->drr_u.drr_spill);
367
368         if (dsp->dsa_pending_op != PENDING_NONE) {
369                 if (dump_record(dsp, NULL, 0) != 0)
370                         return (SET_ERROR(EINTR));
371                 dsp->dsa_pending_op = PENDING_NONE;
372         }
373
374         /* write a SPILL record */
375         bzero(dsp->dsa_drr, sizeof (dmu_replay_record_t));
376         dsp->dsa_drr->drr_type = DRR_SPILL;
377         drrs->drr_object = object;
378         drrs->drr_length = blksz;
379         drrs->drr_toguid = dsp->dsa_toguid;
380
381         if (dump_record(dsp, data, blksz) != 0)
382                 return (SET_ERROR(EINTR));
383         return (0);
384 }
385
386 static int
387 dump_freeobjects(dmu_sendarg_t *dsp, uint64_t firstobj, uint64_t numobjs)
388 {
389         struct drr_freeobjects *drrfo = &(dsp->dsa_drr->drr_u.drr_freeobjects);
390
391         /*
392          * If there is a pending op, but it's not PENDING_FREEOBJECTS,
393          * push it out, since free block aggregation can only be done for
394          * blocks of the same type (i.e., DRR_FREE records can only be
395          * aggregated with other DRR_FREE records.  DRR_FREEOBJECTS records
396          * can only be aggregated with other DRR_FREEOBJECTS records.
397          */
398         if (dsp->dsa_pending_op != PENDING_NONE &&
399             dsp->dsa_pending_op != PENDING_FREEOBJECTS) {
400                 if (dump_record(dsp, NULL, 0) != 0)
401                         return (SET_ERROR(EINTR));
402                 dsp->dsa_pending_op = PENDING_NONE;
403         }
404         if (dsp->dsa_pending_op == PENDING_FREEOBJECTS) {
405                 /*
406                  * See whether this free object array can be aggregated
407                  * with pending one
408                  */
409                 if (drrfo->drr_firstobj + drrfo->drr_numobjs == firstobj) {
410                         drrfo->drr_numobjs += numobjs;
411                         return (0);
412                 } else {
413                         /* can't be aggregated.  Push out pending record */
414                         if (dump_record(dsp, NULL, 0) != 0)
415                                 return (SET_ERROR(EINTR));
416                         dsp->dsa_pending_op = PENDING_NONE;
417                 }
418         }
419
420         /* write a FREEOBJECTS record */
421         bzero(dsp->dsa_drr, sizeof (dmu_replay_record_t));
422         dsp->dsa_drr->drr_type = DRR_FREEOBJECTS;
423         drrfo->drr_firstobj = firstobj;
424         drrfo->drr_numobjs = numobjs;
425         drrfo->drr_toguid = dsp->dsa_toguid;
426
427         dsp->dsa_pending_op = PENDING_FREEOBJECTS;
428
429         return (0);
430 }
431
432 static int
433 dump_dnode(dmu_sendarg_t *dsp, uint64_t object, dnode_phys_t *dnp)
434 {
435         struct drr_object *drro = &(dsp->dsa_drr->drr_u.drr_object);
436
437         if (object < dsp->dsa_resume_object) {
438                 /*
439                  * Note: when resuming, we will visit all the dnodes in
440                  * the block of dnodes that we are resuming from.  In
441                  * this case it's unnecessary to send the dnodes prior to
442                  * the one we are resuming from.  We should be at most one
443                  * block's worth of dnodes behind the resume point.
444                  */
445                 ASSERT3U(dsp->dsa_resume_object - object, <,
446                     1 << (DNODE_BLOCK_SHIFT - DNODE_SHIFT));
447                 return (0);
448         }
449
450         if (dnp == NULL || dnp->dn_type == DMU_OT_NONE)
451                 return (dump_freeobjects(dsp, object, 1));
452
453         if (dsp->dsa_pending_op != PENDING_NONE) {
454                 if (dump_record(dsp, NULL, 0) != 0)
455                         return (SET_ERROR(EINTR));
456                 dsp->dsa_pending_op = PENDING_NONE;
457         }
458
459         /* write an OBJECT record */
460         bzero(dsp->dsa_drr, sizeof (dmu_replay_record_t));
461         dsp->dsa_drr->drr_type = DRR_OBJECT;
462         drro->drr_object = object;
463         drro->drr_type = dnp->dn_type;
464         drro->drr_bonustype = dnp->dn_bonustype;
465         drro->drr_blksz = dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT;
466         drro->drr_bonuslen = dnp->dn_bonuslen;
467         drro->drr_checksumtype = dnp->dn_checksum;
468         drro->drr_compress = dnp->dn_compress;
469         drro->drr_toguid = dsp->dsa_toguid;
470
471         if (!(dsp->dsa_featureflags & DMU_BACKUP_FEATURE_LARGE_BLOCKS) &&
472             drro->drr_blksz > SPA_OLD_MAXBLOCKSIZE)
473                 drro->drr_blksz = SPA_OLD_MAXBLOCKSIZE;
474
475         if (dump_record(dsp, DN_BONUS(dnp),
476             P2ROUNDUP(dnp->dn_bonuslen, 8)) != 0) {
477                 return (SET_ERROR(EINTR));
478         }
479
480         /* Free anything past the end of the file. */
481         if (dump_free(dsp, object, (dnp->dn_maxblkid + 1) *
482             (dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT), -1ULL) != 0)
483                 return (SET_ERROR(EINTR));
484         if (dsp->dsa_err != 0)
485                 return (SET_ERROR(EINTR));
486         return (0);
487 }
488
489 static boolean_t
490 backup_do_embed(dmu_sendarg_t *dsp, const blkptr_t *bp)
491 {
492         if (!BP_IS_EMBEDDED(bp))
493                 return (B_FALSE);
494
495         /*
496          * Compression function must be legacy, or explicitly enabled.
497          */
498         if ((BP_GET_COMPRESS(bp) >= ZIO_COMPRESS_LEGACY_FUNCTIONS &&
499             !(dsp->dsa_featureflags & DMU_BACKUP_FEATURE_EMBED_DATA_LZ4)))
500                 return (B_FALSE);
501
502         /*
503          * Embed type must be explicitly enabled.
504          */
505         switch (BPE_GET_ETYPE(bp)) {
506         case BP_EMBEDDED_TYPE_DATA:
507                 if (dsp->dsa_featureflags & DMU_BACKUP_FEATURE_EMBED_DATA)
508                         return (B_TRUE);
509                 break;
510         default:
511                 return (B_FALSE);
512         }
513         return (B_FALSE);
514 }
515
516 /*
517  * This is the callback function to traverse_dataset that acts as the worker
518  * thread for dmu_send_impl.
519  */
520 /*ARGSUSED*/
521 static int
522 send_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
523     const zbookmark_phys_t *zb, const struct dnode_phys *dnp, void *arg)
524 {
525         struct send_thread_arg *sta = arg;
526         struct send_block_record *record;
527         uint64_t record_size;
528         int err = 0;
529
530         ASSERT(zb->zb_object == DMU_META_DNODE_OBJECT ||
531             zb->zb_object >= sta->resume.zb_object);
532
533         if (sta->cancel)
534                 return (SET_ERROR(EINTR));
535
536         if (bp == NULL) {
537                 ASSERT3U(zb->zb_level, ==, ZB_DNODE_LEVEL);
538                 return (0);
539         } else if (zb->zb_level < 0) {
540                 return (0);
541         }
542
543         record = kmem_zalloc(sizeof (struct send_block_record), KM_SLEEP);
544         record->eos_marker = B_FALSE;
545         record->bp = *bp;
546         record->zb = *zb;
547         record->indblkshift = dnp->dn_indblkshift;
548         record->datablkszsec = dnp->dn_datablkszsec;
549         record_size = dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT;
550         bqueue_enqueue(&sta->q, record, record_size);
551
552         return (err);
553 }
554
555 /*
556  * This function kicks off the traverse_dataset.  It also handles setting the
557  * error code of the thread in case something goes wrong, and pushes the End of
558  * Stream record when the traverse_dataset call has finished.  If there is no
559  * dataset to traverse, the thread immediately pushes End of Stream marker.
560  */
561 static void
562 send_traverse_thread(void *arg)
563 {
564         struct send_thread_arg *st_arg = arg;
565         int err;
566         struct send_block_record *data;
567
568         if (st_arg->ds != NULL) {
569                 err = traverse_dataset_resume(st_arg->ds,
570                     st_arg->fromtxg, &st_arg->resume,
571                     st_arg->flags, send_cb, st_arg);
572
573                 if (err != EINTR)
574                         st_arg->error_code = err;
575         }
576         data = kmem_zalloc(sizeof (*data), KM_SLEEP);
577         data->eos_marker = B_TRUE;
578         bqueue_enqueue(&st_arg->q, data, 1);
579         thread_exit();
580 }
581
582 /*
583  * This function actually handles figuring out what kind of record needs to be
584  * dumped, reading the data (which has hopefully been prefetched), and calling
585  * the appropriate helper function.
586  */
587 static int
588 do_dump(dmu_sendarg_t *dsa, struct send_block_record *data)
589 {
590         dsl_dataset_t *ds = dmu_objset_ds(dsa->dsa_os);
591         const blkptr_t *bp = &data->bp;
592         const zbookmark_phys_t *zb = &data->zb;
593         uint8_t indblkshift = data->indblkshift;
594         uint16_t dblkszsec = data->datablkszsec;
595         spa_t *spa = ds->ds_dir->dd_pool->dp_spa;
596         dmu_object_type_t type = bp ? BP_GET_TYPE(bp) : DMU_OT_NONE;
597         int err = 0;
598
599         ASSERT3U(zb->zb_level, >=, 0);
600
601         ASSERT(zb->zb_object == DMU_META_DNODE_OBJECT ||
602             zb->zb_object >= dsa->dsa_resume_object);
603
604         if (zb->zb_object != DMU_META_DNODE_OBJECT &&
605             DMU_OBJECT_IS_SPECIAL(zb->zb_object)) {
606                 return (0);
607         } else if (BP_IS_HOLE(bp) &&
608             zb->zb_object == DMU_META_DNODE_OBJECT) {
609                 uint64_t span = BP_SPAN(dblkszsec, indblkshift, zb->zb_level);
610                 uint64_t dnobj = (zb->zb_blkid * span) >> DNODE_SHIFT;
611                 err = dump_freeobjects(dsa, dnobj, span >> DNODE_SHIFT);
612         } else if (BP_IS_HOLE(bp)) {
613                 uint64_t span = BP_SPAN(dblkszsec, indblkshift, zb->zb_level);
614                 uint64_t offset = zb->zb_blkid * span;
615                 err = dump_free(dsa, zb->zb_object, offset, span);
616         } else if (zb->zb_level > 0 || type == DMU_OT_OBJSET) {
617                 return (0);
618         } else if (type == DMU_OT_DNODE) {
619                 int blksz = BP_GET_LSIZE(bp);
620                 arc_flags_t aflags = ARC_FLAG_WAIT;
621                 arc_buf_t *abuf;
622
623                 ASSERT0(zb->zb_level);
624
625                 if (arc_read(NULL, spa, bp, arc_getbuf_func, &abuf,
626                     ZIO_PRIORITY_ASYNC_READ, ZIO_FLAG_CANFAIL,
627                     &aflags, zb) != 0)
628                         return (SET_ERROR(EIO));
629
630                 dnode_phys_t *blk = abuf->b_data;
631                 uint64_t dnobj = zb->zb_blkid * (blksz >> DNODE_SHIFT);
632                 for (int i = 0; i < blksz >> DNODE_SHIFT; i++) {
633                         err = dump_dnode(dsa, dnobj + i, blk + i);
634                         if (err != 0)
635                                 break;
636                 }
637                 (void) arc_buf_remove_ref(abuf, &abuf);
638         } else if (type == DMU_OT_SA) {
639                 arc_flags_t aflags = ARC_FLAG_WAIT;
640                 arc_buf_t *abuf;
641                 int blksz = BP_GET_LSIZE(bp);
642
643                 if (arc_read(NULL, spa, bp, arc_getbuf_func, &abuf,
644                     ZIO_PRIORITY_ASYNC_READ, ZIO_FLAG_CANFAIL,
645                     &aflags, zb) != 0)
646                         return (SET_ERROR(EIO));
647
648                 err = dump_spill(dsa, zb->zb_object, blksz, abuf->b_data);
649                 (void) arc_buf_remove_ref(abuf, &abuf);
650         } else if (backup_do_embed(dsa, bp)) {
651                 /* it's an embedded level-0 block of a regular object */
652                 int blksz = dblkszsec << SPA_MINBLOCKSHIFT;
653                 ASSERT0(zb->zb_level);
654                 err = dump_write_embedded(dsa, zb->zb_object,
655                     zb->zb_blkid * blksz, blksz, bp);
656         } else {
657                 /* it's a level-0 block of a regular object */
658                 arc_flags_t aflags = ARC_FLAG_WAIT;
659                 arc_buf_t *abuf;
660                 int blksz = dblkszsec << SPA_MINBLOCKSHIFT;
661                 uint64_t offset;
662
663                 ASSERT0(zb->zb_level);
664                 ASSERT(zb->zb_object > dsa->dsa_resume_object ||
665                     (zb->zb_object == dsa->dsa_resume_object &&
666                     zb->zb_blkid * blksz >= dsa->dsa_resume_offset));
667
668                 if (arc_read(NULL, spa, bp, arc_getbuf_func, &abuf,
669                     ZIO_PRIORITY_ASYNC_READ, ZIO_FLAG_CANFAIL,
670                     &aflags, zb) != 0) {
671                         if (zfs_send_corrupt_data) {
672                                 /* Send a block filled with 0x"zfs badd bloc" */
673                                 abuf = arc_buf_alloc(spa, blksz, &abuf,
674                                     ARC_BUFC_DATA);
675                                 uint64_t *ptr;
676                                 for (ptr = abuf->b_data;
677                                     (char *)ptr < (char *)abuf->b_data + blksz;
678                                     ptr++)
679                                         *ptr = 0x2f5baddb10cULL;
680                         } else {
681                                 return (SET_ERROR(EIO));
682                         }
683                 }
684
685                 offset = zb->zb_blkid * blksz;
686
687                 if (!(dsa->dsa_featureflags &
688                     DMU_BACKUP_FEATURE_LARGE_BLOCKS) &&
689                     blksz > SPA_OLD_MAXBLOCKSIZE) {
690                         char *buf = abuf->b_data;
691                         while (blksz > 0 && err == 0) {
692                                 int n = MIN(blksz, SPA_OLD_MAXBLOCKSIZE);
693                                 err = dump_write(dsa, type, zb->zb_object,
694                                     offset, n, NULL, buf);
695                                 offset += n;
696                                 buf += n;
697                                 blksz -= n;
698                         }
699                 } else {
700                         err = dump_write(dsa, type, zb->zb_object,
701                             offset, blksz, bp, abuf->b_data);
702                 }
703                 (void) arc_buf_remove_ref(abuf, &abuf);
704         }
705
706         ASSERT(err == 0 || err == EINTR);
707         return (err);
708 }
709
710 /*
711  * Pop the new data off the queue, and free the old data.
712  */
713 static struct send_block_record *
714 get_next_record(bqueue_t *bq, struct send_block_record *data)
715 {
716         struct send_block_record *tmp = bqueue_dequeue(bq);
717         kmem_free(data, sizeof (*data));
718         return (tmp);
719 }
720
721 /*
722  * Actually do the bulk of the work in a zfs send.
723  *
724  * Note: Releases dp using the specified tag.
725  */
726 static int
727 dmu_send_impl(void *tag, dsl_pool_t *dp, dsl_dataset_t *to_ds,
728     zfs_bookmark_phys_t *ancestor_zb,
729     boolean_t is_clone, boolean_t embedok, boolean_t large_block_ok, int outfd,
730     uint64_t resumeobj, uint64_t resumeoff,
731 #ifdef illumos
732     vnode_t *vp, offset_t *off)
733 #else
734     struct file *fp, offset_t *off)
735 #endif
736 {
737         objset_t *os;
738         dmu_replay_record_t *drr;
739         dmu_sendarg_t *dsp;
740         int err;
741         uint64_t fromtxg = 0;
742         uint64_t featureflags = 0;
743         struct send_thread_arg to_arg = { 0 };
744
745         err = dmu_objset_from_ds(to_ds, &os);
746         if (err != 0) {
747                 dsl_pool_rele(dp, tag);
748                 return (err);
749         }
750
751         drr = kmem_zalloc(sizeof (dmu_replay_record_t), KM_SLEEP);
752         drr->drr_type = DRR_BEGIN;
753         drr->drr_u.drr_begin.drr_magic = DMU_BACKUP_MAGIC;
754         DMU_SET_STREAM_HDRTYPE(drr->drr_u.drr_begin.drr_versioninfo,
755             DMU_SUBSTREAM);
756
757 #ifdef _KERNEL
758         if (dmu_objset_type(os) == DMU_OST_ZFS) {
759                 uint64_t version;
760                 if (zfs_get_zplprop(os, ZFS_PROP_VERSION, &version) != 0) {
761                         kmem_free(drr, sizeof (dmu_replay_record_t));
762                         dsl_pool_rele(dp, tag);
763                         return (SET_ERROR(EINVAL));
764                 }
765                 if (version >= ZPL_VERSION_SA) {
766                         featureflags |= DMU_BACKUP_FEATURE_SA_SPILL;
767                 }
768         }
769 #endif
770
771         if (large_block_ok && to_ds->ds_feature_inuse[SPA_FEATURE_LARGE_BLOCKS])
772                 featureflags |= DMU_BACKUP_FEATURE_LARGE_BLOCKS;
773         if (embedok &&
774             spa_feature_is_active(dp->dp_spa, SPA_FEATURE_EMBEDDED_DATA)) {
775                 featureflags |= DMU_BACKUP_FEATURE_EMBED_DATA;
776                 if (spa_feature_is_active(dp->dp_spa, SPA_FEATURE_LZ4_COMPRESS))
777                         featureflags |= DMU_BACKUP_FEATURE_EMBED_DATA_LZ4;
778         }
779
780         if (resumeobj != 0 || resumeoff != 0) {
781                 featureflags |= DMU_BACKUP_FEATURE_RESUMING;
782         }
783
784         DMU_SET_FEATUREFLAGS(drr->drr_u.drr_begin.drr_versioninfo,
785             featureflags);
786
787         drr->drr_u.drr_begin.drr_creation_time =
788             dsl_dataset_phys(to_ds)->ds_creation_time;
789         drr->drr_u.drr_begin.drr_type = dmu_objset_type(os);
790         if (is_clone)
791                 drr->drr_u.drr_begin.drr_flags |= DRR_FLAG_CLONE;
792         drr->drr_u.drr_begin.drr_toguid = dsl_dataset_phys(to_ds)->ds_guid;
793         if (dsl_dataset_phys(to_ds)->ds_flags & DS_FLAG_CI_DATASET)
794                 drr->drr_u.drr_begin.drr_flags |= DRR_FLAG_CI_DATA;
795         if (zfs_send_set_freerecords_bit)
796                 drr->drr_u.drr_begin.drr_flags |= DRR_FLAG_FREERECORDS;
797
798         if (ancestor_zb != NULL) {
799                 drr->drr_u.drr_begin.drr_fromguid =
800                     ancestor_zb->zbm_guid;
801                 fromtxg = ancestor_zb->zbm_creation_txg;
802         }
803         dsl_dataset_name(to_ds, drr->drr_u.drr_begin.drr_toname);
804         if (!to_ds->ds_is_snapshot) {
805                 (void) strlcat(drr->drr_u.drr_begin.drr_toname, "@--head--",
806                     sizeof (drr->drr_u.drr_begin.drr_toname));
807         }
808
809         dsp = kmem_zalloc(sizeof (dmu_sendarg_t), KM_SLEEP);
810
811         dsp->dsa_drr = drr;
812         dsp->dsa_outfd = outfd;
813         dsp->dsa_proc = curproc;
814         dsp->dsa_td = curthread;
815         dsp->dsa_fp = fp;
816         dsp->dsa_os = os;
817         dsp->dsa_off = off;
818         dsp->dsa_toguid = dsl_dataset_phys(to_ds)->ds_guid;
819         dsp->dsa_pending_op = PENDING_NONE;
820         dsp->dsa_featureflags = featureflags;
821         dsp->dsa_resume_object = resumeobj;
822         dsp->dsa_resume_offset = resumeoff;
823
824         mutex_enter(&to_ds->ds_sendstream_lock);
825         list_insert_head(&to_ds->ds_sendstreams, dsp);
826         mutex_exit(&to_ds->ds_sendstream_lock);
827
828         dsl_dataset_long_hold(to_ds, FTAG);
829         dsl_pool_rele(dp, tag);
830
831         void *payload = NULL;
832         size_t payload_len = 0;
833         if (resumeobj != 0 || resumeoff != 0) {
834                 dmu_object_info_t to_doi;
835                 err = dmu_object_info(os, resumeobj, &to_doi);
836                 if (err != 0)
837                         goto out;
838                 SET_BOOKMARK(&to_arg.resume, to_ds->ds_object, resumeobj, 0,
839                     resumeoff / to_doi.doi_data_block_size);
840
841                 nvlist_t *nvl = fnvlist_alloc();
842                 fnvlist_add_uint64(nvl, "resume_object", resumeobj);
843                 fnvlist_add_uint64(nvl, "resume_offset", resumeoff);
844                 payload = fnvlist_pack(nvl, &payload_len);
845                 drr->drr_payloadlen = payload_len;
846                 fnvlist_free(nvl);
847         }
848
849         err = dump_record(dsp, payload, payload_len);
850         fnvlist_pack_free(payload, payload_len);
851         if (err != 0) {
852                 err = dsp->dsa_err;
853                 goto out;
854         }
855
856         err = bqueue_init(&to_arg.q, zfs_send_queue_length,
857             offsetof(struct send_block_record, ln));
858         to_arg.error_code = 0;
859         to_arg.cancel = B_FALSE;
860         to_arg.ds = to_ds;
861         to_arg.fromtxg = fromtxg;
862         to_arg.flags = TRAVERSE_PRE | TRAVERSE_PREFETCH;
863         (void) thread_create(NULL, 0, send_traverse_thread, &to_arg, 0, &p0,
864             TS_RUN, minclsyspri);
865
866         struct send_block_record *to_data;
867         to_data = bqueue_dequeue(&to_arg.q);
868
869         while (!to_data->eos_marker && err == 0) {
870                 err = do_dump(dsp, to_data);
871                 to_data = get_next_record(&to_arg.q, to_data);
872                 if (issig(JUSTLOOKING) && issig(FORREAL))
873                         err = EINTR;
874         }
875
876         if (err != 0) {
877                 to_arg.cancel = B_TRUE;
878                 while (!to_data->eos_marker) {
879                         to_data = get_next_record(&to_arg.q, to_data);
880                 }
881         }
882         kmem_free(to_data, sizeof (*to_data));
883
884         bqueue_destroy(&to_arg.q);
885
886         if (err == 0 && to_arg.error_code != 0)
887                 err = to_arg.error_code;
888
889         if (err != 0)
890                 goto out;
891
892         if (dsp->dsa_pending_op != PENDING_NONE)
893                 if (dump_record(dsp, NULL, 0) != 0)
894                         err = SET_ERROR(EINTR);
895
896         if (err != 0) {
897                 if (err == EINTR && dsp->dsa_err != 0)
898                         err = dsp->dsa_err;
899                 goto out;
900         }
901
902         bzero(drr, sizeof (dmu_replay_record_t));
903         drr->drr_type = DRR_END;
904         drr->drr_u.drr_end.drr_checksum = dsp->dsa_zc;
905         drr->drr_u.drr_end.drr_toguid = dsp->dsa_toguid;
906
907         if (dump_record(dsp, NULL, 0) != 0)
908                 err = dsp->dsa_err;
909
910 out:
911         mutex_enter(&to_ds->ds_sendstream_lock);
912         list_remove(&to_ds->ds_sendstreams, dsp);
913         mutex_exit(&to_ds->ds_sendstream_lock);
914
915         kmem_free(drr, sizeof (dmu_replay_record_t));
916         kmem_free(dsp, sizeof (dmu_sendarg_t));
917
918         dsl_dataset_long_rele(to_ds, FTAG);
919
920         return (err);
921 }
922
923 int
924 dmu_send_obj(const char *pool, uint64_t tosnap, uint64_t fromsnap,
925     boolean_t embedok, boolean_t large_block_ok,
926 #ifdef illumos
927     int outfd, vnode_t *vp, offset_t *off)
928 #else
929     int outfd, struct file *fp, offset_t *off)
930 #endif
931 {
932         dsl_pool_t *dp;
933         dsl_dataset_t *ds;
934         dsl_dataset_t *fromds = NULL;
935         int err;
936
937         err = dsl_pool_hold(pool, FTAG, &dp);
938         if (err != 0)
939                 return (err);
940
941         err = dsl_dataset_hold_obj(dp, tosnap, FTAG, &ds);
942         if (err != 0) {
943                 dsl_pool_rele(dp, FTAG);
944                 return (err);
945         }
946
947         if (fromsnap != 0) {
948                 zfs_bookmark_phys_t zb;
949                 boolean_t is_clone;
950
951                 err = dsl_dataset_hold_obj(dp, fromsnap, FTAG, &fromds);
952                 if (err != 0) {
953                         dsl_dataset_rele(ds, FTAG);
954                         dsl_pool_rele(dp, FTAG);
955                         return (err);
956                 }
957                 if (!dsl_dataset_is_before(ds, fromds, 0))
958                         err = SET_ERROR(EXDEV);
959                 zb.zbm_creation_time =
960                     dsl_dataset_phys(fromds)->ds_creation_time;
961                 zb.zbm_creation_txg = dsl_dataset_phys(fromds)->ds_creation_txg;
962                 zb.zbm_guid = dsl_dataset_phys(fromds)->ds_guid;
963                 is_clone = (fromds->ds_dir != ds->ds_dir);
964                 dsl_dataset_rele(fromds, FTAG);
965                 err = dmu_send_impl(FTAG, dp, ds, &zb, is_clone,
966                     embedok, large_block_ok, outfd, 0, 0, fp, off);
967         } else {
968                 err = dmu_send_impl(FTAG, dp, ds, NULL, B_FALSE,
969                     embedok, large_block_ok, outfd, 0, 0, fp, off);
970         }
971         dsl_dataset_rele(ds, FTAG);
972         return (err);
973 }
974
975 int
976 dmu_send(const char *tosnap, const char *fromsnap, boolean_t embedok,
977     boolean_t large_block_ok, int outfd, uint64_t resumeobj, uint64_t resumeoff,
978 #ifdef illumos
979     vnode_t *vp, offset_t *off)
980 #else
981     struct file *fp, offset_t *off)
982 #endif
983 {
984         dsl_pool_t *dp;
985         dsl_dataset_t *ds;
986         int err;
987         boolean_t owned = B_FALSE;
988
989         if (fromsnap != NULL && strpbrk(fromsnap, "@#") == NULL)
990                 return (SET_ERROR(EINVAL));
991
992         err = dsl_pool_hold(tosnap, FTAG, &dp);
993         if (err != 0)
994                 return (err);
995
996         if (strchr(tosnap, '@') == NULL && spa_writeable(dp->dp_spa)) {
997                 /*
998                  * We are sending a filesystem or volume.  Ensure
999                  * that it doesn't change by owning the dataset.
1000                  */
1001                 err = dsl_dataset_own(dp, tosnap, FTAG, &ds);
1002                 owned = B_TRUE;
1003         } else {
1004                 err = dsl_dataset_hold(dp, tosnap, FTAG, &ds);
1005         }
1006         if (err != 0) {
1007                 dsl_pool_rele(dp, FTAG);
1008                 return (err);
1009         }
1010
1011         if (fromsnap != NULL) {
1012                 zfs_bookmark_phys_t zb;
1013                 boolean_t is_clone = B_FALSE;
1014                 int fsnamelen = strchr(tosnap, '@') - tosnap;
1015
1016                 /*
1017                  * If the fromsnap is in a different filesystem, then
1018                  * mark the send stream as a clone.
1019                  */
1020                 if (strncmp(tosnap, fromsnap, fsnamelen) != 0 ||
1021                     (fromsnap[fsnamelen] != '@' &&
1022                     fromsnap[fsnamelen] != '#')) {
1023                         is_clone = B_TRUE;
1024                 }
1025
1026                 if (strchr(fromsnap, '@')) {
1027                         dsl_dataset_t *fromds;
1028                         err = dsl_dataset_hold(dp, fromsnap, FTAG, &fromds);
1029                         if (err == 0) {
1030                                 if (!dsl_dataset_is_before(ds, fromds, 0))
1031                                         err = SET_ERROR(EXDEV);
1032                                 zb.zbm_creation_time =
1033                                     dsl_dataset_phys(fromds)->ds_creation_time;
1034                                 zb.zbm_creation_txg =
1035                                     dsl_dataset_phys(fromds)->ds_creation_txg;
1036                                 zb.zbm_guid = dsl_dataset_phys(fromds)->ds_guid;
1037                                 is_clone = (ds->ds_dir != fromds->ds_dir);
1038                                 dsl_dataset_rele(fromds, FTAG);
1039                         }
1040                 } else {
1041                         err = dsl_bookmark_lookup(dp, fromsnap, ds, &zb);
1042                 }
1043                 if (err != 0) {
1044                         dsl_dataset_rele(ds, FTAG);
1045                         dsl_pool_rele(dp, FTAG);
1046                         return (err);
1047                 }
1048                 err = dmu_send_impl(FTAG, dp, ds, &zb, is_clone,
1049                     embedok, large_block_ok,
1050                     outfd, resumeobj, resumeoff, fp, off);
1051         } else {
1052                 err = dmu_send_impl(FTAG, dp, ds, NULL, B_FALSE,
1053                     embedok, large_block_ok,
1054                     outfd, resumeobj, resumeoff, fp, off);
1055         }
1056         if (owned)
1057                 dsl_dataset_disown(ds, FTAG);
1058         else
1059                 dsl_dataset_rele(ds, FTAG);
1060         return (err);
1061 }
1062
1063 static int
1064 dmu_adjust_send_estimate_for_indirects(dsl_dataset_t *ds, uint64_t size,
1065     uint64_t *sizep)
1066 {
1067         int err;
1068         /*
1069          * Assume that space (both on-disk and in-stream) is dominated by
1070          * data.  We will adjust for indirect blocks and the copies property,
1071          * but ignore per-object space used (eg, dnodes and DRR_OBJECT records).
1072          */
1073
1074         /*
1075          * Subtract out approximate space used by indirect blocks.
1076          * Assume most space is used by data blocks (non-indirect, non-dnode).
1077          * Assume all blocks are recordsize.  Assume ditto blocks and
1078          * internal fragmentation counter out compression.
1079          *
1080          * Therefore, space used by indirect blocks is sizeof(blkptr_t) per
1081          * block, which we observe in practice.
1082          */
1083         uint64_t recordsize;
1084         err = dsl_prop_get_int_ds(ds, "recordsize", &recordsize);
1085         if (err != 0)
1086                 return (err);
1087         size -= size / recordsize * sizeof (blkptr_t);
1088
1089         /* Add in the space for the record associated with each block. */
1090         size += size / recordsize * sizeof (dmu_replay_record_t);
1091
1092         *sizep = size;
1093
1094         return (0);
1095 }
1096
1097 int
1098 dmu_send_estimate(dsl_dataset_t *ds, dsl_dataset_t *fromds, uint64_t *sizep)
1099 {
1100         dsl_pool_t *dp = ds->ds_dir->dd_pool;
1101         int err;
1102         uint64_t size;
1103
1104         ASSERT(dsl_pool_config_held(dp));
1105
1106         /* tosnap must be a snapshot */
1107         if (!ds->ds_is_snapshot)
1108                 return (SET_ERROR(EINVAL));
1109
1110         /* fromsnap, if provided, must be a snapshot */
1111         if (fromds != NULL && !fromds->ds_is_snapshot)
1112                 return (SET_ERROR(EINVAL));
1113
1114         /*
1115          * fromsnap must be an earlier snapshot from the same fs as tosnap,
1116          * or the origin's fs.
1117          */
1118         if (fromds != NULL && !dsl_dataset_is_before(ds, fromds, 0))
1119                 return (SET_ERROR(EXDEV));
1120
1121         /* Get uncompressed size estimate of changed data. */
1122         if (fromds == NULL) {
1123                 size = dsl_dataset_phys(ds)->ds_uncompressed_bytes;
1124         } else {
1125                 uint64_t used, comp;
1126                 err = dsl_dataset_space_written(fromds, ds,
1127                     &used, &comp, &size);
1128                 if (err != 0)
1129                         return (err);
1130         }
1131
1132         err = dmu_adjust_send_estimate_for_indirects(ds, size, sizep);
1133         return (err);
1134 }
1135
1136 /*
1137  * Simple callback used to traverse the blocks of a snapshot and sum their
1138  * uncompressed size
1139  */
1140 /* ARGSUSED */
1141 static int
1142 dmu_calculate_send_traversal(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
1143     const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
1144 {
1145         uint64_t *spaceptr = arg;
1146         if (bp != NULL && !BP_IS_HOLE(bp)) {
1147                 *spaceptr += BP_GET_UCSIZE(bp);
1148         }
1149         return (0);
1150 }
1151
1152 /*
1153  * Given a desination snapshot and a TXG, calculate the approximate size of a
1154  * send stream sent from that TXG. from_txg may be zero, indicating that the
1155  * whole snapshot will be sent.
1156  */
1157 int
1158 dmu_send_estimate_from_txg(dsl_dataset_t *ds, uint64_t from_txg,
1159     uint64_t *sizep)
1160 {
1161         dsl_pool_t *dp = ds->ds_dir->dd_pool;
1162         int err;
1163         uint64_t size = 0;
1164
1165         ASSERT(dsl_pool_config_held(dp));
1166
1167         /* tosnap must be a snapshot */
1168         if (!dsl_dataset_is_snapshot(ds))
1169                 return (SET_ERROR(EINVAL));
1170
1171         /* verify that from_txg is before the provided snapshot was taken */
1172         if (from_txg >= dsl_dataset_phys(ds)->ds_creation_txg) {
1173                 return (SET_ERROR(EXDEV));
1174         }
1175
1176         /*
1177          * traverse the blocks of the snapshot with birth times after
1178          * from_txg, summing their uncompressed size
1179          */
1180         err = traverse_dataset(ds, from_txg, TRAVERSE_POST,
1181             dmu_calculate_send_traversal, &size);
1182         if (err)
1183                 return (err);
1184
1185         err = dmu_adjust_send_estimate_for_indirects(ds, size, sizep);
1186         return (err);
1187 }
1188
1189 typedef struct dmu_recv_begin_arg {
1190         const char *drba_origin;
1191         dmu_recv_cookie_t *drba_cookie;
1192         cred_t *drba_cred;
1193         uint64_t drba_snapobj;
1194 } dmu_recv_begin_arg_t;
1195
1196 static int
1197 recv_begin_check_existing_impl(dmu_recv_begin_arg_t *drba, dsl_dataset_t *ds,
1198     uint64_t fromguid)
1199 {
1200         uint64_t val;
1201         int error;
1202         dsl_pool_t *dp = ds->ds_dir->dd_pool;
1203
1204         /* temporary clone name must not exist */
1205         error = zap_lookup(dp->dp_meta_objset,
1206             dsl_dir_phys(ds->ds_dir)->dd_child_dir_zapobj, recv_clone_name,
1207             8, 1, &val);
1208         if (error != ENOENT)
1209                 return (error == 0 ? EBUSY : error);
1210
1211         /* new snapshot name must not exist */
1212         error = zap_lookup(dp->dp_meta_objset,
1213             dsl_dataset_phys(ds)->ds_snapnames_zapobj,
1214             drba->drba_cookie->drc_tosnap, 8, 1, &val);
1215         if (error != ENOENT)
1216                 return (error == 0 ? EEXIST : error);
1217
1218         /*
1219          * Check snapshot limit before receiving. We'll recheck again at the
1220          * end, but might as well abort before receiving if we're already over
1221          * the limit.
1222          *
1223          * Note that we do not check the file system limit with
1224          * dsl_dir_fscount_check because the temporary %clones don't count
1225          * against that limit.
1226          */
1227         error = dsl_fs_ss_limit_check(ds->ds_dir, 1, ZFS_PROP_SNAPSHOT_LIMIT,
1228             NULL, drba->drba_cred);
1229         if (error != 0)
1230                 return (error);
1231
1232         if (fromguid != 0) {
1233                 dsl_dataset_t *snap;
1234                 uint64_t obj = dsl_dataset_phys(ds)->ds_prev_snap_obj;
1235
1236                 /* Find snapshot in this dir that matches fromguid. */
1237                 while (obj != 0) {
1238                         error = dsl_dataset_hold_obj(dp, obj, FTAG,
1239                             &snap);
1240                         if (error != 0)
1241                                 return (SET_ERROR(ENODEV));
1242                         if (snap->ds_dir != ds->ds_dir) {
1243                                 dsl_dataset_rele(snap, FTAG);
1244                                 return (SET_ERROR(ENODEV));
1245                         }
1246                         if (dsl_dataset_phys(snap)->ds_guid == fromguid)
1247                                 break;
1248                         obj = dsl_dataset_phys(snap)->ds_prev_snap_obj;
1249                         dsl_dataset_rele(snap, FTAG);
1250                 }
1251                 if (obj == 0)
1252                         return (SET_ERROR(ENODEV));
1253
1254                 if (drba->drba_cookie->drc_force) {
1255                         drba->drba_snapobj = obj;
1256                 } else {
1257                         /*
1258                          * If we are not forcing, there must be no
1259                          * changes since fromsnap.
1260                          */
1261                         if (dsl_dataset_modified_since_snap(ds, snap)) {
1262                                 dsl_dataset_rele(snap, FTAG);
1263                                 return (SET_ERROR(ETXTBSY));
1264                         }
1265                         drba->drba_snapobj = ds->ds_prev->ds_object;
1266                 }
1267
1268                 dsl_dataset_rele(snap, FTAG);
1269         } else {
1270                 /* if full, then must be forced */
1271                 if (!drba->drba_cookie->drc_force)
1272                         return (SET_ERROR(EEXIST));
1273                 /* start from $ORIGIN@$ORIGIN, if supported */
1274                 drba->drba_snapobj = dp->dp_origin_snap != NULL ?
1275                     dp->dp_origin_snap->ds_object : 0;
1276         }
1277
1278         return (0);
1279
1280 }
1281
1282 static int
1283 dmu_recv_begin_check(void *arg, dmu_tx_t *tx)
1284 {
1285         dmu_recv_begin_arg_t *drba = arg;
1286         dsl_pool_t *dp = dmu_tx_pool(tx);
1287         struct drr_begin *drrb = drba->drba_cookie->drc_drrb;
1288         uint64_t fromguid = drrb->drr_fromguid;
1289         int flags = drrb->drr_flags;
1290         int error;
1291         uint64_t featureflags = DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo);
1292         dsl_dataset_t *ds;
1293         const char *tofs = drba->drba_cookie->drc_tofs;
1294
1295         /* already checked */
1296         ASSERT3U(drrb->drr_magic, ==, DMU_BACKUP_MAGIC);
1297         ASSERT(!(featureflags & DMU_BACKUP_FEATURE_RESUMING));
1298
1299         if (DMU_GET_STREAM_HDRTYPE(drrb->drr_versioninfo) ==
1300             DMU_COMPOUNDSTREAM ||
1301             drrb->drr_type >= DMU_OST_NUMTYPES ||
1302             ((flags & DRR_FLAG_CLONE) && drba->drba_origin == NULL))
1303                 return (SET_ERROR(EINVAL));
1304
1305         /* Verify pool version supports SA if SA_SPILL feature set */
1306         if ((featureflags & DMU_BACKUP_FEATURE_SA_SPILL) &&
1307             spa_version(dp->dp_spa) < SPA_VERSION_SA)
1308                 return (SET_ERROR(ENOTSUP));
1309
1310         if (drba->drba_cookie->drc_resumable &&
1311             !spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_EXTENSIBLE_DATASET))
1312                 return (SET_ERROR(ENOTSUP));
1313
1314         /*
1315          * The receiving code doesn't know how to translate a WRITE_EMBEDDED
1316          * record to a plan WRITE record, so the pool must have the
1317          * EMBEDDED_DATA feature enabled if the stream has WRITE_EMBEDDED
1318          * records.  Same with WRITE_EMBEDDED records that use LZ4 compression.
1319          */
1320         if ((featureflags & DMU_BACKUP_FEATURE_EMBED_DATA) &&
1321             !spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_EMBEDDED_DATA))
1322                 return (SET_ERROR(ENOTSUP));
1323         if ((featureflags & DMU_BACKUP_FEATURE_EMBED_DATA_LZ4) &&
1324             !spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_LZ4_COMPRESS))
1325                 return (SET_ERROR(ENOTSUP));
1326
1327         /*
1328          * The receiving code doesn't know how to translate large blocks
1329          * to smaller ones, so the pool must have the LARGE_BLOCKS
1330          * feature enabled if the stream has LARGE_BLOCKS.
1331          */
1332         if ((featureflags & DMU_BACKUP_FEATURE_LARGE_BLOCKS) &&
1333             !spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_LARGE_BLOCKS))
1334                 return (SET_ERROR(ENOTSUP));
1335
1336         error = dsl_dataset_hold(dp, tofs, FTAG, &ds);
1337         if (error == 0) {
1338                 /* target fs already exists; recv into temp clone */
1339
1340                 /* Can't recv a clone into an existing fs */
1341                 if (flags & DRR_FLAG_CLONE || drba->drba_origin) {
1342                         dsl_dataset_rele(ds, FTAG);
1343                         return (SET_ERROR(EINVAL));
1344                 }
1345
1346                 error = recv_begin_check_existing_impl(drba, ds, fromguid);
1347                 dsl_dataset_rele(ds, FTAG);
1348         } else if (error == ENOENT) {
1349                 /* target fs does not exist; must be a full backup or clone */
1350                 char buf[MAXNAMELEN];
1351
1352                 /*
1353                  * If it's a non-clone incremental, we are missing the
1354                  * target fs, so fail the recv.
1355                  */
1356                 if (fromguid != 0 && !(flags & DRR_FLAG_CLONE ||
1357                     drba->drba_origin))
1358                         return (SET_ERROR(ENOENT));
1359
1360                 /*
1361                  * If we're receiving a full send as a clone, and it doesn't
1362                  * contain all the necessary free records and freeobject
1363                  * records, reject it.
1364                  */
1365                 if (fromguid == 0 && drba->drba_origin &&
1366                     !(flags & DRR_FLAG_FREERECORDS))
1367                         return (SET_ERROR(EINVAL));
1368
1369                 /* Open the parent of tofs */
1370                 ASSERT3U(strlen(tofs), <, MAXNAMELEN);
1371                 (void) strlcpy(buf, tofs, strrchr(tofs, '/') - tofs + 1);
1372                 error = dsl_dataset_hold(dp, buf, FTAG, &ds);
1373                 if (error != 0)
1374                         return (error);
1375
1376                 /*
1377                  * Check filesystem and snapshot limits before receiving. We'll
1378                  * recheck snapshot limits again at the end (we create the
1379                  * filesystems and increment those counts during begin_sync).
1380                  */
1381                 error = dsl_fs_ss_limit_check(ds->ds_dir, 1,
1382                     ZFS_PROP_FILESYSTEM_LIMIT, NULL, drba->drba_cred);
1383                 if (error != 0) {
1384                         dsl_dataset_rele(ds, FTAG);
1385                         return (error);
1386                 }
1387
1388                 error = dsl_fs_ss_limit_check(ds->ds_dir, 1,
1389                     ZFS_PROP_SNAPSHOT_LIMIT, NULL, drba->drba_cred);
1390                 if (error != 0) {
1391                         dsl_dataset_rele(ds, FTAG);
1392                         return (error);
1393                 }
1394
1395                 if (drba->drba_origin != NULL) {
1396                         dsl_dataset_t *origin;
1397                         error = dsl_dataset_hold(dp, drba->drba_origin,
1398                             FTAG, &origin);
1399                         if (error != 0) {
1400                                 dsl_dataset_rele(ds, FTAG);
1401                                 return (error);
1402                         }
1403                         if (!origin->ds_is_snapshot) {
1404                                 dsl_dataset_rele(origin, FTAG);
1405                                 dsl_dataset_rele(ds, FTAG);
1406                                 return (SET_ERROR(EINVAL));
1407                         }
1408                         if (dsl_dataset_phys(origin)->ds_guid != fromguid &&
1409                             fromguid != 0) {
1410                                 dsl_dataset_rele(origin, FTAG);
1411                                 dsl_dataset_rele(ds, FTAG);
1412                                 return (SET_ERROR(ENODEV));
1413                         }
1414                         dsl_dataset_rele(origin, FTAG);
1415                 }
1416                 dsl_dataset_rele(ds, FTAG);
1417                 error = 0;
1418         }
1419         return (error);
1420 }
1421
1422 static void
1423 dmu_recv_begin_sync(void *arg, dmu_tx_t *tx)
1424 {
1425         dmu_recv_begin_arg_t *drba = arg;
1426         dsl_pool_t *dp = dmu_tx_pool(tx);
1427         objset_t *mos = dp->dp_meta_objset;
1428         struct drr_begin *drrb = drba->drba_cookie->drc_drrb;
1429         const char *tofs = drba->drba_cookie->drc_tofs;
1430         dsl_dataset_t *ds, *newds;
1431         uint64_t dsobj;
1432         int error;
1433         uint64_t crflags = 0;
1434
1435         if (drrb->drr_flags & DRR_FLAG_CI_DATA)
1436                 crflags |= DS_FLAG_CI_DATASET;
1437
1438         error = dsl_dataset_hold(dp, tofs, FTAG, &ds);
1439         if (error == 0) {
1440                 /* create temporary clone */
1441                 dsl_dataset_t *snap = NULL;
1442                 if (drba->drba_snapobj != 0) {
1443                         VERIFY0(dsl_dataset_hold_obj(dp,
1444                             drba->drba_snapobj, FTAG, &snap));
1445                 }
1446                 dsobj = dsl_dataset_create_sync(ds->ds_dir, recv_clone_name,
1447                     snap, crflags, drba->drba_cred, tx);
1448                 if (drba->drba_snapobj != 0)
1449                         dsl_dataset_rele(snap, FTAG);
1450                 dsl_dataset_rele(ds, FTAG);
1451         } else {
1452                 dsl_dir_t *dd;
1453                 const char *tail;
1454                 dsl_dataset_t *origin = NULL;
1455
1456                 VERIFY0(dsl_dir_hold(dp, tofs, FTAG, &dd, &tail));
1457
1458                 if (drba->drba_origin != NULL) {
1459                         VERIFY0(dsl_dataset_hold(dp, drba->drba_origin,
1460                             FTAG, &origin));
1461                 }
1462
1463                 /* Create new dataset. */
1464                 dsobj = dsl_dataset_create_sync(dd,
1465                     strrchr(tofs, '/') + 1,
1466                     origin, crflags, drba->drba_cred, tx);
1467                 if (origin != NULL)
1468                         dsl_dataset_rele(origin, FTAG);
1469                 dsl_dir_rele(dd, FTAG);
1470                 drba->drba_cookie->drc_newfs = B_TRUE;
1471         }
1472         VERIFY0(dsl_dataset_own_obj(dp, dsobj, dmu_recv_tag, &newds));
1473
1474         if (drba->drba_cookie->drc_resumable) {
1475                 dsl_dataset_zapify(newds, tx);
1476                 if (drrb->drr_fromguid != 0) {
1477                         VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_FROMGUID,
1478                             8, 1, &drrb->drr_fromguid, tx));
1479                 }
1480                 VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_TOGUID,
1481                     8, 1, &drrb->drr_toguid, tx));
1482                 VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_TONAME,
1483                     1, strlen(drrb->drr_toname) + 1, drrb->drr_toname, tx));
1484                 uint64_t one = 1;
1485                 uint64_t zero = 0;
1486                 VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_OBJECT,
1487                     8, 1, &one, tx));
1488                 VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_OFFSET,
1489                     8, 1, &zero, tx));
1490                 VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_BYTES,
1491                     8, 1, &zero, tx));
1492                 if (DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo) &
1493                     DMU_BACKUP_FEATURE_EMBED_DATA) {
1494                         VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_EMBEDOK,
1495                             8, 1, &one, tx));
1496                 }
1497         }
1498
1499         dmu_buf_will_dirty(newds->ds_dbuf, tx);
1500         dsl_dataset_phys(newds)->ds_flags |= DS_FLAG_INCONSISTENT;
1501
1502         /*
1503          * If we actually created a non-clone, we need to create the
1504          * objset in our new dataset.
1505          */
1506         if (BP_IS_HOLE(dsl_dataset_get_blkptr(newds))) {
1507                 (void) dmu_objset_create_impl(dp->dp_spa,
1508                     newds, dsl_dataset_get_blkptr(newds), drrb->drr_type, tx);
1509         }
1510
1511         drba->drba_cookie->drc_ds = newds;
1512
1513         spa_history_log_internal_ds(newds, "receive", tx, "");
1514 }
1515
1516 static int
1517 dmu_recv_resume_begin_check(void *arg, dmu_tx_t *tx)
1518 {
1519         dmu_recv_begin_arg_t *drba = arg;
1520         dsl_pool_t *dp = dmu_tx_pool(tx);
1521         struct drr_begin *drrb = drba->drba_cookie->drc_drrb;
1522         int error;
1523         uint64_t featureflags = DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo);
1524         dsl_dataset_t *ds;
1525         const char *tofs = drba->drba_cookie->drc_tofs;
1526
1527         /* already checked */
1528         ASSERT3U(drrb->drr_magic, ==, DMU_BACKUP_MAGIC);
1529         ASSERT(featureflags & DMU_BACKUP_FEATURE_RESUMING);
1530
1531         if (DMU_GET_STREAM_HDRTYPE(drrb->drr_versioninfo) ==
1532             DMU_COMPOUNDSTREAM ||
1533             drrb->drr_type >= DMU_OST_NUMTYPES)
1534                 return (SET_ERROR(EINVAL));
1535
1536         /* Verify pool version supports SA if SA_SPILL feature set */
1537         if ((featureflags & DMU_BACKUP_FEATURE_SA_SPILL) &&
1538             spa_version(dp->dp_spa) < SPA_VERSION_SA)
1539                 return (SET_ERROR(ENOTSUP));
1540
1541         /*
1542          * The receiving code doesn't know how to translate a WRITE_EMBEDDED
1543          * record to a plain WRITE record, so the pool must have the
1544          * EMBEDDED_DATA feature enabled if the stream has WRITE_EMBEDDED
1545          * records.  Same with WRITE_EMBEDDED records that use LZ4 compression.
1546          */
1547         if ((featureflags & DMU_BACKUP_FEATURE_EMBED_DATA) &&
1548             !spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_EMBEDDED_DATA))
1549                 return (SET_ERROR(ENOTSUP));
1550         if ((featureflags & DMU_BACKUP_FEATURE_EMBED_DATA_LZ4) &&
1551             !spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_LZ4_COMPRESS))
1552                 return (SET_ERROR(ENOTSUP));
1553
1554         char recvname[ZFS_MAXNAMELEN];
1555
1556         (void) snprintf(recvname, sizeof (recvname), "%s/%s",
1557             tofs, recv_clone_name);
1558
1559         if (dsl_dataset_hold(dp, recvname, FTAG, &ds) != 0) {
1560                 /* %recv does not exist; continue in tofs */
1561                 error = dsl_dataset_hold(dp, tofs, FTAG, &ds);
1562                 if (error != 0)
1563                         return (error);
1564         }
1565
1566         /* check that ds is marked inconsistent */
1567         if (!DS_IS_INCONSISTENT(ds)) {
1568                 dsl_dataset_rele(ds, FTAG);
1569                 return (SET_ERROR(EINVAL));
1570         }
1571
1572         /* check that there is resuming data, and that the toguid matches */
1573         if (!dsl_dataset_is_zapified(ds)) {
1574                 dsl_dataset_rele(ds, FTAG);
1575                 return (SET_ERROR(EINVAL));
1576         }
1577         uint64_t val;
1578         error = zap_lookup(dp->dp_meta_objset, ds->ds_object,
1579             DS_FIELD_RESUME_TOGUID, sizeof (val), 1, &val);
1580         if (error != 0 || drrb->drr_toguid != val) {
1581                 dsl_dataset_rele(ds, FTAG);
1582                 return (SET_ERROR(EINVAL));
1583         }
1584
1585         /*
1586          * Check if the receive is still running.  If so, it will be owned.
1587          * Note that nothing else can own the dataset (e.g. after the receive
1588          * fails) because it will be marked inconsistent.
1589          */
1590         if (dsl_dataset_has_owner(ds)) {
1591                 dsl_dataset_rele(ds, FTAG);
1592                 return (SET_ERROR(EBUSY));
1593         }
1594
1595         /* There should not be any snapshots of this fs yet. */
1596         if (ds->ds_prev != NULL && ds->ds_prev->ds_dir == ds->ds_dir) {
1597                 dsl_dataset_rele(ds, FTAG);
1598                 return (SET_ERROR(EINVAL));
1599         }
1600
1601         /*
1602          * Note: resume point will be checked when we process the first WRITE
1603          * record.
1604          */
1605
1606         /* check that the origin matches */
1607         val = 0;
1608         (void) zap_lookup(dp->dp_meta_objset, ds->ds_object,
1609             DS_FIELD_RESUME_FROMGUID, sizeof (val), 1, &val);
1610         if (drrb->drr_fromguid != val) {
1611                 dsl_dataset_rele(ds, FTAG);
1612                 return (SET_ERROR(EINVAL));
1613         }
1614
1615         dsl_dataset_rele(ds, FTAG);
1616         return (0);
1617 }
1618
1619 static void
1620 dmu_recv_resume_begin_sync(void *arg, dmu_tx_t *tx)
1621 {
1622         dmu_recv_begin_arg_t *drba = arg;
1623         dsl_pool_t *dp = dmu_tx_pool(tx);
1624         const char *tofs = drba->drba_cookie->drc_tofs;
1625         dsl_dataset_t *ds;
1626         uint64_t dsobj;
1627         char recvname[ZFS_MAXNAMELEN];
1628
1629         (void) snprintf(recvname, sizeof (recvname), "%s/%s",
1630             tofs, recv_clone_name);
1631
1632         if (dsl_dataset_hold(dp, recvname, FTAG, &ds) != 0) {
1633                 /* %recv does not exist; continue in tofs */
1634                 VERIFY0(dsl_dataset_hold(dp, tofs, FTAG, &ds));
1635                 drba->drba_cookie->drc_newfs = B_TRUE;
1636         }
1637
1638         /* clear the inconsistent flag so that we can own it */
1639         ASSERT(DS_IS_INCONSISTENT(ds));
1640         dmu_buf_will_dirty(ds->ds_dbuf, tx);
1641         dsl_dataset_phys(ds)->ds_flags &= ~DS_FLAG_INCONSISTENT;
1642         dsobj = ds->ds_object;
1643         dsl_dataset_rele(ds, FTAG);
1644
1645         VERIFY0(dsl_dataset_own_obj(dp, dsobj, dmu_recv_tag, &ds));
1646
1647         dmu_buf_will_dirty(ds->ds_dbuf, tx);
1648         dsl_dataset_phys(ds)->ds_flags |= DS_FLAG_INCONSISTENT;
1649
1650         ASSERT(!BP_IS_HOLE(dsl_dataset_get_blkptr(ds)));
1651
1652         drba->drba_cookie->drc_ds = ds;
1653
1654         spa_history_log_internal_ds(ds, "resume receive", tx, "");
1655 }
1656
1657 /*
1658  * NB: callers *MUST* call dmu_recv_stream() if dmu_recv_begin()
1659  * succeeds; otherwise we will leak the holds on the datasets.
1660  */
1661 int
1662 dmu_recv_begin(char *tofs, char *tosnap, dmu_replay_record_t *drr_begin,
1663     boolean_t force, boolean_t resumable, char *origin, dmu_recv_cookie_t *drc)
1664 {
1665         dmu_recv_begin_arg_t drba = { 0 };
1666
1667         bzero(drc, sizeof (dmu_recv_cookie_t));
1668         drc->drc_drr_begin = drr_begin;
1669         drc->drc_drrb = &drr_begin->drr_u.drr_begin;
1670         drc->drc_tosnap = tosnap;
1671         drc->drc_tofs = tofs;
1672         drc->drc_force = force;
1673         drc->drc_resumable = resumable;
1674         drc->drc_cred = CRED();
1675
1676         if (drc->drc_drrb->drr_magic == BSWAP_64(DMU_BACKUP_MAGIC)) {
1677                 drc->drc_byteswap = B_TRUE;
1678                 fletcher_4_incremental_byteswap(drr_begin,
1679                     sizeof (dmu_replay_record_t), &drc->drc_cksum);
1680                 byteswap_record(drr_begin);
1681         } else if (drc->drc_drrb->drr_magic == DMU_BACKUP_MAGIC) {
1682                 fletcher_4_incremental_native(drr_begin,
1683                     sizeof (dmu_replay_record_t), &drc->drc_cksum);
1684         } else {
1685                 return (SET_ERROR(EINVAL));
1686         }
1687
1688         drba.drba_origin = origin;
1689         drba.drba_cookie = drc;
1690         drba.drba_cred = CRED();
1691
1692         if (DMU_GET_FEATUREFLAGS(drc->drc_drrb->drr_versioninfo) &
1693             DMU_BACKUP_FEATURE_RESUMING) {
1694                 return (dsl_sync_task(tofs,
1695                     dmu_recv_resume_begin_check, dmu_recv_resume_begin_sync,
1696                     &drba, 5, ZFS_SPACE_CHECK_NORMAL));
1697         } else  {
1698                 return (dsl_sync_task(tofs,
1699                     dmu_recv_begin_check, dmu_recv_begin_sync,
1700                     &drba, 5, ZFS_SPACE_CHECK_NORMAL));
1701         }
1702 }
1703
1704 struct receive_record_arg {
1705         dmu_replay_record_t header;
1706         void *payload; /* Pointer to a buffer containing the payload */
1707         /*
1708          * If the record is a write, pointer to the arc_buf_t containing the
1709          * payload.
1710          */
1711         arc_buf_t *write_buf;
1712         int payload_size;
1713         uint64_t bytes_read; /* bytes read from stream when record created */
1714         boolean_t eos_marker; /* Marks the end of the stream */
1715         bqueue_node_t node;
1716 };
1717
1718 struct receive_writer_arg {
1719         objset_t *os;
1720         boolean_t byteswap;
1721         bqueue_t q;
1722
1723         /*
1724          * These three args are used to signal to the main thread that we're
1725          * done.
1726          */
1727         kmutex_t mutex;
1728         kcondvar_t cv;
1729         boolean_t done;
1730
1731         int err;
1732         /* A map from guid to dataset to help handle dedup'd streams. */
1733         avl_tree_t *guid_to_ds_map;
1734         boolean_t resumable;
1735         uint64_t last_object, last_offset;
1736         uint64_t bytes_read; /* bytes read when current record created */
1737 };
1738
1739 struct objlist {
1740         list_t list; /* List of struct receive_objnode. */
1741         /*
1742          * Last object looked up. Used to assert that objects are being looked
1743          * up in ascending order.
1744          */
1745         uint64_t last_lookup;
1746 };
1747
1748 struct receive_objnode {
1749         list_node_t node;
1750         uint64_t object;
1751 };
1752
1753 struct receive_arg  {
1754         objset_t *os;
1755         kthread_t *td;
1756         struct file *fp;
1757         uint64_t voff; /* The current offset in the stream */
1758         uint64_t bytes_read;
1759         /*
1760          * A record that has had its payload read in, but hasn't yet been handed
1761          * off to the worker thread.
1762          */
1763         struct receive_record_arg *rrd;
1764         /* A record that has had its header read in, but not its payload. */
1765         struct receive_record_arg *next_rrd;
1766         zio_cksum_t cksum;
1767         zio_cksum_t prev_cksum;
1768         int err;
1769         boolean_t byteswap;
1770         /* Sorted list of objects not to issue prefetches for. */
1771         struct objlist ignore_objlist;
1772 };
1773
1774 typedef struct guid_map_entry {
1775         uint64_t        guid;
1776         dsl_dataset_t   *gme_ds;
1777         avl_node_t      avlnode;
1778 } guid_map_entry_t;
1779
1780 static int
1781 guid_compare(const void *arg1, const void *arg2)
1782 {
1783         const guid_map_entry_t *gmep1 = arg1;
1784         const guid_map_entry_t *gmep2 = arg2;
1785
1786         if (gmep1->guid < gmep2->guid)
1787                 return (-1);
1788         else if (gmep1->guid > gmep2->guid)
1789                 return (1);
1790         return (0);
1791 }
1792
1793 static void
1794 free_guid_map_onexit(void *arg)
1795 {
1796         avl_tree_t *ca = arg;
1797         void *cookie = NULL;
1798         guid_map_entry_t *gmep;
1799
1800         while ((gmep = avl_destroy_nodes(ca, &cookie)) != NULL) {
1801                 dsl_dataset_long_rele(gmep->gme_ds, gmep);
1802                 dsl_dataset_rele(gmep->gme_ds, gmep);
1803                 kmem_free(gmep, sizeof (guid_map_entry_t));
1804         }
1805         avl_destroy(ca);
1806         kmem_free(ca, sizeof (avl_tree_t));
1807 }
1808
1809 static int
1810 restore_bytes(struct receive_arg *ra, void *buf, int len, off_t off, ssize_t *resid)
1811 {
1812         struct uio auio;
1813         struct iovec aiov;
1814         int error;
1815
1816         aiov.iov_base = buf;
1817         aiov.iov_len = len;
1818         auio.uio_iov = &aiov;
1819         auio.uio_iovcnt = 1;
1820         auio.uio_resid = len;
1821         auio.uio_segflg = UIO_SYSSPACE;
1822         auio.uio_rw = UIO_READ;
1823         auio.uio_offset = off;
1824         auio.uio_td = ra->td;
1825 #ifdef _KERNEL
1826         error = fo_read(ra->fp, &auio, ra->td->td_ucred, FOF_OFFSET, ra->td);
1827 #else
1828         fprintf(stderr, "%s: returning EOPNOTSUPP\n", __func__);
1829         error = EOPNOTSUPP;
1830 #endif
1831         *resid = auio.uio_resid;
1832         return (error);
1833 }
1834
1835 static int
1836 receive_read(struct receive_arg *ra, int len, void *buf)
1837 {
1838         int done = 0;
1839
1840         /*
1841          * The code doesn't rely on this (lengths being multiples of 8).  See
1842          * comment in dump_bytes.
1843          */
1844         ASSERT0(len % 8);
1845
1846         while (done < len) {
1847                 ssize_t resid;
1848
1849                 ra->err = restore_bytes(ra, buf + done,
1850                     len - done, ra->voff, &resid);
1851
1852                 if (resid == len - done) {
1853                         /*
1854                          * Note: ECKSUM indicates that the receive
1855                          * was interrupted and can potentially be resumed.
1856                          */
1857                         ra->err = SET_ERROR(ECKSUM);
1858                 }
1859                 ra->voff += len - done - resid;
1860                 done = len - resid;
1861                 if (ra->err != 0)
1862                         return (ra->err);
1863         }
1864
1865         ra->bytes_read += len;
1866
1867         ASSERT3U(done, ==, len);
1868         return (0);
1869 }
1870
1871 static void
1872 byteswap_record(dmu_replay_record_t *drr)
1873 {
1874 #define DO64(X) (drr->drr_u.X = BSWAP_64(drr->drr_u.X))
1875 #define DO32(X) (drr->drr_u.X = BSWAP_32(drr->drr_u.X))
1876         drr->drr_type = BSWAP_32(drr->drr_type);
1877         drr->drr_payloadlen = BSWAP_32(drr->drr_payloadlen);
1878
1879         switch (drr->drr_type) {
1880         case DRR_BEGIN:
1881                 DO64(drr_begin.drr_magic);
1882                 DO64(drr_begin.drr_versioninfo);
1883                 DO64(drr_begin.drr_creation_time);
1884                 DO32(drr_begin.drr_type);
1885                 DO32(drr_begin.drr_flags);
1886                 DO64(drr_begin.drr_toguid);
1887                 DO64(drr_begin.drr_fromguid);
1888                 break;
1889         case DRR_OBJECT:
1890                 DO64(drr_object.drr_object);
1891                 DO32(drr_object.drr_type);
1892                 DO32(drr_object.drr_bonustype);
1893                 DO32(drr_object.drr_blksz);
1894                 DO32(drr_object.drr_bonuslen);
1895                 DO64(drr_object.drr_toguid);
1896                 break;
1897         case DRR_FREEOBJECTS:
1898                 DO64(drr_freeobjects.drr_firstobj);
1899                 DO64(drr_freeobjects.drr_numobjs);
1900                 DO64(drr_freeobjects.drr_toguid);
1901                 break;
1902         case DRR_WRITE:
1903                 DO64(drr_write.drr_object);
1904                 DO32(drr_write.drr_type);
1905                 DO64(drr_write.drr_offset);
1906                 DO64(drr_write.drr_length);
1907                 DO64(drr_write.drr_toguid);
1908                 ZIO_CHECKSUM_BSWAP(&drr->drr_u.drr_write.drr_key.ddk_cksum);
1909                 DO64(drr_write.drr_key.ddk_prop);
1910                 break;
1911         case DRR_WRITE_BYREF:
1912                 DO64(drr_write_byref.drr_object);
1913                 DO64(drr_write_byref.drr_offset);
1914                 DO64(drr_write_byref.drr_length);
1915                 DO64(drr_write_byref.drr_toguid);
1916                 DO64(drr_write_byref.drr_refguid);
1917                 DO64(drr_write_byref.drr_refobject);
1918                 DO64(drr_write_byref.drr_refoffset);
1919                 ZIO_CHECKSUM_BSWAP(&drr->drr_u.drr_write_byref.
1920                     drr_key.ddk_cksum);
1921                 DO64(drr_write_byref.drr_key.ddk_prop);
1922                 break;
1923         case DRR_WRITE_EMBEDDED:
1924                 DO64(drr_write_embedded.drr_object);
1925                 DO64(drr_write_embedded.drr_offset);
1926                 DO64(drr_write_embedded.drr_length);
1927                 DO64(drr_write_embedded.drr_toguid);
1928                 DO32(drr_write_embedded.drr_lsize);
1929                 DO32(drr_write_embedded.drr_psize);
1930                 break;
1931         case DRR_FREE:
1932                 DO64(drr_free.drr_object);
1933                 DO64(drr_free.drr_offset);
1934                 DO64(drr_free.drr_length);
1935                 DO64(drr_free.drr_toguid);
1936                 break;
1937         case DRR_SPILL:
1938                 DO64(drr_spill.drr_object);
1939                 DO64(drr_spill.drr_length);
1940                 DO64(drr_spill.drr_toguid);
1941                 break;
1942         case DRR_END:
1943                 DO64(drr_end.drr_toguid);
1944                 ZIO_CHECKSUM_BSWAP(&drr->drr_u.drr_end.drr_checksum);
1945                 break;
1946         }
1947
1948         if (drr->drr_type != DRR_BEGIN) {
1949                 ZIO_CHECKSUM_BSWAP(&drr->drr_u.drr_checksum.drr_checksum);
1950         }
1951
1952 #undef DO64
1953 #undef DO32
1954 }
1955
1956 static inline uint8_t
1957 deduce_nblkptr(dmu_object_type_t bonus_type, uint64_t bonus_size)
1958 {
1959         if (bonus_type == DMU_OT_SA) {
1960                 return (1);
1961         } else {
1962                 return (1 +
1963                     ((DN_MAX_BONUSLEN - bonus_size) >> SPA_BLKPTRSHIFT));
1964         }
1965 }
1966
1967 static void
1968 save_resume_state(struct receive_writer_arg *rwa,
1969     uint64_t object, uint64_t offset, dmu_tx_t *tx)
1970 {
1971         int txgoff = dmu_tx_get_txg(tx) & TXG_MASK;
1972
1973         if (!rwa->resumable)
1974                 return;
1975
1976         /*
1977          * We use ds_resume_bytes[] != 0 to indicate that we need to
1978          * update this on disk, so it must not be 0.
1979          */
1980         ASSERT(rwa->bytes_read != 0);
1981
1982         /*
1983          * We only resume from write records, which have a valid
1984          * (non-meta-dnode) object number.
1985          */
1986         ASSERT(object != 0);
1987
1988         /*
1989          * For resuming to work correctly, we must receive records in order,
1990          * sorted by object,offset.  This is checked by the callers, but
1991          * assert it here for good measure.
1992          */
1993         ASSERT3U(object, >=, rwa->os->os_dsl_dataset->ds_resume_object[txgoff]);
1994         ASSERT(object != rwa->os->os_dsl_dataset->ds_resume_object[txgoff] ||
1995             offset >= rwa->os->os_dsl_dataset->ds_resume_offset[txgoff]);
1996         ASSERT3U(rwa->bytes_read, >=,
1997             rwa->os->os_dsl_dataset->ds_resume_bytes[txgoff]);
1998
1999         rwa->os->os_dsl_dataset->ds_resume_object[txgoff] = object;
2000         rwa->os->os_dsl_dataset->ds_resume_offset[txgoff] = offset;
2001         rwa->os->os_dsl_dataset->ds_resume_bytes[txgoff] = rwa->bytes_read;
2002 }
2003
2004 static int
2005 receive_object(struct receive_writer_arg *rwa, struct drr_object *drro,
2006     void *data)
2007 {
2008         dmu_object_info_t doi;
2009         dmu_tx_t *tx;
2010         uint64_t object;
2011         int err;
2012
2013         if (drro->drr_type == DMU_OT_NONE ||
2014             !DMU_OT_IS_VALID(drro->drr_type) ||
2015             !DMU_OT_IS_VALID(drro->drr_bonustype) ||
2016             drro->drr_checksumtype >= ZIO_CHECKSUM_FUNCTIONS ||
2017             drro->drr_compress >= ZIO_COMPRESS_FUNCTIONS ||
2018             P2PHASE(drro->drr_blksz, SPA_MINBLOCKSIZE) ||
2019             drro->drr_blksz < SPA_MINBLOCKSIZE ||
2020             drro->drr_blksz > spa_maxblocksize(dmu_objset_spa(rwa->os)) ||
2021             drro->drr_bonuslen > DN_MAX_BONUSLEN) {
2022                 return (SET_ERROR(EINVAL));
2023         }
2024
2025         err = dmu_object_info(rwa->os, drro->drr_object, &doi);
2026
2027         if (err != 0 && err != ENOENT)
2028                 return (SET_ERROR(EINVAL));
2029         object = err == 0 ? drro->drr_object : DMU_NEW_OBJECT;
2030
2031         /*
2032          * If we are losing blkptrs or changing the block size this must
2033          * be a new file instance.  We must clear out the previous file
2034          * contents before we can change this type of metadata in the dnode.
2035          */
2036         if (err == 0) {
2037                 int nblkptr;
2038
2039                 nblkptr = deduce_nblkptr(drro->drr_bonustype,
2040                     drro->drr_bonuslen);
2041
2042                 if (drro->drr_blksz != doi.doi_data_block_size ||
2043                     nblkptr < doi.doi_nblkptr) {
2044                         err = dmu_free_long_range(rwa->os, drro->drr_object,
2045                             0, DMU_OBJECT_END);
2046                         if (err != 0)
2047                                 return (SET_ERROR(EINVAL));
2048                 }
2049         }
2050
2051         tx = dmu_tx_create(rwa->os);
2052         dmu_tx_hold_bonus(tx, object);
2053         err = dmu_tx_assign(tx, TXG_WAIT);
2054         if (err != 0) {
2055                 dmu_tx_abort(tx);
2056                 return (err);
2057         }
2058
2059         if (object == DMU_NEW_OBJECT) {
2060                 /* currently free, want to be allocated */
2061                 err = dmu_object_claim(rwa->os, drro->drr_object,
2062                     drro->drr_type, drro->drr_blksz,
2063                     drro->drr_bonustype, drro->drr_bonuslen, tx);
2064         } else if (drro->drr_type != doi.doi_type ||
2065             drro->drr_blksz != doi.doi_data_block_size ||
2066             drro->drr_bonustype != doi.doi_bonus_type ||
2067             drro->drr_bonuslen != doi.doi_bonus_size) {
2068                 /* currently allocated, but with different properties */
2069                 err = dmu_object_reclaim(rwa->os, drro->drr_object,
2070                     drro->drr_type, drro->drr_blksz,
2071                     drro->drr_bonustype, drro->drr_bonuslen, tx);
2072         }
2073         if (err != 0) {
2074                 dmu_tx_commit(tx);
2075                 return (SET_ERROR(EINVAL));
2076         }
2077
2078         dmu_object_set_checksum(rwa->os, drro->drr_object,
2079             drro->drr_checksumtype, tx);
2080         dmu_object_set_compress(rwa->os, drro->drr_object,
2081             drro->drr_compress, tx);
2082
2083         if (data != NULL) {
2084                 dmu_buf_t *db;
2085
2086                 VERIFY0(dmu_bonus_hold(rwa->os, drro->drr_object, FTAG, &db));
2087                 dmu_buf_will_dirty(db, tx);
2088
2089                 ASSERT3U(db->db_size, >=, drro->drr_bonuslen);
2090                 bcopy(data, db->db_data, drro->drr_bonuslen);
2091                 if (rwa->byteswap) {
2092                         dmu_object_byteswap_t byteswap =
2093                             DMU_OT_BYTESWAP(drro->drr_bonustype);
2094                         dmu_ot_byteswap[byteswap].ob_func(db->db_data,
2095                             drro->drr_bonuslen);
2096                 }
2097                 dmu_buf_rele(db, FTAG);
2098         }
2099         dmu_tx_commit(tx);
2100
2101         return (0);
2102 }
2103
2104 /* ARGSUSED */
2105 static int
2106 receive_freeobjects(struct receive_writer_arg *rwa,
2107     struct drr_freeobjects *drrfo)
2108 {
2109         uint64_t obj;
2110         int next_err = 0;
2111
2112         if (drrfo->drr_firstobj + drrfo->drr_numobjs < drrfo->drr_firstobj)
2113                 return (SET_ERROR(EINVAL));
2114
2115         for (obj = drrfo->drr_firstobj;
2116             obj < drrfo->drr_firstobj + drrfo->drr_numobjs && next_err == 0;
2117             next_err = dmu_object_next(rwa->os, &obj, FALSE, 0)) {
2118                 int err;
2119
2120                 if (dmu_object_info(rwa->os, obj, NULL) != 0)
2121                         continue;
2122
2123                 err = dmu_free_long_object(rwa->os, obj);
2124                 if (err != 0)
2125                         return (err);
2126         }
2127         if (next_err != ESRCH)
2128                 return (next_err);
2129         return (0);
2130 }
2131
2132 static int
2133 receive_write(struct receive_writer_arg *rwa, struct drr_write *drrw,
2134     arc_buf_t *abuf)
2135 {
2136         dmu_tx_t *tx;
2137         int err;
2138
2139         if (drrw->drr_offset + drrw->drr_length < drrw->drr_offset ||
2140             !DMU_OT_IS_VALID(drrw->drr_type))
2141                 return (SET_ERROR(EINVAL));
2142
2143         /*
2144          * For resuming to work, records must be in increasing order
2145          * by (object, offset).
2146          */
2147         if (drrw->drr_object < rwa->last_object ||
2148             (drrw->drr_object == rwa->last_object &&
2149             drrw->drr_offset < rwa->last_offset)) {
2150                 return (SET_ERROR(EINVAL));
2151         }
2152         rwa->last_object = drrw->drr_object;
2153         rwa->last_offset = drrw->drr_offset;
2154
2155         if (dmu_object_info(rwa->os, drrw->drr_object, NULL) != 0)
2156                 return (SET_ERROR(EINVAL));
2157
2158         tx = dmu_tx_create(rwa->os);
2159
2160         dmu_tx_hold_write(tx, drrw->drr_object,
2161             drrw->drr_offset, drrw->drr_length);
2162         err = dmu_tx_assign(tx, TXG_WAIT);
2163         if (err != 0) {
2164                 dmu_tx_abort(tx);
2165                 return (err);
2166         }
2167         if (rwa->byteswap) {
2168                 dmu_object_byteswap_t byteswap =
2169                     DMU_OT_BYTESWAP(drrw->drr_type);
2170                 dmu_ot_byteswap[byteswap].ob_func(abuf->b_data,
2171                     drrw->drr_length);
2172         }
2173
2174         dmu_buf_t *bonus;
2175         if (dmu_bonus_hold(rwa->os, drrw->drr_object, FTAG, &bonus) != 0)
2176                 return (SET_ERROR(EINVAL));
2177         dmu_assign_arcbuf(bonus, drrw->drr_offset, abuf, tx);
2178
2179         /*
2180          * Note: If the receive fails, we want the resume stream to start
2181          * with the same record that we last successfully received (as opposed
2182          * to the next record), so that we can verify that we are
2183          * resuming from the correct location.
2184          */
2185         save_resume_state(rwa, drrw->drr_object, drrw->drr_offset, tx);
2186         dmu_tx_commit(tx);
2187         dmu_buf_rele(bonus, FTAG);
2188
2189         return (0);
2190 }
2191
2192 /*
2193  * Handle a DRR_WRITE_BYREF record.  This record is used in dedup'ed
2194  * streams to refer to a copy of the data that is already on the
2195  * system because it came in earlier in the stream.  This function
2196  * finds the earlier copy of the data, and uses that copy instead of
2197  * data from the stream to fulfill this write.
2198  */
2199 static int
2200 receive_write_byref(struct receive_writer_arg *rwa,
2201     struct drr_write_byref *drrwbr)
2202 {
2203         dmu_tx_t *tx;
2204         int err;
2205         guid_map_entry_t gmesrch;
2206         guid_map_entry_t *gmep;
2207         avl_index_t where;
2208         objset_t *ref_os = NULL;
2209         dmu_buf_t *dbp;
2210
2211         if (drrwbr->drr_offset + drrwbr->drr_length < drrwbr->drr_offset)
2212                 return (SET_ERROR(EINVAL));
2213
2214         /*
2215          * If the GUID of the referenced dataset is different from the
2216          * GUID of the target dataset, find the referenced dataset.
2217          */
2218         if (drrwbr->drr_toguid != drrwbr->drr_refguid) {
2219                 gmesrch.guid = drrwbr->drr_refguid;
2220                 if ((gmep = avl_find(rwa->guid_to_ds_map, &gmesrch,
2221                     &where)) == NULL) {
2222                         return (SET_ERROR(EINVAL));
2223                 }
2224                 if (dmu_objset_from_ds(gmep->gme_ds, &ref_os))
2225                         return (SET_ERROR(EINVAL));
2226         } else {
2227                 ref_os = rwa->os;
2228         }
2229
2230         err = dmu_buf_hold(ref_os, drrwbr->drr_refobject,
2231             drrwbr->drr_refoffset, FTAG, &dbp, DMU_READ_PREFETCH);
2232         if (err != 0)
2233                 return (err);
2234
2235         tx = dmu_tx_create(rwa->os);
2236
2237         dmu_tx_hold_write(tx, drrwbr->drr_object,
2238             drrwbr->drr_offset, drrwbr->drr_length);
2239         err = dmu_tx_assign(tx, TXG_WAIT);
2240         if (err != 0) {
2241                 dmu_tx_abort(tx);
2242                 return (err);
2243         }
2244         dmu_write(rwa->os, drrwbr->drr_object,
2245             drrwbr->drr_offset, drrwbr->drr_length, dbp->db_data, tx);
2246         dmu_buf_rele(dbp, FTAG);
2247
2248         /* See comment in restore_write. */
2249         save_resume_state(rwa, drrwbr->drr_object, drrwbr->drr_offset, tx);
2250         dmu_tx_commit(tx);
2251         return (0);
2252 }
2253
2254 static int
2255 receive_write_embedded(struct receive_writer_arg *rwa,
2256     struct drr_write_embedded *drrwe, void *data)
2257 {
2258         dmu_tx_t *tx;
2259         int err;
2260
2261         if (drrwe->drr_offset + drrwe->drr_length < drrwe->drr_offset)
2262                 return (EINVAL);
2263
2264         if (drrwe->drr_psize > BPE_PAYLOAD_SIZE)
2265                 return (EINVAL);
2266
2267         if (drrwe->drr_etype >= NUM_BP_EMBEDDED_TYPES)
2268                 return (EINVAL);
2269         if (drrwe->drr_compression >= ZIO_COMPRESS_FUNCTIONS)
2270                 return (EINVAL);
2271
2272         tx = dmu_tx_create(rwa->os);
2273
2274         dmu_tx_hold_write(tx, drrwe->drr_object,
2275             drrwe->drr_offset, drrwe->drr_length);
2276         err = dmu_tx_assign(tx, TXG_WAIT);
2277         if (err != 0) {
2278                 dmu_tx_abort(tx);
2279                 return (err);
2280         }
2281
2282         dmu_write_embedded(rwa->os, drrwe->drr_object,
2283             drrwe->drr_offset, data, drrwe->drr_etype,
2284             drrwe->drr_compression, drrwe->drr_lsize, drrwe->drr_psize,
2285             rwa->byteswap ^ ZFS_HOST_BYTEORDER, tx);
2286
2287         /* See comment in restore_write. */
2288         save_resume_state(rwa, drrwe->drr_object, drrwe->drr_offset, tx);
2289         dmu_tx_commit(tx);
2290         return (0);
2291 }
2292
2293 static int
2294 receive_spill(struct receive_writer_arg *rwa, struct drr_spill *drrs,
2295     void *data)
2296 {
2297         dmu_tx_t *tx;
2298         dmu_buf_t *db, *db_spill;
2299         int err;
2300
2301         if (drrs->drr_length < SPA_MINBLOCKSIZE ||
2302             drrs->drr_length > spa_maxblocksize(dmu_objset_spa(rwa->os)))
2303                 return (SET_ERROR(EINVAL));
2304
2305         if (dmu_object_info(rwa->os, drrs->drr_object, NULL) != 0)
2306                 return (SET_ERROR(EINVAL));
2307
2308         VERIFY0(dmu_bonus_hold(rwa->os, drrs->drr_object, FTAG, &db));
2309         if ((err = dmu_spill_hold_by_bonus(db, FTAG, &db_spill)) != 0) {
2310                 dmu_buf_rele(db, FTAG);
2311                 return (err);
2312         }
2313
2314         tx = dmu_tx_create(rwa->os);
2315
2316         dmu_tx_hold_spill(tx, db->db_object);
2317
2318         err = dmu_tx_assign(tx, TXG_WAIT);
2319         if (err != 0) {
2320                 dmu_buf_rele(db, FTAG);
2321                 dmu_buf_rele(db_spill, FTAG);
2322                 dmu_tx_abort(tx);
2323                 return (err);
2324         }
2325         dmu_buf_will_dirty(db_spill, tx);
2326
2327         if (db_spill->db_size < drrs->drr_length)
2328                 VERIFY(0 == dbuf_spill_set_blksz(db_spill,
2329                     drrs->drr_length, tx));
2330         bcopy(data, db_spill->db_data, drrs->drr_length);
2331
2332         dmu_buf_rele(db, FTAG);
2333         dmu_buf_rele(db_spill, FTAG);
2334
2335         dmu_tx_commit(tx);
2336         return (0);
2337 }
2338
2339 /* ARGSUSED */
2340 static int
2341 receive_free(struct receive_writer_arg *rwa, struct drr_free *drrf)
2342 {
2343         int err;
2344
2345         if (drrf->drr_length != -1ULL &&
2346             drrf->drr_offset + drrf->drr_length < drrf->drr_offset)
2347                 return (SET_ERROR(EINVAL));
2348
2349         if (dmu_object_info(rwa->os, drrf->drr_object, NULL) != 0)
2350                 return (SET_ERROR(EINVAL));
2351
2352         err = dmu_free_long_range(rwa->os, drrf->drr_object,
2353             drrf->drr_offset, drrf->drr_length);
2354
2355         return (err);
2356 }
2357
2358 /* used to destroy the drc_ds on error */
2359 static void
2360 dmu_recv_cleanup_ds(dmu_recv_cookie_t *drc)
2361 {
2362         if (drc->drc_resumable) {
2363                 /* wait for our resume state to be written to disk */
2364                 txg_wait_synced(drc->drc_ds->ds_dir->dd_pool, 0);
2365                 dsl_dataset_disown(drc->drc_ds, dmu_recv_tag);
2366         } else {
2367                 char name[MAXNAMELEN];
2368                 dsl_dataset_name(drc->drc_ds, name);
2369                 dsl_dataset_disown(drc->drc_ds, dmu_recv_tag);
2370                 (void) dsl_destroy_head(name);
2371         }
2372 }
2373
2374 static void
2375 receive_cksum(struct receive_arg *ra, int len, void *buf)
2376 {
2377         if (ra->byteswap) {
2378                 fletcher_4_incremental_byteswap(buf, len, &ra->cksum);
2379         } else {
2380                 fletcher_4_incremental_native(buf, len, &ra->cksum);
2381         }
2382 }
2383
2384 /*
2385  * Read the payload into a buffer of size len, and update the current record's
2386  * payload field.
2387  * Allocate ra->next_rrd and read the next record's header into
2388  * ra->next_rrd->header.
2389  * Verify checksum of payload and next record.
2390  */
2391 static int
2392 receive_read_payload_and_next_header(struct receive_arg *ra, int len, void *buf)
2393 {
2394         int err;
2395
2396         if (len != 0) {
2397                 ASSERT3U(len, <=, SPA_MAXBLOCKSIZE);
2398                 err = receive_read(ra, len, buf);
2399                 if (err != 0)
2400                         return (err);
2401                 receive_cksum(ra, len, buf);
2402
2403                 /* note: rrd is NULL when reading the begin record's payload */
2404                 if (ra->rrd != NULL) {
2405                         ra->rrd->payload = buf;
2406                         ra->rrd->payload_size = len;
2407                         ra->rrd->bytes_read = ra->bytes_read;
2408                 }
2409         }
2410
2411         ra->prev_cksum = ra->cksum;
2412
2413         ra->next_rrd = kmem_zalloc(sizeof (*ra->next_rrd), KM_SLEEP);
2414         err = receive_read(ra, sizeof (ra->next_rrd->header),
2415             &ra->next_rrd->header);
2416         ra->next_rrd->bytes_read = ra->bytes_read;
2417         if (err != 0) {
2418                 kmem_free(ra->next_rrd, sizeof (*ra->next_rrd));
2419                 ra->next_rrd = NULL;
2420                 return (err);
2421         }
2422         if (ra->next_rrd->header.drr_type == DRR_BEGIN) {
2423                 kmem_free(ra->next_rrd, sizeof (*ra->next_rrd));
2424                 ra->next_rrd = NULL;
2425                 return (SET_ERROR(EINVAL));
2426         }
2427
2428         /*
2429          * Note: checksum is of everything up to but not including the
2430          * checksum itself.
2431          */
2432         ASSERT3U(offsetof(dmu_replay_record_t, drr_u.drr_checksum.drr_checksum),
2433             ==, sizeof (dmu_replay_record_t) - sizeof (zio_cksum_t));
2434         receive_cksum(ra,
2435             offsetof(dmu_replay_record_t, drr_u.drr_checksum.drr_checksum),
2436             &ra->next_rrd->header);
2437
2438         zio_cksum_t cksum_orig =
2439             ra->next_rrd->header.drr_u.drr_checksum.drr_checksum;
2440         zio_cksum_t *cksump =
2441             &ra->next_rrd->header.drr_u.drr_checksum.drr_checksum;
2442
2443         if (ra->byteswap)
2444                 byteswap_record(&ra->next_rrd->header);
2445
2446         if ((!ZIO_CHECKSUM_IS_ZERO(cksump)) &&
2447             !ZIO_CHECKSUM_EQUAL(ra->cksum, *cksump)) {
2448                 kmem_free(ra->next_rrd, sizeof (*ra->next_rrd));
2449                 ra->next_rrd = NULL;
2450                 return (SET_ERROR(ECKSUM));
2451         }
2452
2453         receive_cksum(ra, sizeof (cksum_orig), &cksum_orig);
2454
2455         return (0);
2456 }
2457
2458 static void
2459 objlist_create(struct objlist *list)
2460 {
2461         list_create(&list->list, sizeof (struct receive_objnode),
2462             offsetof(struct receive_objnode, node));
2463         list->last_lookup = 0;
2464 }
2465
2466 static void
2467 objlist_destroy(struct objlist *list)
2468 {
2469         for (struct receive_objnode *n = list_remove_head(&list->list);
2470             n != NULL; n = list_remove_head(&list->list)) {
2471                 kmem_free(n, sizeof (*n));
2472         }
2473         list_destroy(&list->list);
2474 }
2475
2476 /*
2477  * This function looks through the objlist to see if the specified object number
2478  * is contained in the objlist.  In the process, it will remove all object
2479  * numbers in the list that are smaller than the specified object number.  Thus,
2480  * any lookup of an object number smaller than a previously looked up object
2481  * number will always return false; therefore, all lookups should be done in
2482  * ascending order.
2483  */
2484 static boolean_t
2485 objlist_exists(struct objlist *list, uint64_t object)
2486 {
2487         struct receive_objnode *node = list_head(&list->list);
2488         ASSERT3U(object, >=, list->last_lookup);
2489         list->last_lookup = object;
2490         while (node != NULL && node->object < object) {
2491                 VERIFY3P(node, ==, list_remove_head(&list->list));
2492                 kmem_free(node, sizeof (*node));
2493                 node = list_head(&list->list);
2494         }
2495         return (node != NULL && node->object == object);
2496 }
2497
2498 /*
2499  * The objlist is a list of object numbers stored in ascending order.  However,
2500  * the insertion of new object numbers does not seek out the correct location to
2501  * store a new object number; instead, it appends it to the list for simplicity.
2502  * Thus, any users must take care to only insert new object numbers in ascending
2503  * order.
2504  */
2505 static void
2506 objlist_insert(struct objlist *list, uint64_t object)
2507 {
2508         struct receive_objnode *node = kmem_zalloc(sizeof (*node), KM_SLEEP);
2509         node->object = object;
2510 #ifdef ZFS_DEBUG
2511         struct receive_objnode *last_object = list_tail(&list->list);
2512         uint64_t last_objnum = (last_object != NULL ? last_object->object : 0);
2513         ASSERT3U(node->object, >, last_objnum);
2514 #endif
2515         list_insert_tail(&list->list, node);
2516 }
2517
2518 /*
2519  * Issue the prefetch reads for any necessary indirect blocks.
2520  *
2521  * We use the object ignore list to tell us whether or not to issue prefetches
2522  * for a given object.  We do this for both correctness (in case the blocksize
2523  * of an object has changed) and performance (if the object doesn't exist, don't
2524  * needlessly try to issue prefetches).  We also trim the list as we go through
2525  * the stream to prevent it from growing to an unbounded size.
2526  *
2527  * The object numbers within will always be in sorted order, and any write
2528  * records we see will also be in sorted order, but they're not sorted with
2529  * respect to each other (i.e. we can get several object records before
2530  * receiving each object's write records).  As a result, once we've reached a
2531  * given object number, we can safely remove any reference to lower object
2532  * numbers in the ignore list. In practice, we receive up to 32 object records
2533  * before receiving write records, so the list can have up to 32 nodes in it.
2534  */
2535 /* ARGSUSED */
2536 static void
2537 receive_read_prefetch(struct receive_arg *ra,
2538     uint64_t object, uint64_t offset, uint64_t length)
2539 {
2540         if (!objlist_exists(&ra->ignore_objlist, object)) {
2541                 dmu_prefetch(ra->os, object, 1, offset, length,
2542                     ZIO_PRIORITY_SYNC_READ);
2543         }
2544 }
2545
2546 /*
2547  * Read records off the stream, issuing any necessary prefetches.
2548  */
2549 static int
2550 receive_read_record(struct receive_arg *ra)
2551 {
2552         int err;
2553
2554         switch (ra->rrd->header.drr_type) {
2555         case DRR_OBJECT:
2556         {
2557                 struct drr_object *drro = &ra->rrd->header.drr_u.drr_object;
2558                 uint32_t size = P2ROUNDUP(drro->drr_bonuslen, 8);
2559                 void *buf = kmem_zalloc(size, KM_SLEEP);
2560                 dmu_object_info_t doi;
2561                 err = receive_read_payload_and_next_header(ra, size, buf);
2562                 if (err != 0) {
2563                         kmem_free(buf, size);
2564                         return (err);
2565                 }
2566                 err = dmu_object_info(ra->os, drro->drr_object, &doi);
2567                 /*
2568                  * See receive_read_prefetch for an explanation why we're
2569                  * storing this object in the ignore_obj_list.
2570                  */
2571                 if (err == ENOENT ||
2572                     (err == 0 && doi.doi_data_block_size != drro->drr_blksz)) {
2573                         objlist_insert(&ra->ignore_objlist, drro->drr_object);
2574                         err = 0;
2575                 }
2576                 return (err);
2577         }
2578         case DRR_FREEOBJECTS:
2579         {
2580                 err = receive_read_payload_and_next_header(ra, 0, NULL);
2581                 return (err);
2582         }
2583         case DRR_WRITE:
2584         {
2585                 struct drr_write *drrw = &ra->rrd->header.drr_u.drr_write;
2586                 arc_buf_t *abuf = arc_loan_buf(dmu_objset_spa(ra->os),
2587                     drrw->drr_length);
2588
2589                 err = receive_read_payload_and_next_header(ra,
2590                     drrw->drr_length, abuf->b_data);
2591                 if (err != 0) {
2592                         dmu_return_arcbuf(abuf);
2593                         return (err);
2594                 }
2595                 ra->rrd->write_buf = abuf;
2596                 receive_read_prefetch(ra, drrw->drr_object, drrw->drr_offset,
2597                     drrw->drr_length);
2598                 return (err);
2599         }
2600         case DRR_WRITE_BYREF:
2601         {
2602                 struct drr_write_byref *drrwb =
2603                     &ra->rrd->header.drr_u.drr_write_byref;
2604                 err = receive_read_payload_and_next_header(ra, 0, NULL);
2605                 receive_read_prefetch(ra, drrwb->drr_object, drrwb->drr_offset,
2606                     drrwb->drr_length);
2607                 return (err);
2608         }
2609         case DRR_WRITE_EMBEDDED:
2610         {
2611                 struct drr_write_embedded *drrwe =
2612                     &ra->rrd->header.drr_u.drr_write_embedded;
2613                 uint32_t size = P2ROUNDUP(drrwe->drr_psize, 8);
2614                 void *buf = kmem_zalloc(size, KM_SLEEP);
2615
2616                 err = receive_read_payload_and_next_header(ra, size, buf);
2617                 if (err != 0) {
2618                         kmem_free(buf, size);
2619                         return (err);
2620                 }
2621
2622                 receive_read_prefetch(ra, drrwe->drr_object, drrwe->drr_offset,
2623                     drrwe->drr_length);
2624                 return (err);
2625         }
2626         case DRR_FREE:
2627         {
2628                 /*
2629                  * It might be beneficial to prefetch indirect blocks here, but
2630                  * we don't really have the data to decide for sure.
2631                  */
2632                 err = receive_read_payload_and_next_header(ra, 0, NULL);
2633                 return (err);
2634         }
2635         case DRR_END:
2636         {
2637                 struct drr_end *drre = &ra->rrd->header.drr_u.drr_end;
2638                 if (!ZIO_CHECKSUM_EQUAL(ra->prev_cksum, drre->drr_checksum))
2639                         return (SET_ERROR(ECKSUM));
2640                 return (0);
2641         }
2642         case DRR_SPILL:
2643         {
2644                 struct drr_spill *drrs = &ra->rrd->header.drr_u.drr_spill;
2645                 void *buf = kmem_zalloc(drrs->drr_length, KM_SLEEP);
2646                 err = receive_read_payload_and_next_header(ra, drrs->drr_length,
2647                     buf);
2648                 if (err != 0)
2649                         kmem_free(buf, drrs->drr_length);
2650                 return (err);
2651         }
2652         default:
2653                 return (SET_ERROR(EINVAL));
2654         }
2655 }
2656
2657 /*
2658  * Commit the records to the pool.
2659  */
2660 static int
2661 receive_process_record(struct receive_writer_arg *rwa,
2662     struct receive_record_arg *rrd)
2663 {
2664         int err;
2665
2666         /* Processing in order, therefore bytes_read should be increasing. */
2667         ASSERT3U(rrd->bytes_read, >=, rwa->bytes_read);
2668         rwa->bytes_read = rrd->bytes_read;
2669
2670         switch (rrd->header.drr_type) {
2671         case DRR_OBJECT:
2672         {
2673                 struct drr_object *drro = &rrd->header.drr_u.drr_object;
2674                 err = receive_object(rwa, drro, rrd->payload);
2675                 kmem_free(rrd->payload, rrd->payload_size);
2676                 rrd->payload = NULL;
2677                 return (err);
2678         }
2679         case DRR_FREEOBJECTS:
2680         {
2681                 struct drr_freeobjects *drrfo =
2682                     &rrd->header.drr_u.drr_freeobjects;
2683                 return (receive_freeobjects(rwa, drrfo));
2684         }
2685         case DRR_WRITE:
2686         {
2687                 struct drr_write *drrw = &rrd->header.drr_u.drr_write;
2688                 err = receive_write(rwa, drrw, rrd->write_buf);
2689                 /* if receive_write() is successful, it consumes the arc_buf */
2690                 if (err != 0)
2691                         dmu_return_arcbuf(rrd->write_buf);
2692                 rrd->write_buf = NULL;
2693                 rrd->payload = NULL;
2694                 return (err);
2695         }
2696         case DRR_WRITE_BYREF:
2697         {
2698                 struct drr_write_byref *drrwbr =
2699                     &rrd->header.drr_u.drr_write_byref;
2700                 return (receive_write_byref(rwa, drrwbr));
2701         }
2702         case DRR_WRITE_EMBEDDED:
2703         {
2704                 struct drr_write_embedded *drrwe =
2705                     &rrd->header.drr_u.drr_write_embedded;
2706                 err = receive_write_embedded(rwa, drrwe, rrd->payload);
2707                 kmem_free(rrd->payload, rrd->payload_size);
2708                 rrd->payload = NULL;
2709                 return (err);
2710         }
2711         case DRR_FREE:
2712         {
2713                 struct drr_free *drrf = &rrd->header.drr_u.drr_free;
2714                 return (receive_free(rwa, drrf));
2715         }
2716         case DRR_SPILL:
2717         {
2718                 struct drr_spill *drrs = &rrd->header.drr_u.drr_spill;
2719                 err = receive_spill(rwa, drrs, rrd->payload);
2720                 kmem_free(rrd->payload, rrd->payload_size);
2721                 rrd->payload = NULL;
2722                 return (err);
2723         }
2724         default:
2725                 return (SET_ERROR(EINVAL));
2726         }
2727 }
2728
2729 /*
2730  * dmu_recv_stream's worker thread; pull records off the queue, and then call
2731  * receive_process_record  When we're done, signal the main thread and exit.
2732  */
2733 static void
2734 receive_writer_thread(void *arg)
2735 {
2736         struct receive_writer_arg *rwa = arg;
2737         struct receive_record_arg *rrd;
2738         for (rrd = bqueue_dequeue(&rwa->q); !rrd->eos_marker;
2739             rrd = bqueue_dequeue(&rwa->q)) {
2740                 /*
2741                  * If there's an error, the main thread will stop putting things
2742                  * on the queue, but we need to clear everything in it before we
2743                  * can exit.
2744                  */
2745                 if (rwa->err == 0) {
2746                         rwa->err = receive_process_record(rwa, rrd);
2747                 } else if (rrd->write_buf != NULL) {
2748                         dmu_return_arcbuf(rrd->write_buf);
2749                         rrd->write_buf = NULL;
2750                         rrd->payload = NULL;
2751                 } else if (rrd->payload != NULL) {
2752                         kmem_free(rrd->payload, rrd->payload_size);
2753                         rrd->payload = NULL;
2754                 }
2755                 kmem_free(rrd, sizeof (*rrd));
2756         }
2757         kmem_free(rrd, sizeof (*rrd));
2758         mutex_enter(&rwa->mutex);
2759         rwa->done = B_TRUE;
2760         cv_signal(&rwa->cv);
2761         mutex_exit(&rwa->mutex);
2762         thread_exit();
2763 }
2764
2765 static int
2766 resume_check(struct receive_arg *ra, nvlist_t *begin_nvl)
2767 {
2768         uint64_t val;
2769         objset_t *mos = dmu_objset_pool(ra->os)->dp_meta_objset;
2770         uint64_t dsobj = dmu_objset_id(ra->os);
2771         uint64_t resume_obj, resume_off;
2772
2773         if (nvlist_lookup_uint64(begin_nvl,
2774             "resume_object", &resume_obj) != 0 ||
2775             nvlist_lookup_uint64(begin_nvl,
2776             "resume_offset", &resume_off) != 0) {
2777                 return (SET_ERROR(EINVAL));
2778         }
2779         VERIFY0(zap_lookup(mos, dsobj,
2780             DS_FIELD_RESUME_OBJECT, sizeof (val), 1, &val));
2781         if (resume_obj != val)
2782                 return (SET_ERROR(EINVAL));
2783         VERIFY0(zap_lookup(mos, dsobj,
2784             DS_FIELD_RESUME_OFFSET, sizeof (val), 1, &val));
2785         if (resume_off != val)
2786                 return (SET_ERROR(EINVAL));
2787
2788         return (0);
2789 }
2790
2791 /*
2792  * Read in the stream's records, one by one, and apply them to the pool.  There
2793  * are two threads involved; the thread that calls this function will spin up a
2794  * worker thread, read the records off the stream one by one, and issue
2795  * prefetches for any necessary indirect blocks.  It will then push the records
2796  * onto an internal blocking queue.  The worker thread will pull the records off
2797  * the queue, and actually write the data into the DMU.  This way, the worker
2798  * thread doesn't have to wait for reads to complete, since everything it needs
2799  * (the indirect blocks) will be prefetched.
2800  *
2801  * NB: callers *must* call dmu_recv_end() if this succeeds.
2802  */
2803 int
2804 dmu_recv_stream(dmu_recv_cookie_t *drc, struct file *fp, offset_t *voffp,
2805     int cleanup_fd, uint64_t *action_handlep)
2806 {
2807         int err = 0;
2808         struct receive_arg ra = { 0 };
2809         struct receive_writer_arg rwa = { 0 };
2810         int featureflags;
2811         nvlist_t *begin_nvl = NULL;
2812
2813         ra.byteswap = drc->drc_byteswap;
2814         ra.cksum = drc->drc_cksum;
2815         ra.td = curthread;
2816         ra.fp = fp;
2817         ra.voff = *voffp;
2818
2819         if (dsl_dataset_is_zapified(drc->drc_ds)) {
2820                 (void) zap_lookup(drc->drc_ds->ds_dir->dd_pool->dp_meta_objset,
2821                     drc->drc_ds->ds_object, DS_FIELD_RESUME_BYTES,
2822                     sizeof (ra.bytes_read), 1, &ra.bytes_read);
2823         }
2824
2825         objlist_create(&ra.ignore_objlist);
2826
2827         /* these were verified in dmu_recv_begin */
2828         ASSERT3U(DMU_GET_STREAM_HDRTYPE(drc->drc_drrb->drr_versioninfo), ==,
2829             DMU_SUBSTREAM);
2830         ASSERT3U(drc->drc_drrb->drr_type, <, DMU_OST_NUMTYPES);
2831
2832         /*
2833          * Open the objset we are modifying.
2834          */
2835         VERIFY0(dmu_objset_from_ds(drc->drc_ds, &ra.os));
2836
2837         ASSERT(dsl_dataset_phys(drc->drc_ds)->ds_flags & DS_FLAG_INCONSISTENT);
2838
2839         featureflags = DMU_GET_FEATUREFLAGS(drc->drc_drrb->drr_versioninfo);
2840
2841         /* if this stream is dedup'ed, set up the avl tree for guid mapping */
2842         if (featureflags & DMU_BACKUP_FEATURE_DEDUP) {
2843                 minor_t minor;
2844
2845                 if (cleanup_fd == -1) {
2846                         ra.err = SET_ERROR(EBADF);
2847                         goto out;
2848                 }
2849                 ra.err = zfs_onexit_fd_hold(cleanup_fd, &minor);
2850                 if (ra.err != 0) {
2851                         cleanup_fd = -1;
2852                         goto out;
2853                 }
2854
2855                 if (*action_handlep == 0) {
2856                         rwa.guid_to_ds_map =
2857                             kmem_alloc(sizeof (avl_tree_t), KM_SLEEP);
2858                         avl_create(rwa.guid_to_ds_map, guid_compare,
2859                             sizeof (guid_map_entry_t),
2860                             offsetof(guid_map_entry_t, avlnode));
2861                         err = zfs_onexit_add_cb(minor,
2862                             free_guid_map_onexit, rwa.guid_to_ds_map,
2863                             action_handlep);
2864                         if (ra.err != 0)
2865                                 goto out;
2866                 } else {
2867                         err = zfs_onexit_cb_data(minor, *action_handlep,
2868                             (void **)&rwa.guid_to_ds_map);
2869                         if (ra.err != 0)
2870                                 goto out;
2871                 }
2872
2873                 drc->drc_guid_to_ds_map = rwa.guid_to_ds_map;
2874         }
2875
2876         uint32_t payloadlen = drc->drc_drr_begin->drr_payloadlen;
2877         void *payload = NULL;
2878         if (payloadlen != 0)
2879                 payload = kmem_alloc(payloadlen, KM_SLEEP);
2880
2881         err = receive_read_payload_and_next_header(&ra, payloadlen, payload);
2882         if (err != 0) {
2883                 if (payloadlen != 0)
2884                         kmem_free(payload, payloadlen);
2885                 goto out;
2886         }
2887         if (payloadlen != 0) {
2888                 err = nvlist_unpack(payload, payloadlen, &begin_nvl, KM_SLEEP);
2889                 kmem_free(payload, payloadlen);
2890                 if (err != 0)
2891                         goto out;
2892         }
2893
2894         if (featureflags & DMU_BACKUP_FEATURE_RESUMING) {
2895                 err = resume_check(&ra, begin_nvl);
2896                 if (err != 0)
2897                         goto out;
2898         }
2899
2900         (void) bqueue_init(&rwa.q, zfs_recv_queue_length,
2901             offsetof(struct receive_record_arg, node));
2902         cv_init(&rwa.cv, NULL, CV_DEFAULT, NULL);
2903         mutex_init(&rwa.mutex, NULL, MUTEX_DEFAULT, NULL);
2904         rwa.os = ra.os;
2905         rwa.byteswap = drc->drc_byteswap;
2906         rwa.resumable = drc->drc_resumable;
2907
2908         (void) thread_create(NULL, 0, receive_writer_thread, &rwa, 0, &p0,
2909             TS_RUN, minclsyspri);
2910         /*
2911          * We're reading rwa.err without locks, which is safe since we are the
2912          * only reader, and the worker thread is the only writer.  It's ok if we
2913          * miss a write for an iteration or two of the loop, since the writer
2914          * thread will keep freeing records we send it until we send it an eos
2915          * marker.
2916          *
2917          * We can leave this loop in 3 ways:  First, if rwa.err is
2918          * non-zero.  In that case, the writer thread will free the rrd we just
2919          * pushed.  Second, if  we're interrupted; in that case, either it's the
2920          * first loop and ra.rrd was never allocated, or it's later, and ra.rrd
2921          * has been handed off to the writer thread who will free it.  Finally,
2922          * if receive_read_record fails or we're at the end of the stream, then
2923          * we free ra.rrd and exit.
2924          */
2925         while (rwa.err == 0) {
2926                 if (issig(JUSTLOOKING) && issig(FORREAL)) {
2927                         err = SET_ERROR(EINTR);
2928                         break;
2929                 }
2930
2931                 ASSERT3P(ra.rrd, ==, NULL);
2932                 ra.rrd = ra.next_rrd;
2933                 ra.next_rrd = NULL;
2934                 /* Allocates and loads header into ra.next_rrd */
2935                 err = receive_read_record(&ra);
2936
2937                 if (ra.rrd->header.drr_type == DRR_END || err != 0) {
2938                         kmem_free(ra.rrd, sizeof (*ra.rrd));
2939                         ra.rrd = NULL;
2940                         break;
2941                 }
2942
2943                 bqueue_enqueue(&rwa.q, ra.rrd,
2944                     sizeof (struct receive_record_arg) + ra.rrd->payload_size);
2945                 ra.rrd = NULL;
2946         }
2947         if (ra.next_rrd == NULL)
2948                 ra.next_rrd = kmem_zalloc(sizeof (*ra.next_rrd), KM_SLEEP);
2949         ra.next_rrd->eos_marker = B_TRUE;
2950         bqueue_enqueue(&rwa.q, ra.next_rrd, 1);
2951
2952         mutex_enter(&rwa.mutex);
2953         while (!rwa.done) {
2954                 cv_wait(&rwa.cv, &rwa.mutex);
2955         }
2956         mutex_exit(&rwa.mutex);
2957
2958         cv_destroy(&rwa.cv);
2959         mutex_destroy(&rwa.mutex);
2960         bqueue_destroy(&rwa.q);
2961         if (err == 0)
2962                 err = rwa.err;
2963
2964 out:
2965         nvlist_free(begin_nvl);
2966         if ((featureflags & DMU_BACKUP_FEATURE_DEDUP) && (cleanup_fd != -1))
2967                 zfs_onexit_fd_rele(cleanup_fd);
2968
2969         if (err != 0) {
2970                 /*
2971                  * Clean up references. If receive is not resumable,
2972                  * destroy what we created, so we don't leave it in
2973                  * the inconsistent state.
2974                  */
2975                 dmu_recv_cleanup_ds(drc);
2976         }
2977
2978         *voffp = ra.voff;
2979         objlist_destroy(&ra.ignore_objlist);
2980         return (err);
2981 }
2982
2983 static int
2984 dmu_recv_end_check(void *arg, dmu_tx_t *tx)
2985 {
2986         dmu_recv_cookie_t *drc = arg;
2987         dsl_pool_t *dp = dmu_tx_pool(tx);
2988         int error;
2989
2990         ASSERT3P(drc->drc_ds->ds_owner, ==, dmu_recv_tag);
2991
2992         if (!drc->drc_newfs) {
2993                 dsl_dataset_t *origin_head;
2994
2995                 error = dsl_dataset_hold(dp, drc->drc_tofs, FTAG, &origin_head);
2996                 if (error != 0)
2997                         return (error);
2998                 if (drc->drc_force) {
2999                         /*
3000                          * We will destroy any snapshots in tofs (i.e. before
3001                          * origin_head) that are after the origin (which is
3002                          * the snap before drc_ds, because drc_ds can not
3003                          * have any snaps of its own).
3004                          */
3005                         uint64_t obj;
3006
3007                         obj = dsl_dataset_phys(origin_head)->ds_prev_snap_obj;
3008                         while (obj !=
3009                             dsl_dataset_phys(drc->drc_ds)->ds_prev_snap_obj) {
3010                                 dsl_dataset_t *snap;
3011                                 error = dsl_dataset_hold_obj(dp, obj, FTAG,
3012                                     &snap);
3013                                 if (error != 0)
3014                                         break;
3015                                 if (snap->ds_dir != origin_head->ds_dir)
3016                                         error = SET_ERROR(EINVAL);
3017                                 if (error == 0)  {
3018                                         error = dsl_destroy_snapshot_check_impl(
3019                                             snap, B_FALSE);
3020                                 }
3021                                 obj = dsl_dataset_phys(snap)->ds_prev_snap_obj;
3022                                 dsl_dataset_rele(snap, FTAG);
3023                                 if (error != 0)
3024                                         break;
3025                         }
3026                         if (error != 0) {
3027                                 dsl_dataset_rele(origin_head, FTAG);
3028                                 return (error);
3029                         }
3030                 }
3031                 error = dsl_dataset_clone_swap_check_impl(drc->drc_ds,
3032                     origin_head, drc->drc_force, drc->drc_owner, tx);
3033                 if (error != 0) {
3034                         dsl_dataset_rele(origin_head, FTAG);
3035                         return (error);
3036                 }
3037                 error = dsl_dataset_snapshot_check_impl(origin_head,
3038                     drc->drc_tosnap, tx, B_TRUE, 1, drc->drc_cred);
3039                 dsl_dataset_rele(origin_head, FTAG);
3040                 if (error != 0)
3041                         return (error);
3042
3043                 error = dsl_destroy_head_check_impl(drc->drc_ds, 1);
3044         } else {
3045                 error = dsl_dataset_snapshot_check_impl(drc->drc_ds,
3046                     drc->drc_tosnap, tx, B_TRUE, 1, drc->drc_cred);
3047         }
3048         return (error);
3049 }
3050
3051 static void
3052 dmu_recv_end_sync(void *arg, dmu_tx_t *tx)
3053 {
3054         dmu_recv_cookie_t *drc = arg;
3055         dsl_pool_t *dp = dmu_tx_pool(tx);
3056
3057         spa_history_log_internal_ds(drc->drc_ds, "finish receiving",
3058             tx, "snap=%s", drc->drc_tosnap);
3059
3060         if (!drc->drc_newfs) {
3061                 dsl_dataset_t *origin_head;
3062
3063                 VERIFY0(dsl_dataset_hold(dp, drc->drc_tofs, FTAG,
3064                     &origin_head));
3065
3066                 if (drc->drc_force) {
3067                         /*
3068                          * Destroy any snapshots of drc_tofs (origin_head)
3069                          * after the origin (the snap before drc_ds).
3070                          */
3071                         uint64_t obj;
3072
3073                         obj = dsl_dataset_phys(origin_head)->ds_prev_snap_obj;
3074                         while (obj !=
3075                             dsl_dataset_phys(drc->drc_ds)->ds_prev_snap_obj) {
3076                                 dsl_dataset_t *snap;
3077                                 VERIFY0(dsl_dataset_hold_obj(dp, obj, FTAG,
3078                                     &snap));
3079                                 ASSERT3P(snap->ds_dir, ==, origin_head->ds_dir);
3080                                 obj = dsl_dataset_phys(snap)->ds_prev_snap_obj;
3081                                 dsl_destroy_snapshot_sync_impl(snap,
3082                                     B_FALSE, tx);
3083                                 dsl_dataset_rele(snap, FTAG);
3084                         }
3085                 }
3086                 VERIFY3P(drc->drc_ds->ds_prev, ==,
3087                     origin_head->ds_prev);
3088
3089                 dsl_dataset_clone_swap_sync_impl(drc->drc_ds,
3090                     origin_head, tx);
3091                 dsl_dataset_snapshot_sync_impl(origin_head,
3092                     drc->drc_tosnap, tx);
3093
3094                 /* set snapshot's creation time and guid */
3095                 dmu_buf_will_dirty(origin_head->ds_prev->ds_dbuf, tx);
3096                 dsl_dataset_phys(origin_head->ds_prev)->ds_creation_time =
3097                     drc->drc_drrb->drr_creation_time;
3098                 dsl_dataset_phys(origin_head->ds_prev)->ds_guid =
3099                     drc->drc_drrb->drr_toguid;
3100                 dsl_dataset_phys(origin_head->ds_prev)->ds_flags &=
3101                     ~DS_FLAG_INCONSISTENT;
3102
3103                 dmu_buf_will_dirty(origin_head->ds_dbuf, tx);
3104                 dsl_dataset_phys(origin_head)->ds_flags &=
3105                     ~DS_FLAG_INCONSISTENT;
3106
3107                 dsl_dataset_rele(origin_head, FTAG);
3108                 dsl_destroy_head_sync_impl(drc->drc_ds, tx);
3109
3110                 if (drc->drc_owner != NULL)
3111                         VERIFY3P(origin_head->ds_owner, ==, drc->drc_owner);
3112         } else {
3113                 dsl_dataset_t *ds = drc->drc_ds;
3114
3115                 dsl_dataset_snapshot_sync_impl(ds, drc->drc_tosnap, tx);
3116
3117                 /* set snapshot's creation time and guid */
3118                 dmu_buf_will_dirty(ds->ds_prev->ds_dbuf, tx);
3119                 dsl_dataset_phys(ds->ds_prev)->ds_creation_time =
3120                     drc->drc_drrb->drr_creation_time;
3121                 dsl_dataset_phys(ds->ds_prev)->ds_guid =
3122                     drc->drc_drrb->drr_toguid;
3123                 dsl_dataset_phys(ds->ds_prev)->ds_flags &=
3124                     ~DS_FLAG_INCONSISTENT;
3125
3126                 dmu_buf_will_dirty(ds->ds_dbuf, tx);
3127                 dsl_dataset_phys(ds)->ds_flags &= ~DS_FLAG_INCONSISTENT;
3128                 if (dsl_dataset_has_resume_receive_state(ds)) {
3129                         (void) zap_remove(dp->dp_meta_objset, ds->ds_object,
3130                             DS_FIELD_RESUME_FROMGUID, tx);
3131                         (void) zap_remove(dp->dp_meta_objset, ds->ds_object,
3132                             DS_FIELD_RESUME_OBJECT, tx);
3133                         (void) zap_remove(dp->dp_meta_objset, ds->ds_object,
3134                             DS_FIELD_RESUME_OFFSET, tx);
3135                         (void) zap_remove(dp->dp_meta_objset, ds->ds_object,
3136                             DS_FIELD_RESUME_BYTES, tx);
3137                         (void) zap_remove(dp->dp_meta_objset, ds->ds_object,
3138                             DS_FIELD_RESUME_TOGUID, tx);
3139                         (void) zap_remove(dp->dp_meta_objset, ds->ds_object,
3140                             DS_FIELD_RESUME_TONAME, tx);
3141                 }
3142         }
3143         drc->drc_newsnapobj = dsl_dataset_phys(drc->drc_ds)->ds_prev_snap_obj;
3144         /*
3145          * Release the hold from dmu_recv_begin.  This must be done before
3146          * we return to open context, so that when we free the dataset's dnode,
3147          * we can evict its bonus buffer.
3148          */
3149         dsl_dataset_disown(drc->drc_ds, dmu_recv_tag);
3150         drc->drc_ds = NULL;
3151 }
3152
3153 static int
3154 add_ds_to_guidmap(const char *name, avl_tree_t *guid_map, uint64_t snapobj)
3155 {
3156         dsl_pool_t *dp;
3157         dsl_dataset_t *snapds;
3158         guid_map_entry_t *gmep;
3159         int err;
3160
3161         ASSERT(guid_map != NULL);
3162
3163         err = dsl_pool_hold(name, FTAG, &dp);
3164         if (err != 0)
3165                 return (err);
3166         gmep = kmem_alloc(sizeof (*gmep), KM_SLEEP);
3167         err = dsl_dataset_hold_obj(dp, snapobj, gmep, &snapds);
3168         if (err == 0) {
3169                 gmep->guid = dsl_dataset_phys(snapds)->ds_guid;
3170                 gmep->gme_ds = snapds;
3171                 avl_add(guid_map, gmep);
3172                 dsl_dataset_long_hold(snapds, gmep);
3173         } else
3174                 kmem_free(gmep, sizeof (*gmep));
3175
3176         dsl_pool_rele(dp, FTAG);
3177         return (err);
3178 }
3179
3180 static int dmu_recv_end_modified_blocks = 3;
3181
3182 static int
3183 dmu_recv_existing_end(dmu_recv_cookie_t *drc)
3184 {
3185         int error;
3186         char name[MAXNAMELEN];
3187
3188 #ifdef _KERNEL
3189         /*
3190          * We will be destroying the ds; make sure its origin is unmounted if
3191          * necessary.
3192          */
3193         dsl_dataset_name(drc->drc_ds, name);
3194         zfs_destroy_unmount_origin(name);
3195 #endif
3196
3197         error = dsl_sync_task(drc->drc_tofs,
3198             dmu_recv_end_check, dmu_recv_end_sync, drc,
3199             dmu_recv_end_modified_blocks, ZFS_SPACE_CHECK_NORMAL);
3200
3201         if (error != 0)
3202                 dmu_recv_cleanup_ds(drc);
3203         return (error);
3204 }
3205
3206 static int
3207 dmu_recv_new_end(dmu_recv_cookie_t *drc)
3208 {
3209         int error;
3210
3211         error = dsl_sync_task(drc->drc_tofs,
3212             dmu_recv_end_check, dmu_recv_end_sync, drc,
3213             dmu_recv_end_modified_blocks, ZFS_SPACE_CHECK_NORMAL);
3214
3215         if (error != 0) {
3216                 dmu_recv_cleanup_ds(drc);
3217         } else if (drc->drc_guid_to_ds_map != NULL) {
3218                 (void) add_ds_to_guidmap(drc->drc_tofs,
3219                     drc->drc_guid_to_ds_map,
3220                     drc->drc_newsnapobj);
3221         }
3222         return (error);
3223 }
3224
3225 int
3226 dmu_recv_end(dmu_recv_cookie_t *drc, void *owner)
3227 {
3228         drc->drc_owner = owner;
3229
3230         if (drc->drc_newfs)
3231                 return (dmu_recv_new_end(drc));
3232         else
3233                 return (dmu_recv_existing_end(drc));
3234 }
3235
3236 /*
3237  * Return TRUE if this objset is currently being received into.
3238  */
3239 boolean_t
3240 dmu_objset_is_receiving(objset_t *os)
3241 {
3242         return (os->os_dsl_dataset != NULL &&
3243             os->os_dsl_dataset->ds_owner == dmu_recv_tag);
3244 }