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