xref: /freebsd/sys/contrib/openzfs/module/zfs/dmu_send.c (revision 2f10ffc003be396f3fc23cd2888023896560252b)
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, 2018 by Delphix. All rights reserved.
16  * Copyright (c) 2014, Joyent, Inc. All rights reserved.
17  * Copyright 2014 HybridCluster. All rights reserved.
18  * Copyright 2016 RackTop Systems.
19  * Copyright (c) 2016 Actifio, Inc. All rights reserved.
20  * Copyright (c) 2019, 2024, Klara, Inc.
21  * Copyright (c) 2019, Allan Jude
22  */
23 
24 #include <sys/dmu.h>
25 #include <sys/dmu_impl.h>
26 #include <sys/dmu_tx.h>
27 #include <sys/dbuf.h>
28 #include <sys/dnode.h>
29 #include <sys/zfs_context.h>
30 #include <sys/dmu_objset.h>
31 #include <sys/dmu_traverse.h>
32 #include <sys/dsl_dataset.h>
33 #include <sys/dsl_dir.h>
34 #include <sys/dsl_prop.h>
35 #include <sys/dsl_pool.h>
36 #include <sys/dsl_synctask.h>
37 #include <sys/spa_impl.h>
38 #include <sys/zfs_ioctl.h>
39 #include <sys/zap.h>
40 #include <sys/zio_checksum.h>
41 #include <sys/zfs_znode.h>
42 #include <zfs_fletcher.h>
43 #include <sys/avl.h>
44 #include <sys/ddt.h>
45 #include <sys/zfs_onexit.h>
46 #include <sys/dmu_send.h>
47 #include <sys/dmu_recv.h>
48 #include <sys/dsl_destroy.h>
49 #include <sys/blkptr.h>
50 #include <sys/dsl_bookmark.h>
51 #include <sys/zfeature.h>
52 #include <sys/bqueue.h>
53 #include <sys/zvol.h>
54 #include <sys/policy.h>
55 #include <sys/objlist.h>
56 #ifdef _KERNEL
57 #include <sys/zfs_vfsops.h>
58 #endif
59 
60 /* Set this tunable to TRUE to replace corrupt data with 0x2f5baddb10c */
61 static int zfs_send_corrupt_data = B_FALSE;
62 /*
63  * This tunable controls the amount of data (measured in bytes) that will be
64  * prefetched by zfs send.  If the main thread is blocking on reads that haven't
65  * completed, this variable might need to be increased.  If instead the main
66  * thread is issuing new reads because the prefetches have fallen out of the
67  * cache, this may need to be decreased.
68  */
69 static uint_t zfs_send_queue_length = SPA_MAXBLOCKSIZE;
70 /*
71  * This tunable controls the length of the queues that zfs send worker threads
72  * use to communicate.  If the send_main_thread is blocking on these queues,
73  * this variable may need to be increased.  If there is a significant slowdown
74  * at the start of a send as these threads consume all the available IO
75  * resources, this variable may need to be decreased.
76  */
77 static uint_t zfs_send_no_prefetch_queue_length = 1024 * 1024;
78 /*
79  * These tunables control the fill fraction of the queues by zfs send.  The fill
80  * fraction controls the frequency with which threads have to be cv_signaled.
81  * If a lot of cpu time is being spent on cv_signal, then these should be tuned
82  * down.  If the queues empty before the signalled thread can catch up, then
83  * these should be tuned up.
84  */
85 static uint_t zfs_send_queue_ff = 20;
86 static uint_t zfs_send_no_prefetch_queue_ff = 20;
87 
88 /*
89  * Use this to override the recordsize calculation for fast zfs send estimates.
90  */
91 static uint_t zfs_override_estimate_recordsize = 0;
92 
93 /* Set this tunable to FALSE to disable setting of DRR_FLAG_FREERECORDS */
94 static const boolean_t zfs_send_set_freerecords_bit = B_TRUE;
95 
96 /* Set this tunable to FALSE is disable sending unmodified spill blocks. */
97 static int zfs_send_unmodified_spill_blocks = B_TRUE;
98 
99 static inline boolean_t
overflow_multiply(uint64_t a,uint64_t b,uint64_t * c)100 overflow_multiply(uint64_t a, uint64_t b, uint64_t *c)
101 {
102 	uint64_t temp = a * b;
103 	if (b != 0 && temp / b != a)
104 		return (B_FALSE);
105 	*c = temp;
106 	return (B_TRUE);
107 }
108 
109 struct send_thread_arg {
110 	bqueue_t	q;
111 	objset_t	*os;		/* Objset to traverse */
112 	uint64_t	fromtxg;	/* Traverse from this txg */
113 	int		flags;		/* flags to pass to traverse_dataset */
114 	int		error_code;
115 	boolean_t	cancel;
116 	zbookmark_phys_t resume;
117 	uint64_t	*num_blocks_visited;
118 };
119 
120 struct redact_list_thread_arg {
121 	boolean_t		cancel;
122 	bqueue_t		q;
123 	zbookmark_phys_t	resume;
124 	redaction_list_t	*rl;
125 	boolean_t		mark_redact;
126 	int			error_code;
127 	uint64_t		*num_blocks_visited;
128 };
129 
130 struct send_merge_thread_arg {
131 	bqueue_t			q;
132 	objset_t			*os;
133 	struct redact_list_thread_arg	*from_arg;
134 	struct send_thread_arg		*to_arg;
135 	struct redact_list_thread_arg	*redact_arg;
136 	int				error;
137 	boolean_t			cancel;
138 };
139 
140 struct send_range {
141 	boolean_t		eos_marker; /* Marks the end of the stream */
142 	uint64_t		object;
143 	uint64_t		start_blkid;
144 	uint64_t		end_blkid;
145 	bqueue_node_t		ln;
146 	enum type {DATA, HOLE, OBJECT, OBJECT_RANGE, REDACT,
147 	    PREVIOUSLY_REDACTED} type;
148 	union {
149 		struct srd {
150 			dmu_object_type_t	obj_type;
151 			uint32_t		datablksz; // logical size
152 			uint32_t		datasz; // payload size
153 			blkptr_t		bp;
154 			arc_buf_t		*abuf;
155 			abd_t			*abd;
156 			kmutex_t		lock;
157 			kcondvar_t		cv;
158 			boolean_t		io_outstanding;
159 			boolean_t		io_compressed;
160 			int			io_err;
161 		} data;
162 		struct srh {
163 			uint32_t		datablksz;
164 		} hole;
165 		struct sro {
166 			/*
167 			 * This is a pointer because embedding it in the
168 			 * struct causes these structures to be massively larger
169 			 * for all range types; this makes the code much less
170 			 * memory efficient.
171 			 */
172 			dnode_phys_t		*dnp;
173 			blkptr_t		bp;
174 			/* Piggyback unmodified spill block */
175 			struct send_range	*spill_range;
176 		} object;
177 		struct srr {
178 			uint32_t		datablksz;
179 		} redact;
180 		struct sror {
181 			blkptr_t		bp;
182 		} object_range;
183 	} sru;
184 };
185 
186 /*
187  * The list of data whose inclusion in a send stream can be pending from
188  * one call to backup_cb to another.  Multiple calls to dump_free(),
189  * dump_freeobjects(), and dump_redact() can be aggregated into a single
190  * DRR_FREE, DRR_FREEOBJECTS, or DRR_REDACT replay record.
191  */
192 typedef enum {
193 	PENDING_NONE,
194 	PENDING_FREE,
195 	PENDING_FREEOBJECTS,
196 	PENDING_REDACT
197 } dmu_pendop_t;
198 
199 typedef struct dmu_send_cookie {
200 	dmu_replay_record_t *dsc_drr;
201 	dmu_send_outparams_t *dsc_dso;
202 	offset_t *dsc_off;
203 	objset_t *dsc_os;
204 	zio_cksum_t dsc_zc;
205 	uint64_t dsc_toguid;
206 	uint64_t dsc_fromtxg;
207 	int dsc_err;
208 	dmu_pendop_t dsc_pending_op;
209 	uint64_t dsc_featureflags;
210 	uint64_t dsc_last_data_object;
211 	uint64_t dsc_last_data_offset;
212 	uint64_t dsc_resume_object;
213 	uint64_t dsc_resume_offset;
214 	boolean_t dsc_sent_begin;
215 	boolean_t dsc_sent_end;
216 } dmu_send_cookie_t;
217 
218 static int do_dump(dmu_send_cookie_t *dscp, struct send_range *range);
219 
220 static void
range_free(struct send_range * range)221 range_free(struct send_range *range)
222 {
223 	if (range->type == OBJECT) {
224 		size_t size = sizeof (dnode_phys_t) *
225 		    (range->sru.object.dnp->dn_extra_slots + 1);
226 		kmem_free(range->sru.object.dnp, size);
227 		if (range->sru.object.spill_range)
228 			range_free(range->sru.object.spill_range);
229 	} else if (range->type == DATA) {
230 		mutex_enter(&range->sru.data.lock);
231 		while (range->sru.data.io_outstanding)
232 			cv_wait(&range->sru.data.cv, &range->sru.data.lock);
233 		if (range->sru.data.abd != NULL)
234 			abd_free(range->sru.data.abd);
235 		if (range->sru.data.abuf != NULL) {
236 			arc_buf_destroy(range->sru.data.abuf,
237 			    &range->sru.data.abuf);
238 		}
239 		mutex_exit(&range->sru.data.lock);
240 
241 		cv_destroy(&range->sru.data.cv);
242 		mutex_destroy(&range->sru.data.lock);
243 	}
244 	kmem_free(range, sizeof (*range));
245 }
246 
247 /*
248  * For all record types except BEGIN, fill in the checksum (overlaid in
249  * drr_u.drr_checksum.drr_checksum).  The checksum verifies everything
250  * up to the start of the checksum itself.
251  */
252 static int
dump_record(dmu_send_cookie_t * dscp,void * payload,int payload_len)253 dump_record(dmu_send_cookie_t *dscp, void *payload, int payload_len)
254 {
255 	dmu_send_outparams_t *dso = dscp->dsc_dso;
256 	ASSERT3U(offsetof(dmu_replay_record_t, drr_u.drr_checksum.drr_checksum),
257 	    ==, sizeof (dmu_replay_record_t) - sizeof (zio_cksum_t));
258 	(void) fletcher_4_incremental_native(dscp->dsc_drr,
259 	    offsetof(dmu_replay_record_t, drr_u.drr_checksum.drr_checksum),
260 	    &dscp->dsc_zc);
261 	if (dscp->dsc_drr->drr_type == DRR_BEGIN) {
262 		dscp->dsc_sent_begin = B_TRUE;
263 	} else {
264 		ASSERT(ZIO_CHECKSUM_IS_ZERO(&dscp->dsc_drr->drr_u.
265 		    drr_checksum.drr_checksum));
266 		dscp->dsc_drr->drr_u.drr_checksum.drr_checksum = dscp->dsc_zc;
267 	}
268 	if (dscp->dsc_drr->drr_type == DRR_END) {
269 		dscp->dsc_sent_end = B_TRUE;
270 	}
271 	(void) fletcher_4_incremental_native(&dscp->dsc_drr->
272 	    drr_u.drr_checksum.drr_checksum,
273 	    sizeof (zio_cksum_t), &dscp->dsc_zc);
274 	*dscp->dsc_off += sizeof (dmu_replay_record_t);
275 	dscp->dsc_err = dso->dso_outfunc(dscp->dsc_os, dscp->dsc_drr,
276 	    sizeof (dmu_replay_record_t), dso->dso_arg);
277 	if (dscp->dsc_err != 0)
278 		return (SET_ERROR(EINTR));
279 	if (payload_len != 0) {
280 		*dscp->dsc_off += payload_len;
281 		/*
282 		 * payload is null when dso_dryrun == B_TRUE (i.e. when we're
283 		 * doing a send size calculation)
284 		 */
285 		if (payload != NULL) {
286 			(void) fletcher_4_incremental_native(
287 			    payload, payload_len, &dscp->dsc_zc);
288 		}
289 
290 		/*
291 		 * The code does not rely on this (len being a multiple of 8).
292 		 * We keep this assertion because of the corresponding assertion
293 		 * in receive_read().  Keeping this assertion ensures that we do
294 		 * not inadvertently break backwards compatibility (causing the
295 		 * assertion in receive_read() to trigger on old software).
296 		 *
297 		 * Raw sends cannot be received on old software, and so can
298 		 * bypass this assertion.
299 		 */
300 
301 		ASSERT((payload_len % 8 == 0) ||
302 		    (dscp->dsc_featureflags & DMU_BACKUP_FEATURE_RAW));
303 
304 		dscp->dsc_err = dso->dso_outfunc(dscp->dsc_os, payload,
305 		    payload_len, dso->dso_arg);
306 		if (dscp->dsc_err != 0)
307 			return (SET_ERROR(EINTR));
308 	}
309 	return (0);
310 }
311 
312 /*
313  * Fill in the drr_free struct, or perform aggregation if the previous record is
314  * also a free record, and the two are adjacent.
315  *
316  * Note that we send free records even for a full send, because we want to be
317  * able to receive a full send as a clone, which requires a list of all the free
318  * and freeobject records that were generated on the source.
319  */
320 static int
dump_free(dmu_send_cookie_t * dscp,uint64_t object,uint64_t offset,uint64_t length)321 dump_free(dmu_send_cookie_t *dscp, uint64_t object, uint64_t offset,
322     uint64_t length)
323 {
324 	struct drr_free *drrf = &(dscp->dsc_drr->drr_u.drr_free);
325 
326 	/*
327 	 * When we receive a free record, dbuf_free_range() assumes
328 	 * that the receiving system doesn't have any dbufs in the range
329 	 * being freed.  This is always true because there is a one-record
330 	 * constraint: we only send one WRITE record for any given
331 	 * object,offset.  We know that the one-record constraint is
332 	 * true because we always send data in increasing order by
333 	 * object,offset.
334 	 *
335 	 * If the increasing-order constraint ever changes, we should find
336 	 * another way to assert that the one-record constraint is still
337 	 * satisfied.
338 	 */
339 	ASSERT(object > dscp->dsc_last_data_object ||
340 	    (object == dscp->dsc_last_data_object &&
341 	    offset > dscp->dsc_last_data_offset));
342 
343 	/*
344 	 * If there is a pending op, but it's not PENDING_FREE, push it out,
345 	 * since free block aggregation can only be done for blocks of the
346 	 * same type (i.e., DRR_FREE records can only be aggregated with
347 	 * other DRR_FREE records.  DRR_FREEOBJECTS records can only be
348 	 * aggregated with other DRR_FREEOBJECTS records).
349 	 */
350 	if (dscp->dsc_pending_op != PENDING_NONE &&
351 	    dscp->dsc_pending_op != PENDING_FREE) {
352 		if (dump_record(dscp, NULL, 0) != 0)
353 			return (SET_ERROR(EINTR));
354 		dscp->dsc_pending_op = PENDING_NONE;
355 	}
356 
357 	if (dscp->dsc_pending_op == PENDING_FREE) {
358 		/*
359 		 * Check to see whether this free block can be aggregated
360 		 * with pending one.
361 		 */
362 		if (drrf->drr_object == object && drrf->drr_offset +
363 		    drrf->drr_length == offset) {
364 			if (offset + length < offset || length == UINT64_MAX)
365 				drrf->drr_length = UINT64_MAX;
366 			else
367 				drrf->drr_length += length;
368 			return (0);
369 		} else {
370 			/* not a continuation.  Push out pending record */
371 			if (dump_record(dscp, NULL, 0) != 0)
372 				return (SET_ERROR(EINTR));
373 			dscp->dsc_pending_op = PENDING_NONE;
374 		}
375 	}
376 	/* create a FREE record and make it pending */
377 	memset(dscp->dsc_drr, 0, sizeof (dmu_replay_record_t));
378 	dscp->dsc_drr->drr_type = DRR_FREE;
379 	drrf->drr_object = object;
380 	drrf->drr_offset = offset;
381 	if (offset + length < offset)
382 		drrf->drr_length = DMU_OBJECT_END;
383 	else
384 		drrf->drr_length = length;
385 	drrf->drr_toguid = dscp->dsc_toguid;
386 	if (length == DMU_OBJECT_END) {
387 		if (dump_record(dscp, NULL, 0) != 0)
388 			return (SET_ERROR(EINTR));
389 	} else {
390 		dscp->dsc_pending_op = PENDING_FREE;
391 	}
392 
393 	return (0);
394 }
395 
396 /*
397  * Fill in the drr_redact struct, or perform aggregation if the previous record
398  * is also a redaction record, and the two are adjacent.
399  */
400 static int
dump_redact(dmu_send_cookie_t * dscp,uint64_t object,uint64_t offset,uint64_t length)401 dump_redact(dmu_send_cookie_t *dscp, uint64_t object, uint64_t offset,
402     uint64_t length)
403 {
404 	struct drr_redact *drrr = &dscp->dsc_drr->drr_u.drr_redact;
405 
406 	/*
407 	 * If there is a pending op, but it's not PENDING_REDACT, push it out,
408 	 * since free block aggregation can only be done for blocks of the
409 	 * same type (i.e., DRR_REDACT records can only be aggregated with
410 	 * other DRR_REDACT records).
411 	 */
412 	if (dscp->dsc_pending_op != PENDING_NONE &&
413 	    dscp->dsc_pending_op != PENDING_REDACT) {
414 		if (dump_record(dscp, NULL, 0) != 0)
415 			return (SET_ERROR(EINTR));
416 		dscp->dsc_pending_op = PENDING_NONE;
417 	}
418 
419 	if (dscp->dsc_pending_op == PENDING_REDACT) {
420 		/*
421 		 * Check to see whether this redacted block can be aggregated
422 		 * with pending one.
423 		 */
424 		if (drrr->drr_object == object && drrr->drr_offset +
425 		    drrr->drr_length == offset) {
426 			drrr->drr_length += length;
427 			return (0);
428 		} else {
429 			/* not a continuation.  Push out pending record */
430 			if (dump_record(dscp, NULL, 0) != 0)
431 				return (SET_ERROR(EINTR));
432 			dscp->dsc_pending_op = PENDING_NONE;
433 		}
434 	}
435 	/* create a REDACT record and make it pending */
436 	memset(dscp->dsc_drr, 0, sizeof (dmu_replay_record_t));
437 	dscp->dsc_drr->drr_type = DRR_REDACT;
438 	drrr->drr_object = object;
439 	drrr->drr_offset = offset;
440 	drrr->drr_length = length;
441 	drrr->drr_toguid = dscp->dsc_toguid;
442 	dscp->dsc_pending_op = PENDING_REDACT;
443 
444 	return (0);
445 }
446 
447 static int
dmu_dump_write(dmu_send_cookie_t * dscp,dmu_object_type_t type,uint64_t object,uint64_t offset,int lsize,int psize,const blkptr_t * bp,boolean_t io_compressed,void * data)448 dmu_dump_write(dmu_send_cookie_t *dscp, dmu_object_type_t type, uint64_t object,
449     uint64_t offset, int lsize, int psize, const blkptr_t *bp,
450     boolean_t io_compressed, void *data)
451 {
452 	uint64_t payload_size;
453 	boolean_t raw = (dscp->dsc_featureflags & DMU_BACKUP_FEATURE_RAW);
454 	struct drr_write *drrw = &(dscp->dsc_drr->drr_u.drr_write);
455 
456 	/*
457 	 * We send data in increasing object, offset order.
458 	 * See comment in dump_free() for details.
459 	 */
460 	ASSERT(object > dscp->dsc_last_data_object ||
461 	    (object == dscp->dsc_last_data_object &&
462 	    offset > dscp->dsc_last_data_offset));
463 	dscp->dsc_last_data_object = object;
464 	dscp->dsc_last_data_offset = offset + lsize - 1;
465 
466 	/*
467 	 * If there is any kind of pending aggregation (currently either
468 	 * a grouping of free objects or free blocks), push it out to
469 	 * the stream, since aggregation can't be done across operations
470 	 * of different types.
471 	 */
472 	if (dscp->dsc_pending_op != PENDING_NONE) {
473 		if (dump_record(dscp, NULL, 0) != 0)
474 			return (SET_ERROR(EINTR));
475 		dscp->dsc_pending_op = PENDING_NONE;
476 	}
477 	/* write a WRITE record */
478 	memset(dscp->dsc_drr, 0, sizeof (dmu_replay_record_t));
479 	dscp->dsc_drr->drr_type = DRR_WRITE;
480 	drrw->drr_object = object;
481 	drrw->drr_type = type;
482 	drrw->drr_offset = offset;
483 	drrw->drr_toguid = dscp->dsc_toguid;
484 	drrw->drr_logical_size = lsize;
485 
486 	/* only set the compression fields if the buf is compressed or raw */
487 	boolean_t compressed =
488 	    (bp != NULL ? BP_GET_COMPRESS(bp) != ZIO_COMPRESS_OFF &&
489 	    io_compressed : lsize != psize);
490 	if (raw || compressed) {
491 		ASSERT(bp != NULL);
492 		ASSERT(raw || dscp->dsc_featureflags &
493 		    DMU_BACKUP_FEATURE_COMPRESSED);
494 		ASSERT(!BP_IS_EMBEDDED(bp));
495 		ASSERT3S(psize, >, 0);
496 
497 		if (raw) {
498 			ASSERT(BP_IS_PROTECTED(bp));
499 
500 			/*
501 			 * This is a raw protected block so we need to pass
502 			 * along everything the receiving side will need to
503 			 * interpret this block, including the byteswap, salt,
504 			 * IV, and MAC.
505 			 */
506 			if (BP_SHOULD_BYTESWAP(bp))
507 				drrw->drr_flags |= DRR_RAW_BYTESWAP;
508 			zio_crypt_decode_params_bp(bp, drrw->drr_salt,
509 			    drrw->drr_iv);
510 			zio_crypt_decode_mac_bp(bp, drrw->drr_mac);
511 		} else {
512 			/* this is a compressed block */
513 			ASSERT(dscp->dsc_featureflags &
514 			    DMU_BACKUP_FEATURE_COMPRESSED);
515 			ASSERT(!BP_SHOULD_BYTESWAP(bp));
516 			ASSERT(!DMU_OT_IS_METADATA(BP_GET_TYPE(bp)));
517 			ASSERT3U(BP_GET_COMPRESS(bp), !=, ZIO_COMPRESS_OFF);
518 			ASSERT3S(lsize, >=, psize);
519 		}
520 
521 		/* set fields common to compressed and raw sends */
522 		drrw->drr_compressiontype = BP_GET_COMPRESS(bp);
523 		drrw->drr_compressed_size = psize;
524 		payload_size = drrw->drr_compressed_size;
525 	} else {
526 		payload_size = drrw->drr_logical_size;
527 	}
528 
529 	if (bp == NULL || BP_IS_EMBEDDED(bp) || (BP_IS_PROTECTED(bp) && !raw)) {
530 		/*
531 		 * There's no pre-computed checksum for partial-block writes,
532 		 * embedded BP's, or encrypted BP's that are being sent as
533 		 * plaintext, so (like fletcher4-checksummed blocks) userland
534 		 * will have to compute a dedup-capable checksum itself.
535 		 */
536 		drrw->drr_checksumtype = ZIO_CHECKSUM_OFF;
537 	} else {
538 		drrw->drr_checksumtype = BP_GET_CHECKSUM(bp);
539 		if (zio_checksum_table[drrw->drr_checksumtype].ci_flags &
540 		    ZCHECKSUM_FLAG_DEDUP)
541 			drrw->drr_flags |= DRR_CHECKSUM_DEDUP;
542 		DDK_SET_LSIZE(&drrw->drr_key, BP_GET_LSIZE(bp));
543 		DDK_SET_PSIZE(&drrw->drr_key, BP_GET_PSIZE(bp));
544 		DDK_SET_COMPRESS(&drrw->drr_key, BP_GET_COMPRESS(bp));
545 		DDK_SET_CRYPT(&drrw->drr_key, BP_IS_PROTECTED(bp));
546 		drrw->drr_key.ddk_cksum = bp->blk_cksum;
547 	}
548 
549 	if (dump_record(dscp, data, payload_size) != 0)
550 		return (SET_ERROR(EINTR));
551 	return (0);
552 }
553 
554 static int
dump_write_embedded(dmu_send_cookie_t * dscp,uint64_t object,uint64_t offset,int blksz,const blkptr_t * bp)555 dump_write_embedded(dmu_send_cookie_t *dscp, uint64_t object, uint64_t offset,
556     int blksz, const blkptr_t *bp)
557 {
558 	char buf[BPE_PAYLOAD_SIZE];
559 	struct drr_write_embedded *drrw =
560 	    &(dscp->dsc_drr->drr_u.drr_write_embedded);
561 
562 	if (dscp->dsc_pending_op != PENDING_NONE) {
563 		if (dump_record(dscp, NULL, 0) != 0)
564 			return (SET_ERROR(EINTR));
565 		dscp->dsc_pending_op = PENDING_NONE;
566 	}
567 
568 	ASSERT(BP_IS_EMBEDDED(bp));
569 
570 	memset(dscp->dsc_drr, 0, sizeof (dmu_replay_record_t));
571 	dscp->dsc_drr->drr_type = DRR_WRITE_EMBEDDED;
572 	drrw->drr_object = object;
573 	drrw->drr_offset = offset;
574 	drrw->drr_length = blksz;
575 	drrw->drr_toguid = dscp->dsc_toguid;
576 	drrw->drr_compression = BP_GET_COMPRESS(bp);
577 	drrw->drr_etype = BPE_GET_ETYPE(bp);
578 	drrw->drr_lsize = BPE_GET_LSIZE(bp);
579 	drrw->drr_psize = BPE_GET_PSIZE(bp);
580 
581 	decode_embedded_bp_compressed(bp, buf);
582 
583 	uint32_t psize = drrw->drr_psize;
584 	uint32_t rsize = P2ROUNDUP(psize, 8);
585 
586 	if (psize != rsize)
587 		memset(buf + psize, 0, rsize - psize);
588 
589 	if (dump_record(dscp, buf, rsize) != 0)
590 		return (SET_ERROR(EINTR));
591 	return (0);
592 }
593 
594 static int
dump_spill(dmu_send_cookie_t * dscp,const blkptr_t * bp,uint64_t object,void * data)595 dump_spill(dmu_send_cookie_t *dscp, const blkptr_t *bp, uint64_t object,
596     void *data)
597 {
598 	struct drr_spill *drrs = &(dscp->dsc_drr->drr_u.drr_spill);
599 	uint64_t blksz = BP_GET_LSIZE(bp);
600 	uint64_t payload_size = blksz;
601 
602 	if (dscp->dsc_pending_op != PENDING_NONE) {
603 		if (dump_record(dscp, NULL, 0) != 0)
604 			return (SET_ERROR(EINTR));
605 		dscp->dsc_pending_op = PENDING_NONE;
606 	}
607 
608 	/* write a SPILL record */
609 	memset(dscp->dsc_drr, 0, sizeof (dmu_replay_record_t));
610 	dscp->dsc_drr->drr_type = DRR_SPILL;
611 	drrs->drr_object = object;
612 	drrs->drr_length = blksz;
613 	drrs->drr_toguid = dscp->dsc_toguid;
614 
615 	/* See comment in piggyback_unmodified_spill() for full details */
616 	if (zfs_send_unmodified_spill_blocks &&
617 	    (BP_GET_LOGICAL_BIRTH(bp) <= dscp->dsc_fromtxg)) {
618 		drrs->drr_flags |= DRR_SPILL_UNMODIFIED;
619 	}
620 
621 	/* handle raw send fields */
622 	if (dscp->dsc_featureflags & DMU_BACKUP_FEATURE_RAW) {
623 		ASSERT(BP_IS_PROTECTED(bp));
624 
625 		if (BP_SHOULD_BYTESWAP(bp))
626 			drrs->drr_flags |= DRR_RAW_BYTESWAP;
627 		drrs->drr_compressiontype = BP_GET_COMPRESS(bp);
628 		drrs->drr_compressed_size = BP_GET_PSIZE(bp);
629 		zio_crypt_decode_params_bp(bp, drrs->drr_salt, drrs->drr_iv);
630 		zio_crypt_decode_mac_bp(bp, drrs->drr_mac);
631 		payload_size = drrs->drr_compressed_size;
632 	}
633 
634 	if (dump_record(dscp, data, payload_size) != 0)
635 		return (SET_ERROR(EINTR));
636 	return (0);
637 }
638 
639 static int
dump_freeobjects(dmu_send_cookie_t * dscp,uint64_t firstobj,uint64_t numobjs)640 dump_freeobjects(dmu_send_cookie_t *dscp, uint64_t firstobj, uint64_t numobjs)
641 {
642 	struct drr_freeobjects *drrfo = &(dscp->dsc_drr->drr_u.drr_freeobjects);
643 	uint64_t maxobj = DNODES_PER_BLOCK *
644 	    (DMU_META_DNODE(dscp->dsc_os)->dn_maxblkid + 1);
645 
646 	/*
647 	 * ZoL < 0.7 does not handle large FREEOBJECTS records correctly,
648 	 * leading to zfs recv never completing. to avoid this issue, don't
649 	 * send FREEOBJECTS records for object IDs which cannot exist on the
650 	 * receiving side.
651 	 */
652 	if (maxobj > 0) {
653 		if (maxobj <= firstobj)
654 			return (0);
655 
656 		if (maxobj < firstobj + numobjs)
657 			numobjs = maxobj - firstobj;
658 	}
659 
660 	/*
661 	 * If there is a pending op, but it's not PENDING_FREEOBJECTS,
662 	 * push it out, since free block aggregation can only be done for
663 	 * blocks of the same type (i.e., DRR_FREE records can only be
664 	 * aggregated with other DRR_FREE records.  DRR_FREEOBJECTS records
665 	 * can only be aggregated with other DRR_FREEOBJECTS records).
666 	 */
667 	if (dscp->dsc_pending_op != PENDING_NONE &&
668 	    dscp->dsc_pending_op != PENDING_FREEOBJECTS) {
669 		if (dump_record(dscp, NULL, 0) != 0)
670 			return (SET_ERROR(EINTR));
671 		dscp->dsc_pending_op = PENDING_NONE;
672 	}
673 
674 	if (dscp->dsc_pending_op == PENDING_FREEOBJECTS) {
675 		/*
676 		 * See whether this free object array can be aggregated
677 		 * with pending one
678 		 */
679 		if (drrfo->drr_firstobj + drrfo->drr_numobjs == firstobj) {
680 			drrfo->drr_numobjs += numobjs;
681 			return (0);
682 		} else {
683 			/* can't be aggregated.  Push out pending record */
684 			if (dump_record(dscp, NULL, 0) != 0)
685 				return (SET_ERROR(EINTR));
686 			dscp->dsc_pending_op = PENDING_NONE;
687 		}
688 	}
689 
690 	/* write a FREEOBJECTS record */
691 	memset(dscp->dsc_drr, 0, sizeof (dmu_replay_record_t));
692 	dscp->dsc_drr->drr_type = DRR_FREEOBJECTS;
693 	drrfo->drr_firstobj = firstobj;
694 	drrfo->drr_numobjs = numobjs;
695 	drrfo->drr_toguid = dscp->dsc_toguid;
696 
697 	dscp->dsc_pending_op = PENDING_FREEOBJECTS;
698 
699 	return (0);
700 }
701 
702 static int
dump_dnode(dmu_send_cookie_t * dscp,const blkptr_t * bp,uint64_t object,dnode_phys_t * dnp)703 dump_dnode(dmu_send_cookie_t *dscp, const blkptr_t *bp, uint64_t object,
704     dnode_phys_t *dnp)
705 {
706 	struct drr_object *drro = &(dscp->dsc_drr->drr_u.drr_object);
707 	int bonuslen;
708 
709 	if (object < dscp->dsc_resume_object) {
710 		/*
711 		 * Note: when resuming, we will visit all the dnodes in
712 		 * the block of dnodes that we are resuming from.  In
713 		 * this case it's unnecessary to send the dnodes prior to
714 		 * the one we are resuming from.  We should be at most one
715 		 * block's worth of dnodes behind the resume point.
716 		 */
717 		ASSERT3U(dscp->dsc_resume_object - object, <,
718 		    1 << (DNODE_BLOCK_SHIFT - DNODE_SHIFT));
719 		return (0);
720 	}
721 
722 	if (dnp == NULL || dnp->dn_type == DMU_OT_NONE)
723 		return (dump_freeobjects(dscp, object, 1));
724 
725 	if (dscp->dsc_pending_op != PENDING_NONE) {
726 		if (dump_record(dscp, NULL, 0) != 0)
727 			return (SET_ERROR(EINTR));
728 		dscp->dsc_pending_op = PENDING_NONE;
729 	}
730 
731 	/* write an OBJECT record */
732 	memset(dscp->dsc_drr, 0, sizeof (dmu_replay_record_t));
733 	dscp->dsc_drr->drr_type = DRR_OBJECT;
734 	drro->drr_object = object;
735 	drro->drr_type = dnp->dn_type;
736 	drro->drr_bonustype = dnp->dn_bonustype;
737 	drro->drr_blksz = dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT;
738 	drro->drr_bonuslen = dnp->dn_bonuslen;
739 	drro->drr_dn_slots = dnp->dn_extra_slots + 1;
740 	drro->drr_checksumtype = dnp->dn_checksum;
741 	drro->drr_compress = dnp->dn_compress;
742 	drro->drr_toguid = dscp->dsc_toguid;
743 
744 	if (!(dscp->dsc_featureflags & DMU_BACKUP_FEATURE_LARGE_BLOCKS) &&
745 	    drro->drr_blksz > SPA_OLD_MAXBLOCKSIZE)
746 		drro->drr_blksz = SPA_OLD_MAXBLOCKSIZE;
747 
748 	bonuslen = P2ROUNDUP(dnp->dn_bonuslen, 8);
749 
750 	if ((dscp->dsc_featureflags & DMU_BACKUP_FEATURE_RAW)) {
751 		ASSERT(BP_IS_ENCRYPTED(bp));
752 
753 		if (BP_SHOULD_BYTESWAP(bp))
754 			drro->drr_flags |= DRR_RAW_BYTESWAP;
755 
756 		/* needed for reconstructing dnp on recv side */
757 		drro->drr_maxblkid = dnp->dn_maxblkid;
758 		drro->drr_indblkshift = dnp->dn_indblkshift;
759 		drro->drr_nlevels = dnp->dn_nlevels;
760 		drro->drr_nblkptr = dnp->dn_nblkptr;
761 
762 		/*
763 		 * Since we encrypt the entire bonus area, the (raw) part
764 		 * beyond the bonuslen is actually nonzero, so we need
765 		 * to send it.
766 		 */
767 		if (bonuslen != 0) {
768 			if (drro->drr_bonuslen > DN_MAX_BONUS_LEN(dnp))
769 				return (SET_ERROR(EINVAL));
770 			drro->drr_raw_bonuslen = DN_MAX_BONUS_LEN(dnp);
771 			bonuslen = drro->drr_raw_bonuslen;
772 		}
773 	}
774 
775 	/*
776 	 * DRR_OBJECT_SPILL is set for every dnode which references a
777 	 * spill block.	 This allows the receiving pool to definitively
778 	 * determine when a spill block should be kept or freed.
779 	 */
780 	if (dnp->dn_flags & DNODE_FLAG_SPILL_BLKPTR)
781 		drro->drr_flags |= DRR_OBJECT_SPILL;
782 
783 	if (dump_record(dscp, DN_BONUS(dnp), bonuslen) != 0)
784 		return (SET_ERROR(EINTR));
785 
786 	/* Free anything past the end of the file. */
787 	if (dump_free(dscp, object, (dnp->dn_maxblkid + 1) *
788 	    (dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT), DMU_OBJECT_END) != 0)
789 		return (SET_ERROR(EINTR));
790 
791 	if (dscp->dsc_err != 0)
792 		return (SET_ERROR(EINTR));
793 
794 	return (0);
795 }
796 
797 static int
dump_object_range(dmu_send_cookie_t * dscp,const blkptr_t * bp,uint64_t firstobj,uint64_t numslots)798 dump_object_range(dmu_send_cookie_t *dscp, const blkptr_t *bp,
799     uint64_t firstobj, uint64_t numslots)
800 {
801 	struct drr_object_range *drror =
802 	    &(dscp->dsc_drr->drr_u.drr_object_range);
803 
804 	/* we only use this record type for raw sends */
805 	ASSERT(BP_IS_PROTECTED(bp));
806 	ASSERT(dscp->dsc_featureflags & DMU_BACKUP_FEATURE_RAW);
807 	ASSERT3U(BP_GET_COMPRESS(bp), ==, ZIO_COMPRESS_OFF);
808 	ASSERT3U(BP_GET_TYPE(bp), ==, DMU_OT_DNODE);
809 	ASSERT0(BP_GET_LEVEL(bp));
810 
811 	if (dscp->dsc_pending_op != PENDING_NONE) {
812 		if (dump_record(dscp, NULL, 0) != 0)
813 			return (SET_ERROR(EINTR));
814 		dscp->dsc_pending_op = PENDING_NONE;
815 	}
816 
817 	memset(dscp->dsc_drr, 0, sizeof (dmu_replay_record_t));
818 	dscp->dsc_drr->drr_type = DRR_OBJECT_RANGE;
819 	drror->drr_firstobj = firstobj;
820 	drror->drr_numslots = numslots;
821 	drror->drr_toguid = dscp->dsc_toguid;
822 	if (BP_SHOULD_BYTESWAP(bp))
823 		drror->drr_flags |= DRR_RAW_BYTESWAP;
824 	zio_crypt_decode_params_bp(bp, drror->drr_salt, drror->drr_iv);
825 	zio_crypt_decode_mac_bp(bp, drror->drr_mac);
826 
827 	if (dump_record(dscp, NULL, 0) != 0)
828 		return (SET_ERROR(EINTR));
829 	return (0);
830 }
831 
832 static boolean_t
send_do_embed(const blkptr_t * bp,uint64_t featureflags)833 send_do_embed(const blkptr_t *bp, uint64_t featureflags)
834 {
835 	if (!BP_IS_EMBEDDED(bp))
836 		return (B_FALSE);
837 
838 	/*
839 	 * Compression function must be legacy, or explicitly enabled.
840 	 */
841 	if ((BP_GET_COMPRESS(bp) >= ZIO_COMPRESS_LEGACY_FUNCTIONS &&
842 	    !(featureflags & DMU_BACKUP_FEATURE_LZ4)))
843 		return (B_FALSE);
844 
845 	/*
846 	 * If we have not set the ZSTD feature flag, we can't send ZSTD
847 	 * compressed embedded blocks, as the receiver may not support them.
848 	 */
849 	if ((BP_GET_COMPRESS(bp) == ZIO_COMPRESS_ZSTD &&
850 	    !(featureflags & DMU_BACKUP_FEATURE_ZSTD)))
851 		return (B_FALSE);
852 
853 	/*
854 	 * Embed type must be explicitly enabled.
855 	 */
856 	switch (BPE_GET_ETYPE(bp)) {
857 	case BP_EMBEDDED_TYPE_DATA:
858 		if (featureflags & DMU_BACKUP_FEATURE_EMBED_DATA)
859 			return (B_TRUE);
860 		break;
861 	default:
862 		return (B_FALSE);
863 	}
864 	return (B_FALSE);
865 }
866 
867 /*
868  * This function actually handles figuring out what kind of record needs to be
869  * dumped, and calling the appropriate helper function.  In most cases,
870  * the data has already been read by send_reader_thread().
871  */
872 static int
do_dump(dmu_send_cookie_t * dscp,struct send_range * range)873 do_dump(dmu_send_cookie_t *dscp, struct send_range *range)
874 {
875 	int err = 0;
876 	switch (range->type) {
877 	case OBJECT:
878 		err = dump_dnode(dscp, &range->sru.object.bp, range->object,
879 		    range->sru.object.dnp);
880 		/* Dump piggybacked unmodified spill block */
881 		if (!err && range->sru.object.spill_range)
882 			err = do_dump(dscp, range->sru.object.spill_range);
883 		return (err);
884 	case OBJECT_RANGE: {
885 		ASSERT3U(range->start_blkid + 1, ==, range->end_blkid);
886 		if (!(dscp->dsc_featureflags & DMU_BACKUP_FEATURE_RAW)) {
887 			return (0);
888 		}
889 		uint64_t epb = BP_GET_LSIZE(&range->sru.object_range.bp) >>
890 		    DNODE_SHIFT;
891 		uint64_t firstobj = range->start_blkid * epb;
892 		err = dump_object_range(dscp, &range->sru.object_range.bp,
893 		    firstobj, epb);
894 		break;
895 	}
896 	case REDACT: {
897 		struct srr *srrp = &range->sru.redact;
898 		err = dump_redact(dscp, range->object, range->start_blkid *
899 		    srrp->datablksz, (range->end_blkid - range->start_blkid) *
900 		    srrp->datablksz);
901 		return (err);
902 	}
903 	case DATA: {
904 		struct srd *srdp = &range->sru.data;
905 		blkptr_t *bp = &srdp->bp;
906 		spa_t *spa =
907 		    dmu_objset_spa(dscp->dsc_os);
908 
909 		ASSERT3U(srdp->datablksz, ==, BP_GET_LSIZE(bp));
910 		ASSERT3U(range->start_blkid + 1, ==, range->end_blkid);
911 
912 		if (send_do_embed(bp, dscp->dsc_featureflags)) {
913 			err = dump_write_embedded(dscp, range->object,
914 			    range->start_blkid * srdp->datablksz,
915 			    srdp->datablksz, bp);
916 			return (err);
917 		}
918 		ASSERT(range->object > dscp->dsc_resume_object ||
919 		    (range->object == dscp->dsc_resume_object &&
920 		    (range->start_blkid == DMU_SPILL_BLKID ||
921 		    range->start_blkid * srdp->datablksz >=
922 		    dscp->dsc_resume_offset)));
923 		/* it's a level-0 block of a regular object */
924 
925 		mutex_enter(&srdp->lock);
926 		while (srdp->io_outstanding)
927 			cv_wait(&srdp->cv, &srdp->lock);
928 		err = srdp->io_err;
929 		mutex_exit(&srdp->lock);
930 
931 		if (err != 0) {
932 			if (zfs_send_corrupt_data &&
933 			    !dscp->dsc_dso->dso_dryrun) {
934 				/*
935 				 * Send a block filled with 0x"zfs badd bloc"
936 				 */
937 				srdp->abuf = arc_alloc_buf(spa, &srdp->abuf,
938 				    ARC_BUFC_DATA, srdp->datablksz);
939 				uint64_t *ptr;
940 				for (ptr = srdp->abuf->b_data;
941 				    (char *)ptr < (char *)srdp->abuf->b_data +
942 				    srdp->datablksz; ptr++)
943 					*ptr = 0x2f5baddb10cULL;
944 			} else {
945 				return (SET_ERROR(EIO));
946 			}
947 		}
948 
949 		ASSERT(dscp->dsc_dso->dso_dryrun ||
950 		    srdp->abuf != NULL || srdp->abd != NULL);
951 
952 		char *data = NULL;
953 		if (srdp->abd != NULL) {
954 			data = abd_to_buf(srdp->abd);
955 			ASSERT0P(srdp->abuf);
956 		} else if (srdp->abuf != NULL) {
957 			data = srdp->abuf->b_data;
958 		}
959 
960 		if (BP_GET_TYPE(bp) == DMU_OT_SA) {
961 			ASSERT3U(range->start_blkid, ==, DMU_SPILL_BLKID);
962 			err = dump_spill(dscp, bp, range->object, data);
963 			return (err);
964 		}
965 
966 		uint64_t offset = range->start_blkid * srdp->datablksz;
967 
968 		/*
969 		 * If we have large blocks stored on disk but the send flags
970 		 * don't allow us to send large blocks, we split the data from
971 		 * the arc buf into chunks.
972 		 */
973 		if (srdp->datablksz > SPA_OLD_MAXBLOCKSIZE &&
974 		    !(dscp->dsc_featureflags &
975 		    DMU_BACKUP_FEATURE_LARGE_BLOCKS)) {
976 			while (srdp->datablksz > 0 && err == 0) {
977 				int n = MIN(srdp->datablksz,
978 				    SPA_OLD_MAXBLOCKSIZE);
979 				err = dmu_dump_write(dscp, srdp->obj_type,
980 				    range->object, offset, n, n, NULL, B_FALSE,
981 				    data);
982 				offset += n;
983 				/*
984 				 * When doing dry run, data==NULL is used as a
985 				 * sentinel value by
986 				 * dmu_dump_write()->dump_record().
987 				 */
988 				if (data != NULL)
989 					data += n;
990 				srdp->datablksz -= n;
991 			}
992 		} else {
993 			err = dmu_dump_write(dscp, srdp->obj_type,
994 			    range->object, offset,
995 			    srdp->datablksz, srdp->datasz, bp,
996 			    srdp->io_compressed, data);
997 		}
998 		return (err);
999 	}
1000 	case HOLE: {
1001 		struct srh *srhp = &range->sru.hole;
1002 		if (range->object == DMU_META_DNODE_OBJECT) {
1003 			uint32_t span = srhp->datablksz >> DNODE_SHIFT;
1004 			uint64_t first_obj = range->start_blkid * span;
1005 			uint64_t numobj = range->end_blkid * span - first_obj;
1006 			return (dump_freeobjects(dscp, first_obj, numobj));
1007 		}
1008 		uint64_t offset = 0;
1009 
1010 		/*
1011 		 * If this multiply overflows, we don't need to send this block.
1012 		 * Even if it has a birth time, it can never not be a hole, so
1013 		 * we don't need to send records for it.
1014 		 */
1015 		if (!overflow_multiply(range->start_blkid, srhp->datablksz,
1016 		    &offset)) {
1017 			return (0);
1018 		}
1019 		uint64_t len = 0;
1020 
1021 		if (!overflow_multiply(range->end_blkid, srhp->datablksz, &len))
1022 			len = UINT64_MAX;
1023 		len = len - offset;
1024 		return (dump_free(dscp, range->object, offset, len));
1025 	}
1026 	default:
1027 		panic("Invalid range type in do_dump: %d", range->type);
1028 	}
1029 	return (err);
1030 }
1031 
1032 static struct send_range *
range_alloc(enum type type,uint64_t object,uint64_t start_blkid,uint64_t end_blkid,boolean_t eos)1033 range_alloc(enum type type, uint64_t object, uint64_t start_blkid,
1034     uint64_t end_blkid, boolean_t eos)
1035 {
1036 	struct send_range *range = kmem_alloc(sizeof (*range), KM_SLEEP);
1037 	range->type = type;
1038 	range->object = object;
1039 	range->start_blkid = start_blkid;
1040 	range->end_blkid = end_blkid;
1041 	range->eos_marker = eos;
1042 	if (type == DATA) {
1043 		range->sru.data.abd = NULL;
1044 		range->sru.data.abuf = NULL;
1045 		mutex_init(&range->sru.data.lock, NULL, MUTEX_DEFAULT, NULL);
1046 		cv_init(&range->sru.data.cv, NULL, CV_DEFAULT, NULL);
1047 		range->sru.data.io_outstanding = 0;
1048 		range->sru.data.io_err = 0;
1049 		range->sru.data.io_compressed = B_FALSE;
1050 	} else if (type == OBJECT) {
1051 		range->sru.object.spill_range = NULL;
1052 	}
1053 	return (range);
1054 }
1055 
1056 /*
1057  * This is the callback function to traverse_dataset that acts as a worker
1058  * thread for dmu_send_impl.
1059  */
1060 static int
send_cb(spa_t * spa,zilog_t * zilog,const blkptr_t * bp,const zbookmark_phys_t * zb,const struct dnode_phys * dnp,void * arg)1061 send_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
1062     const zbookmark_phys_t *zb, const struct dnode_phys *dnp, void *arg)
1063 {
1064 	(void) zilog;
1065 	struct send_thread_arg *sta = arg;
1066 	struct send_range *record;
1067 
1068 	ASSERT(zb->zb_object == DMU_META_DNODE_OBJECT ||
1069 	    zb->zb_object >= sta->resume.zb_object);
1070 
1071 	/*
1072 	 * All bps of an encrypted os should have the encryption bit set.
1073 	 * If this is not true it indicates tampering and we report an error.
1074 	 */
1075 	if (sta->os->os_encrypted &&
1076 	    !BP_IS_HOLE(bp) && !BP_USES_CRYPT(bp)) {
1077 		spa_log_error(spa, zb, BP_GET_PHYSICAL_BIRTH(bp));
1078 		return (SET_ERROR(EIO));
1079 	}
1080 
1081 	if (sta->cancel)
1082 		return (SET_ERROR(EINTR));
1083 	if (zb->zb_object != DMU_META_DNODE_OBJECT &&
1084 	    DMU_OBJECT_IS_SPECIAL(zb->zb_object))
1085 		return (0);
1086 	atomic_inc_64(sta->num_blocks_visited);
1087 
1088 	if (zb->zb_level == ZB_DNODE_LEVEL) {
1089 		if (zb->zb_object == DMU_META_DNODE_OBJECT)
1090 			return (0);
1091 		record = range_alloc(OBJECT, zb->zb_object, 0, 0, B_FALSE);
1092 		record->sru.object.bp = *bp;
1093 		size_t size  = sizeof (*dnp) * (dnp->dn_extra_slots + 1);
1094 		record->sru.object.dnp = kmem_alloc(size, KM_SLEEP);
1095 		memcpy(record->sru.object.dnp, dnp, size);
1096 		bqueue_enqueue(&sta->q, record, sizeof (*record));
1097 		return (0);
1098 	}
1099 	if (zb->zb_level == 0 && zb->zb_object == DMU_META_DNODE_OBJECT &&
1100 	    !BP_IS_HOLE(bp)) {
1101 		record = range_alloc(OBJECT_RANGE, 0, zb->zb_blkid,
1102 		    zb->zb_blkid + 1, B_FALSE);
1103 		record->sru.object_range.bp = *bp;
1104 		bqueue_enqueue(&sta->q, record, sizeof (*record));
1105 		return (0);
1106 	}
1107 	if (zb->zb_level < 0 || (zb->zb_level > 0 && !BP_IS_HOLE(bp)))
1108 		return (0);
1109 	if (zb->zb_object == DMU_META_DNODE_OBJECT && !BP_IS_HOLE(bp))
1110 		return (0);
1111 
1112 	uint64_t span = bp_span_in_blocks(dnp->dn_indblkshift, zb->zb_level);
1113 	uint64_t start;
1114 
1115 	/*
1116 	 * If this multiply overflows, we don't need to send this block.
1117 	 * Even if it has a birth time, it can never not be a hole, so
1118 	 * we don't need to send records for it.
1119 	 */
1120 	if (!overflow_multiply(span, zb->zb_blkid, &start) || (!(zb->zb_blkid ==
1121 	    DMU_SPILL_BLKID || DMU_OT_IS_METADATA(dnp->dn_type)) &&
1122 	    span * zb->zb_blkid > dnp->dn_maxblkid)) {
1123 		ASSERT(BP_IS_HOLE(bp));
1124 		return (0);
1125 	}
1126 
1127 	if (zb->zb_blkid == DMU_SPILL_BLKID)
1128 		ASSERT3U(BP_GET_TYPE(bp), ==, DMU_OT_SA);
1129 
1130 	enum type record_type = DATA;
1131 	if (BP_IS_HOLE(bp))
1132 		record_type = HOLE;
1133 	else if (BP_IS_REDACTED(bp))
1134 		record_type = REDACT;
1135 	else
1136 		record_type = DATA;
1137 
1138 	record = range_alloc(record_type, zb->zb_object, start,
1139 	    (start + span < start ? 0 : start + span), B_FALSE);
1140 
1141 	uint64_t datablksz = (zb->zb_blkid == DMU_SPILL_BLKID ?
1142 	    BP_GET_LSIZE(bp) : dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT);
1143 
1144 	if (BP_IS_HOLE(bp)) {
1145 		record->sru.hole.datablksz = datablksz;
1146 	} else if (BP_IS_REDACTED(bp)) {
1147 		record->sru.redact.datablksz = datablksz;
1148 	} else {
1149 		record->sru.data.datablksz = datablksz;
1150 		record->sru.data.obj_type = dnp->dn_type;
1151 		record->sru.data.bp = *bp;
1152 	}
1153 
1154 	bqueue_enqueue(&sta->q, record, sizeof (*record));
1155 	return (0);
1156 }
1157 
1158 struct redact_list_cb_arg {
1159 	uint64_t *num_blocks_visited;
1160 	bqueue_t *q;
1161 	boolean_t *cancel;
1162 	boolean_t mark_redact;
1163 };
1164 
1165 static int
redact_list_cb(redact_block_phys_t * rb,void * arg)1166 redact_list_cb(redact_block_phys_t *rb, void *arg)
1167 {
1168 	struct redact_list_cb_arg *rlcap = arg;
1169 
1170 	atomic_inc_64(rlcap->num_blocks_visited);
1171 	if (*rlcap->cancel)
1172 		return (-1);
1173 
1174 	struct send_range *data = range_alloc(REDACT, rb->rbp_object,
1175 	    rb->rbp_blkid, rb->rbp_blkid + redact_block_get_count(rb), B_FALSE);
1176 	ASSERT3U(data->end_blkid, >, rb->rbp_blkid);
1177 	if (rlcap->mark_redact) {
1178 		data->type = REDACT;
1179 		data->sru.redact.datablksz = redact_block_get_size(rb);
1180 	} else {
1181 		data->type = PREVIOUSLY_REDACTED;
1182 	}
1183 	bqueue_enqueue(rlcap->q, data, sizeof (*data));
1184 
1185 	return (0);
1186 }
1187 
1188 /*
1189  * This function kicks off the traverse_dataset.  It also handles setting the
1190  * error code of the thread in case something goes wrong, and pushes the End of
1191  * Stream record when the traverse_dataset call has finished.
1192  */
1193 static __attribute__((noreturn)) void
send_traverse_thread(void * arg)1194 send_traverse_thread(void *arg)
1195 {
1196 	struct send_thread_arg *st_arg = arg;
1197 	int err = 0;
1198 	struct send_range *data;
1199 	fstrans_cookie_t cookie = spl_fstrans_mark();
1200 
1201 	err = traverse_dataset_resume(st_arg->os->os_dsl_dataset,
1202 	    st_arg->fromtxg, &st_arg->resume,
1203 	    st_arg->flags | TRAVERSE_LOGICAL, send_cb, st_arg);
1204 
1205 	if (err != EINTR)
1206 		st_arg->error_code = err;
1207 	data = range_alloc(DATA, 0, 0, 0, B_TRUE);
1208 	bqueue_enqueue_flush(&st_arg->q, data, sizeof (*data));
1209 	spl_fstrans_unmark(cookie);
1210 	thread_exit();
1211 }
1212 
1213 /*
1214  * Utility function that causes End of Stream records to compare after of all
1215  * others, so that other threads' comparison logic can stay simple.
1216  */
1217 static int __attribute__((unused))
send_range_after(const struct send_range * from,const struct send_range * to)1218 send_range_after(const struct send_range *from, const struct send_range *to)
1219 {
1220 	if (from->eos_marker == B_TRUE)
1221 		return (1);
1222 	if (to->eos_marker == B_TRUE)
1223 		return (-1);
1224 
1225 	uint64_t from_obj = from->object;
1226 	uint64_t from_end_obj = from->object + 1;
1227 	uint64_t to_obj = to->object;
1228 	uint64_t to_end_obj = to->object + 1;
1229 	if (from_obj == 0) {
1230 		ASSERT(from->type == HOLE || from->type == OBJECT_RANGE);
1231 		from_obj = from->start_blkid << DNODES_PER_BLOCK_SHIFT;
1232 		from_end_obj = from->end_blkid << DNODES_PER_BLOCK_SHIFT;
1233 	}
1234 	if (to_obj == 0) {
1235 		ASSERT(to->type == HOLE || to->type == OBJECT_RANGE);
1236 		to_obj = to->start_blkid << DNODES_PER_BLOCK_SHIFT;
1237 		to_end_obj = to->end_blkid << DNODES_PER_BLOCK_SHIFT;
1238 	}
1239 
1240 	if (from_end_obj <= to_obj)
1241 		return (-1);
1242 	if (from_obj >= to_end_obj)
1243 		return (1);
1244 	int64_t cmp = TREE_CMP(to->type == OBJECT_RANGE, from->type ==
1245 	    OBJECT_RANGE);
1246 	if (unlikely(cmp))
1247 		return (cmp);
1248 	cmp = TREE_CMP(to->type == OBJECT, from->type == OBJECT);
1249 	if (unlikely(cmp))
1250 		return (cmp);
1251 	/*
1252 	 * A meta-dnode range and an ordinary object's range express their
1253 	 * blkids in different units, dnode blocks against that object's data
1254 	 * blocks, so the blkid comparisons below cannot be applied to them.
1255 	 * Reaching here means their object ranges overlap; the meta-dnode
1256 	 * range sorts before the ranges of every object it covers, which is
1257 	 * the order send_range_start_compare() also establishes.
1258 	 */
1259 	cmp = TREE_CMP(to->object == 0, from->object == 0);
1260 	if (unlikely(cmp))
1261 		return (cmp);
1262 	if (from->end_blkid <= to->start_blkid)
1263 		return (-1);
1264 	if (from->start_blkid >= to->end_blkid)
1265 		return (1);
1266 	return (0);
1267 }
1268 
1269 /*
1270  * Pop the new data off the queue, check that the records we receive are in
1271  * the right order, but do not free the old data.  This is used so that the
1272  * records can be sent on to the main thread without copying the data.
1273  */
1274 static struct send_range *
get_next_range_nofree(bqueue_t * bq,struct send_range * prev)1275 get_next_range_nofree(bqueue_t *bq, struct send_range *prev)
1276 {
1277 	struct send_range *next = bqueue_dequeue(bq);
1278 	ASSERT3S(send_range_after(prev, next), ==, -1);
1279 	return (next);
1280 }
1281 
1282 /*
1283  * Pop the new data off the queue, check that the records we receive are in
1284  * the right order, and free the old data.
1285  */
1286 static struct send_range *
get_next_range(bqueue_t * bq,struct send_range * prev)1287 get_next_range(bqueue_t *bq, struct send_range *prev)
1288 {
1289 	struct send_range *next = get_next_range_nofree(bq, prev);
1290 	range_free(prev);
1291 	return (next);
1292 }
1293 
1294 static __attribute__((noreturn)) void
redact_list_thread(void * arg)1295 redact_list_thread(void *arg)
1296 {
1297 	struct redact_list_thread_arg *rlt_arg = arg;
1298 	struct send_range *record;
1299 	fstrans_cookie_t cookie = spl_fstrans_mark();
1300 	if (rlt_arg->rl != NULL) {
1301 		struct redact_list_cb_arg rlcba = {0};
1302 		rlcba.cancel = &rlt_arg->cancel;
1303 		rlcba.q = &rlt_arg->q;
1304 		rlcba.num_blocks_visited = rlt_arg->num_blocks_visited;
1305 		rlcba.mark_redact = rlt_arg->mark_redact;
1306 		int err = dsl_redaction_list_traverse(rlt_arg->rl,
1307 		    &rlt_arg->resume, redact_list_cb, &rlcba);
1308 		if (err != EINTR)
1309 			rlt_arg->error_code = err;
1310 	}
1311 	record = range_alloc(DATA, 0, 0, 0, B_TRUE);
1312 	bqueue_enqueue_flush(&rlt_arg->q, record, sizeof (*record));
1313 	spl_fstrans_unmark(cookie);
1314 
1315 	thread_exit();
1316 }
1317 
1318 /*
1319  * Compare the start point of the two provided ranges. End of stream ranges
1320  * compare last, objects compare before any data or hole inside that object and
1321  * multi-object holes that start at the same object.
1322  */
1323 static int
send_range_start_compare(struct send_range * r1,struct send_range * r2)1324 send_range_start_compare(struct send_range *r1, struct send_range *r2)
1325 {
1326 	uint64_t r1_objequiv = r1->object;
1327 	uint64_t r1_l0equiv = r1->start_blkid;
1328 	uint64_t r2_objequiv = r2->object;
1329 	uint64_t r2_l0equiv = r2->start_blkid;
1330 	int64_t cmp = TREE_CMP(r1->eos_marker, r2->eos_marker);
1331 	if (unlikely(cmp))
1332 		return (cmp);
1333 	if (r1->object == 0) {
1334 		r1_objequiv = r1->start_blkid * DNODES_PER_BLOCK;
1335 		r1_l0equiv = 0;
1336 	}
1337 	if (r2->object == 0) {
1338 		r2_objequiv = r2->start_blkid * DNODES_PER_BLOCK;
1339 		r2_l0equiv = 0;
1340 	}
1341 
1342 	cmp = TREE_CMP(r1_objequiv, r2_objequiv);
1343 	if (likely(cmp))
1344 		return (cmp);
1345 	cmp = TREE_CMP(r2->type == OBJECT_RANGE, r1->type == OBJECT_RANGE);
1346 	if (unlikely(cmp))
1347 		return (cmp);
1348 	cmp = TREE_CMP(r2->type == OBJECT, r1->type == OBJECT);
1349 	if (unlikely(cmp))
1350 		return (cmp);
1351 	/*
1352 	 * A meta-dnode range covering dnode block b has the same objequiv as
1353 	 * the first block of object b * DNODES_PER_BLOCK, but the two do not
1354 	 * start at the same place: their blkids count different things.  The
1355 	 * merge in find_next_range() may only treat ranges as starting
1356 	 * together when they genuinely share an object and a block, so order
1357 	 * the meta-dnode range first rather than reporting them equal.
1358 	 */
1359 	cmp = TREE_CMP(r2->object == 0, r1->object == 0);
1360 	if (unlikely(cmp))
1361 		return (cmp);
1362 
1363 	return (TREE_CMP(r1_l0equiv, r2_l0equiv));
1364 }
1365 
1366 enum q_idx {
1367 	REDACT_IDX = 0,
1368 	TO_IDX,
1369 	FROM_IDX,
1370 	NUM_THREADS
1371 };
1372 
1373 /*
1374  * This function returns the next range the send_merge_thread should operate on.
1375  * The inputs are two arrays; the first one stores the range at the front of the
1376  * queues stored in the second one.  The ranges are sorted in descending
1377  * priority order; the metadata from earlier ranges overrules metadata from
1378  * later ranges.  out_mask is used to return which threads the ranges came from;
1379  * bit i is set if ranges[i] started at the same place as the returned range.
1380  *
1381  * This code is not hardcoded to compare a specific number of threads; it could
1382  * be used with any number, just by changing the q_idx enum.
1383  *
1384  * The "next range" is the one with the earliest start; if two starts are equal,
1385  * the highest-priority range is the next to operate on.  If a higher-priority
1386  * range starts in the middle of the first range, then the first range will be
1387  * truncated to end where the higher-priority range starts, and we will operate
1388  * on that one next time.   In this way, we make sure that each block covered by
1389  * some range gets covered by a returned range, and each block covered is
1390  * returned using the metadata of the highest-priority range it appears in.
1391  *
1392  * For example, if the three ranges at the front of the queues were [2,4),
1393  * [3,5), and [1,3), then the ranges returned would be [1,2) with the metadata
1394  * from the third range, [2,4) with the metadata from the first range, and then
1395  * [4,5) with the metadata from the second.
1396  */
1397 static struct send_range *
find_next_range(struct send_range ** ranges,bqueue_t ** qs,uint64_t * out_mask)1398 find_next_range(struct send_range **ranges, bqueue_t **qs, uint64_t *out_mask)
1399 {
1400 	int idx = 0; // index of the range with the earliest start
1401 	int i;
1402 	uint64_t bmask = 0;
1403 	for (i = 1; i < NUM_THREADS; i++) {
1404 		if (send_range_start_compare(ranges[i], ranges[idx]) < 0)
1405 			idx = i;
1406 	}
1407 	if (ranges[idx]->eos_marker) {
1408 		struct send_range *ret = range_alloc(DATA, 0, 0, 0, B_TRUE);
1409 		*out_mask = 0;
1410 		return (ret);
1411 	}
1412 	/*
1413 	 * Find all the ranges that start at that same point.
1414 	 */
1415 	for (i = 0; i < NUM_THREADS; i++) {
1416 		if (send_range_start_compare(ranges[i], ranges[idx]) == 0)
1417 			bmask |= 1 << i;
1418 	}
1419 	*out_mask = bmask;
1420 	/*
1421 	 * OBJECT_RANGE records only come from the TO thread, and should always
1422 	 * be treated as overlapping with nothing and sent on immediately.  They
1423 	 * are only used in raw sends, and are never redacted.
1424 	 */
1425 	if (ranges[idx]->type == OBJECT_RANGE) {
1426 		ASSERT3U(idx, ==, TO_IDX);
1427 		ASSERT3U(*out_mask, ==, 1 << TO_IDX);
1428 		struct send_range *ret = ranges[idx];
1429 		ranges[idx] = get_next_range_nofree(qs[idx], ranges[idx]);
1430 		return (ret);
1431 	}
1432 	/*
1433 	 * Find the first start or end point after the start of the first range.
1434 	 */
1435 	uint64_t first_change = ranges[idx]->end_blkid;
1436 	for (i = 0; i < NUM_THREADS; i++) {
1437 		if (i == idx || ranges[i]->eos_marker ||
1438 		    ranges[i]->object > ranges[idx]->object ||
1439 		    ranges[i]->object == DMU_META_DNODE_OBJECT)
1440 			continue;
1441 		ASSERT3U(ranges[i]->object, ==, ranges[idx]->object);
1442 		if (first_change > ranges[i]->start_blkid &&
1443 		    (bmask & (1 << i)) == 0)
1444 			first_change = ranges[i]->start_blkid;
1445 		else if (first_change > ranges[i]->end_blkid)
1446 			first_change = ranges[i]->end_blkid;
1447 	}
1448 	/*
1449 	 * Update all ranges to no longer overlap with the range we're
1450 	 * returning. All such ranges must start at the same place as the range
1451 	 * being returned, and end at or after first_change. Thus we update
1452 	 * their start to first_change. If that makes them size 0, then free
1453 	 * them and pull a new range from that thread.
1454 	 */
1455 	for (i = 0; i < NUM_THREADS; i++) {
1456 		if (i == idx || (bmask & (1 << i)) == 0)
1457 			continue;
1458 		ASSERT3U(ranges[i]->object, ==, ranges[idx]->object);
1459 		ASSERT3U(first_change, >, ranges[i]->start_blkid);
1460 		ranges[i]->start_blkid = first_change;
1461 		ASSERT3U(ranges[i]->start_blkid, <=, ranges[i]->end_blkid);
1462 		if (ranges[i]->start_blkid == ranges[i]->end_blkid)
1463 			ranges[i] = get_next_range(qs[i], ranges[i]);
1464 	}
1465 	/*
1466 	 * Short-circuit the simple case; if the range doesn't overlap with
1467 	 * anything else, or it only overlaps with things that start at the same
1468 	 * place and are longer, send it on.
1469 	 */
1470 	if (first_change == ranges[idx]->end_blkid) {
1471 		struct send_range *ret = ranges[idx];
1472 		ranges[idx] = get_next_range_nofree(qs[idx], ranges[idx]);
1473 		return (ret);
1474 	}
1475 
1476 	/*
1477 	 * Otherwise, return a truncated copy of ranges[idx] and move the start
1478 	 * of ranges[idx] back to first_change.
1479 	 */
1480 	struct send_range *ret = kmem_alloc(sizeof (*ret), KM_SLEEP);
1481 	*ret = *ranges[idx];
1482 	ret->end_blkid = first_change;
1483 	ranges[idx]->start_blkid = first_change;
1484 	return (ret);
1485 }
1486 
1487 #define	FROM_AND_REDACT_BITS ((1 << REDACT_IDX) | (1 << FROM_IDX))
1488 
1489 /*
1490  * Merge the results from the from thread and the to thread, and then hand the
1491  * records off to send_prefetch_thread to prefetch them.  If this is not a
1492  * send from a redaction bookmark, the from thread will push an end of stream
1493  * record and stop, and we'll just send everything that was changed in the
1494  * to_ds since the ancestor's creation txg. If it is, then since
1495  * traverse_dataset has a canonical order, we can compare each change as
1496  * they're pulled off the queues.  That will give us a stream that is
1497  * appropriately sorted, and covers all records.  In addition, we pull the
1498  * data from the redact_list_thread and use that to determine which blocks
1499  * should be redacted.
1500  */
1501 static __attribute__((noreturn)) void
send_merge_thread(void * arg)1502 send_merge_thread(void *arg)
1503 {
1504 	struct send_merge_thread_arg *smt_arg = arg;
1505 	struct send_range *front_ranges[NUM_THREADS];
1506 	bqueue_t *queues[NUM_THREADS];
1507 	int err = 0;
1508 	fstrans_cookie_t cookie = spl_fstrans_mark();
1509 
1510 	if (smt_arg->redact_arg == NULL) {
1511 		front_ranges[REDACT_IDX] =
1512 		    kmem_zalloc(sizeof (struct send_range), KM_SLEEP);
1513 		front_ranges[REDACT_IDX]->eos_marker = B_TRUE;
1514 		front_ranges[REDACT_IDX]->type = REDACT;
1515 		queues[REDACT_IDX] = NULL;
1516 	} else {
1517 		front_ranges[REDACT_IDX] =
1518 		    bqueue_dequeue(&smt_arg->redact_arg->q);
1519 		queues[REDACT_IDX] = &smt_arg->redact_arg->q;
1520 	}
1521 	front_ranges[TO_IDX] = bqueue_dequeue(&smt_arg->to_arg->q);
1522 	queues[TO_IDX] = &smt_arg->to_arg->q;
1523 	front_ranges[FROM_IDX] = bqueue_dequeue(&smt_arg->from_arg->q);
1524 	queues[FROM_IDX] = &smt_arg->from_arg->q;
1525 	uint64_t mask = 0;
1526 	struct send_range *range;
1527 	for (range = find_next_range(front_ranges, queues, &mask);
1528 	    !range->eos_marker && err == 0 && !smt_arg->cancel;
1529 	    range = find_next_range(front_ranges, queues, &mask)) {
1530 		/*
1531 		 * If the range in question was in both the from redact bookmark
1532 		 * and the bookmark we're using to redact, then don't send it.
1533 		 * It's already redacted on the receiving system, so a redaction
1534 		 * record would be redundant.
1535 		 */
1536 		if ((mask & FROM_AND_REDACT_BITS) == FROM_AND_REDACT_BITS) {
1537 			ASSERT3U(range->type, ==, REDACT);
1538 			range_free(range);
1539 			continue;
1540 		}
1541 		bqueue_enqueue(&smt_arg->q, range, sizeof (*range));
1542 
1543 		if (smt_arg->to_arg->error_code != 0) {
1544 			err = smt_arg->to_arg->error_code;
1545 		} else if (smt_arg->from_arg->error_code != 0) {
1546 			err = smt_arg->from_arg->error_code;
1547 		} else if (smt_arg->redact_arg != NULL &&
1548 		    smt_arg->redact_arg->error_code != 0) {
1549 			err = smt_arg->redact_arg->error_code;
1550 		}
1551 	}
1552 	if (smt_arg->cancel && err == 0)
1553 		err = SET_ERROR(EINTR);
1554 	smt_arg->error = err;
1555 	if (smt_arg->error != 0) {
1556 		smt_arg->to_arg->cancel = B_TRUE;
1557 		smt_arg->from_arg->cancel = B_TRUE;
1558 		if (smt_arg->redact_arg != NULL)
1559 			smt_arg->redact_arg->cancel = B_TRUE;
1560 	}
1561 	for (int i = 0; i < NUM_THREADS; i++) {
1562 		while (!front_ranges[i]->eos_marker) {
1563 			front_ranges[i] = get_next_range(queues[i],
1564 			    front_ranges[i]);
1565 		}
1566 		range_free(front_ranges[i]);
1567 	}
1568 	range->eos_marker = B_TRUE;
1569 	bqueue_enqueue_flush(&smt_arg->q, range, 1);
1570 	spl_fstrans_unmark(cookie);
1571 	thread_exit();
1572 }
1573 
1574 struct send_reader_thread_arg {
1575 	struct send_merge_thread_arg *smta;
1576 	bqueue_t q;
1577 	boolean_t cancel;
1578 	boolean_t issue_reads;
1579 	uint64_t featureflags;
1580 	int error;
1581 };
1582 
1583 static void
dmu_send_read_done(zio_t * zio)1584 dmu_send_read_done(zio_t *zio)
1585 {
1586 	struct send_range *range = zio->io_private;
1587 
1588 	mutex_enter(&range->sru.data.lock);
1589 	if (zio->io_error != 0) {
1590 		abd_free(range->sru.data.abd);
1591 		range->sru.data.abd = NULL;
1592 		range->sru.data.io_err = zio->io_error;
1593 	}
1594 
1595 	ASSERT(range->sru.data.io_outstanding);
1596 	range->sru.data.io_outstanding = B_FALSE;
1597 	cv_broadcast(&range->sru.data.cv);
1598 	mutex_exit(&range->sru.data.lock);
1599 }
1600 
1601 static void
issue_data_read(struct send_reader_thread_arg * srta,struct send_range * range)1602 issue_data_read(struct send_reader_thread_arg *srta, struct send_range *range)
1603 {
1604 	struct srd *srdp = &range->sru.data;
1605 	blkptr_t *bp = &srdp->bp;
1606 	objset_t *os = srta->smta->os;
1607 
1608 	ASSERT3U(range->type, ==, DATA);
1609 	ASSERT3U(range->start_blkid + 1, ==, range->end_blkid);
1610 	/*
1611 	 * If we have large blocks stored on disk but
1612 	 * the send flags don't allow us to send large
1613 	 * blocks, we split the data from the arc buf
1614 	 * into chunks.
1615 	 */
1616 	boolean_t split_large_blocks =
1617 	    srdp->datablksz > SPA_OLD_MAXBLOCKSIZE &&
1618 	    !(srta->featureflags & DMU_BACKUP_FEATURE_LARGE_BLOCKS);
1619 	/*
1620 	 * We should only request compressed data from the ARC if all
1621 	 * the following are true:
1622 	 *  - stream compression was requested
1623 	 *  - we aren't splitting large blocks into smaller chunks
1624 	 *  - the data won't need to be byteswapped before sending
1625 	 *  - this isn't an embedded block
1626 	 *  - this isn't metadata (if receiving on a different endian
1627 	 *    system it can be byteswapped more easily)
1628 	 */
1629 	boolean_t request_compressed =
1630 	    (srta->featureflags & DMU_BACKUP_FEATURE_COMPRESSED) &&
1631 	    !split_large_blocks && !BP_SHOULD_BYTESWAP(bp) &&
1632 	    !BP_IS_EMBEDDED(bp) && !DMU_OT_IS_METADATA(BP_GET_TYPE(bp));
1633 
1634 	zio_flag_t zioflags = ZIO_FLAG_CANFAIL;
1635 
1636 	if (srta->featureflags & DMU_BACKUP_FEATURE_RAW) {
1637 		zioflags |= ZIO_FLAG_RAW;
1638 		srdp->io_compressed = B_TRUE;
1639 	} else if (request_compressed) {
1640 		zioflags |= ZIO_FLAG_RAW_COMPRESS;
1641 		srdp->io_compressed = B_TRUE;
1642 	}
1643 
1644 	srdp->datasz = (zioflags & ZIO_FLAG_RAW_COMPRESS) ?
1645 	    BP_GET_PSIZE(bp) : BP_GET_LSIZE(bp);
1646 
1647 	if (!srta->issue_reads)
1648 		return;
1649 	if (BP_IS_REDACTED(bp))
1650 		return;
1651 	if (send_do_embed(bp, srta->featureflags))
1652 		return;
1653 
1654 	zbookmark_phys_t zb = {
1655 	    .zb_objset = dmu_objset_id(os),
1656 	    .zb_object = range->object,
1657 	    .zb_level = 0,
1658 	    .zb_blkid = range->start_blkid,
1659 	};
1660 
1661 	arc_flags_t aflags = ARC_FLAG_CACHED_ONLY;
1662 
1663 	int arc_err = arc_read(NULL, os->os_spa, bp,
1664 	    arc_getbuf_func, &srdp->abuf, ZIO_PRIORITY_ASYNC_READ,
1665 	    zioflags, &aflags, &zb);
1666 	/*
1667 	 * If the data is not already cached in the ARC, we read directly
1668 	 * from zio.  This avoids the performance overhead of adding a new
1669 	 * entry to the ARC, and we also avoid polluting the ARC cache with
1670 	 * data that is not likely to be used in the future.
1671 	 */
1672 	if (arc_err != 0) {
1673 		srdp->abd = abd_alloc_linear(srdp->datasz, B_FALSE);
1674 		srdp->io_outstanding = B_TRUE;
1675 		zio_nowait(zio_read(NULL, os->os_spa, bp, srdp->abd,
1676 		    srdp->datasz, dmu_send_read_done, range,
1677 		    ZIO_PRIORITY_ASYNC_READ, zioflags, &zb));
1678 	}
1679 }
1680 
1681 /*
1682  * Create a new record with the given values.
1683  */
1684 static void
enqueue_range(struct send_reader_thread_arg * srta,bqueue_t * q,dnode_t * dn,uint64_t blkid,uint64_t count,const blkptr_t * bp,uint32_t datablksz)1685 enqueue_range(struct send_reader_thread_arg *srta, bqueue_t *q, dnode_t *dn,
1686     uint64_t blkid, uint64_t count, const blkptr_t *bp, uint32_t datablksz)
1687 {
1688 	enum type range_type = (bp == NULL || BP_IS_HOLE(bp) ? HOLE :
1689 	    (BP_IS_REDACTED(bp) ? REDACT : DATA));
1690 
1691 	struct send_range *range = range_alloc(range_type, dn->dn_object,
1692 	    blkid, blkid + count, B_FALSE);
1693 
1694 	if (blkid == DMU_SPILL_BLKID) {
1695 		ASSERT3P(bp, !=, NULL);
1696 		ASSERT3U(BP_GET_TYPE(bp), ==, DMU_OT_SA);
1697 	}
1698 
1699 	switch (range_type) {
1700 	case HOLE:
1701 		range->sru.hole.datablksz = datablksz;
1702 		break;
1703 	case DATA:
1704 		ASSERT3U(count, ==, 1);
1705 		range->sru.data.datablksz = datablksz;
1706 		range->sru.data.obj_type = dn->dn_type;
1707 		range->sru.data.bp = *bp;
1708 		issue_data_read(srta, range);
1709 		break;
1710 	case REDACT:
1711 		range->sru.redact.datablksz = datablksz;
1712 		break;
1713 	default:
1714 		break;
1715 	}
1716 	bqueue_enqueue(q, range, datablksz);
1717 }
1718 
1719 /*
1720  * Send DRR_SPILL records for unmodified spill blocks.	This is useful
1721  * because changing certain attributes of the object (e.g. blocksize)
1722  * can cause old versions of ZFS to incorrectly remove a spill block.
1723  * Including these records in the stream forces an up to date version
1724  * to always be written ensuring they're never lost.  Current versions
1725  * of the code which understand the DRR_FLAG_SPILL_BLOCK feature can
1726  * ignore these unmodified spill blocks.
1727  *
1728  * We piggyback the spill_range to dnode range instead of enqueueing it
1729  * so send_range_after won't complain.
1730  */
1731 static uint64_t
piggyback_unmodified_spill(struct send_reader_thread_arg * srta,struct send_range * range)1732 piggyback_unmodified_spill(struct send_reader_thread_arg *srta,
1733     struct send_range *range)
1734 {
1735 	ASSERT3U(range->type, ==, OBJECT);
1736 
1737 	dnode_phys_t *dnp = range->sru.object.dnp;
1738 	uint64_t fromtxg = srta->smta->to_arg->fromtxg;
1739 
1740 	if (!zfs_send_unmodified_spill_blocks ||
1741 	    !(dnp->dn_flags & DNODE_FLAG_SPILL_BLKPTR) ||
1742 	    !(BP_GET_LOGICAL_BIRTH(DN_SPILL_BLKPTR(dnp)) <= fromtxg))
1743 		return (0);
1744 
1745 	blkptr_t *bp = DN_SPILL_BLKPTR(dnp);
1746 	struct send_range *spill_range = range_alloc(DATA, range->object,
1747 	    DMU_SPILL_BLKID, DMU_SPILL_BLKID+1, B_FALSE);
1748 	spill_range->sru.data.bp = *bp;
1749 	spill_range->sru.data.obj_type = dnp->dn_type;
1750 	spill_range->sru.data.datablksz = BP_GET_LSIZE(bp);
1751 
1752 	issue_data_read(srta, spill_range);
1753 	range->sru.object.spill_range = spill_range;
1754 
1755 	return (BP_GET_LSIZE(bp));
1756 }
1757 
1758 /*
1759  * This thread is responsible for two things: First, it retrieves the correct
1760  * blkptr in the to ds if we need to send the data because of something from
1761  * the from thread.  As a result of this, we're the first ones to discover that
1762  * some indirect blocks can be discarded because they're not holes. Second,
1763  * it issues prefetches for the data we need to send.
1764  */
1765 static __attribute__((noreturn)) void
send_reader_thread(void * arg)1766 send_reader_thread(void *arg)
1767 {
1768 	struct send_reader_thread_arg *srta = arg;
1769 	struct send_merge_thread_arg *smta = srta->smta;
1770 	bqueue_t *inq = &smta->q;
1771 	bqueue_t *outq = &srta->q;
1772 	objset_t *os = smta->os;
1773 	fstrans_cookie_t cookie = spl_fstrans_mark();
1774 	struct send_range *range = bqueue_dequeue(inq);
1775 	int err = 0;
1776 
1777 	/*
1778 	 * If the record we're analyzing is from a redaction bookmark from the
1779 	 * fromds, then we need to know whether or not it exists in the tods so
1780 	 * we know whether to create records for it or not. If it does, we need
1781 	 * the datablksz so we can generate an appropriate record for it.
1782 	 * Finally, if it isn't redacted, we need the blkptr so that we can send
1783 	 * a WRITE record containing the actual data.
1784 	 */
1785 	uint64_t last_obj = UINT64_MAX;
1786 	uint64_t last_obj_exists = B_TRUE;
1787 	while (!range->eos_marker && !srta->cancel && smta->error == 0 &&
1788 	    err == 0) {
1789 		uint64_t spill = 0;
1790 		switch (range->type) {
1791 		case DATA:
1792 			issue_data_read(srta, range);
1793 			bqueue_enqueue(outq, range, range->sru.data.datablksz);
1794 			range = get_next_range_nofree(inq, range);
1795 			break;
1796 		case OBJECT:
1797 			spill = piggyback_unmodified_spill(srta, range);
1798 			zfs_fallthrough;
1799 		case HOLE:
1800 		case OBJECT_RANGE:
1801 		case REDACT: // Redacted blocks must exist
1802 			bqueue_enqueue(outq, range, sizeof (*range) + spill);
1803 			range = get_next_range_nofree(inq, range);
1804 			break;
1805 		case PREVIOUSLY_REDACTED: {
1806 			/*
1807 			 * This entry came from the "from bookmark" when
1808 			 * sending from a bookmark that has a redaction
1809 			 * list.  We need to check if this object/blkid
1810 			 * exists in the target ("to") dataset, and if
1811 			 * not then we drop this entry.  We also need
1812 			 * to fill in the block pointer so that we know
1813 			 * what to prefetch.
1814 			 *
1815 			 * To accomplish the above, we first cache whether or
1816 			 * not the last object we examined exists.  If it
1817 			 * doesn't, we can drop this record. If it does, we hold
1818 			 * the dnode and use it to call dbuf_dnode_findbp. We do
1819 			 * this instead of dbuf_bookmark_findbp because we will
1820 			 * often operate on large ranges, and holding the dnode
1821 			 * once is more efficient.
1822 			 */
1823 			boolean_t object_exists = B_TRUE;
1824 			/*
1825 			 * If the data is redacted, we only care if it exists,
1826 			 * so that we don't send records for objects that have
1827 			 * been deleted.
1828 			 */
1829 			dnode_t *dn;
1830 			if (range->object == last_obj && !last_obj_exists) {
1831 				/*
1832 				 * If we're still examining the same object as
1833 				 * previously, and it doesn't exist, we don't
1834 				 * need to call dbuf_bookmark_findbp.
1835 				 */
1836 				object_exists = B_FALSE;
1837 			} else {
1838 				err = dnode_hold(os, range->object, FTAG, &dn);
1839 				if (err == ENOENT) {
1840 					object_exists = B_FALSE;
1841 					err = 0;
1842 				}
1843 				last_obj = range->object;
1844 				last_obj_exists = object_exists;
1845 			}
1846 
1847 			if (err != 0) {
1848 				break;
1849 			} else if (!object_exists) {
1850 				/*
1851 				 * The block was modified, but doesn't
1852 				 * exist in the to dataset; if it was
1853 				 * deleted in the to dataset, then we'll
1854 				 * visit the hole bp for it at some point.
1855 				 */
1856 				range = get_next_range(inq, range);
1857 				continue;
1858 			}
1859 			uint64_t file_max =
1860 			    MIN(dn->dn_maxblkid + 1, range->end_blkid);
1861 			/*
1862 			 * The object exists, so we need to try to find the
1863 			 * blkptr for each block in the range we're processing.
1864 			 */
1865 			rw_enter(&dn->dn_struct_rwlock, RW_READER);
1866 			for (uint64_t blkid = range->start_blkid;
1867 			    blkid < file_max; blkid++) {
1868 				blkptr_t bp;
1869 				uint32_t datablksz =
1870 				    dn->dn_phys->dn_datablkszsec <<
1871 				    SPA_MINBLOCKSHIFT;
1872 				uint64_t offset = blkid * datablksz;
1873 				/*
1874 				 * This call finds the next non-hole block in
1875 				 * the object. This is to prevent a
1876 				 * performance problem where we're unredacting
1877 				 * a large hole. Using dnode_next_offset to
1878 				 * skip over the large hole avoids iterating
1879 				 * over every block in it.
1880 				 */
1881 				err = dnode_next_offset(dn, DNODE_FIND_HAVELOCK,
1882 				    &offset, 1, 1, 0);
1883 				if (err == ESRCH) {
1884 					offset = UINT64_MAX;
1885 					err = 0;
1886 				} else if (err != 0) {
1887 					break;
1888 				}
1889 				if (offset != blkid * datablksz) {
1890 					/*
1891 					 * if there is a hole from here
1892 					 * (blkid) to offset
1893 					 */
1894 					offset = MIN(offset, file_max *
1895 					    datablksz);
1896 					uint64_t nblks = (offset / datablksz) -
1897 					    blkid;
1898 					enqueue_range(srta, outq, dn, blkid,
1899 					    nblks, NULL, datablksz);
1900 					blkid += nblks;
1901 				}
1902 				if (blkid >= file_max)
1903 					break;
1904 				err = dbuf_dnode_findbp(dn, 0, blkid, &bp,
1905 				    NULL, NULL);
1906 				if (err != 0)
1907 					break;
1908 				ASSERT(!BP_IS_HOLE(&bp));
1909 				enqueue_range(srta, outq, dn, blkid, 1, &bp,
1910 				    datablksz);
1911 			}
1912 			rw_exit(&dn->dn_struct_rwlock);
1913 			dnode_rele(dn, FTAG);
1914 			range = get_next_range(inq, range);
1915 		}
1916 		}
1917 	}
1918 	if (srta->cancel || err != 0) {
1919 		smta->cancel = B_TRUE;
1920 		srta->error = err;
1921 	} else if (smta->error != 0) {
1922 		srta->error = smta->error;
1923 	}
1924 	while (!range->eos_marker)
1925 		range = get_next_range(inq, range);
1926 
1927 	bqueue_enqueue_flush(outq, range, 1);
1928 	spl_fstrans_unmark(cookie);
1929 	thread_exit();
1930 }
1931 
1932 #define	NUM_SNAPS_NOT_REDACTED UINT64_MAX
1933 
1934 struct dmu_send_params {
1935 	/* Pool args */
1936 	const void *tag; // Tag dp was held with, will be used to release dp.
1937 	dsl_pool_t *dp;
1938 	/* To snapshot args */
1939 	const char *tosnap;
1940 	dsl_dataset_t *to_ds;
1941 	/* From snapshot args */
1942 	zfs_bookmark_phys_t ancestor_zb;
1943 	uint64_t *fromredactsnaps;
1944 	/* NUM_SNAPS_NOT_REDACTED if not sending from redaction bookmark */
1945 	uint64_t numfromredactsnaps;
1946 	/* Stream params */
1947 	boolean_t is_clone;
1948 	boolean_t embedok;
1949 	boolean_t large_block_ok;
1950 	boolean_t compressok;
1951 	boolean_t rawok;
1952 	boolean_t savedok;
1953 	uint64_t resumeobj;
1954 	uint64_t resumeoff;
1955 	uint64_t saved_guid;
1956 	zfs_bookmark_phys_t *redactbook;
1957 	/* Stream output params */
1958 	dmu_send_outparams_t *dso;
1959 
1960 	/* Stream progress params */
1961 	offset_t *off;
1962 	int outfd;
1963 	char saved_toname[MAXNAMELEN];
1964 };
1965 
1966 static int
setup_featureflags(struct dmu_send_params * dspp,objset_t * os,uint64_t * featureflags)1967 setup_featureflags(struct dmu_send_params *dspp, objset_t *os,
1968     uint64_t *featureflags)
1969 {
1970 	dsl_dataset_t *to_ds = dspp->to_ds;
1971 	dsl_pool_t *dp = dspp->dp;
1972 
1973 	if (dmu_objset_type(os) == DMU_OST_ZFS) {
1974 		uint64_t version;
1975 		if (zfs_get_zplprop(os, ZFS_PROP_VERSION, &version) != 0)
1976 			return (SET_ERROR(EINVAL));
1977 
1978 		if (version >= ZPL_VERSION_SA)
1979 			*featureflags |= DMU_BACKUP_FEATURE_SA_SPILL;
1980 	}
1981 
1982 	/* raw sends imply large_block_ok */
1983 	if ((dspp->rawok || dspp->large_block_ok) &&
1984 	    dsl_dataset_feature_is_active(to_ds, SPA_FEATURE_LARGE_BLOCKS)) {
1985 		*featureflags |= DMU_BACKUP_FEATURE_LARGE_BLOCKS;
1986 	}
1987 
1988 	/* encrypted datasets will not have embedded blocks */
1989 	if ((dspp->embedok || dspp->rawok) && !os->os_encrypted &&
1990 	    spa_feature_is_active(dp->dp_spa, SPA_FEATURE_EMBEDDED_DATA)) {
1991 		*featureflags |= DMU_BACKUP_FEATURE_EMBED_DATA;
1992 	}
1993 
1994 	/* raw send implies compressok */
1995 	if (dspp->compressok || dspp->rawok)
1996 		*featureflags |= DMU_BACKUP_FEATURE_COMPRESSED;
1997 
1998 	if (dspp->rawok && os->os_encrypted)
1999 		*featureflags |= DMU_BACKUP_FEATURE_RAW;
2000 
2001 	if ((*featureflags &
2002 	    (DMU_BACKUP_FEATURE_EMBED_DATA | DMU_BACKUP_FEATURE_COMPRESSED |
2003 	    DMU_BACKUP_FEATURE_RAW)) != 0 &&
2004 	    spa_feature_is_active(dp->dp_spa, SPA_FEATURE_LZ4_COMPRESS)) {
2005 		*featureflags |= DMU_BACKUP_FEATURE_LZ4;
2006 	}
2007 
2008 	/*
2009 	 * We specifically do not include DMU_BACKUP_FEATURE_EMBED_DATA here to
2010 	 * allow sending ZSTD compressed datasets to a receiver that does not
2011 	 * support ZSTD
2012 	 */
2013 	if ((*featureflags &
2014 	    (DMU_BACKUP_FEATURE_COMPRESSED | DMU_BACKUP_FEATURE_RAW)) != 0 &&
2015 	    dsl_dataset_feature_is_active(to_ds, SPA_FEATURE_ZSTD_COMPRESS)) {
2016 		*featureflags |= DMU_BACKUP_FEATURE_ZSTD;
2017 	}
2018 
2019 	if (dspp->resumeobj != 0 || dspp->resumeoff != 0) {
2020 		*featureflags |= DMU_BACKUP_FEATURE_RESUMING;
2021 	}
2022 
2023 	if (dspp->redactbook != NULL) {
2024 		*featureflags |= DMU_BACKUP_FEATURE_REDACTED;
2025 	}
2026 
2027 	if (dsl_dataset_feature_is_active(to_ds, SPA_FEATURE_LARGE_DNODE)) {
2028 		*featureflags |= DMU_BACKUP_FEATURE_LARGE_DNODE;
2029 	}
2030 
2031 	if (dsl_dataset_feature_is_active(to_ds, SPA_FEATURE_LONGNAME)) {
2032 		*featureflags |= DMU_BACKUP_FEATURE_LONGNAME;
2033 	}
2034 
2035 	if (dsl_dataset_feature_is_active(to_ds, SPA_FEATURE_LARGE_MICROZAP)) {
2036 		/*
2037 		 * We must never split a large microzap block, so we can only
2038 		 * send large microzaps if LARGE_BLOCKS is already enabled.
2039 		 */
2040 		if (!(*featureflags & DMU_BACKUP_FEATURE_LARGE_BLOCKS))
2041 			return (SET_ERROR(ZFS_ERR_STREAM_LARGE_MICROZAP));
2042 		*featureflags |= DMU_BACKUP_FEATURE_LARGE_MICROZAP;
2043 	}
2044 
2045 	return (0);
2046 }
2047 
2048 static dmu_replay_record_t *
create_begin_record(struct dmu_send_params * dspp,objset_t * os,uint64_t featureflags)2049 create_begin_record(struct dmu_send_params *dspp, objset_t *os,
2050     uint64_t featureflags)
2051 {
2052 	dmu_replay_record_t *drr = kmem_zalloc(sizeof (dmu_replay_record_t),
2053 	    KM_SLEEP);
2054 	drr->drr_type = DRR_BEGIN;
2055 
2056 	struct drr_begin *drrb = &drr->drr_u.drr_begin;
2057 	dsl_dataset_t *to_ds = dspp->to_ds;
2058 
2059 	drrb->drr_magic = DMU_BACKUP_MAGIC;
2060 	drrb->drr_creation_time = dsl_dataset_phys(to_ds)->ds_creation_time;
2061 	drrb->drr_type = dmu_objset_type(os);
2062 	drrb->drr_toguid = dsl_dataset_phys(to_ds)->ds_guid;
2063 	drrb->drr_fromguid = dspp->ancestor_zb.zbm_guid;
2064 
2065 	DMU_SET_STREAM_HDRTYPE(drrb->drr_versioninfo, DMU_SUBSTREAM);
2066 	DMU_SET_FEATUREFLAGS(drrb->drr_versioninfo, featureflags);
2067 
2068 	if (dspp->is_clone)
2069 		drrb->drr_flags |= DRR_FLAG_CLONE;
2070 	if (dsl_dataset_phys(dspp->to_ds)->ds_flags & DS_FLAG_CI_DATASET)
2071 		drrb->drr_flags |= DRR_FLAG_CI_DATA;
2072 	if (zfs_send_set_freerecords_bit)
2073 		drrb->drr_flags |= DRR_FLAG_FREERECORDS;
2074 	drr->drr_u.drr_begin.drr_flags |= DRR_FLAG_SPILL_BLOCK;
2075 
2076 	if (dspp->savedok) {
2077 		drrb->drr_toguid = dspp->saved_guid;
2078 		strlcpy(drrb->drr_toname, dspp->saved_toname,
2079 		    sizeof (drrb->drr_toname));
2080 	} else {
2081 		dsl_dataset_name(to_ds, drrb->drr_toname);
2082 		if (!to_ds->ds_is_snapshot) {
2083 			(void) strlcat(drrb->drr_toname, "@--head--",
2084 			    sizeof (drrb->drr_toname));
2085 		}
2086 	}
2087 	return (drr);
2088 }
2089 
2090 static void
setup_to_thread(struct send_thread_arg * to_arg,objset_t * to_os,dmu_sendstatus_t * dssp,uint64_t fromtxg,boolean_t rawok)2091 setup_to_thread(struct send_thread_arg *to_arg, objset_t *to_os,
2092     dmu_sendstatus_t *dssp, uint64_t fromtxg, boolean_t rawok)
2093 {
2094 	VERIFY0(bqueue_init(&to_arg->q, zfs_send_no_prefetch_queue_ff,
2095 	    MAX(zfs_send_no_prefetch_queue_length, 2 * zfs_max_recordsize),
2096 	    offsetof(struct send_range, ln)));
2097 	to_arg->error_code = 0;
2098 	to_arg->cancel = B_FALSE;
2099 	to_arg->os = to_os;
2100 	to_arg->fromtxg = fromtxg;
2101 	to_arg->flags = TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA;
2102 	if (rawok)
2103 		to_arg->flags |= TRAVERSE_NO_DECRYPT;
2104 	if (zfs_send_corrupt_data)
2105 		to_arg->flags |= TRAVERSE_HARD;
2106 	to_arg->num_blocks_visited = &dssp->dss_blocks;
2107 	(void) thread_create(NULL, 0, send_traverse_thread, to_arg, 0,
2108 	    curproc, TS_RUN, minclsyspri);
2109 }
2110 
2111 static void
setup_from_thread(struct redact_list_thread_arg * from_arg,redaction_list_t * from_rl,dmu_sendstatus_t * dssp)2112 setup_from_thread(struct redact_list_thread_arg *from_arg,
2113     redaction_list_t *from_rl, dmu_sendstatus_t *dssp)
2114 {
2115 	VERIFY0(bqueue_init(&from_arg->q, zfs_send_no_prefetch_queue_ff,
2116 	    MAX(zfs_send_no_prefetch_queue_length, 2 * zfs_max_recordsize),
2117 	    offsetof(struct send_range, ln)));
2118 	from_arg->error_code = 0;
2119 	from_arg->cancel = B_FALSE;
2120 	from_arg->rl = from_rl;
2121 	from_arg->mark_redact = B_FALSE;
2122 	from_arg->num_blocks_visited = &dssp->dss_blocks;
2123 	/*
2124 	 * If from_ds is null, send_traverse_thread just returns success and
2125 	 * enqueues an eos marker.
2126 	 */
2127 	(void) thread_create(NULL, 0, redact_list_thread, from_arg, 0,
2128 	    curproc, TS_RUN, minclsyspri);
2129 }
2130 
2131 static void
setup_redact_list_thread(struct redact_list_thread_arg * rlt_arg,struct dmu_send_params * dspp,redaction_list_t * rl,dmu_sendstatus_t * dssp)2132 setup_redact_list_thread(struct redact_list_thread_arg *rlt_arg,
2133     struct dmu_send_params *dspp, redaction_list_t *rl, dmu_sendstatus_t *dssp)
2134 {
2135 	if (dspp->redactbook == NULL)
2136 		return;
2137 
2138 	rlt_arg->cancel = B_FALSE;
2139 	VERIFY0(bqueue_init(&rlt_arg->q, zfs_send_no_prefetch_queue_ff,
2140 	    MAX(zfs_send_no_prefetch_queue_length, 2 * zfs_max_recordsize),
2141 	    offsetof(struct send_range, ln)));
2142 	rlt_arg->error_code = 0;
2143 	rlt_arg->mark_redact = B_TRUE;
2144 	rlt_arg->rl = rl;
2145 	rlt_arg->num_blocks_visited = &dssp->dss_blocks;
2146 
2147 	(void) thread_create(NULL, 0, redact_list_thread, rlt_arg, 0,
2148 	    curproc, TS_RUN, minclsyspri);
2149 }
2150 
2151 static void
setup_merge_thread(struct send_merge_thread_arg * smt_arg,struct dmu_send_params * dspp,struct redact_list_thread_arg * from_arg,struct send_thread_arg * to_arg,struct redact_list_thread_arg * rlt_arg,objset_t * os)2152 setup_merge_thread(struct send_merge_thread_arg *smt_arg,
2153     struct dmu_send_params *dspp, struct redact_list_thread_arg *from_arg,
2154     struct send_thread_arg *to_arg, struct redact_list_thread_arg *rlt_arg,
2155     objset_t *os)
2156 {
2157 	VERIFY0(bqueue_init(&smt_arg->q, zfs_send_no_prefetch_queue_ff,
2158 	    MAX(zfs_send_no_prefetch_queue_length, 2 * zfs_max_recordsize),
2159 	    offsetof(struct send_range, ln)));
2160 	smt_arg->cancel = B_FALSE;
2161 	smt_arg->error = 0;
2162 	smt_arg->from_arg = from_arg;
2163 	smt_arg->to_arg = to_arg;
2164 	if (dspp->redactbook != NULL)
2165 		smt_arg->redact_arg = rlt_arg;
2166 
2167 	smt_arg->os = os;
2168 	(void) thread_create(NULL, 0, send_merge_thread, smt_arg, 0, curproc,
2169 	    TS_RUN, minclsyspri);
2170 }
2171 
2172 static void
setup_reader_thread(struct send_reader_thread_arg * srt_arg,struct dmu_send_params * dspp,struct send_merge_thread_arg * smt_arg,uint64_t featureflags)2173 setup_reader_thread(struct send_reader_thread_arg *srt_arg,
2174     struct dmu_send_params *dspp, struct send_merge_thread_arg *smt_arg,
2175     uint64_t featureflags)
2176 {
2177 	VERIFY0(bqueue_init(&srt_arg->q, zfs_send_queue_ff,
2178 	    MAX(zfs_send_queue_length, 2 * zfs_max_recordsize),
2179 	    offsetof(struct send_range, ln)));
2180 	srt_arg->smta = smt_arg;
2181 	srt_arg->issue_reads = !dspp->dso->dso_dryrun;
2182 	srt_arg->featureflags = featureflags;
2183 	(void) thread_create(NULL, 0, send_reader_thread, srt_arg, 0,
2184 	    curproc, TS_RUN, minclsyspri);
2185 }
2186 
2187 static int
setup_resume_points(struct dmu_send_params * dspp,struct send_thread_arg * to_arg,struct redact_list_thread_arg * from_arg,struct redact_list_thread_arg * rlt_arg,struct send_merge_thread_arg * smt_arg,boolean_t resuming,objset_t * os,redaction_list_t * redact_rl,nvlist_t * nvl)2188 setup_resume_points(struct dmu_send_params *dspp,
2189     struct send_thread_arg *to_arg, struct redact_list_thread_arg *from_arg,
2190     struct redact_list_thread_arg *rlt_arg,
2191     struct send_merge_thread_arg *smt_arg, boolean_t resuming, objset_t *os,
2192     redaction_list_t *redact_rl, nvlist_t *nvl)
2193 {
2194 	(void) smt_arg;
2195 	dsl_dataset_t *to_ds = dspp->to_ds;
2196 	int err = 0;
2197 
2198 	uint64_t obj = 0;
2199 	uint64_t blkid = 0;
2200 	if (resuming) {
2201 		obj = dspp->resumeobj;
2202 		dmu_object_info_t to_doi;
2203 		err = dmu_object_info(os, obj, &to_doi);
2204 		if (err != 0)
2205 			return (err);
2206 
2207 		blkid = dspp->resumeoff / to_doi.doi_data_block_size;
2208 	}
2209 	/*
2210 	 * If we're resuming a redacted send, we can skip to the appropriate
2211 	 * point in the redaction bookmark by binary searching through it.
2212 	 */
2213 	if (redact_rl != NULL) {
2214 		SET_BOOKMARK(&rlt_arg->resume, to_ds->ds_object, obj, 0, blkid);
2215 	}
2216 
2217 	SET_BOOKMARK(&to_arg->resume, to_ds->ds_object, obj, 0, blkid);
2218 	if (nvlist_exists(nvl, BEGINNV_REDACT_FROM_SNAPS)) {
2219 		uint64_t objset = dspp->ancestor_zb.zbm_redaction_obj;
2220 		/*
2221 		 * Note: If the resume point is in an object whose
2222 		 * blocksize is different in the from vs to snapshots,
2223 		 * we will have divided by the "wrong" blocksize.
2224 		 * However, in this case fromsnap's send_cb() will
2225 		 * detect that the blocksize has changed and therefore
2226 		 * ignore this object.
2227 		 *
2228 		 * If we're resuming a send from a redaction bookmark,
2229 		 * we still cannot accidentally suggest blocks behind
2230 		 * the to_ds.  In addition, we know that any blocks in
2231 		 * the object in the to_ds will have to be sent, since
2232 		 * the size changed.  Therefore, we can't cause any harm
2233 		 * this way either.
2234 		 */
2235 		SET_BOOKMARK(&from_arg->resume, objset, obj, 0, blkid);
2236 	}
2237 	if (resuming) {
2238 		fnvlist_add_uint64(nvl, BEGINNV_RESUME_OBJECT, dspp->resumeobj);
2239 		fnvlist_add_uint64(nvl, BEGINNV_RESUME_OFFSET, dspp->resumeoff);
2240 	}
2241 	return (0);
2242 }
2243 
2244 static dmu_sendstatus_t *
setup_send_progress(struct dmu_send_params * dspp)2245 setup_send_progress(struct dmu_send_params *dspp)
2246 {
2247 	dmu_sendstatus_t *dssp = kmem_zalloc(sizeof (*dssp), KM_SLEEP);
2248 	dssp->dss_outfd = dspp->outfd;
2249 	dssp->dss_off = dspp->off;
2250 	dssp->dss_proc = curproc;
2251 	mutex_enter(&dspp->to_ds->ds_sendstream_lock);
2252 	list_insert_head(&dspp->to_ds->ds_sendstreams, dssp);
2253 	mutex_exit(&dspp->to_ds->ds_sendstream_lock);
2254 	return (dssp);
2255 }
2256 
2257 /*
2258  * Payloads must be multiples of 8 bytes for historical compatibility, but
2259  * XDR-encoded nvlists are sized in multiples of 4 bytes and may need padding.
2260  *
2261  * Here we do the simplest possible thing and copy the data to a separate
2262  * buffer. Not ideal in terms of performance and memory use, but most BEGIN
2263  * nvlists are small or absent, the allocation is momentary, and we'll need
2264  * to do this at most once per dataset.
2265  *
2266  * It's OK if there is extra data after a packed nvlist on the receiving
2267  * side because packed nvlists have an internal end-of-list marker.
2268  *
2269  * The new buffer is allocated with kmem_alloc() and can be freed with
2270  * fnvlist_pack_free(), like the original.
2271  */
2272 static inline void
pad_packed_nvlist(char ** buffer,size_t * size)2273 pad_packed_nvlist(char **buffer, size_t *size)
2274 {
2275 	size_t size_in = *size;
2276 	size_t extra_bytes = P2ROUNDUP(size_in, 8) - size_in;
2277 	if (extra_bytes != 0) {
2278 		size_t expanded_size = size_in + extra_bytes;
2279 		char *longbuf = kmem_alloc(expanded_size, KM_SLEEP);
2280 		memcpy(longbuf, *buffer, size_in);
2281 		memset(longbuf + size_in, 0, extra_bytes);
2282 		fnvlist_pack_free(*buffer, size_in);
2283 		*buffer = longbuf;
2284 		*size = expanded_size;
2285 	}
2286 }
2287 
2288 /*
2289  * Actually do the bulk of the work in a zfs send.
2290  *
2291  * The idea is that we want to do a send from ancestor_zb to to_ds.  We also
2292  * want to not send any data that has been modified by all the datasets in
2293  * redactsnaparr, and store the list of blocks that are redacted in this way in
2294  * a bookmark named redactbook, created on the to_ds.  We do this by creating
2295  * several worker threads, whose function is described below.
2296  *
2297  * There are three cases.
2298  * The first case is a redacted zfs send.  In this case there are 5 threads.
2299  * The first thread is the to_ds traversal thread: it calls dataset_traverse on
2300  * the to_ds and finds all the blocks that have changed since ancestor_zb (if
2301  * it's a full send, that's all blocks in the dataset).  It then sends those
2302  * blocks on to the send merge thread. The redact list thread takes the data
2303  * from the redaction bookmark and sends those blocks on to the send merge
2304  * thread.  The send merge thread takes the data from the to_ds traversal
2305  * thread, and combines it with the redaction records from the redact list
2306  * thread.  If a block appears in both the to_ds's data and the redaction data,
2307  * the send merge thread will mark it as redacted and send it on to the prefetch
2308  * thread.  Otherwise, the send merge thread will send the block on to the
2309  * prefetch thread unchanged. The prefetch thread will issue prefetch reads for
2310  * any data that isn't redacted, and then send the data on to the main thread.
2311  * The main thread behaves the same as in a normal send case, issuing demand
2312  * reads for data blocks and sending out records over the network
2313  *
2314  * The graphic below diagrams the flow of data in the case of a redacted zfs
2315  * send.  Each box represents a thread, and each line represents the flow of
2316  * data.
2317  *
2318  *             Records from the |
2319  *           redaction bookmark |
2320  * +--------------------+       |  +---------------------------+
2321  * |                    |       v  | Send Merge Thread         |
2322  * | Redact List Thread +----------> Apply redaction marks to  |
2323  * |                    |          | records as specified by   |
2324  * +--------------------+          | redaction ranges          |
2325  *                                 +----^---------------+------+
2326  *                                      |               | Merged data
2327  *                                      |               |
2328  *                                      |  +------------v--------+
2329  *                                      |  | Prefetch Thread     |
2330  * +--------------------+               |  | Issues prefetch     |
2331  * | to_ds Traversal    |               |  | reads of data blocks|
2332  * | Thread (finds      +---------------+  +------------+--------+
2333  * | candidate blocks)  |  Blocks modified              | Prefetched data
2334  * +--------------------+  by to_ds since               |
2335  *                         ancestor_zb     +------------v----+
2336  *                                         | Main Thread     |  File Descriptor
2337  *                                         | Sends data over +->(to zfs receive)
2338  *                                         | wire            |
2339  *                                         +-----------------+
2340  *
2341  * The second case is an incremental send from a redaction bookmark.  The to_ds
2342  * traversal thread and the main thread behave the same as in the redacted
2343  * send case.  The new thread is the from bookmark traversal thread.  It
2344  * iterates over the redaction list in the redaction bookmark, and enqueues
2345  * records for each block that was redacted in the original send.  The send
2346  * merge thread now has to merge the data from the two threads.  For details
2347  * about that process, see the header comment of send_merge_thread().  Any data
2348  * it decides to send on will be prefetched by the prefetch thread.  Note that
2349  * you can perform a redacted send from a redaction bookmark; in that case,
2350  * the data flow behaves very similarly to the flow in the redacted send case,
2351  * except with the addition of the bookmark traversal thread iterating over the
2352  * redaction bookmark.  The send_merge_thread also has to take on the
2353  * responsibility of merging the redact list thread's records, the bookmark
2354  * traversal thread's records, and the to_ds records.
2355  *
2356  * +---------------------+
2357  * |                     |
2358  * | Redact List Thread  +--------------+
2359  * |                     |              |
2360  * +---------------------+              |
2361  *        Blocks in redaction list      | Ranges modified by every secure snap
2362  *        of from bookmark              | (or EOS if not readcted)
2363  *                                      |
2364  * +---------------------+   |     +----v----------------------+
2365  * | bookmark Traversal  |   v     | Send Merge Thread         |
2366  * | Thread (finds       +---------> Merges bookmark, rlt, and |
2367  * | candidate blocks)   |         | to_ds send records        |
2368  * +---------------------+         +----^---------------+------+
2369  *                                      |               | Merged data
2370  *                                      |  +------------v--------+
2371  *                                      |  | Prefetch Thread     |
2372  * +--------------------+               |  | Issues prefetch     |
2373  * | to_ds Traversal    |               |  | reads of data blocks|
2374  * | Thread (finds      +---------------+  +------------+--------+
2375  * | candidate blocks)  |  Blocks modified              | Prefetched data
2376  * +--------------------+  by to_ds since  +------------v----+
2377  *                         ancestor_zb     | Main Thread     |  File Descriptor
2378  *                                         | Sends data over +->(to zfs receive)
2379  *                                         | wire            |
2380  *                                         +-----------------+
2381  *
2382  * The final case is a simple zfs full or incremental send.  The to_ds traversal
2383  * thread behaves the same as always. The redact list thread is never started.
2384  * The send merge thread takes all the blocks that the to_ds traversal thread
2385  * sends it, prefetches the data, and sends the blocks on to the main thread.
2386  * The main thread sends the data over the wire.
2387  *
2388  * To keep performance acceptable, we want to prefetch the data in the worker
2389  * threads.  While the to_ds thread could simply use the TRAVERSE_PREFETCH
2390  * feature built into traverse_dataset, the combining and deletion of records
2391  * due to redaction and sends from redaction bookmarks mean that we could
2392  * issue many unnecessary prefetches.  As a result, we only prefetch data
2393  * after we've determined that the record is not going to be redacted.  To
2394  * prevent the prefetching from getting too far ahead of the main thread, the
2395  * blocking queues that are used for communication are capped not by the
2396  * number of entries in the queue, but by the sum of the size of the
2397  * prefetches associated with them.  The limit on the amount of data that the
2398  * thread can prefetch beyond what the main thread has reached is controlled
2399  * by the global variable zfs_send_queue_length.  In addition, to prevent poor
2400  * performance in the beginning of a send, we also limit the distance ahead
2401  * that the traversal threads can be.  That distance is controlled by the
2402  * zfs_send_no_prefetch_queue_length tunable.
2403  *
2404  * Note: Releases dp using the specified tag.
2405  */
2406 static int
dmu_send_impl(struct dmu_send_params * dspp)2407 dmu_send_impl(struct dmu_send_params *dspp)
2408 {
2409 	objset_t *os;
2410 	dmu_replay_record_t *drr;
2411 	dmu_sendstatus_t *dssp;
2412 	dmu_send_cookie_t dsc = {0};
2413 	int err;
2414 	uint64_t fromtxg = dspp->ancestor_zb.zbm_creation_txg;
2415 	uint64_t featureflags = 0;
2416 	struct redact_list_thread_arg *from_arg;
2417 	struct send_thread_arg *to_arg;
2418 	struct redact_list_thread_arg *rlt_arg;
2419 	struct send_merge_thread_arg *smt_arg;
2420 	struct send_reader_thread_arg *srt_arg;
2421 	struct send_range *range;
2422 	redaction_list_t *from_rl = NULL;
2423 	redaction_list_t *redact_rl = NULL;
2424 	boolean_t resuming = (dspp->resumeobj != 0 || dspp->resumeoff != 0);
2425 	boolean_t book_resuming = resuming;
2426 
2427 	dsl_dataset_t *to_ds = dspp->to_ds;
2428 	zfs_bookmark_phys_t *ancestor_zb = &dspp->ancestor_zb;
2429 	dsl_pool_t *dp = dspp->dp;
2430 	const void *tag = dspp->tag;
2431 
2432 	err = dmu_objset_from_ds(to_ds, &os);
2433 	if (err != 0) {
2434 		dsl_pool_rele(dp, tag);
2435 		return (err);
2436 	}
2437 
2438 	/*
2439 	 * If this is a non-raw send of an encrypted ds, we can ensure that
2440 	 * the objset_phys_t is authenticated. This is safe because this is
2441 	 * either a snapshot or we have owned the dataset, ensuring that
2442 	 * it can't be modified.
2443 	 */
2444 	if (!dspp->rawok && os->os_encrypted &&
2445 	    arc_is_unauthenticated(os->os_phys_buf)) {
2446 		zbookmark_phys_t zb;
2447 
2448 		SET_BOOKMARK(&zb, to_ds->ds_object, ZB_ROOT_OBJECT,
2449 		    ZB_ROOT_LEVEL, ZB_ROOT_BLKID);
2450 		err = arc_untransform(os->os_phys_buf, os->os_spa,
2451 		    &zb, B_FALSE);
2452 		if (err != 0) {
2453 			dsl_pool_rele(dp, tag);
2454 			return (err);
2455 		}
2456 
2457 		ASSERT0(arc_is_unauthenticated(os->os_phys_buf));
2458 	}
2459 
2460 	if ((err = setup_featureflags(dspp, os, &featureflags)) != 0) {
2461 		dsl_pool_rele(dp, tag);
2462 		return (err);
2463 	}
2464 
2465 	/*
2466 	 * If we're doing a redacted send, hold the bookmark's redaction list.
2467 	 */
2468 	if (dspp->redactbook != NULL) {
2469 		err = dsl_redaction_list_hold_obj(dp,
2470 		    dspp->redactbook->zbm_redaction_obj, FTAG,
2471 		    &redact_rl);
2472 		if (err != 0) {
2473 			dsl_pool_rele(dp, tag);
2474 			return (SET_ERROR(EINVAL));
2475 		}
2476 		dsl_redaction_list_long_hold(dp, redact_rl, FTAG);
2477 	}
2478 
2479 	/*
2480 	 * If we're sending from a redaction bookmark, hold the redaction list
2481 	 * so that we can consider sending the redacted blocks.
2482 	 */
2483 	if (ancestor_zb->zbm_redaction_obj != 0) {
2484 		err = dsl_redaction_list_hold_obj(dp,
2485 		    ancestor_zb->zbm_redaction_obj, FTAG, &from_rl);
2486 		if (err != 0) {
2487 			if (redact_rl != NULL) {
2488 				dsl_redaction_list_long_rele(redact_rl, FTAG);
2489 				dsl_redaction_list_rele(redact_rl, FTAG);
2490 			}
2491 			dsl_pool_rele(dp, tag);
2492 			return (SET_ERROR(EINVAL));
2493 		}
2494 		dsl_redaction_list_long_hold(dp, from_rl, FTAG);
2495 	}
2496 
2497 	dsl_dataset_long_hold(to_ds, FTAG);
2498 
2499 	from_arg = kmem_zalloc(sizeof (*from_arg), KM_SLEEP);
2500 	to_arg = kmem_zalloc(sizeof (*to_arg), KM_SLEEP);
2501 	rlt_arg = kmem_zalloc(sizeof (*rlt_arg), KM_SLEEP);
2502 	smt_arg = kmem_zalloc(sizeof (*smt_arg), KM_SLEEP);
2503 	srt_arg = kmem_zalloc(sizeof (*srt_arg), KM_SLEEP);
2504 
2505 	drr = create_begin_record(dspp, os, featureflags);
2506 	dssp = setup_send_progress(dspp);
2507 
2508 	dsc.dsc_drr = drr;
2509 	dsc.dsc_dso = dspp->dso;
2510 	dsc.dsc_os = os;
2511 	dsc.dsc_off = dspp->off;
2512 	dsc.dsc_toguid = dsl_dataset_phys(to_ds)->ds_guid;
2513 	dsc.dsc_fromtxg = fromtxg;
2514 	dsc.dsc_pending_op = PENDING_NONE;
2515 	dsc.dsc_featureflags = featureflags;
2516 	dsc.dsc_resume_object = dspp->resumeobj;
2517 	dsc.dsc_resume_offset = dspp->resumeoff;
2518 
2519 	dsl_pool_rele(dp, tag);
2520 
2521 	char *payload = NULL;
2522 	size_t payload_len = 0;
2523 	nvlist_t *nvl = fnvlist_alloc();
2524 
2525 	/*
2526 	 * If we're doing a redacted send, we include the snapshots we're
2527 	 * redacted with respect to so that the target system knows what send
2528 	 * streams can be correctly received on top of this dataset. If we're
2529 	 * instead sending a redacted dataset, we include the snapshots that the
2530 	 * dataset was created with respect to.
2531 	 */
2532 	if (dspp->redactbook != NULL) {
2533 		fnvlist_add_uint64_array(nvl, BEGINNV_REDACT_SNAPS,
2534 		    redact_rl->rl_phys->rlp_snaps,
2535 		    redact_rl->rl_phys->rlp_num_snaps);
2536 	} else if (dsl_dataset_feature_is_active(to_ds,
2537 	    SPA_FEATURE_REDACTED_DATASETS)) {
2538 		uint64_t *tods_guids;
2539 		uint64_t length;
2540 		VERIFY(dsl_dataset_get_uint64_array_feature(to_ds,
2541 		    SPA_FEATURE_REDACTED_DATASETS, &length, &tods_guids));
2542 		fnvlist_add_uint64_array(nvl, BEGINNV_REDACT_SNAPS, tods_guids,
2543 		    length);
2544 	}
2545 
2546 	/*
2547 	 * If we're sending from a redaction bookmark, then we should retrieve
2548 	 * the guids of that bookmark so we can send them over the wire.
2549 	 */
2550 	if (from_rl != NULL) {
2551 		fnvlist_add_uint64_array(nvl, BEGINNV_REDACT_FROM_SNAPS,
2552 		    from_rl->rl_phys->rlp_snaps,
2553 		    from_rl->rl_phys->rlp_num_snaps);
2554 	}
2555 
2556 	/*
2557 	 * If the snapshot we're sending from is redacted, include the redaction
2558 	 * list in the stream.
2559 	 */
2560 	if (dspp->numfromredactsnaps != NUM_SNAPS_NOT_REDACTED) {
2561 		ASSERT0P(from_rl);
2562 		fnvlist_add_uint64_array(nvl, BEGINNV_REDACT_FROM_SNAPS,
2563 		    dspp->fromredactsnaps, (uint_t)dspp->numfromredactsnaps);
2564 		if (dspp->numfromredactsnaps > 0) {
2565 			kmem_free(dspp->fromredactsnaps,
2566 			    dspp->numfromredactsnaps * sizeof (uint64_t));
2567 			dspp->fromredactsnaps = NULL;
2568 		}
2569 	}
2570 
2571 	if (resuming || book_resuming) {
2572 		err = setup_resume_points(dspp, to_arg, from_arg,
2573 		    rlt_arg, smt_arg, resuming, os, redact_rl, nvl);
2574 		if (err != 0)
2575 			goto out;
2576 	}
2577 
2578 	if (featureflags & DMU_BACKUP_FEATURE_RAW) {
2579 		uint64_t ivset_guid = ancestor_zb->zbm_ivset_guid;
2580 		nvlist_t *keynvl = NULL;
2581 		ASSERT(os->os_encrypted);
2582 
2583 		err = dsl_crypto_populate_key_nvlist(os, ivset_guid,
2584 		    &keynvl);
2585 		if (err != 0) {
2586 			fnvlist_free(nvl);
2587 			goto out;
2588 		}
2589 
2590 		fnvlist_add_nvlist(nvl, "crypt_keydata", keynvl);
2591 		fnvlist_free(keynvl);
2592 	}
2593 
2594 	if (!nvlist_empty(nvl)) {
2595 		VERIFY0(nvlist_pack(nvl, &payload, &payload_len,
2596 		    NV_ENCODE_XDR, KM_SLEEP));
2597 		pad_packed_nvlist(&payload, &payload_len);
2598 		drr->drr_payloadlen = payload_len;
2599 	}
2600 
2601 	fnvlist_free(nvl);
2602 	err = dump_record(&dsc, payload, payload_len);
2603 	fnvlist_pack_free(payload, payload_len);
2604 	if (err != 0) {
2605 		err = dsc.dsc_err;
2606 		goto out;
2607 	}
2608 
2609 	setup_to_thread(to_arg, os, dssp, fromtxg, dspp->rawok);
2610 	setup_from_thread(from_arg, from_rl, dssp);
2611 	setup_redact_list_thread(rlt_arg, dspp, redact_rl, dssp);
2612 	setup_merge_thread(smt_arg, dspp, from_arg, to_arg, rlt_arg, os);
2613 	setup_reader_thread(srt_arg, dspp, smt_arg, featureflags);
2614 
2615 	range = bqueue_dequeue(&srt_arg->q);
2616 	while (err == 0 && !range->eos_marker) {
2617 		err = do_dump(&dsc, range);
2618 		range = get_next_range(&srt_arg->q, range);
2619 		if (issig())
2620 			err = SET_ERROR(EINTR);
2621 	}
2622 
2623 	/*
2624 	 * If we hit an error or are interrupted, cancel our worker threads and
2625 	 * clear the queue of any pending records.  The threads will pass the
2626 	 * cancel up the tree of worker threads, and each one will clean up any
2627 	 * pending records before exiting.
2628 	 */
2629 	if (err != 0) {
2630 		srt_arg->cancel = B_TRUE;
2631 		while (!range->eos_marker) {
2632 			range = get_next_range(&srt_arg->q, range);
2633 		}
2634 	}
2635 	range_free(range);
2636 
2637 	bqueue_destroy(&srt_arg->q);
2638 	bqueue_destroy(&smt_arg->q);
2639 	if (dspp->redactbook != NULL)
2640 		bqueue_destroy(&rlt_arg->q);
2641 	bqueue_destroy(&to_arg->q);
2642 	bqueue_destroy(&from_arg->q);
2643 
2644 	if (err == 0 && srt_arg->error != 0)
2645 		err = srt_arg->error;
2646 
2647 	if (err != 0)
2648 		goto out;
2649 
2650 	if (dsc.dsc_pending_op != PENDING_NONE)
2651 		if (dump_record(&dsc, NULL, 0) != 0)
2652 			err = SET_ERROR(EINTR);
2653 
2654 	if (err != 0) {
2655 		if (err == EINTR && dsc.dsc_err != 0)
2656 			err = dsc.dsc_err;
2657 		goto out;
2658 	}
2659 
2660 	/*
2661 	 * Send the DRR_END record if this is not a saved stream.
2662 	 * Otherwise, the omitted DRR_END record will signal to
2663 	 * the receive side that the stream is incomplete.
2664 	 */
2665 	if (!dspp->savedok) {
2666 		memset(drr, 0, sizeof (dmu_replay_record_t));
2667 		drr->drr_type = DRR_END;
2668 		drr->drr_u.drr_end.drr_checksum = dsc.dsc_zc;
2669 		drr->drr_u.drr_end.drr_toguid = dsc.dsc_toguid;
2670 
2671 		if (dump_record(&dsc, NULL, 0) != 0)
2672 			err = dsc.dsc_err;
2673 	}
2674 out:
2675 	mutex_enter(&to_ds->ds_sendstream_lock);
2676 	list_remove(&to_ds->ds_sendstreams, dssp);
2677 	mutex_exit(&to_ds->ds_sendstream_lock);
2678 
2679 	VERIFY(err != 0 || (dsc.dsc_sent_begin &&
2680 	    (dsc.dsc_sent_end || dspp->savedok)));
2681 
2682 	kmem_free(drr, sizeof (dmu_replay_record_t));
2683 	kmem_free(dssp, sizeof (dmu_sendstatus_t));
2684 	kmem_free(from_arg, sizeof (*from_arg));
2685 	kmem_free(to_arg, sizeof (*to_arg));
2686 	kmem_free(rlt_arg, sizeof (*rlt_arg));
2687 	kmem_free(smt_arg, sizeof (*smt_arg));
2688 	kmem_free(srt_arg, sizeof (*srt_arg));
2689 
2690 	dsl_dataset_long_rele(to_ds, FTAG);
2691 	if (from_rl != NULL) {
2692 		dsl_redaction_list_long_rele(from_rl, FTAG);
2693 		dsl_redaction_list_rele(from_rl, FTAG);
2694 	}
2695 	if (redact_rl != NULL) {
2696 		dsl_redaction_list_long_rele(redact_rl, FTAG);
2697 		dsl_redaction_list_rele(redact_rl, FTAG);
2698 	}
2699 
2700 	return (err);
2701 }
2702 
2703 int
dmu_send_obj(const char * pool,uint64_t tosnap,uint64_t fromsnap,boolean_t embedok,boolean_t large_block_ok,boolean_t compressok,boolean_t rawok,boolean_t savedok,int outfd,offset_t * off,dmu_send_outparams_t * dsop)2704 dmu_send_obj(const char *pool, uint64_t tosnap, uint64_t fromsnap,
2705     boolean_t embedok, boolean_t large_block_ok, boolean_t compressok,
2706     boolean_t rawok, boolean_t savedok, int outfd, offset_t *off,
2707     dmu_send_outparams_t *dsop)
2708 {
2709 	int err;
2710 	dsl_dataset_t *fromds;
2711 	ds_hold_flags_t dsflags;
2712 	struct dmu_send_params dspp = {0};
2713 	dspp.embedok = embedok;
2714 	dspp.large_block_ok = large_block_ok;
2715 	dspp.compressok = compressok;
2716 	dspp.outfd = outfd;
2717 	dspp.off = off;
2718 	dspp.dso = dsop;
2719 	dspp.tag = FTAG;
2720 	dspp.rawok = rawok;
2721 	dspp.savedok = savedok;
2722 
2723 	dsflags = (rawok) ? DS_HOLD_FLAG_NONE : DS_HOLD_FLAG_DECRYPT;
2724 	err = dsl_pool_hold(pool, FTAG, &dspp.dp);
2725 	if (err != 0)
2726 		return (err);
2727 
2728 	err = dsl_dataset_hold_obj_flags(dspp.dp, tosnap, dsflags, FTAG,
2729 	    &dspp.to_ds);
2730 	if (err != 0) {
2731 		dsl_pool_rele(dspp.dp, FTAG);
2732 		return (err);
2733 	}
2734 
2735 	if (fromsnap != 0) {
2736 		err = dsl_dataset_hold_obj(dspp.dp, fromsnap, FTAG, &fromds);
2737 
2738 		if (err != 0) {
2739 			dsl_dataset_rele_flags(dspp.to_ds, dsflags, FTAG);
2740 			dsl_pool_rele(dspp.dp, FTAG);
2741 			return (err);
2742 		}
2743 		dspp.ancestor_zb.zbm_guid = dsl_dataset_phys(fromds)->ds_guid;
2744 		dspp.ancestor_zb.zbm_creation_txg =
2745 		    dsl_dataset_phys(fromds)->ds_creation_txg;
2746 		dspp.ancestor_zb.zbm_creation_time =
2747 		    dsl_dataset_phys(fromds)->ds_creation_time;
2748 
2749 		if (dsl_dataset_is_zapified(fromds)) {
2750 			(void) zap_lookup(dspp.dp->dp_meta_objset,
2751 			    fromds->ds_object, DS_FIELD_IVSET_GUID, 8, 1,
2752 			    &dspp.ancestor_zb.zbm_ivset_guid);
2753 		}
2754 
2755 		/* See dmu_send for the reasons behind this. */
2756 		uint64_t *fromredact;
2757 
2758 		if (!dsl_dataset_get_uint64_array_feature(fromds,
2759 		    SPA_FEATURE_REDACTED_DATASETS,
2760 		    &dspp.numfromredactsnaps,
2761 		    &fromredact)) {
2762 			dspp.numfromredactsnaps = NUM_SNAPS_NOT_REDACTED;
2763 		} else if (dspp.numfromredactsnaps > 0) {
2764 			uint64_t size = dspp.numfromredactsnaps *
2765 			    sizeof (uint64_t);
2766 			dspp.fromredactsnaps = kmem_zalloc(size, KM_SLEEP);
2767 			memcpy(dspp.fromredactsnaps, fromredact, size);
2768 		}
2769 
2770 		boolean_t is_before =
2771 		    dsl_dataset_is_before(dspp.to_ds, fromds, 0);
2772 		dspp.is_clone = (dspp.to_ds->ds_dir !=
2773 		    fromds->ds_dir);
2774 		dsl_dataset_rele(fromds, FTAG);
2775 		if (!is_before) {
2776 			dsl_pool_rele(dspp.dp, FTAG);
2777 			err = SET_ERROR(EXDEV);
2778 		} else {
2779 			err = dmu_send_impl(&dspp);
2780 		}
2781 	} else {
2782 		dspp.numfromredactsnaps = NUM_SNAPS_NOT_REDACTED;
2783 		err = dmu_send_impl(&dspp);
2784 	}
2785 	if (dspp.fromredactsnaps)
2786 		kmem_free(dspp.fromredactsnaps,
2787 		    dspp.numfromredactsnaps * sizeof (uint64_t));
2788 
2789 	dsl_dataset_rele_flags(dspp.to_ds, dsflags, FTAG);
2790 	return (err);
2791 }
2792 
2793 int
dmu_send(const char * tosnap,const char * fromsnap,boolean_t embedok,boolean_t large_block_ok,boolean_t compressok,boolean_t rawok,boolean_t savedok,uint64_t resumeobj,uint64_t resumeoff,const char * redactbook,int outfd,offset_t * off,dmu_send_outparams_t * dsop)2794 dmu_send(const char *tosnap, const char *fromsnap, boolean_t embedok,
2795     boolean_t large_block_ok, boolean_t compressok, boolean_t rawok,
2796     boolean_t savedok, uint64_t resumeobj, uint64_t resumeoff,
2797     const char *redactbook, int outfd, offset_t *off,
2798     dmu_send_outparams_t *dsop)
2799 {
2800 	int err = 0;
2801 	ds_hold_flags_t dsflags;
2802 	boolean_t owned = B_FALSE;
2803 	dsl_dataset_t *fromds = NULL;
2804 	zfs_bookmark_phys_t book = {0};
2805 	struct dmu_send_params dspp = {0};
2806 
2807 	dsflags = (rawok) ? DS_HOLD_FLAG_NONE : DS_HOLD_FLAG_DECRYPT;
2808 	dspp.tosnap = tosnap;
2809 	dspp.embedok = embedok;
2810 	dspp.large_block_ok = large_block_ok;
2811 	dspp.compressok = compressok;
2812 	dspp.outfd = outfd;
2813 	dspp.off = off;
2814 	dspp.dso = dsop;
2815 	dspp.tag = FTAG;
2816 	dspp.resumeobj = resumeobj;
2817 	dspp.resumeoff = resumeoff;
2818 	dspp.rawok = rawok;
2819 	dspp.savedok = savedok;
2820 
2821 	if (fromsnap != NULL && strpbrk(fromsnap, "@#") == NULL)
2822 		return (SET_ERROR(EINVAL));
2823 
2824 	err = dsl_pool_hold(tosnap, FTAG, &dspp.dp);
2825 	if (err != 0)
2826 		return (err);
2827 
2828 	if (strchr(tosnap, '@') == NULL && spa_writeable(dspp.dp->dp_spa)) {
2829 		/*
2830 		 * We are sending a filesystem or volume.  Ensure
2831 		 * that it doesn't change by owning the dataset.
2832 		 */
2833 
2834 		if (savedok) {
2835 			/*
2836 			 * We are looking for the dataset that represents the
2837 			 * partially received send stream. If this stream was
2838 			 * received as a new snapshot of an existing dataset,
2839 			 * this will be saved in a hidden clone named
2840 			 * "<pool>/<dataset>/%recv". Otherwise, the stream
2841 			 * will be saved in the live dataset itself. In
2842 			 * either case we need to use dsl_dataset_own_force()
2843 			 * because the stream is marked as inconsistent,
2844 			 * which would normally make it unavailable to be
2845 			 * owned.
2846 			 */
2847 			char *name = kmem_asprintf("%s/%s", tosnap,
2848 			    recv_clone_name);
2849 			err = dsl_dataset_own_force(dspp.dp, name, dsflags,
2850 			    FTAG, &dspp.to_ds);
2851 			if (err == ENOENT) {
2852 				err = dsl_dataset_own_force(dspp.dp, tosnap,
2853 				    dsflags, FTAG, &dspp.to_ds);
2854 			}
2855 
2856 			if (err == 0) {
2857 				owned = B_TRUE;
2858 				err = zap_lookup(dspp.dp->dp_meta_objset,
2859 				    dspp.to_ds->ds_object,
2860 				    DS_FIELD_RESUME_TOGUID, 8, 1,
2861 				    &dspp.saved_guid);
2862 			}
2863 
2864 			if (err == 0) {
2865 				err = zap_lookup(dspp.dp->dp_meta_objset,
2866 				    dspp.to_ds->ds_object,
2867 				    DS_FIELD_RESUME_TONAME, 1,
2868 				    sizeof (dspp.saved_toname),
2869 				    dspp.saved_toname);
2870 			}
2871 			/* Only disown if there was an error in the lookups */
2872 			if (owned && (err != 0))
2873 				dsl_dataset_disown(dspp.to_ds, dsflags, FTAG);
2874 
2875 			kmem_strfree(name);
2876 		} else {
2877 			err = dsl_dataset_own(dspp.dp, tosnap, dsflags,
2878 			    FTAG, &dspp.to_ds);
2879 			if (err == 0)
2880 				owned = B_TRUE;
2881 		}
2882 	} else {
2883 		err = dsl_dataset_hold_flags(dspp.dp, tosnap, dsflags, FTAG,
2884 		    &dspp.to_ds);
2885 	}
2886 
2887 	if (err != 0) {
2888 		/* Note: dsl dataset is not owned at this point */
2889 		dsl_pool_rele(dspp.dp, FTAG);
2890 		return (err);
2891 	}
2892 
2893 	if (redactbook != NULL) {
2894 		char path[ZFS_MAX_DATASET_NAME_LEN];
2895 		(void) strlcpy(path, tosnap, sizeof (path));
2896 		char *at = strchr(path, '@');
2897 		if (at == NULL) {
2898 			err = EINVAL;
2899 		} else {
2900 			(void) snprintf(at, sizeof (path) - (at - path), "#%s",
2901 			    redactbook);
2902 			err = dsl_bookmark_lookup(dspp.dp, path,
2903 			    NULL, &book);
2904 			dspp.redactbook = &book;
2905 		}
2906 	}
2907 
2908 	if (err != 0) {
2909 		dsl_pool_rele(dspp.dp, FTAG);
2910 		if (owned)
2911 			dsl_dataset_disown(dspp.to_ds, dsflags, FTAG);
2912 		else
2913 			dsl_dataset_rele_flags(dspp.to_ds, dsflags, FTAG);
2914 		return (err);
2915 	}
2916 
2917 	if (fromsnap != NULL) {
2918 		zfs_bookmark_phys_t *zb = &dspp.ancestor_zb;
2919 		int fsnamelen;
2920 		if (strpbrk(tosnap, "@#") != NULL)
2921 			fsnamelen = strpbrk(tosnap, "@#") - tosnap;
2922 		else
2923 			fsnamelen = strlen(tosnap);
2924 
2925 		/*
2926 		 * If the fromsnap is in a different filesystem, then
2927 		 * mark the send stream as a clone.
2928 		 */
2929 		if (strncmp(tosnap, fromsnap, fsnamelen) != 0 ||
2930 		    (fromsnap[fsnamelen] != '@' &&
2931 		    fromsnap[fsnamelen] != '#')) {
2932 			dspp.is_clone = B_TRUE;
2933 		}
2934 
2935 		if (strchr(fromsnap, '@') != NULL) {
2936 			err = dsl_dataset_hold(dspp.dp, fromsnap, FTAG,
2937 			    &fromds);
2938 
2939 			if (err != 0) {
2940 				ASSERT0P(fromds);
2941 			} else {
2942 				/*
2943 				 * We need to make a deep copy of the redact
2944 				 * snapshots of the from snapshot, because the
2945 				 * array will be freed when we evict from_ds.
2946 				 */
2947 				uint64_t *fromredact;
2948 				if (!dsl_dataset_get_uint64_array_feature(
2949 				    fromds, SPA_FEATURE_REDACTED_DATASETS,
2950 				    &dspp.numfromredactsnaps,
2951 				    &fromredact)) {
2952 					dspp.numfromredactsnaps =
2953 					    NUM_SNAPS_NOT_REDACTED;
2954 				} else if (dspp.numfromredactsnaps > 0) {
2955 					uint64_t size =
2956 					    dspp.numfromredactsnaps *
2957 					    sizeof (uint64_t);
2958 					dspp.fromredactsnaps = kmem_zalloc(size,
2959 					    KM_SLEEP);
2960 					memcpy(dspp.fromredactsnaps, fromredact,
2961 					    size);
2962 				}
2963 				if (!dsl_dataset_is_before(dspp.to_ds, fromds,
2964 				    0)) {
2965 					err = SET_ERROR(EXDEV);
2966 				} else {
2967 					zb->zbm_creation_txg =
2968 					    dsl_dataset_phys(fromds)->
2969 					    ds_creation_txg;
2970 					zb->zbm_creation_time =
2971 					    dsl_dataset_phys(fromds)->
2972 					    ds_creation_time;
2973 					zb->zbm_guid =
2974 					    dsl_dataset_phys(fromds)->ds_guid;
2975 					zb->zbm_redaction_obj = 0;
2976 
2977 					if (dsl_dataset_is_zapified(fromds)) {
2978 						(void) zap_lookup(
2979 						    dspp.dp->dp_meta_objset,
2980 						    fromds->ds_object,
2981 						    DS_FIELD_IVSET_GUID, 8, 1,
2982 						    &zb->zbm_ivset_guid);
2983 					}
2984 				}
2985 				dsl_dataset_rele(fromds, FTAG);
2986 			}
2987 		} else {
2988 			dspp.numfromredactsnaps = NUM_SNAPS_NOT_REDACTED;
2989 			err = dsl_bookmark_lookup(dspp.dp, fromsnap, dspp.to_ds,
2990 			    zb);
2991 			if (err == EXDEV && zb->zbm_redaction_obj != 0 &&
2992 			    zb->zbm_guid ==
2993 			    dsl_dataset_phys(dspp.to_ds)->ds_guid)
2994 				err = 0;
2995 		}
2996 
2997 		if (err == 0) {
2998 			/* dmu_send_impl will call dsl_pool_rele for us. */
2999 			err = dmu_send_impl(&dspp);
3000 		} else {
3001 			if (dspp.fromredactsnaps)
3002 				kmem_free(dspp.fromredactsnaps,
3003 				    dspp.numfromredactsnaps *
3004 				    sizeof (uint64_t));
3005 			dsl_pool_rele(dspp.dp, FTAG);
3006 		}
3007 	} else {
3008 		dspp.numfromredactsnaps = NUM_SNAPS_NOT_REDACTED;
3009 		err = dmu_send_impl(&dspp);
3010 	}
3011 	if (owned)
3012 		dsl_dataset_disown(dspp.to_ds, dsflags, FTAG);
3013 	else
3014 		dsl_dataset_rele_flags(dspp.to_ds, dsflags, FTAG);
3015 	return (err);
3016 }
3017 
3018 static int
dmu_adjust_send_estimate_for_indirects(dsl_dataset_t * ds,uint64_t uncompressed,uint64_t compressed,boolean_t stream_compressed,uint64_t * sizep)3019 dmu_adjust_send_estimate_for_indirects(dsl_dataset_t *ds, uint64_t uncompressed,
3020     uint64_t compressed, boolean_t stream_compressed, uint64_t *sizep)
3021 {
3022 	int err = 0;
3023 	uint64_t size;
3024 	/*
3025 	 * Assume that space (both on-disk and in-stream) is dominated by
3026 	 * data.  We will adjust for indirect blocks and the copies property,
3027 	 * but ignore per-object space used (eg, dnodes and DRR_OBJECT records).
3028 	 */
3029 
3030 	uint64_t recordsize;
3031 	uint64_t record_count;
3032 	objset_t *os;
3033 	VERIFY0(dmu_objset_from_ds(ds, &os));
3034 
3035 	/* Assume all (uncompressed) blocks are recordsize. */
3036 	if (zfs_override_estimate_recordsize != 0) {
3037 		recordsize = zfs_override_estimate_recordsize;
3038 	} else if (os->os_phys->os_type == DMU_OST_ZVOL) {
3039 		err = dsl_prop_get_int_ds(ds,
3040 		    zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE), &recordsize);
3041 	} else {
3042 		err = dsl_prop_get_int_ds(ds,
3043 		    zfs_prop_to_name(ZFS_PROP_RECORDSIZE), &recordsize);
3044 	}
3045 	if (err != 0)
3046 		return (err);
3047 	record_count = uncompressed / recordsize;
3048 
3049 	/*
3050 	 * If we're estimating a send size for a compressed stream, use the
3051 	 * compressed data size to estimate the stream size. Otherwise, use the
3052 	 * uncompressed data size.
3053 	 */
3054 	size = stream_compressed ? compressed : uncompressed;
3055 
3056 	/*
3057 	 * Subtract out approximate space used by indirect blocks.
3058 	 * Assume most space is used by data blocks (non-indirect, non-dnode).
3059 	 * Assume no ditto blocks or internal fragmentation.
3060 	 *
3061 	 * Therefore, space used by indirect blocks is sizeof(blkptr_t) per
3062 	 * block.
3063 	 */
3064 	size -= record_count * sizeof (blkptr_t);
3065 
3066 	/* Add in the space for the record associated with each block. */
3067 	size += record_count * sizeof (dmu_replay_record_t);
3068 
3069 	*sizep = size;
3070 
3071 	return (0);
3072 }
3073 
3074 int
dmu_send_estimate_fast(dsl_dataset_t * origds,dsl_dataset_t * fromds,zfs_bookmark_phys_t * frombook,boolean_t stream_compressed,boolean_t saved,uint64_t * sizep)3075 dmu_send_estimate_fast(dsl_dataset_t *origds, dsl_dataset_t *fromds,
3076     zfs_bookmark_phys_t *frombook, boolean_t stream_compressed,
3077     boolean_t saved, uint64_t *sizep)
3078 {
3079 	int err;
3080 	dsl_dataset_t *ds = origds;
3081 	uint64_t uncomp, comp;
3082 
3083 	ASSERT(dsl_pool_config_held(origds->ds_dir->dd_pool));
3084 	ASSERT(fromds == NULL || frombook == NULL);
3085 
3086 	/*
3087 	 * If this is a saved send we may actually be sending
3088 	 * from the %recv clone used for resuming.
3089 	 */
3090 	if (saved) {
3091 		objset_t *mos = origds->ds_dir->dd_pool->dp_meta_objset;
3092 		uint64_t guid;
3093 		char dsname[ZFS_MAX_DATASET_NAME_LEN + 6];
3094 
3095 		dsl_dataset_name(origds, dsname);
3096 		(void) strcat(dsname, "/");
3097 		(void) strlcat(dsname, recv_clone_name, sizeof (dsname));
3098 
3099 		err = dsl_dataset_hold(origds->ds_dir->dd_pool,
3100 		    dsname, FTAG, &ds);
3101 		if (err != ENOENT && err != 0) {
3102 			return (err);
3103 		} else if (err == ENOENT) {
3104 			ds = origds;
3105 		}
3106 
3107 		/* check that this dataset has partially received data */
3108 		err = zap_lookup(mos, ds->ds_object,
3109 		    DS_FIELD_RESUME_TOGUID, 8, 1, &guid);
3110 		if (err != 0) {
3111 			err = SET_ERROR(err == ENOENT ? EINVAL : err);
3112 			goto out;
3113 		}
3114 
3115 		err = zap_lookup(mos, ds->ds_object,
3116 		    DS_FIELD_RESUME_TONAME, 1, sizeof (dsname), dsname);
3117 		if (err != 0) {
3118 			err = SET_ERROR(err == ENOENT ? EINVAL : err);
3119 			goto out;
3120 		}
3121 	}
3122 
3123 	/* tosnap must be a snapshot or the target of a saved send */
3124 	if (!ds->ds_is_snapshot && ds == origds)
3125 		return (SET_ERROR(EINVAL));
3126 
3127 	if (fromds != NULL) {
3128 		uint64_t used;
3129 		if (!fromds->ds_is_snapshot) {
3130 			err = SET_ERROR(EINVAL);
3131 			goto out;
3132 		}
3133 
3134 		if (!dsl_dataset_is_before(ds, fromds, 0)) {
3135 			err = SET_ERROR(EXDEV);
3136 			goto out;
3137 		}
3138 
3139 		err = dsl_dataset_space_written(fromds, ds, &used, &comp,
3140 		    &uncomp);
3141 		if (err != 0)
3142 			goto out;
3143 	} else if (frombook != NULL) {
3144 		uint64_t used;
3145 		err = dsl_dataset_space_written_bookmark(frombook, ds, &used,
3146 		    &comp, &uncomp);
3147 		if (err != 0)
3148 			goto out;
3149 	} else {
3150 		uncomp = dsl_dataset_phys(ds)->ds_uncompressed_bytes;
3151 		comp = dsl_dataset_phys(ds)->ds_compressed_bytes;
3152 	}
3153 
3154 	err = dmu_adjust_send_estimate_for_indirects(ds, uncomp, comp,
3155 	    stream_compressed, sizep);
3156 	/*
3157 	 * Add the size of the BEGIN and END records to the estimate.
3158 	 */
3159 	*sizep += 2 * sizeof (dmu_replay_record_t);
3160 
3161 out:
3162 	if (ds != origds)
3163 		dsl_dataset_rele(ds, FTAG);
3164 	return (err);
3165 }
3166 
3167 ZFS_MODULE_PARAM(zfs_send, zfs_send_, corrupt_data, INT, ZMOD_RW,
3168 	"Allow sending corrupt data");
3169 
3170 ZFS_MODULE_PARAM(zfs_send, zfs_send_, queue_length, UINT, ZMOD_RW,
3171 	"Maximum send queue length");
3172 
3173 ZFS_MODULE_PARAM(zfs_send, zfs_send_, unmodified_spill_blocks, INT, ZMOD_RW,
3174 	"Send unmodified spill blocks");
3175 
3176 ZFS_MODULE_PARAM(zfs_send, zfs_send_, no_prefetch_queue_length, UINT, ZMOD_RW,
3177 	"Maximum send queue length for non-prefetch queues");
3178 
3179 ZFS_MODULE_PARAM(zfs_send, zfs_send_, queue_ff, UINT, ZMOD_RW,
3180 	"Send queue fill fraction");
3181 
3182 ZFS_MODULE_PARAM(zfs_send, zfs_send_, no_prefetch_queue_ff, UINT, ZMOD_RW,
3183 	"Send queue fill fraction for non-prefetch queues");
3184 
3185 ZFS_MODULE_PARAM(zfs_send, zfs_, override_estimate_recordsize, UINT, ZMOD_RW,
3186 	"Override block size estimate with fixed size");
3187