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