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