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