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