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