xref: /freebsd/sys/contrib/openzfs/module/zfs/dmu_recv.c (revision 22649d4dba730d46244fd2dff4fd174903c8379f)
1 // SPDX-License-Identifier: CDDL-1.0
2 /*
3  * This file and its contents are supplied under the terms of the
4  * Common Development and Distribution License ("CDDL"), version 1.0.
5  * You may only use this file in accordance with the terms of version
6  * 1.0 of the CDDL.
7  *
8  * A full copy of the text of the CDDL should have accompanied this
9  * source.  A copy of the CDDL is also available via the Internet at
10  * https://opensource.org/license/CDDL-1.0.
11  */
12 /*
13  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
14  * Copyright 2011 Nexenta Systems, Inc. All rights reserved.
15  * Copyright (c) 2011, 2020 by Delphix. All rights reserved.
16  * Copyright (c) 2014, Joyent, Inc. All rights reserved.
17  * Copyright 2014 HybridCluster. All rights reserved.
18  * Copyright (c) 2018, loli10K <ezomori.nozomu@gmail.com>. All rights reserved.
19  * Copyright (c) 2019, 2024, Klara, Inc.
20  * Copyright (c) 2019, Allan Jude
21  * Copyright (c) 2019 Datto Inc.
22  * Copyright (c) 2022 Axcient.
23  * Copyright (c) 2025, Rob Norris <robn@despairlabs.com>
24  */
25 
26 #include <sys/arc.h>
27 #include <sys/spa_impl.h>
28 #include <sys/dmu.h>
29 #include <sys/dmu_impl.h>
30 #include <sys/dmu_send.h>
31 #include <sys/dmu_recv.h>
32 #include <sys/dmu_tx.h>
33 #include <sys/dbuf.h>
34 #include <sys/dnode.h>
35 #include <sys/zfs_context.h>
36 #include <sys/dmu_objset.h>
37 #include <sys/dmu_traverse.h>
38 #include <sys/dsl_dataset.h>
39 #include <sys/dsl_dir.h>
40 #include <sys/dsl_prop.h>
41 #include <sys/dsl_pool.h>
42 #include <sys/dsl_synctask.h>
43 #include <sys/zfs_ioctl.h>
44 #include <sys/zap.h>
45 #include <sys/zvol.h>
46 #include <sys/zio_checksum.h>
47 #include <sys/zfs_znode.h>
48 #include <zfs_fletcher.h>
49 #include <sys/avl.h>
50 #include <sys/ddt.h>
51 #include <sys/zfs_onexit.h>
52 #include <sys/dsl_destroy.h>
53 #include <sys/blkptr.h>
54 #include <sys/dsl_bookmark.h>
55 #include <sys/zfeature.h>
56 #include <sys/bqueue.h>
57 #include <sys/objlist.h>
58 #ifdef _KERNEL
59 #include <sys/zfs_vfsops.h>
60 #endif
61 #include <sys/zfs_file.h>
62 #include <sys/cred.h>
63 #include <sys/fs/zfs.h>
64 
65 static uint_t zfs_recv_queue_length = SPA_MAXBLOCKSIZE;
66 static uint_t zfs_recv_queue_ff = 20;
67 static uint_t zfs_recv_write_batch_size = 1024 * 1024;
68 static uint_t zfs_recv_defer_batch_size = 32 * 1024 * 1024;
69 static int zfs_recv_best_effort_corrective = 0;
70 
71 static const void *const dmu_recv_tag = "dmu_recv_tag";
72 const char *const recv_clone_name = "%recv";
73 
74 typedef enum {
75 	ORNS_NO,
76 	ORNS_YES,
77 	ORNS_MAYBE
78 } or_need_sync_t;
79 
80 static int receive_read_payload_and_next_header(dmu_recv_cookie_t *ra, int len,
81     void *buf);
82 
83 struct receive_record_arg {
84 	dmu_replay_record_t header;
85 	void *payload; /* Pointer to a buffer containing the payload */
86 	/*
87 	 * If the record is a WRITE or SPILL, pointer to the abd containing the
88 	 * payload.
89 	 */
90 	abd_t *abd;
91 	int payload_size;
92 	uint64_t bytes_read; /* bytes read from stream when record created */
93 	boolean_t eos_marker; /* Marks the end of the stream */
94 	bqueue_node_t node;
95 };
96 
97 /*
98  * A range of dnode slots that must not be touched until the deferred
99  * frees covering it have synced out; see receive_defer_park().
100  */
101 typedef struct receive_defer_range {
102 	avl_node_t rdr_node;
103 	uint64_t rdr_first;	/* first slot in the range */
104 	uint64_t rdr_last;	/* last slot in the range (inclusive) */
105 } receive_defer_range_t;
106 
107 struct receive_writer_arg {
108 	objset_t *os;
109 	boolean_t byteswap;
110 	bqueue_t q;
111 
112 	/*
113 	 * These three members are used to signal to the main thread when
114 	 * we're done.
115 	 */
116 	kmutex_t mutex;
117 	kcondvar_t cv;
118 	boolean_t done;
119 
120 	int err;
121 	const char *tofs;
122 	boolean_t heal;
123 	boolean_t resumable;
124 	boolean_t raw;   /* DMU_BACKUP_FEATURE_RAW set */
125 	boolean_t spill; /* DRR_FLAG_SPILL_BLOCK set */
126 	boolean_t full;  /* this is a full send stream */
127 	uint64_t featureflags; /* from DRR_BEGIN */
128 	uint64_t last_object;
129 	uint64_t last_offset;
130 	uint64_t max_object; /* highest object ID referenced in stream */
131 	uint64_t bytes_read; /* bytes read when current record created */
132 
133 	list_t write_batch;
134 
135 	/* Encryption parameters for the last received DRR_OBJECT_RANGE */
136 	boolean_t or_crypt_params_present;
137 	uint64_t or_firstobj;
138 	uint64_t or_numslots;
139 	uint8_t or_salt[ZIO_DATA_SALT_LEN];
140 	uint8_t or_iv[ZIO_DATA_IV_LEN];
141 	uint8_t or_mac[ZIO_DATA_MAC_LEN];
142 	boolean_t or_byteorder;
143 	zio_t *heal_pio;
144 
145 	/* Keep track of DRR_FREEOBJECTS right after DRR_OBJECT_RANGE */
146 	or_need_sync_t or_need_sync;
147 
148 	/*
149 	 * Records whose application is deferred until the frees they
150 	 * depend on have synced out, the dnode slot ranges they cover,
151 	 * and the resume-state pin for the first deferred record.  See
152 	 * receive_defer_park().
153 	 */
154 	list_t defer_records;
155 	avl_tree_t defer_ranges;
156 	uint64_t defer_bytes;
157 	uint64_t defer_nrecords;
158 	uint64_t defer_first_object;
159 	uint64_t defer_first_bytes_read;
160 	uint64_t defer_max_free_txg;
161 	boolean_t defer_replaying;
162 };
163 
164 static int receive_process_record(struct receive_writer_arg *rwa,
165     struct receive_record_arg *rrd);
166 static int flush_write_batch(struct receive_writer_arg *rwa);
167 
168 typedef struct dmu_recv_begin_arg {
169 	const char *drba_origin;
170 	dmu_recv_cookie_t *drba_cookie;
171 	cred_t *drba_cred;
172 	dsl_crypto_params_t *drba_dcp;
173 } dmu_recv_begin_arg_t;
174 
175 static void
byteswap_record(dmu_replay_record_t * drr)176 byteswap_record(dmu_replay_record_t *drr)
177 {
178 #define	DO64(X) (drr->drr_u.X = BSWAP_64(drr->drr_u.X))
179 #define	DO32(X) (drr->drr_u.X = BSWAP_32(drr->drr_u.X))
180 	drr->drr_type = BSWAP_32(drr->drr_type);
181 	drr->drr_payloadlen = BSWAP_32(drr->drr_payloadlen);
182 
183 	switch (drr->drr_type) {
184 	case DRR_BEGIN:
185 		DO64(drr_begin.drr_magic);
186 		DO64(drr_begin.drr_versioninfo);
187 		DO64(drr_begin.drr_creation_time);
188 		DO32(drr_begin.drr_type);
189 		DO32(drr_begin.drr_flags);
190 		DO64(drr_begin.drr_toguid);
191 		DO64(drr_begin.drr_fromguid);
192 		break;
193 	case DRR_OBJECT:
194 		DO64(drr_object.drr_object);
195 		DO32(drr_object.drr_type);
196 		DO32(drr_object.drr_bonustype);
197 		DO32(drr_object.drr_blksz);
198 		DO32(drr_object.drr_bonuslen);
199 		DO32(drr_object.drr_raw_bonuslen);
200 		DO64(drr_object.drr_toguid);
201 		DO64(drr_object.drr_maxblkid);
202 		break;
203 	case DRR_FREEOBJECTS:
204 		DO64(drr_freeobjects.drr_firstobj);
205 		DO64(drr_freeobjects.drr_numobjs);
206 		DO64(drr_freeobjects.drr_toguid);
207 		break;
208 	case DRR_WRITE:
209 		DO64(drr_write.drr_object);
210 		DO32(drr_write.drr_type);
211 		DO64(drr_write.drr_offset);
212 		DO64(drr_write.drr_logical_size);
213 		DO64(drr_write.drr_toguid);
214 		ZIO_CHECKSUM_BSWAP(&drr->drr_u.drr_write.drr_key.ddk_cksum);
215 		DO64(drr_write.drr_key.ddk_prop);
216 		DO64(drr_write.drr_compressed_size);
217 		break;
218 	case DRR_WRITE_EMBEDDED:
219 		DO64(drr_write_embedded.drr_object);
220 		DO64(drr_write_embedded.drr_offset);
221 		DO64(drr_write_embedded.drr_length);
222 		DO64(drr_write_embedded.drr_toguid);
223 		DO32(drr_write_embedded.drr_lsize);
224 		DO32(drr_write_embedded.drr_psize);
225 		break;
226 	case DRR_FREE:
227 		DO64(drr_free.drr_object);
228 		DO64(drr_free.drr_offset);
229 		DO64(drr_free.drr_length);
230 		DO64(drr_free.drr_toguid);
231 		break;
232 	case DRR_SPILL:
233 		DO64(drr_spill.drr_object);
234 		DO64(drr_spill.drr_length);
235 		DO64(drr_spill.drr_toguid);
236 		DO64(drr_spill.drr_compressed_size);
237 		DO32(drr_spill.drr_type);
238 		break;
239 	case DRR_OBJECT_RANGE:
240 		DO64(drr_object_range.drr_firstobj);
241 		DO64(drr_object_range.drr_numslots);
242 		DO64(drr_object_range.drr_toguid);
243 		break;
244 	case DRR_REDACT:
245 		DO64(drr_redact.drr_object);
246 		DO64(drr_redact.drr_offset);
247 		DO64(drr_redact.drr_length);
248 		DO64(drr_redact.drr_toguid);
249 		break;
250 	case DRR_END:
251 		DO64(drr_end.drr_toguid);
252 		ZIO_CHECKSUM_BSWAP(&drr->drr_u.drr_end.drr_checksum);
253 		break;
254 	default:
255 		break;
256 	}
257 
258 	if (drr->drr_type != DRR_BEGIN) {
259 		ZIO_CHECKSUM_BSWAP(&drr->drr_u.drr_checksum.drr_checksum);
260 	}
261 
262 #undef DO64
263 #undef DO32
264 }
265 
266 static boolean_t
redact_snaps_contains(uint64_t * snaps,uint64_t num_snaps,uint64_t guid)267 redact_snaps_contains(uint64_t *snaps, uint64_t num_snaps, uint64_t guid)
268 {
269 	for (int i = 0; i < num_snaps; i++) {
270 		if (snaps[i] == guid)
271 			return (B_TRUE);
272 	}
273 	return (B_FALSE);
274 }
275 
276 /*
277  * Check that the new stream we're trying to receive is redacted with respect to
278  * a subset of the snapshots that the origin was redacted with respect to.  For
279  * the reasons behind this, see the man page on redacted zfs sends and receives.
280  */
281 static boolean_t
compatible_redact_snaps(uint64_t * origin_snaps,uint64_t origin_num_snaps,uint64_t * redact_snaps,uint64_t num_redact_snaps)282 compatible_redact_snaps(uint64_t *origin_snaps, uint64_t origin_num_snaps,
283     uint64_t *redact_snaps, uint64_t num_redact_snaps)
284 {
285 	/*
286 	 * Short circuit the comparison; if we are redacted with respect to
287 	 * more snapshots than the origin, we can't be redacted with respect
288 	 * to a subset.
289 	 */
290 	if (num_redact_snaps > origin_num_snaps) {
291 		return (B_FALSE);
292 	}
293 
294 	for (int i = 0; i < num_redact_snaps; i++) {
295 		if (!redact_snaps_contains(origin_snaps, origin_num_snaps,
296 		    redact_snaps[i])) {
297 			return (B_FALSE);
298 		}
299 	}
300 	return (B_TRUE);
301 }
302 
303 static boolean_t
redact_check(dmu_recv_begin_arg_t * drba,dsl_dataset_t * origin)304 redact_check(dmu_recv_begin_arg_t *drba, dsl_dataset_t *origin)
305 {
306 	uint64_t *origin_snaps;
307 	uint64_t origin_num_snaps;
308 	dmu_recv_cookie_t *drc = drba->drba_cookie;
309 	struct drr_begin *drrb = drc->drc_drrb;
310 	int featureflags = DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo);
311 	int err = 0;
312 	boolean_t ret = B_TRUE;
313 	uint64_t *redact_snaps;
314 	uint_t numredactsnaps;
315 
316 	/*
317 	 * If this is a full send stream, we're safe no matter what.
318 	 */
319 	if (drrb->drr_fromguid == 0)
320 		return (ret);
321 
322 	VERIFY(dsl_dataset_get_uint64_array_feature(origin,
323 	    SPA_FEATURE_REDACTED_DATASETS, &origin_num_snaps, &origin_snaps));
324 
325 	if (nvlist_lookup_uint64_array(drc->drc_begin_nvl,
326 	    BEGINNV_REDACT_FROM_SNAPS, &redact_snaps, &numredactsnaps) ==
327 	    0) {
328 		/*
329 		 * If the send stream was sent from the redaction bookmark or
330 		 * the redacted version of the dataset, then we're safe.  Verify
331 		 * that this is from the a compatible redaction bookmark or
332 		 * redacted dataset.
333 		 */
334 		if (!compatible_redact_snaps(origin_snaps, origin_num_snaps,
335 		    redact_snaps, numredactsnaps)) {
336 			err = EINVAL;
337 		}
338 	} else if (featureflags & DMU_BACKUP_FEATURE_REDACTED) {
339 		/*
340 		 * If the stream is redacted, it must be redacted with respect
341 		 * to a subset of what the origin is redacted with respect to.
342 		 * See case number 2 in the zfs man page section on redacted zfs
343 		 * send.
344 		 */
345 		err = nvlist_lookup_uint64_array(drc->drc_begin_nvl,
346 		    BEGINNV_REDACT_SNAPS, &redact_snaps, &numredactsnaps);
347 
348 		if (err != 0 || !compatible_redact_snaps(origin_snaps,
349 		    origin_num_snaps, redact_snaps, numredactsnaps)) {
350 			err = EINVAL;
351 		}
352 	} else if (!redact_snaps_contains(origin_snaps, origin_num_snaps,
353 	    drrb->drr_toguid)) {
354 		/*
355 		 * If the stream isn't redacted but the origin is, this must be
356 		 * one of the snapshots the origin is redacted with respect to.
357 		 * See case number 1 in the zfs man page section on redacted zfs
358 		 * send.
359 		 */
360 		err = EINVAL;
361 	}
362 
363 	if (err != 0)
364 		ret = B_FALSE;
365 	return (ret);
366 }
367 
368 /*
369  * If we previously received a stream with --large-block, we don't support
370  * receiving an incremental on top of it without --large-block.  This avoids
371  * forcing a read-modify-write or trying to re-aggregate a string of WRITE
372  * records.
373  */
374 static int
recv_check_large_blocks(dsl_dataset_t * ds,uint64_t featureflags)375 recv_check_large_blocks(dsl_dataset_t *ds, uint64_t featureflags)
376 {
377 	if (dsl_dataset_feature_is_active(ds, SPA_FEATURE_LARGE_BLOCKS) &&
378 	    !(featureflags & DMU_BACKUP_FEATURE_LARGE_BLOCKS))
379 		return (SET_ERROR(ZFS_ERR_STREAM_LARGE_BLOCK_MISMATCH));
380 	return (0);
381 }
382 
383 static int
recv_begin_check_existing_impl(dmu_recv_begin_arg_t * drba,dsl_dataset_t * ds,uint64_t fromguid,uint64_t featureflags)384 recv_begin_check_existing_impl(dmu_recv_begin_arg_t *drba, dsl_dataset_t *ds,
385     uint64_t fromguid, uint64_t featureflags)
386 {
387 	uint64_t obj;
388 	uint64_t children;
389 	int error;
390 	dsl_dataset_t *snap;
391 	dsl_pool_t *dp = ds->ds_dir->dd_pool;
392 	boolean_t encrypted = ds->ds_dir->dd_crypto_obj != 0;
393 	boolean_t raw = (featureflags & DMU_BACKUP_FEATURE_RAW) != 0;
394 	boolean_t embed = (featureflags & DMU_BACKUP_FEATURE_EMBED_DATA) != 0;
395 
396 	/* Temporary clone name must not exist. */
397 	error = zap_lookup(dp->dp_meta_objset,
398 	    dsl_dir_phys(ds->ds_dir)->dd_child_dir_zapobj, recv_clone_name,
399 	    8, 1, &obj);
400 	if (error != ENOENT)
401 		return (error == 0 ? SET_ERROR(EBUSY) : error);
402 
403 	/* Resume state must not be set. */
404 	if (dsl_dataset_has_resume_receive_state(ds))
405 		return (SET_ERROR(EBUSY));
406 
407 	/* New snapshot name must not exist if we're not healing it. */
408 	error = zap_lookup(dp->dp_meta_objset,
409 	    dsl_dataset_phys(ds)->ds_snapnames_zapobj,
410 	    drba->drba_cookie->drc_tosnap, 8, 1, &obj);
411 	if (drba->drba_cookie->drc_heal) {
412 		if (error != 0)
413 			return (error);
414 	} else if (error != ENOENT) {
415 		return (error == 0 ? SET_ERROR(EEXIST) : error);
416 	}
417 
418 	/* Must not have children if receiving a ZVOL. */
419 	error = zap_count(dp->dp_meta_objset,
420 	    dsl_dir_phys(ds->ds_dir)->dd_child_dir_zapobj, &children);
421 	if (error != 0)
422 		return (error);
423 	if (drba->drba_cookie->drc_drrb->drr_type != DMU_OST_ZFS &&
424 	    children > 0)
425 		return (SET_ERROR(ZFS_ERR_WRONG_PARENT));
426 
427 	/*
428 	 * Check snapshot limit before receiving. We'll recheck again at the
429 	 * end, but might as well abort before receiving if we're already over
430 	 * the limit.
431 	 *
432 	 * Note that we do not check the file system limit with
433 	 * dsl_dir_fscount_check because the temporary %clones don't count
434 	 * against that limit.
435 	 */
436 	error = dsl_fs_ss_limit_check(ds->ds_dir, 1, ZFS_PROP_SNAPSHOT_LIMIT,
437 	    NULL, drba->drba_cred);
438 	if (error != 0)
439 		return (error);
440 
441 	if (drba->drba_cookie->drc_heal) {
442 		/* Encryption is incompatible with embedded data. */
443 		if (encrypted && embed)
444 			return (SET_ERROR(EINVAL));
445 
446 		/* Healing is not supported when in 'force' mode. */
447 		if (drba->drba_cookie->drc_force)
448 			return (SET_ERROR(EINVAL));
449 
450 		/* Must have keys loaded if doing encrypted non-raw recv. */
451 		if (encrypted && !raw) {
452 			if (spa_keystore_lookup_key(dp->dp_spa, ds->ds_object,
453 			    NULL, NULL) != 0)
454 				return (SET_ERROR(EACCES));
455 		}
456 
457 		error = dsl_dataset_hold_obj(dp, obj, FTAG, &snap);
458 		if (error != 0)
459 			return (error);
460 
461 		/*
462 		 * When not doing best effort corrective recv healing can only
463 		 * be done if the send stream is for the same snapshot as the
464 		 * one we are trying to heal.
465 		 */
466 		if (zfs_recv_best_effort_corrective == 0 &&
467 		    drba->drba_cookie->drc_drrb->drr_toguid !=
468 		    dsl_dataset_phys(snap)->ds_guid) {
469 			dsl_dataset_rele(snap, FTAG);
470 			return (SET_ERROR(ENOTSUP));
471 		}
472 		dsl_dataset_rele(snap, FTAG);
473 	} else if (fromguid != 0) {
474 		/* Sanity check the incremental recv */
475 		uint64_t obj = dsl_dataset_phys(ds)->ds_prev_snap_obj;
476 
477 		/* Can't perform a raw receive on top of a non-raw receive */
478 		if (!encrypted && raw)
479 			return (SET_ERROR(EINVAL));
480 
481 		/* Encryption is incompatible with embedded data */
482 		if (encrypted && embed)
483 			return (SET_ERROR(EINVAL));
484 
485 		/* Find snapshot in this dir that matches fromguid. */
486 		while (obj != 0) {
487 			error = dsl_dataset_hold_obj(dp, obj, FTAG,
488 			    &snap);
489 			if (error != 0)
490 				return (SET_ERROR(ENODEV));
491 			if (snap->ds_dir != ds->ds_dir) {
492 				dsl_dataset_rele(snap, FTAG);
493 				return (SET_ERROR(ENODEV));
494 			}
495 			if (dsl_dataset_phys(snap)->ds_guid == fromguid)
496 				break;
497 			obj = dsl_dataset_phys(snap)->ds_prev_snap_obj;
498 			dsl_dataset_rele(snap, FTAG);
499 		}
500 		if (obj == 0)
501 			return (SET_ERROR(ENODEV));
502 
503 		/*
504 		 * A non-raw incremental onto a snapshot that was itself
505 		 * received raw re-stamps the new snapshot's ivset guid, so it
506 		 * no longer matches the sending lineage and a later raw
507 		 * incremental would be rejected (#8758). Note it here so the
508 		 * receive can warn about it as it happens.
509 		 */
510 		if (encrypted && !raw) {
511 			uint64_t rawrecv = 0;
512 			(void) zap_lookup(dp->dp_meta_objset, snap->ds_object,
513 			    DS_FIELD_RAW_RECEIVED, sizeof (uint64_t), 1,
514 			    &rawrecv);
515 			if (rawrecv != 0)
516 				drba->drba_cookie->drc_ivset_diverged = B_TRUE;
517 		}
518 
519 		if (drba->drba_cookie->drc_force) {
520 			drba->drba_cookie->drc_fromsnapobj = obj;
521 		} else {
522 			/*
523 			 * If we are not forcing, there must be no
524 			 * changes since fromsnap. Raw sends have an
525 			 * additional constraint that requires that
526 			 * no "noop" snapshots exist between fromsnap
527 			 * and tosnap for the IVset checking code to
528 			 * work properly.
529 			 */
530 			if (dsl_dataset_modified_since_snap(ds, snap) ||
531 			    (raw &&
532 			    dsl_dataset_phys(ds)->ds_prev_snap_obj !=
533 			    snap->ds_object)) {
534 				dsl_dataset_rele(snap, FTAG);
535 				return (SET_ERROR(ETXTBSY));
536 			}
537 			drba->drba_cookie->drc_fromsnapobj =
538 			    ds->ds_prev->ds_object;
539 		}
540 
541 		if (dsl_dataset_feature_is_active(snap,
542 		    SPA_FEATURE_REDACTED_DATASETS) && !redact_check(drba,
543 		    snap)) {
544 			dsl_dataset_rele(snap, FTAG);
545 			return (SET_ERROR(EINVAL));
546 		}
547 
548 		error = recv_check_large_blocks(snap, featureflags);
549 		if (error != 0) {
550 			dsl_dataset_rele(snap, FTAG);
551 			return (error);
552 		}
553 
554 		dsl_dataset_rele(snap, FTAG);
555 	} else {
556 		/* If full and not healing then must be forced. */
557 		if (!drba->drba_cookie->drc_force)
558 			return (SET_ERROR(EEXIST));
559 
560 		/*
561 		 * We don't support using zfs recv -F to blow away
562 		 * encrypted filesystems. This would require the
563 		 * dsl dir to point to the old encryption key and
564 		 * the new one at the same time during the receive.
565 		 */
566 		if ((!encrypted && raw) || encrypted)
567 			return (SET_ERROR(EINVAL));
568 
569 		/*
570 		 * Perform the same encryption checks we would if
571 		 * we were creating a new dataset from scratch.
572 		 */
573 		if (!raw) {
574 			boolean_t will_encrypt;
575 
576 			error = dmu_objset_create_crypt_check(
577 			    ds->ds_dir->dd_parent, drba->drba_dcp,
578 			    &will_encrypt);
579 			if (error != 0)
580 				return (error);
581 
582 			if (will_encrypt && embed)
583 				return (SET_ERROR(EINVAL));
584 		}
585 	}
586 
587 	return (0);
588 }
589 
590 /*
591  * Check that any feature flags used in the data stream we're receiving are
592  * supported by the pool we are receiving into.
593  *
594  * Note that some of the features we explicitly check here have additional
595  * (implicit) features they depend on, but those dependencies are enforced
596  * through the zfeature_register() calls declaring the features that we
597  * explicitly check.
598  */
599 static int
recv_begin_check_feature_flags_impl(uint64_t featureflags,spa_t * spa)600 recv_begin_check_feature_flags_impl(uint64_t featureflags, spa_t *spa)
601 {
602 	/*
603 	 * Check if there are any unsupported feature flags.
604 	 */
605 	if (!DMU_STREAM_SUPPORTED(featureflags)) {
606 		return (SET_ERROR(ZFS_ERR_UNKNOWN_SEND_STREAM_FEATURE));
607 	}
608 
609 	/* Verify pool version supports SA if SA_SPILL feature set */
610 	if ((featureflags & DMU_BACKUP_FEATURE_SA_SPILL) &&
611 	    spa_version(spa) < SPA_VERSION_SA)
612 		return (SET_ERROR(ENOTSUP));
613 
614 	/*
615 	 * LZ4 compressed, ZSTD compressed, embedded, mooched, large blocks,
616 	 * and large_dnodes in the stream can only be used if those pool
617 	 * features are enabled because we don't attempt to decompress /
618 	 * un-embed / un-mooch / split up the blocks / dnodes during the
619 	 * receive process.
620 	 */
621 	if ((featureflags & DMU_BACKUP_FEATURE_LZ4) &&
622 	    !spa_feature_is_enabled(spa, SPA_FEATURE_LZ4_COMPRESS))
623 		return (SET_ERROR(ENOTSUP));
624 	if ((featureflags & DMU_BACKUP_FEATURE_ZSTD) &&
625 	    !spa_feature_is_enabled(spa, SPA_FEATURE_ZSTD_COMPRESS))
626 		return (SET_ERROR(ENOTSUP));
627 	if ((featureflags & DMU_BACKUP_FEATURE_EMBED_DATA) &&
628 	    !spa_feature_is_enabled(spa, SPA_FEATURE_EMBEDDED_DATA))
629 		return (SET_ERROR(ENOTSUP));
630 	if ((featureflags & DMU_BACKUP_FEATURE_LARGE_BLOCKS) &&
631 	    !spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_BLOCKS))
632 		return (SET_ERROR(ENOTSUP));
633 	if ((featureflags & DMU_BACKUP_FEATURE_LARGE_DNODE) &&
634 	    !spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_DNODE))
635 		return (SET_ERROR(ENOTSUP));
636 	if ((featureflags & DMU_BACKUP_FEATURE_LARGE_MICROZAP) &&
637 	    !spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_MICROZAP))
638 		return (SET_ERROR(ENOTSUP));
639 
640 	/*
641 	 * Receiving redacted streams requires that redacted datasets are
642 	 * enabled.
643 	 */
644 	if ((featureflags & DMU_BACKUP_FEATURE_REDACTED) &&
645 	    !spa_feature_is_enabled(spa, SPA_FEATURE_REDACTED_DATASETS))
646 		return (SET_ERROR(ENOTSUP));
647 
648 	/*
649 	 * If the LONGNAME is not enabled on the target, fail that request.
650 	 */
651 	if ((featureflags & DMU_BACKUP_FEATURE_LONGNAME) &&
652 	    !spa_feature_is_enabled(spa, SPA_FEATURE_LONGNAME))
653 		return (SET_ERROR(ENOTSUP));
654 
655 	return (0);
656 }
657 
658 static int
dmu_recv_begin_check(void * arg,dmu_tx_t * tx)659 dmu_recv_begin_check(void *arg, dmu_tx_t *tx)
660 {
661 	dmu_recv_begin_arg_t *drba = arg;
662 	dsl_pool_t *dp = dmu_tx_pool(tx);
663 	struct drr_begin *drrb = drba->drba_cookie->drc_drrb;
664 	uint64_t fromguid = drrb->drr_fromguid;
665 	int flags = drrb->drr_flags;
666 	ds_hold_flags_t dsflags = DS_HOLD_FLAG_NONE;
667 	int error;
668 	uint64_t featureflags = drba->drba_cookie->drc_featureflags;
669 	dsl_dataset_t *ds;
670 	const char *tofs = drba->drba_cookie->drc_tofs;
671 
672 	/* already checked */
673 	ASSERT3U(drrb->drr_magic, ==, DMU_BACKUP_MAGIC);
674 	ASSERT(!(featureflags & DMU_BACKUP_FEATURE_RESUMING));
675 
676 	if (DMU_GET_STREAM_HDRTYPE(drrb->drr_versioninfo) ==
677 	    DMU_COMPOUNDSTREAM ||
678 	    drrb->drr_type >= DMU_OST_NUMTYPES ||
679 	    ((flags & DRR_FLAG_CLONE) && drba->drba_origin == NULL))
680 		return (SET_ERROR(EINVAL));
681 
682 	error = recv_begin_check_feature_flags_impl(featureflags, dp->dp_spa);
683 	if (error != 0)
684 		return (error);
685 
686 	/* Resumable receives require extensible datasets */
687 	if (drba->drba_cookie->drc_resumable &&
688 	    !spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_EXTENSIBLE_DATASET))
689 		return (SET_ERROR(ENOTSUP));
690 
691 	if (featureflags & DMU_BACKUP_FEATURE_RAW) {
692 		/* raw receives require the encryption feature */
693 		if (!spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_ENCRYPTION))
694 			return (SET_ERROR(ENOTSUP));
695 
696 		/* embedded data is incompatible with encryption and raw recv */
697 		if (featureflags & DMU_BACKUP_FEATURE_EMBED_DATA)
698 			return (SET_ERROR(EINVAL));
699 
700 		/* raw receives require spill block allocation flag */
701 		if (!(flags & DRR_FLAG_SPILL_BLOCK))
702 			return (SET_ERROR(ZFS_ERR_SPILL_BLOCK_FLAG_MISSING));
703 	} else {
704 		/*
705 		 * We support unencrypted datasets below encrypted ones now,
706 		 * so add the DS_HOLD_FLAG_DECRYPT flag only if we are dealing
707 		 * with a dataset we may encrypt.
708 		 */
709 		if (drba->drba_dcp == NULL ||
710 		    drba->drba_dcp->cp_crypt != ZIO_CRYPT_OFF) {
711 			dsflags |= DS_HOLD_FLAG_DECRYPT;
712 		}
713 	}
714 
715 	error = dsl_dataset_hold_flags(dp, tofs, dsflags, FTAG, &ds);
716 	if (error == 0) {
717 		/* target fs already exists; recv into temp clone */
718 
719 		/* Can't recv a clone into an existing fs */
720 		if (flags & DRR_FLAG_CLONE || drba->drba_origin) {
721 			dsl_dataset_rele_flags(ds, dsflags, FTAG);
722 			return (SET_ERROR(EINVAL));
723 		}
724 
725 		error = recv_begin_check_existing_impl(drba, ds, fromguid,
726 		    featureflags);
727 		dsl_dataset_rele_flags(ds, dsflags, FTAG);
728 	} else if (error == ENOENT) {
729 		/* target fs does not exist; must be a full backup or clone */
730 		char buf[ZFS_MAX_DATASET_NAME_LEN];
731 		objset_t *os;
732 
733 		/* healing recv must be done "into" an existing snapshot */
734 		if (drba->drba_cookie->drc_heal == B_TRUE)
735 			return (SET_ERROR(ENOTSUP));
736 
737 		/*
738 		 * If it's a non-clone incremental, we are missing the
739 		 * target fs, so fail the recv.
740 		 */
741 		if (fromguid != 0 && !((flags & DRR_FLAG_CLONE) ||
742 		    drba->drba_origin))
743 			return (SET_ERROR(ENOENT));
744 
745 		/*
746 		 * If we're receiving a full send as a clone, and it doesn't
747 		 * contain all the necessary free records and freeobject
748 		 * records, reject it.
749 		 */
750 		if (fromguid == 0 && drba->drba_origin != NULL &&
751 		    !(flags & DRR_FLAG_FREERECORDS))
752 			return (SET_ERROR(EINVAL));
753 
754 		/* Open the parent of tofs */
755 		ASSERT3U(strlen(tofs), <, sizeof (buf));
756 		(void) strlcpy(buf, tofs, strrchr(tofs, '/') - tofs + 1);
757 		error = dsl_dataset_hold(dp, buf, FTAG, &ds);
758 		if (error != 0)
759 			return (error);
760 
761 		if ((featureflags & DMU_BACKUP_FEATURE_RAW) == 0 &&
762 		    drba->drba_origin == NULL) {
763 			boolean_t will_encrypt;
764 
765 			/*
766 			 * Check that we aren't breaking any encryption rules
767 			 * and that we have all the parameters we need to
768 			 * create an encrypted dataset if necessary. If we are
769 			 * making an encrypted dataset the stream can't have
770 			 * embedded data.
771 			 */
772 			error = dmu_objset_create_crypt_check(ds->ds_dir,
773 			    drba->drba_dcp, &will_encrypt);
774 			if (error != 0) {
775 				dsl_dataset_rele(ds, FTAG);
776 				return (error);
777 			}
778 
779 			if (will_encrypt &&
780 			    (featureflags & DMU_BACKUP_FEATURE_EMBED_DATA)) {
781 				dsl_dataset_rele(ds, FTAG);
782 				return (SET_ERROR(EINVAL));
783 			}
784 		}
785 
786 		/*
787 		 * Check filesystem and snapshot limits before receiving. We'll
788 		 * recheck snapshot limits again at the end (we create the
789 		 * filesystems and increment those counts during begin_sync).
790 		 */
791 		error = dsl_fs_ss_limit_check(ds->ds_dir, 1,
792 		    ZFS_PROP_FILESYSTEM_LIMIT, NULL, drba->drba_cred);
793 		if (error != 0) {
794 			dsl_dataset_rele(ds, FTAG);
795 			return (error);
796 		}
797 
798 		error = dsl_fs_ss_limit_check(ds->ds_dir, 1,
799 		    ZFS_PROP_SNAPSHOT_LIMIT, NULL, drba->drba_cred);
800 		if (error != 0) {
801 			dsl_dataset_rele(ds, FTAG);
802 			return (error);
803 		}
804 
805 		/* can't recv below anything but filesystems (eg. no ZVOLs) */
806 		error = dmu_objset_from_ds(ds, &os);
807 		if (error != 0) {
808 			dsl_dataset_rele(ds, FTAG);
809 			return (error);
810 		}
811 		if (dmu_objset_type(os) != DMU_OST_ZFS) {
812 			dsl_dataset_rele(ds, FTAG);
813 			return (SET_ERROR(ZFS_ERR_WRONG_PARENT));
814 		}
815 
816 		if (drba->drba_origin != NULL) {
817 			dsl_dataset_t *origin;
818 			error = dsl_dataset_hold_flags(dp, drba->drba_origin,
819 			    dsflags, FTAG, &origin);
820 			if (error != 0) {
821 				dsl_dataset_rele(ds, FTAG);
822 				return (error);
823 			}
824 			if (!origin->ds_is_snapshot) {
825 				dsl_dataset_rele_flags(origin, dsflags, FTAG);
826 				dsl_dataset_rele(ds, FTAG);
827 				return (SET_ERROR(EINVAL));
828 			}
829 			if (dsl_dataset_phys(origin)->ds_guid != fromguid &&
830 			    fromguid != 0) {
831 				dsl_dataset_rele_flags(origin, dsflags, FTAG);
832 				dsl_dataset_rele(ds, FTAG);
833 				return (SET_ERROR(ENODEV));
834 			}
835 
836 			if (origin->ds_dir->dd_crypto_obj != 0 &&
837 			    (featureflags & DMU_BACKUP_FEATURE_EMBED_DATA)) {
838 				dsl_dataset_rele_flags(origin, dsflags, FTAG);
839 				dsl_dataset_rele(ds, FTAG);
840 				return (SET_ERROR(EINVAL));
841 			}
842 
843 			/*
844 			 * If the origin is redacted we need to verify that this
845 			 * send stream can safely be received on top of the
846 			 * origin.
847 			 */
848 			if (dsl_dataset_feature_is_active(origin,
849 			    SPA_FEATURE_REDACTED_DATASETS)) {
850 				if (!redact_check(drba, origin)) {
851 					dsl_dataset_rele_flags(origin, dsflags,
852 					    FTAG);
853 					dsl_dataset_rele(ds, FTAG);
854 					return (SET_ERROR(EINVAL));
855 				}
856 			}
857 
858 			error = recv_check_large_blocks(ds, featureflags);
859 			if (error != 0) {
860 				dsl_dataset_rele_flags(origin, dsflags, FTAG);
861 				dsl_dataset_rele(ds, FTAG);
862 				return (error);
863 			}
864 
865 			dsl_dataset_rele_flags(origin, dsflags, FTAG);
866 		}
867 
868 		dsl_dataset_rele(ds, FTAG);
869 		error = 0;
870 	}
871 	return (error);
872 }
873 
874 static void
dmu_recv_begin_sync(void * arg,dmu_tx_t * tx)875 dmu_recv_begin_sync(void *arg, dmu_tx_t *tx)
876 {
877 	dmu_recv_begin_arg_t *drba = arg;
878 	dsl_pool_t *dp = dmu_tx_pool(tx);
879 	objset_t *mos = dp->dp_meta_objset;
880 	dmu_recv_cookie_t *drc = drba->drba_cookie;
881 	struct drr_begin *drrb = drc->drc_drrb;
882 	const char *tofs = drc->drc_tofs;
883 	uint64_t featureflags = drc->drc_featureflags;
884 	dsl_dataset_t *ds, *newds;
885 	objset_t *os;
886 	uint64_t dsobj;
887 	ds_hold_flags_t dsflags = DS_HOLD_FLAG_NONE;
888 	int error;
889 	uint64_t crflags = 0;
890 	dsl_crypto_params_t dummy_dcp = { 0 };
891 	dsl_crypto_params_t *dcp = drba->drba_dcp;
892 
893 	if (drrb->drr_flags & DRR_FLAG_CI_DATA)
894 		crflags |= DS_FLAG_CI_DATASET;
895 
896 	if ((featureflags & DMU_BACKUP_FEATURE_RAW) == 0)
897 		dsflags |= DS_HOLD_FLAG_DECRYPT;
898 
899 	/*
900 	 * Raw, non-incremental recvs always use a dummy dcp with
901 	 * the raw cmd set. Raw incremental recvs do not use a dcp
902 	 * since the encryption parameters are already set in stone.
903 	 */
904 	if (dcp == NULL && drrb->drr_fromguid == 0 &&
905 	    drba->drba_origin == NULL) {
906 		ASSERT0P(dcp);
907 		dcp = &dummy_dcp;
908 
909 		if (featureflags & DMU_BACKUP_FEATURE_RAW)
910 			dcp->cp_cmd = DCP_CMD_RAW_RECV;
911 	}
912 
913 	error = dsl_dataset_hold_flags(dp, tofs, dsflags, FTAG, &ds);
914 	if (error == 0) {
915 		/* Create temporary clone unless we're doing corrective recv */
916 		dsl_dataset_t *snap = NULL;
917 
918 		if (drba->drba_cookie->drc_fromsnapobj != 0) {
919 			VERIFY0(dsl_dataset_hold_obj(dp,
920 			    drba->drba_cookie->drc_fromsnapobj, FTAG, &snap));
921 			ASSERT0P(dcp);
922 		}
923 		if (drc->drc_heal) {
924 			/* When healing we want to use the provided snapshot */
925 			VERIFY0(dsl_dataset_snap_lookup(ds, drc->drc_tosnap,
926 			    &dsobj));
927 		} else {
928 			dsobj = dsl_dataset_create_sync(ds->ds_dir,
929 			    recv_clone_name, snap, crflags, drba->drba_cred,
930 			    dcp, tx);
931 		}
932 		if (drba->drba_cookie->drc_fromsnapobj != 0)
933 			dsl_dataset_rele(snap, FTAG);
934 		dsl_dataset_rele_flags(ds, dsflags, FTAG);
935 	} else {
936 		dsl_dir_t *dd;
937 		const char *tail;
938 		dsl_dataset_t *origin = NULL;
939 
940 		VERIFY0(dsl_dir_hold(dp, tofs, FTAG, &dd, &tail));
941 
942 		if (drba->drba_origin != NULL) {
943 			VERIFY0(dsl_dataset_hold(dp, drba->drba_origin,
944 			    FTAG, &origin));
945 			ASSERT0P(dcp);
946 		}
947 
948 		/* Create new dataset. */
949 		dsobj = dsl_dataset_create_sync(dd, strrchr(tofs, '/') + 1,
950 		    origin, crflags, drba->drba_cred, dcp, tx);
951 		if (origin != NULL)
952 			dsl_dataset_rele(origin, FTAG);
953 		dsl_dir_rele(dd, FTAG);
954 		drc->drc_newfs = B_TRUE;
955 	}
956 	VERIFY0(dsl_dataset_own_obj_force(dp, dsobj, dsflags, dmu_recv_tag,
957 	    &newds));
958 	if (dsl_dataset_feature_is_active(newds,
959 	    SPA_FEATURE_REDACTED_DATASETS)) {
960 		/*
961 		 * If the origin dataset is redacted, the child will be redacted
962 		 * when we create it.  We clear the new dataset's
963 		 * redaction info; if it should be redacted, we'll fill
964 		 * in its information later.
965 		 */
966 		dsl_dataset_deactivate_feature(newds,
967 		    SPA_FEATURE_REDACTED_DATASETS, tx);
968 	}
969 	VERIFY0(dmu_objset_from_ds(newds, &os));
970 
971 	if (drc->drc_resumable) {
972 		dsl_dataset_zapify(newds, tx);
973 		if (drrb->drr_fromguid != 0) {
974 			VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_FROMGUID,
975 			    8, 1, &drrb->drr_fromguid, tx));
976 		}
977 		VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_TOGUID,
978 		    8, 1, &drrb->drr_toguid, tx));
979 		VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_TONAME,
980 		    1, strlen(drrb->drr_toname) + 1, drrb->drr_toname, tx));
981 		uint64_t one = 1;
982 		uint64_t zero = 0;
983 		VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_OBJECT,
984 		    8, 1, &one, tx));
985 		VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_OFFSET,
986 		    8, 1, &zero, tx));
987 		VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_BYTES,
988 		    8, 1, &zero, tx));
989 		if (featureflags & DMU_BACKUP_FEATURE_LARGE_BLOCKS) {
990 			VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_LARGEBLOCK,
991 			    8, 1, &one, tx));
992 		}
993 		if (featureflags & DMU_BACKUP_FEATURE_EMBED_DATA) {
994 			VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_EMBEDOK,
995 			    8, 1, &one, tx));
996 		}
997 		if (featureflags & DMU_BACKUP_FEATURE_COMPRESSED) {
998 			VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_COMPRESSOK,
999 			    8, 1, &one, tx));
1000 		}
1001 		if (featureflags & DMU_BACKUP_FEATURE_RAW) {
1002 			VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_RAWOK,
1003 			    8, 1, &one, tx));
1004 		}
1005 
1006 		uint64_t *redact_snaps;
1007 		uint_t numredactsnaps;
1008 		if (nvlist_lookup_uint64_array(drc->drc_begin_nvl,
1009 		    BEGINNV_REDACT_FROM_SNAPS, &redact_snaps,
1010 		    &numredactsnaps) == 0) {
1011 			VERIFY0(zap_add(mos, dsobj,
1012 			    DS_FIELD_RESUME_REDACT_BOOKMARK_SNAPS,
1013 			    sizeof (*redact_snaps), numredactsnaps,
1014 			    redact_snaps, tx));
1015 		}
1016 	}
1017 
1018 	/*
1019 	 * Usually the os->os_encrypted value is tied to the presence of a
1020 	 * DSL Crypto Key object in the dd. However, that will not be received
1021 	 * until dmu_recv_stream(), so we set the value manually for now.
1022 	 */
1023 	if (featureflags & DMU_BACKUP_FEATURE_RAW) {
1024 		os->os_encrypted = B_TRUE;
1025 		drba->drba_cookie->drc_raw = B_TRUE;
1026 	}
1027 
1028 	if (featureflags & DMU_BACKUP_FEATURE_REDACTED) {
1029 		uint64_t *redact_snaps;
1030 		uint_t numredactsnaps;
1031 		VERIFY0(nvlist_lookup_uint64_array(drc->drc_begin_nvl,
1032 		    BEGINNV_REDACT_SNAPS, &redact_snaps, &numredactsnaps));
1033 		dsl_dataset_activate_redaction(newds, redact_snaps,
1034 		    numredactsnaps, tx);
1035 	}
1036 
1037 	dmu_buf_will_dirty(newds->ds_dbuf, tx);
1038 	dsl_dataset_phys(newds)->ds_flags |= DS_FLAG_INCONSISTENT;
1039 
1040 	/*
1041 	 * When receiving, we refuse to accept streams that are missing the
1042 	 * large block feature flag if the large block is already active
1043 	 * (see ZFS_ERR_STREAM_LARGE_BLOCK_MISMATCH). To prevent this
1044 	 * check from being spuriously triggered, we always activate
1045 	 * the large block feature if the feature flag is present in the
1046 	 * stream.  This covers the case where the sending side has the feature
1047 	 * active, but has since deleted the file containing large blocks.
1048 	 */
1049 	if (featureflags & DMU_BACKUP_FEATURE_LARGE_BLOCKS &&
1050 	    !dsl_dataset_feature_is_active(newds, SPA_FEATURE_LARGE_BLOCKS)) {
1051 		dsl_dataset_activate_feature(newds->ds_object,
1052 		    SPA_FEATURE_LARGE_BLOCKS, (void *)B_TRUE, tx);
1053 		newds->ds_feature[SPA_FEATURE_LARGE_BLOCKS] = (void *)B_TRUE;
1054 	}
1055 
1056 	/*
1057 	 * Activate longname feature if received
1058 	 */
1059 	if (featureflags & DMU_BACKUP_FEATURE_LONGNAME &&
1060 	    !dsl_dataset_feature_is_active(newds, SPA_FEATURE_LONGNAME)) {
1061 		dsl_dataset_activate_feature(newds->ds_object,
1062 		    SPA_FEATURE_LONGNAME, (void *)B_TRUE, tx);
1063 		newds->ds_feature[SPA_FEATURE_LONGNAME] = (void *)B_TRUE;
1064 	}
1065 
1066 	if (featureflags & DMU_BACKUP_FEATURE_LARGE_MICROZAP &&
1067 	    !dsl_dataset_feature_is_active(newds, SPA_FEATURE_LARGE_MICROZAP)) {
1068 		/*
1069 		 * The source has seen a large microzap at least once in its
1070 		 * life, so we activate the feature here to match. It's not
1071 		 * strictly necessary since a large microzap is usable without
1072 		 * the feature active, but if that object is sent on from here,
1073 		 * we need this info to know to add the stream feature.
1074 		 *
1075 		 * There may be no large microzap in the incoming stream, or
1076 		 * ever again, but this is a very niche feature and its very
1077 		 * difficult to spot a large microzap in the stream, so its
1078 		 * not worth the effort of trying harder to activate the
1079 		 * feature at first use.
1080 		 */
1081 		dsl_dataset_activate_feature(dsobj, SPA_FEATURE_LARGE_MICROZAP,
1082 		    (void *)B_TRUE, tx);
1083 		newds->ds_feature[SPA_FEATURE_LARGE_MICROZAP] = (void *)B_TRUE;
1084 	}
1085 
1086 	/*
1087 	 * If we actually created a non-clone, we need to create the objset
1088 	 * in our new dataset. If this is a raw send we postpone this until
1089 	 * dmu_recv_stream() so that we can allocate the metadnode with the
1090 	 * properties from the DRR_BEGIN payload.
1091 	 */
1092 	rrw_enter(&newds->ds_bp_rwlock, RW_READER, FTAG);
1093 	if (BP_IS_HOLE(dsl_dataset_get_blkptr(newds)) &&
1094 	    (featureflags & DMU_BACKUP_FEATURE_RAW) == 0 &&
1095 	    !drc->drc_heal) {
1096 		(void) dmu_objset_create_impl(dp->dp_spa,
1097 		    newds, dsl_dataset_get_blkptr(newds), drrb->drr_type, tx);
1098 	}
1099 	rrw_exit(&newds->ds_bp_rwlock, FTAG);
1100 
1101 	drba->drba_cookie->drc_ds = newds;
1102 	drba->drba_cookie->drc_os = os;
1103 
1104 	spa_history_log_internal_ds(newds, "receive", tx, " ");
1105 }
1106 
1107 static int
dmu_recv_resume_begin_check(void * arg,dmu_tx_t * tx)1108 dmu_recv_resume_begin_check(void *arg, dmu_tx_t *tx)
1109 {
1110 	dmu_recv_begin_arg_t *drba = arg;
1111 	dmu_recv_cookie_t *drc = drba->drba_cookie;
1112 	dsl_pool_t *dp = dmu_tx_pool(tx);
1113 	struct drr_begin *drrb = drc->drc_drrb;
1114 	int error;
1115 	ds_hold_flags_t dsflags = DS_HOLD_FLAG_NONE;
1116 	dsl_dataset_t *ds;
1117 	const char *tofs = drc->drc_tofs;
1118 
1119 	/* already checked */
1120 	ASSERT3U(drrb->drr_magic, ==, DMU_BACKUP_MAGIC);
1121 	ASSERT(drc->drc_featureflags & DMU_BACKUP_FEATURE_RESUMING);
1122 
1123 	if (DMU_GET_STREAM_HDRTYPE(drrb->drr_versioninfo) ==
1124 	    DMU_COMPOUNDSTREAM ||
1125 	    drrb->drr_type >= DMU_OST_NUMTYPES)
1126 		return (SET_ERROR(EINVAL));
1127 
1128 	/*
1129 	 * This is mostly a sanity check since we should have already done these
1130 	 * checks during a previous attempt to receive the data.
1131 	 */
1132 	error = recv_begin_check_feature_flags_impl(drc->drc_featureflags,
1133 	    dp->dp_spa);
1134 	if (error != 0)
1135 		return (error);
1136 
1137 	/* 6 extra bytes for /%recv */
1138 	char recvname[ZFS_MAX_DATASET_NAME_LEN + 6];
1139 
1140 	(void) snprintf(recvname, sizeof (recvname), "%s/%s",
1141 	    tofs, recv_clone_name);
1142 
1143 	if (drc->drc_featureflags & DMU_BACKUP_FEATURE_RAW) {
1144 		/* raw receives require spill block allocation flag */
1145 		if (!(drrb->drr_flags & DRR_FLAG_SPILL_BLOCK))
1146 			return (SET_ERROR(ZFS_ERR_SPILL_BLOCK_FLAG_MISSING));
1147 	} else {
1148 		dsflags |= DS_HOLD_FLAG_DECRYPT;
1149 	}
1150 
1151 	boolean_t recvexist = B_TRUE;
1152 	if (dsl_dataset_hold_flags(dp, recvname, dsflags, FTAG, &ds) != 0) {
1153 		/* %recv does not exist; continue in tofs */
1154 		recvexist = B_FALSE;
1155 		error = dsl_dataset_hold_flags(dp, tofs, dsflags, FTAG, &ds);
1156 		if (error != 0)
1157 			return (error);
1158 	}
1159 
1160 	/*
1161 	 * Resume of full/newfs recv on existing dataset should be done with
1162 	 * force flag
1163 	 */
1164 	if (recvexist && drrb->drr_fromguid == 0 && !drc->drc_force) {
1165 		dsl_dataset_rele_flags(ds, dsflags, FTAG);
1166 		return (SET_ERROR(ZFS_ERR_RESUME_EXISTS));
1167 	}
1168 
1169 	/* check that ds is marked inconsistent */
1170 	if (!DS_IS_INCONSISTENT(ds)) {
1171 		dsl_dataset_rele_flags(ds, dsflags, FTAG);
1172 		return (SET_ERROR(EINVAL));
1173 	}
1174 
1175 	/* check that there is resuming data, and that the toguid matches */
1176 	if (!dsl_dataset_is_zapified(ds)) {
1177 		dsl_dataset_rele_flags(ds, dsflags, FTAG);
1178 		return (SET_ERROR(EINVAL));
1179 	}
1180 	uint64_t val;
1181 	error = zap_lookup(dp->dp_meta_objset, ds->ds_object,
1182 	    DS_FIELD_RESUME_TOGUID, sizeof (val), 1, &val);
1183 	if (error != 0 || drrb->drr_toguid != val) {
1184 		dsl_dataset_rele_flags(ds, dsflags, FTAG);
1185 		return (SET_ERROR(EINVAL));
1186 	}
1187 
1188 	/*
1189 	 * Check if the receive is still running.  If so, it will be owned.
1190 	 * Note that nothing else can own the dataset (e.g. after the receive
1191 	 * fails) because it will be marked inconsistent.
1192 	 */
1193 	if (dsl_dataset_has_owner(ds)) {
1194 		dsl_dataset_rele_flags(ds, dsflags, FTAG);
1195 		return (SET_ERROR(EBUSY));
1196 	}
1197 
1198 	/* There should not be any snapshots of this fs yet. */
1199 	if (ds->ds_prev != NULL && ds->ds_prev->ds_dir == ds->ds_dir) {
1200 		dsl_dataset_rele_flags(ds, dsflags, FTAG);
1201 		return (SET_ERROR(EINVAL));
1202 	}
1203 
1204 	/*
1205 	 * Note: resume point will be checked when we process the first WRITE
1206 	 * record.
1207 	 */
1208 
1209 	/* check that the origin matches */
1210 	val = 0;
1211 	(void) zap_lookup(dp->dp_meta_objset, ds->ds_object,
1212 	    DS_FIELD_RESUME_FROMGUID, sizeof (val), 1, &val);
1213 	if (drrb->drr_fromguid != val) {
1214 		dsl_dataset_rele_flags(ds, dsflags, FTAG);
1215 		return (SET_ERROR(EINVAL));
1216 	}
1217 
1218 	if (ds->ds_prev != NULL && drrb->drr_fromguid != 0) {
1219 		drc->drc_fromsnapobj = ds->ds_prev->ds_object;
1220 
1221 		/*
1222 		 * As in recv_begin_check_existing_impl(): if this non-raw
1223 		 * incremental resumes onto a raw-received snapshot, note that
1224 		 * it is diverging the IV set so the receive can warn (#8758).
1225 		 */
1226 		if (ds->ds_dir->dd_crypto_obj != 0 &&
1227 		    !(drc->drc_featureflags & DMU_BACKUP_FEATURE_RAW)) {
1228 			uint64_t rawrecv = 0;
1229 			(void) zap_lookup(dp->dp_meta_objset,
1230 			    drc->drc_fromsnapobj, DS_FIELD_RAW_RECEIVED,
1231 			    sizeof (uint64_t), 1, &rawrecv);
1232 			if (rawrecv != 0)
1233 				drc->drc_ivset_diverged = B_TRUE;
1234 		}
1235 	}
1236 
1237 	/*
1238 	 * If we're resuming, and the send is redacted, then the original send
1239 	 * must have been redacted, and must have been redacted with respect to
1240 	 * the same snapshots.
1241 	 */
1242 	if (drc->drc_featureflags & DMU_BACKUP_FEATURE_REDACTED) {
1243 		uint64_t num_ds_redact_snaps;
1244 		uint64_t *ds_redact_snaps;
1245 
1246 		uint_t num_stream_redact_snaps;
1247 		uint64_t *stream_redact_snaps;
1248 
1249 		if (nvlist_lookup_uint64_array(drc->drc_begin_nvl,
1250 		    BEGINNV_REDACT_SNAPS, &stream_redact_snaps,
1251 		    &num_stream_redact_snaps) != 0) {
1252 			dsl_dataset_rele_flags(ds, dsflags, FTAG);
1253 			return (SET_ERROR(EINVAL));
1254 		}
1255 
1256 		if (!dsl_dataset_get_uint64_array_feature(ds,
1257 		    SPA_FEATURE_REDACTED_DATASETS, &num_ds_redact_snaps,
1258 		    &ds_redact_snaps)) {
1259 			dsl_dataset_rele_flags(ds, dsflags, FTAG);
1260 			return (SET_ERROR(EINVAL));
1261 		}
1262 
1263 		for (int i = 0; i < num_ds_redact_snaps; i++) {
1264 			if (!redact_snaps_contains(ds_redact_snaps,
1265 			    num_ds_redact_snaps, stream_redact_snaps[i])) {
1266 				dsl_dataset_rele_flags(ds, dsflags, FTAG);
1267 				return (SET_ERROR(EINVAL));
1268 			}
1269 		}
1270 	}
1271 
1272 	error = recv_check_large_blocks(ds, drc->drc_featureflags);
1273 	if (error != 0) {
1274 		dsl_dataset_rele_flags(ds, dsflags, FTAG);
1275 		return (error);
1276 	}
1277 
1278 	dsl_dataset_rele_flags(ds, dsflags, FTAG);
1279 	return (0);
1280 }
1281 
1282 static void
dmu_recv_resume_begin_sync(void * arg,dmu_tx_t * tx)1283 dmu_recv_resume_begin_sync(void *arg, dmu_tx_t *tx)
1284 {
1285 	dmu_recv_begin_arg_t *drba = arg;
1286 	dsl_pool_t *dp = dmu_tx_pool(tx);
1287 	const char *tofs = drba->drba_cookie->drc_tofs;
1288 	uint64_t featureflags = drba->drba_cookie->drc_featureflags;
1289 	dsl_dataset_t *ds;
1290 	ds_hold_flags_t dsflags = DS_HOLD_FLAG_NONE;
1291 	/* 6 extra bytes for /%recv */
1292 	char recvname[ZFS_MAX_DATASET_NAME_LEN + 6];
1293 
1294 	(void) snprintf(recvname, sizeof (recvname), "%s/%s", tofs,
1295 	    recv_clone_name);
1296 
1297 	if (featureflags & DMU_BACKUP_FEATURE_RAW) {
1298 		drba->drba_cookie->drc_raw = B_TRUE;
1299 	} else {
1300 		dsflags |= DS_HOLD_FLAG_DECRYPT;
1301 	}
1302 
1303 	if (dsl_dataset_own_force(dp, recvname, dsflags, dmu_recv_tag, &ds)
1304 	    != 0) {
1305 		/* %recv does not exist; continue in tofs */
1306 		VERIFY0(dsl_dataset_own_force(dp, tofs, dsflags, dmu_recv_tag,
1307 		    &ds));
1308 		drba->drba_cookie->drc_newfs = B_TRUE;
1309 	}
1310 
1311 	ASSERT(DS_IS_INCONSISTENT(ds));
1312 	rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);
1313 	ASSERT(!BP_IS_HOLE(dsl_dataset_get_blkptr(ds)) ||
1314 	    drba->drba_cookie->drc_raw);
1315 	rrw_exit(&ds->ds_bp_rwlock, FTAG);
1316 
1317 	drba->drba_cookie->drc_ds = ds;
1318 	VERIFY0(dmu_objset_from_ds(ds, &drba->drba_cookie->drc_os));
1319 	drba->drba_cookie->drc_should_save = B_TRUE;
1320 
1321 	spa_history_log_internal_ds(ds, "resume receive", tx, " ");
1322 }
1323 
1324 /*
1325  * NB: callers *MUST* call dmu_recv_stream() if dmu_recv_begin()
1326  * succeeds; otherwise we will leak the holds on the datasets.
1327  */
1328 int
dmu_recv_begin(const char * tofs,const char * tosnap,dmu_replay_record_t * drr_begin,boolean_t force,boolean_t heal,boolean_t resumable,nvlist_t * localprops,nvlist_t * hidden_args,const char * origin,dmu_recv_cookie_t * drc,zfs_file_t * fp,offset_t * voffp)1329 dmu_recv_begin(const char *tofs, const char *tosnap,
1330     dmu_replay_record_t *drr_begin, boolean_t force, boolean_t heal,
1331     boolean_t resumable, nvlist_t *localprops, nvlist_t *hidden_args,
1332     const char *origin, dmu_recv_cookie_t *drc, zfs_file_t *fp,
1333     offset_t *voffp)
1334 {
1335 	dmu_recv_begin_arg_t drba = { 0 };
1336 	int err = 0;
1337 
1338 	cred_t *cr = CRED();
1339 	crhold(cr);
1340 
1341 	memset(drc, 0, sizeof (dmu_recv_cookie_t));
1342 	drc->drc_drr_begin = drr_begin;
1343 	drc->drc_drrb = &drr_begin->drr_u.drr_begin;
1344 	drc->drc_tosnap = tosnap;
1345 	drc->drc_tofs = tofs;
1346 	drc->drc_force = force;
1347 	drc->drc_heal = heal;
1348 	drc->drc_resumable = resumable;
1349 	drc->drc_cred = cr;
1350 	drc->drc_clone = (origin != NULL);
1351 
1352 	if (drc->drc_drrb->drr_magic == BSWAP_64(DMU_BACKUP_MAGIC)) {
1353 		drc->drc_byteswap = B_TRUE;
1354 		(void) fletcher_4_incremental_byteswap(drr_begin,
1355 		    sizeof (dmu_replay_record_t), &drc->drc_cksum);
1356 		byteswap_record(drr_begin);
1357 	} else if (drc->drc_drrb->drr_magic == DMU_BACKUP_MAGIC) {
1358 		(void) fletcher_4_incremental_native(drr_begin,
1359 		    sizeof (dmu_replay_record_t), &drc->drc_cksum);
1360 	} else {
1361 		crfree(cr);
1362 		drc->drc_cred = NULL;
1363 		return (SET_ERROR(EINVAL));
1364 	}
1365 
1366 	drc->drc_fp = fp;
1367 	drc->drc_voff = *voffp;
1368 	drc->drc_featureflags =
1369 	    DMU_GET_FEATUREFLAGS(drc->drc_drrb->drr_versioninfo);
1370 
1371 	uint32_t payloadlen = drc->drc_drr_begin->drr_payloadlen;
1372 
1373 	/*
1374 	 * Since OpenZFS 2.0.0, we have enforced a 64MB limit in userspace
1375 	 * configurable via ZFS_SENDRECV_MAX_NVLIST. We enforce 256MB as a hard
1376 	 * upper limit. Systems with less than 1GB of RAM will see a lower
1377 	 * limit from `arc_all_memory() / 4`.
1378 	 */
1379 	if (payloadlen > (MIN((1U << 28), arc_all_memory() / 4))) {
1380 		crfree(cr);
1381 		drc->drc_cred = NULL;
1382 		return (SET_ERROR(E2BIG));
1383 	}
1384 
1385 	if (payloadlen != 0) {
1386 		void *payload = vmem_alloc(payloadlen, KM_SLEEP);
1387 		/*
1388 		 * For compatibility with recursive send streams, we don't do
1389 		 * this here if the stream could be part of a package. Instead,
1390 		 * we'll do it in dmu_recv_stream. If we pull the next header
1391 		 * too early, and it's the END record, we break the `recv_skip`
1392 		 * logic.
1393 		 */
1394 
1395 		err = receive_read_payload_and_next_header(drc, payloadlen,
1396 		    payload);
1397 		if (err != 0) {
1398 			vmem_free(payload, payloadlen);
1399 			crfree(cr);
1400 			drc->drc_cred = NULL;
1401 			return (err);
1402 		}
1403 		err = nvlist_unpack(payload, payloadlen, &drc->drc_begin_nvl,
1404 		    KM_SLEEP);
1405 		vmem_free(payload, payloadlen);
1406 		if (err != 0) {
1407 			kmem_free(drc->drc_next_rrd,
1408 			    sizeof (*drc->drc_next_rrd));
1409 			crfree(cr);
1410 			drc->drc_cred = NULL;
1411 			return (err);
1412 		}
1413 	}
1414 
1415 	if (drc->drc_drrb->drr_flags & DRR_FLAG_SPILL_BLOCK)
1416 		drc->drc_spill = B_TRUE;
1417 
1418 	drba.drba_origin = origin;
1419 	drba.drba_cookie = drc;
1420 	drba.drba_cred = drc->drc_cred;
1421 
1422 	if (drc->drc_featureflags & DMU_BACKUP_FEATURE_RESUMING) {
1423 		err = dsl_sync_task(tofs,
1424 		    dmu_recv_resume_begin_check, dmu_recv_resume_begin_sync,
1425 		    &drba, 5, ZFS_SPACE_CHECK_NORMAL);
1426 	} else {
1427 		/*
1428 		 * For non-raw, non-incremental, non-resuming receives the
1429 		 * user can specify encryption parameters on the command line
1430 		 * with "zfs recv -o". For these receives we create a dcp and
1431 		 * pass it to the sync task. Creating the dcp will implicitly
1432 		 * remove the encryption params from the localprops nvlist,
1433 		 * which avoids errors when trying to set these normally
1434 		 * read-only properties. Any other kind of receive that
1435 		 * attempts to set these properties will fail as a result.
1436 		 */
1437 		if ((DMU_GET_FEATUREFLAGS(drc->drc_drrb->drr_versioninfo) &
1438 		    DMU_BACKUP_FEATURE_RAW) == 0 &&
1439 		    origin == NULL && drc->drc_drrb->drr_fromguid == 0) {
1440 			err = dsl_crypto_params_create_nvlist(DCP_CMD_NONE,
1441 			    localprops, hidden_args, &drba.drba_dcp);
1442 		}
1443 
1444 		if (err == 0) {
1445 			err = dsl_sync_task(tofs,
1446 			    dmu_recv_begin_check, dmu_recv_begin_sync,
1447 			    &drba, 5, ZFS_SPACE_CHECK_NORMAL);
1448 			dsl_crypto_params_free(drba.drba_dcp, !!err);
1449 		}
1450 	}
1451 
1452 	if (err != 0) {
1453 		kmem_free(drc->drc_next_rrd, sizeof (*drc->drc_next_rrd));
1454 		nvlist_free(drc->drc_begin_nvl);
1455 		crfree(cr);
1456 		drc->drc_cred = NULL;
1457 	}
1458 	return (err);
1459 }
1460 
1461 /*
1462  * Holds data need for corrective recv callback
1463  */
1464 typedef struct cr_cb_data {
1465 	uint64_t size;
1466 	zbookmark_phys_t zb;
1467 	spa_t *spa;
1468 } cr_cb_data_t;
1469 
1470 static void
corrective_read_done(zio_t * zio)1471 corrective_read_done(zio_t *zio)
1472 {
1473 	cr_cb_data_t *data = zio->io_private;
1474 	/* Corruption corrected; update error log if needed */
1475 	if (zio->io_error == 0) {
1476 		spa_remove_error(data->spa, &data->zb,
1477 		    BP_GET_PHYSICAL_BIRTH(zio->io_bp));
1478 	}
1479 	kmem_free(data, sizeof (cr_cb_data_t));
1480 	abd_free(zio->io_abd);
1481 }
1482 
1483 /*
1484  * zio_rewrite the data pointed to by bp with the data from the rrd's abd.
1485  */
1486 static int
do_corrective_recv(struct receive_writer_arg * rwa,struct drr_write * drrw,struct receive_record_arg * rrd,blkptr_t * bp)1487 do_corrective_recv(struct receive_writer_arg *rwa, struct drr_write *drrw,
1488     struct receive_record_arg *rrd, blkptr_t *bp)
1489 {
1490 	int err;
1491 	zio_t *io;
1492 	zbookmark_phys_t zb;
1493 	dnode_t *dn;
1494 	abd_t *abd = rrd->abd;
1495 	zio_cksum_t bp_cksum = bp->blk_cksum;
1496 	zio_flag_t flags = ZIO_FLAG_SPECULATIVE | ZIO_FLAG_DONT_RETRY |
1497 	    ZIO_FLAG_CANFAIL;
1498 
1499 	if (rwa->raw)
1500 		flags |= ZIO_FLAG_RAW;
1501 
1502 	err = dnode_hold(rwa->os, drrw->drr_object, FTAG, &dn);
1503 	if (err != 0)
1504 		return (err);
1505 	SET_BOOKMARK(&zb, dmu_objset_id(rwa->os), drrw->drr_object, 0,
1506 	    dbuf_whichblock(dn, 0, drrw->drr_offset));
1507 	dnode_rele(dn, FTAG);
1508 
1509 	if (!rwa->raw && DRR_WRITE_COMPRESSED(drrw)) {
1510 		/* Decompress the stream data */
1511 		abd_t *dabd = abd_alloc_linear(
1512 		    drrw->drr_logical_size, B_FALSE);
1513 		err = zio_decompress_data(drrw->drr_compressiontype,
1514 		    abd, dabd, abd_get_size(abd),
1515 		    abd_get_size(dabd), NULL);
1516 
1517 		if (err != 0) {
1518 			abd_free(dabd);
1519 			return (err);
1520 		}
1521 		/* Swap in the newly decompressed data into the abd */
1522 		abd_free(abd);
1523 		abd = dabd;
1524 	}
1525 
1526 	if (!rwa->raw && BP_GET_COMPRESS(bp) != ZIO_COMPRESS_OFF) {
1527 		/* Recompress the data */
1528 		abd_t *cabd = abd_alloc_linear(BP_GET_PSIZE(bp),
1529 		    B_FALSE);
1530 		uint64_t csize = zio_compress_data(BP_GET_COMPRESS(bp),
1531 		    abd, &cabd, abd_get_size(abd), BP_GET_PSIZE(bp),
1532 		    rwa->os->os_complevel);
1533 		abd_zero_off(cabd, csize, BP_GET_PSIZE(bp) - csize);
1534 		/* Swap in newly compressed data into the abd */
1535 		abd_free(abd);
1536 		abd = cabd;
1537 		flags |= ZIO_FLAG_RAW_COMPRESS;
1538 	}
1539 
1540 	/*
1541 	 * The stream is not encrypted but the data on-disk is.
1542 	 * We need to re-encrypt the buf using the same
1543 	 * encryption type, salt, iv, and mac that was used to encrypt
1544 	 * the block previosly.
1545 	 */
1546 	if (!rwa->raw && BP_USES_CRYPT(bp)) {
1547 		dsl_dataset_t *ds;
1548 		dsl_crypto_key_t *dck = NULL;
1549 		uint8_t salt[ZIO_DATA_SALT_LEN];
1550 		uint8_t iv[ZIO_DATA_IV_LEN];
1551 		uint8_t mac[ZIO_DATA_MAC_LEN];
1552 		boolean_t no_crypt = B_FALSE;
1553 		dsl_pool_t *dp = dmu_objset_pool(rwa->os);
1554 		abd_t *eabd = abd_alloc_linear(BP_GET_PSIZE(bp), B_FALSE);
1555 
1556 		zio_crypt_decode_params_bp(bp, salt, iv);
1557 		zio_crypt_decode_mac_bp(bp, mac);
1558 
1559 		dsl_pool_config_enter(dp, FTAG);
1560 		err = dsl_dataset_hold_flags(dp, rwa->tofs,
1561 		    DS_HOLD_FLAG_DECRYPT, FTAG, &ds);
1562 		if (err != 0) {
1563 			dsl_pool_config_exit(dp, FTAG);
1564 			abd_free(eabd);
1565 			return (SET_ERROR(EACCES));
1566 		}
1567 
1568 		/* Look up the key from the spa's keystore */
1569 		err = spa_keystore_lookup_key(rwa->os->os_spa,
1570 		    zb.zb_objset, FTAG, &dck);
1571 		if (err != 0) {
1572 			dsl_dataset_rele_flags(ds, DS_HOLD_FLAG_DECRYPT,
1573 			    FTAG);
1574 			dsl_pool_config_exit(dp, FTAG);
1575 			abd_free(eabd);
1576 			return (SET_ERROR(EACCES));
1577 		}
1578 
1579 		err = zio_do_crypt_abd(B_TRUE, &dck->dck_key,
1580 		    BP_GET_TYPE(bp), BP_SHOULD_BYTESWAP(bp), salt, iv,
1581 		    mac, abd_get_size(abd), abd, eabd, &no_crypt);
1582 
1583 		spa_keystore_dsl_key_rele(rwa->os->os_spa, dck, FTAG);
1584 		dsl_dataset_rele_flags(ds, DS_HOLD_FLAG_DECRYPT, FTAG);
1585 		dsl_pool_config_exit(dp, FTAG);
1586 
1587 		ASSERT0(no_crypt);
1588 		if (err != 0) {
1589 			abd_free(eabd);
1590 			return (err);
1591 		}
1592 		/* Swap in the newly encrypted data into the abd */
1593 		abd_free(abd);
1594 		abd = eabd;
1595 
1596 		/*
1597 		 * We want to prevent zio_rewrite() from trying to
1598 		 * encrypt the data again
1599 		 */
1600 		flags |= ZIO_FLAG_RAW_ENCRYPT;
1601 	}
1602 	rrd->abd = abd;
1603 
1604 	io = zio_rewrite(NULL, rwa->os->os_spa, BP_GET_BIRTH(bp), bp,
1605 	    abd, BP_GET_PSIZE(bp), NULL, NULL, ZIO_PRIORITY_SYNC_WRITE, flags,
1606 	    &zb);
1607 
1608 	ASSERT(abd_get_size(abd) == BP_GET_LSIZE(bp) ||
1609 	    abd_get_size(abd) == BP_GET_PSIZE(bp));
1610 
1611 	/* compute new bp checksum value and make sure it matches the old one */
1612 	zio_checksum_compute(io, BP_GET_CHECKSUM(bp), abd, abd_get_size(abd));
1613 	if (!ZIO_CHECKSUM_EQUAL(bp_cksum, io->io_bp->blk_cksum)) {
1614 		zio_destroy(io);
1615 		if (zfs_recv_best_effort_corrective != 0)
1616 			return (0);
1617 		return (SET_ERROR(ECKSUM));
1618 	}
1619 
1620 	/* Correct the corruption in place */
1621 	err = zio_wait(io);
1622 	if (err == 0) {
1623 		cr_cb_data_t *cb_data =
1624 		    kmem_alloc(sizeof (cr_cb_data_t), KM_SLEEP);
1625 		cb_data->spa = rwa->os->os_spa;
1626 		cb_data->size = drrw->drr_logical_size;
1627 		cb_data->zb = zb;
1628 		/* Test if healing worked by re-reading the bp */
1629 		err = zio_wait(zio_read(rwa->heal_pio, rwa->os->os_spa, bp,
1630 		    abd_alloc_for_io(drrw->drr_logical_size, B_FALSE),
1631 		    drrw->drr_logical_size, corrective_read_done,
1632 		    cb_data, ZIO_PRIORITY_ASYNC_READ, flags, NULL));
1633 	}
1634 	if (err != 0 && zfs_recv_best_effort_corrective != 0)
1635 		err = 0;
1636 
1637 	return (err);
1638 }
1639 
1640 static int
receive_read(dmu_recv_cookie_t * drc,int len,void * buf)1641 receive_read(dmu_recv_cookie_t *drc, int len, void *buf)
1642 {
1643 	int done = 0;
1644 
1645 	/*
1646 	 * The code doesn't rely on this (lengths being multiples of 8).  See
1647 	 * comment in dump_bytes.
1648 	 */
1649 	ASSERT(len % 8 == 0 ||
1650 	    (drc->drc_featureflags & DMU_BACKUP_FEATURE_RAW) != 0);
1651 
1652 	while (done < len) {
1653 		ssize_t resid = len - done;
1654 		zfs_file_t *fp = drc->drc_fp;
1655 		int err = zfs_file_read(fp, (char *)buf + done,
1656 		    len - done, &resid);
1657 		if (err == 0 && resid == len - done) {
1658 			/*
1659 			 * Note: ECKSUM or ZFS_ERR_STREAM_TRUNCATED indicates
1660 			 * that the receive was interrupted and can
1661 			 * potentially be resumed.
1662 			 */
1663 			err = SET_ERROR(ZFS_ERR_STREAM_TRUNCATED);
1664 		}
1665 		drc->drc_voff += len - done - resid;
1666 		done = len - resid;
1667 		if (err != 0)
1668 			return (err);
1669 	}
1670 
1671 	drc->drc_bytes_read += len;
1672 
1673 	ASSERT3U(done, ==, len);
1674 	return (0);
1675 }
1676 
1677 static inline uint8_t
deduce_nblkptr(dmu_object_type_t bonus_type,uint64_t bonus_size,uint8_t dn_slots)1678 deduce_nblkptr(dmu_object_type_t bonus_type, uint64_t bonus_size,
1679     uint8_t dn_slots)
1680 {
1681 	if (bonus_type == DMU_OT_SA) {
1682 		return (1);
1683 	} else {
1684 		/*
1685 		 * Match dnode_allocate() / dnode_reallocate(): nblkptr is
1686 		 * derived from the dnode's bonus capacity for dn_slots.
1687 		 */
1688 		return (MIN(DN_MAX_NBLKPTR,
1689 		    1 + ((DN_SLOTS_TO_BONUSLEN(dn_slots) -
1690 		    MIN(DN_SLOTS_TO_BONUSLEN(dn_slots), bonus_size)) >>
1691 		    SPA_BLKPTRSHIFT)));
1692 	}
1693 }
1694 
1695 static void
save_resume_state(struct receive_writer_arg * rwa,uint64_t object,uint64_t offset,dmu_tx_t * tx)1696 save_resume_state(struct receive_writer_arg *rwa,
1697     uint64_t object, uint64_t offset, dmu_tx_t *tx)
1698 {
1699 	int txgoff = dmu_tx_get_txg(tx) & TXG_MASK;
1700 	uint64_t bytes = rwa->bytes_read;
1701 
1702 	if (!rwa->resumable)
1703 		return;
1704 
1705 	/*
1706 	 * While records are parked on the defer list (including while
1707 	 * they are being replayed), the resume point must not advance
1708 	 * past the first unapplied record.  Everything parked is at or
1709 	 * after that stream position, and re-receiving records that were
1710 	 * already applied is supported (see receive_object()), so pin
1711 	 * the saved state there until the defer list drains.
1712 	 *
1713 	 * A sender emits objects in ascending order, so the pin can only
1714 	 * sit at or above anything saved before it.  A malformed stream
1715 	 * that reorders objects could place it lower; keep the already
1716 	 * saved state in that case instead of moving resume backwards
1717 	 * past records this receive never parked.
1718 	 */
1719 	if (rwa->defer_replaying || !list_is_empty(&rwa->defer_records)) {
1720 		if (rwa->defer_first_object <
1721 		    rwa->os->os_dsl_dataset->ds_resume_object[txgoff])
1722 			return;
1723 		object = rwa->defer_first_object;
1724 		offset = 0;
1725 		bytes = rwa->defer_first_bytes_read;
1726 	}
1727 
1728 	/*
1729 	 * We use ds_resume_bytes[] != 0 to indicate that we need to
1730 	 * update this on disk, so it must not be 0.
1731 	 */
1732 	ASSERT(bytes != 0);
1733 
1734 	/*
1735 	 * We only resume from write records, which have a valid
1736 	 * (non-meta-dnode) object number.
1737 	 */
1738 	ASSERT(object != 0);
1739 
1740 	/*
1741 	 * For resuming to work correctly, we must receive records in order,
1742 	 * sorted by object,offset.  This is checked by the callers, but
1743 	 * assert it here for good measure.
1744 	 */
1745 	ASSERT3U(object, >=, rwa->os->os_dsl_dataset->ds_resume_object[txgoff]);
1746 	ASSERT(object != rwa->os->os_dsl_dataset->ds_resume_object[txgoff] ||
1747 	    offset >= rwa->os->os_dsl_dataset->ds_resume_offset[txgoff]);
1748 	ASSERT3U(rwa->bytes_read, >=,
1749 	    rwa->os->os_dsl_dataset->ds_resume_bytes[txgoff]);
1750 
1751 	rwa->os->os_dsl_dataset->ds_resume_object[txgoff] = object;
1752 	rwa->os->os_dsl_dataset->ds_resume_offset[txgoff] = offset;
1753 	rwa->os->os_dsl_dataset->ds_resume_bytes[txgoff] = bytes;
1754 }
1755 
1756 static int
receive_object_is_same_generation(objset_t * os,uint64_t object,dmu_object_type_t old_bonus_type,dmu_object_type_t new_bonus_type,const void * new_bonus,boolean_t * samegenp)1757 receive_object_is_same_generation(objset_t *os, uint64_t object,
1758     dmu_object_type_t old_bonus_type, dmu_object_type_t new_bonus_type,
1759     const void *new_bonus, boolean_t *samegenp)
1760 {
1761 	zfs_file_info_t zoi;
1762 	int err;
1763 
1764 	dmu_buf_t *old_bonus_dbuf;
1765 	err = dmu_bonus_hold(os, object, FTAG, &old_bonus_dbuf);
1766 	if (err != 0)
1767 		return (err);
1768 	err = dmu_get_file_info(os, old_bonus_type, old_bonus_dbuf->db_data,
1769 	    &zoi);
1770 	dmu_buf_rele(old_bonus_dbuf, FTAG);
1771 	if (err != 0)
1772 		return (err);
1773 	uint64_t old_gen = zoi.zfi_generation;
1774 
1775 	err = dmu_get_file_info(os, new_bonus_type, new_bonus, &zoi);
1776 	if (err != 0)
1777 		return (err);
1778 	uint64_t new_gen = zoi.zfi_generation;
1779 
1780 	*samegenp = (old_gen == new_gen);
1781 	return (0);
1782 }
1783 
1784 /*
1785  * Return true if a + b would overflow uint64_t.
1786  */
1787 static boolean_t
recv_u64_add_overflow(uint64_t a,uint64_t b)1788 recv_u64_add_overflow(uint64_t a, uint64_t b)
1789 {
1790 	return (a + b < a);
1791 }
1792 
1793 typedef struct recv_check_limits {
1794 	uint64_t rcl_maxblocksize;
1795 	uint64_t rcl_maxdnodesize;
1796 } recv_check_limits_t;
1797 
1798 static void
recv_check_resolve_limits(spa_t * spa,recv_check_limits_t * limits)1799 recv_check_resolve_limits(spa_t *spa, recv_check_limits_t *limits)
1800 {
1801 	if (spa != NULL) {
1802 		limits->rcl_maxblocksize = spa_maxblocksize(spa);
1803 		limits->rcl_maxdnodesize = spa_maxdnodesize(spa);
1804 	} else {
1805 		limits->rcl_maxblocksize = SPA_MAXBLOCKSIZE;
1806 		limits->rcl_maxdnodesize = DNODE_MAX_SIZE;
1807 	}
1808 }
1809 
1810 static int
recv_check_fail(int error,char * errbuf,size_t errbuflen,const char * fmt,...)1811 recv_check_fail(int error, char *errbuf, size_t errbuflen, const char *fmt, ...)
1812 {
1813 	if (errbuf != NULL && errbuflen > 0 && fmt != NULL) {
1814 		va_list ap;
1815 
1816 		va_start(ap, fmt);
1817 		(void) vsnprintf(errbuf, errbuflen, fmt, ap);
1818 		va_end(ap);
1819 	}
1820 	return (SET_ERROR(error));
1821 }
1822 
1823 /*
1824  * Reject compression algorithms that require a feature flag the BEGIN
1825  * record did not advertise.  Legacy algorithms (below LZ4) need no flag.
1826  */
1827 static int
recv_check_compress_feature(uint8_t compress,uint64_t featureflags,char * errbuf,size_t errbuflen,const char * what)1828 recv_check_compress_feature(uint8_t compress, uint64_t featureflags,
1829     char *errbuf, size_t errbuflen, const char *what)
1830 {
1831 	if (compress == ZIO_COMPRESS_ZSTD &&
1832 	    !(featureflags & DMU_BACKUP_FEATURE_ZSTD)) {
1833 		return (recv_check_fail(EINVAL, errbuf, errbuflen,
1834 		    "%s compression type ZSTD requires "
1835 		    "DMU_BACKUP_FEATURE_ZSTD", what));
1836 	}
1837 	if (compress >= ZIO_COMPRESS_LEGACY_FUNCTIONS &&
1838 	    compress != ZIO_COMPRESS_ZSTD &&
1839 	    !(featureflags & DMU_BACKUP_FEATURE_LZ4)) {
1840 		return (recv_check_fail(EINVAL, errbuf, errbuflen,
1841 		    "%s compression type %u requires DMU_BACKUP_FEATURE_LZ4",
1842 		    what, compress));
1843 	}
1844 	return (0);
1845 }
1846 
1847 /*
1848  * Publish a stream rejection reason on the receive errors nvlist.
1849  * Called only from the reader thread (receive_read_record): the writer
1850  * thread shares no lock with the reader, so it must not mutate this nvlist.
1851  */
1852 static void
recv_report_stream_error(nvlist_t * errors,const char * msg)1853 recv_report_stream_error(nvlist_t *errors, const char *msg)
1854 {
1855 	if (errors != NULL && msg != NULL && msg[0] != '\0' &&
1856 	    !nvlist_exists(errors, ZFS_RECV_ERR_STREAM))
1857 		fnvlist_add_string(errors, ZFS_RECV_ERR_STREAM, msg);
1858 }
1859 
1860 /*
1861  * Record validators return ERANGE when a size field exceeds a pool or
1862  * on-wire limit (previously often EINVAL on the apply path, with ERANGE
1863  * only on a few read-path payload checks).  They return EINVAL when a
1864  * field is below a minimum, malformed, or otherwise inconsistent.
1865  * lzc_receive* callers may therefore see ERANGE where older OpenZFS
1866  * modules returned EINVAL for the same oversized record.
1867  */
1868 
1869 /*
1870  * Reject object 0 (meta dnode) and object numbers outside the valid range.
1871  */
1872 static int
recv_check_drr_object_id(uint64_t object,char * errbuf,size_t errbuflen)1873 recv_check_drr_object_id(uint64_t object, char *errbuf, size_t errbuflen)
1874 {
1875 	if (object == 0 || object >= DN_MAX_OBJECT) {
1876 		return (recv_check_fail(EINVAL, errbuf, errbuflen,
1877 		    "object number %llu outside valid range 1-%llu",
1878 		    (u_longlong_t)object, (u_longlong_t)(DN_MAX_OBJECT - 1)));
1879 	}
1880 	return (0);
1881 }
1882 
1883 /*
1884  * Reject sizes below a given minimum.
1885  */
1886 static int
recv_check_drr_size_min(uint64_t size,uint64_t minbs,char * errbuf,size_t errbuflen,const char * what)1887 recv_check_drr_size_min(uint64_t size, uint64_t minbs, char *errbuf,
1888     size_t errbuflen, const char *what)
1889 {
1890 	if (size < minbs) {
1891 		return (recv_check_fail(EINVAL, errbuf, errbuflen,
1892 		    "%s %llu below minimum %llu", what, (u_longlong_t)size,
1893 		    (u_longlong_t)minbs));
1894 	}
1895 	return (0);
1896 }
1897 
1898 /*
1899  * Reject sizes above a given maximum.
1900  */
1901 static int
recv_check_drr_size_max(uint64_t size,uint64_t maxbs,char * errbuf,size_t errbuflen,const char * what)1902 recv_check_drr_size_max(uint64_t size, uint64_t maxbs, char *errbuf,
1903     size_t errbuflen, const char *what)
1904 {
1905 	if (size > maxbs) {
1906 		return (recv_check_fail(ERANGE, errbuf, errbuflen,
1907 		    "%s %llu exceeds maximum %llu", what, (u_longlong_t)size,
1908 		    (u_longlong_t)maxbs));
1909 	}
1910 	return (0);
1911 }
1912 
1913 /*
1914  * Validate a DRR_OBJECT record before reading its bonus payload or
1915  * applying it.  Raw object-range membership is validated later in
1916  * receive_object() once the preceding DRR_OBJECT_RANGE state is
1917  * available.
1918  */
1919 int
recv_check_drr_object(const struct drr_object * drro,spa_t * spa,boolean_t raw,boolean_t spill,uint64_t featureflags,char * errbuf,size_t errbuflen)1920 recv_check_drr_object(const struct drr_object *drro, spa_t *spa,
1921     boolean_t raw, boolean_t spill, uint64_t featureflags, char *errbuf,
1922     size_t errbuflen)
1923 {
1924 	uint32_t psize = DRR_OBJECT_PAYLOAD_SIZE(drro);
1925 	recv_check_limits_t limits;
1926 	uint8_t dn_slots = drro->drr_dn_slots != 0 ?
1927 	    drro->drr_dn_slots : DNODE_MIN_SLOTS;
1928 
1929 	recv_check_resolve_limits(spa, &limits);
1930 
1931 	/* object number must be valid */
1932 	int err = recv_check_drr_object_id(drro->drr_object, errbuf, errbuflen);
1933 
1934 	if (err != 0)
1935 		return (err);
1936 
1937 	/* object type must not be DMU_OT_NONE */
1938 	if (drro->drr_type == DMU_OT_NONE) {
1939 		return (recv_check_fail(EINVAL, errbuf, errbuflen,
1940 		    "DRR_OBJECT type is DMU_OT_NONE"));
1941 	}
1942 
1943 	/* object type must be a valid DMU object type */
1944 	if (!DMU_OT_IS_VALID(drro->drr_type)) {
1945 		return (recv_check_fail(EINVAL, errbuf, errbuflen,
1946 		    "DRR_OBJECT has invalid type %u", drro->drr_type));
1947 	}
1948 
1949 	/* bonus type must be a valid DMU object type */
1950 	if (!DMU_OT_IS_VALID(drro->drr_bonustype)) {
1951 		return (recv_check_fail(EINVAL, errbuf, errbuflen,
1952 		    "DRR_OBJECT has invalid bonus type %u",
1953 		    drro->drr_bonustype));
1954 	}
1955 
1956 	/*
1957 	 * Mirror dnode_allocate() bonus invariants so malformed
1958 	 * bonustype/bonuslen pairs are rejected before payload read/apply
1959 	 * instead of hitting ASSERTs in the allocator.
1960 	 */
1961 	if (!((drro->drr_bonustype == DMU_OT_NONE &&
1962 	    drro->drr_bonuslen == 0) ||
1963 	    (drro->drr_bonustype == DMU_OT_SA && drro->drr_bonuslen == 0) ||
1964 	    (drro->drr_bonustype == DMU_OTN_UINT64_METADATA &&
1965 	    drro->drr_bonuslen == 0) ||
1966 	    (drro->drr_bonustype != DMU_OT_NONE &&
1967 	    drro->drr_bonuslen != 0))) {
1968 		return (recv_check_fail(EINVAL, errbuf, errbuflen,
1969 		    "DRR_OBJECT bonus type %u incompatible with bonus "
1970 		    "length %u", drro->drr_bonustype, drro->drr_bonuslen));
1971 	}
1972 
1973 	/* multi-slot dnodes require LARGE_DNODE in BEGIN */
1974 	if (dn_slots > DNODE_MIN_SLOTS &&
1975 	    !(featureflags & DMU_BACKUP_FEATURE_LARGE_DNODE)) {
1976 		return (recv_check_fail(EINVAL, errbuf, errbuflen,
1977 		    "DRR_OBJECT dnode slots %u require "
1978 		    "DMU_BACKUP_FEATURE_LARGE_DNODE", dn_slots));
1979 	}
1980 
1981 	/* blocks larger than SPA_OLD_MAXBLOCKSIZE require LARGE_BLOCKS */
1982 	if (drro->drr_blksz > SPA_OLD_MAXBLOCKSIZE &&
1983 	    !(featureflags & DMU_BACKUP_FEATURE_LARGE_BLOCKS)) {
1984 		return (recv_check_fail(EINVAL, errbuf, errbuflen,
1985 		    "DRR_OBJECT block size %u requires "
1986 		    "DMU_BACKUP_FEATURE_LARGE_BLOCKS", drro->drr_blksz));
1987 	}
1988 
1989 	/* checksum algorithm must be within ZIO_CHECKSUM_FUNCTIONS */
1990 	if (drro->drr_checksumtype >= ZIO_CHECKSUM_FUNCTIONS) {
1991 		return (recv_check_fail(EINVAL, errbuf, errbuflen,
1992 		    "DRR_OBJECT has invalid checksum type %u",
1993 		    drro->drr_checksumtype));
1994 	}
1995 
1996 	/*
1997 	 * drr_compress is from the object, not a stream payload encoding
1998 	 */
1999 	if (drro->drr_compress >= ZIO_COMPRESS_FUNCTIONS) {
2000 		return (recv_check_fail(EINVAL, errbuf, errbuflen,
2001 		    "DRR_OBJECT has invalid compression type %u",
2002 		    drro->drr_compress));
2003 	}
2004 
2005 	/* data block size must be a multiple of SPA_MINBLOCKSIZE */
2006 	if (P2PHASE(drro->drr_blksz, SPA_MINBLOCKSIZE)) {
2007 		return (recv_check_fail(EINVAL, errbuf, errbuflen,
2008 		    "DRR_OBJECT block size %u is not a multiple of %u",
2009 		    drro->drr_blksz, SPA_MINBLOCKSIZE));
2010 	}
2011 
2012 	/* data block size must be at least SPA_MINBLOCKSIZE */
2013 	err = recv_check_drr_size_min(drro->drr_blksz, SPA_MINBLOCKSIZE, errbuf,
2014 	    errbuflen, "DRR_OBJECT block size");
2015 	if (err != 0)
2016 		return (err);
2017 
2018 	/* data block size must not exceed pool maximum */
2019 	err = recv_check_drr_size_max(drro->drr_blksz, limits.rcl_maxblocksize,
2020 	    errbuf, errbuflen, "DRR_OBJECT block size");
2021 	if (err != 0)
2022 		return (err);
2023 
2024 	/* bonus length must fit in the pool's maximum dnode bonus area */
2025 	if (drro->drr_bonuslen > DN_BONUS_SIZE(limits.rcl_maxdnodesize)) {
2026 		return (recv_check_fail(ERANGE, errbuf, errbuflen,
2027 		    "DRR_OBJECT bonus length %u exceeds maximum %u",
2028 		    drro->drr_bonuslen,
2029 		    (uint32_t)DN_BONUS_SIZE(limits.rcl_maxdnodesize)));
2030 	}
2031 
2032 	/* dnode slot count must fit in the pool's maximum dnode size */
2033 	if (dn_slots > (limits.rcl_maxdnodesize >> DNODE_SHIFT)) {
2034 		return (recv_check_fail(ERANGE, errbuf, errbuflen,
2035 		    "DRR_OBJECT dnode slot count %u exceeds maximum %u",
2036 		    dn_slots,
2037 		    (uint8_t)(limits.rcl_maxdnodesize >> DNODE_SHIFT)));
2038 	}
2039 
2040 	/* bonus payload size must not exceed pool maximum block size */
2041 	err = recv_check_drr_size_max(psize, limits.rcl_maxblocksize, errbuf,
2042 	    errbuflen, "DRR_OBJECT bonus payload size");
2043 	if (err != 0)
2044 		return (err);
2045 
2046 	/* object + dn_slots must not overflow uint64_t */
2047 	if (recv_u64_add_overflow(drro->drr_object, dn_slots)) {
2048 		return (recv_check_fail(EINVAL, errbuf, errbuflen,
2049 		    "DRR_OBJECT object %llu + dn_slots %u overflows",
2050 		    (u_longlong_t)drro->drr_object, dn_slots));
2051 	}
2052 
2053 	/* multi-slot dnode must not extend past DN_MAX_OBJECT */
2054 	if (drro->drr_object + dn_slots > DN_MAX_OBJECT) {
2055 		return (recv_check_fail(EINVAL, errbuf, errbuflen,
2056 		    "DRR_OBJECT object range %llu-%llu exceeds DN_MAX_OBJECT",
2057 		    (u_longlong_t)drro->drr_object,
2058 		    (u_longlong_t)(drro->drr_object + dn_slots - 1)));
2059 	}
2060 
2061 	if (raw) {
2062 		uint8_t nblkptr;
2063 		uint32_t max_raw_bonus;
2064 
2065 		/*
2066 		 * Raw OBJECT records may set DRR_OBJECT_SPILL and/or
2067 		 * DRR_RAW_BYTESWAP (see dump_dnode()).
2068 		 */
2069 		if ((drro->drr_flags &
2070 		    ~(DRR_OBJECT_SPILL | DRR_RAW_BYTESWAP)) != 0) {
2071 			return (recv_check_fail(EINVAL, errbuf, errbuflen,
2072 			    "DRR_OBJECT has invalid flags 0x%x",
2073 			    drro->drr_flags));
2074 		}
2075 
2076 		/* spill flag requires DRR_FLAG_SPILL_BLOCK in BEGIN */
2077 		if (!spill && DRR_OBJECT_HAS_SPILL(drro->drr_flags)) {
2078 			return (recv_check_fail(EINVAL, errbuf, errbuflen,
2079 			    "DRR_OBJECT spill flag set but stream BEGIN "
2080 			    "missing DRR_FLAG_SPILL_BLOCK"));
2081 		}
2082 
2083 		/* raw bonus payload must be at least as large as bonuslen */
2084 		if (drro->drr_raw_bonuslen < drro->drr_bonuslen) {
2085 			return (recv_check_fail(EINVAL, errbuf, errbuflen,
2086 			    "DRR_OBJECT raw bonus length %u < bonus length %u",
2087 			    drro->drr_raw_bonuslen, drro->drr_bonuslen));
2088 		}
2089 
2090 		/*
2091 		 * 0 means "leave the post-allocate default"; otherwise the
2092 		 * shift must be a supported indirect block size.  Values
2093 		 * between 1 and DN_MIN_INDBLKSHIFT-1 or above
2094 		 * DN_MAX_INDBLKSHIFT would be stored by dnode_set_blksz()
2095 		 * and break later addressing math.
2096 		 */
2097 		if (drro->drr_indblkshift != 0 &&
2098 		    (drro->drr_indblkshift < DN_MIN_INDBLKSHIFT ||
2099 		    drro->drr_indblkshift > DN_MAX_INDBLKSHIFT)) {
2100 			return (recv_check_fail(EINVAL, errbuf, errbuflen,
2101 			    "DRR_OBJECT indirect block shift %u outside "
2102 			    "valid range %u-%u", drro->drr_indblkshift,
2103 			    DN_MIN_INDBLKSHIFT, DN_MAX_INDBLKSHIFT));
2104 		}
2105 
2106 		/* tree depth must be in [1, DN_MAX_LEVELS] */
2107 		if (drro->drr_nlevels < 1 ||
2108 		    drro->drr_nlevels > DN_MAX_LEVELS) {
2109 			return (recv_check_fail(EINVAL, errbuf, errbuflen,
2110 			    "DRR_OBJECT tree depth %u outside valid range "
2111 			    "1-%u", drro->drr_nlevels, DN_MAX_LEVELS));
2112 		}
2113 
2114 		/* blkptr count must be in [1, DN_MAX_NBLKPTR] */
2115 		if (drro->drr_nblkptr < 1 ||
2116 		    drro->drr_nblkptr > DN_MAX_NBLKPTR) {
2117 			return (recv_check_fail(EINVAL, errbuf, errbuflen,
2118 			    "DRR_OBJECT blkptr count %u outside valid range "
2119 			    "1-%u", drro->drr_nblkptr, DN_MAX_NBLKPTR));
2120 		}
2121 
2122 		/*
2123 		 * nblkptr must match what dnode_allocate() / reclaim derive
2124 		 * from bonustype+bonuslen.  Otherwise the stream's
2125 		 * raw_bonuslen can be sized for a different layout than the
2126 		 * dnode we actually create (bonus dbuf overflow).
2127 		 */
2128 		nblkptr = deduce_nblkptr(drro->drr_bonustype,
2129 		    drro->drr_bonuslen, dn_slots);
2130 		if (drro->drr_nblkptr != nblkptr) {
2131 			return (recv_check_fail(EINVAL, errbuf, errbuflen,
2132 			    "DRR_OBJECT blkptr count %u incompatible with "
2133 			    "bonus type %u length %u (expected %u)",
2134 			    drro->drr_nblkptr, drro->drr_bonustype,
2135 			    drro->drr_bonuslen, nblkptr));
2136 		}
2137 
2138 		/*
2139 		 * Raw bonus payload must fit the in-memory bonus dbuf, which
2140 		 * shrinks as nblkptr grows, and shrinks by one more blkptr_t
2141 		 * when a spill pointer occupies the tail (see
2142 		 * DN_MAX_BONUS_LEN() / dump_dnode()).
2143 		 */
2144 		max_raw_bonus = DN_SLOTS_TO_BONUSLEN(dn_slots) -
2145 		    (nblkptr - 1) * sizeof (blkptr_t);
2146 		if (DRR_OBJECT_HAS_SPILL(drro->drr_flags)) {
2147 			if (max_raw_bonus < sizeof (blkptr_t)) {
2148 				return (recv_check_fail(EINVAL, errbuf,
2149 				    errbuflen,
2150 				    "DRR_OBJECT spill flag incompatible with "
2151 				    "blkptr count %u", nblkptr));
2152 			}
2153 			max_raw_bonus -= sizeof (blkptr_t);
2154 		}
2155 		if (drro->drr_raw_bonuslen > max_raw_bonus) {
2156 			return (recv_check_fail(ERANGE, errbuf, errbuflen,
2157 			    "DRR_OBJECT raw bonus length %u exceeds dnode "
2158 			    "bonus capacity %u", drro->drr_raw_bonuslen,
2159 			    max_raw_bonus));
2160 		}
2161 	} else {
2162 		/* only DRR_OBJECT_SPILL is a permitted non-raw flag bit */
2163 		if ((drro->drr_flags & ~(DRR_OBJECT_SPILL)) != 0) {
2164 			return (recv_check_fail(EINVAL, errbuf, errbuflen,
2165 			    "DRR_OBJECT has invalid flags 0x%x",
2166 			    drro->drr_flags));
2167 		}
2168 
2169 		/* spill flag requires DRR_FLAG_SPILL_BLOCK in BEGIN */
2170 		if (!spill && DRR_OBJECT_HAS_SPILL(drro->drr_flags)) {
2171 			return (recv_check_fail(EINVAL, errbuf, errbuflen,
2172 			    "DRR_OBJECT spill flag set but stream BEGIN "
2173 			    "missing DRR_FLAG_SPILL_BLOCK"));
2174 		}
2175 
2176 		/* raw bonus length must be zero in non-raw streams */
2177 		if (drro->drr_raw_bonuslen != 0) {
2178 			return (recv_check_fail(EINVAL, errbuf, errbuflen,
2179 			    "DRR_OBJECT raw bonus length must be zero in "
2180 			    "non-raw streams"));
2181 		}
2182 
2183 		/* bonus length must fit in the dnode bonus area */
2184 		if (drro->drr_bonuslen > DN_SLOTS_TO_BONUSLEN(dn_slots)) {
2185 			return (recv_check_fail(ERANGE, errbuf, errbuflen,
2186 			    "DRR_OBJECT bonus length %u exceeds dnode bonus "
2187 			    "capacity %u", drro->drr_bonuslen,
2188 			    (uint32_t)DN_SLOTS_TO_BONUSLEN(dn_slots)));
2189 		}
2190 
2191 		/* blkptr count must be zero in non-raw streams */
2192 		if (drro->drr_nblkptr != 0) {
2193 			return (recv_check_fail(EINVAL, errbuf, errbuflen,
2194 			    "DRR_OBJECT blkptr count must be zero in non-raw "
2195 			    "streams"));
2196 		}
2197 
2198 		/* indirect block shift must be zero in non-raw streams */
2199 		if (drro->drr_indblkshift != 0) {
2200 			return (recv_check_fail(EINVAL, errbuf, errbuflen,
2201 			    "DRR_OBJECT indirect block shift must be zero in "
2202 			    "non-raw streams"));
2203 		}
2204 
2205 		/* tree depth must be zero in non-raw streams */
2206 		if (drro->drr_nlevels != 0) {
2207 			return (recv_check_fail(EINVAL, errbuf, errbuflen,
2208 			    "DRR_OBJECT tree depth must be zero in non-raw "
2209 			    "streams"));
2210 		}
2211 	}
2212 
2213 	return (0);
2214 }
2215 
2216 /*
2217  * Validate a DRR_FREE (or DRR_REDACT, which shares the same layout)
2218  * record.  Target object existence is checked later in receive_free().
2219  */
2220 int
recv_check_drr_free(const struct drr_free * drrf,char * errbuf,size_t errbuflen)2221 recv_check_drr_free(const struct drr_free *drrf, char *errbuf, size_t errbuflen)
2222 {
2223 	/* object number must be valid */
2224 	int err = recv_check_drr_object_id(drrf->drr_object, errbuf, errbuflen);
2225 
2226 	if (err != 0)
2227 		return (err);
2228 
2229 	/* offset + length must not overflow uint64_t (length == -1 is EOF) */
2230 	if (drrf->drr_length != -1ULL &&
2231 	    recv_u64_add_overflow(drrf->drr_offset, drrf->drr_length)) {
2232 		return (recv_check_fail(EINVAL, errbuf, errbuflen,
2233 		    "DRR_FREE offset %llu + length %llu overflows",
2234 		    (u_longlong_t)drrf->drr_offset,
2235 		    (u_longlong_t)drrf->drr_length));
2236 	}
2237 
2238 	return (0);
2239 }
2240 
2241 /*
2242  * Validate a DRR_FREEOBJECTS record before processing the object loop.
2243  */
2244 int
recv_check_drr_freeobjects(const struct drr_freeobjects * drrfo,char * errbuf,size_t errbuflen)2245 recv_check_drr_freeobjects(const struct drr_freeobjects *drrfo, char *errbuf,
2246     size_t errbuflen)
2247 {
2248 	/* firstobj + numobjs must not overflow uint64_t */
2249 	if (recv_u64_add_overflow(drrfo->drr_firstobj, drrfo->drr_numobjs)) {
2250 		return (recv_check_fail(EINVAL, errbuf, errbuflen,
2251 		    "DRR_FREEOBJECTS first object %llu + count %llu overflows",
2252 		    (u_longlong_t)drrfo->drr_firstobj,
2253 		    (u_longlong_t)drrfo->drr_numobjs));
2254 	}
2255 
2256 	return (0);
2257 }
2258 
2259 /*
2260  * Validate a DRR_OBJECT_RANGE record.  Only sent on raw streams.
2261  */
2262 int
recv_check_drr_object_range(const struct drr_object_range * drror,boolean_t raw,char * errbuf,size_t errbuflen)2263 recv_check_drr_object_range(const struct drr_object_range *drror,
2264     boolean_t raw, char *errbuf, size_t errbuflen)
2265 {
2266 	/* DRR_OBJECT_RANGE is only valid on raw receive streams */
2267 	if (!raw) {
2268 		return (recv_check_fail(EINVAL, errbuf, errbuflen,
2269 		    "DRR_OBJECT_RANGE is only valid on raw streams"));
2270 	}
2271 
2272 	/* range must cover exactly one dnode block */
2273 	if (drror->drr_numslots != DNODES_PER_BLOCK) {
2274 		return (recv_check_fail(EINVAL, errbuf, errbuflen,
2275 		    "DRR_OBJECT_RANGE numslots %llu != %u",
2276 		    (u_longlong_t)drror->drr_numslots, DNODES_PER_BLOCK));
2277 	}
2278 
2279 	/* first object must be aligned to a dnode block boundary */
2280 	if (P2PHASE(drror->drr_firstobj, DNODES_PER_BLOCK) != 0) {
2281 		return (recv_check_fail(EINVAL, errbuf, errbuflen,
2282 		    "DRR_OBJECT_RANGE first object %llu is not dnode-block "
2283 		    "aligned", (u_longlong_t)drror->drr_firstobj));
2284 	}
2285 
2286 	/* firstobj + numslots must not overflow uint64_t */
2287 	if (recv_u64_add_overflow(drror->drr_firstobj, drror->drr_numslots)) {
2288 		return (recv_check_fail(EINVAL, errbuf, errbuflen,
2289 		    "DRR_OBJECT_RANGE first object %llu + numslots %llu "
2290 		    "overflows", (u_longlong_t)drror->drr_firstobj,
2291 		    (u_longlong_t)drror->drr_numslots));
2292 	}
2293 
2294 	/* object range must not extend past DN_MAX_OBJECT */
2295 	if (drror->drr_firstobj + drror->drr_numslots > DN_MAX_OBJECT) {
2296 		return (recv_check_fail(EINVAL, errbuf, errbuflen,
2297 		    "DRR_OBJECT_RANGE extends past DN_MAX_OBJECT"));
2298 	}
2299 
2300 	return (0);
2301 }
2302 
2303 /*
2304  * Validate a DRR_SPILL record before reading spill payload or writing
2305  * the spill block.
2306  */
2307 int
recv_check_drr_spill(const struct drr_spill * drrs,spa_t * spa,boolean_t raw,uint64_t featureflags,char * errbuf,size_t errbuflen)2308 recv_check_drr_spill(const struct drr_spill *drrs, spa_t *spa, boolean_t raw,
2309     uint64_t featureflags, char *errbuf, size_t errbuflen)
2310 {
2311 	uint64_t psize = DRR_SPILL_PAYLOAD_SIZE(drrs);
2312 	recv_check_limits_t limits;
2313 
2314 	recv_check_resolve_limits(spa, &limits);
2315 
2316 	/* object number must be valid */
2317 	int err = recv_check_drr_object_id(drrs->drr_object, errbuf, errbuflen);
2318 
2319 	if (err != 0)
2320 		return (err);
2321 
2322 	/*
2323 	 * receive_spill() indexes DMU_OT_* tables with drr_type for both
2324 	 * raw and non-raw paths (metadata bit, byteswap).  Non-raw dumps
2325 	 * leave type as DMU_OT_NONE, which is valid.
2326 	 */
2327 	if (!DMU_OT_IS_VALID(drrs->drr_type)) {
2328 		return (recv_check_fail(EINVAL, errbuf, errbuflen,
2329 		    "DRR_SPILL has invalid type %u", drrs->drr_type));
2330 	}
2331 
2332 	/* logical spill size must be at least SPA_MINBLOCKSIZE */
2333 	err = recv_check_drr_size_min(drrs->drr_length, SPA_MINBLOCKSIZE,
2334 	    errbuf, errbuflen, "DRR_SPILL logical size");
2335 	if (err != 0)
2336 		return (err);
2337 
2338 	/* logical spill size must not exceed pool maximum */
2339 	err = recv_check_drr_size_max(drrs->drr_length, limits.rcl_maxblocksize,
2340 	    errbuf, errbuflen, "DRR_SPILL logical size");
2341 	if (err != 0)
2342 		return (err);
2343 
2344 	/* spill payload size must not exceed pool maximum */
2345 	err = recv_check_drr_size_max(psize, limits.rcl_maxblocksize, errbuf,
2346 	    errbuflen, "DRR_SPILL payload size");
2347 	if (err != 0)
2348 		return (err);
2349 
2350 	/*
2351 	 * On raw streams drr_compressed_size holds the on-disk payload size
2352 	 * (BP psize), not whether compression was used.  dump_spill() always
2353 	 * sets it from BP_GET_PSIZE(); uncompressed raw spill blocks still
2354 	 * have compressiontype == ZIO_COMPRESS_OFF and a non-zero psize.
2355 	 * Non-raw streams leave drr_compressed_size at zero and use drr_length
2356 	 * for the payload (see DRR_SPILL_PAYLOAD_SIZE).
2357 	 */
2358 	if (raw && drrs->drr_compressed_size == 0) {
2359 		return (recv_check_fail(EINVAL, errbuf, errbuflen,
2360 		    "DRR_SPILL payload size must be non-zero on raw "
2361 		    "streams"));
2362 	} else if (!raw && drrs->drr_compressed_size != 0) {
2363 		return (recv_check_fail(EINVAL, errbuf, errbuflen,
2364 		    "DRR_SPILL compressed payload size must be zero on non-raw "
2365 		    "streams"));
2366 	}
2367 
2368 	if (drrs->drr_compressed_size != 0) {
2369 		/* compression type must be within ZIO_COMPRESS_FUNCTIONS */
2370 		if (drrs->drr_compressiontype >= ZIO_COMPRESS_FUNCTIONS) {
2371 			return (recv_check_fail(EINVAL, errbuf, errbuflen,
2372 			    "DRR_SPILL has invalid compression type %u",
2373 			    drrs->drr_compressiontype));
2374 		}
2375 
2376 		err = recv_check_compress_feature(drrs->drr_compressiontype,
2377 		    featureflags, errbuf, errbuflen, "DRR_SPILL");
2378 		if (err != 0)
2379 			return (err);
2380 
2381 		/* length must be at least compressed payload size */
2382 		if (drrs->drr_length < drrs->drr_compressed_size) {
2383 			return (recv_check_fail(EINVAL, errbuf, errbuflen,
2384 			    "DRR_SPILL logical size %llu < "
2385 			    "compressed size %llu",
2386 			    (u_longlong_t)drrs->drr_length,
2387 			    (u_longlong_t)drrs->drr_compressed_size));
2388 		}
2389 	} else if (drrs->drr_compressiontype != 0) {
2390 		/* non-compressed spill must not claim a compression type */
2391 		return (recv_check_fail(EINVAL, errbuf, errbuflen,
2392 		    "DRR_SPILL compression type must be zero when "
2393 		    "uncompressed"));
2394 	}
2395 
2396 	return (0);
2397 }
2398 
2399 /*
2400  * Validate a DRR_WRITE record before reading payload or batching the
2401  * write.
2402  */
2403 int
recv_check_drr_write(const struct drr_write * drrw,spa_t * spa,boolean_t raw,uint64_t featureflags,char * errbuf,size_t errbuflen)2404 recv_check_drr_write(const struct drr_write *drrw, spa_t *spa, boolean_t raw,
2405     uint64_t featureflags, char *errbuf, size_t errbuflen)
2406 {
2407 	uint64_t psize = DRR_WRITE_PAYLOAD_SIZE(drrw);
2408 	recv_check_limits_t limits;
2409 
2410 	recv_check_resolve_limits(spa, &limits);
2411 
2412 	/* object number must be valid */
2413 	int err = recv_check_drr_object_id(drrw->drr_object, errbuf, errbuflen);
2414 
2415 	if (err != 0)
2416 		return (err);
2417 
2418 	/* logical write size must be at least SPA_MINBLOCKSIZE */
2419 	err = recv_check_drr_size_min(drrw->drr_logical_size, SPA_MINBLOCKSIZE,
2420 	    errbuf, errbuflen, "DRR_WRITE logical size");
2421 	if (err != 0)
2422 		return (err);
2423 
2424 	/* logical write size must not exceed pool maximum */
2425 	err = recv_check_drr_size_max(drrw->drr_logical_size,
2426 	    limits.rcl_maxblocksize, errbuf, errbuflen,
2427 	    "DRR_WRITE logical size");
2428 	if (err != 0)
2429 		return (err);
2430 
2431 	/* blocks larger than SPA_OLD_MAXBLOCKSIZE require LARGE_BLOCKS */
2432 	if (drrw->drr_logical_size > SPA_OLD_MAXBLOCKSIZE &&
2433 	    !(featureflags & DMU_BACKUP_FEATURE_LARGE_BLOCKS)) {
2434 		return (recv_check_fail(EINVAL, errbuf, errbuflen,
2435 		    "DRR_WRITE logical size %llu requires "
2436 		    "DMU_BACKUP_FEATURE_LARGE_BLOCKS",
2437 		    (u_longlong_t)drrw->drr_logical_size));
2438 	}
2439 
2440 	/* on-wire payload size must not exceed pool maximum */
2441 	err = recv_check_drr_size_max(psize, limits.rcl_maxblocksize, errbuf,
2442 	    errbuflen, "DRR_WRITE payload size");
2443 	if (err != 0)
2444 		return (err);
2445 
2446 	if (raw) {
2447 		/*
2448 		 * Raw sends populate drr_compressed_size with the on-disk psize
2449 		 * even for ZIO_COMPRESS_OFF blocks.
2450 		 */
2451 		if (drrw->drr_compressed_size == 0) {
2452 			return (recv_check_fail(EINVAL, errbuf, errbuflen,
2453 			    "DRR_WRITE compressed size must be non-zero on "
2454 			    "raw streams"));
2455 		}
2456 
2457 		if (drrw->drr_compressiontype >= ZIO_COMPRESS_FUNCTIONS) {
2458 			return (recv_check_fail(EINVAL, errbuf, errbuflen,
2459 			    "DRR_WRITE has invalid compression type %u",
2460 			    drrw->drr_compressiontype));
2461 		}
2462 
2463 		err = recv_check_compress_feature(drrw->drr_compressiontype,
2464 		    featureflags, errbuf, errbuflen, "DRR_WRITE");
2465 		if (err != 0)
2466 			return (err);
2467 
2468 		if (drrw->drr_logical_size < drrw->drr_compressed_size) {
2469 			return (recv_check_fail(EINVAL, errbuf, errbuflen,
2470 			    "DRR_WRITE logical size %llu < "
2471 			    "compressed size %llu",
2472 			    (u_longlong_t)drrw->drr_logical_size,
2473 			    (u_longlong_t)drrw->drr_compressed_size));
2474 		}
2475 	} else if (DRR_WRITE_COMPRESSED(drrw)) {
2476 		if (!(featureflags & DMU_BACKUP_FEATURE_COMPRESSED)) {
2477 			return (recv_check_fail(EINVAL, errbuf, errbuflen,
2478 			    "DRR_WRITE compressed payload requires "
2479 			    "DMU_BACKUP_FEATURE_COMPRESSED"));
2480 		}
2481 
2482 		/* compression type must be within ZIO_COMPRESS_FUNCTIONS */
2483 		if (drrw->drr_compressiontype >= ZIO_COMPRESS_FUNCTIONS) {
2484 			return (recv_check_fail(EINVAL, errbuf, errbuflen,
2485 			    "DRR_WRITE has invalid compression type %u",
2486 			    drrw->drr_compressiontype));
2487 		}
2488 
2489 		err = recv_check_compress_feature(drrw->drr_compressiontype,
2490 		    featureflags, errbuf, errbuflen, "DRR_WRITE");
2491 		if (err != 0)
2492 			return (err);
2493 
2494 		/* compressed payload size must be non-zero */
2495 		if (drrw->drr_compressed_size == 0) {
2496 			return (recv_check_fail(EINVAL, errbuf, errbuflen,
2497 			    "DRR_WRITE compressed size must be non-zero"));
2498 		}
2499 
2500 		/* logical size must be at least the compressed payload size */
2501 		if (drrw->drr_logical_size < drrw->drr_compressed_size) {
2502 			return (recv_check_fail(EINVAL, errbuf, errbuflen,
2503 			    "DRR_WRITE logical size %llu < "
2504 			    "compressed size %llu",
2505 			    (u_longlong_t)drrw->drr_logical_size,
2506 			    (u_longlong_t)drrw->drr_compressed_size));
2507 		}
2508 	} else if (drrw->drr_compressed_size != 0) {
2509 		/* non-compressed write must not claim a compressed size */
2510 		return (recv_check_fail(EINVAL, errbuf, errbuflen,
2511 		    "DRR_WRITE compressed size must be zero when "
2512 		    "uncompressed"));
2513 	}
2514 
2515 	/* offset + logical_size must not overflow uint64_t */
2516 	if (recv_u64_add_overflow(drrw->drr_offset, drrw->drr_logical_size)) {
2517 		return (recv_check_fail(EINVAL, errbuf, errbuflen,
2518 		    "DRR_WRITE offset %llu + logical size %llu overflows",
2519 		    (u_longlong_t)drrw->drr_offset,
2520 		    (u_longlong_t)drrw->drr_logical_size));
2521 	}
2522 
2523 	/* object type must be a valid DMU object type */
2524 	if (!DMU_OT_IS_VALID(drrw->drr_type)) {
2525 		return (recv_check_fail(EINVAL, errbuf, errbuflen,
2526 		    "DRR_WRITE has invalid type %u", drrw->drr_type));
2527 	}
2528 
2529 	/* checksum algorithm must be within ZIO_CHECKSUM_FUNCTIONS */
2530 	if (drrw->drr_checksumtype >= ZIO_CHECKSUM_FUNCTIONS) {
2531 		return (recv_check_fail(EINVAL, errbuf, errbuflen,
2532 		    "DRR_WRITE has invalid checksum type %u",
2533 		    drrw->drr_checksumtype));
2534 	}
2535 
2536 	return (0);
2537 }
2538 
2539 /*
2540  * Validate a DRR_WRITE_EMBEDDED record before reading payload or calling
2541  * dmu_write_embedded().
2542  */
2543 int
recv_check_drr_write_embedded(const struct drr_write_embedded * drrwe,spa_t * spa,boolean_t raw,uint64_t featureflags,char * errbuf,size_t errbuflen)2544 recv_check_drr_write_embedded(const struct drr_write_embedded *drrwe,
2545     spa_t *spa, boolean_t raw, uint64_t featureflags, char *errbuf,
2546     size_t errbuflen)
2547 {
2548 	recv_check_limits_t limits;
2549 
2550 	recv_check_resolve_limits(spa, &limits);
2551 
2552 	if (raw) {
2553 		return (recv_check_fail(EINVAL, errbuf, errbuflen,
2554 		    "DRR_WRITE_EMBEDDED is invalid on raw streams"));
2555 	}
2556 
2557 	if (!(featureflags & DMU_BACKUP_FEATURE_EMBED_DATA)) {
2558 		return (recv_check_fail(EINVAL, errbuf, errbuflen,
2559 		    "DRR_WRITE_EMBEDDED requires "
2560 		    "DMU_BACKUP_FEATURE_EMBED_DATA"));
2561 	}
2562 
2563 	/* object number must be valid */
2564 	int err = recv_check_drr_object_id(drrwe->drr_object,
2565 	    errbuf, errbuflen);
2566 
2567 	if (err != 0)
2568 		return (err);
2569 
2570 	/* logical block size must not exceed pool maximum */
2571 	err = recv_check_drr_size_max(drrwe->drr_length,
2572 	    limits.rcl_maxblocksize, errbuf, errbuflen,
2573 	    "DRR_WRITE_EMBEDDED length");
2574 	if (err != 0)
2575 		return (err);
2576 
2577 	/* blocks larger than SPA_OLD_MAXBLOCKSIZE require LARGE_BLOCKS */
2578 	if (drrwe->drr_length > SPA_OLD_MAXBLOCKSIZE &&
2579 	    !(featureflags & DMU_BACKUP_FEATURE_LARGE_BLOCKS)) {
2580 		return (recv_check_fail(EINVAL, errbuf, errbuflen,
2581 		    "DRR_WRITE_EMBEDDED length %llu requires "
2582 		    "DMU_BACKUP_FEATURE_LARGE_BLOCKS",
2583 		    (u_longlong_t)drrwe->drr_length));
2584 	}
2585 
2586 	/* compressed logical size must not exceed pool maximum */
2587 	err = recv_check_drr_size_max(drrwe->drr_lsize, limits.rcl_maxblocksize,
2588 	    errbuf, errbuflen, "DRR_WRITE_EMBEDDED logical size");
2589 	if (err != 0)
2590 		return (err);
2591 
2592 	/* on-wire payload must fit in the blkptr_t embedded data area */
2593 	err = recv_check_drr_size_max(drrwe->drr_psize, BPE_PAYLOAD_SIZE,
2594 	    errbuf, errbuflen, "DRR_WRITE_EMBEDDED payload size");
2595 	if (err != 0)
2596 		return (err);
2597 
2598 	/* compression algorithm must be within ZIO_COMPRESS_FUNCTIONS */
2599 	if (drrwe->drr_compression >= ZIO_COMPRESS_FUNCTIONS) {
2600 		return (recv_check_fail(EINVAL, errbuf, errbuflen,
2601 		    "DRR_WRITE_EMBEDDED has invalid compression type %u",
2602 		    drrwe->drr_compression));
2603 	}
2604 
2605 	err = recv_check_compress_feature(drrwe->drr_compression, featureflags,
2606 	    errbuf, errbuflen, "DRR_WRITE_EMBEDDED");
2607 	if (err != 0)
2608 		return (err);
2609 
2610 	/* uncompressed embedded data has matching logical and payload sizes */
2611 	if (drrwe->drr_compression == ZIO_COMPRESS_OFF &&
2612 	    drrwe->drr_lsize != drrwe->drr_psize) {
2613 		return (recv_check_fail(EINVAL, errbuf, errbuflen,
2614 		    "DRR_WRITE_EMBEDDED logical size %u must equal payload "
2615 		    "size %u when compression is off",
2616 		    drrwe->drr_lsize, drrwe->drr_psize));
2617 	}
2618 
2619 	/* compressed lsize must be at least the on-wire compressed size */
2620 	if (drrwe->drr_compression != ZIO_COMPRESS_OFF &&
2621 	    drrwe->drr_lsize < drrwe->drr_psize) {
2622 		return (recv_check_fail(EINVAL, errbuf, errbuflen,
2623 		    "DRR_WRITE_EMBEDDED logical size %u < payload size %u",
2624 		    drrwe->drr_lsize, drrwe->drr_psize));
2625 	}
2626 
2627 	/* uncompressed payload must fit in the logical block */
2628 	if (drrwe->drr_lsize > drrwe->drr_length) {
2629 		return (recv_check_fail(EINVAL, errbuf, errbuflen,
2630 		    "DRR_WRITE_EMBEDDED logical size %u exceeds length %llu",
2631 		    drrwe->drr_lsize, (u_longlong_t)drrwe->drr_length));
2632 	}
2633 
2634 	/* offset + length must not overflow uint64_t */
2635 	if (recv_u64_add_overflow(drrwe->drr_offset, drrwe->drr_length)) {
2636 		return (recv_check_fail(EINVAL, errbuf, errbuflen,
2637 		    "DRR_WRITE_EMBEDDED offset %llu + length %llu overflows",
2638 		    (u_longlong_t)drrwe->drr_offset,
2639 		    (u_longlong_t)drrwe->drr_length));
2640 	}
2641 
2642 	/* embedded block type must be within NUM_BP_EMBEDDED_TYPES */
2643 	if (drrwe->drr_etype >= NUM_BP_EMBEDDED_TYPES) {
2644 		return (recv_check_fail(EINVAL, errbuf, errbuflen,
2645 		    "DRR_WRITE_EMBEDDED has invalid embedded type %u",
2646 		    drrwe->drr_etype));
2647 	}
2648 
2649 	return (0);
2650 }
2651 
2652 static int
receive_defer_range_compare(const void * a,const void * b)2653 receive_defer_range_compare(const void *a, const void *b)
2654 {
2655 	const receive_defer_range_t *ra = a;
2656 	const receive_defer_range_t *rb = b;
2657 
2658 	return (TREE_CMP(ra->rdr_first, rb->rdr_first));
2659 }
2660 
2661 /*
2662  * Reclaiming an object number at a different dnode slot count requires the
2663  * old dnode's free to be synced out before the number can be claimed again
2664  * (dnode_check_slots_free() only accepts slots whose final dirty txg has
2665  * synced).  receive_object() historically enforced that with one
2666  * txg_wait_synced() per reallocated object, which collapses receive
2667  * throughput to a few forced txgs per object when an incremental stream
2668  * reallocates many dnodes at a changed slot count (issue #11353).
2669  *
2670  * Instead of syncing per object, the receive writer defers such claims:
2671  * the frees are issued immediately, the affected slot ranges are recorded
2672  * in rwa->defer_ranges, and the whole record is parked on
2673  * rwa->defer_records.  Any later record that touches a parked range is
2674  * parked too, in stream order, while unrelated records keep flowing.  When
2675  * the batch grows past zfs_recv_defer_batch_size (or the stream ends), a
2676  * single txg_wait_synced() covers every deferred free and the parked
2677  * records are replayed in order; the replayed DRR_OBJECT records then find
2678  * their object numbers free on disk and take the ordinary allocation path.
2679  *
2680  * Raw streams are excluded: their DRR_OBJECT_RANGE encryption parameters
2681  * are consumed by the first claim after each range record, so deferring
2682  * claims would require snapshotting that state per record.  Raw receives
2683  * take the historical sync-per-object path unchanged.
2684  */
2685 static boolean_t
receive_defer_enabled(const struct receive_writer_arg * rwa)2686 receive_defer_enabled(const struct receive_writer_arg *rwa)
2687 {
2688 	return (!rwa->raw && !rwa->heal && !rwa->defer_replaying &&
2689 	    zfs_recv_defer_batch_size != 0);
2690 }
2691 
2692 static boolean_t
receive_defer_active(struct receive_writer_arg * rwa)2693 receive_defer_active(struct receive_writer_arg *rwa)
2694 {
2695 	return (!list_is_empty(&rwa->defer_records));
2696 }
2697 
2698 /*
2699  * dmu_free_long_object(), except the txg the dnode's free lands in is
2700  * folded into rwa->defer_max_free_txg.  The frees a deferred claim
2701  * depends on can never be in a later txg than that high-water mark
2702  * (dmu_free_long_range() commits its transactions before the dnode
2703  * free is assigned), so the defer flush can wait for exactly that txg
2704  * instead of the full open-txg window.
2705  */
2706 static int
receive_defer_free_object(struct receive_writer_arg * rwa,uint64_t object)2707 receive_defer_free_object(struct receive_writer_arg *rwa, uint64_t object)
2708 {
2709 	objset_t *os = rwa->os;
2710 	dmu_tx_t *tx;
2711 	int err;
2712 
2713 	err = dmu_free_long_range(os, object, 0, DMU_OBJECT_END);
2714 	if (err != 0)
2715 		return (err);
2716 
2717 	tx = dmu_tx_create(os);
2718 	dmu_tx_hold_bonus(tx, object);
2719 	dmu_tx_hold_free(tx, object, 0, DMU_OBJECT_END);
2720 	dmu_tx_mark_netfree(tx);
2721 	err = dmu_tx_assign(tx, DMU_TX_WAIT);
2722 	if (err == 0) {
2723 		err = dmu_object_free(os, object, tx);
2724 		rwa->defer_max_free_txg = MAX(rwa->defer_max_free_txg,
2725 		    dmu_tx_get_txg(tx));
2726 		dmu_tx_commit(tx);
2727 	} else {
2728 		dmu_tx_abort(tx);
2729 	}
2730 
2731 	return (err);
2732 }
2733 
2734 /*
2735  * Ranges in the tree are kept disjoint: an insert that overlaps or abuts
2736  * existing ranges merges them into one node.  receive_defer_overlaps()
2737  * relies on this to give exact answers with one neighbor probe each way.
2738  * A bare AVL tree fits better here than zfs_range_tree_t, which asserts
2739  * on overlapping adds (the expansion loop inserts ranges that overlap
2740  * the claim's) and carries segment accounting this tree, empty outside
2741  * a realloc burst, has no use for.
2742  */
2743 static void
receive_defer_range_insert(struct receive_writer_arg * rwa,uint64_t first,uint64_t last)2744 receive_defer_range_insert(struct receive_writer_arg *rwa, uint64_t first,
2745     uint64_t last)
2746 {
2747 	receive_defer_range_t srch = { .rdr_first = first };
2748 	avl_index_t where;
2749 	receive_defer_range_t *rdr, *next;
2750 
2751 	rdr = avl_find(&rwa->defer_ranges, &srch, &where);
2752 	if (rdr == NULL) {
2753 		rdr = avl_nearest(&rwa->defer_ranges, where, AVL_BEFORE);
2754 		if (rdr != NULL && rdr->rdr_last + 1 < first)
2755 			rdr = NULL;
2756 	}
2757 	if (rdr == NULL) {
2758 		rdr = kmem_alloc(sizeof (*rdr), KM_SLEEP);
2759 		rdr->rdr_first = first;
2760 		rdr->rdr_last = last;
2761 		avl_insert(&rwa->defer_ranges, rdr, where);
2762 	} else {
2763 		rdr->rdr_last = MAX(rdr->rdr_last, last);
2764 	}
2765 
2766 	while ((next = AVL_NEXT(&rwa->defer_ranges, rdr)) != NULL &&
2767 	    next->rdr_first <= rdr->rdr_last + 1) {
2768 		rdr->rdr_last = MAX(rdr->rdr_last, next->rdr_last);
2769 		avl_remove(&rwa->defer_ranges, next);
2770 		kmem_free(next, sizeof (*next));
2771 	}
2772 }
2773 
2774 static boolean_t
receive_defer_overlaps(struct receive_writer_arg * rwa,uint64_t first,uint64_t last)2775 receive_defer_overlaps(struct receive_writer_arg *rwa, uint64_t first,
2776     uint64_t last)
2777 {
2778 	receive_defer_range_t srch = { .rdr_first = first };
2779 	avl_index_t where;
2780 	receive_defer_range_t *rdr;
2781 
2782 	if (avl_find(&rwa->defer_ranges, &srch, &where) != NULL)
2783 		return (B_TRUE);
2784 
2785 	rdr = avl_nearest(&rwa->defer_ranges, where, AVL_BEFORE);
2786 	if (rdr != NULL && rdr->rdr_last >= first)
2787 		return (B_TRUE);
2788 
2789 	rdr = avl_nearest(&rwa->defer_ranges, where, AVL_AFTER);
2790 	if (rdr != NULL && rdr->rdr_first <= last)
2791 		return (B_TRUE);
2792 
2793 	return (B_FALSE);
2794 }
2795 
2796 static int receive_defer_flush(struct receive_writer_arg *rwa);
2797 
2798 /*
2799  * Park a record for replay after the next defer flush.  The caller must
2800  * return EAGAIN without touching the record again: once the batch cap is
2801  * reached the flush below replays and frees it.  A flush failure is
2802  * published through rwa->err (this always runs on the writer thread, the
2803  * sole writer of that field).
2804  */
2805 static void
receive_defer_park(struct receive_writer_arg * rwa,struct receive_record_arg * rrd,uint64_t object)2806 receive_defer_park(struct receive_writer_arg *rwa,
2807     struct receive_record_arg *rrd, uint64_t object)
2808 {
2809 	/*
2810 	 * Nothing may defer during replay, or the list being drained
2811 	 * would grow and the record could be freed out from under the
2812 	 * replay loop.
2813 	 */
2814 	ASSERT(!rwa->defer_replaying);
2815 
2816 	if (!receive_defer_active(rwa)) {
2817 		/*
2818 		 * The resume pin depends on the first parked record being
2819 		 * an object record: resuming from (object, 0) is only a
2820 		 * valid stream position for a DRR_OBJECT.
2821 		 */
2822 		ASSERT3U(rrd->header.drr_type, ==, DRR_OBJECT);
2823 		rwa->defer_first_object = object;
2824 		rwa->defer_first_bytes_read = rrd->bytes_read;
2825 	}
2826 	list_insert_tail(&rwa->defer_records, rrd);
2827 	rwa->defer_nrecords++;
2828 	/* For WRITE and SPILL records the payload aliases the abd. */
2829 	rwa->defer_bytes += sizeof (*rrd) + (rrd->abd != NULL ?
2830 	    abd_get_size(rrd->abd) : rrd->payload_size);
2831 
2832 	if (rwa->defer_bytes >= zfs_recv_defer_batch_size) {
2833 		int err = receive_defer_flush(rwa);
2834 		if (err != 0 && rwa->err == 0)
2835 			rwa->err = err;
2836 	}
2837 }
2838 
2839 /*
2840  * Sync out the deferred frees and replay the parked records in stream
2841  * order.  Replay feeds each record back through receive_process_record();
2842  * by now every deferred free has synced, so the replayed DRR_OBJECT
2843  * records find their object numbers free and no longer defer.
2844  */
2845 static int
receive_defer_flush(struct receive_writer_arg * rwa)2846 receive_defer_flush(struct receive_writer_arg *rwa)
2847 {
2848 	struct receive_record_arg *rrd;
2849 	receive_defer_range_t *rdr;
2850 	void *cookie = NULL;
2851 	int err;
2852 
2853 	if (!receive_defer_active(rwa))
2854 		return (0);
2855 
2856 	err = flush_write_batch(rwa);
2857 	if (err != 0)
2858 		return (err);
2859 
2860 	zfs_dbgmsg("recv defer flush: %llu records, %llu bytes, txg %llu",
2861 	    (u_longlong_t)rwa->defer_nrecords,
2862 	    (u_longlong_t)rwa->defer_bytes,
2863 	    (u_longlong_t)rwa->defer_max_free_txg);
2864 
2865 	/*
2866 	 * Every free a parked claim depends on was assigned no later
2867 	 * than defer_max_free_txg, so it is enough to wait for that txg
2868 	 * rather than for the whole open-txg window (typically one or
2869 	 * two txgs instead of up to five).
2870 	 */
2871 	txg_wait_synced(dmu_objset_pool(rwa->os), rwa->defer_max_free_txg);
2872 
2873 	while ((rdr = avl_destroy_nodes(&rwa->defer_ranges, &cookie)) != NULL)
2874 		kmem_free(rdr, sizeof (*rdr));
2875 
2876 	/*
2877 	 * Parked records are earlier in the stream than the writer's
2878 	 * current position, so drop the write-ordering cursor for the
2879 	 * replay; the parked records are in stream order among
2880 	 * themselves, and every record that follows the replay is at a
2881 	 * higher (object, offset) than anything replayed.  The
2882 	 * out-of-order check is correspondingly weakened until the
2883 	 * first replayed write raises the cursor again.
2884 	 */
2885 	rwa->last_object = 0;
2886 	rwa->last_offset = 0;
2887 	rwa->defer_replaying = B_TRUE;
2888 
2889 	while ((rrd = list_remove_head(&rwa->defer_records)) != NULL) {
2890 		if (err != 0) {
2891 			if (rrd->abd != NULL) {
2892 				abd_free(rrd->abd);
2893 				rrd->abd = NULL;
2894 				rrd->payload = NULL;
2895 			} else if (rrd->payload != NULL) {
2896 				vmem_free(rrd->payload, rrd->payload_size);
2897 				rrd->payload = NULL;
2898 			}
2899 			kmem_free(rrd, sizeof (*rrd));
2900 			continue;
2901 		}
2902 		int err2 = receive_process_record(rwa, rrd);
2903 		/*
2904 		 * As in receive_writer_thread(), EAGAIN means the record
2905 		 * was stashed on the write batch and must not be freed.
2906 		 */
2907 		if (err2 != EAGAIN) {
2908 			err = err2;
2909 			kmem_free(rrd, sizeof (*rrd));
2910 		}
2911 	}
2912 
2913 	if (err == 0)
2914 		err = flush_write_batch(rwa);
2915 
2916 	/*
2917 	 * Frees issued during the replay itself are not captured in
2918 	 * defer_max_free_txg once it resets below.  That stays safe:
2919 	 * any txg captured later is no earlier than theirs, and a batch
2920 	 * with nothing captured waits for everything (txg 0).
2921 	 */
2922 	rwa->defer_replaying = B_FALSE;
2923 	rwa->defer_bytes = 0;
2924 	rwa->defer_nrecords = 0;
2925 	rwa->defer_first_object = 0;
2926 	rwa->defer_first_bytes_read = 0;
2927 	rwa->defer_max_free_txg = 0;
2928 
2929 	return (err);
2930 }
2931 
2932 /*
2933  * Free any records still parked after an error, along with the range
2934  * tree.  No-op if a successful flush already drained both.
2935  */
2936 static void
receive_defer_cleanup(struct receive_writer_arg * rwa)2937 receive_defer_cleanup(struct receive_writer_arg *rwa)
2938 {
2939 	struct receive_record_arg *rrd;
2940 	receive_defer_range_t *rdr;
2941 	void *cookie = NULL;
2942 
2943 	while ((rrd = list_remove_head(&rwa->defer_records)) != NULL) {
2944 		if (rrd->abd != NULL) {
2945 			abd_free(rrd->abd);
2946 			rrd->abd = NULL;
2947 			rrd->payload = NULL;
2948 		} else if (rrd->payload != NULL) {
2949 			vmem_free(rrd->payload, rrd->payload_size);
2950 			rrd->payload = NULL;
2951 		}
2952 		kmem_free(rrd, sizeof (*rrd));
2953 	}
2954 	while ((rdr = avl_destroy_nodes(&rwa->defer_ranges, &cookie)) != NULL)
2955 		kmem_free(rdr, sizeof (*rdr));
2956 	rwa->defer_bytes = 0;
2957 	rwa->defer_nrecords = 0;
2958 	rwa->defer_first_object = 0;
2959 	rwa->defer_first_bytes_read = 0;
2960 	rwa->defer_max_free_txg = 0;
2961 }
2962 
2963 /*
2964  * If this record touches a dnode slot range with an unsynced free, park
2965  * it for replay after the next defer flush.  Returns EAGAIN when the
2966  * record was parked (the caller must not free or process it, and the
2967  * park may already have flushed and freed it), or 0 when the record
2968  * should be processed normally.
2969  */
2970 static int
receive_defer_check(struct receive_writer_arg * rwa,struct receive_record_arg * rrd)2971 receive_defer_check(struct receive_writer_arg *rwa,
2972     struct receive_record_arg *rrd)
2973 {
2974 	uint64_t first, last;
2975 
2976 	switch (rrd->header.drr_type) {
2977 	case DRR_OBJECT:
2978 		/*
2979 		 * Object records are never parked here.  A multi-slot claim
2980 		 * can expand over a dnode that begins inside the claimed
2981 		 * range and ends past it, and only the expansion loop in
2982 		 * receive_object() finds that dnode, frees it and records
2983 		 * the extent it actually occupies.  Parking ahead of that
2984 		 * loop would leave the dnode allocated with its tail slots
2985 		 * outside the tree, and the DRR_FREEOBJECTS the sender
2986 		 * emits for those slots would then be applied against an
2987 		 * interior slot and fail the receive.  receive_object()
2988 		 * defers the claim itself, once the loop has run.
2989 		 */
2990 		return (0);
2991 	case DRR_WRITE:
2992 		first = last = rrd->header.drr_u.drr_write.drr_object;
2993 		break;
2994 	case DRR_WRITE_EMBEDDED:
2995 		first = last = rrd->header.drr_u.drr_write_embedded.drr_object;
2996 		break;
2997 	case DRR_FREE:
2998 		first = last = rrd->header.drr_u.drr_free.drr_object;
2999 		break;
3000 	case DRR_SPILL:
3001 		first = last = rrd->header.drr_u.drr_spill.drr_object;
3002 		break;
3003 	case DRR_REDACT:
3004 		first = last = rrd->header.drr_u.drr_redact.drr_object;
3005 		break;
3006 	case DRR_FREEOBJECTS:
3007 	{
3008 		struct drr_freeobjects *drrfo =
3009 		    &rrd->header.drr_u.drr_freeobjects;
3010 
3011 		/*
3012 		 * Senders routinely free the tail slots of an object
3013 		 * that was reallocated at a smaller dnode size, so these
3014 		 * ranges do overlap deferred ones.  Park the record; by
3015 		 * replay time the slots it covers were freed along with
3016 		 * the old dnode and the frees are no-ops.  The parked
3017 		 * range joins the tree so that anything a malformed
3018 		 * stream sends into it afterwards stays ordered behind
3019 		 * the free instead of racing it at replay.
3020 		 */
3021 		if (drrfo->drr_numobjs != 0 &&
3022 		    receive_defer_overlaps(rwa, drrfo->drr_firstobj,
3023 		    drrfo->drr_firstobj + drrfo->drr_numobjs - 1)) {
3024 			receive_defer_range_insert(rwa, drrfo->drr_firstobj,
3025 			    drrfo->drr_firstobj + drrfo->drr_numobjs - 1);
3026 			receive_defer_park(rwa, rrd, drrfo->drr_firstobj);
3027 			return (EAGAIN);
3028 		}
3029 		return (0);
3030 	}
3031 	default:
3032 		return (0);
3033 	}
3034 
3035 	if (receive_defer_overlaps(rwa, first, last)) {
3036 		receive_defer_park(rwa, rrd, first);
3037 		return (EAGAIN);
3038 	}
3039 	return (0);
3040 }
3041 
3042 static int
receive_handle_existing_object(struct receive_writer_arg * rwa,const struct drr_object * drro,const dmu_object_info_t * doi,const void * bonus_data,uint64_t * object_to_hold,uint32_t * new_blksz,boolean_t * deferp)3043 receive_handle_existing_object(struct receive_writer_arg *rwa,
3044     const struct drr_object *drro, const dmu_object_info_t *doi,
3045     const void *bonus_data,
3046     uint64_t *object_to_hold, uint32_t *new_blksz, boolean_t *deferp)
3047 {
3048 	uint32_t indblksz = drro->drr_indblkshift ?
3049 	    1ULL << drro->drr_indblkshift : 0;
3050 	uint8_t dn_slots = drro->drr_dn_slots != 0 ?
3051 	    drro->drr_dn_slots : DNODE_MIN_SLOTS;
3052 	int nblkptr = deduce_nblkptr(drro->drr_bonustype,
3053 	    drro->drr_bonuslen, dn_slots);
3054 	boolean_t do_free_range = B_FALSE;
3055 	int err;
3056 
3057 	*object_to_hold = drro->drr_object;
3058 
3059 	/* nblkptr should be bounded by the bonus size and type */
3060 	if (rwa->raw && nblkptr != drro->drr_nblkptr)
3061 		return (SET_ERROR(EINVAL));
3062 
3063 	/*
3064 	 * After the previous send stream, the sending system may
3065 	 * have freed this object, and then happened to re-allocate
3066 	 * this object number in a later txg. In this case, we are
3067 	 * receiving a different logical file, and the block size may
3068 	 * appear to be different.  i.e. we may have a different
3069 	 * block size for this object than what the send stream says.
3070 	 * In this case we need to remove the object's contents,
3071 	 * so that its structure can be changed and then its contents
3072 	 * entirely replaced by subsequent WRITE records.
3073 	 *
3074 	 * If this is a -L (--large-block) incremental stream, and
3075 	 * the previous stream was not -L, the block size may appear
3076 	 * to increase.  i.e. we may have a smaller block size for
3077 	 * this object than what the send stream says.  In this case
3078 	 * we need to keep the object's contents and block size
3079 	 * intact, so that we don't lose parts of the object's
3080 	 * contents that are not changed by this incremental send
3081 	 * stream.
3082 	 *
3083 	 * We can distinguish between the two above cases by using
3084 	 * the ZPL's generation number (see
3085 	 * receive_object_is_same_generation()).  However, we only
3086 	 * want to rely on the generation number when absolutely
3087 	 * necessary, because with raw receives, the generation is
3088 	 * encrypted.  We also want to minimize dependence on the
3089 	 * ZPL, so that other types of datasets can also be received
3090 	 * (e.g. ZVOLs, although note that ZVOLS currently do not
3091 	 * reallocate their objects or change their structure).
3092 	 * Therefore, we check a number of different cases where we
3093 	 * know it is safe to discard the object's contents, before
3094 	 * using the ZPL's generation number to make the above
3095 	 * distinction.
3096 	 */
3097 	if (drro->drr_blksz != doi->doi_data_block_size) {
3098 		if (rwa->raw) {
3099 			/*
3100 			 * RAW streams always have large blocks, so
3101 			 * we are sure that the data is not needed
3102 			 * due to changing --large-block to be on.
3103 			 * Which is fortunate since the bonus buffer
3104 			 * (which contains the ZPL generation) is
3105 			 * encrypted, and the key might not be
3106 			 * loaded.
3107 			 */
3108 			do_free_range = B_TRUE;
3109 		} else if (rwa->full) {
3110 			/*
3111 			 * This is a full send stream, so it always
3112 			 * replaces what we have.  Even if the
3113 			 * generation numbers happen to match, this
3114 			 * can not actually be the same logical file.
3115 			 * This is relevant when receiving a full
3116 			 * send as a clone.
3117 			 */
3118 			do_free_range = B_TRUE;
3119 		} else if (drro->drr_type !=
3120 		    DMU_OT_PLAIN_FILE_CONTENTS ||
3121 		    doi->doi_type != DMU_OT_PLAIN_FILE_CONTENTS) {
3122 			/*
3123 			 * PLAIN_FILE_CONTENTS are the only type of
3124 			 * objects that have ever been stored with
3125 			 * large blocks, so we don't need the special
3126 			 * logic below.  ZAP blocks can shrink (when
3127 			 * there's only one block), so we don't want
3128 			 * to hit the error below about block size
3129 			 * only increasing.
3130 			 */
3131 			do_free_range = B_TRUE;
3132 		} else if (doi->doi_max_offset <=
3133 		    doi->doi_data_block_size) {
3134 			/*
3135 			 * There is only one block.  We can free it,
3136 			 * because its contents will be replaced by a
3137 			 * WRITE record.  This can not be the no-L ->
3138 			 * -L case, because the no-L case would have
3139 			 * resulted in multiple blocks.  If we
3140 			 * supported -L -> no-L, it would not be safe
3141 			 * to free the file's contents.  Fortunately,
3142 			 * that is not allowed (see
3143 			 * recv_check_large_blocks()).
3144 			 */
3145 			do_free_range = B_TRUE;
3146 		} else {
3147 			boolean_t is_same_gen;
3148 			err = receive_object_is_same_generation(rwa->os,
3149 			    drro->drr_object, doi->doi_bonus_type,
3150 			    drro->drr_bonustype, bonus_data, &is_same_gen);
3151 			if (err != 0)
3152 				return (SET_ERROR(EINVAL));
3153 
3154 			if (is_same_gen) {
3155 				/*
3156 				 * This is the same logical file, and
3157 				 * the block size must be increasing.
3158 				 * It could only decrease if
3159 				 * --large-block was changed to be
3160 				 * off, which is checked in
3161 				 * recv_check_large_blocks().
3162 				 */
3163 				if (drro->drr_blksz <=
3164 				    doi->doi_data_block_size)
3165 					return (SET_ERROR(EINVAL));
3166 				/*
3167 				 * We keep the existing blocksize and
3168 				 * contents.
3169 				 */
3170 				*new_blksz =
3171 				    doi->doi_data_block_size;
3172 			} else {
3173 				do_free_range = B_TRUE;
3174 			}
3175 		}
3176 	}
3177 
3178 	/* nblkptr can only decrease if the object was reallocated */
3179 	if (nblkptr < doi->doi_nblkptr)
3180 		do_free_range = B_TRUE;
3181 
3182 	/* number of slots can only change on reallocation */
3183 	if (dn_slots != doi->doi_dnodesize >> DNODE_SHIFT)
3184 		do_free_range = B_TRUE;
3185 
3186 	/*
3187 	 * For raw sends we also check a few other fields to
3188 	 * ensure we are preserving the objset structure exactly
3189 	 * as it was on the receive side:
3190 	 *     - A changed indirect block size
3191 	 *     - A smaller nlevels
3192 	 */
3193 	if (rwa->raw) {
3194 		if (indblksz != doi->doi_metadata_block_size)
3195 			do_free_range = B_TRUE;
3196 		if (drro->drr_nlevels < doi->doi_indirection)
3197 			do_free_range = B_TRUE;
3198 	}
3199 
3200 	if (do_free_range) {
3201 		err = dmu_free_long_range(rwa->os, drro->drr_object,
3202 		    0, DMU_OBJECT_END);
3203 		if (err != 0)
3204 			return (SET_ERROR(EINVAL));
3205 	}
3206 
3207 	/*
3208 	 * The dmu does not currently support decreasing nlevels or changing
3209 	 * indirect block size if there is already one, same as changing the
3210 	 * number of of dnode slots on an object.  For non-raw sends this
3211 	 * does not matter and the new object can just use the previous one's
3212 	 * parameters.  For raw sends, however, the structure of the received
3213 	 * dnode (including indirects and dnode slots) must match that of the
3214 	 * send side.  Therefore, instead of using dmu_object_reclaim(), we
3215 	 * must free the object completely and call dmu_object_claim_dnsize()
3216 	 * instead.
3217 	 */
3218 	if ((rwa->raw && ((doi->doi_indirection > 1 &&
3219 	    indblksz != doi->doi_metadata_block_size) ||
3220 	    drro->drr_nlevels < doi->doi_indirection)) ||
3221 	    dn_slots != doi->doi_dnodesize >> DNODE_SHIFT) {
3222 		uint8_t old_slots = doi->doi_dnodesize >> DNODE_SHIFT;
3223 
3224 		err = receive_defer_free_object(rwa, drro->drr_object);
3225 		if (err != 0)
3226 			return (SET_ERROR(EINVAL));
3227 
3228 		if (receive_defer_enabled(rwa)) {
3229 			/*
3230 			 * Defer the claim instead of syncing; the caller
3231 			 * parks this record for replay after the batched
3232 			 * sync (see receive_defer_park()).
3233 			 */
3234 			receive_defer_range_insert(rwa, drro->drr_object,
3235 			    drro->drr_object + MAX(old_slots, dn_slots) - 1);
3236 			*deferp = B_TRUE;
3237 			return (0);
3238 		}
3239 
3240 		txg_wait_synced(dmu_objset_pool(rwa->os), 0);
3241 		*object_to_hold = DMU_NEW_OBJECT;
3242 	}
3243 
3244 	/*
3245 	 * For raw receives, free everything beyond the new incoming
3246 	 * maxblkid. Normally this would be done with a DRR_FREE
3247 	 * record that would come after this DRR_OBJECT record is
3248 	 * processed. However, for raw receives we manually set the
3249 	 * maxblkid from the drr_maxblkid and so we must first free
3250 	 * everything above that blkid to ensure the DMU is always
3251 	 * consistent with itself. We will never free the first block
3252 	 * of the object here because a maxblkid of 0 could indicate
3253 	 * an object with a single block or one with no blocks. This
3254 	 * free may be skipped when dmu_free_long_range() was called
3255 	 * above since it covers the entire object's contents.
3256 	 */
3257 	if (rwa->raw && *object_to_hold != DMU_NEW_OBJECT && !do_free_range) {
3258 		uint64_t nblocks = drro->drr_maxblkid + 1;
3259 
3260 		if (drro->drr_maxblkid == UINT64_MAX)
3261 			return (SET_ERROR(EINVAL));
3262 		if (doi->doi_data_block_size != 0 &&
3263 		    nblocks > UINT64_MAX / doi->doi_data_block_size)
3264 			return (SET_ERROR(EINVAL));
3265 		err = dmu_free_long_range(rwa->os, drro->drr_object,
3266 		    nblocks * doi->doi_data_block_size, DMU_OBJECT_END);
3267 		if (err != 0)
3268 			return (SET_ERROR(EINVAL));
3269 	}
3270 	return (0);
3271 }
3272 
3273 noinline static int
receive_object(struct receive_writer_arg * rwa,struct drr_object * drro,void * data)3274 receive_object(struct receive_writer_arg *rwa, struct drr_object *drro,
3275     void *data)
3276 {
3277 	dmu_object_info_t doi;
3278 	dmu_tx_t *tx;
3279 	uint32_t new_blksz = drro->drr_blksz;
3280 	uint8_t dn_slots = drro->drr_dn_slots != 0 ?
3281 	    drro->drr_dn_slots : DNODE_MIN_SLOTS;
3282 
3283 	/*
3284 	 * Re-validate on the writer path (reader already checked).  Do not
3285 	 * publish ZFS_RECV_ERR_STREAM here - only the reader may mutate the
3286 	 * shared errors nvlist.
3287 	 */
3288 	int err = recv_check_drr_object(drro, dmu_objset_spa(rwa->os), rwa->raw,
3289 	    rwa->spill, rwa->featureflags, NULL, 0);
3290 
3291 	if (err != 0)
3292 		return (err);
3293 
3294 	if (rwa->raw) {
3295 		/*
3296 		 * We should have received a DRR_OBJECT_RANGE record
3297 		 * containing this block and stored it in rwa.
3298 		 */
3299 		if (drro->drr_object < rwa->or_firstobj)
3300 			return (SET_ERROR(EINVAL));
3301 
3302 		/* or_firstobj + or_numslots must not overflow uint64_t */
3303 		if (recv_u64_add_overflow(rwa->or_firstobj, rwa->or_numslots))
3304 			return (SET_ERROR(EINVAL));
3305 
3306 		if (drro->drr_object >= rwa->or_firstobj + rwa->or_numslots)
3307 			return (SET_ERROR(EINVAL));
3308 	}
3309 
3310 	err = dmu_object_info(rwa->os, drro->drr_object, &doi);
3311 
3312 	if (err != 0 && err != ENOENT && err != EEXIST)
3313 		return (SET_ERROR(EINVAL));
3314 
3315 	if (drro->drr_object > rwa->max_object)
3316 		rwa->max_object = drro->drr_object;
3317 
3318 	/*
3319 	 * If we are losing blkptrs or changing the block size this must
3320 	 * be a new file instance.  We must clear out the previous file
3321 	 * contents before we can change this type of metadata in the dnode.
3322 	 * Raw receives will also check that the indirect structure of the
3323 	 * dnode hasn't changed.
3324 	 */
3325 	uint64_t object_to_hold = DMU_NEW_OBJECT;
3326 	boolean_t defer = B_FALSE;
3327 
3328 	/*
3329 	 * Claiming slots that a parked record already covers has to wait
3330 	 * for the batch in any case, but the expansion loop below still
3331 	 * has to run first: it is what discovers a dnode reaching past
3332 	 * the end of this claim, frees it, and puts the slots it really
3333 	 * occupies in the tree.  Without that, the frees the sender sends
3334 	 * for those trailing slots would not be parked behind this claim.
3335 	 */
3336 	if (receive_defer_enabled(rwa) && receive_defer_overlaps(rwa,
3337 	    drro->drr_object, drro->drr_object + dn_slots - 1)) {
3338 		receive_defer_range_insert(rwa, drro->drr_object,
3339 		    drro->drr_object + dn_slots - 1);
3340 		defer = B_TRUE;
3341 	}
3342 
3343 	if (err == 0) {
3344 		/*
3345 		 * When the claim is deferred, still fall through to the
3346 		 * multi-slot expansion below so that neighbor frees are
3347 		 * issued now and share the batched sync.
3348 		 */
3349 		err = receive_handle_existing_object(rwa, drro, &doi, data,
3350 		    &object_to_hold, &new_blksz, &defer);
3351 		if (err != 0)
3352 			return (err);
3353 	} else if (err == EEXIST) {
3354 		/*
3355 		 * The object requested is currently an interior slot of a
3356 		 * multi-slot dnode. This will be resolved when the next txg
3357 		 * is synced out, since the send stream will have told us
3358 		 * to free this slot when we freed the associated dnode
3359 		 * earlier in the stream.
3360 		 */
3361 		if (receive_defer_enabled(rwa)) {
3362 			receive_defer_range_insert(rwa, drro->drr_object,
3363 			    drro->drr_object + dn_slots - 1);
3364 			defer = B_TRUE;
3365 		} else {
3366 			txg_wait_synced(dmu_objset_pool(rwa->os), 0);
3367 
3368 			if (dmu_object_info(rwa->os, drro->drr_object,
3369 			    NULL) != ENOENT)
3370 				return (SET_ERROR(EINVAL));
3371 		}
3372 
3373 		/* object was freed and we are about to allocate a new one */
3374 		object_to_hold = DMU_NEW_OBJECT;
3375 	} else {
3376 		/*
3377 		 * If the only record in this range so far was DRR_FREEOBJECTS
3378 		 * with at least one actually freed object, it's possible that
3379 		 * the block will now be converted to a hole. We need to wait
3380 		 * for the txg to sync to prevent races.
3381 		 */
3382 		if (rwa->or_need_sync == ORNS_YES)
3383 			txg_wait_synced(dmu_objset_pool(rwa->os), 0);
3384 
3385 		/* object is free and we are about to allocate a new one */
3386 		object_to_hold = DMU_NEW_OBJECT;
3387 	}
3388 
3389 	/* Only relevant for the first object in the range */
3390 	rwa->or_need_sync = ORNS_NO;
3391 
3392 	/*
3393 	 * If this is a multi-slot dnode there is a chance that this
3394 	 * object will expand into a slot that is already used by
3395 	 * another object from the previous snapshot. We must free
3396 	 * these objects before we attempt to allocate the new dnode.
3397 	 */
3398 	if (dn_slots > 1) {
3399 		boolean_t need_sync = B_FALSE;
3400 
3401 		for (uint64_t slot = drro->drr_object + 1;
3402 		    slot < drro->drr_object + dn_slots;
3403 		    slot++) {
3404 			dmu_object_info_t slot_doi;
3405 
3406 			err = dmu_object_info(rwa->os, slot, &slot_doi);
3407 			if (err == ENOENT || err == EEXIST)
3408 				continue;
3409 			else if (err != 0)
3410 				return (err);
3411 
3412 			err = receive_defer_free_object(rwa, slot);
3413 			if (err != 0)
3414 				return (err);
3415 
3416 			if (receive_defer_enabled(rwa)) {
3417 				/*
3418 				 * The freed neighbor may itself have been
3419 				 * a multi-slot dnode extending past the
3420 				 * range being claimed here.
3421 				 */
3422 				uint8_t slot_slots =
3423 				    slot_doi.doi_dnodesize >> DNODE_SHIFT;
3424 				receive_defer_range_insert(rwa, slot,
3425 				    slot + slot_slots - 1);
3426 			}
3427 
3428 			need_sync = B_TRUE;
3429 		}
3430 
3431 		if (need_sync) {
3432 			if (receive_defer_enabled(rwa)) {
3433 				receive_defer_range_insert(rwa,
3434 				    drro->drr_object,
3435 				    drro->drr_object + dn_slots - 1);
3436 				defer = B_TRUE;
3437 			} else {
3438 				txg_wait_synced(dmu_objset_pool(rwa->os), 0);
3439 			}
3440 		}
3441 	}
3442 
3443 	if (defer)
3444 		return (EAGAIN);
3445 
3446 	tx = dmu_tx_create(rwa->os);
3447 	dmu_tx_hold_bonus(tx, object_to_hold);
3448 	dmu_tx_hold_write(tx, object_to_hold, 0, 0);
3449 	err = dmu_tx_assign(tx, DMU_TX_WAIT);
3450 	if (err != 0) {
3451 		dmu_tx_abort(tx);
3452 		return (err);
3453 	}
3454 
3455 	if (object_to_hold == DMU_NEW_OBJECT) {
3456 		/* Currently free, wants to be allocated */
3457 		err = dmu_object_claim_dnsize(rwa->os, drro->drr_object,
3458 		    drro->drr_type, new_blksz,
3459 		    drro->drr_bonustype, drro->drr_bonuslen,
3460 		    dn_slots << DNODE_SHIFT, tx);
3461 	} else if (drro->drr_type != doi.doi_type ||
3462 	    new_blksz != doi.doi_data_block_size ||
3463 	    drro->drr_bonustype != doi.doi_bonus_type ||
3464 	    drro->drr_bonuslen != doi.doi_bonus_size) {
3465 		/* Currently allocated, but with different properties */
3466 		err = dmu_object_reclaim_dnsize(rwa->os, drro->drr_object,
3467 		    drro->drr_type, new_blksz,
3468 		    drro->drr_bonustype, drro->drr_bonuslen,
3469 		    dn_slots << DNODE_SHIFT, rwa->spill ?
3470 		    DRR_OBJECT_HAS_SPILL(drro->drr_flags) : B_FALSE, tx);
3471 	} else if (rwa->spill && !DRR_OBJECT_HAS_SPILL(drro->drr_flags)) {
3472 		/*
3473 		 * Currently allocated, the existing version of this object
3474 		 * may reference a spill block that is no longer allocated
3475 		 * at the source and needs to be freed.
3476 		 */
3477 		err = dmu_object_rm_spill(rwa->os, drro->drr_object, tx);
3478 	}
3479 
3480 	if (err != 0) {
3481 		dmu_tx_commit(tx);
3482 		return (SET_ERROR(EINVAL));
3483 	}
3484 
3485 	if (rwa->or_crypt_params_present) {
3486 		/*
3487 		 * Set the crypt params for the buffer associated with this
3488 		 * range of dnodes.  This causes the blkptr_t to have the
3489 		 * same crypt params (byteorder, salt, iv, mac) as on the
3490 		 * sending side.
3491 		 *
3492 		 * Since we are committing this tx now, it is possible for
3493 		 * the dnode block to end up on-disk with the incorrect MAC,
3494 		 * if subsequent objects in this block are received in a
3495 		 * different txg.  However, since the dataset is marked as
3496 		 * inconsistent, no code paths will do a non-raw read (or
3497 		 * decrypt the block / verify the MAC). The receive code and
3498 		 * scrub code can safely do raw reads and verify the
3499 		 * checksum.  They don't need to verify the MAC.
3500 		 */
3501 		dmu_buf_t *db = NULL;
3502 		uint64_t offset = rwa->or_firstobj * DNODE_MIN_SIZE;
3503 
3504 		err = dmu_buf_hold_by_dnode(DMU_META_DNODE(rwa->os),
3505 		    offset, FTAG, &db, DMU_READ_PREFETCH | DMU_READ_NO_DECRYPT);
3506 		if (err != 0) {
3507 			dmu_tx_commit(tx);
3508 			return (SET_ERROR(EINVAL));
3509 		}
3510 
3511 		dmu_buf_set_crypt_params(db, rwa->or_byteorder,
3512 		    rwa->or_salt, rwa->or_iv, rwa->or_mac, tx);
3513 
3514 		dmu_buf_rele(db, FTAG);
3515 
3516 		rwa->or_crypt_params_present = B_FALSE;
3517 	}
3518 
3519 	dmu_object_set_checksum(rwa->os, drro->drr_object,
3520 	    drro->drr_checksumtype, tx);
3521 	dmu_object_set_compress(rwa->os, drro->drr_object,
3522 	    drro->drr_compress, tx);
3523 
3524 	/* handle more restrictive dnode structuring for raw recvs */
3525 	if (rwa->raw) {
3526 		/*
3527 		 * Set the indirect block size, block shift, nlevels.
3528 		 * This will not fail because we ensured all of the
3529 		 * blocks were freed earlier if this is a new object.
3530 		 * For non-new objects block size and indirect block
3531 		 * shift cannot change and nlevels can only increase.
3532 		 */
3533 		ASSERT3U(new_blksz, ==, drro->drr_blksz);
3534 		VERIFY0(dmu_object_set_blocksize(rwa->os, drro->drr_object,
3535 		    drro->drr_blksz, drro->drr_indblkshift, tx));
3536 		VERIFY0(dmu_object_set_nlevels(rwa->os, drro->drr_object,
3537 		    drro->drr_nlevels, tx));
3538 
3539 		/*
3540 		 * Set the maxblkid. This will always succeed because
3541 		 * we freed all blocks beyond the new maxblkid above.
3542 		 */
3543 		VERIFY0(dmu_object_set_maxblkid(rwa->os, drro->drr_object,
3544 		    drro->drr_maxblkid, tx));
3545 	}
3546 
3547 	if (data != NULL) {
3548 		dmu_buf_t *db;
3549 		dnode_t *dn;
3550 		dmu_flags_t flags = DMU_READ_NO_PREFETCH;
3551 
3552 		if (rwa->raw)
3553 			flags |= DMU_READ_NO_DECRYPT;
3554 
3555 		VERIFY0(dnode_hold(rwa->os, drro->drr_object, FTAG, &dn));
3556 		VERIFY0(dmu_bonus_hold_by_dnode(dn, FTAG, &db, flags));
3557 
3558 		dmu_buf_will_dirty(db, tx);
3559 
3560 		ASSERT3U(db->db_size, >=, drro->drr_bonuslen);
3561 		memcpy(db->db_data, data, DRR_OBJECT_PAYLOAD_SIZE(drro));
3562 
3563 		/*
3564 		 * Raw bonus buffers have their byteorder determined by the
3565 		 * DRR_OBJECT_RANGE record.
3566 		 */
3567 		if (rwa->byteswap && !rwa->raw) {
3568 			dmu_object_byteswap_t byteswap =
3569 			    DMU_OT_BYTESWAP(drro->drr_bonustype);
3570 			dmu_ot_byteswap[byteswap].ob_func(db->db_data,
3571 			    DRR_OBJECT_PAYLOAD_SIZE(drro));
3572 		}
3573 		dmu_buf_rele(db, FTAG);
3574 		dnode_rele(dn, FTAG);
3575 	}
3576 
3577 	/*
3578 	 * If the receive fails, we want the resume stream to start with the
3579 	 * same record that we last successfully received. There is no way to
3580 	 * request resume from the object record, but we can benefit from the
3581 	 * fact that sender always sends object record before anything else,
3582 	 * after which it will "resend" data at offset 0 and resume normally.
3583 	 */
3584 	save_resume_state(rwa, drro->drr_object, 0, tx);
3585 
3586 	dmu_tx_commit(tx);
3587 
3588 	return (0);
3589 }
3590 
3591 noinline static int
receive_freeobjects(struct receive_writer_arg * rwa,struct drr_freeobjects * drrfo)3592 receive_freeobjects(struct receive_writer_arg *rwa,
3593     struct drr_freeobjects *drrfo)
3594 {
3595 	uint64_t obj;
3596 	int next_err = 0;
3597 
3598 	/* Re-validate; stream errors are reported only by the reader. */
3599 	int err = recv_check_drr_freeobjects(drrfo, NULL, 0);
3600 
3601 	if (err != 0)
3602 		return (err);
3603 
3604 	for (obj = drrfo->drr_firstobj == 0 ? 1 : drrfo->drr_firstobj;
3605 	    obj < drrfo->drr_firstobj + drrfo->drr_numobjs &&
3606 	    obj < DN_MAX_OBJECT && next_err == 0;
3607 	    next_err = dmu_object_next(rwa->os, &obj, FALSE, 0)) {
3608 		dmu_object_info_t doi;
3609 		int err;
3610 
3611 		err = dmu_object_info(rwa->os, obj, &doi);
3612 		if (err == ENOENT)
3613 			continue;
3614 		else if (err != 0)
3615 			return (err);
3616 
3617 		err = receive_defer_free_object(rwa, obj);
3618 
3619 		if (err != 0)
3620 			return (err);
3621 
3622 		if (rwa->or_need_sync == ORNS_MAYBE)
3623 			rwa->or_need_sync = ORNS_YES;
3624 	}
3625 	if (next_err != ESRCH)
3626 		return (next_err);
3627 	return (0);
3628 }
3629 
3630 /*
3631  * Note: if this fails, the caller will clean up any records left on the
3632  * rwa->write_batch list.
3633  */
3634 static int
flush_write_batch_impl(struct receive_writer_arg * rwa)3635 flush_write_batch_impl(struct receive_writer_arg *rwa)
3636 {
3637 	dnode_t *dn;
3638 	int err;
3639 
3640 	if (dnode_hold(rwa->os, rwa->last_object, FTAG, &dn) != 0)
3641 		return (SET_ERROR(EINVAL));
3642 
3643 	struct receive_record_arg *last_rrd = list_tail(&rwa->write_batch);
3644 	struct drr_write *last_drrw = &last_rrd->header.drr_u.drr_write;
3645 
3646 	struct receive_record_arg *first_rrd = list_head(&rwa->write_batch);
3647 	struct drr_write *first_drrw = &first_rrd->header.drr_u.drr_write;
3648 
3649 	ASSERT3U(rwa->last_object, ==, last_drrw->drr_object);
3650 	ASSERT3U(rwa->last_offset, ==, last_drrw->drr_offset);
3651 
3652 	if (last_drrw->drr_offset < first_drrw->drr_offset) {
3653 		dnode_rele(dn, FTAG);
3654 		return (SET_ERROR(EINVAL));
3655 	}
3656 
3657 	uint64_t hold_len = last_drrw->drr_offset - first_drrw->drr_offset;
3658 
3659 	/* hold length + last logical size must not overflow uint64_t */
3660 	if (recv_u64_add_overflow(hold_len, last_drrw->drr_logical_size)) {
3661 		dnode_rele(dn, FTAG);
3662 		return (SET_ERROR(EINVAL));
3663 	}
3664 
3665 	dmu_tx_t *tx = dmu_tx_create(rwa->os);
3666 	dmu_tx_hold_write_by_dnode(tx, dn, first_drrw->drr_offset, hold_len +
3667 	    last_drrw->drr_logical_size);
3668 	err = dmu_tx_assign(tx, DMU_TX_WAIT);
3669 	if (err != 0) {
3670 		dmu_tx_abort(tx);
3671 		dnode_rele(dn, FTAG);
3672 		return (err);
3673 	}
3674 
3675 	struct receive_record_arg *rrd;
3676 	while ((rrd = list_head(&rwa->write_batch)) != NULL) {
3677 		struct drr_write *drrw = &rrd->header.drr_u.drr_write;
3678 		abd_t *abd = rrd->abd;
3679 
3680 		ASSERT3U(drrw->drr_object, ==, rwa->last_object);
3681 
3682 		if (drrw->drr_logical_size != dn->dn_datablksz) {
3683 			/*
3684 			 * The WRITE record size does not match the
3685 			 * object's block size.  This happens when the
3686 			 * record is larger than the block size (an
3687 			 * incremental large-block stream received into a
3688 			 * dataset that previously did a non-large-block
3689 			 * receive), and also when it is a smaller trailing
3690 			 * chunk from splitting a large block for a stream
3691 			 * sent without large blocks: a single-block object
3692 			 * can have a non-power-of-2 block size, so its final
3693 			 * SPA_OLD_MAXBLOCKSIZE-sized chunk may be shorter
3694 			 * than the block size.  Either way a lightweight
3695 			 * write is not possible (those must cover exactly
3696 			 * one block), so we decompress the data (if
3697 			 * compressed) and do a normal dmu_write().
3698 			 */
3699 			if (DRR_WRITE_COMPRESSED(drrw)) {
3700 				abd_t *decomp_abd =
3701 				    abd_alloc_linear(drrw->drr_logical_size,
3702 				    B_FALSE);
3703 
3704 				err = zio_decompress_data(
3705 				    drrw->drr_compressiontype,
3706 				    abd, decomp_abd,
3707 				    abd_get_size(abd),
3708 				    abd_get_size(decomp_abd), NULL);
3709 
3710 				if (err == 0) {
3711 					dmu_write_by_dnode(dn,
3712 					    drrw->drr_offset,
3713 					    drrw->drr_logical_size,
3714 					    abd_to_buf(decomp_abd), tx,
3715 					    DMU_READ_NO_PREFETCH |
3716 					    DMU_UNCACHEDIO);
3717 				}
3718 				abd_free(decomp_abd);
3719 			} else {
3720 				dmu_write_by_dnode(dn,
3721 				    drrw->drr_offset,
3722 				    drrw->drr_logical_size,
3723 				    abd_to_buf(abd), tx,
3724 				    DMU_READ_NO_PREFETCH |
3725 				    DMU_UNCACHEDIO);
3726 			}
3727 			if (err == 0)
3728 				abd_free(abd);
3729 		} else {
3730 			zio_prop_t zp = {0};
3731 			dmu_write_policy(rwa->os, dn, 0, 0, &zp);
3732 
3733 			zio_flag_t zio_flags = 0;
3734 
3735 			if (rwa->raw) {
3736 				zp.zp_encrypt = B_TRUE;
3737 				zp.zp_compress = drrw->drr_compressiontype;
3738 				zp.zp_byteorder = ZFS_HOST_BYTEORDER ^
3739 				    !!DRR_IS_RAW_BYTESWAPPED(drrw->drr_flags) ^
3740 				    rwa->byteswap;
3741 				memcpy(zp.zp_salt, drrw->drr_salt,
3742 				    ZIO_DATA_SALT_LEN);
3743 				memcpy(zp.zp_iv, drrw->drr_iv,
3744 				    ZIO_DATA_IV_LEN);
3745 				memcpy(zp.zp_mac, drrw->drr_mac,
3746 				    ZIO_DATA_MAC_LEN);
3747 				if (DMU_OT_IS_ENCRYPTED(zp.zp_type)) {
3748 					zp.zp_nopwrite = B_FALSE;
3749 					zp.zp_copies = MIN(zp.zp_copies,
3750 					    SPA_DVAS_PER_BP - 1);
3751 					zp.zp_gang_copies =
3752 					    MIN(zp.zp_gang_copies,
3753 					    SPA_DVAS_PER_BP - 1);
3754 				}
3755 				zio_flags |= ZIO_FLAG_RAW;
3756 			} else if (DRR_WRITE_COMPRESSED(drrw)) {
3757 				ASSERT3U(drrw->drr_compressed_size, >, 0);
3758 				ASSERT3U(drrw->drr_logical_size, >=,
3759 				    drrw->drr_compressed_size);
3760 				zp.zp_compress = drrw->drr_compressiontype;
3761 				zio_flags |= ZIO_FLAG_RAW_COMPRESS;
3762 			} else if (rwa->byteswap) {
3763 				/*
3764 				 * Note: compressed blocks never need to be
3765 				 * byteswapped, because WRITE records for
3766 				 * metadata blocks are never compressed. The
3767 				 * exception is raw streams, which are written
3768 				 * in the original byteorder, and the byteorder
3769 				 * bit is preserved in the BP by setting
3770 				 * zp_byteorder above.
3771 				 */
3772 				dmu_object_byteswap_t byteswap =
3773 				    DMU_OT_BYTESWAP(drrw->drr_type);
3774 				dmu_ot_byteswap[byteswap].ob_func(
3775 				    abd_to_buf(abd),
3776 				    DRR_WRITE_PAYLOAD_SIZE(drrw));
3777 			}
3778 
3779 			/*
3780 			 * Since this data can't be read until the receive
3781 			 * completes, we can do a "lightweight" write for
3782 			 * improved performance.
3783 			 */
3784 			err = dmu_lightweight_write_by_dnode(dn,
3785 			    drrw->drr_offset, abd, &zp, zio_flags, tx);
3786 		}
3787 
3788 		if (err != 0) {
3789 			/*
3790 			 * This rrd is left on the list, so the caller will
3791 			 * free it (and the abd).
3792 			 */
3793 			break;
3794 		}
3795 
3796 		/*
3797 		 * Note: If the receive fails, we want the resume stream to
3798 		 * start with the same record that we last successfully
3799 		 * received (as opposed to the next record), so that we can
3800 		 * verify that we are resuming from the correct location.
3801 		 */
3802 		save_resume_state(rwa, drrw->drr_object, drrw->drr_offset, tx);
3803 
3804 		list_remove(&rwa->write_batch, rrd);
3805 		kmem_free(rrd, sizeof (*rrd));
3806 	}
3807 
3808 	dmu_tx_commit(tx);
3809 	dnode_rele(dn, FTAG);
3810 	return (err);
3811 }
3812 
3813 noinline static int
flush_write_batch(struct receive_writer_arg * rwa)3814 flush_write_batch(struct receive_writer_arg *rwa)
3815 {
3816 	if (list_is_empty(&rwa->write_batch))
3817 		return (0);
3818 	int err = rwa->err;
3819 	if (err == 0)
3820 		err = flush_write_batch_impl(rwa);
3821 	if (err != 0) {
3822 		struct receive_record_arg *rrd;
3823 		while ((rrd = list_remove_head(&rwa->write_batch)) != NULL) {
3824 			abd_free(rrd->abd);
3825 			kmem_free(rrd, sizeof (*rrd));
3826 		}
3827 	}
3828 	ASSERT(list_is_empty(&rwa->write_batch));
3829 	return (err);
3830 }
3831 
3832 noinline static int
receive_process_write_record(struct receive_writer_arg * rwa,struct receive_record_arg * rrd)3833 receive_process_write_record(struct receive_writer_arg *rwa,
3834     struct receive_record_arg *rrd)
3835 {
3836 	ASSERT3U(rrd->header.drr_type, ==, DRR_WRITE);
3837 	struct drr_write *drrw = &rrd->header.drr_u.drr_write;
3838 
3839 	/* Re-validate; stream errors are reported only by the reader. */
3840 	int err = recv_check_drr_write(drrw, dmu_objset_spa(rwa->os), rwa->raw,
3841 	    rwa->featureflags, NULL, 0);
3842 
3843 	if (err != 0)
3844 		return (err);
3845 
3846 	if (rwa->heal) {
3847 		blkptr_t *bp;
3848 		dmu_buf_t *dbp;
3849 		dmu_flags_t flags = DB_RF_CANFAIL;
3850 
3851 		if (rwa->raw)
3852 			flags |= DMU_READ_NO_DECRYPT;
3853 
3854 		if (rwa->byteswap) {
3855 			dmu_object_byteswap_t byteswap =
3856 			    DMU_OT_BYTESWAP(drrw->drr_type);
3857 			dmu_ot_byteswap[byteswap].ob_func(abd_to_buf(rrd->abd),
3858 			    DRR_WRITE_PAYLOAD_SIZE(drrw));
3859 		}
3860 
3861 		err = dmu_buf_hold_noread(rwa->os, drrw->drr_object,
3862 		    drrw->drr_offset, FTAG, &dbp);
3863 		if (err != 0)
3864 			return (err);
3865 
3866 		/* Try to read the object to see if it needs healing */
3867 		err = dbuf_read((dmu_buf_impl_t *)dbp, NULL, flags);
3868 		/*
3869 		 * We only try to heal when dbuf_read() returns a ECKSUMs.
3870 		 * Other errors (even EIO) get returned to caller.
3871 		 * EIO indicates that the device is not present/accessible,
3872 		 * so writing to it will likely fail.
3873 		 * If the block is healthy, we don't want to overwrite it
3874 		 * unnecessarily.
3875 		 */
3876 		if (err != ECKSUM) {
3877 			dmu_buf_rele(dbp, FTAG);
3878 			return (err);
3879 		}
3880 		/* Make sure the on-disk block and recv record sizes match */
3881 		if (drrw->drr_logical_size != dbp->db_size) {
3882 			err = ENOTSUP;
3883 			dmu_buf_rele(dbp, FTAG);
3884 			return (err);
3885 		}
3886 		/* Get the block pointer for the corrupted block */
3887 		bp = dmu_buf_get_blkptr(dbp);
3888 		err = do_corrective_recv(rwa, drrw, rrd, bp);
3889 		dmu_buf_rele(dbp, FTAG);
3890 		return (err);
3891 	}
3892 
3893 	/*
3894 	 * For resuming to work, records must be in increasing order
3895 	 * by (object, offset).
3896 	 */
3897 	if (drrw->drr_object < rwa->last_object ||
3898 	    (drrw->drr_object == rwa->last_object &&
3899 	    drrw->drr_offset < rwa->last_offset)) {
3900 		return (SET_ERROR(EINVAL));
3901 	}
3902 
3903 	struct receive_record_arg *first_rrd = list_head(&rwa->write_batch);
3904 	struct drr_write *first_drrw = NULL;
3905 	if (first_rrd != NULL)
3906 		first_drrw = &first_rrd->header.drr_u.drr_write;
3907 	uint64_t batch_size =
3908 	    MIN(zfs_recv_write_batch_size, DMU_MAX_ACCESS / 2);
3909 	if (first_rrd != NULL &&
3910 	    (drrw->drr_object != first_drrw->drr_object ||
3911 	    drrw->drr_offset >= first_drrw->drr_offset + batch_size)) {
3912 		err = flush_write_batch(rwa);
3913 		if (err != 0)
3914 			return (err);
3915 	}
3916 
3917 	rwa->last_object = drrw->drr_object;
3918 	rwa->last_offset = drrw->drr_offset;
3919 
3920 	if (rwa->last_object > rwa->max_object)
3921 		rwa->max_object = rwa->last_object;
3922 
3923 	list_insert_tail(&rwa->write_batch, rrd);
3924 	/*
3925 	 * Return EAGAIN to indicate that we will use this rrd again,
3926 	 * so the caller should not free it
3927 	 */
3928 	return (EAGAIN);
3929 }
3930 
3931 static int
receive_write_embedded(struct receive_writer_arg * rwa,struct drr_write_embedded * drrwe,void * data)3932 receive_write_embedded(struct receive_writer_arg *rwa,
3933     struct drr_write_embedded *drrwe, void *data)
3934 {
3935 	dmu_tx_t *tx;
3936 
3937 	/* Re-validate; stream errors are reported only by the reader. */
3938 	int err = recv_check_drr_write_embedded(drrwe, dmu_objset_spa(rwa->os),
3939 	    rwa->raw, rwa->featureflags, NULL, 0);
3940 	if (err != 0)
3941 		return (err);
3942 
3943 	if (drrwe->drr_object > rwa->max_object)
3944 		rwa->max_object = drrwe->drr_object;
3945 
3946 	tx = dmu_tx_create(rwa->os);
3947 
3948 	dmu_tx_hold_write(tx, drrwe->drr_object,
3949 	    drrwe->drr_offset, drrwe->drr_length);
3950 	err = dmu_tx_assign(tx, DMU_TX_WAIT);
3951 	if (err != 0) {
3952 		dmu_tx_abort(tx);
3953 		return (err);
3954 	}
3955 
3956 	dmu_write_embedded(rwa->os, drrwe->drr_object,
3957 	    drrwe->drr_offset, data, drrwe->drr_etype,
3958 	    drrwe->drr_compression, drrwe->drr_lsize, drrwe->drr_psize,
3959 	    rwa->byteswap ^ ZFS_HOST_BYTEORDER, tx);
3960 
3961 	/* See comment in restore_write. */
3962 	save_resume_state(rwa, drrwe->drr_object, drrwe->drr_offset, tx);
3963 	dmu_tx_commit(tx);
3964 	return (0);
3965 }
3966 
3967 static int
receive_spill(struct receive_writer_arg * rwa,struct drr_spill * drrs,abd_t * abd)3968 receive_spill(struct receive_writer_arg *rwa, struct drr_spill *drrs,
3969     abd_t *abd)
3970 {
3971 	dmu_buf_t *db, *db_spill;
3972 
3973 	/* Re-validate; stream errors are reported only by the reader. */
3974 	int err = recv_check_drr_spill(drrs, dmu_objset_spa(rwa->os), rwa->raw,
3975 	    rwa->featureflags, NULL, 0);
3976 	if (err != 0)
3977 		return (err);
3978 
3979 	/*
3980 	 * This is an unmodified spill block which was added to the stream
3981 	 * to resolve an issue with incorrectly removing spill blocks.  It
3982 	 * should be ignored by current versions of the code which support
3983 	 * the DRR_FLAG_SPILL_BLOCK flag.
3984 	 */
3985 	if (rwa->spill && DRR_SPILL_IS_UNMODIFIED(drrs->drr_flags)) {
3986 		abd_free(abd);
3987 		return (0);
3988 	}
3989 
3990 	if (dmu_object_info(rwa->os, drrs->drr_object, NULL) != 0)
3991 		return (SET_ERROR(EINVAL));
3992 
3993 	if (drrs->drr_object > rwa->max_object)
3994 		rwa->max_object = drrs->drr_object;
3995 
3996 	VERIFY0(dmu_bonus_hold(rwa->os, drrs->drr_object, FTAG, &db));
3997 	if ((err = dmu_spill_hold_by_bonus(db, DMU_READ_NO_DECRYPT |
3998 	    DB_RF_CANFAIL, FTAG, &db_spill)) != 0) {
3999 		dmu_buf_rele(db, FTAG);
4000 		return (err);
4001 	}
4002 
4003 	dmu_tx_t *tx = dmu_tx_create(rwa->os);
4004 
4005 	dmu_tx_hold_spill(tx, db->db_object);
4006 
4007 	err = dmu_tx_assign(tx, DMU_TX_WAIT);
4008 	if (err != 0) {
4009 		dmu_buf_rele(db, FTAG);
4010 		dmu_buf_rele(db_spill, FTAG);
4011 		dmu_tx_abort(tx);
4012 		return (err);
4013 	}
4014 
4015 	/*
4016 	 * Spill blocks may both grow and shrink.  When a change in size
4017 	 * occurs any existing dbuf must be updated to match the logical
4018 	 * size of the provided arc_buf_t.
4019 	 */
4020 	if (db_spill->db_size != drrs->drr_length) {
4021 		dmu_buf_will_fill(db_spill, tx, B_FALSE);
4022 		VERIFY0(dbuf_spill_set_blksz(db_spill,
4023 		    drrs->drr_length, tx));
4024 	}
4025 
4026 	arc_buf_t *abuf;
4027 	if (rwa->raw) {
4028 		boolean_t byteorder = ZFS_HOST_BYTEORDER ^
4029 		    !!DRR_IS_RAW_BYTESWAPPED(drrs->drr_flags) ^
4030 		    rwa->byteswap;
4031 
4032 		abuf = arc_loan_raw_buf(dmu_objset_spa(rwa->os),
4033 		    drrs->drr_object, byteorder, drrs->drr_salt,
4034 		    drrs->drr_iv, drrs->drr_mac, drrs->drr_type,
4035 		    drrs->drr_compressed_size, drrs->drr_length,
4036 		    drrs->drr_compressiontype, 0);
4037 	} else {
4038 		abuf = arc_loan_buf(dmu_objset_spa(rwa->os),
4039 		    DMU_OT_IS_METADATA(drrs->drr_type),
4040 		    drrs->drr_length);
4041 		if (rwa->byteswap) {
4042 			dmu_object_byteswap_t byteswap =
4043 			    DMU_OT_BYTESWAP(drrs->drr_type);
4044 			dmu_ot_byteswap[byteswap].ob_func(abd_to_buf(abd),
4045 			    DRR_SPILL_PAYLOAD_SIZE(drrs));
4046 		}
4047 	}
4048 
4049 	memcpy(abuf->b_data, abd_to_buf(abd), DRR_SPILL_PAYLOAD_SIZE(drrs));
4050 	abd_free(abd);
4051 	dbuf_assign_arcbuf((dmu_buf_impl_t *)db_spill, abuf, tx,
4052 	    DMU_UNCACHEDIO);
4053 
4054 	dmu_buf_rele(db, FTAG);
4055 	dmu_buf_rele(db_spill, FTAG);
4056 
4057 	dmu_tx_commit(tx);
4058 	return (0);
4059 }
4060 
4061 noinline static int
receive_free(struct receive_writer_arg * rwa,struct drr_free * drrf)4062 receive_free(struct receive_writer_arg *rwa, struct drr_free *drrf)
4063 {
4064 	/* Re-validate; stream errors are reported only by the reader. */
4065 	int err = recv_check_drr_free(drrf, NULL, 0);
4066 
4067 	if (err != 0)
4068 		return (err);
4069 
4070 	if (dmu_object_info(rwa->os, drrf->drr_object, NULL) != 0)
4071 		return (SET_ERROR(EINVAL));
4072 
4073 	if (drrf->drr_object > rwa->max_object)
4074 		rwa->max_object = drrf->drr_object;
4075 
4076 	err = dmu_free_long_range(rwa->os, drrf->drr_object,
4077 	    drrf->drr_offset, drrf->drr_length);
4078 
4079 	return (err);
4080 }
4081 
4082 static int
receive_object_range(struct receive_writer_arg * rwa,struct drr_object_range * drror)4083 receive_object_range(struct receive_writer_arg *rwa,
4084     struct drr_object_range *drror)
4085 {
4086 	/* Re-validate; stream errors are reported only by the reader. */
4087 	int err = recv_check_drr_object_range(drror, rwa->raw, NULL, 0);
4088 
4089 	if (err != 0)
4090 		return (err);
4091 
4092 	/*
4093 	 * By default, we assume this block is in our native format
4094 	 * (ZFS_HOST_BYTEORDER). We then take into account whether
4095 	 * the send stream is byteswapped (rwa->byteswap). Finally,
4096 	 * we need to byteswap again if this particular block was
4097 	 * in non-native format on the send side.
4098 	 */
4099 	boolean_t byteorder = ZFS_HOST_BYTEORDER ^ rwa->byteswap ^
4100 	    !!DRR_IS_RAW_BYTESWAPPED(drror->drr_flags);
4101 
4102 	/*
4103 	 * Since dnode block sizes are constant, we should not need to worry
4104 	 * about making sure that the dnode block size is the same on the
4105 	 * sending and receiving sides for the time being. For non-raw sends,
4106 	 * this does not matter (and in fact we do not send a DRR_OBJECT_RANGE
4107 	 * record at all). Raw sends require this record type because the
4108 	 * encryption parameters are used to protect an entire block of bonus
4109 	 * buffers. If the size of dnode blocks ever becomes variable,
4110 	 * handling will need to be added to ensure that dnode block sizes
4111 	 * match on the sending and receiving side.
4112 	 */
4113 
4114 	if (drror->drr_firstobj > rwa->max_object)
4115 		rwa->max_object = drror->drr_firstobj;
4116 
4117 	/*
4118 	 * The DRR_OBJECT_RANGE handling must be deferred to receive_object()
4119 	 * so that the block of dnodes is not written out when it's empty,
4120 	 * and converted to a HOLE BP.
4121 	 */
4122 	rwa->or_crypt_params_present = B_TRUE;
4123 	rwa->or_firstobj = drror->drr_firstobj;
4124 	rwa->or_numslots = drror->drr_numslots;
4125 	memcpy(rwa->or_salt, drror->drr_salt, ZIO_DATA_SALT_LEN);
4126 	memcpy(rwa->or_iv, drror->drr_iv, ZIO_DATA_IV_LEN);
4127 	memcpy(rwa->or_mac, drror->drr_mac, ZIO_DATA_MAC_LEN);
4128 	rwa->or_byteorder = byteorder;
4129 
4130 	rwa->or_need_sync = ORNS_MAYBE;
4131 
4132 	return (0);
4133 }
4134 
4135 /*
4136  * Until we have the ability to redact large ranges of data efficiently, we
4137  * process these records as frees.
4138  */
4139 noinline static int
receive_redact(struct receive_writer_arg * rwa,struct drr_redact * drrr)4140 receive_redact(struct receive_writer_arg *rwa, struct drr_redact *drrr)
4141 {
4142 	struct drr_free drrf = {0};
4143 	drrf.drr_length = drrr->drr_length;
4144 	drrf.drr_object = drrr->drr_object;
4145 	drrf.drr_offset = drrr->drr_offset;
4146 	drrf.drr_toguid = drrr->drr_toguid;
4147 	return (receive_free(rwa, &drrf));
4148 }
4149 
4150 /* used to destroy the drc_ds on error */
4151 static void
dmu_recv_cleanup_ds(dmu_recv_cookie_t * drc)4152 dmu_recv_cleanup_ds(dmu_recv_cookie_t *drc)
4153 {
4154 	dsl_dataset_t *ds = drc->drc_ds;
4155 	ds_hold_flags_t dsflags;
4156 
4157 	dsflags = (drc->drc_raw) ? DS_HOLD_FLAG_NONE : DS_HOLD_FLAG_DECRYPT;
4158 	/*
4159 	 * Wait for the txg sync before cleaning up the receive. For
4160 	 * resumable receives, this ensures that our resume state has
4161 	 * been written out to disk. For raw receives, this ensures
4162 	 * that the user accounting code will not attempt to do anything
4163 	 * after we stopped receiving the dataset.
4164 	 */
4165 	txg_wait_synced(ds->ds_dir->dd_pool, 0);
4166 	ds->ds_objset->os_raw_receive = B_FALSE;
4167 
4168 	rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);
4169 	if (drc->drc_resumable && drc->drc_should_save &&
4170 	    !BP_IS_HOLE(dsl_dataset_get_blkptr(ds))) {
4171 		rrw_exit(&ds->ds_bp_rwlock, FTAG);
4172 		dsl_dataset_disown(ds, dsflags, dmu_recv_tag);
4173 	} else {
4174 		char name[ZFS_MAX_DATASET_NAME_LEN];
4175 		rrw_exit(&ds->ds_bp_rwlock, FTAG);
4176 		dsl_dataset_name(ds, name);
4177 		dsl_dataset_disown(ds, dsflags, dmu_recv_tag);
4178 		if (!drc->drc_heal)
4179 			(void) dsl_destroy_head(name);
4180 	}
4181 }
4182 
4183 static void
receive_cksum(dmu_recv_cookie_t * drc,int len,void * buf)4184 receive_cksum(dmu_recv_cookie_t *drc, int len, void *buf)
4185 {
4186 	if (drc->drc_byteswap) {
4187 		(void) fletcher_4_incremental_byteswap(buf, len,
4188 		    &drc->drc_cksum);
4189 	} else {
4190 		(void) fletcher_4_incremental_native(buf, len, &drc->drc_cksum);
4191 	}
4192 }
4193 
4194 /*
4195  * Read the payload into a buffer of size len, and update the current record's
4196  * payload field.
4197  * Allocate drc->drc_next_rrd and read the next record's header into
4198  * drc->drc_next_rrd->header.
4199  * Verify checksum of payload and next record.
4200  */
4201 static int
receive_read_payload_and_next_header(dmu_recv_cookie_t * drc,int len,void * buf)4202 receive_read_payload_and_next_header(dmu_recv_cookie_t *drc, int len, void *buf)
4203 {
4204 	int err;
4205 
4206 	if (len != 0) {
4207 		ASSERT3U(len, <=, SPA_MAXBLOCKSIZE);
4208 		err = receive_read(drc, len, buf);
4209 		if (err != 0)
4210 			return (err);
4211 		receive_cksum(drc, len, buf);
4212 
4213 		/* note: rrd is NULL when reading the begin record's payload */
4214 		if (drc->drc_rrd != NULL) {
4215 			drc->drc_rrd->payload = buf;
4216 			drc->drc_rrd->payload_size = len;
4217 			drc->drc_rrd->bytes_read = drc->drc_bytes_read;
4218 		}
4219 	} else {
4220 		ASSERT0P(buf);
4221 	}
4222 
4223 	drc->drc_prev_cksum = drc->drc_cksum;
4224 
4225 	drc->drc_next_rrd = kmem_zalloc(sizeof (*drc->drc_next_rrd), KM_SLEEP);
4226 	err = receive_read(drc, sizeof (drc->drc_next_rrd->header),
4227 	    &drc->drc_next_rrd->header);
4228 	drc->drc_next_rrd->bytes_read = drc->drc_bytes_read;
4229 
4230 	if (err != 0) {
4231 		kmem_free(drc->drc_next_rrd, sizeof (*drc->drc_next_rrd));
4232 		drc->drc_next_rrd = NULL;
4233 		return (err);
4234 	}
4235 	if (drc->drc_next_rrd->header.drr_type == DRR_BEGIN) {
4236 		kmem_free(drc->drc_next_rrd, sizeof (*drc->drc_next_rrd));
4237 		drc->drc_next_rrd = NULL;
4238 		return (SET_ERROR(EINVAL));
4239 	}
4240 
4241 	/*
4242 	 * Note: checksum is of everything up to but not including the
4243 	 * checksum itself.
4244 	 */
4245 	ASSERT3U(offsetof(dmu_replay_record_t, drr_u.drr_checksum.drr_checksum),
4246 	    ==, sizeof (dmu_replay_record_t) - sizeof (zio_cksum_t));
4247 	receive_cksum(drc,
4248 	    offsetof(dmu_replay_record_t, drr_u.drr_checksum.drr_checksum),
4249 	    &drc->drc_next_rrd->header);
4250 
4251 	zio_cksum_t cksum_orig =
4252 	    drc->drc_next_rrd->header.drr_u.drr_checksum.drr_checksum;
4253 	zio_cksum_t *cksump =
4254 	    &drc->drc_next_rrd->header.drr_u.drr_checksum.drr_checksum;
4255 
4256 	if (drc->drc_byteswap)
4257 		byteswap_record(&drc->drc_next_rrd->header);
4258 
4259 	if ((!ZIO_CHECKSUM_IS_ZERO(cksump)) &&
4260 	    !ZIO_CHECKSUM_EQUAL(drc->drc_cksum, *cksump)) {
4261 		kmem_free(drc->drc_next_rrd, sizeof (*drc->drc_next_rrd));
4262 		drc->drc_next_rrd = NULL;
4263 		return (SET_ERROR(ECKSUM));
4264 	}
4265 
4266 	receive_cksum(drc, sizeof (cksum_orig), &cksum_orig);
4267 
4268 	return (0);
4269 }
4270 
4271 /*
4272  * Issue the prefetch reads for any necessary indirect blocks.
4273  *
4274  * We use the object ignore list to tell us whether or not to issue prefetches
4275  * for a given object.  We do this for both correctness (in case the blocksize
4276  * of an object has changed) and performance (if the object doesn't exist, don't
4277  * needlessly try to issue prefetches).  We also trim the list as we go through
4278  * the stream to prevent it from growing to an unbounded size.
4279  *
4280  * The object numbers within will always be in sorted order, and any write
4281  * records we see will also be in sorted order, but they're not sorted with
4282  * respect to each other (i.e. we can get several object records before
4283  * receiving each object's write records).  As a result, once we've reached a
4284  * given object number, we can safely remove any reference to lower object
4285  * numbers in the ignore list. In practice, we receive up to 32 object records
4286  * before receiving write records, so the list can have up to 32 nodes in it.
4287  */
4288 static void
receive_read_prefetch(dmu_recv_cookie_t * drc,uint64_t object,uint64_t offset,uint64_t length)4289 receive_read_prefetch(dmu_recv_cookie_t *drc, uint64_t object, uint64_t offset,
4290     uint64_t length)
4291 {
4292 	if (!objlist_exists(drc->drc_ignore_objlist, object)) {
4293 		dmu_prefetch(drc->drc_os, object, 1, offset, length,
4294 		    ZIO_PRIORITY_SYNC_READ);
4295 	}
4296 }
4297 
4298 /*
4299  * Read records off the stream, issuing any necessary prefetches.
4300  */
4301 static int
receive_read_record(dmu_recv_cookie_t * drc)4302 receive_read_record(dmu_recv_cookie_t *drc)
4303 {
4304 	char errbuf[RECV_CHECK_ERRBUFLEN];
4305 
4306 	switch (drc->drc_rrd->header.drr_type) {
4307 	case DRR_OBJECT:
4308 	{
4309 		struct drr_object *drro =
4310 		    &drc->drc_rrd->header.drr_u.drr_object;
4311 		uint32_t size;
4312 		void *buf = NULL;
4313 		dmu_object_info_t doi;
4314 
4315 		/* Reject malformed DRR_OBJECT before reading bonus payload. */
4316 		int err = recv_check_drr_object(drro, drc->drc_os->os_spa,
4317 		    drc->drc_raw, drc->drc_spill, drc->drc_featureflags,
4318 		    errbuf, sizeof (errbuf));
4319 
4320 		if (err != 0) {
4321 			recv_report_stream_error(drc->drc_errors, errbuf);
4322 			return (err);
4323 		}
4324 
4325 		size = DRR_OBJECT_PAYLOAD_SIZE(drro);
4326 
4327 		if (size != 0)
4328 			buf = vmem_zalloc(size, KM_SLEEP);
4329 
4330 		err = receive_read_payload_and_next_header(drc, size, buf);
4331 		if (err != 0) {
4332 			vmem_free(buf, size);
4333 			return (err);
4334 		}
4335 		err = dmu_object_info(drc->drc_os, drro->drr_object, &doi);
4336 		/*
4337 		 * See receive_read_prefetch for an explanation why we're
4338 		 * storing this object in the ignore_obj_list.
4339 		 */
4340 		if (err == ENOENT || err == EEXIST ||
4341 		    (err == 0 && doi.doi_data_block_size != drro->drr_blksz)) {
4342 			objlist_insert(drc->drc_ignore_objlist,
4343 			    drro->drr_object);
4344 			err = 0;
4345 		}
4346 		return (err);
4347 	}
4348 	case DRR_FREEOBJECTS:
4349 	{
4350 		struct drr_freeobjects *drrfo =
4351 		    &drc->drc_rrd->header.drr_u.drr_freeobjects;
4352 
4353 		/* Reject malformed DRR_FREEOBJECTS before advancing stream. */
4354 		int err = recv_check_drr_freeobjects(drrfo, errbuf,
4355 		    sizeof (errbuf));
4356 
4357 		if (err != 0) {
4358 			recv_report_stream_error(drc->drc_errors, errbuf);
4359 			return (err);
4360 		}
4361 
4362 		err = receive_read_payload_and_next_header(drc, 0, NULL);
4363 		return (err);
4364 	}
4365 	case DRR_WRITE:
4366 	{
4367 		struct drr_write *drrw = &drc->drc_rrd->header.drr_u.drr_write;
4368 
4369 		/* Reject malformed DRR_WRITE before reading payload. */
4370 		int err = recv_check_drr_write(drrw, drc->drc_os->os_spa,
4371 		    drc->drc_raw, drc->drc_featureflags, errbuf,
4372 		    sizeof (errbuf));
4373 
4374 		if (err != 0) {
4375 			recv_report_stream_error(drc->drc_errors, errbuf);
4376 			return (err);
4377 		}
4378 
4379 		uint64_t size = DRR_WRITE_PAYLOAD_SIZE(drrw);
4380 
4381 		abd_t *abd = abd_alloc_linear(size, B_FALSE);
4382 		err = receive_read_payload_and_next_header(drc, size,
4383 		    abd_to_buf(abd));
4384 		if (err != 0) {
4385 			abd_free(abd);
4386 			return (err);
4387 		}
4388 		drc->drc_rrd->abd = abd;
4389 		receive_read_prefetch(drc, drrw->drr_object, drrw->drr_offset,
4390 		    drrw->drr_logical_size);
4391 		return (err);
4392 	}
4393 	case DRR_WRITE_EMBEDDED:
4394 	{
4395 		struct drr_write_embedded *drrwe =
4396 		    &drc->drc_rrd->header.drr_u.drr_write_embedded;
4397 
4398 		/* Reject malformed DRR_WRITE_EMBEDDED before reading. */
4399 		int err = recv_check_drr_write_embedded(drrwe,
4400 		    drc->drc_os->os_spa, drc->drc_raw, drc->drc_featureflags,
4401 		    errbuf, sizeof (errbuf));
4402 
4403 		if (err != 0) {
4404 			recv_report_stream_error(drc->drc_errors, errbuf);
4405 			return (err);
4406 		}
4407 
4408 		uint32_t size = P2ROUNDUP(drrwe->drr_psize, 8);
4409 
4410 		void *buf = vmem_zalloc(size, KM_SLEEP);
4411 
4412 		err = receive_read_payload_and_next_header(drc, size, buf);
4413 		if (err != 0) {
4414 			vmem_free(buf, size);
4415 			return (err);
4416 		}
4417 
4418 		receive_read_prefetch(drc, drrwe->drr_object, drrwe->drr_offset,
4419 		    drrwe->drr_length);
4420 		return (err);
4421 	}
4422 	case DRR_FREE:
4423 	case DRR_REDACT:
4424 	{
4425 		struct drr_free *drrf = &drc->drc_rrd->header.drr_u.drr_free;
4426 
4427 		/* Reject malformed DRR_FREE before advancing stream. */
4428 		int err = recv_check_drr_free(drrf, errbuf, sizeof (errbuf));
4429 
4430 		if (err != 0) {
4431 			recv_report_stream_error(drc->drc_errors, errbuf);
4432 			return (err);
4433 		}
4434 
4435 		/*
4436 		 * It might be beneficial to prefetch indirect blocks here, but
4437 		 * we don't really have the data to decide for sure.
4438 		 */
4439 		err = receive_read_payload_and_next_header(drc, 0, NULL);
4440 		return (err);
4441 	}
4442 	case DRR_END:
4443 	{
4444 		struct drr_end *drre = &drc->drc_rrd->header.drr_u.drr_end;
4445 		if (!ZIO_CHECKSUM_EQUAL(drc->drc_prev_cksum,
4446 		    drre->drr_checksum))
4447 			return (SET_ERROR(ECKSUM));
4448 		return (0);
4449 	}
4450 	case DRR_SPILL:
4451 	{
4452 		struct drr_spill *drrs = &drc->drc_rrd->header.drr_u.drr_spill;
4453 
4454 		/* Reject malformed DRR_SPILL before reading payload. */
4455 		int err = recv_check_drr_spill(drrs, drc->drc_os->os_spa,
4456 		    drc->drc_raw, drc->drc_featureflags, errbuf,
4457 		    sizeof (errbuf));
4458 
4459 		if (err != 0) {
4460 			recv_report_stream_error(drc->drc_errors, errbuf);
4461 			return (err);
4462 		}
4463 
4464 		uint64_t size = DRR_SPILL_PAYLOAD_SIZE(drrs);
4465 
4466 		abd_t *abd = abd_alloc_linear(size, B_FALSE);
4467 		err = receive_read_payload_and_next_header(drc, size,
4468 		    abd_to_buf(abd));
4469 		if (err != 0)
4470 			abd_free(abd);
4471 		else
4472 			drc->drc_rrd->abd = abd;
4473 		return (err);
4474 	}
4475 	case DRR_OBJECT_RANGE:
4476 	{
4477 		struct drr_object_range *drror =
4478 		    &drc->drc_rrd->header.drr_u.drr_object_range;
4479 
4480 		/* Reject malformed DRR_OBJECT_RANGE before advancing. */
4481 		int err = recv_check_drr_object_range(drror, drc->drc_raw,
4482 		    errbuf, sizeof (errbuf));
4483 
4484 		if (err != 0) {
4485 			recv_report_stream_error(drc->drc_errors, errbuf);
4486 			return (err);
4487 		}
4488 
4489 		err = receive_read_payload_and_next_header(drc, 0, NULL);
4490 		return (err);
4491 
4492 	}
4493 	default:
4494 		return (SET_ERROR(EINVAL));
4495 	}
4496 }
4497 
4498 
4499 
4500 static void
dprintf_drr(struct receive_record_arg * rrd,int err)4501 dprintf_drr(struct receive_record_arg *rrd, int err)
4502 {
4503 #ifdef ZFS_DEBUG
4504 	switch (rrd->header.drr_type) {
4505 	case DRR_OBJECT:
4506 	{
4507 		struct drr_object *drro = &rrd->header.drr_u.drr_object;
4508 		dprintf("drr_type = OBJECT obj = %llu type = %u "
4509 		    "bonustype = %u blksz = %u bonuslen = %u cksumtype = %u "
4510 		    "compress = %u dn_slots = %u err = %d\n",
4511 		    (u_longlong_t)drro->drr_object, drro->drr_type,
4512 		    drro->drr_bonustype, drro->drr_blksz, drro->drr_bonuslen,
4513 		    drro->drr_checksumtype, drro->drr_compress,
4514 		    drro->drr_dn_slots, err);
4515 		break;
4516 	}
4517 	case DRR_FREEOBJECTS:
4518 	{
4519 		struct drr_freeobjects *drrfo =
4520 		    &rrd->header.drr_u.drr_freeobjects;
4521 		dprintf("drr_type = FREEOBJECTS firstobj = %llu "
4522 		    "numobjs = %llu err = %d\n",
4523 		    (u_longlong_t)drrfo->drr_firstobj,
4524 		    (u_longlong_t)drrfo->drr_numobjs, err);
4525 		break;
4526 	}
4527 	case DRR_WRITE:
4528 	{
4529 		struct drr_write *drrw = &rrd->header.drr_u.drr_write;
4530 		dprintf("drr_type = WRITE obj = %llu type = %u offset = %llu "
4531 		    "lsize = %llu cksumtype = %u flags = %u "
4532 		    "compress = %u psize = %llu err = %d\n",
4533 		    (u_longlong_t)drrw->drr_object, drrw->drr_type,
4534 		    (u_longlong_t)drrw->drr_offset,
4535 		    (u_longlong_t)drrw->drr_logical_size,
4536 		    drrw->drr_checksumtype, drrw->drr_flags,
4537 		    drrw->drr_compressiontype,
4538 		    (u_longlong_t)drrw->drr_compressed_size, err);
4539 		break;
4540 	}
4541 	case DRR_WRITE_BYREF:
4542 	{
4543 		struct drr_write_byref *drrwbr =
4544 		    &rrd->header.drr_u.drr_write_byref;
4545 		dprintf("drr_type = WRITE_BYREF obj = %llu offset = %llu "
4546 		    "length = %llu toguid = %llx refguid = %llx "
4547 		    "refobject = %llu refoffset = %llu cksumtype = %u "
4548 		    "flags = %u err = %d\n",
4549 		    (u_longlong_t)drrwbr->drr_object,
4550 		    (u_longlong_t)drrwbr->drr_offset,
4551 		    (u_longlong_t)drrwbr->drr_length,
4552 		    (u_longlong_t)drrwbr->drr_toguid,
4553 		    (u_longlong_t)drrwbr->drr_refguid,
4554 		    (u_longlong_t)drrwbr->drr_refobject,
4555 		    (u_longlong_t)drrwbr->drr_refoffset,
4556 		    drrwbr->drr_checksumtype, drrwbr->drr_flags, err);
4557 		break;
4558 	}
4559 	case DRR_WRITE_EMBEDDED:
4560 	{
4561 		struct drr_write_embedded *drrwe =
4562 		    &rrd->header.drr_u.drr_write_embedded;
4563 		dprintf("drr_type = WRITE_EMBEDDED obj = %llu offset = %llu "
4564 		    "length = %llu compress = %u etype = %u lsize = %u "
4565 		    "psize = %u err = %d\n",
4566 		    (u_longlong_t)drrwe->drr_object,
4567 		    (u_longlong_t)drrwe->drr_offset,
4568 		    (u_longlong_t)drrwe->drr_length,
4569 		    drrwe->drr_compression, drrwe->drr_etype,
4570 		    drrwe->drr_lsize, drrwe->drr_psize, err);
4571 		break;
4572 	}
4573 	case DRR_FREE:
4574 	{
4575 		struct drr_free *drrf = &rrd->header.drr_u.drr_free;
4576 		dprintf("drr_type = FREE obj = %llu offset = %llu "
4577 		    "length = %lld err = %d\n",
4578 		    (u_longlong_t)drrf->drr_object,
4579 		    (u_longlong_t)drrf->drr_offset,
4580 		    (longlong_t)drrf->drr_length,
4581 		    err);
4582 		break;
4583 	}
4584 	case DRR_SPILL:
4585 	{
4586 		struct drr_spill *drrs = &rrd->header.drr_u.drr_spill;
4587 		dprintf("drr_type = SPILL obj = %llu length = %llu "
4588 		    "err = %d\n", (u_longlong_t)drrs->drr_object,
4589 		    (u_longlong_t)drrs->drr_length, err);
4590 		break;
4591 	}
4592 	case DRR_OBJECT_RANGE:
4593 	{
4594 		struct drr_object_range *drror =
4595 		    &rrd->header.drr_u.drr_object_range;
4596 		dprintf("drr_type = OBJECT_RANGE firstobj = %llu "
4597 		    "numslots = %llu flags = %u err = %d\n",
4598 		    (u_longlong_t)drror->drr_firstobj,
4599 		    (u_longlong_t)drror->drr_numslots,
4600 		    drror->drr_flags, err);
4601 		break;
4602 	}
4603 	default:
4604 		return;
4605 	}
4606 #endif
4607 }
4608 
4609 /*
4610  * Commit the records to the pool.
4611  */
4612 static int
receive_process_record(struct receive_writer_arg * rwa,struct receive_record_arg * rrd)4613 receive_process_record(struct receive_writer_arg *rwa,
4614     struct receive_record_arg *rrd)
4615 {
4616 	int err;
4617 
4618 	/*
4619 	 * Processing in order, therefore bytes_read should be increasing.
4620 	 * Replayed records are earlier in the stream than the writer's
4621 	 * current position, so leave the high-water mark alone for them.
4622 	 */
4623 	if (!rwa->defer_replaying) {
4624 		ASSERT3U(rrd->bytes_read, >=, rwa->bytes_read);
4625 		rwa->bytes_read = rrd->bytes_read;
4626 	}
4627 
4628 	/* We can only heal write records; other ones get ignored */
4629 	if (rwa->heal && rrd->header.drr_type != DRR_WRITE) {
4630 		if (rrd->abd != NULL) {
4631 			abd_free(rrd->abd);
4632 			rrd->abd = NULL;
4633 		} else if (rrd->payload != NULL) {
4634 			vmem_free(rrd->payload, rrd->payload_size);
4635 			rrd->payload = NULL;
4636 		}
4637 		return (0);
4638 	}
4639 
4640 	/*
4641 	 * Records that depend on a deferred object claim are parked in
4642 	 * stream order behind it; everything else keeps flowing.
4643 	 */
4644 	if (!rwa->heal && !rwa->defer_replaying && receive_defer_active(rwa)) {
4645 		err = receive_defer_check(rwa, rrd);
4646 		if (err != 0)
4647 			return (err);
4648 	}
4649 
4650 	if (!rwa->heal && rrd->header.drr_type != DRR_WRITE) {
4651 		err = flush_write_batch(rwa);
4652 		if (err != 0) {
4653 			if (rrd->abd != NULL) {
4654 				abd_free(rrd->abd);
4655 				rrd->abd = NULL;
4656 				rrd->payload = NULL;
4657 			} else if (rrd->payload != NULL) {
4658 				vmem_free(rrd->payload, rrd->payload_size);
4659 				rrd->payload = NULL;
4660 			}
4661 
4662 			return (err);
4663 		}
4664 	}
4665 
4666 	switch (rrd->header.drr_type) {
4667 	case DRR_OBJECT:
4668 	{
4669 		struct drr_object *drro = &rrd->header.drr_u.drr_object;
4670 		err = receive_object(rwa, drro, rrd->payload);
4671 		if (err == EAGAIN) {
4672 			/*
4673 			 * The object's claim was deferred behind a batched
4674 			 * txg sync; keep the record (and its bonus payload)
4675 			 * parked for replay.  The park may flush and free
4676 			 * the record, so it must not be touched again.
4677 			 */
4678 			receive_defer_park(rwa, rrd, drro->drr_object);
4679 			return (EAGAIN);
4680 		}
4681 		vmem_free(rrd->payload, rrd->payload_size);
4682 		rrd->payload = NULL;
4683 		break;
4684 	}
4685 	case DRR_FREEOBJECTS:
4686 	{
4687 		struct drr_freeobjects *drrfo =
4688 		    &rrd->header.drr_u.drr_freeobjects;
4689 		err = receive_freeobjects(rwa, drrfo);
4690 		break;
4691 	}
4692 	case DRR_WRITE:
4693 	{
4694 		err = receive_process_write_record(rwa, rrd);
4695 		if (rwa->heal) {
4696 			/*
4697 			 * If healing - always free the abd after processing
4698 			 */
4699 			abd_free(rrd->abd);
4700 			rrd->abd = NULL;
4701 		} else if (err != EAGAIN) {
4702 			/*
4703 			 * On success, a non-healing
4704 			 * receive_process_write_record() returns
4705 			 * EAGAIN to indicate that we do not want to free
4706 			 * the rrd or arc_buf.
4707 			 */
4708 			ASSERT(err != 0);
4709 			abd_free(rrd->abd);
4710 			rrd->abd = NULL;
4711 		}
4712 		break;
4713 	}
4714 	case DRR_WRITE_EMBEDDED:
4715 	{
4716 		struct drr_write_embedded *drrwe =
4717 		    &rrd->header.drr_u.drr_write_embedded;
4718 		err = receive_write_embedded(rwa, drrwe, rrd->payload);
4719 		vmem_free(rrd->payload, rrd->payload_size);
4720 		rrd->payload = NULL;
4721 		break;
4722 	}
4723 	case DRR_FREE:
4724 	{
4725 		struct drr_free *drrf = &rrd->header.drr_u.drr_free;
4726 		err = receive_free(rwa, drrf);
4727 		break;
4728 	}
4729 	case DRR_SPILL:
4730 	{
4731 		struct drr_spill *drrs = &rrd->header.drr_u.drr_spill;
4732 		err = receive_spill(rwa, drrs, rrd->abd);
4733 		if (err != 0)
4734 			abd_free(rrd->abd);
4735 		rrd->abd = NULL;
4736 		rrd->payload = NULL;
4737 		break;
4738 	}
4739 	case DRR_OBJECT_RANGE:
4740 	{
4741 		struct drr_object_range *drror =
4742 		    &rrd->header.drr_u.drr_object_range;
4743 		err = receive_object_range(rwa, drror);
4744 		break;
4745 	}
4746 	case DRR_REDACT:
4747 	{
4748 		struct drr_redact *drrr = &rrd->header.drr_u.drr_redact;
4749 		err = receive_redact(rwa, drrr);
4750 		break;
4751 	}
4752 	default:
4753 		err = (SET_ERROR(EINVAL));
4754 	}
4755 
4756 	if (err != 0)
4757 		dprintf_drr(rrd, err);
4758 
4759 	return (err);
4760 }
4761 
4762 /*
4763  * dmu_recv_stream's worker thread; pull records off the queue, and then call
4764  * receive_process_record  When we're done, signal the main thread and exit.
4765  */
4766 static __attribute__((noreturn)) void
receive_writer_thread(void * arg)4767 receive_writer_thread(void *arg)
4768 {
4769 	struct receive_writer_arg *rwa = arg;
4770 	struct receive_record_arg *rrd;
4771 	fstrans_cookie_t cookie = spl_fstrans_mark();
4772 
4773 	for (rrd = bqueue_dequeue(&rwa->q); !rrd->eos_marker;
4774 	    rrd = bqueue_dequeue(&rwa->q)) {
4775 		/*
4776 		 * If there's an error, the main thread will stop putting things
4777 		 * on the queue, but we need to clear everything in it before we
4778 		 * can exit.
4779 		 */
4780 		int err = 0;
4781 		if (rwa->err == 0) {
4782 			err = receive_process_record(rwa, rrd);
4783 		} else if (rrd->abd != NULL) {
4784 			abd_free(rrd->abd);
4785 			rrd->abd = NULL;
4786 			rrd->payload = NULL;
4787 		} else if (rrd->payload != NULL) {
4788 			vmem_free(rrd->payload, rrd->payload_size);
4789 			rrd->payload = NULL;
4790 		}
4791 		/*
4792 		 * EAGAIN indicates that ownership of this record has
4793 		 * moved: it was either saved on rwa->write_batch, or
4794 		 * parked on the defer list to be replayed and freed by
4795 		 * the defer flush (or by the defer cleanup on error).
4796 		 * Either way we don't free it here.
4797 		 * When healing data we always need to free the record.
4798 		 */
4799 		if (err != EAGAIN || rwa->heal) {
4800 			if (rwa->err == 0)
4801 				rwa->err = err;
4802 			kmem_free(rrd, sizeof (*rrd));
4803 		}
4804 	}
4805 	kmem_free(rrd, sizeof (*rrd));
4806 
4807 	if (rwa->heal) {
4808 		zio_wait(rwa->heal_pio);
4809 	} else {
4810 		int err = 0;
4811 		if (rwa->err == 0)
4812 			err = receive_defer_flush(rwa);
4813 		if (rwa->err == 0)
4814 			rwa->err = err;
4815 		err = flush_write_batch(rwa);
4816 		if (rwa->err == 0)
4817 			rwa->err = err;
4818 	}
4819 	receive_defer_cleanup(rwa);
4820 	mutex_enter(&rwa->mutex);
4821 	rwa->done = B_TRUE;
4822 	cv_signal(&rwa->cv);
4823 	mutex_exit(&rwa->mutex);
4824 	spl_fstrans_unmark(cookie);
4825 	thread_exit();
4826 }
4827 
4828 static int
resume_check(dmu_recv_cookie_t * drc,nvlist_t * begin_nvl)4829 resume_check(dmu_recv_cookie_t *drc, nvlist_t *begin_nvl)
4830 {
4831 	uint64_t val;
4832 	objset_t *mos = dmu_objset_pool(drc->drc_os)->dp_meta_objset;
4833 	uint64_t dsobj = dmu_objset_id(drc->drc_os);
4834 	uint64_t resume_obj, resume_off;
4835 
4836 	if (nvlist_lookup_uint64(begin_nvl,
4837 	    "resume_object", &resume_obj) != 0 ||
4838 	    nvlist_lookup_uint64(begin_nvl,
4839 	    "resume_offset", &resume_off) != 0) {
4840 		return (SET_ERROR(EINVAL));
4841 	}
4842 	VERIFY0(zap_lookup(mos, dsobj,
4843 	    DS_FIELD_RESUME_OBJECT, sizeof (val), 1, &val));
4844 	if (resume_obj != val)
4845 		return (SET_ERROR(EINVAL));
4846 	VERIFY0(zap_lookup(mos, dsobj,
4847 	    DS_FIELD_RESUME_OFFSET, sizeof (val), 1, &val));
4848 	if (resume_off != val)
4849 		return (SET_ERROR(EINVAL));
4850 
4851 	return (0);
4852 }
4853 
4854 /*
4855  * Read in the stream's records, one by one, and apply them to the pool.  There
4856  * are two threads involved; the thread that calls this function will spin up a
4857  * worker thread, read the records off the stream one by one, and issue
4858  * prefetches for any necessary indirect blocks.  It will then push the records
4859  * onto an internal blocking queue.  The worker thread will pull the records off
4860  * the queue, and actually write the data into the DMU.  This way, the worker
4861  * thread doesn't have to wait for reads to complete, since everything it needs
4862  * (the indirect blocks) will be prefetched.
4863  *
4864  * NB: callers *must* call dmu_recv_end() if this succeeds.
4865  */
4866 int
dmu_recv_stream(dmu_recv_cookie_t * drc,offset_t * voffp)4867 dmu_recv_stream(dmu_recv_cookie_t *drc, offset_t *voffp)
4868 {
4869 	int err = 0;
4870 	struct receive_writer_arg *rwa = kmem_zalloc(sizeof (*rwa), KM_SLEEP);
4871 
4872 	if (dsl_dataset_has_resume_receive_state(drc->drc_ds)) {
4873 		uint64_t bytes = 0;
4874 		(void) zap_lookup(drc->drc_ds->ds_dir->dd_pool->dp_meta_objset,
4875 		    drc->drc_ds->ds_object, DS_FIELD_RESUME_BYTES,
4876 		    sizeof (bytes), 1, &bytes);
4877 		drc->drc_bytes_read += bytes;
4878 	}
4879 
4880 	drc->drc_ignore_objlist = objlist_create();
4881 
4882 	/* these were verified in dmu_recv_begin */
4883 	ASSERT3U(DMU_GET_STREAM_HDRTYPE(drc->drc_drrb->drr_versioninfo), ==,
4884 	    DMU_SUBSTREAM);
4885 	ASSERT3U(drc->drc_drrb->drr_type, <, DMU_OST_NUMTYPES);
4886 
4887 	ASSERT(dsl_dataset_phys(drc->drc_ds)->ds_flags & DS_FLAG_INCONSISTENT);
4888 	ASSERT0(drc->drc_os->os_encrypted &&
4889 	    (drc->drc_featureflags & DMU_BACKUP_FEATURE_EMBED_DATA));
4890 
4891 	/* handle DSL encryption key payload */
4892 	if (drc->drc_featureflags & DMU_BACKUP_FEATURE_RAW) {
4893 		nvlist_t *keynvl = NULL;
4894 
4895 		ASSERT(drc->drc_os->os_encrypted);
4896 		ASSERT(drc->drc_raw);
4897 
4898 		err = nvlist_lookup_nvlist(drc->drc_begin_nvl, "crypt_keydata",
4899 		    &keynvl);
4900 		if (err != 0)
4901 			goto out;
4902 
4903 		if (!drc->drc_heal) {
4904 			/*
4905 			 * If this is a new dataset we set the key immediately.
4906 			 * Otherwise we don't want to change the key until we
4907 			 * are sure the rest of the receive succeeded so we
4908 			 * stash the keynvl away until then.
4909 			 */
4910 			err = dsl_crypto_recv_raw(spa_name(drc->drc_os->os_spa),
4911 			    drc->drc_ds->ds_object, drc->drc_fromsnapobj,
4912 			    drc->drc_drrb->drr_type, keynvl, drc->drc_newfs);
4913 			if (err != 0)
4914 				goto out;
4915 		}
4916 
4917 		/* see comment in dmu_recv_end_sync() */
4918 		drc->drc_ivset_guid = 0;
4919 		(void) nvlist_lookup_uint64(keynvl, "to_ivset_guid",
4920 		    &drc->drc_ivset_guid);
4921 
4922 		if (!drc->drc_newfs)
4923 			drc->drc_keynvl = fnvlist_dup(keynvl);
4924 	}
4925 
4926 	if (drc->drc_featureflags & DMU_BACKUP_FEATURE_RESUMING) {
4927 		err = resume_check(drc, drc->drc_begin_nvl);
4928 		if (err != 0)
4929 			goto out;
4930 	}
4931 
4932 	/*
4933 	 * For compatibility with recursive send streams, we do this here,
4934 	 * rather than in dmu_recv_begin. If we pull the next header too
4935 	 * early, and it's the END record, we break the `recv_skip` logic.
4936 	 */
4937 	if (drc->drc_drr_begin->drr_payloadlen == 0) {
4938 		err = receive_read_payload_and_next_header(drc, 0, NULL);
4939 		if (err != 0)
4940 			goto out;
4941 	}
4942 
4943 	/*
4944 	 * If we failed before this point we will clean up any new resume
4945 	 * state that was created. Now that we've gotten past the initial
4946 	 * checks we are ok to retain that resume state.
4947 	 */
4948 	drc->drc_should_save = B_TRUE;
4949 
4950 	(void) bqueue_init(&rwa->q, zfs_recv_queue_ff,
4951 	    MAX(zfs_recv_queue_length, 2 * zfs_max_recordsize),
4952 	    offsetof(struct receive_record_arg, node));
4953 	cv_init(&rwa->cv, NULL, CV_DEFAULT, NULL);
4954 	mutex_init(&rwa->mutex, NULL, MUTEX_DEFAULT, NULL);
4955 	rwa->os = drc->drc_os;
4956 	rwa->byteswap = drc->drc_byteswap;
4957 	rwa->heal = drc->drc_heal;
4958 	rwa->tofs = drc->drc_tofs;
4959 	rwa->resumable = drc->drc_resumable;
4960 	rwa->raw = drc->drc_raw;
4961 	rwa->spill = drc->drc_spill;
4962 	rwa->featureflags = drc->drc_featureflags;
4963 	rwa->full = (drc->drc_drr_begin->drr_u.drr_begin.drr_fromguid == 0);
4964 	rwa->os->os_raw_receive = drc->drc_raw;
4965 	if (drc->drc_heal) {
4966 		rwa->heal_pio = zio_root(drc->drc_os->os_spa, NULL, NULL,
4967 		    ZIO_FLAG_GODFATHER);
4968 	}
4969 	list_create(&rwa->write_batch, sizeof (struct receive_record_arg),
4970 	    offsetof(struct receive_record_arg, node.bqn_node));
4971 	list_create(&rwa->defer_records, sizeof (struct receive_record_arg),
4972 	    offsetof(struct receive_record_arg, node.bqn_node));
4973 	avl_create(&rwa->defer_ranges, receive_defer_range_compare,
4974 	    sizeof (receive_defer_range_t),
4975 	    offsetof(receive_defer_range_t, rdr_node));
4976 
4977 	(void) thread_create(NULL, 0, receive_writer_thread, rwa, 0, curproc,
4978 	    TS_RUN, minclsyspri);
4979 	/*
4980 	 * We're reading rwa->err without locks, which is safe since we are the
4981 	 * only reader, and the worker thread is the only writer.  It's ok if we
4982 	 * miss a write for an iteration or two of the loop, since the writer
4983 	 * thread will keep freeing records we send it until we send it an eos
4984 	 * marker.
4985 	 *
4986 	 * We can leave this loop in 3 ways:  First, if rwa->err is
4987 	 * non-zero.  In that case, the writer thread will free the rrd we just
4988 	 * pushed.  Second, if  we're interrupted; in that case, either it's the
4989 	 * first loop and drc->drc_rrd was never allocated, or it's later, and
4990 	 * drc->drc_rrd has been handed off to the writer thread who will free
4991 	 * it.  Finally, if receive_read_record fails or we're at the end of the
4992 	 * stream, then we free drc->drc_rrd and exit.
4993 	 */
4994 	while (rwa->err == 0) {
4995 		if (issig()) {
4996 			err = SET_ERROR(EINTR);
4997 			break;
4998 		}
4999 
5000 		ASSERT0P(drc->drc_rrd);
5001 		drc->drc_rrd = drc->drc_next_rrd;
5002 		drc->drc_next_rrd = NULL;
5003 		/* Allocates and loads header into drc->drc_next_rrd */
5004 		err = receive_read_record(drc);
5005 
5006 		if (drc->drc_rrd->header.drr_type == DRR_END || err != 0) {
5007 			kmem_free(drc->drc_rrd, sizeof (*drc->drc_rrd));
5008 			drc->drc_rrd = NULL;
5009 			break;
5010 		}
5011 
5012 		bqueue_enqueue(&rwa->q, drc->drc_rrd,
5013 		    sizeof (struct receive_record_arg) +
5014 		    drc->drc_rrd->payload_size);
5015 		drc->drc_rrd = NULL;
5016 	}
5017 
5018 	ASSERT0P(drc->drc_rrd);
5019 	drc->drc_rrd = kmem_zalloc(sizeof (*drc->drc_rrd), KM_SLEEP);
5020 	drc->drc_rrd->eos_marker = B_TRUE;
5021 	bqueue_enqueue_flush(&rwa->q, drc->drc_rrd, 1);
5022 
5023 	mutex_enter(&rwa->mutex);
5024 	while (!rwa->done) {
5025 		/*
5026 		 * We need to use cv_wait_sig() so that any process that may
5027 		 * be sleeping here can still fork.
5028 		 */
5029 		(void) cv_wait_sig(&rwa->cv, &rwa->mutex);
5030 	}
5031 	mutex_exit(&rwa->mutex);
5032 
5033 	/*
5034 	 * If we are receiving a full stream as a clone, all object IDs which
5035 	 * are greater than the maximum ID referenced in the stream are
5036 	 * by definition unused and must be freed.
5037 	 */
5038 	if (drc->drc_clone && drc->drc_drrb->drr_fromguid == 0) {
5039 		uint64_t obj = rwa->max_object + 1;
5040 		int free_err = 0;
5041 		int next_err = 0;
5042 
5043 		while (next_err == 0) {
5044 			free_err = dmu_free_long_object(rwa->os, obj);
5045 			if (free_err != 0 && free_err != ENOENT)
5046 				break;
5047 
5048 			next_err = dmu_object_next(rwa->os, &obj, FALSE, 0);
5049 		}
5050 
5051 		if (err == 0) {
5052 			if (free_err != 0 && free_err != ENOENT)
5053 				err = free_err;
5054 			else if (next_err != ESRCH)
5055 				err = next_err;
5056 		}
5057 	}
5058 
5059 	cv_destroy(&rwa->cv);
5060 	mutex_destroy(&rwa->mutex);
5061 	bqueue_destroy(&rwa->q);
5062 	list_destroy(&rwa->write_batch);
5063 	list_destroy(&rwa->defer_records);
5064 	avl_destroy(&rwa->defer_ranges);
5065 	if (err == 0)
5066 		err = rwa->err;
5067 
5068 out:
5069 	/*
5070 	 * If we hit an error before we started the receive_writer_thread
5071 	 * we need to clean up the next_rrd we create by processing the
5072 	 * DRR_BEGIN record.
5073 	 */
5074 	if (drc->drc_next_rrd != NULL)
5075 		kmem_free(drc->drc_next_rrd, sizeof (*drc->drc_next_rrd));
5076 
5077 	/*
5078 	 * The objset will be invalidated by dmu_recv_end() when we do
5079 	 * dsl_dataset_clone_swap_sync_impl().
5080 	 */
5081 	drc->drc_os = NULL;
5082 
5083 	kmem_free(rwa, sizeof (*rwa));
5084 	nvlist_free(drc->drc_begin_nvl);
5085 
5086 	if (err != 0) {
5087 		/*
5088 		 * Clean up references. If receive is not resumable,
5089 		 * destroy what we created, so we don't leave it in
5090 		 * the inconsistent state.
5091 		 */
5092 		dmu_recv_cleanup_ds(drc);
5093 		nvlist_free(drc->drc_keynvl);
5094 		crfree(drc->drc_cred);
5095 		drc->drc_cred = NULL;
5096 	}
5097 
5098 	objlist_destroy(drc->drc_ignore_objlist);
5099 	drc->drc_ignore_objlist = NULL;
5100 	*voffp = drc->drc_voff;
5101 	return (err);
5102 }
5103 
5104 static int
dmu_recv_end_check(void * arg,dmu_tx_t * tx)5105 dmu_recv_end_check(void *arg, dmu_tx_t *tx)
5106 {
5107 	dmu_recv_cookie_t *drc = arg;
5108 	dsl_pool_t *dp = dmu_tx_pool(tx);
5109 	int error;
5110 
5111 	ASSERT3P(drc->drc_ds->ds_owner, ==, dmu_recv_tag);
5112 
5113 	if (drc->drc_heal) {
5114 		error = 0;
5115 	} else if (!drc->drc_newfs) {
5116 		dsl_dataset_t *origin_head;
5117 
5118 		error = dsl_dataset_hold(dp, drc->drc_tofs, FTAG, &origin_head);
5119 		if (error != 0)
5120 			return (error);
5121 		if (drc->drc_force) {
5122 			/*
5123 			 * We will destroy any snapshots in tofs (i.e. before
5124 			 * origin_head) that are after the origin (which is
5125 			 * the snap before drc_ds, because drc_ds can not
5126 			 * have any snaps of its own).
5127 			 */
5128 			uint64_t obj;
5129 
5130 			obj = dsl_dataset_phys(origin_head)->ds_prev_snap_obj;
5131 			while (obj !=
5132 			    dsl_dataset_phys(drc->drc_ds)->ds_prev_snap_obj) {
5133 				dsl_dataset_t *snap;
5134 				error = dsl_dataset_hold_obj(dp, obj, FTAG,
5135 				    &snap);
5136 				if (error != 0)
5137 					break;
5138 				if (snap->ds_dir != origin_head->ds_dir)
5139 					error = SET_ERROR(EINVAL);
5140 				if (error == 0)  {
5141 					error = dsl_destroy_snapshot_check_impl(
5142 					    snap, B_FALSE);
5143 				}
5144 				obj = dsl_dataset_phys(snap)->ds_prev_snap_obj;
5145 				dsl_dataset_rele(snap, FTAG);
5146 				if (error != 0)
5147 					break;
5148 			}
5149 			if (error != 0) {
5150 				dsl_dataset_rele(origin_head, FTAG);
5151 				return (error);
5152 			}
5153 		}
5154 		if (drc->drc_keynvl != NULL) {
5155 			error = dsl_crypto_recv_raw_key_check(drc->drc_ds,
5156 			    drc->drc_keynvl, tx);
5157 			if (error != 0) {
5158 				dsl_dataset_rele(origin_head, FTAG);
5159 				return (error);
5160 			}
5161 		}
5162 
5163 		error = dsl_dataset_clone_swap_check_impl(drc->drc_ds,
5164 		    origin_head, drc->drc_force, drc->drc_owner, tx);
5165 		if (error != 0) {
5166 			dsl_dataset_rele(origin_head, FTAG);
5167 			return (error);
5168 		}
5169 		error = dsl_dataset_snapshot_check_impl(origin_head,
5170 		    drc->drc_tosnap, tx, B_TRUE, 1, drc->drc_cred);
5171 		dsl_dataset_rele(origin_head, FTAG);
5172 		if (error != 0)
5173 			return (error);
5174 
5175 		error = dsl_destroy_head_check_impl(drc->drc_ds, 1);
5176 	} else {
5177 		error = dsl_dataset_snapshot_check_impl(drc->drc_ds,
5178 		    drc->drc_tosnap, tx, B_TRUE, 1, drc->drc_cred);
5179 	}
5180 	return (error);
5181 }
5182 
5183 static void
dmu_recv_end_sync(void * arg,dmu_tx_t * tx)5184 dmu_recv_end_sync(void *arg, dmu_tx_t *tx)
5185 {
5186 	dmu_recv_cookie_t *drc = arg;
5187 	dsl_pool_t *dp = dmu_tx_pool(tx);
5188 	boolean_t encrypted = drc->drc_ds->ds_dir->dd_crypto_obj != 0;
5189 	uint64_t newsnapobj = 0;
5190 
5191 	spa_history_log_internal_ds(drc->drc_ds, "finish receiving",
5192 	    tx, "snap=%s", drc->drc_tosnap);
5193 	drc->drc_ds->ds_objset->os_raw_receive = B_FALSE;
5194 
5195 	if (drc->drc_heal) {
5196 		if (drc->drc_keynvl != NULL) {
5197 			nvlist_free(drc->drc_keynvl);
5198 			drc->drc_keynvl = NULL;
5199 		}
5200 	} else if (!drc->drc_newfs) {
5201 		dsl_dataset_t *origin_head;
5202 
5203 		VERIFY0(dsl_dataset_hold(dp, drc->drc_tofs, FTAG,
5204 		    &origin_head));
5205 
5206 		if (drc->drc_force) {
5207 			/*
5208 			 * Destroy any snapshots of drc_tofs (origin_head)
5209 			 * after the origin (the snap before drc_ds).
5210 			 */
5211 			uint64_t obj;
5212 
5213 			obj = dsl_dataset_phys(origin_head)->ds_prev_snap_obj;
5214 			while (obj !=
5215 			    dsl_dataset_phys(drc->drc_ds)->ds_prev_snap_obj) {
5216 				dsl_dataset_t *snap;
5217 				VERIFY0(dsl_dataset_hold_obj(dp, obj, FTAG,
5218 				    &snap));
5219 				ASSERT3P(snap->ds_dir, ==, origin_head->ds_dir);
5220 				obj = dsl_dataset_phys(snap)->ds_prev_snap_obj;
5221 				dsl_destroy_snapshot_sync_impl(snap,
5222 				    B_FALSE, tx);
5223 				dsl_dataset_rele(snap, FTAG);
5224 			}
5225 		}
5226 		if (drc->drc_keynvl != NULL) {
5227 			dsl_crypto_recv_raw_key_sync(drc->drc_ds,
5228 			    drc->drc_keynvl, tx);
5229 			nvlist_free(drc->drc_keynvl);
5230 			drc->drc_keynvl = NULL;
5231 		}
5232 
5233 		VERIFY3P(drc->drc_ds->ds_prev, ==,
5234 		    origin_head->ds_prev);
5235 
5236 		dsl_dataset_clone_swap_sync_impl(drc->drc_ds,
5237 		    origin_head, tx);
5238 		/*
5239 		 * The objset was evicted by dsl_dataset_clone_swap_sync_impl,
5240 		 * so drc_os is no longer valid.
5241 		 */
5242 		drc->drc_os = NULL;
5243 
5244 		dsl_dataset_snapshot_sync_impl(origin_head,
5245 		    drc->drc_tosnap, drc->drc_drrb->drr_creation_time, tx);
5246 
5247 		/* set snapshot's guid */
5248 		dmu_buf_will_dirty(origin_head->ds_prev->ds_dbuf, tx);
5249 		dsl_dataset_phys(origin_head->ds_prev)->ds_guid =
5250 		    drc->drc_drrb->drr_toguid;
5251 		dsl_dataset_phys(origin_head->ds_prev)->ds_flags &=
5252 		    ~DS_FLAG_INCONSISTENT;
5253 
5254 		dmu_buf_will_dirty(origin_head->ds_dbuf, tx);
5255 		dsl_dataset_phys(origin_head)->ds_flags &=
5256 		    ~DS_FLAG_INCONSISTENT;
5257 
5258 		newsnapobj =
5259 		    dsl_dataset_phys(origin_head)->ds_prev_snap_obj;
5260 
5261 		dsl_dataset_rele(origin_head, FTAG);
5262 		dsl_destroy_head_sync_impl(drc->drc_ds, tx);
5263 
5264 		if (drc->drc_owner != NULL)
5265 			VERIFY3P(origin_head->ds_owner, ==, drc->drc_owner);
5266 	} else {
5267 		dsl_dataset_t *ds = drc->drc_ds;
5268 
5269 		dsl_dataset_snapshot_sync_impl(ds, drc->drc_tosnap,
5270 		    drc->drc_drrb->drr_creation_time, tx);
5271 
5272 		/* set snapshot's guid */
5273 		dmu_buf_will_dirty(ds->ds_prev->ds_dbuf, tx);
5274 		dsl_dataset_phys(ds->ds_prev)->ds_guid =
5275 		    drc->drc_drrb->drr_toguid;
5276 		dsl_dataset_phys(ds->ds_prev)->ds_flags &=
5277 		    ~DS_FLAG_INCONSISTENT;
5278 
5279 		dmu_buf_will_dirty(ds->ds_dbuf, tx);
5280 		dsl_dataset_phys(ds)->ds_flags &= ~DS_FLAG_INCONSISTENT;
5281 		if (dsl_dataset_has_resume_receive_state(ds)) {
5282 			(void) zap_remove(dp->dp_meta_objset, ds->ds_object,
5283 			    DS_FIELD_RESUME_FROMGUID, tx);
5284 			(void) zap_remove(dp->dp_meta_objset, ds->ds_object,
5285 			    DS_FIELD_RESUME_OBJECT, tx);
5286 			(void) zap_remove(dp->dp_meta_objset, ds->ds_object,
5287 			    DS_FIELD_RESUME_OFFSET, tx);
5288 			(void) zap_remove(dp->dp_meta_objset, ds->ds_object,
5289 			    DS_FIELD_RESUME_BYTES, tx);
5290 			(void) zap_remove(dp->dp_meta_objset, ds->ds_object,
5291 			    DS_FIELD_RESUME_TOGUID, tx);
5292 			(void) zap_remove(dp->dp_meta_objset, ds->ds_object,
5293 			    DS_FIELD_RESUME_TONAME, tx);
5294 			(void) zap_remove(dp->dp_meta_objset, ds->ds_object,
5295 			    DS_FIELD_RESUME_REDACT_BOOKMARK_SNAPS, tx);
5296 		}
5297 		newsnapobj =
5298 		    dsl_dataset_phys(drc->drc_ds)->ds_prev_snap_obj;
5299 	}
5300 
5301 	/*
5302 	 * If this is a raw receive, the crypt_keydata nvlist will include
5303 	 * a to_ivset_guid for us to set on the new snapshot. This value
5304 	 * will override the value generated by the snapshot code. However,
5305 	 * this value may not be present, because older implementations of
5306 	 * the raw send code did not include this value, and we are still
5307 	 * allowed to receive them if the zfs_disable_ivset_guid_check
5308 	 * tunable is set, in which case we will leave the newly-generated
5309 	 * value.
5310 	 */
5311 	if (!drc->drc_heal && drc->drc_raw && drc->drc_ivset_guid != 0) {
5312 		dmu_object_zapify(dp->dp_meta_objset, newsnapobj,
5313 		    DMU_OT_DSL_DATASET, tx);
5314 		VERIFY0(zap_update(dp->dp_meta_objset, newsnapobj,
5315 		    DS_FIELD_IVSET_GUID, sizeof (uint64_t), 1,
5316 		    &drc->drc_ivset_guid, tx));
5317 	}
5318 
5319 	/*
5320 	 * Mark a raw-received snapshot so a later non-raw incremental onto it
5321 	 * can warn that it is diverging the IV set (see #8758). This is not
5322 	 * gated on drc_ivset_guid, so streams from older senders that omit it
5323 	 * (received under zfs_disable_ivset_guid_check) are still marked.
5324 	 * Snapshots on pools written before this change simply lack the key
5325 	 * and receive no warning.
5326 	 */
5327 	if (!drc->drc_heal && drc->drc_raw) {
5328 		uint64_t one = 1;
5329 		dmu_object_zapify(dp->dp_meta_objset, newsnapobj,
5330 		    DMU_OT_DSL_DATASET, tx);
5331 		VERIFY0(zap_update(dp->dp_meta_objset, newsnapobj,
5332 		    DS_FIELD_RAW_RECEIVED, sizeof (uint64_t), 1, &one, tx));
5333 	}
5334 
5335 	/*
5336 	 * Release the hold from dmu_recv_begin.  This must be done before
5337 	 * we return to open context, so that when we free the dataset's dnode
5338 	 * we can evict its bonus buffer. Since the dataset may be destroyed
5339 	 * at this point (and therefore won't have a valid pointer to the spa)
5340 	 * we release the key mapping manually here while we do have a valid
5341 	 * pointer, if it exists.
5342 	 */
5343 	if (!drc->drc_raw && encrypted) {
5344 		(void) spa_keystore_remove_mapping(dmu_tx_pool(tx)->dp_spa,
5345 		    drc->drc_ds->ds_object, drc->drc_ds);
5346 	}
5347 	dsl_dataset_disown(drc->drc_ds, 0, dmu_recv_tag);
5348 	drc->drc_ds = NULL;
5349 }
5350 
5351 static int dmu_recv_end_modified_blocks = 3;
5352 
5353 static int
dmu_recv_existing_end(dmu_recv_cookie_t * drc)5354 dmu_recv_existing_end(dmu_recv_cookie_t *drc)
5355 {
5356 #ifdef _KERNEL
5357 	/*
5358 	 * We will be destroying the ds; make sure its origin is unmounted if
5359 	 * necessary.
5360 	 */
5361 	char name[ZFS_MAX_DATASET_NAME_LEN];
5362 	dsl_dataset_name(drc->drc_ds, name);
5363 	zfs_destroy_unmount_origin(name);
5364 #endif
5365 
5366 	return (dsl_sync_task(drc->drc_tofs,
5367 	    dmu_recv_end_check, dmu_recv_end_sync, drc,
5368 	    dmu_recv_end_modified_blocks, ZFS_SPACE_CHECK_NORMAL));
5369 }
5370 
5371 static int
dmu_recv_new_end(dmu_recv_cookie_t * drc)5372 dmu_recv_new_end(dmu_recv_cookie_t *drc)
5373 {
5374 	return (dsl_sync_task(drc->drc_tofs,
5375 	    dmu_recv_end_check, dmu_recv_end_sync, drc,
5376 	    dmu_recv_end_modified_blocks, ZFS_SPACE_CHECK_NORMAL));
5377 }
5378 
5379 int
dmu_recv_end(dmu_recv_cookie_t * drc,void * owner)5380 dmu_recv_end(dmu_recv_cookie_t *drc, void *owner)
5381 {
5382 	int error;
5383 
5384 	drc->drc_owner = owner;
5385 
5386 	if (drc->drc_newfs)
5387 		error = dmu_recv_new_end(drc);
5388 	else
5389 		error = dmu_recv_existing_end(drc);
5390 
5391 	if (error != 0) {
5392 		dmu_recv_cleanup_ds(drc);
5393 		nvlist_free(drc->drc_keynvl);
5394 	} else if (!drc->drc_heal) {
5395 		if (drc->drc_newfs) {
5396 			zvol_create_minors(drc->drc_tofs);
5397 		}
5398 		char *snapname = kmem_asprintf("%s@%s",
5399 		    drc->drc_tofs, drc->drc_tosnap);
5400 		zvol_create_minors(snapname);
5401 		kmem_strfree(snapname);
5402 	}
5403 
5404 	crfree(drc->drc_cred);
5405 	drc->drc_cred = NULL;
5406 
5407 	return (error);
5408 }
5409 
5410 /*
5411  * Return TRUE if this objset is currently being received into.
5412  */
5413 boolean_t
dmu_objset_is_receiving(objset_t * os)5414 dmu_objset_is_receiving(objset_t *os)
5415 {
5416 	return (os->os_dsl_dataset != NULL &&
5417 	    os->os_dsl_dataset->ds_owner == dmu_recv_tag);
5418 }
5419 
5420 ZFS_MODULE_PARAM(zfs_recv, zfs_recv_, queue_length, UINT, ZMOD_RW,
5421 	"Maximum receive queue length");
5422 
5423 ZFS_MODULE_PARAM(zfs_recv, zfs_recv_, queue_ff, UINT, ZMOD_RW,
5424 	"Receive queue fill fraction");
5425 
5426 ZFS_MODULE_PARAM(zfs_recv, zfs_recv_, write_batch_size, UINT, ZMOD_RW,
5427 	"Maximum amount of writes to batch into one transaction");
5428 
5429 ZFS_MODULE_PARAM(zfs_recv, zfs_recv_, defer_batch_size, UINT, ZMOD_RW,
5430 	"Maximum bytes of records parked behind one txg sync while "
5431 	"receiving reallocated dnodes (0 to sync per object)");
5432 
5433 ZFS_MODULE_PARAM(zfs_recv, zfs_recv_, best_effort_corrective, INT, ZMOD_RW,
5434 	"Ignore errors during corrective receive");
5435