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