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