xref: /illumos-gate/usr/src/uts/common/fs/zfs/dmu_send.c (revision 45818ee124adeaaf947698996b4f4c722afc6d1f)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23  * Copyright 2011 Nexenta Systems, Inc. All rights reserved.
24  * Copyright (c) 2011, 2015 by Delphix. All rights reserved.
25  * Copyright (c) 2014, Joyent, Inc. All rights reserved.
26  * Copyright 2014 HybridCluster. All rights reserved.
27  */
28 
29 #include <sys/dmu.h>
30 #include <sys/dmu_impl.h>
31 #include <sys/dmu_tx.h>
32 #include <sys/dbuf.h>
33 #include <sys/dnode.h>
34 #include <sys/zfs_context.h>
35 #include <sys/dmu_objset.h>
36 #include <sys/dmu_traverse.h>
37 #include <sys/dsl_dataset.h>
38 #include <sys/dsl_dir.h>
39 #include <sys/dsl_prop.h>
40 #include <sys/dsl_pool.h>
41 #include <sys/dsl_synctask.h>
42 #include <sys/zfs_ioctl.h>
43 #include <sys/zap.h>
44 #include <sys/zio_checksum.h>
45 #include <sys/zfs_znode.h>
46 #include <zfs_fletcher.h>
47 #include <sys/avl.h>
48 #include <sys/ddt.h>
49 #include <sys/zfs_onexit.h>
50 #include <sys/dmu_send.h>
51 #include <sys/dsl_destroy.h>
52 #include <sys/blkptr.h>
53 #include <sys/dsl_bookmark.h>
54 #include <sys/zfeature.h>
55 #include <sys/bqueue.h>
56 
57 /* Set this tunable to TRUE to replace corrupt data with 0x2f5baddb10c */
58 int zfs_send_corrupt_data = B_FALSE;
59 int zfs_send_queue_length = 16 * 1024 * 1024;
60 int zfs_recv_queue_length = 16 * 1024 * 1024;
61 
62 static char *dmu_recv_tag = "dmu_recv_tag";
63 static const char *recv_clone_name = "%recv";
64 
65 #define	BP_SPAN(datablkszsec, indblkshift, level) \
66 	(((uint64_t)datablkszsec) << (SPA_MINBLOCKSHIFT + \
67 	(level) * (indblkshift - SPA_BLKPTRSHIFT)))
68 
69 struct send_thread_arg {
70 	bqueue_t	q;
71 	dsl_dataset_t	*ds;		/* Dataset to traverse */
72 	uint64_t	fromtxg;	/* Traverse from this txg */
73 	int		flags;		/* flags to pass to traverse_dataset */
74 	int		error_code;
75 	boolean_t	cancel;
76 };
77 
78 struct send_block_record {
79 	boolean_t		eos_marker; /* Marks the end of the stream */
80 	blkptr_t		bp;
81 	zbookmark_phys_t	zb;
82 	uint8_t			indblkshift;
83 	uint16_t		datablkszsec;
84 	bqueue_node_t		ln;
85 };
86 
87 static int
88 dump_bytes(dmu_sendarg_t *dsp, void *buf, int len)
89 {
90 	dsl_dataset_t *ds = dsp->dsa_os->os_dsl_dataset;
91 	ssize_t resid; /* have to get resid to get detailed errno */
92 	ASSERT0(len % 8);
93 
94 	dsp->dsa_err = vn_rdwr(UIO_WRITE, dsp->dsa_vp,
95 	    (caddr_t)buf, len,
96 	    0, UIO_SYSSPACE, FAPPEND, RLIM64_INFINITY, CRED(), &resid);
97 
98 	mutex_enter(&ds->ds_sendstream_lock);
99 	*dsp->dsa_off += len;
100 	mutex_exit(&ds->ds_sendstream_lock);
101 
102 	return (dsp->dsa_err);
103 }
104 
105 /*
106  * For all record types except BEGIN, fill in the checksum (overlaid in
107  * drr_u.drr_checksum.drr_checksum).  The checksum verifies everything
108  * up to the start of the checksum itself.
109  */
110 static int
111 dump_record(dmu_sendarg_t *dsp, void *payload, int payload_len)
112 {
113 	ASSERT3U(offsetof(dmu_replay_record_t, drr_u.drr_checksum.drr_checksum),
114 	    ==, sizeof (dmu_replay_record_t) - sizeof (zio_cksum_t));
115 	fletcher_4_incremental_native(dsp->dsa_drr,
116 	    offsetof(dmu_replay_record_t, drr_u.drr_checksum.drr_checksum),
117 	    &dsp->dsa_zc);
118 	if (dsp->dsa_drr->drr_type != DRR_BEGIN) {
119 		ASSERT(ZIO_CHECKSUM_IS_ZERO(&dsp->dsa_drr->drr_u.
120 		    drr_checksum.drr_checksum));
121 		dsp->dsa_drr->drr_u.drr_checksum.drr_checksum = dsp->dsa_zc;
122 	}
123 	fletcher_4_incremental_native(&dsp->dsa_drr->
124 	    drr_u.drr_checksum.drr_checksum,
125 	    sizeof (zio_cksum_t), &dsp->dsa_zc);
126 	if (dump_bytes(dsp, dsp->dsa_drr, sizeof (dmu_replay_record_t)) != 0)
127 		return (SET_ERROR(EINTR));
128 	if (payload_len != 0) {
129 		fletcher_4_incremental_native(payload, payload_len,
130 		    &dsp->dsa_zc);
131 		if (dump_bytes(dsp, payload, payload_len) != 0)
132 			return (SET_ERROR(EINTR));
133 	}
134 	return (0);
135 }
136 
137 static int
138 dump_free(dmu_sendarg_t *dsp, uint64_t object, uint64_t offset,
139     uint64_t length)
140 {
141 	struct drr_free *drrf = &(dsp->dsa_drr->drr_u.drr_free);
142 
143 	/*
144 	 * When we receive a free record, dbuf_free_range() assumes
145 	 * that the receiving system doesn't have any dbufs in the range
146 	 * being freed.  This is always true because there is a one-record
147 	 * constraint: we only send one WRITE record for any given
148 	 * object+offset.  We know that the one-record constraint is
149 	 * true because we always send data in increasing order by
150 	 * object,offset.
151 	 *
152 	 * If the increasing-order constraint ever changes, we should find
153 	 * another way to assert that the one-record constraint is still
154 	 * satisfied.
155 	 */
156 	ASSERT(object > dsp->dsa_last_data_object ||
157 	    (object == dsp->dsa_last_data_object &&
158 	    offset > dsp->dsa_last_data_offset));
159 
160 	/*
161 	 * If we are doing a non-incremental send, then there can't
162 	 * be any data in the dataset we're receiving into.  Therefore
163 	 * a free record would simply be a no-op.  Save space by not
164 	 * sending it to begin with.
165 	 */
166 	if (!dsp->dsa_incremental)
167 		return (0);
168 
169 	if (length != -1ULL && offset + length < offset)
170 		length = -1ULL;
171 
172 	/*
173 	 * If there is a pending op, but it's not PENDING_FREE, push it out,
174 	 * since free block aggregation can only be done for blocks of the
175 	 * same type (i.e., DRR_FREE records can only be aggregated with
176 	 * other DRR_FREE records.  DRR_FREEOBJECTS records can only be
177 	 * aggregated with other DRR_FREEOBJECTS records.
178 	 */
179 	if (dsp->dsa_pending_op != PENDING_NONE &&
180 	    dsp->dsa_pending_op != PENDING_FREE) {
181 		if (dump_record(dsp, NULL, 0) != 0)
182 			return (SET_ERROR(EINTR));
183 		dsp->dsa_pending_op = PENDING_NONE;
184 	}
185 
186 	if (dsp->dsa_pending_op == PENDING_FREE) {
187 		/*
188 		 * There should never be a PENDING_FREE if length is -1
189 		 * (because dump_dnode is the only place where this
190 		 * function is called with a -1, and only after flushing
191 		 * any pending record).
192 		 */
193 		ASSERT(length != -1ULL);
194 		/*
195 		 * Check to see whether this free block can be aggregated
196 		 * with pending one.
197 		 */
198 		if (drrf->drr_object == object && drrf->drr_offset +
199 		    drrf->drr_length == offset) {
200 			drrf->drr_length += length;
201 			return (0);
202 		} else {
203 			/* not a continuation.  Push out pending record */
204 			if (dump_record(dsp, NULL, 0) != 0)
205 				return (SET_ERROR(EINTR));
206 			dsp->dsa_pending_op = PENDING_NONE;
207 		}
208 	}
209 	/* create a FREE record and make it pending */
210 	bzero(dsp->dsa_drr, sizeof (dmu_replay_record_t));
211 	dsp->dsa_drr->drr_type = DRR_FREE;
212 	drrf->drr_object = object;
213 	drrf->drr_offset = offset;
214 	drrf->drr_length = length;
215 	drrf->drr_toguid = dsp->dsa_toguid;
216 	if (length == -1ULL) {
217 		if (dump_record(dsp, NULL, 0) != 0)
218 			return (SET_ERROR(EINTR));
219 	} else {
220 		dsp->dsa_pending_op = PENDING_FREE;
221 	}
222 
223 	return (0);
224 }
225 
226 static int
227 dump_write(dmu_sendarg_t *dsp, dmu_object_type_t type,
228     uint64_t object, uint64_t offset, int blksz, const blkptr_t *bp, void *data)
229 {
230 	struct drr_write *drrw = &(dsp->dsa_drr->drr_u.drr_write);
231 
232 	/*
233 	 * We send data in increasing object, offset order.
234 	 * See comment in dump_free() for details.
235 	 */
236 	ASSERT(object > dsp->dsa_last_data_object ||
237 	    (object == dsp->dsa_last_data_object &&
238 	    offset > dsp->dsa_last_data_offset));
239 	dsp->dsa_last_data_object = object;
240 	dsp->dsa_last_data_offset = offset + blksz - 1;
241 
242 	/*
243 	 * If there is any kind of pending aggregation (currently either
244 	 * a grouping of free objects or free blocks), push it out to
245 	 * the stream, since aggregation can't be done across operations
246 	 * of different types.
247 	 */
248 	if (dsp->dsa_pending_op != PENDING_NONE) {
249 		if (dump_record(dsp, NULL, 0) != 0)
250 			return (SET_ERROR(EINTR));
251 		dsp->dsa_pending_op = PENDING_NONE;
252 	}
253 	/* write a WRITE record */
254 	bzero(dsp->dsa_drr, sizeof (dmu_replay_record_t));
255 	dsp->dsa_drr->drr_type = DRR_WRITE;
256 	drrw->drr_object = object;
257 	drrw->drr_type = type;
258 	drrw->drr_offset = offset;
259 	drrw->drr_length = blksz;
260 	drrw->drr_toguid = dsp->dsa_toguid;
261 	if (bp == NULL || BP_IS_EMBEDDED(bp)) {
262 		/*
263 		 * There's no pre-computed checksum for partial-block
264 		 * writes or embedded BP's, so (like
265 		 * fletcher4-checkummed blocks) userland will have to
266 		 * compute a dedup-capable checksum itself.
267 		 */
268 		drrw->drr_checksumtype = ZIO_CHECKSUM_OFF;
269 	} else {
270 		drrw->drr_checksumtype = BP_GET_CHECKSUM(bp);
271 		if (zio_checksum_table[drrw->drr_checksumtype].ci_flags &
272 		    ZCHECKSUM_FLAG_DEDUP)
273 			drrw->drr_checksumflags |= DRR_CHECKSUM_DEDUP;
274 		DDK_SET_LSIZE(&drrw->drr_key, BP_GET_LSIZE(bp));
275 		DDK_SET_PSIZE(&drrw->drr_key, BP_GET_PSIZE(bp));
276 		DDK_SET_COMPRESS(&drrw->drr_key, BP_GET_COMPRESS(bp));
277 		drrw->drr_key.ddk_cksum = bp->blk_cksum;
278 	}
279 
280 	if (dump_record(dsp, data, blksz) != 0)
281 		return (SET_ERROR(EINTR));
282 	return (0);
283 }
284 
285 static int
286 dump_write_embedded(dmu_sendarg_t *dsp, uint64_t object, uint64_t offset,
287     int blksz, const blkptr_t *bp)
288 {
289 	char buf[BPE_PAYLOAD_SIZE];
290 	struct drr_write_embedded *drrw =
291 	    &(dsp->dsa_drr->drr_u.drr_write_embedded);
292 
293 	if (dsp->dsa_pending_op != PENDING_NONE) {
294 		if (dump_record(dsp, NULL, 0) != 0)
295 			return (EINTR);
296 		dsp->dsa_pending_op = PENDING_NONE;
297 	}
298 
299 	ASSERT(BP_IS_EMBEDDED(bp));
300 
301 	bzero(dsp->dsa_drr, sizeof (dmu_replay_record_t));
302 	dsp->dsa_drr->drr_type = DRR_WRITE_EMBEDDED;
303 	drrw->drr_object = object;
304 	drrw->drr_offset = offset;
305 	drrw->drr_length = blksz;
306 	drrw->drr_toguid = dsp->dsa_toguid;
307 	drrw->drr_compression = BP_GET_COMPRESS(bp);
308 	drrw->drr_etype = BPE_GET_ETYPE(bp);
309 	drrw->drr_lsize = BPE_GET_LSIZE(bp);
310 	drrw->drr_psize = BPE_GET_PSIZE(bp);
311 
312 	decode_embedded_bp_compressed(bp, buf);
313 
314 	if (dump_record(dsp, buf, P2ROUNDUP(drrw->drr_psize, 8)) != 0)
315 		return (EINTR);
316 	return (0);
317 }
318 
319 static int
320 dump_spill(dmu_sendarg_t *dsp, uint64_t object, int blksz, void *data)
321 {
322 	struct drr_spill *drrs = &(dsp->dsa_drr->drr_u.drr_spill);
323 
324 	if (dsp->dsa_pending_op != PENDING_NONE) {
325 		if (dump_record(dsp, NULL, 0) != 0)
326 			return (SET_ERROR(EINTR));
327 		dsp->dsa_pending_op = PENDING_NONE;
328 	}
329 
330 	/* write a SPILL record */
331 	bzero(dsp->dsa_drr, sizeof (dmu_replay_record_t));
332 	dsp->dsa_drr->drr_type = DRR_SPILL;
333 	drrs->drr_object = object;
334 	drrs->drr_length = blksz;
335 	drrs->drr_toguid = dsp->dsa_toguid;
336 
337 	if (dump_record(dsp, data, blksz) != 0)
338 		return (SET_ERROR(EINTR));
339 	return (0);
340 }
341 
342 static int
343 dump_freeobjects(dmu_sendarg_t *dsp, uint64_t firstobj, uint64_t numobjs)
344 {
345 	struct drr_freeobjects *drrfo = &(dsp->dsa_drr->drr_u.drr_freeobjects);
346 
347 	/* See comment in dump_free(). */
348 	if (!dsp->dsa_incremental)
349 		return (0);
350 
351 	/*
352 	 * If there is a pending op, but it's not PENDING_FREEOBJECTS,
353 	 * push it out, since free block aggregation can only be done for
354 	 * blocks of the same type (i.e., DRR_FREE records can only be
355 	 * aggregated with other DRR_FREE records.  DRR_FREEOBJECTS records
356 	 * can only be aggregated with other DRR_FREEOBJECTS records.
357 	 */
358 	if (dsp->dsa_pending_op != PENDING_NONE &&
359 	    dsp->dsa_pending_op != PENDING_FREEOBJECTS) {
360 		if (dump_record(dsp, NULL, 0) != 0)
361 			return (SET_ERROR(EINTR));
362 		dsp->dsa_pending_op = PENDING_NONE;
363 	}
364 	if (dsp->dsa_pending_op == PENDING_FREEOBJECTS) {
365 		/*
366 		 * See whether this free object array can be aggregated
367 		 * with pending one
368 		 */
369 		if (drrfo->drr_firstobj + drrfo->drr_numobjs == firstobj) {
370 			drrfo->drr_numobjs += numobjs;
371 			return (0);
372 		} else {
373 			/* can't be aggregated.  Push out pending record */
374 			if (dump_record(dsp, NULL, 0) != 0)
375 				return (SET_ERROR(EINTR));
376 			dsp->dsa_pending_op = PENDING_NONE;
377 		}
378 	}
379 
380 	/* write a FREEOBJECTS record */
381 	bzero(dsp->dsa_drr, sizeof (dmu_replay_record_t));
382 	dsp->dsa_drr->drr_type = DRR_FREEOBJECTS;
383 	drrfo->drr_firstobj = firstobj;
384 	drrfo->drr_numobjs = numobjs;
385 	drrfo->drr_toguid = dsp->dsa_toguid;
386 
387 	dsp->dsa_pending_op = PENDING_FREEOBJECTS;
388 
389 	return (0);
390 }
391 
392 static int
393 dump_dnode(dmu_sendarg_t *dsp, uint64_t object, dnode_phys_t *dnp)
394 {
395 	struct drr_object *drro = &(dsp->dsa_drr->drr_u.drr_object);
396 
397 	if (dnp == NULL || dnp->dn_type == DMU_OT_NONE)
398 		return (dump_freeobjects(dsp, object, 1));
399 
400 	if (dsp->dsa_pending_op != PENDING_NONE) {
401 		if (dump_record(dsp, NULL, 0) != 0)
402 			return (SET_ERROR(EINTR));
403 		dsp->dsa_pending_op = PENDING_NONE;
404 	}
405 
406 	/* write an OBJECT record */
407 	bzero(dsp->dsa_drr, sizeof (dmu_replay_record_t));
408 	dsp->dsa_drr->drr_type = DRR_OBJECT;
409 	drro->drr_object = object;
410 	drro->drr_type = dnp->dn_type;
411 	drro->drr_bonustype = dnp->dn_bonustype;
412 	drro->drr_blksz = dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT;
413 	drro->drr_bonuslen = dnp->dn_bonuslen;
414 	drro->drr_checksumtype = dnp->dn_checksum;
415 	drro->drr_compress = dnp->dn_compress;
416 	drro->drr_toguid = dsp->dsa_toguid;
417 
418 	if (!(dsp->dsa_featureflags & DMU_BACKUP_FEATURE_LARGE_BLOCKS) &&
419 	    drro->drr_blksz > SPA_OLD_MAXBLOCKSIZE)
420 		drro->drr_blksz = SPA_OLD_MAXBLOCKSIZE;
421 
422 	if (dump_record(dsp, DN_BONUS(dnp),
423 	    P2ROUNDUP(dnp->dn_bonuslen, 8)) != 0) {
424 		return (SET_ERROR(EINTR));
425 	}
426 
427 	/* Free anything past the end of the file. */
428 	if (dump_free(dsp, object, (dnp->dn_maxblkid + 1) *
429 	    (dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT), -1ULL) != 0)
430 		return (SET_ERROR(EINTR));
431 	if (dsp->dsa_err != 0)
432 		return (SET_ERROR(EINTR));
433 	return (0);
434 }
435 
436 static boolean_t
437 backup_do_embed(dmu_sendarg_t *dsp, const blkptr_t *bp)
438 {
439 	if (!BP_IS_EMBEDDED(bp))
440 		return (B_FALSE);
441 
442 	/*
443 	 * Compression function must be legacy, or explicitly enabled.
444 	 */
445 	if ((BP_GET_COMPRESS(bp) >= ZIO_COMPRESS_LEGACY_FUNCTIONS &&
446 	    !(dsp->dsa_featureflags & DMU_BACKUP_FEATURE_EMBED_DATA_LZ4)))
447 		return (B_FALSE);
448 
449 	/*
450 	 * Embed type must be explicitly enabled.
451 	 */
452 	switch (BPE_GET_ETYPE(bp)) {
453 	case BP_EMBEDDED_TYPE_DATA:
454 		if (dsp->dsa_featureflags & DMU_BACKUP_FEATURE_EMBED_DATA)
455 			return (B_TRUE);
456 		break;
457 	default:
458 		return (B_FALSE);
459 	}
460 	return (B_FALSE);
461 }
462 
463 /*
464  * This is the callback function to traverse_dataset that acts as the worker
465  * thread for dmu_send_impl.
466  */
467 /*ARGSUSED*/
468 static int
469 send_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
470     const zbookmark_phys_t *zb, const struct dnode_phys *dnp, void *arg)
471 {
472 	struct send_thread_arg *sta = arg;
473 	struct send_block_record *record;
474 	uint64_t record_size;
475 	int err = 0;
476 
477 	if (sta->cancel)
478 		return (SET_ERROR(EINTR));
479 
480 	if (bp == NULL) {
481 		ASSERT3U(zb->zb_level, ==, ZB_DNODE_LEVEL);
482 		return (0);
483 	} else if (zb->zb_level < 0) {
484 		return (0);
485 	}
486 
487 	record = kmem_zalloc(sizeof (struct send_block_record), KM_SLEEP);
488 	record->eos_marker = B_FALSE;
489 	record->bp = *bp;
490 	record->zb = *zb;
491 	record->indblkshift = dnp->dn_indblkshift;
492 	record->datablkszsec = dnp->dn_datablkszsec;
493 	record_size = dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT;
494 	bqueue_enqueue(&sta->q, record, record_size);
495 
496 	return (err);
497 }
498 
499 /*
500  * This function kicks off the traverse_dataset.  It also handles setting the
501  * error code of the thread in case something goes wrong, and pushes the End of
502  * Stream record when the traverse_dataset call has finished.  If there is no
503  * dataset to traverse, the thread immediately pushes End of Stream marker.
504  */
505 static void
506 send_traverse_thread(void *arg)
507 {
508 	struct send_thread_arg *st_arg = arg;
509 	int err;
510 	struct send_block_record *data;
511 
512 	if (st_arg->ds != NULL) {
513 		err = traverse_dataset(st_arg->ds, st_arg->fromtxg,
514 		    st_arg->flags, send_cb, arg);
515 		if (err != EINTR)
516 			st_arg->error_code = err;
517 	}
518 	data = kmem_zalloc(sizeof (*data), KM_SLEEP);
519 	data->eos_marker = B_TRUE;
520 	bqueue_enqueue(&st_arg->q, data, 1);
521 }
522 
523 /*
524  * This function actually handles figuring out what kind of record needs to be
525  * dumped, reading the data (which has hopefully been prefetched), and calling
526  * the appropriate helper function.
527  */
528 static int
529 do_dump(dmu_sendarg_t *dsa, struct send_block_record *data)
530 {
531 	dsl_dataset_t *ds = dmu_objset_ds(dsa->dsa_os);
532 	const blkptr_t *bp = &data->bp;
533 	const zbookmark_phys_t *zb = &data->zb;
534 	uint8_t indblkshift = data->indblkshift;
535 	uint16_t dblkszsec = data->datablkszsec;
536 	spa_t *spa = ds->ds_dir->dd_pool->dp_spa;
537 	dmu_object_type_t type = bp ? BP_GET_TYPE(bp) : DMU_OT_NONE;
538 	int err = 0;
539 
540 	ASSERT3U(zb->zb_level, >=, 0);
541 
542 	if (zb->zb_object != DMU_META_DNODE_OBJECT &&
543 	    DMU_OBJECT_IS_SPECIAL(zb->zb_object)) {
544 		return (0);
545 	} else if (BP_IS_HOLE(bp) &&
546 	    zb->zb_object == DMU_META_DNODE_OBJECT) {
547 		uint64_t span = BP_SPAN(dblkszsec, indblkshift, zb->zb_level);
548 		uint64_t dnobj = (zb->zb_blkid * span) >> DNODE_SHIFT;
549 		err = dump_freeobjects(dsa, dnobj, span >> DNODE_SHIFT);
550 	} else if (BP_IS_HOLE(bp)) {
551 		uint64_t span = BP_SPAN(dblkszsec, indblkshift, zb->zb_level);
552 		uint64_t offset = zb->zb_blkid * span;
553 		err = dump_free(dsa, zb->zb_object, offset, span);
554 	} else if (zb->zb_level > 0 || type == DMU_OT_OBJSET) {
555 		return (0);
556 	} else if (type == DMU_OT_DNODE) {
557 		int blksz = BP_GET_LSIZE(bp);
558 		arc_flags_t aflags = ARC_FLAG_WAIT;
559 		arc_buf_t *abuf;
560 
561 		ASSERT0(zb->zb_level);
562 
563 		if (arc_read(NULL, spa, bp, arc_getbuf_func, &abuf,
564 		    ZIO_PRIORITY_ASYNC_READ, ZIO_FLAG_CANFAIL,
565 		    &aflags, zb) != 0)
566 			return (SET_ERROR(EIO));
567 
568 		dnode_phys_t *blk = abuf->b_data;
569 		uint64_t dnobj = zb->zb_blkid * (blksz >> DNODE_SHIFT);
570 		for (int i = 0; i < blksz >> DNODE_SHIFT; i++) {
571 			err = dump_dnode(dsa, dnobj + i, blk + i);
572 			if (err != 0)
573 				break;
574 		}
575 		(void) arc_buf_remove_ref(abuf, &abuf);
576 	} else if (type == DMU_OT_SA) {
577 		arc_flags_t aflags = ARC_FLAG_WAIT;
578 		arc_buf_t *abuf;
579 		int blksz = BP_GET_LSIZE(bp);
580 
581 		if (arc_read(NULL, spa, bp, arc_getbuf_func, &abuf,
582 		    ZIO_PRIORITY_ASYNC_READ, ZIO_FLAG_CANFAIL,
583 		    &aflags, zb) != 0)
584 			return (SET_ERROR(EIO));
585 
586 		err = dump_spill(dsa, zb->zb_object, blksz, abuf->b_data);
587 		(void) arc_buf_remove_ref(abuf, &abuf);
588 	} else if (backup_do_embed(dsa, bp)) {
589 		/* it's an embedded level-0 block of a regular object */
590 		int blksz = dblkszsec << SPA_MINBLOCKSHIFT;
591 		ASSERT0(zb->zb_level);
592 		err = dump_write_embedded(dsa, zb->zb_object,
593 		    zb->zb_blkid * blksz, blksz, bp);
594 	} else {
595 		/* it's a level-0 block of a regular object */
596 		arc_flags_t aflags = ARC_FLAG_WAIT;
597 		arc_buf_t *abuf;
598 		int blksz = dblkszsec << SPA_MINBLOCKSHIFT;
599 		uint64_t offset;
600 
601 		ASSERT0(zb->zb_level);
602 		if (arc_read(NULL, spa, bp, arc_getbuf_func, &abuf,
603 		    ZIO_PRIORITY_ASYNC_READ, ZIO_FLAG_CANFAIL,
604 		    &aflags, zb) != 0) {
605 			if (zfs_send_corrupt_data) {
606 				/* Send a block filled with 0x"zfs badd bloc" */
607 				abuf = arc_buf_alloc(spa, blksz, &abuf,
608 				    ARC_BUFC_DATA);
609 				uint64_t *ptr;
610 				for (ptr = abuf->b_data;
611 				    (char *)ptr < (char *)abuf->b_data + blksz;
612 				    ptr++)
613 					*ptr = 0x2f5baddb10cULL;
614 			} else {
615 				return (SET_ERROR(EIO));
616 			}
617 		}
618 
619 		offset = zb->zb_blkid * blksz;
620 
621 		if (!(dsa->dsa_featureflags &
622 		    DMU_BACKUP_FEATURE_LARGE_BLOCKS) &&
623 		    blksz > SPA_OLD_MAXBLOCKSIZE) {
624 			char *buf = abuf->b_data;
625 			while (blksz > 0 && err == 0) {
626 				int n = MIN(blksz, SPA_OLD_MAXBLOCKSIZE);
627 				err = dump_write(dsa, type, zb->zb_object,
628 				    offset, n, NULL, buf);
629 				offset += n;
630 				buf += n;
631 				blksz -= n;
632 			}
633 		} else {
634 			err = dump_write(dsa, type, zb->zb_object,
635 			    offset, blksz, bp, abuf->b_data);
636 		}
637 		(void) arc_buf_remove_ref(abuf, &abuf);
638 	}
639 
640 	ASSERT(err == 0 || err == EINTR);
641 	return (err);
642 }
643 
644 /*
645  * Pop the new data off the queue, and free the old data.
646  */
647 static struct send_block_record *
648 get_next_record(bqueue_t *bq, struct send_block_record *data)
649 {
650 	struct send_block_record *tmp = bqueue_dequeue(bq);
651 	kmem_free(data, sizeof (*data));
652 	return (tmp);
653 }
654 
655 /*
656  * Actually do the bulk of the work in a zfs send.
657  *
658  * Note: Releases dp using the specified tag.
659  */
660 static int
661 dmu_send_impl(void *tag, dsl_pool_t *dp, dsl_dataset_t *to_ds,
662     zfs_bookmark_phys_t *ancestor_zb, boolean_t is_clone, boolean_t embedok,
663     boolean_t large_block_ok, int outfd, vnode_t *vp, offset_t *off)
664 {
665 	objset_t *os;
666 	dmu_replay_record_t *drr;
667 	dmu_sendarg_t *dsp;
668 	int err;
669 	uint64_t fromtxg = 0;
670 	uint64_t featureflags = 0;
671 	struct send_thread_arg to_arg;
672 
673 	err = dmu_objset_from_ds(to_ds, &os);
674 	if (err != 0) {
675 		dsl_pool_rele(dp, tag);
676 		return (err);
677 	}
678 
679 	drr = kmem_zalloc(sizeof (dmu_replay_record_t), KM_SLEEP);
680 	drr->drr_type = DRR_BEGIN;
681 	drr->drr_u.drr_begin.drr_magic = DMU_BACKUP_MAGIC;
682 	DMU_SET_STREAM_HDRTYPE(drr->drr_u.drr_begin.drr_versioninfo,
683 	    DMU_SUBSTREAM);
684 
685 #ifdef _KERNEL
686 	if (dmu_objset_type(os) == DMU_OST_ZFS) {
687 		uint64_t version;
688 		if (zfs_get_zplprop(os, ZFS_PROP_VERSION, &version) != 0) {
689 			kmem_free(drr, sizeof (dmu_replay_record_t));
690 			dsl_pool_rele(dp, tag);
691 			return (SET_ERROR(EINVAL));
692 		}
693 		if (version >= ZPL_VERSION_SA) {
694 			featureflags |= DMU_BACKUP_FEATURE_SA_SPILL;
695 		}
696 	}
697 #endif
698 
699 	if (large_block_ok && to_ds->ds_feature_inuse[SPA_FEATURE_LARGE_BLOCKS])
700 		featureflags |= DMU_BACKUP_FEATURE_LARGE_BLOCKS;
701 	if (embedok &&
702 	    spa_feature_is_active(dp->dp_spa, SPA_FEATURE_EMBEDDED_DATA)) {
703 		featureflags |= DMU_BACKUP_FEATURE_EMBED_DATA;
704 		if (spa_feature_is_active(dp->dp_spa, SPA_FEATURE_LZ4_COMPRESS))
705 			featureflags |= DMU_BACKUP_FEATURE_EMBED_DATA_LZ4;
706 	}
707 
708 	DMU_SET_FEATUREFLAGS(drr->drr_u.drr_begin.drr_versioninfo,
709 	    featureflags);
710 
711 	drr->drr_u.drr_begin.drr_creation_time =
712 	    dsl_dataset_phys(to_ds)->ds_creation_time;
713 	drr->drr_u.drr_begin.drr_type = dmu_objset_type(os);
714 	if (is_clone)
715 		drr->drr_u.drr_begin.drr_flags |= DRR_FLAG_CLONE;
716 	drr->drr_u.drr_begin.drr_toguid = dsl_dataset_phys(to_ds)->ds_guid;
717 	if (dsl_dataset_phys(to_ds)->ds_flags & DS_FLAG_CI_DATASET)
718 		drr->drr_u.drr_begin.drr_flags |= DRR_FLAG_CI_DATA;
719 
720 	if (ancestor_zb != NULL) {
721 		drr->drr_u.drr_begin.drr_fromguid =
722 		    ancestor_zb->zbm_guid;
723 		fromtxg = ancestor_zb->zbm_creation_txg;
724 	}
725 	dsl_dataset_name(to_ds, drr->drr_u.drr_begin.drr_toname);
726 	if (!to_ds->ds_is_snapshot) {
727 		(void) strlcat(drr->drr_u.drr_begin.drr_toname, "@--head--",
728 		    sizeof (drr->drr_u.drr_begin.drr_toname));
729 	}
730 
731 	dsp = kmem_zalloc(sizeof (dmu_sendarg_t), KM_SLEEP);
732 
733 	dsp->dsa_drr = drr;
734 	dsp->dsa_vp = vp;
735 	dsp->dsa_outfd = outfd;
736 	dsp->dsa_proc = curproc;
737 	dsp->dsa_os = os;
738 	dsp->dsa_off = off;
739 	dsp->dsa_toguid = dsl_dataset_phys(to_ds)->ds_guid;
740 	dsp->dsa_pending_op = PENDING_NONE;
741 	dsp->dsa_incremental = (ancestor_zb != NULL);
742 	dsp->dsa_featureflags = featureflags;
743 
744 	mutex_enter(&to_ds->ds_sendstream_lock);
745 	list_insert_head(&to_ds->ds_sendstreams, dsp);
746 	mutex_exit(&to_ds->ds_sendstream_lock);
747 
748 	dsl_dataset_long_hold(to_ds, FTAG);
749 	dsl_pool_rele(dp, tag);
750 
751 	if (dump_record(dsp, NULL, 0) != 0) {
752 		err = dsp->dsa_err;
753 		goto out;
754 	}
755 
756 	err = bqueue_init(&to_arg.q, zfs_send_queue_length,
757 	    offsetof(struct send_block_record, ln));
758 	to_arg.error_code = 0;
759 	to_arg.cancel = B_FALSE;
760 	to_arg.ds = to_ds;
761 	to_arg.fromtxg = fromtxg;
762 	to_arg.flags = TRAVERSE_PRE | TRAVERSE_PREFETCH;
763 	(void) thread_create(NULL, 0, send_traverse_thread, &to_arg, 0, curproc,
764 	    TS_RUN, minclsyspri);
765 
766 	struct send_block_record *to_data;
767 	to_data = bqueue_dequeue(&to_arg.q);
768 
769 	while (!to_data->eos_marker && err == 0) {
770 		err = do_dump(dsp, to_data);
771 		to_data = get_next_record(&to_arg.q, to_data);
772 		if (issig(JUSTLOOKING) && issig(FORREAL))
773 			err = EINTR;
774 	}
775 
776 	if (err != 0) {
777 		to_arg.cancel = B_TRUE;
778 		while (!to_data->eos_marker) {
779 			to_data = get_next_record(&to_arg.q, to_data);
780 		}
781 	}
782 	kmem_free(to_data, sizeof (*to_data));
783 
784 	bqueue_destroy(&to_arg.q);
785 
786 	if (err == 0 && to_arg.error_code != 0)
787 		err = to_arg.error_code;
788 
789 	if (err != 0)
790 		goto out;
791 
792 	if (dsp->dsa_pending_op != PENDING_NONE)
793 		if (dump_record(dsp, NULL, 0) != 0)
794 			err = SET_ERROR(EINTR);
795 
796 	if (err != 0) {
797 		if (err == EINTR && dsp->dsa_err != 0)
798 			err = dsp->dsa_err;
799 		goto out;
800 	}
801 
802 	bzero(drr, sizeof (dmu_replay_record_t));
803 	drr->drr_type = DRR_END;
804 	drr->drr_u.drr_end.drr_checksum = dsp->dsa_zc;
805 	drr->drr_u.drr_end.drr_toguid = dsp->dsa_toguid;
806 
807 	if (dump_record(dsp, NULL, 0) != 0)
808 		err = dsp->dsa_err;
809 
810 out:
811 	mutex_enter(&to_ds->ds_sendstream_lock);
812 	list_remove(&to_ds->ds_sendstreams, dsp);
813 	mutex_exit(&to_ds->ds_sendstream_lock);
814 
815 	kmem_free(drr, sizeof (dmu_replay_record_t));
816 	kmem_free(dsp, sizeof (dmu_sendarg_t));
817 
818 	dsl_dataset_long_rele(to_ds, FTAG);
819 
820 	return (err);
821 }
822 
823 int
824 dmu_send_obj(const char *pool, uint64_t tosnap, uint64_t fromsnap,
825     boolean_t embedok, boolean_t large_block_ok,
826     int outfd, vnode_t *vp, offset_t *off)
827 {
828 	dsl_pool_t *dp;
829 	dsl_dataset_t *ds;
830 	dsl_dataset_t *fromds = NULL;
831 	int err;
832 
833 	err = dsl_pool_hold(pool, FTAG, &dp);
834 	if (err != 0)
835 		return (err);
836 
837 	err = dsl_dataset_hold_obj(dp, tosnap, FTAG, &ds);
838 	if (err != 0) {
839 		dsl_pool_rele(dp, FTAG);
840 		return (err);
841 	}
842 
843 	if (fromsnap != 0) {
844 		zfs_bookmark_phys_t zb;
845 		boolean_t is_clone;
846 
847 		err = dsl_dataset_hold_obj(dp, fromsnap, FTAG, &fromds);
848 		if (err != 0) {
849 			dsl_dataset_rele(ds, FTAG);
850 			dsl_pool_rele(dp, FTAG);
851 			return (err);
852 		}
853 		if (!dsl_dataset_is_before(ds, fromds, 0))
854 			err = SET_ERROR(EXDEV);
855 		zb.zbm_creation_time =
856 		    dsl_dataset_phys(fromds)->ds_creation_time;
857 		zb.zbm_creation_txg = dsl_dataset_phys(fromds)->ds_creation_txg;
858 		zb.zbm_guid = dsl_dataset_phys(fromds)->ds_guid;
859 		is_clone = (fromds->ds_dir != ds->ds_dir);
860 		dsl_dataset_rele(fromds, FTAG);
861 		err = dmu_send_impl(FTAG, dp, ds, &zb, is_clone,
862 		    embedok, large_block_ok, outfd, vp, off);
863 	} else {
864 		err = dmu_send_impl(FTAG, dp, ds, NULL, B_FALSE,
865 		    embedok, large_block_ok, outfd, vp, off);
866 	}
867 	dsl_dataset_rele(ds, FTAG);
868 	return (err);
869 }
870 
871 int
872 dmu_send(const char *tosnap, const char *fromsnap,
873     boolean_t embedok, boolean_t large_block_ok,
874     int outfd, vnode_t *vp, offset_t *off)
875 {
876 	dsl_pool_t *dp;
877 	dsl_dataset_t *ds;
878 	int err;
879 	boolean_t owned = B_FALSE;
880 
881 	if (fromsnap != NULL && strpbrk(fromsnap, "@#") == NULL)
882 		return (SET_ERROR(EINVAL));
883 
884 	err = dsl_pool_hold(tosnap, FTAG, &dp);
885 	if (err != 0)
886 		return (err);
887 
888 	if (strchr(tosnap, '@') == NULL && spa_writeable(dp->dp_spa)) {
889 		/*
890 		 * We are sending a filesystem or volume.  Ensure
891 		 * that it doesn't change by owning the dataset.
892 		 */
893 		err = dsl_dataset_own(dp, tosnap, FTAG, &ds);
894 		owned = B_TRUE;
895 	} else {
896 		err = dsl_dataset_hold(dp, tosnap, FTAG, &ds);
897 	}
898 	if (err != 0) {
899 		dsl_pool_rele(dp, FTAG);
900 		return (err);
901 	}
902 
903 	if (fromsnap != NULL) {
904 		zfs_bookmark_phys_t zb;
905 		boolean_t is_clone = B_FALSE;
906 		int fsnamelen = strchr(tosnap, '@') - tosnap;
907 
908 		/*
909 		 * If the fromsnap is in a different filesystem, then
910 		 * mark the send stream as a clone.
911 		 */
912 		if (strncmp(tosnap, fromsnap, fsnamelen) != 0 ||
913 		    (fromsnap[fsnamelen] != '@' &&
914 		    fromsnap[fsnamelen] != '#')) {
915 			is_clone = B_TRUE;
916 		}
917 
918 		if (strchr(fromsnap, '@')) {
919 			dsl_dataset_t *fromds;
920 			err = dsl_dataset_hold(dp, fromsnap, FTAG, &fromds);
921 			if (err == 0) {
922 				if (!dsl_dataset_is_before(ds, fromds, 0))
923 					err = SET_ERROR(EXDEV);
924 				zb.zbm_creation_time =
925 				    dsl_dataset_phys(fromds)->ds_creation_time;
926 				zb.zbm_creation_txg =
927 				    dsl_dataset_phys(fromds)->ds_creation_txg;
928 				zb.zbm_guid = dsl_dataset_phys(fromds)->ds_guid;
929 				is_clone = (ds->ds_dir != fromds->ds_dir);
930 				dsl_dataset_rele(fromds, FTAG);
931 			}
932 		} else {
933 			err = dsl_bookmark_lookup(dp, fromsnap, ds, &zb);
934 		}
935 		if (err != 0) {
936 			dsl_dataset_rele(ds, FTAG);
937 			dsl_pool_rele(dp, FTAG);
938 			return (err);
939 		}
940 		err = dmu_send_impl(FTAG, dp, ds, &zb, is_clone,
941 		    embedok, large_block_ok, outfd, vp, off);
942 	} else {
943 		err = dmu_send_impl(FTAG, dp, ds, NULL, B_FALSE,
944 		    embedok, large_block_ok, outfd, vp, off);
945 	}
946 	if (owned)
947 		dsl_dataset_disown(ds, FTAG);
948 	else
949 		dsl_dataset_rele(ds, FTAG);
950 	return (err);
951 }
952 
953 static int
954 dmu_adjust_send_estimate_for_indirects(dsl_dataset_t *ds, uint64_t size,
955     uint64_t *sizep)
956 {
957 	int err;
958 	/*
959 	 * Assume that space (both on-disk and in-stream) is dominated by
960 	 * data.  We will adjust for indirect blocks and the copies property,
961 	 * but ignore per-object space used (eg, dnodes and DRR_OBJECT records).
962 	 */
963 
964 	/*
965 	 * Subtract out approximate space used by indirect blocks.
966 	 * Assume most space is used by data blocks (non-indirect, non-dnode).
967 	 * Assume all blocks are recordsize.  Assume ditto blocks and
968 	 * internal fragmentation counter out compression.
969 	 *
970 	 * Therefore, space used by indirect blocks is sizeof(blkptr_t) per
971 	 * block, which we observe in practice.
972 	 */
973 	uint64_t recordsize;
974 	err = dsl_prop_get_int_ds(ds, "recordsize", &recordsize);
975 	if (err != 0)
976 		return (err);
977 	size -= size / recordsize * sizeof (blkptr_t);
978 
979 	/* Add in the space for the record associated with each block. */
980 	size += size / recordsize * sizeof (dmu_replay_record_t);
981 
982 	*sizep = size;
983 
984 	return (0);
985 }
986 
987 int
988 dmu_send_estimate(dsl_dataset_t *ds, dsl_dataset_t *fromds, uint64_t *sizep)
989 {
990 	dsl_pool_t *dp = ds->ds_dir->dd_pool;
991 	int err;
992 	uint64_t size;
993 
994 	ASSERT(dsl_pool_config_held(dp));
995 
996 	/* tosnap must be a snapshot */
997 	if (!ds->ds_is_snapshot)
998 		return (SET_ERROR(EINVAL));
999 
1000 	/* fromsnap, if provided, must be a snapshot */
1001 	if (fromds != NULL && !fromds->ds_is_snapshot)
1002 		return (SET_ERROR(EINVAL));
1003 
1004 	/*
1005 	 * fromsnap must be an earlier snapshot from the same fs as tosnap,
1006 	 * or the origin's fs.
1007 	 */
1008 	if (fromds != NULL && !dsl_dataset_is_before(ds, fromds, 0))
1009 		return (SET_ERROR(EXDEV));
1010 
1011 	/* Get uncompressed size estimate of changed data. */
1012 	if (fromds == NULL) {
1013 		size = dsl_dataset_phys(ds)->ds_uncompressed_bytes;
1014 	} else {
1015 		uint64_t used, comp;
1016 		err = dsl_dataset_space_written(fromds, ds,
1017 		    &used, &comp, &size);
1018 		if (err != 0)
1019 			return (err);
1020 	}
1021 
1022 	err = dmu_adjust_send_estimate_for_indirects(ds, size, sizep);
1023 	return (err);
1024 }
1025 
1026 /*
1027  * Simple callback used to traverse the blocks of a snapshot and sum their
1028  * uncompressed size
1029  */
1030 /* ARGSUSED */
1031 static int
1032 dmu_calculate_send_traversal(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
1033     const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
1034 {
1035 	uint64_t *spaceptr = arg;
1036 	if (bp != NULL && !BP_IS_HOLE(bp)) {
1037 		*spaceptr += BP_GET_UCSIZE(bp);
1038 	}
1039 	return (0);
1040 }
1041 
1042 /*
1043  * Given a desination snapshot and a TXG, calculate the approximate size of a
1044  * send stream sent from that TXG. from_txg may be zero, indicating that the
1045  * whole snapshot will be sent.
1046  */
1047 int
1048 dmu_send_estimate_from_txg(dsl_dataset_t *ds, uint64_t from_txg,
1049     uint64_t *sizep)
1050 {
1051 	dsl_pool_t *dp = ds->ds_dir->dd_pool;
1052 	int err;
1053 	uint64_t size = 0;
1054 
1055 	ASSERT(dsl_pool_config_held(dp));
1056 
1057 	/* tosnap must be a snapshot */
1058 	if (!dsl_dataset_is_snapshot(ds))
1059 		return (SET_ERROR(EINVAL));
1060 
1061 	/* verify that from_txg is before the provided snapshot was taken */
1062 	if (from_txg >= dsl_dataset_phys(ds)->ds_creation_txg) {
1063 		return (SET_ERROR(EXDEV));
1064 	}
1065 
1066 	/*
1067 	 * traverse the blocks of the snapshot with birth times after
1068 	 * from_txg, summing their uncompressed size
1069 	 */
1070 	err = traverse_dataset(ds, from_txg, TRAVERSE_POST,
1071 	    dmu_calculate_send_traversal, &size);
1072 	if (err)
1073 		return (err);
1074 
1075 	err = dmu_adjust_send_estimate_for_indirects(ds, size, sizep);
1076 	return (err);
1077 }
1078 
1079 typedef struct dmu_recv_begin_arg {
1080 	const char *drba_origin;
1081 	dmu_recv_cookie_t *drba_cookie;
1082 	cred_t *drba_cred;
1083 	uint64_t drba_snapobj;
1084 } dmu_recv_begin_arg_t;
1085 
1086 static int
1087 recv_begin_check_existing_impl(dmu_recv_begin_arg_t *drba, dsl_dataset_t *ds,
1088     uint64_t fromguid)
1089 {
1090 	uint64_t val;
1091 	int error;
1092 	dsl_pool_t *dp = ds->ds_dir->dd_pool;
1093 
1094 	/* temporary clone name must not exist */
1095 	error = zap_lookup(dp->dp_meta_objset,
1096 	    dsl_dir_phys(ds->ds_dir)->dd_child_dir_zapobj, recv_clone_name,
1097 	    8, 1, &val);
1098 	if (error != ENOENT)
1099 		return (error == 0 ? EBUSY : error);
1100 
1101 	/* new snapshot name must not exist */
1102 	error = zap_lookup(dp->dp_meta_objset,
1103 	    dsl_dataset_phys(ds)->ds_snapnames_zapobj,
1104 	    drba->drba_cookie->drc_tosnap, 8, 1, &val);
1105 	if (error != ENOENT)
1106 		return (error == 0 ? EEXIST : error);
1107 
1108 	/*
1109 	 * Check snapshot limit before receiving. We'll recheck again at the
1110 	 * end, but might as well abort before receiving if we're already over
1111 	 * the limit.
1112 	 *
1113 	 * Note that we do not check the file system limit with
1114 	 * dsl_dir_fscount_check because the temporary %clones don't count
1115 	 * against that limit.
1116 	 */
1117 	error = dsl_fs_ss_limit_check(ds->ds_dir, 1, ZFS_PROP_SNAPSHOT_LIMIT,
1118 	    NULL, drba->drba_cred);
1119 	if (error != 0)
1120 		return (error);
1121 
1122 	if (fromguid != 0) {
1123 		dsl_dataset_t *snap;
1124 		uint64_t obj = dsl_dataset_phys(ds)->ds_prev_snap_obj;
1125 
1126 		/* Find snapshot in this dir that matches fromguid. */
1127 		while (obj != 0) {
1128 			error = dsl_dataset_hold_obj(dp, obj, FTAG,
1129 			    &snap);
1130 			if (error != 0)
1131 				return (SET_ERROR(ENODEV));
1132 			if (snap->ds_dir != ds->ds_dir) {
1133 				dsl_dataset_rele(snap, FTAG);
1134 				return (SET_ERROR(ENODEV));
1135 			}
1136 			if (dsl_dataset_phys(snap)->ds_guid == fromguid)
1137 				break;
1138 			obj = dsl_dataset_phys(snap)->ds_prev_snap_obj;
1139 			dsl_dataset_rele(snap, FTAG);
1140 		}
1141 		if (obj == 0)
1142 			return (SET_ERROR(ENODEV));
1143 
1144 		if (drba->drba_cookie->drc_force) {
1145 			drba->drba_snapobj = obj;
1146 		} else {
1147 			/*
1148 			 * If we are not forcing, there must be no
1149 			 * changes since fromsnap.
1150 			 */
1151 			if (dsl_dataset_modified_since_snap(ds, snap)) {
1152 				dsl_dataset_rele(snap, FTAG);
1153 				return (SET_ERROR(ETXTBSY));
1154 			}
1155 			drba->drba_snapobj = ds->ds_prev->ds_object;
1156 		}
1157 
1158 		dsl_dataset_rele(snap, FTAG);
1159 	} else {
1160 		/* if full, then must be forced */
1161 		if (!drba->drba_cookie->drc_force)
1162 			return (SET_ERROR(EEXIST));
1163 		/* start from $ORIGIN@$ORIGIN, if supported */
1164 		drba->drba_snapobj = dp->dp_origin_snap != NULL ?
1165 		    dp->dp_origin_snap->ds_object : 0;
1166 	}
1167 
1168 	return (0);
1169 
1170 }
1171 
1172 static int
1173 dmu_recv_begin_check(void *arg, dmu_tx_t *tx)
1174 {
1175 	dmu_recv_begin_arg_t *drba = arg;
1176 	dsl_pool_t *dp = dmu_tx_pool(tx);
1177 	struct drr_begin *drrb = drba->drba_cookie->drc_drrb;
1178 	uint64_t fromguid = drrb->drr_fromguid;
1179 	int flags = drrb->drr_flags;
1180 	int error;
1181 	uint64_t featureflags = DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo);
1182 	dsl_dataset_t *ds;
1183 	const char *tofs = drba->drba_cookie->drc_tofs;
1184 
1185 	/* already checked */
1186 	ASSERT3U(drrb->drr_magic, ==, DMU_BACKUP_MAGIC);
1187 
1188 	if (DMU_GET_STREAM_HDRTYPE(drrb->drr_versioninfo) ==
1189 	    DMU_COMPOUNDSTREAM ||
1190 	    drrb->drr_type >= DMU_OST_NUMTYPES ||
1191 	    ((flags & DRR_FLAG_CLONE) && drba->drba_origin == NULL))
1192 		return (SET_ERROR(EINVAL));
1193 
1194 	/* Verify pool version supports SA if SA_SPILL feature set */
1195 	if ((featureflags & DMU_BACKUP_FEATURE_SA_SPILL) &&
1196 	    spa_version(dp->dp_spa) < SPA_VERSION_SA)
1197 		return (SET_ERROR(ENOTSUP));
1198 
1199 	/*
1200 	 * The receiving code doesn't know how to translate a WRITE_EMBEDDED
1201 	 * record to a plan WRITE record, so the pool must have the
1202 	 * EMBEDDED_DATA feature enabled if the stream has WRITE_EMBEDDED
1203 	 * records.  Same with WRITE_EMBEDDED records that use LZ4 compression.
1204 	 */
1205 	if ((featureflags & DMU_BACKUP_FEATURE_EMBED_DATA) &&
1206 	    !spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_EMBEDDED_DATA))
1207 		return (SET_ERROR(ENOTSUP));
1208 	if ((featureflags & DMU_BACKUP_FEATURE_EMBED_DATA_LZ4) &&
1209 	    !spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_LZ4_COMPRESS))
1210 		return (SET_ERROR(ENOTSUP));
1211 
1212 	/*
1213 	 * The receiving code doesn't know how to translate large blocks
1214 	 * to smaller ones, so the pool must have the LARGE_BLOCKS
1215 	 * feature enabled if the stream has LARGE_BLOCKS.
1216 	 */
1217 	if ((featureflags & DMU_BACKUP_FEATURE_LARGE_BLOCKS) &&
1218 	    !spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_LARGE_BLOCKS))
1219 		return (SET_ERROR(ENOTSUP));
1220 
1221 	error = dsl_dataset_hold(dp, tofs, FTAG, &ds);
1222 	if (error == 0) {
1223 		/* target fs already exists; recv into temp clone */
1224 
1225 		/* Can't recv a clone into an existing fs */
1226 		if (flags & DRR_FLAG_CLONE) {
1227 			dsl_dataset_rele(ds, FTAG);
1228 			return (SET_ERROR(EINVAL));
1229 		}
1230 
1231 		error = recv_begin_check_existing_impl(drba, ds, fromguid);
1232 		dsl_dataset_rele(ds, FTAG);
1233 	} else if (error == ENOENT) {
1234 		/* target fs does not exist; must be a full backup or clone */
1235 		char buf[MAXNAMELEN];
1236 
1237 		/*
1238 		 * If it's a non-clone incremental, we are missing the
1239 		 * target fs, so fail the recv.
1240 		 */
1241 		if (fromguid != 0 && !(flags & DRR_FLAG_CLONE ||
1242 		    drba->drba_origin))
1243 			return (SET_ERROR(ENOENT));
1244 
1245 		/* Open the parent of tofs */
1246 		ASSERT3U(strlen(tofs), <, MAXNAMELEN);
1247 		(void) strlcpy(buf, tofs, strrchr(tofs, '/') - tofs + 1);
1248 		error = dsl_dataset_hold(dp, buf, FTAG, &ds);
1249 		if (error != 0)
1250 			return (error);
1251 
1252 		/*
1253 		 * Check filesystem and snapshot limits before receiving. We'll
1254 		 * recheck snapshot limits again at the end (we create the
1255 		 * filesystems and increment those counts during begin_sync).
1256 		 */
1257 		error = dsl_fs_ss_limit_check(ds->ds_dir, 1,
1258 		    ZFS_PROP_FILESYSTEM_LIMIT, NULL, drba->drba_cred);
1259 		if (error != 0) {
1260 			dsl_dataset_rele(ds, FTAG);
1261 			return (error);
1262 		}
1263 
1264 		error = dsl_fs_ss_limit_check(ds->ds_dir, 1,
1265 		    ZFS_PROP_SNAPSHOT_LIMIT, NULL, drba->drba_cred);
1266 		if (error != 0) {
1267 			dsl_dataset_rele(ds, FTAG);
1268 			return (error);
1269 		}
1270 
1271 		if (drba->drba_origin != NULL) {
1272 			dsl_dataset_t *origin;
1273 			error = dsl_dataset_hold(dp, drba->drba_origin,
1274 			    FTAG, &origin);
1275 			if (error != 0) {
1276 				dsl_dataset_rele(ds, FTAG);
1277 				return (error);
1278 			}
1279 			if (!origin->ds_is_snapshot) {
1280 				dsl_dataset_rele(origin, FTAG);
1281 				dsl_dataset_rele(ds, FTAG);
1282 				return (SET_ERROR(EINVAL));
1283 			}
1284 			if (dsl_dataset_phys(origin)->ds_guid != fromguid) {
1285 				dsl_dataset_rele(origin, FTAG);
1286 				dsl_dataset_rele(ds, FTAG);
1287 				return (SET_ERROR(ENODEV));
1288 			}
1289 			dsl_dataset_rele(origin, FTAG);
1290 		}
1291 		dsl_dataset_rele(ds, FTAG);
1292 		error = 0;
1293 	}
1294 	return (error);
1295 }
1296 
1297 static void
1298 dmu_recv_begin_sync(void *arg, dmu_tx_t *tx)
1299 {
1300 	dmu_recv_begin_arg_t *drba = arg;
1301 	dsl_pool_t *dp = dmu_tx_pool(tx);
1302 	struct drr_begin *drrb = drba->drba_cookie->drc_drrb;
1303 	const char *tofs = drba->drba_cookie->drc_tofs;
1304 	dsl_dataset_t *ds, *newds;
1305 	uint64_t dsobj;
1306 	int error;
1307 	uint64_t crflags;
1308 
1309 	crflags = (drrb->drr_flags & DRR_FLAG_CI_DATA) ?
1310 	    DS_FLAG_CI_DATASET : 0;
1311 
1312 	error = dsl_dataset_hold(dp, tofs, FTAG, &ds);
1313 	if (error == 0) {
1314 		/* create temporary clone */
1315 		dsl_dataset_t *snap = NULL;
1316 		if (drba->drba_snapobj != 0) {
1317 			VERIFY0(dsl_dataset_hold_obj(dp,
1318 			    drba->drba_snapobj, FTAG, &snap));
1319 		}
1320 		dsobj = dsl_dataset_create_sync(ds->ds_dir, recv_clone_name,
1321 		    snap, crflags, drba->drba_cred, tx);
1322 		if (drba->drba_snapobj != 0)
1323 			dsl_dataset_rele(snap, FTAG);
1324 		dsl_dataset_rele(ds, FTAG);
1325 	} else {
1326 		dsl_dir_t *dd;
1327 		const char *tail;
1328 		dsl_dataset_t *origin = NULL;
1329 
1330 		VERIFY0(dsl_dir_hold(dp, tofs, FTAG, &dd, &tail));
1331 
1332 		if (drba->drba_origin != NULL) {
1333 			VERIFY0(dsl_dataset_hold(dp, drba->drba_origin,
1334 			    FTAG, &origin));
1335 		}
1336 
1337 		/* Create new dataset. */
1338 		dsobj = dsl_dataset_create_sync(dd,
1339 		    strrchr(tofs, '/') + 1,
1340 		    origin, crflags, drba->drba_cred, tx);
1341 		if (origin != NULL)
1342 			dsl_dataset_rele(origin, FTAG);
1343 		dsl_dir_rele(dd, FTAG);
1344 		drba->drba_cookie->drc_newfs = B_TRUE;
1345 	}
1346 	VERIFY0(dsl_dataset_own_obj(dp, dsobj, dmu_recv_tag, &newds));
1347 
1348 	dmu_buf_will_dirty(newds->ds_dbuf, tx);
1349 	dsl_dataset_phys(newds)->ds_flags |= DS_FLAG_INCONSISTENT;
1350 
1351 	/*
1352 	 * If we actually created a non-clone, we need to create the
1353 	 * objset in our new dataset.
1354 	 */
1355 	if (BP_IS_HOLE(dsl_dataset_get_blkptr(newds))) {
1356 		(void) dmu_objset_create_impl(dp->dp_spa,
1357 		    newds, dsl_dataset_get_blkptr(newds), drrb->drr_type, tx);
1358 	}
1359 
1360 	drba->drba_cookie->drc_ds = newds;
1361 
1362 	spa_history_log_internal_ds(newds, "receive", tx, "");
1363 }
1364 
1365 /*
1366  * NB: callers *MUST* call dmu_recv_stream() if dmu_recv_begin()
1367  * succeeds; otherwise we will leak the holds on the datasets.
1368  */
1369 int
1370 dmu_recv_begin(char *tofs, char *tosnap, struct drr_begin *drrb,
1371     boolean_t force, char *origin, dmu_recv_cookie_t *drc)
1372 {
1373 	dmu_recv_begin_arg_t drba = { 0 };
1374 	dmu_replay_record_t *drr;
1375 
1376 	bzero(drc, sizeof (dmu_recv_cookie_t));
1377 	drc->drc_drrb = drrb;
1378 	drc->drc_tosnap = tosnap;
1379 	drc->drc_tofs = tofs;
1380 	drc->drc_force = force;
1381 	drc->drc_cred = CRED();
1382 
1383 	if (drrb->drr_magic == BSWAP_64(DMU_BACKUP_MAGIC))
1384 		drc->drc_byteswap = B_TRUE;
1385 	else if (drrb->drr_magic != DMU_BACKUP_MAGIC)
1386 		return (SET_ERROR(EINVAL));
1387 
1388 	drr = kmem_zalloc(sizeof (dmu_replay_record_t), KM_SLEEP);
1389 	drr->drr_type = DRR_BEGIN;
1390 	drr->drr_u.drr_begin = *drc->drc_drrb;
1391 	if (drc->drc_byteswap) {
1392 		fletcher_4_incremental_byteswap(drr,
1393 		    sizeof (dmu_replay_record_t), &drc->drc_cksum);
1394 	} else {
1395 		fletcher_4_incremental_native(drr,
1396 		    sizeof (dmu_replay_record_t), &drc->drc_cksum);
1397 	}
1398 	kmem_free(drr, sizeof (dmu_replay_record_t));
1399 
1400 	if (drc->drc_byteswap) {
1401 		drrb->drr_magic = BSWAP_64(drrb->drr_magic);
1402 		drrb->drr_versioninfo = BSWAP_64(drrb->drr_versioninfo);
1403 		drrb->drr_creation_time = BSWAP_64(drrb->drr_creation_time);
1404 		drrb->drr_type = BSWAP_32(drrb->drr_type);
1405 		drrb->drr_toguid = BSWAP_64(drrb->drr_toguid);
1406 		drrb->drr_fromguid = BSWAP_64(drrb->drr_fromguid);
1407 	}
1408 
1409 	drba.drba_origin = origin;
1410 	drba.drba_cookie = drc;
1411 	drba.drba_cred = CRED();
1412 
1413 	return (dsl_sync_task(tofs, dmu_recv_begin_check, dmu_recv_begin_sync,
1414 	    &drba, 5, ZFS_SPACE_CHECK_NORMAL));
1415 }
1416 
1417 struct receive_record_arg {
1418 	dmu_replay_record_t header;
1419 	void *payload; /* Pointer to a buffer containing the payload */
1420 	/*
1421 	 * If the record is a write, pointer to the arc_buf_t containing the
1422 	 * payload.
1423 	 */
1424 	arc_buf_t *write_buf;
1425 	int payload_size;
1426 	boolean_t eos_marker; /* Marks the end of the stream */
1427 	bqueue_node_t node;
1428 };
1429 
1430 struct receive_writer_arg {
1431 	objset_t *os;
1432 	boolean_t byteswap;
1433 	bqueue_t q;
1434 	/*
1435 	 * These three args are used to signal to the main thread that we're
1436 	 * done.
1437 	 */
1438 	kmutex_t mutex;
1439 	kcondvar_t cv;
1440 	boolean_t done;
1441 	int err;
1442 	/* A map from guid to dataset to help handle dedup'd streams. */
1443 	avl_tree_t *guid_to_ds_map;
1444 };
1445 
1446 struct receive_arg  {
1447 	objset_t *os;
1448 	vnode_t *vp; /* The vnode to read the stream from */
1449 	uint64_t voff; /* The current offset in the stream */
1450 	/*
1451 	 * A record that has had its payload read in, but hasn't yet been handed
1452 	 * off to the worker thread.
1453 	 */
1454 	struct receive_record_arg *rrd;
1455 	/* A record that has had its header read in, but not its payload. */
1456 	struct receive_record_arg *next_rrd;
1457 	zio_cksum_t cksum;
1458 	zio_cksum_t prev_cksum;
1459 	int err;
1460 	boolean_t byteswap;
1461 	/* Sorted list of objects not to issue prefetches for. */
1462 	list_t ignore_obj_list;
1463 };
1464 
1465 struct receive_ign_obj_node {
1466 	list_node_t node;
1467 	uint64_t object;
1468 };
1469 
1470 typedef struct guid_map_entry {
1471 	uint64_t	guid;
1472 	dsl_dataset_t	*gme_ds;
1473 	avl_node_t	avlnode;
1474 } guid_map_entry_t;
1475 
1476 static int
1477 guid_compare(const void *arg1, const void *arg2)
1478 {
1479 	const guid_map_entry_t *gmep1 = arg1;
1480 	const guid_map_entry_t *gmep2 = arg2;
1481 
1482 	if (gmep1->guid < gmep2->guid)
1483 		return (-1);
1484 	else if (gmep1->guid > gmep2->guid)
1485 		return (1);
1486 	return (0);
1487 }
1488 
1489 static void
1490 free_guid_map_onexit(void *arg)
1491 {
1492 	avl_tree_t *ca = arg;
1493 	void *cookie = NULL;
1494 	guid_map_entry_t *gmep;
1495 
1496 	while ((gmep = avl_destroy_nodes(ca, &cookie)) != NULL) {
1497 		dsl_dataset_long_rele(gmep->gme_ds, gmep);
1498 		dsl_dataset_rele(gmep->gme_ds, gmep);
1499 		kmem_free(gmep, sizeof (guid_map_entry_t));
1500 	}
1501 	avl_destroy(ca);
1502 	kmem_free(ca, sizeof (avl_tree_t));
1503 }
1504 
1505 static int
1506 receive_read(struct receive_arg *ra, int len, void *buf)
1507 {
1508 	int done = 0;
1509 
1510 	/* some things will require 8-byte alignment, so everything must */
1511 	ASSERT0(len % 8);
1512 
1513 	while (done < len) {
1514 		ssize_t resid;
1515 
1516 		ra->err = vn_rdwr(UIO_READ, ra->vp,
1517 		    (char *)buf + done, len - done,
1518 		    ra->voff, UIO_SYSSPACE, FAPPEND,
1519 		    RLIM64_INFINITY, CRED(), &resid);
1520 
1521 		if (resid == len - done)
1522 			ra->err = SET_ERROR(EINVAL);
1523 		ra->voff += len - done - resid;
1524 		done = len - resid;
1525 		if (ra->err != 0)
1526 			return (ra->err);
1527 	}
1528 
1529 	ASSERT3U(done, ==, len);
1530 	return (0);
1531 }
1532 
1533 static void
1534 byteswap_record(dmu_replay_record_t *drr)
1535 {
1536 #define	DO64(X) (drr->drr_u.X = BSWAP_64(drr->drr_u.X))
1537 #define	DO32(X) (drr->drr_u.X = BSWAP_32(drr->drr_u.X))
1538 	drr->drr_type = BSWAP_32(drr->drr_type);
1539 	drr->drr_payloadlen = BSWAP_32(drr->drr_payloadlen);
1540 
1541 	switch (drr->drr_type) {
1542 	case DRR_BEGIN:
1543 		DO64(drr_begin.drr_magic);
1544 		DO64(drr_begin.drr_versioninfo);
1545 		DO64(drr_begin.drr_creation_time);
1546 		DO32(drr_begin.drr_type);
1547 		DO32(drr_begin.drr_flags);
1548 		DO64(drr_begin.drr_toguid);
1549 		DO64(drr_begin.drr_fromguid);
1550 		break;
1551 	case DRR_OBJECT:
1552 		DO64(drr_object.drr_object);
1553 		DO32(drr_object.drr_type);
1554 		DO32(drr_object.drr_bonustype);
1555 		DO32(drr_object.drr_blksz);
1556 		DO32(drr_object.drr_bonuslen);
1557 		DO64(drr_object.drr_toguid);
1558 		break;
1559 	case DRR_FREEOBJECTS:
1560 		DO64(drr_freeobjects.drr_firstobj);
1561 		DO64(drr_freeobjects.drr_numobjs);
1562 		DO64(drr_freeobjects.drr_toguid);
1563 		break;
1564 	case DRR_WRITE:
1565 		DO64(drr_write.drr_object);
1566 		DO32(drr_write.drr_type);
1567 		DO64(drr_write.drr_offset);
1568 		DO64(drr_write.drr_length);
1569 		DO64(drr_write.drr_toguid);
1570 		ZIO_CHECKSUM_BSWAP(&drr->drr_u.drr_write.drr_key.ddk_cksum);
1571 		DO64(drr_write.drr_key.ddk_prop);
1572 		break;
1573 	case DRR_WRITE_BYREF:
1574 		DO64(drr_write_byref.drr_object);
1575 		DO64(drr_write_byref.drr_offset);
1576 		DO64(drr_write_byref.drr_length);
1577 		DO64(drr_write_byref.drr_toguid);
1578 		DO64(drr_write_byref.drr_refguid);
1579 		DO64(drr_write_byref.drr_refobject);
1580 		DO64(drr_write_byref.drr_refoffset);
1581 		ZIO_CHECKSUM_BSWAP(&drr->drr_u.drr_write_byref.
1582 		    drr_key.ddk_cksum);
1583 		DO64(drr_write_byref.drr_key.ddk_prop);
1584 		break;
1585 	case DRR_WRITE_EMBEDDED:
1586 		DO64(drr_write_embedded.drr_object);
1587 		DO64(drr_write_embedded.drr_offset);
1588 		DO64(drr_write_embedded.drr_length);
1589 		DO64(drr_write_embedded.drr_toguid);
1590 		DO32(drr_write_embedded.drr_lsize);
1591 		DO32(drr_write_embedded.drr_psize);
1592 		break;
1593 	case DRR_FREE:
1594 		DO64(drr_free.drr_object);
1595 		DO64(drr_free.drr_offset);
1596 		DO64(drr_free.drr_length);
1597 		DO64(drr_free.drr_toguid);
1598 		break;
1599 	case DRR_SPILL:
1600 		DO64(drr_spill.drr_object);
1601 		DO64(drr_spill.drr_length);
1602 		DO64(drr_spill.drr_toguid);
1603 		break;
1604 	case DRR_END:
1605 		DO64(drr_end.drr_toguid);
1606 		ZIO_CHECKSUM_BSWAP(&drr->drr_u.drr_end.drr_checksum);
1607 		break;
1608 	}
1609 
1610 	if (drr->drr_type != DRR_BEGIN) {
1611 		ZIO_CHECKSUM_BSWAP(&drr->drr_u.drr_checksum.drr_checksum);
1612 	}
1613 
1614 #undef DO64
1615 #undef DO32
1616 }
1617 
1618 static inline uint8_t
1619 deduce_nblkptr(dmu_object_type_t bonus_type, uint64_t bonus_size)
1620 {
1621 	if (bonus_type == DMU_OT_SA) {
1622 		return (1);
1623 	} else {
1624 		return (1 +
1625 		    ((DN_MAX_BONUSLEN - bonus_size) >> SPA_BLKPTRSHIFT));
1626 	}
1627 }
1628 
1629 static int
1630 receive_object(struct receive_writer_arg *rwa, struct drr_object *drro,
1631     void *data)
1632 {
1633 	dmu_object_info_t doi;
1634 	dmu_tx_t *tx;
1635 	uint64_t object;
1636 	int err;
1637 
1638 	if (drro->drr_type == DMU_OT_NONE ||
1639 	    !DMU_OT_IS_VALID(drro->drr_type) ||
1640 	    !DMU_OT_IS_VALID(drro->drr_bonustype) ||
1641 	    drro->drr_checksumtype >= ZIO_CHECKSUM_FUNCTIONS ||
1642 	    drro->drr_compress >= ZIO_COMPRESS_FUNCTIONS ||
1643 	    P2PHASE(drro->drr_blksz, SPA_MINBLOCKSIZE) ||
1644 	    drro->drr_blksz < SPA_MINBLOCKSIZE ||
1645 	    drro->drr_blksz > spa_maxblocksize(dmu_objset_spa(rwa->os)) ||
1646 	    drro->drr_bonuslen > DN_MAX_BONUSLEN) {
1647 		return (SET_ERROR(EINVAL));
1648 	}
1649 
1650 	err = dmu_object_info(rwa->os, drro->drr_object, &doi);
1651 
1652 	if (err != 0 && err != ENOENT)
1653 		return (SET_ERROR(EINVAL));
1654 	object = err == 0 ? drro->drr_object : DMU_NEW_OBJECT;
1655 
1656 	/*
1657 	 * If we are losing blkptrs or changing the block size this must
1658 	 * be a new file instance.  We must clear out the previous file
1659 	 * contents before we can change this type of metadata in the dnode.
1660 	 */
1661 	if (err == 0) {
1662 		int nblkptr;
1663 
1664 		nblkptr = deduce_nblkptr(drro->drr_bonustype,
1665 		    drro->drr_bonuslen);
1666 
1667 		if (drro->drr_blksz != doi.doi_data_block_size ||
1668 		    nblkptr < doi.doi_nblkptr) {
1669 			err = dmu_free_long_range(rwa->os, drro->drr_object,
1670 			    0, DMU_OBJECT_END);
1671 			if (err != 0)
1672 				return (SET_ERROR(EINVAL));
1673 		}
1674 	}
1675 
1676 	tx = dmu_tx_create(rwa->os);
1677 	dmu_tx_hold_bonus(tx, object);
1678 	err = dmu_tx_assign(tx, TXG_WAIT);
1679 	if (err != 0) {
1680 		dmu_tx_abort(tx);
1681 		return (err);
1682 	}
1683 
1684 	if (object == DMU_NEW_OBJECT) {
1685 		/* currently free, want to be allocated */
1686 		err = dmu_object_claim(rwa->os, drro->drr_object,
1687 		    drro->drr_type, drro->drr_blksz,
1688 		    drro->drr_bonustype, drro->drr_bonuslen, tx);
1689 	} else if (drro->drr_type != doi.doi_type ||
1690 	    drro->drr_blksz != doi.doi_data_block_size ||
1691 	    drro->drr_bonustype != doi.doi_bonus_type ||
1692 	    drro->drr_bonuslen != doi.doi_bonus_size) {
1693 		/* currently allocated, but with different properties */
1694 		err = dmu_object_reclaim(rwa->os, drro->drr_object,
1695 		    drro->drr_type, drro->drr_blksz,
1696 		    drro->drr_bonustype, drro->drr_bonuslen, tx);
1697 	}
1698 	if (err != 0) {
1699 		dmu_tx_commit(tx);
1700 		return (SET_ERROR(EINVAL));
1701 	}
1702 
1703 	dmu_object_set_checksum(rwa->os, drro->drr_object,
1704 	    drro->drr_checksumtype, tx);
1705 	dmu_object_set_compress(rwa->os, drro->drr_object,
1706 	    drro->drr_compress, tx);
1707 
1708 	if (data != NULL) {
1709 		dmu_buf_t *db;
1710 
1711 		VERIFY0(dmu_bonus_hold(rwa->os, drro->drr_object, FTAG, &db));
1712 		dmu_buf_will_dirty(db, tx);
1713 
1714 		ASSERT3U(db->db_size, >=, drro->drr_bonuslen);
1715 		bcopy(data, db->db_data, drro->drr_bonuslen);
1716 		if (rwa->byteswap) {
1717 			dmu_object_byteswap_t byteswap =
1718 			    DMU_OT_BYTESWAP(drro->drr_bonustype);
1719 			dmu_ot_byteswap[byteswap].ob_func(db->db_data,
1720 			    drro->drr_bonuslen);
1721 		}
1722 		dmu_buf_rele(db, FTAG);
1723 	}
1724 	dmu_tx_commit(tx);
1725 	return (0);
1726 }
1727 
1728 /* ARGSUSED */
1729 static int
1730 receive_freeobjects(struct receive_writer_arg *rwa,
1731     struct drr_freeobjects *drrfo)
1732 {
1733 	uint64_t obj;
1734 
1735 	if (drrfo->drr_firstobj + drrfo->drr_numobjs < drrfo->drr_firstobj)
1736 		return (SET_ERROR(EINVAL));
1737 
1738 	for (obj = drrfo->drr_firstobj;
1739 	    obj < drrfo->drr_firstobj + drrfo->drr_numobjs;
1740 	    (void) dmu_object_next(rwa->os, &obj, FALSE, 0)) {
1741 		int err;
1742 
1743 		if (dmu_object_info(rwa->os, obj, NULL) != 0)
1744 			continue;
1745 
1746 		err = dmu_free_long_object(rwa->os, obj);
1747 		if (err != 0)
1748 			return (err);
1749 	}
1750 	return (0);
1751 }
1752 
1753 static int
1754 receive_write(struct receive_writer_arg *rwa, struct drr_write *drrw,
1755     arc_buf_t *abuf)
1756 {
1757 	dmu_tx_t *tx;
1758 	int err;
1759 
1760 	if (drrw->drr_offset + drrw->drr_length < drrw->drr_offset ||
1761 	    !DMU_OT_IS_VALID(drrw->drr_type))
1762 		return (SET_ERROR(EINVAL));
1763 
1764 	if (dmu_object_info(rwa->os, drrw->drr_object, NULL) != 0)
1765 		return (SET_ERROR(EINVAL));
1766 
1767 	tx = dmu_tx_create(rwa->os);
1768 
1769 	dmu_tx_hold_write(tx, drrw->drr_object,
1770 	    drrw->drr_offset, drrw->drr_length);
1771 	err = dmu_tx_assign(tx, TXG_WAIT);
1772 	if (err != 0) {
1773 		dmu_tx_abort(tx);
1774 		return (err);
1775 	}
1776 	if (rwa->byteswap) {
1777 		dmu_object_byteswap_t byteswap =
1778 		    DMU_OT_BYTESWAP(drrw->drr_type);
1779 		dmu_ot_byteswap[byteswap].ob_func(abuf->b_data,
1780 		    drrw->drr_length);
1781 	}
1782 
1783 	dmu_buf_t *bonus;
1784 	if (dmu_bonus_hold(rwa->os, drrw->drr_object, FTAG, &bonus) != 0)
1785 		return (SET_ERROR(EINVAL));
1786 	dmu_assign_arcbuf(bonus, drrw->drr_offset, abuf, tx);
1787 	dmu_tx_commit(tx);
1788 	dmu_buf_rele(bonus, FTAG);
1789 	return (0);
1790 }
1791 
1792 /*
1793  * Handle a DRR_WRITE_BYREF record.  This record is used in dedup'ed
1794  * streams to refer to a copy of the data that is already on the
1795  * system because it came in earlier in the stream.  This function
1796  * finds the earlier copy of the data, and uses that copy instead of
1797  * data from the stream to fulfill this write.
1798  */
1799 static int
1800 receive_write_byref(struct receive_writer_arg *rwa,
1801     struct drr_write_byref *drrwbr)
1802 {
1803 	dmu_tx_t *tx;
1804 	int err;
1805 	guid_map_entry_t gmesrch;
1806 	guid_map_entry_t *gmep;
1807 	avl_index_t where;
1808 	objset_t *ref_os = NULL;
1809 	dmu_buf_t *dbp;
1810 
1811 	if (drrwbr->drr_offset + drrwbr->drr_length < drrwbr->drr_offset)
1812 		return (SET_ERROR(EINVAL));
1813 
1814 	/*
1815 	 * If the GUID of the referenced dataset is different from the
1816 	 * GUID of the target dataset, find the referenced dataset.
1817 	 */
1818 	if (drrwbr->drr_toguid != drrwbr->drr_refguid) {
1819 		gmesrch.guid = drrwbr->drr_refguid;
1820 		if ((gmep = avl_find(rwa->guid_to_ds_map, &gmesrch,
1821 		    &where)) == NULL) {
1822 			return (SET_ERROR(EINVAL));
1823 		}
1824 		if (dmu_objset_from_ds(gmep->gme_ds, &ref_os))
1825 			return (SET_ERROR(EINVAL));
1826 	} else {
1827 		ref_os = rwa->os;
1828 	}
1829 
1830 	err = dmu_buf_hold(ref_os, drrwbr->drr_refobject,
1831 	    drrwbr->drr_refoffset, FTAG, &dbp, DMU_READ_PREFETCH);
1832 	if (err != 0)
1833 		return (err);
1834 
1835 	tx = dmu_tx_create(rwa->os);
1836 
1837 	dmu_tx_hold_write(tx, drrwbr->drr_object,
1838 	    drrwbr->drr_offset, drrwbr->drr_length);
1839 	err = dmu_tx_assign(tx, TXG_WAIT);
1840 	if (err != 0) {
1841 		dmu_tx_abort(tx);
1842 		return (err);
1843 	}
1844 	dmu_write(rwa->os, drrwbr->drr_object,
1845 	    drrwbr->drr_offset, drrwbr->drr_length, dbp->db_data, tx);
1846 	dmu_buf_rele(dbp, FTAG);
1847 	dmu_tx_commit(tx);
1848 	return (0);
1849 }
1850 
1851 static int
1852 receive_write_embedded(struct receive_writer_arg *rwa,
1853     struct drr_write_embedded *drrwnp, void *data)
1854 {
1855 	dmu_tx_t *tx;
1856 	int err;
1857 
1858 	if (drrwnp->drr_offset + drrwnp->drr_length < drrwnp->drr_offset)
1859 		return (EINVAL);
1860 
1861 	if (drrwnp->drr_psize > BPE_PAYLOAD_SIZE)
1862 		return (EINVAL);
1863 
1864 	if (drrwnp->drr_etype >= NUM_BP_EMBEDDED_TYPES)
1865 		return (EINVAL);
1866 	if (drrwnp->drr_compression >= ZIO_COMPRESS_FUNCTIONS)
1867 		return (EINVAL);
1868 
1869 	tx = dmu_tx_create(rwa->os);
1870 
1871 	dmu_tx_hold_write(tx, drrwnp->drr_object,
1872 	    drrwnp->drr_offset, drrwnp->drr_length);
1873 	err = dmu_tx_assign(tx, TXG_WAIT);
1874 	if (err != 0) {
1875 		dmu_tx_abort(tx);
1876 		return (err);
1877 	}
1878 
1879 	dmu_write_embedded(rwa->os, drrwnp->drr_object,
1880 	    drrwnp->drr_offset, data, drrwnp->drr_etype,
1881 	    drrwnp->drr_compression, drrwnp->drr_lsize, drrwnp->drr_psize,
1882 	    rwa->byteswap ^ ZFS_HOST_BYTEORDER, tx);
1883 
1884 	dmu_tx_commit(tx);
1885 	return (0);
1886 }
1887 
1888 static int
1889 receive_spill(struct receive_writer_arg *rwa, struct drr_spill *drrs,
1890     void *data)
1891 {
1892 	dmu_tx_t *tx;
1893 	dmu_buf_t *db, *db_spill;
1894 	int err;
1895 
1896 	if (drrs->drr_length < SPA_MINBLOCKSIZE ||
1897 	    drrs->drr_length > spa_maxblocksize(dmu_objset_spa(rwa->os)))
1898 		return (SET_ERROR(EINVAL));
1899 
1900 	if (dmu_object_info(rwa->os, drrs->drr_object, NULL) != 0)
1901 		return (SET_ERROR(EINVAL));
1902 
1903 	VERIFY0(dmu_bonus_hold(rwa->os, drrs->drr_object, FTAG, &db));
1904 	if ((err = dmu_spill_hold_by_bonus(db, FTAG, &db_spill)) != 0) {
1905 		dmu_buf_rele(db, FTAG);
1906 		return (err);
1907 	}
1908 
1909 	tx = dmu_tx_create(rwa->os);
1910 
1911 	dmu_tx_hold_spill(tx, db->db_object);
1912 
1913 	err = dmu_tx_assign(tx, TXG_WAIT);
1914 	if (err != 0) {
1915 		dmu_buf_rele(db, FTAG);
1916 		dmu_buf_rele(db_spill, FTAG);
1917 		dmu_tx_abort(tx);
1918 		return (err);
1919 	}
1920 	dmu_buf_will_dirty(db_spill, tx);
1921 
1922 	if (db_spill->db_size < drrs->drr_length)
1923 		VERIFY(0 == dbuf_spill_set_blksz(db_spill,
1924 		    drrs->drr_length, tx));
1925 	bcopy(data, db_spill->db_data, drrs->drr_length);
1926 
1927 	dmu_buf_rele(db, FTAG);
1928 	dmu_buf_rele(db_spill, FTAG);
1929 
1930 	dmu_tx_commit(tx);
1931 	return (0);
1932 }
1933 
1934 /* ARGSUSED */
1935 static int
1936 receive_free(struct receive_writer_arg *rwa, struct drr_free *drrf)
1937 {
1938 	int err;
1939 
1940 	if (drrf->drr_length != -1ULL &&
1941 	    drrf->drr_offset + drrf->drr_length < drrf->drr_offset)
1942 		return (SET_ERROR(EINVAL));
1943 
1944 	if (dmu_object_info(rwa->os, drrf->drr_object, NULL) != 0)
1945 		return (SET_ERROR(EINVAL));
1946 
1947 	err = dmu_free_long_range(rwa->os, drrf->drr_object,
1948 	    drrf->drr_offset, drrf->drr_length);
1949 
1950 	return (err);
1951 }
1952 
1953 /* used to destroy the drc_ds on error */
1954 static void
1955 dmu_recv_cleanup_ds(dmu_recv_cookie_t *drc)
1956 {
1957 	char name[MAXNAMELEN];
1958 	dsl_dataset_name(drc->drc_ds, name);
1959 	dsl_dataset_disown(drc->drc_ds, dmu_recv_tag);
1960 	(void) dsl_destroy_head(name);
1961 }
1962 
1963 static void
1964 receive_cksum(struct receive_arg *ra, int len, void *buf)
1965 {
1966 	if (ra->byteswap) {
1967 		fletcher_4_incremental_byteswap(buf, len, &ra->cksum);
1968 	} else {
1969 		fletcher_4_incremental_native(buf, len, &ra->cksum);
1970 	}
1971 }
1972 
1973 /*
1974  * Read the payload into a buffer of size len, and update the current record's
1975  * payload field.
1976  * Allocate ra->next_rrd and read the next record's header into
1977  * ra->next_rrd->header.
1978  * Verify checksum of payload and next record.
1979  */
1980 static int
1981 receive_read_payload_and_next_header(struct receive_arg *ra, int len, void *buf)
1982 {
1983 	int err;
1984 
1985 	if (len != 0) {
1986 		ASSERT3U(len, <=, SPA_MAXBLOCKSIZE);
1987 		ra->rrd->payload = buf;
1988 		ra->rrd->payload_size = len;
1989 		err = receive_read(ra, len, ra->rrd->payload);
1990 		if (err != 0)
1991 			return (err);
1992 		receive_cksum(ra, len, ra->rrd->payload);
1993 	}
1994 
1995 	ra->prev_cksum = ra->cksum;
1996 
1997 	ra->next_rrd = kmem_zalloc(sizeof (*ra->next_rrd), KM_SLEEP);
1998 	err = receive_read(ra, sizeof (ra->next_rrd->header),
1999 	    &ra->next_rrd->header);
2000 	if (err != 0) {
2001 		kmem_free(ra->next_rrd, sizeof (*ra->next_rrd));
2002 		ra->next_rrd = NULL;
2003 		return (err);
2004 	}
2005 	if (ra->next_rrd->header.drr_type == DRR_BEGIN) {
2006 		kmem_free(ra->next_rrd, sizeof (*ra->next_rrd));
2007 		ra->next_rrd = NULL;
2008 		return (SET_ERROR(EINVAL));
2009 	}
2010 
2011 	/*
2012 	 * Note: checksum is of everything up to but not including the
2013 	 * checksum itself.
2014 	 */
2015 	ASSERT3U(offsetof(dmu_replay_record_t, drr_u.drr_checksum.drr_checksum),
2016 	    ==, sizeof (dmu_replay_record_t) - sizeof (zio_cksum_t));
2017 	receive_cksum(ra,
2018 	    offsetof(dmu_replay_record_t, drr_u.drr_checksum.drr_checksum),
2019 	    &ra->next_rrd->header);
2020 
2021 	zio_cksum_t cksum_orig =
2022 	    ra->next_rrd->header.drr_u.drr_checksum.drr_checksum;
2023 	zio_cksum_t *cksump =
2024 	    &ra->next_rrd->header.drr_u.drr_checksum.drr_checksum;
2025 
2026 	if (ra->byteswap)
2027 		byteswap_record(&ra->next_rrd->header);
2028 
2029 	if ((!ZIO_CHECKSUM_IS_ZERO(cksump)) &&
2030 	    !ZIO_CHECKSUM_EQUAL(ra->cksum, *cksump)) {
2031 		kmem_free(ra->next_rrd, sizeof (*ra->next_rrd));
2032 		ra->next_rrd = NULL;
2033 		return (SET_ERROR(ECKSUM));
2034 	}
2035 
2036 	receive_cksum(ra, sizeof (cksum_orig), &cksum_orig);
2037 
2038 	return (0);
2039 }
2040 
2041 /*
2042  * Issue the prefetch reads for any necessary indirect blocks.
2043  *
2044  * We use the object ignore list to tell us whether or not to issue prefetches
2045  * for a given object.  We do this for both correctness (in case the blocksize
2046  * of an object has changed) and performance (if the object doesn't exist, don't
2047  * needlessly try to issue prefetches).  We also trim the list as we go through
2048  * the stream to prevent it from growing to an unbounded size.
2049  *
2050  * The object numbers within will always be in sorted order, and any write
2051  * records we see will also be in sorted order, but they're not sorted with
2052  * respect to each other (i.e. we can get several object records before
2053  * receiving each object's write records).  As a result, once we've reached a
2054  * given object number, we can safely remove any reference to lower object
2055  * numbers in the ignore list. In practice, we receive up to 32 object records
2056  * before receiving write records, so the list can have up to 32 nodes in it.
2057  */
2058 /* ARGSUSED */
2059 static void
2060 receive_read_prefetch(struct receive_arg *ra,
2061     uint64_t object, uint64_t offset, uint64_t length)
2062 {
2063 	struct receive_ign_obj_node *node = list_head(&ra->ignore_obj_list);
2064 	while (node != NULL && node->object < object) {
2065 		VERIFY3P(node, ==, list_remove_head(&ra->ignore_obj_list));
2066 		kmem_free(node, sizeof (*node));
2067 		node = list_head(&ra->ignore_obj_list);
2068 	}
2069 	if (node == NULL || node->object > object) {
2070 		dmu_prefetch(ra->os, object, 1, offset, length,
2071 		    ZIO_PRIORITY_SYNC_READ);
2072 	}
2073 }
2074 
2075 /*
2076  * Read records off the stream, issuing any necessary prefetches.
2077  */
2078 static int
2079 receive_read_record(struct receive_arg *ra)
2080 {
2081 	int err;
2082 
2083 	switch (ra->rrd->header.drr_type) {
2084 	case DRR_OBJECT:
2085 	{
2086 		struct drr_object *drro = &ra->rrd->header.drr_u.drr_object;
2087 		uint32_t size = P2ROUNDUP(drro->drr_bonuslen, 8);
2088 		void *buf = kmem_zalloc(size, KM_SLEEP);
2089 		dmu_object_info_t doi;
2090 		err = receive_read_payload_and_next_header(ra, size, buf);
2091 		if (err != 0) {
2092 			kmem_free(buf, size);
2093 			return (err);
2094 		}
2095 		err = dmu_object_info(ra->os, drro->drr_object, &doi);
2096 		/*
2097 		 * See receive_read_prefetch for an explanation why we're
2098 		 * storing this object in the ignore_obj_list.
2099 		 */
2100 		if (err == ENOENT ||
2101 		    (err == 0 && doi.doi_data_block_size != drro->drr_blksz)) {
2102 			struct receive_ign_obj_node *node =
2103 			    kmem_zalloc(sizeof (*node),
2104 			    KM_SLEEP);
2105 			node->object = drro->drr_object;
2106 #ifdef ZFS_DEBUG
2107 			struct receive_ign_obj_node *last_object =
2108 			    list_tail(&ra->ignore_obj_list);
2109 			uint64_t last_objnum = (last_object != NULL ?
2110 			    last_object->object : 0);
2111 			ASSERT3U(node->object, >, last_objnum);
2112 #endif
2113 			list_insert_tail(&ra->ignore_obj_list, node);
2114 			err = 0;
2115 		}
2116 		return (err);
2117 	}
2118 	case DRR_FREEOBJECTS:
2119 	{
2120 		err = receive_read_payload_and_next_header(ra, 0, NULL);
2121 		return (err);
2122 	}
2123 	case DRR_WRITE:
2124 	{
2125 		struct drr_write *drrw = &ra->rrd->header.drr_u.drr_write;
2126 		arc_buf_t *abuf = arc_loan_buf(dmu_objset_spa(ra->os),
2127 		    drrw->drr_length);
2128 
2129 		err = receive_read_payload_and_next_header(ra,
2130 		    drrw->drr_length, abuf->b_data);
2131 		if (err != 0) {
2132 			dmu_return_arcbuf(abuf);
2133 			return (err);
2134 		}
2135 		ra->rrd->write_buf = abuf;
2136 		receive_read_prefetch(ra, drrw->drr_object, drrw->drr_offset,
2137 		    drrw->drr_length);
2138 		return (err);
2139 	}
2140 	case DRR_WRITE_BYREF:
2141 	{
2142 		struct drr_write_byref *drrwb =
2143 		    &ra->rrd->header.drr_u.drr_write_byref;
2144 		err = receive_read_payload_and_next_header(ra, 0, NULL);
2145 		receive_read_prefetch(ra, drrwb->drr_object, drrwb->drr_offset,
2146 		    drrwb->drr_length);
2147 		return (err);
2148 	}
2149 	case DRR_WRITE_EMBEDDED:
2150 	{
2151 		struct drr_write_embedded *drrwe =
2152 		    &ra->rrd->header.drr_u.drr_write_embedded;
2153 		uint32_t size = P2ROUNDUP(drrwe->drr_psize, 8);
2154 		void *buf = kmem_zalloc(size, KM_SLEEP);
2155 
2156 		err = receive_read_payload_and_next_header(ra, size, buf);
2157 		if (err != 0) {
2158 			kmem_free(buf, size);
2159 			return (err);
2160 		}
2161 
2162 		receive_read_prefetch(ra, drrwe->drr_object, drrwe->drr_offset,
2163 		    drrwe->drr_length);
2164 		return (err);
2165 	}
2166 	case DRR_FREE:
2167 	{
2168 		/*
2169 		 * It might be beneficial to prefetch indirect blocks here, but
2170 		 * we don't really have the data to decide for sure.
2171 		 */
2172 		err = receive_read_payload_and_next_header(ra, 0, NULL);
2173 		return (err);
2174 	}
2175 	case DRR_END:
2176 	{
2177 		struct drr_end *drre = &ra->rrd->header.drr_u.drr_end;
2178 		if (!ZIO_CHECKSUM_EQUAL(ra->prev_cksum, drre->drr_checksum))
2179 			return (SET_ERROR(EINVAL));
2180 		return (0);
2181 	}
2182 	case DRR_SPILL:
2183 	{
2184 		struct drr_spill *drrs = &ra->rrd->header.drr_u.drr_spill;
2185 		void *buf = kmem_zalloc(drrs->drr_length, KM_SLEEP);
2186 		err = receive_read_payload_and_next_header(ra, drrs->drr_length,
2187 		    buf);
2188 		if (err != 0)
2189 			kmem_free(buf, drrs->drr_length);
2190 		return (err);
2191 	}
2192 	default:
2193 		return (SET_ERROR(EINVAL));
2194 	}
2195 }
2196 
2197 /*
2198  * Commit the records to the pool.
2199  */
2200 static int
2201 receive_process_record(struct receive_writer_arg *rwa,
2202     struct receive_record_arg *rrd)
2203 {
2204 	int err;
2205 
2206 	switch (rrd->header.drr_type) {
2207 	case DRR_OBJECT:
2208 	{
2209 		struct drr_object *drro = &rrd->header.drr_u.drr_object;
2210 		err = receive_object(rwa, drro, rrd->payload);
2211 		kmem_free(rrd->payload, rrd->payload_size);
2212 		rrd->payload = NULL;
2213 		return (err);
2214 	}
2215 	case DRR_FREEOBJECTS:
2216 	{
2217 		struct drr_freeobjects *drrfo =
2218 		    &rrd->header.drr_u.drr_freeobjects;
2219 		return (receive_freeobjects(rwa, drrfo));
2220 	}
2221 	case DRR_WRITE:
2222 	{
2223 		struct drr_write *drrw = &rrd->header.drr_u.drr_write;
2224 		err = receive_write(rwa, drrw, rrd->write_buf);
2225 		/* if receive_write() is successful, it consumes the arc_buf */
2226 		if (err != 0)
2227 			dmu_return_arcbuf(rrd->write_buf);
2228 		rrd->write_buf = NULL;
2229 		rrd->payload = NULL;
2230 		return (err);
2231 	}
2232 	case DRR_WRITE_BYREF:
2233 	{
2234 		struct drr_write_byref *drrwbr =
2235 		    &rrd->header.drr_u.drr_write_byref;
2236 		return (receive_write_byref(rwa, drrwbr));
2237 	}
2238 	case DRR_WRITE_EMBEDDED:
2239 	{
2240 		struct drr_write_embedded *drrwe =
2241 		    &rrd->header.drr_u.drr_write_embedded;
2242 		err = receive_write_embedded(rwa, drrwe, rrd->payload);
2243 		kmem_free(rrd->payload, rrd->payload_size);
2244 		rrd->payload = NULL;
2245 		return (err);
2246 	}
2247 	case DRR_FREE:
2248 	{
2249 		struct drr_free *drrf = &rrd->header.drr_u.drr_free;
2250 		return (receive_free(rwa, drrf));
2251 	}
2252 	case DRR_SPILL:
2253 	{
2254 		struct drr_spill *drrs = &rrd->header.drr_u.drr_spill;
2255 		err = receive_spill(rwa, drrs, rrd->payload);
2256 		kmem_free(rrd->payload, rrd->payload_size);
2257 		rrd->payload = NULL;
2258 		return (err);
2259 	}
2260 	default:
2261 		return (SET_ERROR(EINVAL));
2262 	}
2263 }
2264 
2265 /*
2266  * dmu_recv_stream's worker thread; pull records off the queue, and then call
2267  * receive_process_record  When we're done, signal the main thread and exit.
2268  */
2269 static void
2270 receive_writer_thread(void *arg)
2271 {
2272 	struct receive_writer_arg *rwa = arg;
2273 	struct receive_record_arg *rrd;
2274 	for (rrd = bqueue_dequeue(&rwa->q); !rrd->eos_marker;
2275 	    rrd = bqueue_dequeue(&rwa->q)) {
2276 		/*
2277 		 * If there's an error, the main thread will stop putting things
2278 		 * on the queue, but we need to clear everything in it before we
2279 		 * can exit.
2280 		 */
2281 		if (rwa->err == 0) {
2282 			rwa->err = receive_process_record(rwa, rrd);
2283 		} else if (rrd->write_buf != NULL) {
2284 			dmu_return_arcbuf(rrd->write_buf);
2285 			rrd->write_buf = NULL;
2286 			rrd->payload = NULL;
2287 		} else if (rrd->payload != NULL) {
2288 			kmem_free(rrd->payload, rrd->payload_size);
2289 			rrd->payload = NULL;
2290 		}
2291 		kmem_free(rrd, sizeof (*rrd));
2292 	}
2293 	kmem_free(rrd, sizeof (*rrd));
2294 	mutex_enter(&rwa->mutex);
2295 	rwa->done = B_TRUE;
2296 	cv_signal(&rwa->cv);
2297 	mutex_exit(&rwa->mutex);
2298 }
2299 
2300 /*
2301  * Read in the stream's records, one by one, and apply them to the pool.  There
2302  * are two threads involved; the thread that calls this function will spin up a
2303  * worker thread, read the records off the stream one by one, and issue
2304  * prefetches for any necessary indirect blocks.  It will then push the records
2305  * onto an internal blocking queue.  The worker thread will pull the records off
2306  * the queue, and actually write the data into the DMU.  This way, the worker
2307  * thread doesn't have to wait for reads to complete, since everything it needs
2308  * (the indirect blocks) will be prefetched.
2309  *
2310  * NB: callers *must* call dmu_recv_end() if this succeeds.
2311  */
2312 int
2313 dmu_recv_stream(dmu_recv_cookie_t *drc, vnode_t *vp, offset_t *voffp,
2314     int cleanup_fd, uint64_t *action_handlep)
2315 {
2316 	int err = 0;
2317 	struct receive_arg ra = { 0 };
2318 	struct receive_writer_arg rwa = { 0 };
2319 	int featureflags;
2320 
2321 	ra.byteswap = drc->drc_byteswap;
2322 	ra.cksum = drc->drc_cksum;
2323 	ra.vp = vp;
2324 	ra.voff = *voffp;
2325 	list_create(&ra.ignore_obj_list, sizeof (struct receive_ign_obj_node),
2326 	    offsetof(struct receive_ign_obj_node, node));
2327 
2328 	/* these were verified in dmu_recv_begin */
2329 	ASSERT3U(DMU_GET_STREAM_HDRTYPE(drc->drc_drrb->drr_versioninfo), ==,
2330 	    DMU_SUBSTREAM);
2331 	ASSERT3U(drc->drc_drrb->drr_type, <, DMU_OST_NUMTYPES);
2332 
2333 	/*
2334 	 * Open the objset we are modifying.
2335 	 */
2336 	VERIFY0(dmu_objset_from_ds(drc->drc_ds, &ra.os));
2337 
2338 	ASSERT(dsl_dataset_phys(drc->drc_ds)->ds_flags & DS_FLAG_INCONSISTENT);
2339 
2340 	featureflags = DMU_GET_FEATUREFLAGS(drc->drc_drrb->drr_versioninfo);
2341 
2342 	/* if this stream is dedup'ed, set up the avl tree for guid mapping */
2343 	if (featureflags & DMU_BACKUP_FEATURE_DEDUP) {
2344 		minor_t minor;
2345 
2346 		if (cleanup_fd == -1) {
2347 			ra.err = SET_ERROR(EBADF);
2348 			goto out;
2349 		}
2350 		ra.err = zfs_onexit_fd_hold(cleanup_fd, &minor);
2351 		if (ra.err != 0) {
2352 			cleanup_fd = -1;
2353 			goto out;
2354 		}
2355 
2356 		if (*action_handlep == 0) {
2357 			rwa.guid_to_ds_map =
2358 			    kmem_alloc(sizeof (avl_tree_t), KM_SLEEP);
2359 			avl_create(rwa.guid_to_ds_map, guid_compare,
2360 			    sizeof (guid_map_entry_t),
2361 			    offsetof(guid_map_entry_t, avlnode));
2362 			err = zfs_onexit_add_cb(minor,
2363 			    free_guid_map_onexit, rwa.guid_to_ds_map,
2364 			    action_handlep);
2365 			if (ra.err != 0)
2366 				goto out;
2367 		} else {
2368 			err = zfs_onexit_cb_data(minor, *action_handlep,
2369 			    (void **)&rwa.guid_to_ds_map);
2370 			if (ra.err != 0)
2371 				goto out;
2372 		}
2373 
2374 		drc->drc_guid_to_ds_map = rwa.guid_to_ds_map;
2375 	}
2376 
2377 	err = receive_read_payload_and_next_header(&ra, 0, NULL);
2378 	if (err)
2379 		goto out;
2380 
2381 	(void) bqueue_init(&rwa.q, zfs_recv_queue_length,
2382 	    offsetof(struct receive_record_arg, node));
2383 	cv_init(&rwa.cv, NULL, CV_DEFAULT, NULL);
2384 	mutex_init(&rwa.mutex, NULL, MUTEX_DEFAULT, NULL);
2385 	rwa.os = ra.os;
2386 	rwa.byteswap = drc->drc_byteswap;
2387 
2388 	(void) thread_create(NULL, 0, receive_writer_thread, &rwa, 0, curproc,
2389 	    TS_RUN, minclsyspri);
2390 	/*
2391 	 * We're reading rwa.err without locks, which is safe since we are the
2392 	 * only reader, and the worker thread is the only writer.  It's ok if we
2393 	 * miss a write for an iteration or two of the loop, since the writer
2394 	 * thread will keep freeing records we send it until we send it an eos
2395 	 * marker.
2396 	 *
2397 	 * We can leave this loop in 3 ways:  First, if rwa.err is
2398 	 * non-zero.  In that case, the writer thread will free the rrd we just
2399 	 * pushed.  Second, if  we're interrupted; in that case, either it's the
2400 	 * first loop and ra.rrd was never allocated, or it's later, and ra.rrd
2401 	 * has been handed off to the writer thread who will free it.  Finally,
2402 	 * if receive_read_record fails or we're at the end of the stream, then
2403 	 * we free ra.rrd and exit.
2404 	 */
2405 	while (rwa.err == 0) {
2406 		if (issig(JUSTLOOKING) && issig(FORREAL)) {
2407 			err = SET_ERROR(EINTR);
2408 			break;
2409 		}
2410 
2411 		ASSERT3P(ra.rrd, ==, NULL);
2412 		ra.rrd = ra.next_rrd;
2413 		ra.next_rrd = NULL;
2414 		/* Allocates and loads header into ra.next_rrd */
2415 		err = receive_read_record(&ra);
2416 
2417 		if (ra.rrd->header.drr_type == DRR_END || err != 0) {
2418 			kmem_free(ra.rrd, sizeof (*ra.rrd));
2419 			ra.rrd = NULL;
2420 			break;
2421 		}
2422 
2423 		bqueue_enqueue(&rwa.q, ra.rrd,
2424 		    sizeof (struct receive_record_arg) + ra.rrd->payload_size);
2425 		ra.rrd = NULL;
2426 	}
2427 	if (ra.next_rrd == NULL)
2428 		ra.next_rrd = kmem_zalloc(sizeof (*ra.next_rrd), KM_SLEEP);
2429 	ra.next_rrd->eos_marker = B_TRUE;
2430 	bqueue_enqueue(&rwa.q, ra.next_rrd, 1);
2431 
2432 	mutex_enter(&rwa.mutex);
2433 	while (!rwa.done) {
2434 		cv_wait(&rwa.cv, &rwa.mutex);
2435 	}
2436 	mutex_exit(&rwa.mutex);
2437 
2438 	cv_destroy(&rwa.cv);
2439 	mutex_destroy(&rwa.mutex);
2440 	bqueue_destroy(&rwa.q);
2441 	if (err == 0)
2442 		err = rwa.err;
2443 
2444 out:
2445 	if ((featureflags & DMU_BACKUP_FEATURE_DEDUP) && (cleanup_fd != -1))
2446 		zfs_onexit_fd_rele(cleanup_fd);
2447 
2448 	if (err != 0) {
2449 		/*
2450 		 * destroy what we created, so we don't leave it in the
2451 		 * inconsistent restoring state.
2452 		 */
2453 		dmu_recv_cleanup_ds(drc);
2454 	}
2455 
2456 	*voffp = ra.voff;
2457 	for (struct receive_ign_obj_node *n =
2458 	    list_remove_head(&ra.ignore_obj_list); n != NULL;
2459 	    n = list_remove_head(&ra.ignore_obj_list)) {
2460 		kmem_free(n, sizeof (*n));
2461 	}
2462 	list_destroy(&ra.ignore_obj_list);
2463 	return (err);
2464 }
2465 
2466 static int
2467 dmu_recv_end_check(void *arg, dmu_tx_t *tx)
2468 {
2469 	dmu_recv_cookie_t *drc = arg;
2470 	dsl_pool_t *dp = dmu_tx_pool(tx);
2471 	int error;
2472 
2473 	ASSERT3P(drc->drc_ds->ds_owner, ==, dmu_recv_tag);
2474 
2475 	if (!drc->drc_newfs) {
2476 		dsl_dataset_t *origin_head;
2477 
2478 		error = dsl_dataset_hold(dp, drc->drc_tofs, FTAG, &origin_head);
2479 		if (error != 0)
2480 			return (error);
2481 		if (drc->drc_force) {
2482 			/*
2483 			 * We will destroy any snapshots in tofs (i.e. before
2484 			 * origin_head) that are after the origin (which is
2485 			 * the snap before drc_ds, because drc_ds can not
2486 			 * have any snaps of its own).
2487 			 */
2488 			uint64_t obj;
2489 
2490 			obj = dsl_dataset_phys(origin_head)->ds_prev_snap_obj;
2491 			while (obj !=
2492 			    dsl_dataset_phys(drc->drc_ds)->ds_prev_snap_obj) {
2493 				dsl_dataset_t *snap;
2494 				error = dsl_dataset_hold_obj(dp, obj, FTAG,
2495 				    &snap);
2496 				if (error != 0)
2497 					break;
2498 				if (snap->ds_dir != origin_head->ds_dir)
2499 					error = SET_ERROR(EINVAL);
2500 				if (error == 0)  {
2501 					error = dsl_destroy_snapshot_check_impl(
2502 					    snap, B_FALSE);
2503 				}
2504 				obj = dsl_dataset_phys(snap)->ds_prev_snap_obj;
2505 				dsl_dataset_rele(snap, FTAG);
2506 				if (error != 0)
2507 					break;
2508 			}
2509 			if (error != 0) {
2510 				dsl_dataset_rele(origin_head, FTAG);
2511 				return (error);
2512 			}
2513 		}
2514 		error = dsl_dataset_clone_swap_check_impl(drc->drc_ds,
2515 		    origin_head, drc->drc_force, drc->drc_owner, tx);
2516 		if (error != 0) {
2517 			dsl_dataset_rele(origin_head, FTAG);
2518 			return (error);
2519 		}
2520 		error = dsl_dataset_snapshot_check_impl(origin_head,
2521 		    drc->drc_tosnap, tx, B_TRUE, 1, drc->drc_cred);
2522 		dsl_dataset_rele(origin_head, FTAG);
2523 		if (error != 0)
2524 			return (error);
2525 
2526 		error = dsl_destroy_head_check_impl(drc->drc_ds, 1);
2527 	} else {
2528 		error = dsl_dataset_snapshot_check_impl(drc->drc_ds,
2529 		    drc->drc_tosnap, tx, B_TRUE, 1, drc->drc_cred);
2530 	}
2531 	return (error);
2532 }
2533 
2534 static void
2535 dmu_recv_end_sync(void *arg, dmu_tx_t *tx)
2536 {
2537 	dmu_recv_cookie_t *drc = arg;
2538 	dsl_pool_t *dp = dmu_tx_pool(tx);
2539 
2540 	spa_history_log_internal_ds(drc->drc_ds, "finish receiving",
2541 	    tx, "snap=%s", drc->drc_tosnap);
2542 
2543 	if (!drc->drc_newfs) {
2544 		dsl_dataset_t *origin_head;
2545 
2546 		VERIFY0(dsl_dataset_hold(dp, drc->drc_tofs, FTAG,
2547 		    &origin_head));
2548 
2549 		if (drc->drc_force) {
2550 			/*
2551 			 * Destroy any snapshots of drc_tofs (origin_head)
2552 			 * after the origin (the snap before drc_ds).
2553 			 */
2554 			uint64_t obj;
2555 
2556 			obj = dsl_dataset_phys(origin_head)->ds_prev_snap_obj;
2557 			while (obj !=
2558 			    dsl_dataset_phys(drc->drc_ds)->ds_prev_snap_obj) {
2559 				dsl_dataset_t *snap;
2560 				VERIFY0(dsl_dataset_hold_obj(dp, obj, FTAG,
2561 				    &snap));
2562 				ASSERT3P(snap->ds_dir, ==, origin_head->ds_dir);
2563 				obj = dsl_dataset_phys(snap)->ds_prev_snap_obj;
2564 				dsl_destroy_snapshot_sync_impl(snap,
2565 				    B_FALSE, tx);
2566 				dsl_dataset_rele(snap, FTAG);
2567 			}
2568 		}
2569 		VERIFY3P(drc->drc_ds->ds_prev, ==,
2570 		    origin_head->ds_prev);
2571 
2572 		dsl_dataset_clone_swap_sync_impl(drc->drc_ds,
2573 		    origin_head, tx);
2574 		dsl_dataset_snapshot_sync_impl(origin_head,
2575 		    drc->drc_tosnap, tx);
2576 
2577 		/* set snapshot's creation time and guid */
2578 		dmu_buf_will_dirty(origin_head->ds_prev->ds_dbuf, tx);
2579 		dsl_dataset_phys(origin_head->ds_prev)->ds_creation_time =
2580 		    drc->drc_drrb->drr_creation_time;
2581 		dsl_dataset_phys(origin_head->ds_prev)->ds_guid =
2582 		    drc->drc_drrb->drr_toguid;
2583 		dsl_dataset_phys(origin_head->ds_prev)->ds_flags &=
2584 		    ~DS_FLAG_INCONSISTENT;
2585 
2586 		dmu_buf_will_dirty(origin_head->ds_dbuf, tx);
2587 		dsl_dataset_phys(origin_head)->ds_flags &=
2588 		    ~DS_FLAG_INCONSISTENT;
2589 
2590 		dsl_dataset_rele(origin_head, FTAG);
2591 		dsl_destroy_head_sync_impl(drc->drc_ds, tx);
2592 
2593 		if (drc->drc_owner != NULL)
2594 			VERIFY3P(origin_head->ds_owner, ==, drc->drc_owner);
2595 	} else {
2596 		dsl_dataset_t *ds = drc->drc_ds;
2597 
2598 		dsl_dataset_snapshot_sync_impl(ds, drc->drc_tosnap, tx);
2599 
2600 		/* set snapshot's creation time and guid */
2601 		dmu_buf_will_dirty(ds->ds_prev->ds_dbuf, tx);
2602 		dsl_dataset_phys(ds->ds_prev)->ds_creation_time =
2603 		    drc->drc_drrb->drr_creation_time;
2604 		dsl_dataset_phys(ds->ds_prev)->ds_guid =
2605 		    drc->drc_drrb->drr_toguid;
2606 		dsl_dataset_phys(ds->ds_prev)->ds_flags &=
2607 		    ~DS_FLAG_INCONSISTENT;
2608 
2609 		dmu_buf_will_dirty(ds->ds_dbuf, tx);
2610 		dsl_dataset_phys(ds)->ds_flags &= ~DS_FLAG_INCONSISTENT;
2611 	}
2612 	drc->drc_newsnapobj = dsl_dataset_phys(drc->drc_ds)->ds_prev_snap_obj;
2613 	/*
2614 	 * Release the hold from dmu_recv_begin.  This must be done before
2615 	 * we return to open context, so that when we free the dataset's dnode,
2616 	 * we can evict its bonus buffer.
2617 	 */
2618 	dsl_dataset_disown(drc->drc_ds, dmu_recv_tag);
2619 	drc->drc_ds = NULL;
2620 }
2621 
2622 static int
2623 add_ds_to_guidmap(const char *name, avl_tree_t *guid_map, uint64_t snapobj)
2624 {
2625 	dsl_pool_t *dp;
2626 	dsl_dataset_t *snapds;
2627 	guid_map_entry_t *gmep;
2628 	int err;
2629 
2630 	ASSERT(guid_map != NULL);
2631 
2632 	err = dsl_pool_hold(name, FTAG, &dp);
2633 	if (err != 0)
2634 		return (err);
2635 	gmep = kmem_alloc(sizeof (*gmep), KM_SLEEP);
2636 	err = dsl_dataset_hold_obj(dp, snapobj, gmep, &snapds);
2637 	if (err == 0) {
2638 		gmep->guid = dsl_dataset_phys(snapds)->ds_guid;
2639 		gmep->gme_ds = snapds;
2640 		avl_add(guid_map, gmep);
2641 		dsl_dataset_long_hold(snapds, gmep);
2642 	} else {
2643 		kmem_free(gmep, sizeof (*gmep));
2644 	}
2645 
2646 	dsl_pool_rele(dp, FTAG);
2647 	return (err);
2648 }
2649 
2650 static int dmu_recv_end_modified_blocks = 3;
2651 
2652 static int
2653 dmu_recv_existing_end(dmu_recv_cookie_t *drc)
2654 {
2655 	int error;
2656 	char name[MAXNAMELEN];
2657 
2658 #ifdef _KERNEL
2659 	/*
2660 	 * We will be destroying the ds; make sure its origin is unmounted if
2661 	 * necessary.
2662 	 */
2663 	dsl_dataset_name(drc->drc_ds, name);
2664 	zfs_destroy_unmount_origin(name);
2665 #endif
2666 
2667 	error = dsl_sync_task(drc->drc_tofs,
2668 	    dmu_recv_end_check, dmu_recv_end_sync, drc,
2669 	    dmu_recv_end_modified_blocks, ZFS_SPACE_CHECK_NORMAL);
2670 
2671 	if (error != 0)
2672 		dmu_recv_cleanup_ds(drc);
2673 	return (error);
2674 }
2675 
2676 static int
2677 dmu_recv_new_end(dmu_recv_cookie_t *drc)
2678 {
2679 	int error;
2680 
2681 	error = dsl_sync_task(drc->drc_tofs,
2682 	    dmu_recv_end_check, dmu_recv_end_sync, drc,
2683 	    dmu_recv_end_modified_blocks, ZFS_SPACE_CHECK_NORMAL);
2684 
2685 	if (error != 0) {
2686 		dmu_recv_cleanup_ds(drc);
2687 	} else if (drc->drc_guid_to_ds_map != NULL) {
2688 		(void) add_ds_to_guidmap(drc->drc_tofs,
2689 		    drc->drc_guid_to_ds_map,
2690 		    drc->drc_newsnapobj);
2691 	}
2692 	return (error);
2693 }
2694 
2695 int
2696 dmu_recv_end(dmu_recv_cookie_t *drc, void *owner)
2697 {
2698 	drc->drc_owner = owner;
2699 
2700 	if (drc->drc_newfs)
2701 		return (dmu_recv_new_end(drc));
2702 	else
2703 		return (dmu_recv_existing_end(drc));
2704 }
2705 
2706 /*
2707  * Return TRUE if this objset is currently being received into.
2708  */
2709 boolean_t
2710 dmu_objset_is_receiving(objset_t *os)
2711 {
2712 	return (os->os_dsl_dataset != NULL &&
2713 	    os->os_dsl_dataset->ds_owner == dmu_recv_tag);
2714 }
2715