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