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