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