xref: /illumos-gate/usr/src/uts/common/fs/zfs/dmu_recv.c (revision c4ccc1f9004b70b07e4cdb57641c38ab607306c9)
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 = arg1;
887 	const guid_map_entry_t *gmep2 = arg2;
888 
889 	if (gmep1->guid < gmep2->guid)
890 		return (-1);
891 	else if (gmep1->guid > gmep2->guid)
892 		return (1);
893 	return (0);
894 }
895 
896 static void
897 free_guid_map_onexit(void *arg)
898 {
899 	avl_tree_t *ca = arg;
900 	void *cookie = NULL;
901 	guid_map_entry_t *gmep;
902 
903 	while ((gmep = avl_destroy_nodes(ca, &cookie)) != NULL) {
904 		ds_hold_flags_t dsflags = DS_HOLD_FLAG_DECRYPT;
905 
906 		if (gmep->raw) {
907 			gmep->gme_ds->ds_objset->os_raw_receive = B_FALSE;
908 			dsflags &= ~DS_HOLD_FLAG_DECRYPT;
909 		}
910 
911 		dsl_dataset_disown(gmep->gme_ds, dsflags, gmep);
912 		kmem_free(gmep, sizeof (guid_map_entry_t));
913 	}
914 	avl_destroy(ca);
915 	kmem_free(ca, sizeof (avl_tree_t));
916 }
917 
918 static int
919 receive_read(struct receive_arg *ra, int len, void *buf)
920 {
921 	int done = 0;
922 
923 	/*
924 	 * The code doesn't rely on this (lengths being multiples of 8).  See
925 	 * comment in dump_bytes.
926 	 */
927 	ASSERT(len % 8 == 0 ||
928 	    (ra->featureflags & DMU_BACKUP_FEATURE_RAW) != 0);
929 
930 	while (done < len) {
931 		ssize_t resid;
932 
933 		ra->err = vn_rdwr(UIO_READ, ra->vp,
934 		    (char *)buf + done, len - done,
935 		    ra->voff, UIO_SYSSPACE, FAPPEND,
936 		    RLIM64_INFINITY, CRED(), &resid);
937 
938 		if (resid == len - done) {
939 			/*
940 			 * Note: ECKSUM indicates that the receive
941 			 * was interrupted and can potentially be resumed.
942 			 */
943 			ra->err = SET_ERROR(ECKSUM);
944 		}
945 		ra->voff += len - done - resid;
946 		done = len - resid;
947 		if (ra->err != 0)
948 			return (ra->err);
949 	}
950 
951 	ra->bytes_read += len;
952 
953 	ASSERT3U(done, ==, len);
954 	return (0);
955 }
956 
957 static void
958 byteswap_record(dmu_replay_record_t *drr)
959 {
960 #define	DO64(X) (drr->drr_u.X = BSWAP_64(drr->drr_u.X))
961 #define	DO32(X) (drr->drr_u.X = BSWAP_32(drr->drr_u.X))
962 	drr->drr_type = BSWAP_32(drr->drr_type);
963 	drr->drr_payloadlen = BSWAP_32(drr->drr_payloadlen);
964 
965 	switch (drr->drr_type) {
966 	case DRR_BEGIN:
967 		DO64(drr_begin.drr_magic);
968 		DO64(drr_begin.drr_versioninfo);
969 		DO64(drr_begin.drr_creation_time);
970 		DO32(drr_begin.drr_type);
971 		DO32(drr_begin.drr_flags);
972 		DO64(drr_begin.drr_toguid);
973 		DO64(drr_begin.drr_fromguid);
974 		break;
975 	case DRR_OBJECT:
976 		DO64(drr_object.drr_object);
977 		DO32(drr_object.drr_type);
978 		DO32(drr_object.drr_bonustype);
979 		DO32(drr_object.drr_blksz);
980 		DO32(drr_object.drr_bonuslen);
981 		DO32(drr_object.drr_raw_bonuslen);
982 		DO64(drr_object.drr_toguid);
983 		DO64(drr_object.drr_maxblkid);
984 		break;
985 	case DRR_FREEOBJECTS:
986 		DO64(drr_freeobjects.drr_firstobj);
987 		DO64(drr_freeobjects.drr_numobjs);
988 		DO64(drr_freeobjects.drr_toguid);
989 		break;
990 	case DRR_WRITE:
991 		DO64(drr_write.drr_object);
992 		DO32(drr_write.drr_type);
993 		DO64(drr_write.drr_offset);
994 		DO64(drr_write.drr_logical_size);
995 		DO64(drr_write.drr_toguid);
996 		ZIO_CHECKSUM_BSWAP(&drr->drr_u.drr_write.drr_key.ddk_cksum);
997 		DO64(drr_write.drr_key.ddk_prop);
998 		DO64(drr_write.drr_compressed_size);
999 		break;
1000 	case DRR_WRITE_BYREF:
1001 		DO64(drr_write_byref.drr_object);
1002 		DO64(drr_write_byref.drr_offset);
1003 		DO64(drr_write_byref.drr_length);
1004 		DO64(drr_write_byref.drr_toguid);
1005 		DO64(drr_write_byref.drr_refguid);
1006 		DO64(drr_write_byref.drr_refobject);
1007 		DO64(drr_write_byref.drr_refoffset);
1008 		ZIO_CHECKSUM_BSWAP(&drr->drr_u.drr_write_byref.
1009 		    drr_key.ddk_cksum);
1010 		DO64(drr_write_byref.drr_key.ddk_prop);
1011 		break;
1012 	case DRR_WRITE_EMBEDDED:
1013 		DO64(drr_write_embedded.drr_object);
1014 		DO64(drr_write_embedded.drr_offset);
1015 		DO64(drr_write_embedded.drr_length);
1016 		DO64(drr_write_embedded.drr_toguid);
1017 		DO32(drr_write_embedded.drr_lsize);
1018 		DO32(drr_write_embedded.drr_psize);
1019 		break;
1020 	case DRR_FREE:
1021 		DO64(drr_free.drr_object);
1022 		DO64(drr_free.drr_offset);
1023 		DO64(drr_free.drr_length);
1024 		DO64(drr_free.drr_toguid);
1025 		break;
1026 	case DRR_SPILL:
1027 		DO64(drr_spill.drr_object);
1028 		DO64(drr_spill.drr_length);
1029 		DO64(drr_spill.drr_toguid);
1030 		DO64(drr_spill.drr_compressed_size);
1031 		DO32(drr_spill.drr_type);
1032 		break;
1033 	case DRR_OBJECT_RANGE:
1034 		DO64(drr_object_range.drr_firstobj);
1035 		DO64(drr_object_range.drr_numslots);
1036 		DO64(drr_object_range.drr_toguid);
1037 		break;
1038 	case DRR_END:
1039 		DO64(drr_end.drr_toguid);
1040 		ZIO_CHECKSUM_BSWAP(&drr->drr_u.drr_end.drr_checksum);
1041 		break;
1042 	}
1043 
1044 	if (drr->drr_type != DRR_BEGIN) {
1045 		ZIO_CHECKSUM_BSWAP(&drr->drr_u.drr_checksum.drr_checksum);
1046 	}
1047 
1048 #undef DO64
1049 #undef DO32
1050 }
1051 
1052 static inline uint8_t
1053 deduce_nblkptr(dmu_object_type_t bonus_type, uint64_t bonus_size)
1054 {
1055 	if (bonus_type == DMU_OT_SA) {
1056 		return (1);
1057 	} else {
1058 		return (1 +
1059 		    ((DN_OLD_MAX_BONUSLEN -
1060 		    MIN(DN_OLD_MAX_BONUSLEN, bonus_size)) >> SPA_BLKPTRSHIFT));
1061 	}
1062 }
1063 
1064 static void
1065 save_resume_state(struct receive_writer_arg *rwa,
1066     uint64_t object, uint64_t offset, dmu_tx_t *tx)
1067 {
1068 	int txgoff = dmu_tx_get_txg(tx) & TXG_MASK;
1069 
1070 	if (!rwa->resumable)
1071 		return;
1072 
1073 	/*
1074 	 * We use ds_resume_bytes[] != 0 to indicate that we need to
1075 	 * update this on disk, so it must not be 0.
1076 	 */
1077 	ASSERT(rwa->bytes_read != 0);
1078 
1079 	/*
1080 	 * We only resume from write records, which have a valid
1081 	 * (non-meta-dnode) object number.
1082 	 */
1083 	ASSERT(object != 0);
1084 
1085 	/*
1086 	 * For resuming to work correctly, we must receive records in order,
1087 	 * sorted by object,offset.  This is checked by the callers, but
1088 	 * assert it here for good measure.
1089 	 */
1090 	ASSERT3U(object, >=, rwa->os->os_dsl_dataset->ds_resume_object[txgoff]);
1091 	ASSERT(object != rwa->os->os_dsl_dataset->ds_resume_object[txgoff] ||
1092 	    offset >= rwa->os->os_dsl_dataset->ds_resume_offset[txgoff]);
1093 	ASSERT3U(rwa->bytes_read, >=,
1094 	    rwa->os->os_dsl_dataset->ds_resume_bytes[txgoff]);
1095 
1096 	rwa->os->os_dsl_dataset->ds_resume_object[txgoff] = object;
1097 	rwa->os->os_dsl_dataset->ds_resume_offset[txgoff] = offset;
1098 	rwa->os->os_dsl_dataset->ds_resume_bytes[txgoff] = rwa->bytes_read;
1099 }
1100 
1101 int receive_object_delay_frac = 0;
1102 
1103 static int
1104 receive_object(struct receive_writer_arg *rwa, struct drr_object *drro,
1105     void *data)
1106 {
1107 	dmu_object_info_t doi;
1108 	dmu_tx_t *tx;
1109 	uint64_t object;
1110 	int err;
1111 	uint8_t dn_slots = drro->drr_dn_slots != 0 ?
1112 	    drro->drr_dn_slots : DNODE_MIN_SLOTS;
1113 
1114 	if (receive_object_delay_frac != 0 &&
1115 	    spa_get_random(receive_object_delay_frac) == 0)
1116 		delay(1);
1117 
1118 	if (drro->drr_type == DMU_OT_NONE ||
1119 	    !DMU_OT_IS_VALID(drro->drr_type) ||
1120 	    !DMU_OT_IS_VALID(drro->drr_bonustype) ||
1121 	    drro->drr_checksumtype >= ZIO_CHECKSUM_FUNCTIONS ||
1122 	    drro->drr_compress >= ZIO_COMPRESS_FUNCTIONS ||
1123 	    P2PHASE(drro->drr_blksz, SPA_MINBLOCKSIZE) ||
1124 	    drro->drr_blksz < SPA_MINBLOCKSIZE ||
1125 	    drro->drr_blksz > spa_maxblocksize(dmu_objset_spa(rwa->os)) ||
1126 	    drro->drr_bonuslen >
1127 	    DN_BONUS_SIZE(spa_maxdnodesize(dmu_objset_spa(rwa->os))) ||
1128 	    dn_slots >
1129 	    (spa_maxdnodesize(dmu_objset_spa(rwa->os)) >> DNODE_SHIFT)) {
1130 		return (SET_ERROR(EINVAL));
1131 	}
1132 
1133 	if (rwa->raw) {
1134 		/*
1135 		 * We should have received a DRR_OBJECT_RANGE record
1136 		 * containing this block and stored it in rwa.
1137 		 */
1138 		if (drro->drr_object < rwa->or_firstobj ||
1139 		    drro->drr_object >= rwa->or_firstobj + rwa->or_numslots ||
1140 		    drro->drr_raw_bonuslen < drro->drr_bonuslen ||
1141 		    drro->drr_indblkshift > SPA_MAXBLOCKSHIFT ||
1142 		    drro->drr_nlevels > DN_MAX_LEVELS ||
1143 		    drro->drr_nblkptr > DN_MAX_NBLKPTR ||
1144 		    DN_SLOTS_TO_BONUSLEN(drro->drr_dn_slots) <
1145 		    drro->drr_raw_bonuslen)
1146 			return (SET_ERROR(EINVAL));
1147 	} else {
1148 
1149 		/*
1150 		 * The DRR_OBJECT_SPILL flag is valid when the DRR_BEGIN
1151 		 * record indicates this by setting DRR_FLAG_SPILL_BLOCK.
1152 		 */
1153 		if (((drro->drr_flags & ~(DRR_OBJECT_SPILL))) ||
1154 		    (!rwa->spill && DRR_OBJECT_HAS_SPILL(drro->drr_flags))) {
1155 			return (SET_ERROR(EINVAL));
1156 		}
1157 
1158 		if (drro->drr_raw_bonuslen != 0 || drro->drr_nblkptr != 0 ||
1159 		    drro->drr_indblkshift != 0 || drro->drr_nlevels != 0) {
1160 			return (SET_ERROR(EINVAL));
1161 		}
1162 	}
1163 
1164 	err = dmu_object_info(rwa->os, drro->drr_object, &doi);
1165 
1166 	if (err != 0 && err != ENOENT && err != EEXIST)
1167 		return (SET_ERROR(EINVAL));
1168 
1169 	if (drro->drr_object > rwa->max_object)
1170 		rwa->max_object = drro->drr_object;
1171 
1172 	/*
1173 	 * If we are losing blkptrs or changing the block size this must
1174 	 * be a new file instance.  We must clear out the previous file
1175 	 * contents before we can change this type of metadata in the dnode.
1176 	 * Raw receives will also check that the indirect structure of the
1177 	 * dnode hasn't changed.
1178 	 */
1179 	if (err == 0) {
1180 		uint32_t indblksz = drro->drr_indblkshift ?
1181 		    1ULL << drro->drr_indblkshift : 0;
1182 		int nblkptr = deduce_nblkptr(drro->drr_bonustype,
1183 		    drro->drr_bonuslen);
1184 		boolean_t did_free = B_FALSE;
1185 
1186 		object = drro->drr_object;
1187 
1188 		/* nblkptr should be bounded by the bonus size and type */
1189 		if (rwa->raw && nblkptr != drro->drr_nblkptr)
1190 			return (SET_ERROR(EINVAL));
1191 
1192 		/*
1193 		 * Check for indicators that the object was freed and
1194 		 * reallocated. For all sends, these indicators are:
1195 		 *	- A changed block size
1196 		 *	- A smaller nblkptr
1197 		 *	- A changed dnode size
1198 		 * For raw sends we also check a few other fields to
1199 		 * ensure we are preserving the objset structure exactly
1200 		 * as it was on the receive side:
1201 		 *	- A changed indirect block size
1202 		 *	- A smaller nlevels
1203 		 */
1204 		if (drro->drr_blksz != doi.doi_data_block_size ||
1205 		    nblkptr < doi.doi_nblkptr ||
1206 		    dn_slots != doi.doi_dnodesize >> DNODE_SHIFT ||
1207 		    (rwa->raw &&
1208 		    (indblksz != doi.doi_metadata_block_size ||
1209 		    drro->drr_nlevels < doi.doi_indirection))) {
1210 			err = dmu_free_long_range(rwa->os,
1211 			    drro->drr_object, 0, DMU_OBJECT_END);
1212 			if (err != 0)
1213 				return (SET_ERROR(EINVAL));
1214 			else
1215 				did_free = B_TRUE;
1216 		}
1217 
1218 		/*
1219 		 * The dmu does not currently support decreasing nlevels
1220 		 * or changing the number of dnode slots on an object. For
1221 		 * non-raw sends, this does not matter and the new object
1222 		 * can just use the previous one's nlevels. For raw sends,
1223 		 * however, the structure of the received dnode (including
1224 		 * nlevels and dnode slots) must match that of the send
1225 		 * side. Therefore, instead of using dmu_object_reclaim(),
1226 		 * we must free the object completely and call
1227 		 * dmu_object_claim_dnsize() instead.
1228 		 */
1229 		if ((rwa->raw && drro->drr_nlevels < doi.doi_indirection) ||
1230 		    dn_slots != doi.doi_dnodesize >> DNODE_SHIFT) {
1231 			err = dmu_free_long_object(rwa->os, drro->drr_object);
1232 			if (err != 0)
1233 				return (SET_ERROR(EINVAL));
1234 
1235 			txg_wait_synced(dmu_objset_pool(rwa->os), 0);
1236 			object = DMU_NEW_OBJECT;
1237 		}
1238 
1239 		/*
1240 		 * For raw receives, free everything beyond the new incoming
1241 		 * maxblkid. Normally this would be done with a DRR_FREE
1242 		 * record that would come after this DRR_OBJECT record is
1243 		 * processed. However, for raw receives we manually set the
1244 		 * maxblkid from the drr_maxblkid and so we must first free
1245 		 * everything above that blkid to ensure the DMU is always
1246 		 * consistent with itself. We will never free the first block
1247 		 * of the object here because a maxblkid of 0 could indicate
1248 		 * an object with a single block or one with no blocks. This
1249 		 * free may be skipped when dmu_free_long_range() was called
1250 		 * above since it covers the entire object's contents.
1251 		 */
1252 		if (rwa->raw && object != DMU_NEW_OBJECT && !did_free) {
1253 			err = dmu_free_long_range(rwa->os, drro->drr_object,
1254 			    (drro->drr_maxblkid + 1) * doi.doi_data_block_size,
1255 			    DMU_OBJECT_END);
1256 			if (err != 0)
1257 				return (SET_ERROR(EINVAL));
1258 		}
1259 	} else if (err == EEXIST) {
1260 		/*
1261 		 * The object requested is currently an interior slot of a
1262 		 * multi-slot dnode. This will be resolved when the next txg
1263 		 * is synced out, since the send stream will have told us
1264 		 * to free this slot when we freed the associated dnode
1265 		 * earlier in the stream.
1266 		 */
1267 		txg_wait_synced(dmu_objset_pool(rwa->os), 0);
1268 
1269 		if (dmu_object_info(rwa->os, drro->drr_object, NULL) != ENOENT)
1270 			return (SET_ERROR(EINVAL));
1271 
1272 		/* object was freed and we are about to allocate a new one */
1273 		object = DMU_NEW_OBJECT;
1274 	} else {
1275 		/* object is free and we are about to allocate a new one */
1276 		object = DMU_NEW_OBJECT;
1277 	}
1278 
1279 	/*
1280 	 * If this is a multi-slot dnode there is a chance that this
1281 	 * object will expand into a slot that is already used by
1282 	 * another object from the previous snapshot. We must free
1283 	 * these objects before we attempt to allocate the new dnode.
1284 	 */
1285 	if (dn_slots > 1) {
1286 		boolean_t need_sync = B_FALSE;
1287 
1288 		for (uint64_t slot = drro->drr_object + 1;
1289 		    slot < drro->drr_object + dn_slots;
1290 		    slot++) {
1291 			dmu_object_info_t slot_doi;
1292 
1293 			err = dmu_object_info(rwa->os, slot, &slot_doi);
1294 			if (err == ENOENT || err == EEXIST)
1295 				continue;
1296 			else if (err != 0)
1297 				return (err);
1298 
1299 			err = dmu_free_long_object(rwa->os, slot);
1300 
1301 			if (err != 0)
1302 				return (err);
1303 
1304 			need_sync = B_TRUE;
1305 		}
1306 
1307 		if (need_sync)
1308 			txg_wait_synced(dmu_objset_pool(rwa->os), 0);
1309 	}
1310 
1311 	tx = dmu_tx_create(rwa->os);
1312 	dmu_tx_hold_bonus(tx, object);
1313 	dmu_tx_hold_write(tx, object, 0, 0);
1314 	err = dmu_tx_assign(tx, TXG_WAIT);
1315 	if (err != 0) {
1316 		dmu_tx_abort(tx);
1317 		return (err);
1318 	}
1319 
1320 	if (object == DMU_NEW_OBJECT) {
1321 		/* Currently free, wants to be allocated */
1322 		err = dmu_object_claim_dnsize(rwa->os, drro->drr_object,
1323 		    drro->drr_type, drro->drr_blksz,
1324 		    drro->drr_bonustype, drro->drr_bonuslen,
1325 		    dn_slots << DNODE_SHIFT, tx);
1326 	} else if (drro->drr_type != doi.doi_type ||
1327 	    drro->drr_blksz != doi.doi_data_block_size ||
1328 	    drro->drr_bonustype != doi.doi_bonus_type ||
1329 	    drro->drr_bonuslen != doi.doi_bonus_size) {
1330 		/* Currently allocated, but with different properties */
1331 		err = dmu_object_reclaim_dnsize(rwa->os, drro->drr_object,
1332 		    drro->drr_type, drro->drr_blksz,
1333 		    drro->drr_bonustype, drro->drr_bonuslen,
1334 		    dn_slots << DNODE_SHIFT, rwa->spill ?
1335 		    DRR_OBJECT_HAS_SPILL(drro->drr_flags) : B_FALSE, tx);
1336 	} else if (rwa->spill && !DRR_OBJECT_HAS_SPILL(drro->drr_flags)) {
1337 		/*
1338 		 * Currently allocated, the existing version of this object
1339 		 * may reference a spill block that is no longer allocated
1340 		 * at the source and needs to be freed.
1341 		 */
1342 		err = dmu_object_rm_spill(rwa->os, drro->drr_object, tx);
1343 	}
1344 
1345 	if (err != 0) {
1346 		dmu_tx_commit(tx);
1347 		return (SET_ERROR(EINVAL));
1348 	}
1349 
1350 	if (rwa->or_crypt_params_present) {
1351 		/*
1352 		 * Set the crypt params for the buffer associated with this
1353 		 * range of dnodes.  This causes the blkptr_t to have the
1354 		 * same crypt params (byteorder, salt, iv, mac) as on the
1355 		 * sending side.
1356 		 *
1357 		 * Since we are committing this tx now, it is possible for
1358 		 * the dnode block to end up on-disk with the incorrect MAC,
1359 		 * if subsequent objects in this block are received in a
1360 		 * different txg.  However, since the dataset is marked as
1361 		 * inconsistent, no code paths will do a non-raw read (or
1362 		 * decrypt the block / verify the MAC). The receive code and
1363 		 * scrub code can safely do raw reads and verify the
1364 		 * checksum.  They don't need to verify the MAC.
1365 		 */
1366 		dmu_buf_t *db = NULL;
1367 		uint64_t offset = rwa->or_firstobj * DNODE_MIN_SIZE;
1368 
1369 		err = dmu_buf_hold_by_dnode(DMU_META_DNODE(rwa->os),
1370 		    offset, FTAG, &db, DMU_READ_PREFETCH | DMU_READ_NO_DECRYPT);
1371 		if (err != 0) {
1372 			dmu_tx_commit(tx);
1373 			return (SET_ERROR(EINVAL));
1374 		}
1375 
1376 		dmu_buf_set_crypt_params(db, rwa->or_byteorder,
1377 		    rwa->or_salt, rwa->or_iv, rwa->or_mac, tx);
1378 
1379 		dmu_buf_rele(db, FTAG);
1380 
1381 		rwa->or_crypt_params_present = B_FALSE;
1382 	}
1383 
1384 	dmu_object_set_checksum(rwa->os, drro->drr_object,
1385 	    drro->drr_checksumtype, tx);
1386 	dmu_object_set_compress(rwa->os, drro->drr_object,
1387 	    drro->drr_compress, tx);
1388 
1389 	/* handle more restrictive dnode structuring for raw recvs */
1390 	if (rwa->raw) {
1391 		/*
1392 		 * Set the indirect block size, block shift, nlevels.
1393 		 * This will not fail because we ensured all of the
1394 		 * blocks were freed earlier if this is a new object.
1395 		 * For non-new objects block size and indirect block
1396 		 * shift cannot change and nlevels can only increase.
1397 		 */
1398 		VERIFY0(dmu_object_set_blocksize(rwa->os, drro->drr_object,
1399 		    drro->drr_blksz, drro->drr_indblkshift, tx));
1400 		VERIFY0(dmu_object_set_nlevels(rwa->os, drro->drr_object,
1401 		    drro->drr_nlevels, tx));
1402 
1403 		/*
1404 		 * Set the maxblkid. This will always succeed because
1405 		 * we freed all blocks beyond the new maxblkid above.
1406 		 */
1407 		VERIFY0(dmu_object_set_maxblkid(rwa->os, drro->drr_object,
1408 		    drro->drr_maxblkid, tx));
1409 	}
1410 
1411 	if (data != NULL) {
1412 		dmu_buf_t *db;
1413 		dnode_t *dn;
1414 		uint32_t flags = DMU_READ_NO_PREFETCH;
1415 
1416 		if (rwa->raw)
1417 			flags |= DMU_READ_NO_DECRYPT;
1418 
1419 		VERIFY0(dnode_hold(rwa->os, drro->drr_object, FTAG, &dn));
1420 		VERIFY0(dmu_bonus_hold_by_dnode(dn, FTAG, &db, flags));
1421 
1422 		dmu_buf_will_dirty(db, tx);
1423 
1424 		ASSERT3U(db->db_size, >=, drro->drr_bonuslen);
1425 		bcopy(data, db->db_data, DRR_OBJECT_PAYLOAD_SIZE(drro));
1426 
1427 		/*
1428 		 * Raw bonus buffers have their byteorder determined by the
1429 		 * DRR_OBJECT_RANGE record.
1430 		 */
1431 		if (rwa->byteswap && !rwa->raw) {
1432 			dmu_object_byteswap_t byteswap =
1433 			    DMU_OT_BYTESWAP(drro->drr_bonustype);
1434 			dmu_ot_byteswap[byteswap].ob_func(db->db_data,
1435 			    DRR_OBJECT_PAYLOAD_SIZE(drro));
1436 		}
1437 		dmu_buf_rele(db, FTAG);
1438 		dnode_rele(dn, FTAG);
1439 	}
1440 	dmu_tx_commit(tx);
1441 
1442 	return (0);
1443 }
1444 
1445 /* ARGSUSED */
1446 static int
1447 receive_freeobjects(struct receive_writer_arg *rwa,
1448     struct drr_freeobjects *drrfo)
1449 {
1450 	uint64_t obj;
1451 	int next_err = 0;
1452 
1453 	if (drrfo->drr_firstobj + drrfo->drr_numobjs < drrfo->drr_firstobj)
1454 		return (SET_ERROR(EINVAL));
1455 
1456 	for (obj = drrfo->drr_firstobj == 0 ? 1 : drrfo->drr_firstobj;
1457 	    obj < drrfo->drr_firstobj + drrfo->drr_numobjs && next_err == 0;
1458 	    next_err = dmu_object_next(rwa->os, &obj, FALSE, 0)) {
1459 		dmu_object_info_t doi;
1460 		int err;
1461 
1462 		err = dmu_object_info(rwa->os, obj, &doi);
1463 		if (err == ENOENT)
1464 			continue;
1465 		else if (err != 0)
1466 			return (err);
1467 
1468 		err = dmu_free_long_object(rwa->os, obj);
1469 
1470 		if (err != 0)
1471 			return (err);
1472 
1473 		if (obj > rwa->max_object)
1474 			rwa->max_object = obj;
1475 	}
1476 	if (next_err != ESRCH)
1477 		return (next_err);
1478 	return (0);
1479 }
1480 
1481 static int
1482 receive_write(struct receive_writer_arg *rwa, struct drr_write *drrw,
1483     arc_buf_t *abuf)
1484 {
1485 	int err;
1486 	dmu_tx_t *tx;
1487 	dnode_t *dn;
1488 
1489 	if (drrw->drr_offset + drrw->drr_logical_size < drrw->drr_offset ||
1490 	    !DMU_OT_IS_VALID(drrw->drr_type))
1491 		return (SET_ERROR(EINVAL));
1492 
1493 	/*
1494 	 * For resuming to work, records must be in increasing order
1495 	 * by (object, offset).
1496 	 */
1497 	if (drrw->drr_object < rwa->last_object ||
1498 	    (drrw->drr_object == rwa->last_object &&
1499 	    drrw->drr_offset < rwa->last_offset)) {
1500 		return (SET_ERROR(EINVAL));
1501 	}
1502 	rwa->last_object = drrw->drr_object;
1503 	rwa->last_offset = drrw->drr_offset;
1504 
1505 	if (rwa->last_object > rwa->max_object)
1506 		rwa->max_object = rwa->last_object;
1507 
1508 	if (dmu_object_info(rwa->os, drrw->drr_object, NULL) != 0)
1509 		return (SET_ERROR(EINVAL));
1510 
1511 	tx = dmu_tx_create(rwa->os);
1512 	dmu_tx_hold_write(tx, drrw->drr_object,
1513 	    drrw->drr_offset, drrw->drr_logical_size);
1514 	err = dmu_tx_assign(tx, TXG_WAIT);
1515 	if (err != 0) {
1516 		dmu_tx_abort(tx);
1517 		return (err);
1518 	}
1519 
1520 	if (rwa->byteswap && !arc_is_encrypted(abuf) &&
1521 	    arc_get_compression(abuf) == ZIO_COMPRESS_OFF) {
1522 		dmu_object_byteswap_t byteswap =
1523 		    DMU_OT_BYTESWAP(drrw->drr_type);
1524 		dmu_ot_byteswap[byteswap].ob_func(abuf->b_data,
1525 		    DRR_WRITE_PAYLOAD_SIZE(drrw));
1526 	}
1527 
1528 	VERIFY0(dnode_hold(rwa->os, drrw->drr_object, FTAG, &dn));
1529 	err = dmu_assign_arcbuf_by_dnode(dn, drrw->drr_offset, abuf, tx);
1530 	if (err != 0) {
1531 		dnode_rele(dn, FTAG);
1532 		dmu_tx_commit(tx);
1533 		return (err);
1534 	}
1535 	dnode_rele(dn, FTAG);
1536 
1537 	/*
1538 	 * Note: If the receive fails, we want the resume stream to start
1539 	 * with the same record that we last successfully received (as opposed
1540 	 * to the next record), so that we can verify that we are
1541 	 * resuming from the correct location.
1542 	 */
1543 	save_resume_state(rwa, drrw->drr_object, drrw->drr_offset, tx);
1544 	dmu_tx_commit(tx);
1545 
1546 	return (0);
1547 }
1548 
1549 /*
1550  * Handle a DRR_WRITE_BYREF record.  This record is used in dedup'ed
1551  * streams to refer to a copy of the data that is already on the
1552  * system because it came in earlier in the stream.  This function
1553  * finds the earlier copy of the data, and uses that copy instead of
1554  * data from the stream to fulfill this write.
1555  */
1556 static int
1557 receive_write_byref(struct receive_writer_arg *rwa,
1558     struct drr_write_byref *drrwbr)
1559 {
1560 	dmu_tx_t *tx;
1561 	int err;
1562 	guid_map_entry_t gmesrch;
1563 	guid_map_entry_t *gmep;
1564 	avl_index_t where;
1565 	objset_t *ref_os = NULL;
1566 	int flags = DMU_READ_PREFETCH;
1567 	dmu_buf_t *dbp;
1568 
1569 	if (drrwbr->drr_offset + drrwbr->drr_length < drrwbr->drr_offset)
1570 		return (SET_ERROR(EINVAL));
1571 
1572 	/*
1573 	 * If the GUID of the referenced dataset is different from the
1574 	 * GUID of the target dataset, find the referenced dataset.
1575 	 */
1576 	if (drrwbr->drr_toguid != drrwbr->drr_refguid) {
1577 		gmesrch.guid = drrwbr->drr_refguid;
1578 		if ((gmep = avl_find(rwa->guid_to_ds_map, &gmesrch,
1579 		    &where)) == NULL) {
1580 			return (SET_ERROR(EINVAL));
1581 		}
1582 		if (dmu_objset_from_ds(gmep->gme_ds, &ref_os))
1583 			return (SET_ERROR(EINVAL));
1584 	} else {
1585 		ref_os = rwa->os;
1586 	}
1587 
1588 	if (drrwbr->drr_object > rwa->max_object)
1589 		rwa->max_object = drrwbr->drr_object;
1590 
1591 	if (rwa->raw)
1592 		flags |= DMU_READ_NO_DECRYPT;
1593 
1594 	/* may return either a regular db or an encrypted one */
1595 	err = dmu_buf_hold(ref_os, drrwbr->drr_refobject,
1596 	    drrwbr->drr_refoffset, FTAG, &dbp, flags);
1597 	if (err != 0)
1598 		return (err);
1599 
1600 	tx = dmu_tx_create(rwa->os);
1601 
1602 	dmu_tx_hold_write(tx, drrwbr->drr_object,
1603 	    drrwbr->drr_offset, drrwbr->drr_length);
1604 	err = dmu_tx_assign(tx, TXG_WAIT);
1605 	if (err != 0) {
1606 		dmu_tx_abort(tx);
1607 		return (err);
1608 	}
1609 
1610 	if (rwa->raw) {
1611 		dmu_copy_from_buf(rwa->os, drrwbr->drr_object,
1612 		    drrwbr->drr_offset, dbp, tx);
1613 	} else {
1614 		dmu_write(rwa->os, drrwbr->drr_object,
1615 		    drrwbr->drr_offset, drrwbr->drr_length, dbp->db_data, tx);
1616 	}
1617 	dmu_buf_rele(dbp, FTAG);
1618 
1619 	/* See comment in restore_write. */
1620 	save_resume_state(rwa, drrwbr->drr_object, drrwbr->drr_offset, tx);
1621 	dmu_tx_commit(tx);
1622 	return (0);
1623 }
1624 
1625 static int
1626 receive_write_embedded(struct receive_writer_arg *rwa,
1627     struct drr_write_embedded *drrwe, void *data)
1628 {
1629 	dmu_tx_t *tx;
1630 	int err;
1631 
1632 	if (drrwe->drr_offset + drrwe->drr_length < drrwe->drr_offset)
1633 		return (EINVAL);
1634 
1635 	if (drrwe->drr_psize > BPE_PAYLOAD_SIZE)
1636 		return (EINVAL);
1637 
1638 	if (drrwe->drr_etype >= NUM_BP_EMBEDDED_TYPES)
1639 		return (EINVAL);
1640 	if (drrwe->drr_compression >= ZIO_COMPRESS_FUNCTIONS)
1641 		return (EINVAL);
1642 	if (rwa->raw)
1643 		return (SET_ERROR(EINVAL));
1644 
1645 	if (drrwe->drr_object > rwa->max_object)
1646 		rwa->max_object = drrwe->drr_object;
1647 
1648 	tx = dmu_tx_create(rwa->os);
1649 
1650 	dmu_tx_hold_write(tx, drrwe->drr_object,
1651 	    drrwe->drr_offset, drrwe->drr_length);
1652 	err = dmu_tx_assign(tx, TXG_WAIT);
1653 	if (err != 0) {
1654 		dmu_tx_abort(tx);
1655 		return (err);
1656 	}
1657 
1658 	dmu_write_embedded(rwa->os, drrwe->drr_object,
1659 	    drrwe->drr_offset, data, drrwe->drr_etype,
1660 	    drrwe->drr_compression, drrwe->drr_lsize, drrwe->drr_psize,
1661 	    rwa->byteswap ^ ZFS_HOST_BYTEORDER, tx);
1662 
1663 	/* See comment in restore_write. */
1664 	save_resume_state(rwa, drrwe->drr_object, drrwe->drr_offset, tx);
1665 	dmu_tx_commit(tx);
1666 	return (0);
1667 }
1668 
1669 static int
1670 receive_spill(struct receive_writer_arg *rwa, struct drr_spill *drrs,
1671     arc_buf_t *abuf)
1672 {
1673 	dmu_tx_t *tx;
1674 	dmu_buf_t *db, *db_spill;
1675 	int err;
1676 	uint32_t flags = 0;
1677 
1678 	if (drrs->drr_length < SPA_MINBLOCKSIZE ||
1679 	    drrs->drr_length > spa_maxblocksize(dmu_objset_spa(rwa->os)))
1680 		return (SET_ERROR(EINVAL));
1681 
1682 	/*
1683 	 * This is an unmodified spill block which was added to the stream
1684 	 * to resolve an issue with incorrectly removing spill blocks.  It
1685 	 * should be ignored by current versions of the code which support
1686 	 * the DRR_FLAG_SPILL_BLOCK flag.
1687 	 */
1688 	if (rwa->spill && DRR_SPILL_IS_UNMODIFIED(drrs->drr_flags)) {
1689 		dmu_return_arcbuf(abuf);
1690 		return (0);
1691 	}
1692 
1693 	if (rwa->raw) {
1694 		if (!DMU_OT_IS_VALID(drrs->drr_type) ||
1695 		    drrs->drr_compressiontype >= ZIO_COMPRESS_FUNCTIONS ||
1696 		    drrs->drr_compressed_size == 0)
1697 			return (SET_ERROR(EINVAL));
1698 
1699 		flags |= DMU_READ_NO_DECRYPT;
1700 	}
1701 
1702 	if (dmu_object_info(rwa->os, drrs->drr_object, NULL) != 0)
1703 		return (SET_ERROR(EINVAL));
1704 
1705 	if (drrs->drr_object > rwa->max_object)
1706 		rwa->max_object = drrs->drr_object;
1707 
1708 	VERIFY0(dmu_bonus_hold(rwa->os, drrs->drr_object, FTAG, &db));
1709 	if ((err = dmu_spill_hold_by_bonus(db, DMU_READ_NO_DECRYPT, FTAG,
1710 	    &db_spill)) != 0) {
1711 		dmu_buf_rele(db, FTAG);
1712 		return (err);
1713 	}
1714 
1715 	tx = dmu_tx_create(rwa->os);
1716 
1717 	dmu_tx_hold_spill(tx, db->db_object);
1718 
1719 	err = dmu_tx_assign(tx, TXG_WAIT);
1720 	if (err != 0) {
1721 		dmu_buf_rele(db, FTAG);
1722 		dmu_buf_rele(db_spill, FTAG);
1723 		dmu_tx_abort(tx);
1724 		return (err);
1725 	}
1726 
1727 	/*
1728 	 * Spill blocks may both grow and shrink.  When a change in size
1729 	 * occurs any existing dbuf must be updated to match the logical
1730 	 * size of the provided arc_buf_t.
1731 	 */
1732 	if (db_spill->db_size != drrs->drr_length) {
1733 		dmu_buf_will_fill(db_spill, tx);
1734 		VERIFY(0 == dbuf_spill_set_blksz(db_spill,
1735 		    drrs->drr_length, tx));
1736 	}
1737 
1738 	if (rwa->byteswap && !arc_is_encrypted(abuf) &&
1739 	    arc_get_compression(abuf) == ZIO_COMPRESS_OFF) {
1740 		dmu_object_byteswap_t byteswap =
1741 		    DMU_OT_BYTESWAP(drrs->drr_type);
1742 		dmu_ot_byteswap[byteswap].ob_func(abuf->b_data,
1743 		    DRR_SPILL_PAYLOAD_SIZE(drrs));
1744 	}
1745 
1746 	dbuf_assign_arcbuf((dmu_buf_impl_t *)db_spill, abuf, tx);
1747 
1748 	dmu_buf_rele(db, FTAG);
1749 	dmu_buf_rele(db_spill, FTAG);
1750 
1751 	dmu_tx_commit(tx);
1752 	return (0);
1753 }
1754 
1755 /* ARGSUSED */
1756 static int
1757 receive_free(struct receive_writer_arg *rwa, struct drr_free *drrf)
1758 {
1759 	int err;
1760 
1761 	if (drrf->drr_length != DMU_OBJECT_END &&
1762 	    drrf->drr_offset + drrf->drr_length < drrf->drr_offset)
1763 		return (SET_ERROR(EINVAL));
1764 
1765 	if (dmu_object_info(rwa->os, drrf->drr_object, NULL) != 0)
1766 		return (SET_ERROR(EINVAL));
1767 
1768 	if (drrf->drr_object > rwa->max_object)
1769 		rwa->max_object = drrf->drr_object;
1770 
1771 	err = dmu_free_long_range(rwa->os, drrf->drr_object,
1772 	    drrf->drr_offset, drrf->drr_length);
1773 
1774 	return (err);
1775 }
1776 
1777 static int
1778 receive_object_range(struct receive_writer_arg *rwa,
1779     struct drr_object_range *drror)
1780 {
1781 	/*
1782 	 * By default, we assume this block is in our native format
1783 	 * (ZFS_HOST_BYTEORDER). We then take into account whether
1784 	 * the send stream is byteswapped (rwa->byteswap). Finally,
1785 	 * we need to byteswap again if this particular block was
1786 	 * in non-native format on the send side.
1787 	 */
1788 	boolean_t byteorder = ZFS_HOST_BYTEORDER ^ rwa->byteswap ^
1789 	    !!DRR_IS_RAW_BYTESWAPPED(drror->drr_flags);
1790 
1791 	/*
1792 	 * Since dnode block sizes are constant, we should not need to worry
1793 	 * about making sure that the dnode block size is the same on the
1794 	 * sending and receiving sides for the time being. For non-raw sends,
1795 	 * this does not matter (and in fact we do not send a DRR_OBJECT_RANGE
1796 	 * record at all). Raw sends require this record type because the
1797 	 * encryption parameters are used to protect an entire block of bonus
1798 	 * buffers. If the size of dnode blocks ever becomes variable,
1799 	 * handling will need to be added to ensure that dnode block sizes
1800 	 * match on the sending and receiving side.
1801 	 */
1802 	if (drror->drr_numslots != DNODES_PER_BLOCK ||
1803 	    P2PHASE(drror->drr_firstobj, DNODES_PER_BLOCK) != 0 ||
1804 	    !rwa->raw)
1805 		return (SET_ERROR(EINVAL));
1806 
1807 	if (drror->drr_firstobj > rwa->max_object)
1808 		rwa->max_object = drror->drr_firstobj;
1809 
1810 	/*
1811 	 * The DRR_OBJECT_RANGE handling must be deferred to receive_object()
1812 	 * so that the block of dnodes is not written out when it's empty,
1813 	 * and converted to a HOLE BP.
1814 	 */
1815 	rwa->or_crypt_params_present = B_TRUE;
1816 	rwa->or_firstobj = drror->drr_firstobj;
1817 	rwa->or_numslots = drror->drr_numslots;
1818 	bcopy(drror->drr_salt, rwa->or_salt, ZIO_DATA_SALT_LEN);
1819 	bcopy(drror->drr_iv, rwa->or_iv, ZIO_DATA_IV_LEN);
1820 	bcopy(drror->drr_mac, rwa->or_mac, ZIO_DATA_MAC_LEN);
1821 	rwa->or_byteorder = byteorder;
1822 
1823 	return (0);
1824 }
1825 
1826 /* used to destroy the drc_ds on error */
1827 static void
1828 dmu_recv_cleanup_ds(dmu_recv_cookie_t *drc)
1829 {
1830 	dsl_dataset_t *ds = drc->drc_ds;
1831 	ds_hold_flags_t dsflags = (drc->drc_raw) ? 0 : DS_HOLD_FLAG_DECRYPT;
1832 
1833 	/*
1834 	 * Wait for the txg sync before cleaning up the receive. For
1835 	 * resumable receives, this ensures that our resume state has
1836 	 * been written out to disk. For raw receives, this ensures
1837 	 * that the user accounting code will not attempt to do anything
1838 	 * after we stopped receiving the dataset.
1839 	 */
1840 	txg_wait_synced(ds->ds_dir->dd_pool, 0);
1841 	ds->ds_objset->os_raw_receive = B_FALSE;
1842 
1843 	rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);
1844 	if (drc->drc_resumable && !BP_IS_HOLE(dsl_dataset_get_blkptr(ds))) {
1845 		rrw_exit(&ds->ds_bp_rwlock, FTAG);
1846 		dsl_dataset_disown(ds, dsflags, dmu_recv_tag);
1847 	} else {
1848 		char name[ZFS_MAX_DATASET_NAME_LEN];
1849 		rrw_exit(&ds->ds_bp_rwlock, FTAG);
1850 		dsl_dataset_name(ds, name);
1851 		dsl_dataset_disown(ds, dsflags, dmu_recv_tag);
1852 		(void) dsl_destroy_head(name);
1853 	}
1854 }
1855 
1856 static void
1857 receive_cksum(struct receive_arg *ra, int len, void *buf)
1858 {
1859 	if (ra->byteswap) {
1860 		(void) fletcher_4_incremental_byteswap(buf, len, &ra->cksum);
1861 	} else {
1862 		(void) fletcher_4_incremental_native(buf, len, &ra->cksum);
1863 	}
1864 }
1865 
1866 /*
1867  * Read the payload into a buffer of size len, and update the current record's
1868  * payload field.
1869  * Allocate ra->next_rrd and read the next record's header into
1870  * ra->next_rrd->header.
1871  * Verify checksum of payload and next record.
1872  */
1873 static int
1874 receive_read_payload_and_next_header(struct receive_arg *ra, int len, void *buf)
1875 {
1876 	int err;
1877 
1878 	if (len != 0) {
1879 		ASSERT3U(len, <=, SPA_MAXBLOCKSIZE);
1880 		err = receive_read(ra, len, buf);
1881 		if (err != 0)
1882 			return (err);
1883 		receive_cksum(ra, len, buf);
1884 
1885 		/* note: rrd is NULL when reading the begin record's payload */
1886 		if (ra->rrd != NULL) {
1887 			ra->rrd->payload = buf;
1888 			ra->rrd->payload_size = len;
1889 			ra->rrd->bytes_read = ra->bytes_read;
1890 		}
1891 	}
1892 
1893 	ra->prev_cksum = ra->cksum;
1894 
1895 	ra->next_rrd = kmem_zalloc(sizeof (*ra->next_rrd), KM_SLEEP);
1896 	err = receive_read(ra, sizeof (ra->next_rrd->header),
1897 	    &ra->next_rrd->header);
1898 	ra->next_rrd->bytes_read = ra->bytes_read;
1899 
1900 	if (err != 0) {
1901 		kmem_free(ra->next_rrd, sizeof (*ra->next_rrd));
1902 		ra->next_rrd = NULL;
1903 		return (err);
1904 	}
1905 	if (ra->next_rrd->header.drr_type == DRR_BEGIN) {
1906 		kmem_free(ra->next_rrd, sizeof (*ra->next_rrd));
1907 		ra->next_rrd = NULL;
1908 		return (SET_ERROR(EINVAL));
1909 	}
1910 
1911 	/*
1912 	 * Note: checksum is of everything up to but not including the
1913 	 * checksum itself.
1914 	 */
1915 	ASSERT3U(offsetof(dmu_replay_record_t, drr_u.drr_checksum.drr_checksum),
1916 	    ==, sizeof (dmu_replay_record_t) - sizeof (zio_cksum_t));
1917 	receive_cksum(ra,
1918 	    offsetof(dmu_replay_record_t, drr_u.drr_checksum.drr_checksum),
1919 	    &ra->next_rrd->header);
1920 
1921 	zio_cksum_t cksum_orig =
1922 	    ra->next_rrd->header.drr_u.drr_checksum.drr_checksum;
1923 	zio_cksum_t *cksump =
1924 	    &ra->next_rrd->header.drr_u.drr_checksum.drr_checksum;
1925 
1926 	if (ra->byteswap)
1927 		byteswap_record(&ra->next_rrd->header);
1928 
1929 	if ((!ZIO_CHECKSUM_IS_ZERO(cksump)) &&
1930 	    !ZIO_CHECKSUM_EQUAL(ra->cksum, *cksump)) {
1931 		kmem_free(ra->next_rrd, sizeof (*ra->next_rrd));
1932 		ra->next_rrd = NULL;
1933 		return (SET_ERROR(ECKSUM));
1934 	}
1935 
1936 	receive_cksum(ra, sizeof (cksum_orig), &cksum_orig);
1937 
1938 	return (0);
1939 }
1940 
1941 static void
1942 objlist_create(struct objlist *list)
1943 {
1944 	list_create(&list->list, sizeof (struct receive_objnode),
1945 	    offsetof(struct receive_objnode, node));
1946 	list->last_lookup = 0;
1947 }
1948 
1949 static void
1950 objlist_destroy(struct objlist *list)
1951 {
1952 	for (struct receive_objnode *n = list_remove_head(&list->list);
1953 	    n != NULL; n = list_remove_head(&list->list)) {
1954 		kmem_free(n, sizeof (*n));
1955 	}
1956 	list_destroy(&list->list);
1957 }
1958 
1959 /*
1960  * This function looks through the objlist to see if the specified object number
1961  * is contained in the objlist.  In the process, it will remove all object
1962  * numbers in the list that are smaller than the specified object number.  Thus,
1963  * any lookup of an object number smaller than a previously looked up object
1964  * number will always return false; therefore, all lookups should be done in
1965  * ascending order.
1966  */
1967 static boolean_t
1968 objlist_exists(struct objlist *list, uint64_t object)
1969 {
1970 	struct receive_objnode *node = list_head(&list->list);
1971 	ASSERT3U(object, >=, list->last_lookup);
1972 	list->last_lookup = object;
1973 	while (node != NULL && node->object < object) {
1974 		VERIFY3P(node, ==, list_remove_head(&list->list));
1975 		kmem_free(node, sizeof (*node));
1976 		node = list_head(&list->list);
1977 	}
1978 	return (node != NULL && node->object == object);
1979 }
1980 
1981 /*
1982  * The objlist is a list of object numbers stored in ascending order.  However,
1983  * the insertion of new object numbers does not seek out the correct location to
1984  * store a new object number; instead, it appends it to the list for simplicity.
1985  * Thus, any users must take care to only insert new object numbers in ascending
1986  * order.
1987  */
1988 static void
1989 objlist_insert(struct objlist *list, uint64_t object)
1990 {
1991 	struct receive_objnode *node = kmem_zalloc(sizeof (*node), KM_SLEEP);
1992 	node->object = object;
1993 #ifdef ZFS_DEBUG
1994 	struct receive_objnode *last_object = list_tail(&list->list);
1995 	uint64_t last_objnum = (last_object != NULL ? last_object->object : 0);
1996 	ASSERT3U(node->object, >, last_objnum);
1997 #endif
1998 	list_insert_tail(&list->list, node);
1999 }
2000 
2001 /*
2002  * Issue the prefetch reads for any necessary indirect blocks.
2003  *
2004  * We use the object ignore list to tell us whether or not to issue prefetches
2005  * for a given object.  We do this for both correctness (in case the blocksize
2006  * of an object has changed) and performance (if the object doesn't exist, don't
2007  * needlessly try to issue prefetches).  We also trim the list as we go through
2008  * the stream to prevent it from growing to an unbounded size.
2009  *
2010  * The object numbers within will always be in sorted order, and any write
2011  * records we see will also be in sorted order, but they're not sorted with
2012  * respect to each other (i.e. we can get several object records before
2013  * receiving each object's write records).  As a result, once we've reached a
2014  * given object number, we can safely remove any reference to lower object
2015  * numbers in the ignore list. In practice, we receive up to 32 object records
2016  * before receiving write records, so the list can have up to 32 nodes in it.
2017  */
2018 /* ARGSUSED */
2019 static void
2020 receive_read_prefetch(struct receive_arg *ra,
2021     uint64_t object, uint64_t offset, uint64_t length)
2022 {
2023 	if (!objlist_exists(&ra->ignore_objlist, object)) {
2024 		dmu_prefetch(ra->os, object, 1, offset, length,
2025 		    ZIO_PRIORITY_SYNC_READ);
2026 	}
2027 }
2028 
2029 /*
2030  * Read records off the stream, issuing any necessary prefetches.
2031  */
2032 static int
2033 receive_read_record(struct receive_arg *ra)
2034 {
2035 	int err;
2036 
2037 	switch (ra->rrd->header.drr_type) {
2038 	case DRR_OBJECT:
2039 	{
2040 		struct drr_object *drro = &ra->rrd->header.drr_u.drr_object;
2041 		uint32_t size = DRR_OBJECT_PAYLOAD_SIZE(drro);
2042 		void *buf = NULL;
2043 		dmu_object_info_t doi;
2044 
2045 		if (size != 0)
2046 			buf = kmem_zalloc(size, KM_SLEEP);
2047 
2048 		err = receive_read_payload_and_next_header(ra, size, buf);
2049 		if (err != 0) {
2050 			kmem_free(buf, size);
2051 			return (err);
2052 		}
2053 		err = dmu_object_info(ra->os, drro->drr_object, &doi);
2054 		/*
2055 		 * See receive_read_prefetch for an explanation why we're
2056 		 * storing this object in the ignore_obj_list.
2057 		 */
2058 		if (err == ENOENT || err == EEXIST ||
2059 		    (err == 0 && doi.doi_data_block_size != drro->drr_blksz)) {
2060 			objlist_insert(&ra->ignore_objlist, drro->drr_object);
2061 			err = 0;
2062 		}
2063 		return (err);
2064 	}
2065 	case DRR_FREEOBJECTS:
2066 	{
2067 		err = receive_read_payload_and_next_header(ra, 0, NULL);
2068 		return (err);
2069 	}
2070 	case DRR_WRITE:
2071 	{
2072 		struct drr_write *drrw = &ra->rrd->header.drr_u.drr_write;
2073 		arc_buf_t *abuf;
2074 		boolean_t is_meta = DMU_OT_IS_METADATA(drrw->drr_type);
2075 
2076 		if (ra->raw) {
2077 			boolean_t byteorder = ZFS_HOST_BYTEORDER ^
2078 			    !!DRR_IS_RAW_BYTESWAPPED(drrw->drr_flags) ^
2079 			    ra->byteswap;
2080 
2081 			abuf = arc_loan_raw_buf(dmu_objset_spa(ra->os),
2082 			    drrw->drr_object, byteorder, drrw->drr_salt,
2083 			    drrw->drr_iv, drrw->drr_mac, drrw->drr_type,
2084 			    drrw->drr_compressed_size, drrw->drr_logical_size,
2085 			    drrw->drr_compressiontype);
2086 		} else if (DRR_WRITE_COMPRESSED(drrw)) {
2087 			ASSERT3U(drrw->drr_compressed_size, >, 0);
2088 			ASSERT3U(drrw->drr_logical_size, >=,
2089 			    drrw->drr_compressed_size);
2090 			ASSERT(!is_meta);
2091 			abuf = arc_loan_compressed_buf(
2092 			    dmu_objset_spa(ra->os),
2093 			    drrw->drr_compressed_size, drrw->drr_logical_size,
2094 			    drrw->drr_compressiontype);
2095 		} else {
2096 			abuf = arc_loan_buf(dmu_objset_spa(ra->os),
2097 			    is_meta, drrw->drr_logical_size);
2098 		}
2099 
2100 		err = receive_read_payload_and_next_header(ra,
2101 		    DRR_WRITE_PAYLOAD_SIZE(drrw), abuf->b_data);
2102 		if (err != 0) {
2103 			dmu_return_arcbuf(abuf);
2104 			return (err);
2105 		}
2106 		ra->rrd->arc_buf = abuf;
2107 		receive_read_prefetch(ra, drrw->drr_object, drrw->drr_offset,
2108 		    drrw->drr_logical_size);
2109 		return (err);
2110 	}
2111 	case DRR_WRITE_BYREF:
2112 	{
2113 		struct drr_write_byref *drrwb =
2114 		    &ra->rrd->header.drr_u.drr_write_byref;
2115 		err = receive_read_payload_and_next_header(ra, 0, NULL);
2116 		receive_read_prefetch(ra, drrwb->drr_object, drrwb->drr_offset,
2117 		    drrwb->drr_length);
2118 		return (err);
2119 	}
2120 	case DRR_WRITE_EMBEDDED:
2121 	{
2122 		struct drr_write_embedded *drrwe =
2123 		    &ra->rrd->header.drr_u.drr_write_embedded;
2124 		uint32_t size = P2ROUNDUP(drrwe->drr_psize, 8);
2125 		void *buf = kmem_zalloc(size, KM_SLEEP);
2126 
2127 		err = receive_read_payload_and_next_header(ra, size, buf);
2128 		if (err != 0) {
2129 			kmem_free(buf, size);
2130 			return (err);
2131 		}
2132 
2133 		receive_read_prefetch(ra, drrwe->drr_object, drrwe->drr_offset,
2134 		    drrwe->drr_length);
2135 		return (err);
2136 	}
2137 	case DRR_FREE:
2138 	{
2139 		/*
2140 		 * It might be beneficial to prefetch indirect blocks here, but
2141 		 * we don't really have the data to decide for sure.
2142 		 */
2143 		err = receive_read_payload_and_next_header(ra, 0, NULL);
2144 		return (err);
2145 	}
2146 	case DRR_END:
2147 	{
2148 		struct drr_end *drre = &ra->rrd->header.drr_u.drr_end;
2149 		if (!ZIO_CHECKSUM_EQUAL(ra->prev_cksum, drre->drr_checksum))
2150 			return (SET_ERROR(ECKSUM));
2151 		return (0);
2152 	}
2153 	case DRR_SPILL:
2154 	{
2155 		struct drr_spill *drrs = &ra->rrd->header.drr_u.drr_spill;
2156 		arc_buf_t *abuf;
2157 		int len = DRR_SPILL_PAYLOAD_SIZE(drrs);
2158 
2159 		/* DRR_SPILL records are either raw or uncompressed */
2160 		if (ra->raw) {
2161 			boolean_t byteorder = ZFS_HOST_BYTEORDER ^
2162 			    !!DRR_IS_RAW_BYTESWAPPED(drrs->drr_flags) ^
2163 			    ra->byteswap;
2164 
2165 			abuf = arc_loan_raw_buf(dmu_objset_spa(ra->os),
2166 			    dmu_objset_id(ra->os), byteorder, drrs->drr_salt,
2167 			    drrs->drr_iv, drrs->drr_mac, drrs->drr_type,
2168 			    drrs->drr_compressed_size, drrs->drr_length,
2169 			    drrs->drr_compressiontype);
2170 		} else {
2171 			abuf = arc_loan_buf(dmu_objset_spa(ra->os),
2172 			    DMU_OT_IS_METADATA(drrs->drr_type),
2173 			    drrs->drr_length);
2174 		}
2175 
2176 		err = receive_read_payload_and_next_header(ra, len,
2177 		    abuf->b_data);
2178 		if (err != 0) {
2179 			dmu_return_arcbuf(abuf);
2180 			return (err);
2181 		}
2182 		ra->rrd->arc_buf = abuf;
2183 		return (err);
2184 	}
2185 	case DRR_OBJECT_RANGE:
2186 	{
2187 		err = receive_read_payload_and_next_header(ra, 0, NULL);
2188 		return (err);
2189 	}
2190 	default:
2191 		return (SET_ERROR(EINVAL));
2192 	}
2193 }
2194 
2195 /*
2196  * Commit the records to the pool.
2197  */
2198 static int
2199 receive_process_record(struct receive_writer_arg *rwa,
2200     struct receive_record_arg *rrd)
2201 {
2202 	int err;
2203 
2204 	/* Processing in order, therefore bytes_read should be increasing. */
2205 	ASSERT3U(rrd->bytes_read, >=, rwa->bytes_read);
2206 	rwa->bytes_read = rrd->bytes_read;
2207 
2208 	switch (rrd->header.drr_type) {
2209 	case DRR_OBJECT:
2210 	{
2211 		struct drr_object *drro = &rrd->header.drr_u.drr_object;
2212 		err = receive_object(rwa, drro, rrd->payload);
2213 		kmem_free(rrd->payload, rrd->payload_size);
2214 		rrd->payload = NULL;
2215 		return (err);
2216 	}
2217 	case DRR_FREEOBJECTS:
2218 	{
2219 		struct drr_freeobjects *drrfo =
2220 		    &rrd->header.drr_u.drr_freeobjects;
2221 		return (receive_freeobjects(rwa, drrfo));
2222 	}
2223 	case DRR_WRITE:
2224 	{
2225 		struct drr_write *drrw = &rrd->header.drr_u.drr_write;
2226 		err = receive_write(rwa, drrw, rrd->arc_buf);
2227 		/* if receive_write() is successful, it consumes the arc_buf */
2228 		if (err != 0)
2229 			dmu_return_arcbuf(rrd->arc_buf);
2230 		rrd->arc_buf = NULL;
2231 		rrd->payload = NULL;
2232 		return (err);
2233 	}
2234 	case DRR_WRITE_BYREF:
2235 	{
2236 		struct drr_write_byref *drrwbr =
2237 		    &rrd->header.drr_u.drr_write_byref;
2238 		return (receive_write_byref(rwa, drrwbr));
2239 	}
2240 	case DRR_WRITE_EMBEDDED:
2241 	{
2242 		struct drr_write_embedded *drrwe =
2243 		    &rrd->header.drr_u.drr_write_embedded;
2244 		err = receive_write_embedded(rwa, drrwe, rrd->payload);
2245 		kmem_free(rrd->payload, rrd->payload_size);
2246 		rrd->payload = NULL;
2247 		return (err);
2248 	}
2249 	case DRR_FREE:
2250 	{
2251 		struct drr_free *drrf = &rrd->header.drr_u.drr_free;
2252 		return (receive_free(rwa, drrf));
2253 	}
2254 	case DRR_SPILL:
2255 	{
2256 		struct drr_spill *drrs = &rrd->header.drr_u.drr_spill;
2257 		err = receive_spill(rwa, drrs, rrd->arc_buf);
2258 		/* if receive_spill() is successful, it consumes the arc_buf */
2259 		if (err != 0)
2260 			dmu_return_arcbuf(rrd->arc_buf);
2261 		rrd->arc_buf = NULL;
2262 		rrd->payload = NULL;
2263 		return (err);
2264 	}
2265 	case DRR_OBJECT_RANGE:
2266 	{
2267 		struct drr_object_range *drror =
2268 		    &rrd->header.drr_u.drr_object_range;
2269 		return (receive_object_range(rwa, drror));
2270 	}
2271 	default:
2272 		return (SET_ERROR(EINVAL));
2273 	}
2274 }
2275 
2276 /*
2277  * dmu_recv_stream's worker thread; pull records off the queue, and then call
2278  * receive_process_record  When we're done, signal the main thread and exit.
2279  */
2280 static void
2281 receive_writer_thread(void *arg)
2282 {
2283 	struct receive_writer_arg *rwa = arg;
2284 	struct receive_record_arg *rrd;
2285 	for (rrd = bqueue_dequeue(&rwa->q); !rrd->eos_marker;
2286 	    rrd = bqueue_dequeue(&rwa->q)) {
2287 		/*
2288 		 * If there's an error, the main thread will stop putting things
2289 		 * on the queue, but we need to clear everything in it before we
2290 		 * can exit.
2291 		 */
2292 		if (rwa->err == 0) {
2293 			rwa->err = receive_process_record(rwa, rrd);
2294 		} else if (rrd->arc_buf != NULL) {
2295 			dmu_return_arcbuf(rrd->arc_buf);
2296 			rrd->arc_buf = NULL;
2297 			rrd->payload = NULL;
2298 		} else if (rrd->payload != NULL) {
2299 			kmem_free(rrd->payload, rrd->payload_size);
2300 			rrd->payload = NULL;
2301 		}
2302 		kmem_free(rrd, sizeof (*rrd));
2303 	}
2304 	kmem_free(rrd, sizeof (*rrd));
2305 	mutex_enter(&rwa->mutex);
2306 	rwa->done = B_TRUE;
2307 	cv_signal(&rwa->cv);
2308 	mutex_exit(&rwa->mutex);
2309 	thread_exit();
2310 }
2311 
2312 static int
2313 resume_check(struct receive_arg *ra, nvlist_t *begin_nvl)
2314 {
2315 	uint64_t val;
2316 	objset_t *mos = dmu_objset_pool(ra->os)->dp_meta_objset;
2317 	uint64_t dsobj = dmu_objset_id(ra->os);
2318 	uint64_t resume_obj, resume_off;
2319 
2320 	if (nvlist_lookup_uint64(begin_nvl,
2321 	    "resume_object", &resume_obj) != 0 ||
2322 	    nvlist_lookup_uint64(begin_nvl,
2323 	    "resume_offset", &resume_off) != 0) {
2324 		return (SET_ERROR(EINVAL));
2325 	}
2326 	VERIFY0(zap_lookup(mos, dsobj,
2327 	    DS_FIELD_RESUME_OBJECT, sizeof (val), 1, &val));
2328 	if (resume_obj != val)
2329 		return (SET_ERROR(EINVAL));
2330 	VERIFY0(zap_lookup(mos, dsobj,
2331 	    DS_FIELD_RESUME_OFFSET, sizeof (val), 1, &val));
2332 	if (resume_off != val)
2333 		return (SET_ERROR(EINVAL));
2334 
2335 	return (0);
2336 }
2337 
2338 /*
2339  * Read in the stream's records, one by one, and apply them to the pool.  There
2340  * are two threads involved; the thread that calls this function will spin up a
2341  * worker thread, read the records off the stream one by one, and issue
2342  * prefetches for any necessary indirect blocks.  It will then push the records
2343  * onto an internal blocking queue.  The worker thread will pull the records off
2344  * the queue, and actually write the data into the DMU.  This way, the worker
2345  * thread doesn't have to wait for reads to complete, since everything it needs
2346  * (the indirect blocks) will be prefetched.
2347  *
2348  * NB: callers *must* call dmu_recv_end() if this succeeds.
2349  */
2350 int
2351 dmu_recv_stream(dmu_recv_cookie_t *drc, vnode_t *vp, offset_t *voffp,
2352     int cleanup_fd, uint64_t *action_handlep)
2353 {
2354 	int err = 0;
2355 	struct receive_arg ra = { 0 };
2356 	struct receive_writer_arg rwa = { 0 };
2357 	int featureflags;
2358 	nvlist_t *begin_nvl = NULL;
2359 
2360 	ra.byteswap = drc->drc_byteswap;
2361 	ra.raw = drc->drc_raw;
2362 	ra.cksum = drc->drc_cksum;
2363 	ra.vp = vp;
2364 	ra.voff = *voffp;
2365 
2366 	if (dsl_dataset_is_zapified(drc->drc_ds)) {
2367 		(void) zap_lookup(drc->drc_ds->ds_dir->dd_pool->dp_meta_objset,
2368 		    drc->drc_ds->ds_object, DS_FIELD_RESUME_BYTES,
2369 		    sizeof (ra.bytes_read), 1, &ra.bytes_read);
2370 	}
2371 
2372 	objlist_create(&ra.ignore_objlist);
2373 
2374 	/* these were verified in dmu_recv_begin */
2375 	ASSERT3U(DMU_GET_STREAM_HDRTYPE(drc->drc_drrb->drr_versioninfo), ==,
2376 	    DMU_SUBSTREAM);
2377 	ASSERT3U(drc->drc_drrb->drr_type, <, DMU_OST_NUMTYPES);
2378 
2379 	/*
2380 	 * Open the objset we are modifying.
2381 	 */
2382 	VERIFY0(dmu_objset_from_ds(drc->drc_ds, &ra.os));
2383 
2384 	ASSERT(dsl_dataset_phys(drc->drc_ds)->ds_flags & DS_FLAG_INCONSISTENT);
2385 
2386 	featureflags = DMU_GET_FEATUREFLAGS(drc->drc_drrb->drr_versioninfo);
2387 	ra.featureflags = featureflags;
2388 
2389 	ASSERT0(ra.os->os_encrypted &&
2390 	    (featureflags & DMU_BACKUP_FEATURE_EMBED_DATA));
2391 
2392 	/* if this stream is dedup'ed, set up the avl tree for guid mapping */
2393 	if (featureflags & DMU_BACKUP_FEATURE_DEDUP) {
2394 		minor_t minor;
2395 
2396 		if (cleanup_fd == -1) {
2397 			err = SET_ERROR(EBADF);
2398 			goto out;
2399 		}
2400 		err = zfs_onexit_fd_hold(cleanup_fd, &minor);
2401 		if (err != 0) {
2402 			cleanup_fd = -1;
2403 			goto out;
2404 		}
2405 
2406 		if (*action_handlep == 0) {
2407 			rwa.guid_to_ds_map =
2408 			    kmem_alloc(sizeof (avl_tree_t), KM_SLEEP);
2409 			avl_create(rwa.guid_to_ds_map, guid_compare,
2410 			    sizeof (guid_map_entry_t),
2411 			    offsetof(guid_map_entry_t, avlnode));
2412 			err = zfs_onexit_add_cb(minor,
2413 			    free_guid_map_onexit, rwa.guid_to_ds_map,
2414 			    action_handlep);
2415 			if (err != 0)
2416 				goto out;
2417 		} else {
2418 			err = zfs_onexit_cb_data(minor, *action_handlep,
2419 			    (void **)&rwa.guid_to_ds_map);
2420 			if (err != 0)
2421 				goto out;
2422 		}
2423 
2424 		drc->drc_guid_to_ds_map = rwa.guid_to_ds_map;
2425 	}
2426 
2427 	uint32_t payloadlen = drc->drc_drr_begin->drr_payloadlen;
2428 	void *payload = NULL;
2429 	if (payloadlen != 0)
2430 		payload = kmem_alloc(payloadlen, KM_SLEEP);
2431 
2432 	err = receive_read_payload_and_next_header(&ra, payloadlen, payload);
2433 	if (err != 0) {
2434 		if (payloadlen != 0)
2435 			kmem_free(payload, payloadlen);
2436 		goto out;
2437 	}
2438 	if (payloadlen != 0) {
2439 		err = nvlist_unpack(payload, payloadlen, &begin_nvl, KM_SLEEP);
2440 		kmem_free(payload, payloadlen);
2441 		if (err != 0)
2442 			goto out;
2443 	}
2444 
2445 	/* handle DSL encryption key payload */
2446 	if (featureflags & DMU_BACKUP_FEATURE_RAW) {
2447 		nvlist_t *keynvl = NULL;
2448 
2449 		ASSERT(ra.os->os_encrypted);
2450 		ASSERT(drc->drc_raw);
2451 
2452 		err = nvlist_lookup_nvlist(begin_nvl, "crypt_keydata", &keynvl);
2453 		if (err != 0)
2454 			goto out;
2455 
2456 		/*
2457 		 * If this is a new dataset we set the key immediately.
2458 		 * Otherwise we don't want to change the key until we
2459 		 * are sure the rest of the receive succeeded so we stash
2460 		 * the keynvl away until then.
2461 		 */
2462 		err = dsl_crypto_recv_raw(spa_name(ra.os->os_spa),
2463 		    drc->drc_ds->ds_object, drc->drc_fromsnapobj,
2464 		    drc->drc_drrb->drr_type, keynvl, drc->drc_newfs);
2465 		if (err != 0)
2466 			goto out;
2467 
2468 		/* see comment in dmu_recv_end_sync() */
2469 		drc->drc_ivset_guid = 0;
2470 		(void) nvlist_lookup_uint64(keynvl, "to_ivset_guid",
2471 		    &drc->drc_ivset_guid);
2472 
2473 		if (!drc->drc_newfs)
2474 			drc->drc_keynvl = fnvlist_dup(keynvl);
2475 	}
2476 
2477 	if (featureflags & DMU_BACKUP_FEATURE_RESUMING) {
2478 		err = resume_check(&ra, begin_nvl);
2479 		if (err != 0)
2480 			goto out;
2481 	}
2482 
2483 	(void) bqueue_init(&rwa.q,
2484 	    MAX(zfs_recv_queue_length, 2 * zfs_max_recordsize),
2485 	    offsetof(struct receive_record_arg, node));
2486 	cv_init(&rwa.cv, NULL, CV_DEFAULT, NULL);
2487 	mutex_init(&rwa.mutex, NULL, MUTEX_DEFAULT, NULL);
2488 	rwa.os = ra.os;
2489 	rwa.byteswap = drc->drc_byteswap;
2490 	rwa.resumable = drc->drc_resumable;
2491 	rwa.raw = drc->drc_raw;
2492 	rwa.spill = drc->drc_spill;
2493 	rwa.os->os_raw_receive = drc->drc_raw;
2494 
2495 	(void) thread_create(NULL, 0, receive_writer_thread, &rwa, 0, curproc,
2496 	    TS_RUN, minclsyspri);
2497 	/*
2498 	 * We're reading rwa.err without locks, which is safe since we are the
2499 	 * only reader, and the worker thread is the only writer.  It's ok if we
2500 	 * miss a write for an iteration or two of the loop, since the writer
2501 	 * thread will keep freeing records we send it until we send it an eos
2502 	 * marker.
2503 	 *
2504 	 * We can leave this loop in 3 ways:  First, if rwa.err is
2505 	 * non-zero.  In that case, the writer thread will free the rrd we just
2506 	 * pushed.  Second, if  we're interrupted; in that case, either it's the
2507 	 * first loop and ra.rrd was never allocated, or it's later, and ra.rrd
2508 	 * has been handed off to the writer thread who will free it.  Finally,
2509 	 * if receive_read_record fails or we're at the end of the stream, then
2510 	 * we free ra.rrd and exit.
2511 	 */
2512 	while (rwa.err == 0) {
2513 		if (issig(JUSTLOOKING) && issig(FORREAL)) {
2514 			err = SET_ERROR(EINTR);
2515 			break;
2516 		}
2517 
2518 		ASSERT3P(ra.rrd, ==, NULL);
2519 		ra.rrd = ra.next_rrd;
2520 		ra.next_rrd = NULL;
2521 		/* Allocates and loads header into ra.next_rrd */
2522 		err = receive_read_record(&ra);
2523 
2524 		if (ra.rrd->header.drr_type == DRR_END || err != 0) {
2525 			kmem_free(ra.rrd, sizeof (*ra.rrd));
2526 			ra.rrd = NULL;
2527 			break;
2528 		}
2529 
2530 		bqueue_enqueue(&rwa.q, ra.rrd,
2531 		    sizeof (struct receive_record_arg) + ra.rrd->payload_size);
2532 		ra.rrd = NULL;
2533 	}
2534 	ASSERT3P(ra.rrd, ==, NULL);
2535 	ra.rrd = kmem_zalloc(sizeof (*ra.rrd), KM_SLEEP);
2536 	ra.rrd->eos_marker = B_TRUE;
2537 	bqueue_enqueue(&rwa.q, ra.rrd, 1);
2538 
2539 	mutex_enter(&rwa.mutex);
2540 	while (!rwa.done) {
2541 		cv_wait(&rwa.cv, &rwa.mutex);
2542 	}
2543 	mutex_exit(&rwa.mutex);
2544 
2545 	/*
2546 	 * If we are receiving a full stream as a clone, all object IDs which
2547 	 * are greater than the maximum ID referenced in the stream are
2548 	 * by definition unused and must be freed. Note that it's possible that
2549 	 * we've resumed this send and the first record we received was the END
2550 	 * record. In that case, max_object would be 0, but we shouldn't start
2551 	 * freeing all objects from there; instead we should start from the
2552 	 * resumeobj.
2553 	 */
2554 	if (drc->drc_clone && drc->drc_drrb->drr_fromguid == 0) {
2555 		uint64_t obj;
2556 		if (nvlist_lookup_uint64(begin_nvl, "resume_object", &obj) != 0)
2557 			obj = 0;
2558 		if (rwa.max_object > obj)
2559 			obj = rwa.max_object;
2560 		obj++;
2561 		int free_err = 0;
2562 		int next_err = 0;
2563 
2564 		while (next_err == 0) {
2565 			free_err = dmu_free_long_object(rwa.os, obj);
2566 			if (free_err != 0 && free_err != ENOENT)
2567 				break;
2568 
2569 			next_err = dmu_object_next(rwa.os, &obj, FALSE, 0);
2570 		}
2571 
2572 		if (err == 0) {
2573 			if (free_err != 0 && free_err != ENOENT)
2574 				err = free_err;
2575 			else if (next_err != ESRCH)
2576 				err = next_err;
2577 		}
2578 	}
2579 
2580 	cv_destroy(&rwa.cv);
2581 	mutex_destroy(&rwa.mutex);
2582 	bqueue_destroy(&rwa.q);
2583 	if (err == 0)
2584 		err = rwa.err;
2585 
2586 out:
2587 	/*
2588 	 * If we hit an error before we started the receive_writer_thread
2589 	 * we need to clean up the next_rrd we create by processing the
2590 	 * DRR_BEGIN record.
2591 	 */
2592 	if (ra.next_rrd != NULL)
2593 		kmem_free(ra.next_rrd, sizeof (*ra.next_rrd));
2594 
2595 	nvlist_free(begin_nvl);
2596 	if ((featureflags & DMU_BACKUP_FEATURE_DEDUP) && (cleanup_fd != -1))
2597 		zfs_onexit_fd_rele(cleanup_fd);
2598 
2599 	if (err != 0) {
2600 		/*
2601 		 * Clean up references. If receive is not resumable,
2602 		 * destroy what we created, so we don't leave it in
2603 		 * the inconsistent state.
2604 		 */
2605 		dmu_recv_cleanup_ds(drc);
2606 		nvlist_free(drc->drc_keynvl);
2607 	}
2608 
2609 	*voffp = ra.voff;
2610 	objlist_destroy(&ra.ignore_objlist);
2611 	return (err);
2612 }
2613 
2614 static int
2615 dmu_recv_end_check(void *arg, dmu_tx_t *tx)
2616 {
2617 	dmu_recv_cookie_t *drc = arg;
2618 	dsl_pool_t *dp = dmu_tx_pool(tx);
2619 	int error;
2620 
2621 	ASSERT3P(drc->drc_ds->ds_owner, ==, dmu_recv_tag);
2622 
2623 	if (!drc->drc_newfs) {
2624 		dsl_dataset_t *origin_head;
2625 
2626 		error = dsl_dataset_hold(dp, drc->drc_tofs, FTAG, &origin_head);
2627 		if (error != 0)
2628 			return (error);
2629 		if (drc->drc_force) {
2630 			/*
2631 			 * We will destroy any snapshots in tofs (i.e. before
2632 			 * origin_head) that are after the origin (which is
2633 			 * the snap before drc_ds, because drc_ds can not
2634 			 * have any snaps of its own).
2635 			 */
2636 			uint64_t obj;
2637 
2638 			obj = dsl_dataset_phys(origin_head)->ds_prev_snap_obj;
2639 			while (obj !=
2640 			    dsl_dataset_phys(drc->drc_ds)->ds_prev_snap_obj) {
2641 				dsl_dataset_t *snap;
2642 				error = dsl_dataset_hold_obj(dp, obj, FTAG,
2643 				    &snap);
2644 				if (error != 0)
2645 					break;
2646 				if (snap->ds_dir != origin_head->ds_dir)
2647 					error = SET_ERROR(EINVAL);
2648 				if (error == 0)  {
2649 					error = dsl_destroy_snapshot_check_impl(
2650 					    snap, B_FALSE);
2651 				}
2652 				obj = dsl_dataset_phys(snap)->ds_prev_snap_obj;
2653 				dsl_dataset_rele(snap, FTAG);
2654 				if (error != 0)
2655 					break;
2656 			}
2657 			if (error != 0) {
2658 				dsl_dataset_rele(origin_head, FTAG);
2659 				return (error);
2660 			}
2661 		}
2662 		if (drc->drc_keynvl != NULL) {
2663 			error = dsl_crypto_recv_raw_key_check(drc->drc_ds,
2664 			    drc->drc_keynvl, tx);
2665 			if (error != 0) {
2666 				dsl_dataset_rele(origin_head, FTAG);
2667 				return (error);
2668 			}
2669 		}
2670 
2671 		error = dsl_dataset_clone_swap_check_impl(drc->drc_ds,
2672 		    origin_head, drc->drc_force, drc->drc_owner, tx);
2673 		if (error != 0) {
2674 			dsl_dataset_rele(origin_head, FTAG);
2675 			return (error);
2676 		}
2677 		error = dsl_dataset_snapshot_check_impl(origin_head,
2678 		    drc->drc_tosnap, tx, B_TRUE, 1, drc->drc_cred);
2679 		dsl_dataset_rele(origin_head, FTAG);
2680 		if (error != 0)
2681 			return (error);
2682 
2683 		error = dsl_destroy_head_check_impl(drc->drc_ds, 1);
2684 	} else {
2685 		error = dsl_dataset_snapshot_check_impl(drc->drc_ds,
2686 		    drc->drc_tosnap, tx, B_TRUE, 1, drc->drc_cred);
2687 	}
2688 	return (error);
2689 }
2690 
2691 static void
2692 dmu_recv_end_sync(void *arg, dmu_tx_t *tx)
2693 {
2694 	dmu_recv_cookie_t *drc = arg;
2695 	dsl_pool_t *dp = dmu_tx_pool(tx);
2696 	boolean_t encrypted = drc->drc_ds->ds_dir->dd_crypto_obj != 0;
2697 
2698 	spa_history_log_internal_ds(drc->drc_ds, "finish receiving",
2699 	    tx, "snap=%s", drc->drc_tosnap);
2700 	drc->drc_ds->ds_objset->os_raw_receive = B_FALSE;
2701 
2702 	if (!drc->drc_newfs) {
2703 		dsl_dataset_t *origin_head;
2704 
2705 		VERIFY0(dsl_dataset_hold(dp, drc->drc_tofs, FTAG,
2706 		    &origin_head));
2707 
2708 		if (drc->drc_force) {
2709 			/*
2710 			 * Destroy any snapshots of drc_tofs (origin_head)
2711 			 * after the origin (the snap before drc_ds).
2712 			 */
2713 			uint64_t obj;
2714 
2715 			obj = dsl_dataset_phys(origin_head)->ds_prev_snap_obj;
2716 			while (obj !=
2717 			    dsl_dataset_phys(drc->drc_ds)->ds_prev_snap_obj) {
2718 				dsl_dataset_t *snap;
2719 				VERIFY0(dsl_dataset_hold_obj(dp, obj, FTAG,
2720 				    &snap));
2721 				ASSERT3P(snap->ds_dir, ==, origin_head->ds_dir);
2722 				obj = dsl_dataset_phys(snap)->ds_prev_snap_obj;
2723 				dsl_destroy_snapshot_sync_impl(snap,
2724 				    B_FALSE, tx);
2725 				dsl_dataset_rele(snap, FTAG);
2726 			}
2727 		}
2728 		if (drc->drc_keynvl != NULL) {
2729 			dsl_crypto_recv_raw_key_sync(drc->drc_ds,
2730 			    drc->drc_keynvl, tx);
2731 			nvlist_free(drc->drc_keynvl);
2732 			drc->drc_keynvl = NULL;
2733 		}
2734 
2735 		VERIFY3P(drc->drc_ds->ds_prev, ==, origin_head->ds_prev);
2736 
2737 		dsl_dataset_clone_swap_sync_impl(drc->drc_ds,
2738 		    origin_head, tx);
2739 		dsl_dataset_snapshot_sync_impl(origin_head,
2740 		    drc->drc_tosnap, tx);
2741 
2742 		/* set snapshot's creation time and guid */
2743 		dmu_buf_will_dirty(origin_head->ds_prev->ds_dbuf, tx);
2744 		dsl_dataset_phys(origin_head->ds_prev)->ds_creation_time =
2745 		    drc->drc_drrb->drr_creation_time;
2746 		dsl_dataset_phys(origin_head->ds_prev)->ds_guid =
2747 		    drc->drc_drrb->drr_toguid;
2748 		dsl_dataset_phys(origin_head->ds_prev)->ds_flags &=
2749 		    ~DS_FLAG_INCONSISTENT;
2750 
2751 		dmu_buf_will_dirty(origin_head->ds_dbuf, tx);
2752 		dsl_dataset_phys(origin_head)->ds_flags &=
2753 		    ~DS_FLAG_INCONSISTENT;
2754 
2755 		drc->drc_newsnapobj =
2756 		    dsl_dataset_phys(origin_head)->ds_prev_snap_obj;
2757 
2758 		dsl_dataset_rele(origin_head, FTAG);
2759 		dsl_destroy_head_sync_impl(drc->drc_ds, tx);
2760 
2761 		if (drc->drc_owner != NULL)
2762 			VERIFY3P(origin_head->ds_owner, ==, drc->drc_owner);
2763 	} else {
2764 		dsl_dataset_t *ds = drc->drc_ds;
2765 
2766 		dsl_dataset_snapshot_sync_impl(ds, drc->drc_tosnap, tx);
2767 
2768 		/* set snapshot's creation time and guid */
2769 		dmu_buf_will_dirty(ds->ds_prev->ds_dbuf, tx);
2770 		dsl_dataset_phys(ds->ds_prev)->ds_creation_time =
2771 		    drc->drc_drrb->drr_creation_time;
2772 		dsl_dataset_phys(ds->ds_prev)->ds_guid =
2773 		    drc->drc_drrb->drr_toguid;
2774 		dsl_dataset_phys(ds->ds_prev)->ds_flags &=
2775 		    ~DS_FLAG_INCONSISTENT;
2776 
2777 		dmu_buf_will_dirty(ds->ds_dbuf, tx);
2778 		dsl_dataset_phys(ds)->ds_flags &= ~DS_FLAG_INCONSISTENT;
2779 		if (dsl_dataset_has_resume_receive_state(ds)) {
2780 			(void) zap_remove(dp->dp_meta_objset, ds->ds_object,
2781 			    DS_FIELD_RESUME_FROMGUID, tx);
2782 			(void) zap_remove(dp->dp_meta_objset, ds->ds_object,
2783 			    DS_FIELD_RESUME_OBJECT, tx);
2784 			(void) zap_remove(dp->dp_meta_objset, ds->ds_object,
2785 			    DS_FIELD_RESUME_OFFSET, tx);
2786 			(void) zap_remove(dp->dp_meta_objset, ds->ds_object,
2787 			    DS_FIELD_RESUME_BYTES, tx);
2788 			(void) zap_remove(dp->dp_meta_objset, ds->ds_object,
2789 			    DS_FIELD_RESUME_TOGUID, tx);
2790 			(void) zap_remove(dp->dp_meta_objset, ds->ds_object,
2791 			    DS_FIELD_RESUME_TONAME, tx);
2792 		}
2793 		drc->drc_newsnapobj =
2794 		    dsl_dataset_phys(drc->drc_ds)->ds_prev_snap_obj;
2795 	}
2796 
2797 	/*
2798 	 * If this is a raw receive, the crypt_keydata nvlist will include
2799 	 * a to_ivset_guid for us to set on the new snapshot. This value
2800 	 * will override the value generated by the snapshot code. However,
2801 	 * this value may not be present, because older implementations of
2802 	 * the raw send code did not include this value, and we are still
2803 	 * allowed to receive them if the zfs_disable_ivset_guid_check
2804 	 * tunable is set, in which case we will leave the newly-generated
2805 	 * value.
2806 	 */
2807 	if (drc->drc_raw && drc->drc_ivset_guid != 0) {
2808 		dmu_object_zapify(dp->dp_meta_objset, drc->drc_newsnapobj,
2809 		    DMU_OT_DSL_DATASET, tx);
2810 		VERIFY0(zap_update(dp->dp_meta_objset, drc->drc_newsnapobj,
2811 		    DS_FIELD_IVSET_GUID, sizeof (uint64_t), 1,
2812 		    &drc->drc_ivset_guid, tx));
2813 	}
2814 
2815 	/*
2816 	 * Release the hold from dmu_recv_begin.  This must be done before
2817 	 * we return to open context, so that when we free the dataset's dnode
2818 	 * we can evict its bonus buffer. Since the dataset may be destroyed
2819 	 * at this point (and therefore won't have a valid pointer to the spa)
2820 	 * we release the key mapping manually here while we do have a valid
2821 	 * pointer, if it exists.
2822 	 */
2823 	if (!drc->drc_raw && encrypted) {
2824 		(void) spa_keystore_remove_mapping(dmu_tx_pool(tx)->dp_spa,
2825 		    drc->drc_ds->ds_object, drc->drc_ds);
2826 	}
2827 	dsl_dataset_disown(drc->drc_ds, 0, dmu_recv_tag);
2828 	drc->drc_ds = NULL;
2829 }
2830 
2831 static int
2832 add_ds_to_guidmap(const char *name, avl_tree_t *guid_map, uint64_t snapobj,
2833     boolean_t raw)
2834 {
2835 	dsl_pool_t *dp;
2836 	dsl_dataset_t *snapds;
2837 	guid_map_entry_t *gmep;
2838 	objset_t *os;
2839 	ds_hold_flags_t dsflags = (raw) ? 0 : DS_HOLD_FLAG_DECRYPT;
2840 	int err;
2841 
2842 	ASSERT(guid_map != NULL);
2843 
2844 	err = dsl_pool_hold(name, FTAG, &dp);
2845 	if (err != 0)
2846 		return (err);
2847 	gmep = kmem_alloc(sizeof (*gmep), KM_SLEEP);
2848 	err = dsl_dataset_own_obj(dp, snapobj, dsflags, gmep, &snapds);
2849 	if (err == 0) {
2850 		/*
2851 		 * If this is a deduplicated raw send stream, we need
2852 		 * to make sure that we can still read raw blocks from
2853 		 * earlier datasets in the stream, so we set the
2854 		 * os_raw_receive flag now.
2855 		 */
2856 		if (raw) {
2857 			err = dmu_objset_from_ds(snapds, &os);
2858 			if (err != 0) {
2859 				dsl_dataset_disown(snapds, dsflags, FTAG);
2860 				dsl_pool_rele(dp, FTAG);
2861 				kmem_free(gmep, sizeof (*gmep));
2862 				return (err);
2863 			}
2864 			os->os_raw_receive = B_TRUE;
2865 		}
2866 
2867 		gmep->raw = raw;
2868 		gmep->guid = dsl_dataset_phys(snapds)->ds_guid;
2869 		gmep->gme_ds = snapds;
2870 		avl_add(guid_map, gmep);
2871 	} else {
2872 		kmem_free(gmep, sizeof (*gmep));
2873 	}
2874 
2875 	dsl_pool_rele(dp, FTAG);
2876 	return (err);
2877 }
2878 
2879 static int dmu_recv_end_modified_blocks = 3;
2880 
2881 static int
2882 dmu_recv_existing_end(dmu_recv_cookie_t *drc)
2883 {
2884 #ifdef _KERNEL
2885 	/*
2886 	 * We will be destroying the ds; make sure its origin is unmounted if
2887 	 * necessary.
2888 	 */
2889 	char name[ZFS_MAX_DATASET_NAME_LEN];
2890 	dsl_dataset_name(drc->drc_ds, name);
2891 	zfs_destroy_unmount_origin(name);
2892 #endif
2893 
2894 	return (dsl_sync_task(drc->drc_tofs,
2895 	    dmu_recv_end_check, dmu_recv_end_sync, drc,
2896 	    dmu_recv_end_modified_blocks, ZFS_SPACE_CHECK_NORMAL));
2897 }
2898 
2899 static int
2900 dmu_recv_new_end(dmu_recv_cookie_t *drc)
2901 {
2902 	return (dsl_sync_task(drc->drc_tofs,
2903 	    dmu_recv_end_check, dmu_recv_end_sync, drc,
2904 	    dmu_recv_end_modified_blocks, ZFS_SPACE_CHECK_NORMAL));
2905 }
2906 
2907 int
2908 dmu_recv_end(dmu_recv_cookie_t *drc, void *owner)
2909 {
2910 	int error;
2911 
2912 	drc->drc_owner = owner;
2913 
2914 	if (drc->drc_newfs)
2915 		error = dmu_recv_new_end(drc);
2916 	else
2917 		error = dmu_recv_existing_end(drc);
2918 
2919 	if (error != 0) {
2920 		dmu_recv_cleanup_ds(drc);
2921 		nvlist_free(drc->drc_keynvl);
2922 	} else if (drc->drc_guid_to_ds_map != NULL) {
2923 		(void) add_ds_to_guidmap(drc->drc_tofs, drc->drc_guid_to_ds_map,
2924 		    drc->drc_newsnapobj, drc->drc_raw);
2925 	}
2926 	return (error);
2927 }
2928 
2929 /*
2930  * Return TRUE if this objset is currently being received into.
2931  */
2932 boolean_t
2933 dmu_objset_is_receiving(objset_t *os)
2934 {
2935 	return (os->os_dsl_dataset != NULL &&
2936 	    os->os_dsl_dataset->ds_owner == dmu_recv_tag);
2937 }
2938