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