xref: /titanic_51/usr/src/uts/common/fs/zfs/dmu_send.c (revision cf988fac1debd92859f8068ee3d3e53782043469)
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) 2013 by Delphix. All rights reserved.
25  * Copyright (c) 2012, Joyent, Inc. All rights reserved.
26  */
27 
28 #include <sys/dmu.h>
29 #include <sys/dmu_impl.h>
30 #include <sys/dmu_tx.h>
31 #include <sys/dbuf.h>
32 #include <sys/dnode.h>
33 #include <sys/zfs_context.h>
34 #include <sys/dmu_objset.h>
35 #include <sys/dmu_traverse.h>
36 #include <sys/dsl_dataset.h>
37 #include <sys/dsl_dir.h>
38 #include <sys/dsl_prop.h>
39 #include <sys/dsl_pool.h>
40 #include <sys/dsl_synctask.h>
41 #include <sys/zfs_ioctl.h>
42 #include <sys/zap.h>
43 #include <sys/zio_checksum.h>
44 #include <sys/zfs_znode.h>
45 #include <zfs_fletcher.h>
46 #include <sys/avl.h>
47 #include <sys/ddt.h>
48 #include <sys/zfs_onexit.h>
49 #include <sys/dmu_send.h>
50 #include <sys/dsl_destroy.h>
51 #include <sys/dsl_bookmark.h>
52 
53 /* Set this tunable to TRUE to replace corrupt data with 0x2f5baddb10c */
54 int zfs_send_corrupt_data = B_FALSE;
55 
56 static char *dmu_recv_tag = "dmu_recv_tag";
57 static const char *recv_clone_name = "%recv";
58 
59 static int
60 dump_bytes(dmu_sendarg_t *dsp, void *buf, int len)
61 {
62 	dsl_dataset_t *ds = dsp->dsa_os->os_dsl_dataset;
63 	ssize_t resid; /* have to get resid to get detailed errno */
64 	ASSERT0(len % 8);
65 
66 	fletcher_4_incremental_native(buf, len, &dsp->dsa_zc);
67 	dsp->dsa_err = vn_rdwr(UIO_WRITE, dsp->dsa_vp,
68 	    (caddr_t)buf, len,
69 	    0, UIO_SYSSPACE, FAPPEND, RLIM64_INFINITY, CRED(), &resid);
70 
71 	mutex_enter(&ds->ds_sendstream_lock);
72 	*dsp->dsa_off += len;
73 	mutex_exit(&ds->ds_sendstream_lock);
74 
75 	return (dsp->dsa_err);
76 }
77 
78 static int
79 dump_free(dmu_sendarg_t *dsp, uint64_t object, uint64_t offset,
80     uint64_t length)
81 {
82 	struct drr_free *drrf = &(dsp->dsa_drr->drr_u.drr_free);
83 
84 	/*
85 	 * When we receive a free record, dbuf_free_range() assumes
86 	 * that the receiving system doesn't have any dbufs in the range
87 	 * being freed.  This is always true because there is a one-record
88 	 * constraint: we only send one WRITE record for any given
89 	 * object+offset.  We know that the one-record constraint is
90 	 * true because we always send data in increasing order by
91 	 * object,offset.
92 	 *
93 	 * If the increasing-order constraint ever changes, we should find
94 	 * another way to assert that the one-record constraint is still
95 	 * satisfied.
96 	 */
97 	ASSERT(object > dsp->dsa_last_data_object ||
98 	    (object == dsp->dsa_last_data_object &&
99 	    offset > dsp->dsa_last_data_offset));
100 
101 	/*
102 	 * If we are doing a non-incremental send, then there can't
103 	 * be any data in the dataset we're receiving into.  Therefore
104 	 * a free record would simply be a no-op.  Save space by not
105 	 * sending it to begin with.
106 	 */
107 	if (!dsp->dsa_incremental)
108 		return (0);
109 
110 	if (length != -1ULL && offset + length < offset)
111 		length = -1ULL;
112 
113 	/*
114 	 * If there is a pending op, but it's not PENDING_FREE, push it out,
115 	 * since free block aggregation can only be done for blocks of the
116 	 * same type (i.e., DRR_FREE records can only be aggregated with
117 	 * other DRR_FREE records.  DRR_FREEOBJECTS records can only be
118 	 * aggregated with other DRR_FREEOBJECTS records.
119 	 */
120 	if (dsp->dsa_pending_op != PENDING_NONE &&
121 	    dsp->dsa_pending_op != PENDING_FREE) {
122 		if (dump_bytes(dsp, dsp->dsa_drr,
123 		    sizeof (dmu_replay_record_t)) != 0)
124 			return (SET_ERROR(EINTR));
125 		dsp->dsa_pending_op = PENDING_NONE;
126 	}
127 
128 	if (dsp->dsa_pending_op == PENDING_FREE) {
129 		/*
130 		 * There should never be a PENDING_FREE if length is -1
131 		 * (because dump_dnode is the only place where this
132 		 * function is called with a -1, and only after flushing
133 		 * any pending record).
134 		 */
135 		ASSERT(length != -1ULL);
136 		/*
137 		 * Check to see whether this free block can be aggregated
138 		 * with pending one.
139 		 */
140 		if (drrf->drr_object == object && drrf->drr_offset +
141 		    drrf->drr_length == offset) {
142 			drrf->drr_length += length;
143 			return (0);
144 		} else {
145 			/* not a continuation.  Push out pending record */
146 			if (dump_bytes(dsp, dsp->dsa_drr,
147 			    sizeof (dmu_replay_record_t)) != 0)
148 				return (SET_ERROR(EINTR));
149 			dsp->dsa_pending_op = PENDING_NONE;
150 		}
151 	}
152 	/* create a FREE record and make it pending */
153 	bzero(dsp->dsa_drr, sizeof (dmu_replay_record_t));
154 	dsp->dsa_drr->drr_type = DRR_FREE;
155 	drrf->drr_object = object;
156 	drrf->drr_offset = offset;
157 	drrf->drr_length = length;
158 	drrf->drr_toguid = dsp->dsa_toguid;
159 	if (length == -1ULL) {
160 		if (dump_bytes(dsp, dsp->dsa_drr,
161 		    sizeof (dmu_replay_record_t)) != 0)
162 			return (SET_ERROR(EINTR));
163 	} else {
164 		dsp->dsa_pending_op = PENDING_FREE;
165 	}
166 
167 	return (0);
168 }
169 
170 static int
171 dump_data(dmu_sendarg_t *dsp, dmu_object_type_t type,
172     uint64_t object, uint64_t offset, int blksz, const blkptr_t *bp, void *data)
173 {
174 	struct drr_write *drrw = &(dsp->dsa_drr->drr_u.drr_write);
175 
176 	/*
177 	 * We send data in increasing object, offset order.
178 	 * See comment in dump_free() for details.
179 	 */
180 	ASSERT(object > dsp->dsa_last_data_object ||
181 	    (object == dsp->dsa_last_data_object &&
182 	    offset > dsp->dsa_last_data_offset));
183 	dsp->dsa_last_data_object = object;
184 	dsp->dsa_last_data_offset = offset + blksz - 1;
185 
186 	/*
187 	 * If there is any kind of pending aggregation (currently either
188 	 * a grouping of free objects or free blocks), push it out to
189 	 * the stream, since aggregation can't be done across operations
190 	 * of different types.
191 	 */
192 	if (dsp->dsa_pending_op != PENDING_NONE) {
193 		if (dump_bytes(dsp, dsp->dsa_drr,
194 		    sizeof (dmu_replay_record_t)) != 0)
195 			return (SET_ERROR(EINTR));
196 		dsp->dsa_pending_op = PENDING_NONE;
197 	}
198 	/* write a DATA record */
199 	bzero(dsp->dsa_drr, sizeof (dmu_replay_record_t));
200 	dsp->dsa_drr->drr_type = DRR_WRITE;
201 	drrw->drr_object = object;
202 	drrw->drr_type = type;
203 	drrw->drr_offset = offset;
204 	drrw->drr_length = blksz;
205 	drrw->drr_toguid = dsp->dsa_toguid;
206 	drrw->drr_checksumtype = BP_GET_CHECKSUM(bp);
207 	if (zio_checksum_table[drrw->drr_checksumtype].ci_dedup)
208 		drrw->drr_checksumflags |= DRR_CHECKSUM_DEDUP;
209 	DDK_SET_LSIZE(&drrw->drr_key, BP_GET_LSIZE(bp));
210 	DDK_SET_PSIZE(&drrw->drr_key, BP_GET_PSIZE(bp));
211 	DDK_SET_COMPRESS(&drrw->drr_key, BP_GET_COMPRESS(bp));
212 	drrw->drr_key.ddk_cksum = bp->blk_cksum;
213 
214 	if (dump_bytes(dsp, dsp->dsa_drr, sizeof (dmu_replay_record_t)) != 0)
215 		return (SET_ERROR(EINTR));
216 	if (dump_bytes(dsp, data, blksz) != 0)
217 		return (SET_ERROR(EINTR));
218 	return (0);
219 }
220 
221 static int
222 dump_spill(dmu_sendarg_t *dsp, uint64_t object, int blksz, void *data)
223 {
224 	struct drr_spill *drrs = &(dsp->dsa_drr->drr_u.drr_spill);
225 
226 	if (dsp->dsa_pending_op != PENDING_NONE) {
227 		if (dump_bytes(dsp, dsp->dsa_drr,
228 		    sizeof (dmu_replay_record_t)) != 0)
229 			return (SET_ERROR(EINTR));
230 		dsp->dsa_pending_op = PENDING_NONE;
231 	}
232 
233 	/* write a SPILL record */
234 	bzero(dsp->dsa_drr, sizeof (dmu_replay_record_t));
235 	dsp->dsa_drr->drr_type = DRR_SPILL;
236 	drrs->drr_object = object;
237 	drrs->drr_length = blksz;
238 	drrs->drr_toguid = dsp->dsa_toguid;
239 
240 	if (dump_bytes(dsp, dsp->dsa_drr, sizeof (dmu_replay_record_t)))
241 		return (SET_ERROR(EINTR));
242 	if (dump_bytes(dsp, data, blksz))
243 		return (SET_ERROR(EINTR));
244 	return (0);
245 }
246 
247 static int
248 dump_freeobjects(dmu_sendarg_t *dsp, uint64_t firstobj, uint64_t numobjs)
249 {
250 	struct drr_freeobjects *drrfo = &(dsp->dsa_drr->drr_u.drr_freeobjects);
251 
252 	/* See comment in dump_free(). */
253 	if (!dsp->dsa_incremental)
254 		return (0);
255 
256 	/*
257 	 * If there is a pending op, but it's not PENDING_FREEOBJECTS,
258 	 * push it out, since free block aggregation can only be done for
259 	 * blocks of the same type (i.e., DRR_FREE records can only be
260 	 * aggregated with other DRR_FREE records.  DRR_FREEOBJECTS records
261 	 * can only be aggregated with other DRR_FREEOBJECTS records.
262 	 */
263 	if (dsp->dsa_pending_op != PENDING_NONE &&
264 	    dsp->dsa_pending_op != PENDING_FREEOBJECTS) {
265 		if (dump_bytes(dsp, dsp->dsa_drr,
266 		    sizeof (dmu_replay_record_t)) != 0)
267 			return (SET_ERROR(EINTR));
268 		dsp->dsa_pending_op = PENDING_NONE;
269 	}
270 	if (dsp->dsa_pending_op == PENDING_FREEOBJECTS) {
271 		/*
272 		 * See whether this free object array can be aggregated
273 		 * with pending one
274 		 */
275 		if (drrfo->drr_firstobj + drrfo->drr_numobjs == firstobj) {
276 			drrfo->drr_numobjs += numobjs;
277 			return (0);
278 		} else {
279 			/* can't be aggregated.  Push out pending record */
280 			if (dump_bytes(dsp, dsp->dsa_drr,
281 			    sizeof (dmu_replay_record_t)) != 0)
282 				return (SET_ERROR(EINTR));
283 			dsp->dsa_pending_op = PENDING_NONE;
284 		}
285 	}
286 
287 	/* write a FREEOBJECTS record */
288 	bzero(dsp->dsa_drr, sizeof (dmu_replay_record_t));
289 	dsp->dsa_drr->drr_type = DRR_FREEOBJECTS;
290 	drrfo->drr_firstobj = firstobj;
291 	drrfo->drr_numobjs = numobjs;
292 	drrfo->drr_toguid = dsp->dsa_toguid;
293 
294 	dsp->dsa_pending_op = PENDING_FREEOBJECTS;
295 
296 	return (0);
297 }
298 
299 static int
300 dump_dnode(dmu_sendarg_t *dsp, uint64_t object, dnode_phys_t *dnp)
301 {
302 	struct drr_object *drro = &(dsp->dsa_drr->drr_u.drr_object);
303 
304 	if (dnp == NULL || dnp->dn_type == DMU_OT_NONE)
305 		return (dump_freeobjects(dsp, object, 1));
306 
307 	if (dsp->dsa_pending_op != PENDING_NONE) {
308 		if (dump_bytes(dsp, dsp->dsa_drr,
309 		    sizeof (dmu_replay_record_t)) != 0)
310 			return (SET_ERROR(EINTR));
311 		dsp->dsa_pending_op = PENDING_NONE;
312 	}
313 
314 	/* write an OBJECT record */
315 	bzero(dsp->dsa_drr, sizeof (dmu_replay_record_t));
316 	dsp->dsa_drr->drr_type = DRR_OBJECT;
317 	drro->drr_object = object;
318 	drro->drr_type = dnp->dn_type;
319 	drro->drr_bonustype = dnp->dn_bonustype;
320 	drro->drr_blksz = dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT;
321 	drro->drr_bonuslen = dnp->dn_bonuslen;
322 	drro->drr_checksumtype = dnp->dn_checksum;
323 	drro->drr_compress = dnp->dn_compress;
324 	drro->drr_toguid = dsp->dsa_toguid;
325 
326 	if (dump_bytes(dsp, dsp->dsa_drr, sizeof (dmu_replay_record_t)) != 0)
327 		return (SET_ERROR(EINTR));
328 
329 	if (dump_bytes(dsp, DN_BONUS(dnp), P2ROUNDUP(dnp->dn_bonuslen, 8)) != 0)
330 		return (SET_ERROR(EINTR));
331 
332 	/* Free anything past the end of the file. */
333 	if (dump_free(dsp, object, (dnp->dn_maxblkid + 1) *
334 	    (dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT), -1ULL) != 0)
335 		return (SET_ERROR(EINTR));
336 	if (dsp->dsa_err != 0)
337 		return (SET_ERROR(EINTR));
338 	return (0);
339 }
340 
341 #define	BP_SPAN(dnp, level) \
342 	(((uint64_t)dnp->dn_datablkszsec) << (SPA_MINBLOCKSHIFT + \
343 	(level) * (dnp->dn_indblkshift - SPA_BLKPTRSHIFT)))
344 
345 /* ARGSUSED */
346 static int
347 backup_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
348     const zbookmark_t *zb, const dnode_phys_t *dnp, void *arg)
349 {
350 	dmu_sendarg_t *dsp = arg;
351 	dmu_object_type_t type = bp ? BP_GET_TYPE(bp) : DMU_OT_NONE;
352 	int err = 0;
353 
354 	if (issig(JUSTLOOKING) && issig(FORREAL))
355 		return (SET_ERROR(EINTR));
356 
357 	if (zb->zb_object != DMU_META_DNODE_OBJECT &&
358 	    DMU_OBJECT_IS_SPECIAL(zb->zb_object)) {
359 		return (0);
360 	} else if (zb->zb_level == ZB_ZIL_LEVEL) {
361 		/*
362 		 * If we are sending a non-snapshot (which is allowed on
363 		 * read-only pools), it may have a ZIL, which must be ignored.
364 		 */
365 		return (0);
366 	} else if (BP_IS_HOLE(bp) &&
367 	    zb->zb_object == DMU_META_DNODE_OBJECT) {
368 		uint64_t span = BP_SPAN(dnp, zb->zb_level);
369 		uint64_t dnobj = (zb->zb_blkid * span) >> DNODE_SHIFT;
370 		err = dump_freeobjects(dsp, dnobj, span >> DNODE_SHIFT);
371 	} else if (BP_IS_HOLE(bp)) {
372 		uint64_t span = BP_SPAN(dnp, zb->zb_level);
373 		err = dump_free(dsp, zb->zb_object, zb->zb_blkid * span, span);
374 	} else if (zb->zb_level > 0 || type == DMU_OT_OBJSET) {
375 		return (0);
376 	} else if (type == DMU_OT_DNODE) {
377 		dnode_phys_t *blk;
378 		int i;
379 		int blksz = BP_GET_LSIZE(bp);
380 		uint32_t aflags = ARC_WAIT;
381 		arc_buf_t *abuf;
382 
383 		if (arc_read(NULL, spa, bp, arc_getbuf_func, &abuf,
384 		    ZIO_PRIORITY_ASYNC_READ, ZIO_FLAG_CANFAIL,
385 		    &aflags, zb) != 0)
386 			return (SET_ERROR(EIO));
387 
388 		blk = abuf->b_data;
389 		for (i = 0; i < blksz >> DNODE_SHIFT; i++) {
390 			uint64_t dnobj = (zb->zb_blkid <<
391 			    (DNODE_BLOCK_SHIFT - DNODE_SHIFT)) + i;
392 			err = dump_dnode(dsp, dnobj, blk+i);
393 			if (err != 0)
394 				break;
395 		}
396 		(void) arc_buf_remove_ref(abuf, &abuf);
397 	} else if (type == DMU_OT_SA) {
398 		uint32_t aflags = ARC_WAIT;
399 		arc_buf_t *abuf;
400 		int blksz = BP_GET_LSIZE(bp);
401 
402 		if (arc_read(NULL, spa, bp, arc_getbuf_func, &abuf,
403 		    ZIO_PRIORITY_ASYNC_READ, ZIO_FLAG_CANFAIL,
404 		    &aflags, zb) != 0)
405 			return (SET_ERROR(EIO));
406 
407 		err = dump_spill(dsp, zb->zb_object, blksz, abuf->b_data);
408 		(void) arc_buf_remove_ref(abuf, &abuf);
409 	} else { /* it's a level-0 block of a regular object */
410 		uint32_t aflags = ARC_WAIT;
411 		arc_buf_t *abuf;
412 		int blksz = BP_GET_LSIZE(bp);
413 
414 		ASSERT0(zb->zb_level);
415 		if (arc_read(NULL, spa, bp, arc_getbuf_func, &abuf,
416 		    ZIO_PRIORITY_ASYNC_READ, ZIO_FLAG_CANFAIL,
417 		    &aflags, zb) != 0) {
418 			if (zfs_send_corrupt_data) {
419 				/* Send a block filled with 0x"zfs badd bloc" */
420 				abuf = arc_buf_alloc(spa, blksz, &abuf,
421 				    ARC_BUFC_DATA);
422 				uint64_t *ptr;
423 				for (ptr = abuf->b_data;
424 				    (char *)ptr < (char *)abuf->b_data + blksz;
425 				    ptr++)
426 					*ptr = 0x2f5baddb10c;
427 			} else {
428 				return (SET_ERROR(EIO));
429 			}
430 		}
431 
432 		err = dump_data(dsp, type, zb->zb_object, zb->zb_blkid * blksz,
433 		    blksz, bp, abuf->b_data);
434 		(void) arc_buf_remove_ref(abuf, &abuf);
435 	}
436 
437 	ASSERT(err == 0 || err == EINTR);
438 	return (err);
439 }
440 
441 /*
442  * Releases dp using the specified tag.
443  */
444 static int
445 dmu_send_impl(void *tag, dsl_pool_t *dp, dsl_dataset_t *ds,
446     zfs_bookmark_phys_t *fromzb, boolean_t is_clone, int outfd,
447     vnode_t *vp, offset_t *off)
448 {
449 	objset_t *os;
450 	dmu_replay_record_t *drr;
451 	dmu_sendarg_t *dsp;
452 	int err;
453 	uint64_t fromtxg = 0;
454 
455 	err = dmu_objset_from_ds(ds, &os);
456 	if (err != 0) {
457 		dsl_pool_rele(dp, tag);
458 		return (err);
459 	}
460 
461 	drr = kmem_zalloc(sizeof (dmu_replay_record_t), KM_SLEEP);
462 	drr->drr_type = DRR_BEGIN;
463 	drr->drr_u.drr_begin.drr_magic = DMU_BACKUP_MAGIC;
464 	DMU_SET_STREAM_HDRTYPE(drr->drr_u.drr_begin.drr_versioninfo,
465 	    DMU_SUBSTREAM);
466 
467 #ifdef _KERNEL
468 	if (dmu_objset_type(os) == DMU_OST_ZFS) {
469 		uint64_t version;
470 		if (zfs_get_zplprop(os, ZFS_PROP_VERSION, &version) != 0) {
471 			kmem_free(drr, sizeof (dmu_replay_record_t));
472 			dsl_pool_rele(dp, tag);
473 			return (SET_ERROR(EINVAL));
474 		}
475 		if (version >= ZPL_VERSION_SA) {
476 			DMU_SET_FEATUREFLAGS(
477 			    drr->drr_u.drr_begin.drr_versioninfo,
478 			    DMU_BACKUP_FEATURE_SA_SPILL);
479 		}
480 	}
481 #endif
482 
483 	drr->drr_u.drr_begin.drr_creation_time =
484 	    ds->ds_phys->ds_creation_time;
485 	drr->drr_u.drr_begin.drr_type = dmu_objset_type(os);
486 	if (is_clone)
487 		drr->drr_u.drr_begin.drr_flags |= DRR_FLAG_CLONE;
488 	drr->drr_u.drr_begin.drr_toguid = ds->ds_phys->ds_guid;
489 	if (ds->ds_phys->ds_flags & DS_FLAG_CI_DATASET)
490 		drr->drr_u.drr_begin.drr_flags |= DRR_FLAG_CI_DATA;
491 
492 	if (fromzb != NULL) {
493 		drr->drr_u.drr_begin.drr_fromguid = fromzb->zbm_guid;
494 		fromtxg = fromzb->zbm_creation_txg;
495 	}
496 	dsl_dataset_name(ds, drr->drr_u.drr_begin.drr_toname);
497 	if (!dsl_dataset_is_snapshot(ds)) {
498 		(void) strlcat(drr->drr_u.drr_begin.drr_toname, "@--head--",
499 		    sizeof (drr->drr_u.drr_begin.drr_toname));
500 	}
501 
502 	dsp = kmem_zalloc(sizeof (dmu_sendarg_t), KM_SLEEP);
503 
504 	dsp->dsa_drr = drr;
505 	dsp->dsa_vp = vp;
506 	dsp->dsa_outfd = outfd;
507 	dsp->dsa_proc = curproc;
508 	dsp->dsa_os = os;
509 	dsp->dsa_off = off;
510 	dsp->dsa_toguid = ds->ds_phys->ds_guid;
511 	ZIO_SET_CHECKSUM(&dsp->dsa_zc, 0, 0, 0, 0);
512 	dsp->dsa_pending_op = PENDING_NONE;
513 	dsp->dsa_incremental = (fromzb != NULL);
514 
515 	mutex_enter(&ds->ds_sendstream_lock);
516 	list_insert_head(&ds->ds_sendstreams, dsp);
517 	mutex_exit(&ds->ds_sendstream_lock);
518 
519 	dsl_dataset_long_hold(ds, FTAG);
520 	dsl_pool_rele(dp, tag);
521 
522 	if (dump_bytes(dsp, drr, sizeof (dmu_replay_record_t)) != 0) {
523 		err = dsp->dsa_err;
524 		goto out;
525 	}
526 
527 	err = traverse_dataset(ds, fromtxg, TRAVERSE_PRE | TRAVERSE_PREFETCH,
528 	    backup_cb, dsp);
529 
530 	if (dsp->dsa_pending_op != PENDING_NONE)
531 		if (dump_bytes(dsp, drr, sizeof (dmu_replay_record_t)) != 0)
532 			err = SET_ERROR(EINTR);
533 
534 	if (err != 0) {
535 		if (err == EINTR && dsp->dsa_err != 0)
536 			err = dsp->dsa_err;
537 		goto out;
538 	}
539 
540 	bzero(drr, sizeof (dmu_replay_record_t));
541 	drr->drr_type = DRR_END;
542 	drr->drr_u.drr_end.drr_checksum = dsp->dsa_zc;
543 	drr->drr_u.drr_end.drr_toguid = dsp->dsa_toguid;
544 
545 	if (dump_bytes(dsp, drr, sizeof (dmu_replay_record_t)) != 0) {
546 		err = dsp->dsa_err;
547 		goto out;
548 	}
549 
550 out:
551 	mutex_enter(&ds->ds_sendstream_lock);
552 	list_remove(&ds->ds_sendstreams, dsp);
553 	mutex_exit(&ds->ds_sendstream_lock);
554 
555 	kmem_free(drr, sizeof (dmu_replay_record_t));
556 	kmem_free(dsp, sizeof (dmu_sendarg_t));
557 
558 	dsl_dataset_long_rele(ds, FTAG);
559 
560 	return (err);
561 }
562 
563 int
564 dmu_send_obj(const char *pool, uint64_t tosnap, uint64_t fromsnap,
565     int outfd, vnode_t *vp, offset_t *off)
566 {
567 	dsl_pool_t *dp;
568 	dsl_dataset_t *ds;
569 	dsl_dataset_t *fromds = NULL;
570 	int err;
571 
572 	err = dsl_pool_hold(pool, FTAG, &dp);
573 	if (err != 0)
574 		return (err);
575 
576 	err = dsl_dataset_hold_obj(dp, tosnap, FTAG, &ds);
577 	if (err != 0) {
578 		dsl_pool_rele(dp, FTAG);
579 		return (err);
580 	}
581 
582 	if (fromsnap != 0) {
583 		zfs_bookmark_phys_t zb;
584 		boolean_t is_clone;
585 
586 		err = dsl_dataset_hold_obj(dp, fromsnap, FTAG, &fromds);
587 		if (err != 0) {
588 			dsl_dataset_rele(ds, FTAG);
589 			dsl_pool_rele(dp, FTAG);
590 			return (err);
591 		}
592 		if (!dsl_dataset_is_before(ds, fromds, 0))
593 			err = SET_ERROR(EXDEV);
594 		zb.zbm_creation_time = fromds->ds_phys->ds_creation_time;
595 		zb.zbm_creation_txg = fromds->ds_phys->ds_creation_txg;
596 		zb.zbm_guid = fromds->ds_phys->ds_guid;
597 		is_clone = (fromds->ds_dir != ds->ds_dir);
598 		dsl_dataset_rele(fromds, FTAG);
599 		err = dmu_send_impl(FTAG, dp, ds, &zb, is_clone,
600 		    outfd, vp, off);
601 	} else {
602 		err = dmu_send_impl(FTAG, dp, ds, NULL, B_FALSE,
603 		    outfd, vp, off);
604 	}
605 	dsl_dataset_rele(ds, FTAG);
606 	return (err);
607 }
608 
609 int
610 dmu_send(const char *tosnap, const char *fromsnap,
611     int outfd, vnode_t *vp, offset_t *off)
612 {
613 	dsl_pool_t *dp;
614 	dsl_dataset_t *ds;
615 	int err;
616 	boolean_t owned = B_FALSE;
617 
618 	if (fromsnap != NULL && strpbrk(fromsnap, "@#") == NULL)
619 		return (SET_ERROR(EINVAL));
620 
621 	err = dsl_pool_hold(tosnap, FTAG, &dp);
622 	if (err != 0)
623 		return (err);
624 
625 	if (strchr(tosnap, '@') == NULL && spa_writeable(dp->dp_spa)) {
626 		/*
627 		 * We are sending a filesystem or volume.  Ensure
628 		 * that it doesn't change by owning the dataset.
629 		 */
630 		err = dsl_dataset_own(dp, tosnap, FTAG, &ds);
631 		owned = B_TRUE;
632 	} else {
633 		err = dsl_dataset_hold(dp, tosnap, FTAG, &ds);
634 	}
635 	if (err != 0) {
636 		dsl_pool_rele(dp, FTAG);
637 		return (err);
638 	}
639 
640 	if (fromsnap != NULL) {
641 		zfs_bookmark_phys_t zb;
642 		boolean_t is_clone = B_FALSE;
643 		int fsnamelen = strchr(tosnap, '@') - tosnap;
644 
645 		/*
646 		 * If the fromsnap is in a different filesystem, then
647 		 * mark the send stream as a clone.
648 		 */
649 		if (strncmp(tosnap, fromsnap, fsnamelen) != 0 ||
650 		    (fromsnap[fsnamelen] != '@' &&
651 		    fromsnap[fsnamelen] != '#')) {
652 			is_clone = B_TRUE;
653 		}
654 
655 		if (strchr(fromsnap, '@')) {
656 			dsl_dataset_t *fromds;
657 			err = dsl_dataset_hold(dp, fromsnap, FTAG, &fromds);
658 			if (err == 0) {
659 				if (!dsl_dataset_is_before(ds, fromds, 0))
660 					err = SET_ERROR(EXDEV);
661 				zb.zbm_creation_time =
662 				    fromds->ds_phys->ds_creation_time;
663 				zb.zbm_creation_txg =
664 				    fromds->ds_phys->ds_creation_txg;
665 				zb.zbm_guid = fromds->ds_phys->ds_guid;
666 				is_clone = (ds->ds_dir != fromds->ds_dir);
667 				dsl_dataset_rele(fromds, FTAG);
668 			}
669 		} else {
670 			err = dsl_bookmark_lookup(dp, fromsnap, ds, &zb);
671 		}
672 		if (err != 0) {
673 			dsl_dataset_rele(ds, FTAG);
674 			dsl_pool_rele(dp, FTAG);
675 			return (err);
676 		}
677 		err = dmu_send_impl(FTAG, dp, ds, &zb, is_clone,
678 		    outfd, vp, off);
679 	} else {
680 		err = dmu_send_impl(FTAG, dp, ds, NULL, B_FALSE,
681 		    outfd, vp, off);
682 	}
683 	if (owned)
684 		dsl_dataset_disown(ds, FTAG);
685 	else
686 		dsl_dataset_rele(ds, FTAG);
687 	return (err);
688 }
689 
690 int
691 dmu_send_estimate(dsl_dataset_t *ds, dsl_dataset_t *fromds, uint64_t *sizep)
692 {
693 	dsl_pool_t *dp = ds->ds_dir->dd_pool;
694 	int err;
695 	uint64_t size;
696 
697 	ASSERT(dsl_pool_config_held(dp));
698 
699 	/* tosnap must be a snapshot */
700 	if (!dsl_dataset_is_snapshot(ds))
701 		return (SET_ERROR(EINVAL));
702 
703 	/*
704 	 * fromsnap must be an earlier snapshot from the same fs as tosnap,
705 	 * or the origin's fs.
706 	 */
707 	if (fromds != NULL && !dsl_dataset_is_before(ds, fromds, 0))
708 		return (SET_ERROR(EXDEV));
709 
710 	/* Get uncompressed size estimate of changed data. */
711 	if (fromds == NULL) {
712 		size = ds->ds_phys->ds_uncompressed_bytes;
713 	} else {
714 		uint64_t used, comp;
715 		err = dsl_dataset_space_written(fromds, ds,
716 		    &used, &comp, &size);
717 		if (err != 0)
718 			return (err);
719 	}
720 
721 	/*
722 	 * Assume that space (both on-disk and in-stream) is dominated by
723 	 * data.  We will adjust for indirect blocks and the copies property,
724 	 * but ignore per-object space used (eg, dnodes and DRR_OBJECT records).
725 	 */
726 
727 	/*
728 	 * Subtract out approximate space used by indirect blocks.
729 	 * Assume most space is used by data blocks (non-indirect, non-dnode).
730 	 * Assume all blocks are recordsize.  Assume ditto blocks and
731 	 * internal fragmentation counter out compression.
732 	 *
733 	 * Therefore, space used by indirect blocks is sizeof(blkptr_t) per
734 	 * block, which we observe in practice.
735 	 */
736 	uint64_t recordsize;
737 	err = dsl_prop_get_int_ds(ds, "recordsize", &recordsize);
738 	if (err != 0)
739 		return (err);
740 	size -= size / recordsize * sizeof (blkptr_t);
741 
742 	/* Add in the space for the record associated with each block. */
743 	size += size / recordsize * sizeof (dmu_replay_record_t);
744 
745 	*sizep = size;
746 
747 	return (0);
748 }
749 
750 typedef struct dmu_recv_begin_arg {
751 	const char *drba_origin;
752 	dmu_recv_cookie_t *drba_cookie;
753 	cred_t *drba_cred;
754 	uint64_t drba_snapobj;
755 } dmu_recv_begin_arg_t;
756 
757 static int
758 recv_begin_check_existing_impl(dmu_recv_begin_arg_t *drba, dsl_dataset_t *ds,
759     uint64_t fromguid)
760 {
761 	uint64_t val;
762 	int error;
763 	dsl_pool_t *dp = ds->ds_dir->dd_pool;
764 
765 	/* temporary clone name must not exist */
766 	error = zap_lookup(dp->dp_meta_objset,
767 	    ds->ds_dir->dd_phys->dd_child_dir_zapobj, recv_clone_name,
768 	    8, 1, &val);
769 	if (error != ENOENT)
770 		return (error == 0 ? EBUSY : error);
771 
772 	/* new snapshot name must not exist */
773 	error = zap_lookup(dp->dp_meta_objset,
774 	    ds->ds_phys->ds_snapnames_zapobj, drba->drba_cookie->drc_tosnap,
775 	    8, 1, &val);
776 	if (error != ENOENT)
777 		return (error == 0 ? EEXIST : error);
778 
779 	if (fromguid != 0) {
780 		dsl_dataset_t *snap;
781 		uint64_t obj = ds->ds_phys->ds_prev_snap_obj;
782 
783 		/* Find snapshot in this dir that matches fromguid. */
784 		while (obj != 0) {
785 			error = dsl_dataset_hold_obj(dp, obj, FTAG,
786 			    &snap);
787 			if (error != 0)
788 				return (SET_ERROR(ENODEV));
789 			if (snap->ds_dir != ds->ds_dir) {
790 				dsl_dataset_rele(snap, FTAG);
791 				return (SET_ERROR(ENODEV));
792 			}
793 			if (snap->ds_phys->ds_guid == fromguid)
794 				break;
795 			obj = snap->ds_phys->ds_prev_snap_obj;
796 			dsl_dataset_rele(snap, FTAG);
797 		}
798 		if (obj == 0)
799 			return (SET_ERROR(ENODEV));
800 
801 		if (drba->drba_cookie->drc_force) {
802 			drba->drba_snapobj = obj;
803 		} else {
804 			/*
805 			 * If we are not forcing, there must be no
806 			 * changes since fromsnap.
807 			 */
808 			if (dsl_dataset_modified_since_snap(ds, snap)) {
809 				dsl_dataset_rele(snap, FTAG);
810 				return (SET_ERROR(ETXTBSY));
811 			}
812 			drba->drba_snapobj = ds->ds_prev->ds_object;
813 		}
814 
815 		dsl_dataset_rele(snap, FTAG);
816 	} else {
817 		/* if full, most recent snapshot must be $ORIGIN */
818 		if (ds->ds_phys->ds_prev_snap_txg >= TXG_INITIAL)
819 			return (SET_ERROR(ENODEV));
820 		drba->drba_snapobj = ds->ds_phys->ds_prev_snap_obj;
821 	}
822 
823 	return (0);
824 
825 }
826 
827 static int
828 dmu_recv_begin_check(void *arg, dmu_tx_t *tx)
829 {
830 	dmu_recv_begin_arg_t *drba = arg;
831 	dsl_pool_t *dp = dmu_tx_pool(tx);
832 	struct drr_begin *drrb = drba->drba_cookie->drc_drrb;
833 	uint64_t fromguid = drrb->drr_fromguid;
834 	int flags = drrb->drr_flags;
835 	int error;
836 	dsl_dataset_t *ds;
837 	const char *tofs = drba->drba_cookie->drc_tofs;
838 
839 	/* already checked */
840 	ASSERT3U(drrb->drr_magic, ==, DMU_BACKUP_MAGIC);
841 
842 	if (DMU_GET_STREAM_HDRTYPE(drrb->drr_versioninfo) ==
843 	    DMU_COMPOUNDSTREAM ||
844 	    drrb->drr_type >= DMU_OST_NUMTYPES ||
845 	    ((flags & DRR_FLAG_CLONE) && drba->drba_origin == NULL))
846 		return (SET_ERROR(EINVAL));
847 
848 	/* Verify pool version supports SA if SA_SPILL feature set */
849 	if ((DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo) &
850 	    DMU_BACKUP_FEATURE_SA_SPILL) &&
851 	    spa_version(dp->dp_spa) < SPA_VERSION_SA) {
852 		return (SET_ERROR(ENOTSUP));
853 	}
854 
855 	error = dsl_dataset_hold(dp, tofs, FTAG, &ds);
856 	if (error == 0) {
857 		/* target fs already exists; recv into temp clone */
858 
859 		/* Can't recv a clone into an existing fs */
860 		if (flags & DRR_FLAG_CLONE) {
861 			dsl_dataset_rele(ds, FTAG);
862 			return (SET_ERROR(EINVAL));
863 		}
864 
865 		error = recv_begin_check_existing_impl(drba, ds, fromguid);
866 		dsl_dataset_rele(ds, FTAG);
867 	} else if (error == ENOENT) {
868 		/* target fs does not exist; must be a full backup or clone */
869 		char buf[MAXNAMELEN];
870 
871 		/*
872 		 * If it's a non-clone incremental, we are missing the
873 		 * target fs, so fail the recv.
874 		 */
875 		if (fromguid != 0 && !(flags & DRR_FLAG_CLONE))
876 			return (SET_ERROR(ENOENT));
877 
878 		/* Open the parent of tofs */
879 		ASSERT3U(strlen(tofs), <, MAXNAMELEN);
880 		(void) strlcpy(buf, tofs, strrchr(tofs, '/') - tofs + 1);
881 		error = dsl_dataset_hold(dp, buf, FTAG, &ds);
882 		if (error != 0)
883 			return (error);
884 
885 		if (drba->drba_origin != NULL) {
886 			dsl_dataset_t *origin;
887 			error = dsl_dataset_hold(dp, drba->drba_origin,
888 			    FTAG, &origin);
889 			if (error != 0) {
890 				dsl_dataset_rele(ds, FTAG);
891 				return (error);
892 			}
893 			if (!dsl_dataset_is_snapshot(origin)) {
894 				dsl_dataset_rele(origin, FTAG);
895 				dsl_dataset_rele(ds, FTAG);
896 				return (SET_ERROR(EINVAL));
897 			}
898 			if (origin->ds_phys->ds_guid != fromguid) {
899 				dsl_dataset_rele(origin, FTAG);
900 				dsl_dataset_rele(ds, FTAG);
901 				return (SET_ERROR(ENODEV));
902 			}
903 			dsl_dataset_rele(origin, FTAG);
904 		}
905 		dsl_dataset_rele(ds, FTAG);
906 		error = 0;
907 	}
908 	return (error);
909 }
910 
911 static void
912 dmu_recv_begin_sync(void *arg, dmu_tx_t *tx)
913 {
914 	dmu_recv_begin_arg_t *drba = arg;
915 	dsl_pool_t *dp = dmu_tx_pool(tx);
916 	struct drr_begin *drrb = drba->drba_cookie->drc_drrb;
917 	const char *tofs = drba->drba_cookie->drc_tofs;
918 	dsl_dataset_t *ds, *newds;
919 	uint64_t dsobj;
920 	int error;
921 	uint64_t crflags;
922 
923 	crflags = (drrb->drr_flags & DRR_FLAG_CI_DATA) ?
924 	    DS_FLAG_CI_DATASET : 0;
925 
926 	error = dsl_dataset_hold(dp, tofs, FTAG, &ds);
927 	if (error == 0) {
928 		/* create temporary clone */
929 		dsl_dataset_t *snap = NULL;
930 		if (drba->drba_snapobj != 0) {
931 			VERIFY0(dsl_dataset_hold_obj(dp,
932 			    drba->drba_snapobj, FTAG, &snap));
933 		}
934 		dsobj = dsl_dataset_create_sync(ds->ds_dir, recv_clone_name,
935 		    snap, crflags, drba->drba_cred, tx);
936 		dsl_dataset_rele(snap, FTAG);
937 		dsl_dataset_rele(ds, FTAG);
938 	} else {
939 		dsl_dir_t *dd;
940 		const char *tail;
941 		dsl_dataset_t *origin = NULL;
942 
943 		VERIFY0(dsl_dir_hold(dp, tofs, FTAG, &dd, &tail));
944 
945 		if (drba->drba_origin != NULL) {
946 			VERIFY0(dsl_dataset_hold(dp, drba->drba_origin,
947 			    FTAG, &origin));
948 		}
949 
950 		/* Create new dataset. */
951 		dsobj = dsl_dataset_create_sync(dd,
952 		    strrchr(tofs, '/') + 1,
953 		    origin, crflags, drba->drba_cred, tx);
954 		if (origin != NULL)
955 			dsl_dataset_rele(origin, FTAG);
956 		dsl_dir_rele(dd, FTAG);
957 		drba->drba_cookie->drc_newfs = B_TRUE;
958 	}
959 	VERIFY0(dsl_dataset_own_obj(dp, dsobj, dmu_recv_tag, &newds));
960 
961 	dmu_buf_will_dirty(newds->ds_dbuf, tx);
962 	newds->ds_phys->ds_flags |= DS_FLAG_INCONSISTENT;
963 
964 	/*
965 	 * If we actually created a non-clone, we need to create the
966 	 * objset in our new dataset.
967 	 */
968 	if (BP_IS_HOLE(dsl_dataset_get_blkptr(newds))) {
969 		(void) dmu_objset_create_impl(dp->dp_spa,
970 		    newds, dsl_dataset_get_blkptr(newds), drrb->drr_type, tx);
971 	}
972 
973 	drba->drba_cookie->drc_ds = newds;
974 
975 	spa_history_log_internal_ds(newds, "receive", tx, "");
976 }
977 
978 /*
979  * NB: callers *MUST* call dmu_recv_stream() if dmu_recv_begin()
980  * succeeds; otherwise we will leak the holds on the datasets.
981  */
982 int
983 dmu_recv_begin(char *tofs, char *tosnap, struct drr_begin *drrb,
984     boolean_t force, char *origin, dmu_recv_cookie_t *drc)
985 {
986 	dmu_recv_begin_arg_t drba = { 0 };
987 	dmu_replay_record_t *drr;
988 
989 	bzero(drc, sizeof (dmu_recv_cookie_t));
990 	drc->drc_drrb = drrb;
991 	drc->drc_tosnap = tosnap;
992 	drc->drc_tofs = tofs;
993 	drc->drc_force = force;
994 
995 	if (drrb->drr_magic == BSWAP_64(DMU_BACKUP_MAGIC))
996 		drc->drc_byteswap = B_TRUE;
997 	else if (drrb->drr_magic != DMU_BACKUP_MAGIC)
998 		return (SET_ERROR(EINVAL));
999 
1000 	drr = kmem_zalloc(sizeof (dmu_replay_record_t), KM_SLEEP);
1001 	drr->drr_type = DRR_BEGIN;
1002 	drr->drr_u.drr_begin = *drc->drc_drrb;
1003 	if (drc->drc_byteswap) {
1004 		fletcher_4_incremental_byteswap(drr,
1005 		    sizeof (dmu_replay_record_t), &drc->drc_cksum);
1006 	} else {
1007 		fletcher_4_incremental_native(drr,
1008 		    sizeof (dmu_replay_record_t), &drc->drc_cksum);
1009 	}
1010 	kmem_free(drr, sizeof (dmu_replay_record_t));
1011 
1012 	if (drc->drc_byteswap) {
1013 		drrb->drr_magic = BSWAP_64(drrb->drr_magic);
1014 		drrb->drr_versioninfo = BSWAP_64(drrb->drr_versioninfo);
1015 		drrb->drr_creation_time = BSWAP_64(drrb->drr_creation_time);
1016 		drrb->drr_type = BSWAP_32(drrb->drr_type);
1017 		drrb->drr_toguid = BSWAP_64(drrb->drr_toguid);
1018 		drrb->drr_fromguid = BSWAP_64(drrb->drr_fromguid);
1019 	}
1020 
1021 	drba.drba_origin = origin;
1022 	drba.drba_cookie = drc;
1023 	drba.drba_cred = CRED();
1024 
1025 	return (dsl_sync_task(tofs, dmu_recv_begin_check, dmu_recv_begin_sync,
1026 	    &drba, 5));
1027 }
1028 
1029 struct restorearg {
1030 	int err;
1031 	boolean_t byteswap;
1032 	vnode_t *vp;
1033 	char *buf;
1034 	uint64_t voff;
1035 	int bufsize; /* amount of memory allocated for buf */
1036 	zio_cksum_t cksum;
1037 	avl_tree_t *guid_to_ds_map;
1038 };
1039 
1040 typedef struct guid_map_entry {
1041 	uint64_t	guid;
1042 	dsl_dataset_t	*gme_ds;
1043 	avl_node_t	avlnode;
1044 } guid_map_entry_t;
1045 
1046 static int
1047 guid_compare(const void *arg1, const void *arg2)
1048 {
1049 	const guid_map_entry_t *gmep1 = arg1;
1050 	const guid_map_entry_t *gmep2 = arg2;
1051 
1052 	if (gmep1->guid < gmep2->guid)
1053 		return (-1);
1054 	else if (gmep1->guid > gmep2->guid)
1055 		return (1);
1056 	return (0);
1057 }
1058 
1059 static void
1060 free_guid_map_onexit(void *arg)
1061 {
1062 	avl_tree_t *ca = arg;
1063 	void *cookie = NULL;
1064 	guid_map_entry_t *gmep;
1065 
1066 	while ((gmep = avl_destroy_nodes(ca, &cookie)) != NULL) {
1067 		dsl_dataset_long_rele(gmep->gme_ds, gmep);
1068 		dsl_dataset_rele(gmep->gme_ds, gmep);
1069 		kmem_free(gmep, sizeof (guid_map_entry_t));
1070 	}
1071 	avl_destroy(ca);
1072 	kmem_free(ca, sizeof (avl_tree_t));
1073 }
1074 
1075 static void *
1076 restore_read(struct restorearg *ra, int len)
1077 {
1078 	void *rv;
1079 	int done = 0;
1080 
1081 	/* some things will require 8-byte alignment, so everything must */
1082 	ASSERT0(len % 8);
1083 
1084 	while (done < len) {
1085 		ssize_t resid;
1086 
1087 		ra->err = vn_rdwr(UIO_READ, ra->vp,
1088 		    (caddr_t)ra->buf + done, len - done,
1089 		    ra->voff, UIO_SYSSPACE, FAPPEND,
1090 		    RLIM64_INFINITY, CRED(), &resid);
1091 
1092 		if (resid == len - done)
1093 			ra->err = SET_ERROR(EINVAL);
1094 		ra->voff += len - done - resid;
1095 		done = len - resid;
1096 		if (ra->err != 0)
1097 			return (NULL);
1098 	}
1099 
1100 	ASSERT3U(done, ==, len);
1101 	rv = ra->buf;
1102 	if (ra->byteswap)
1103 		fletcher_4_incremental_byteswap(rv, len, &ra->cksum);
1104 	else
1105 		fletcher_4_incremental_native(rv, len, &ra->cksum);
1106 	return (rv);
1107 }
1108 
1109 static void
1110 backup_byteswap(dmu_replay_record_t *drr)
1111 {
1112 #define	DO64(X) (drr->drr_u.X = BSWAP_64(drr->drr_u.X))
1113 #define	DO32(X) (drr->drr_u.X = BSWAP_32(drr->drr_u.X))
1114 	drr->drr_type = BSWAP_32(drr->drr_type);
1115 	drr->drr_payloadlen = BSWAP_32(drr->drr_payloadlen);
1116 	switch (drr->drr_type) {
1117 	case DRR_BEGIN:
1118 		DO64(drr_begin.drr_magic);
1119 		DO64(drr_begin.drr_versioninfo);
1120 		DO64(drr_begin.drr_creation_time);
1121 		DO32(drr_begin.drr_type);
1122 		DO32(drr_begin.drr_flags);
1123 		DO64(drr_begin.drr_toguid);
1124 		DO64(drr_begin.drr_fromguid);
1125 		break;
1126 	case DRR_OBJECT:
1127 		DO64(drr_object.drr_object);
1128 		/* DO64(drr_object.drr_allocation_txg); */
1129 		DO32(drr_object.drr_type);
1130 		DO32(drr_object.drr_bonustype);
1131 		DO32(drr_object.drr_blksz);
1132 		DO32(drr_object.drr_bonuslen);
1133 		DO64(drr_object.drr_toguid);
1134 		break;
1135 	case DRR_FREEOBJECTS:
1136 		DO64(drr_freeobjects.drr_firstobj);
1137 		DO64(drr_freeobjects.drr_numobjs);
1138 		DO64(drr_freeobjects.drr_toguid);
1139 		break;
1140 	case DRR_WRITE:
1141 		DO64(drr_write.drr_object);
1142 		DO32(drr_write.drr_type);
1143 		DO64(drr_write.drr_offset);
1144 		DO64(drr_write.drr_length);
1145 		DO64(drr_write.drr_toguid);
1146 		DO64(drr_write.drr_key.ddk_cksum.zc_word[0]);
1147 		DO64(drr_write.drr_key.ddk_cksum.zc_word[1]);
1148 		DO64(drr_write.drr_key.ddk_cksum.zc_word[2]);
1149 		DO64(drr_write.drr_key.ddk_cksum.zc_word[3]);
1150 		DO64(drr_write.drr_key.ddk_prop);
1151 		break;
1152 	case DRR_WRITE_BYREF:
1153 		DO64(drr_write_byref.drr_object);
1154 		DO64(drr_write_byref.drr_offset);
1155 		DO64(drr_write_byref.drr_length);
1156 		DO64(drr_write_byref.drr_toguid);
1157 		DO64(drr_write_byref.drr_refguid);
1158 		DO64(drr_write_byref.drr_refobject);
1159 		DO64(drr_write_byref.drr_refoffset);
1160 		DO64(drr_write_byref.drr_key.ddk_cksum.zc_word[0]);
1161 		DO64(drr_write_byref.drr_key.ddk_cksum.zc_word[1]);
1162 		DO64(drr_write_byref.drr_key.ddk_cksum.zc_word[2]);
1163 		DO64(drr_write_byref.drr_key.ddk_cksum.zc_word[3]);
1164 		DO64(drr_write_byref.drr_key.ddk_prop);
1165 		break;
1166 	case DRR_FREE:
1167 		DO64(drr_free.drr_object);
1168 		DO64(drr_free.drr_offset);
1169 		DO64(drr_free.drr_length);
1170 		DO64(drr_free.drr_toguid);
1171 		break;
1172 	case DRR_SPILL:
1173 		DO64(drr_spill.drr_object);
1174 		DO64(drr_spill.drr_length);
1175 		DO64(drr_spill.drr_toguid);
1176 		break;
1177 	case DRR_END:
1178 		DO64(drr_end.drr_checksum.zc_word[0]);
1179 		DO64(drr_end.drr_checksum.zc_word[1]);
1180 		DO64(drr_end.drr_checksum.zc_word[2]);
1181 		DO64(drr_end.drr_checksum.zc_word[3]);
1182 		DO64(drr_end.drr_toguid);
1183 		break;
1184 	}
1185 #undef DO64
1186 #undef DO32
1187 }
1188 
1189 static int
1190 restore_object(struct restorearg *ra, objset_t *os, struct drr_object *drro)
1191 {
1192 	int err;
1193 	dmu_tx_t *tx;
1194 	void *data = NULL;
1195 
1196 	if (drro->drr_type == DMU_OT_NONE ||
1197 	    !DMU_OT_IS_VALID(drro->drr_type) ||
1198 	    !DMU_OT_IS_VALID(drro->drr_bonustype) ||
1199 	    drro->drr_checksumtype >= ZIO_CHECKSUM_FUNCTIONS ||
1200 	    drro->drr_compress >= ZIO_COMPRESS_FUNCTIONS ||
1201 	    P2PHASE(drro->drr_blksz, SPA_MINBLOCKSIZE) ||
1202 	    drro->drr_blksz < SPA_MINBLOCKSIZE ||
1203 	    drro->drr_blksz > SPA_MAXBLOCKSIZE ||
1204 	    drro->drr_bonuslen > DN_MAX_BONUSLEN) {
1205 		return (SET_ERROR(EINVAL));
1206 	}
1207 
1208 	err = dmu_object_info(os, drro->drr_object, NULL);
1209 
1210 	if (err != 0 && err != ENOENT)
1211 		return (SET_ERROR(EINVAL));
1212 
1213 	if (drro->drr_bonuslen) {
1214 		data = restore_read(ra, P2ROUNDUP(drro->drr_bonuslen, 8));
1215 		if (ra->err != 0)
1216 			return (ra->err);
1217 	}
1218 
1219 	if (err == ENOENT) {
1220 		/* currently free, want to be allocated */
1221 		tx = dmu_tx_create(os);
1222 		dmu_tx_hold_bonus(tx, DMU_NEW_OBJECT);
1223 		err = dmu_tx_assign(tx, TXG_WAIT);
1224 		if (err != 0) {
1225 			dmu_tx_abort(tx);
1226 			return (err);
1227 		}
1228 		err = dmu_object_claim(os, drro->drr_object,
1229 		    drro->drr_type, drro->drr_blksz,
1230 		    drro->drr_bonustype, drro->drr_bonuslen, tx);
1231 		dmu_tx_commit(tx);
1232 	} else {
1233 		/* currently allocated, want to be allocated */
1234 		err = dmu_object_reclaim(os, drro->drr_object,
1235 		    drro->drr_type, drro->drr_blksz,
1236 		    drro->drr_bonustype, drro->drr_bonuslen);
1237 	}
1238 	if (err != 0) {
1239 		return (SET_ERROR(EINVAL));
1240 	}
1241 
1242 	tx = dmu_tx_create(os);
1243 	dmu_tx_hold_bonus(tx, drro->drr_object);
1244 	err = dmu_tx_assign(tx, TXG_WAIT);
1245 	if (err != 0) {
1246 		dmu_tx_abort(tx);
1247 		return (err);
1248 	}
1249 
1250 	dmu_object_set_checksum(os, drro->drr_object, drro->drr_checksumtype,
1251 	    tx);
1252 	dmu_object_set_compress(os, drro->drr_object, drro->drr_compress, tx);
1253 
1254 	if (data != NULL) {
1255 		dmu_buf_t *db;
1256 
1257 		VERIFY(0 == dmu_bonus_hold(os, drro->drr_object, FTAG, &db));
1258 		dmu_buf_will_dirty(db, tx);
1259 
1260 		ASSERT3U(db->db_size, >=, drro->drr_bonuslen);
1261 		bcopy(data, db->db_data, drro->drr_bonuslen);
1262 		if (ra->byteswap) {
1263 			dmu_object_byteswap_t byteswap =
1264 			    DMU_OT_BYTESWAP(drro->drr_bonustype);
1265 			dmu_ot_byteswap[byteswap].ob_func(db->db_data,
1266 			    drro->drr_bonuslen);
1267 		}
1268 		dmu_buf_rele(db, FTAG);
1269 	}
1270 	dmu_tx_commit(tx);
1271 	return (0);
1272 }
1273 
1274 /* ARGSUSED */
1275 static int
1276 restore_freeobjects(struct restorearg *ra, objset_t *os,
1277     struct drr_freeobjects *drrfo)
1278 {
1279 	uint64_t obj;
1280 
1281 	if (drrfo->drr_firstobj + drrfo->drr_numobjs < drrfo->drr_firstobj)
1282 		return (SET_ERROR(EINVAL));
1283 
1284 	for (obj = drrfo->drr_firstobj;
1285 	    obj < drrfo->drr_firstobj + drrfo->drr_numobjs;
1286 	    (void) dmu_object_next(os, &obj, FALSE, 0)) {
1287 		int err;
1288 
1289 		if (dmu_object_info(os, obj, NULL) != 0)
1290 			continue;
1291 
1292 		err = dmu_free_long_object(os, obj);
1293 		if (err != 0)
1294 			return (err);
1295 	}
1296 	return (0);
1297 }
1298 
1299 static int
1300 restore_write(struct restorearg *ra, objset_t *os,
1301     struct drr_write *drrw)
1302 {
1303 	dmu_tx_t *tx;
1304 	void *data;
1305 	int err;
1306 
1307 	if (drrw->drr_offset + drrw->drr_length < drrw->drr_offset ||
1308 	    !DMU_OT_IS_VALID(drrw->drr_type))
1309 		return (SET_ERROR(EINVAL));
1310 
1311 	data = restore_read(ra, drrw->drr_length);
1312 	if (data == NULL)
1313 		return (ra->err);
1314 
1315 	if (dmu_object_info(os, drrw->drr_object, NULL) != 0)
1316 		return (SET_ERROR(EINVAL));
1317 
1318 	tx = dmu_tx_create(os);
1319 
1320 	dmu_tx_hold_write(tx, drrw->drr_object,
1321 	    drrw->drr_offset, drrw->drr_length);
1322 	err = dmu_tx_assign(tx, TXG_WAIT);
1323 	if (err != 0) {
1324 		dmu_tx_abort(tx);
1325 		return (err);
1326 	}
1327 	if (ra->byteswap) {
1328 		dmu_object_byteswap_t byteswap =
1329 		    DMU_OT_BYTESWAP(drrw->drr_type);
1330 		dmu_ot_byteswap[byteswap].ob_func(data, drrw->drr_length);
1331 	}
1332 	dmu_write(os, drrw->drr_object,
1333 	    drrw->drr_offset, drrw->drr_length, data, tx);
1334 	dmu_tx_commit(tx);
1335 	return (0);
1336 }
1337 
1338 /*
1339  * Handle a DRR_WRITE_BYREF record.  This record is used in dedup'ed
1340  * streams to refer to a copy of the data that is already on the
1341  * system because it came in earlier in the stream.  This function
1342  * finds the earlier copy of the data, and uses that copy instead of
1343  * data from the stream to fulfill this write.
1344  */
1345 static int
1346 restore_write_byref(struct restorearg *ra, objset_t *os,
1347     struct drr_write_byref *drrwbr)
1348 {
1349 	dmu_tx_t *tx;
1350 	int err;
1351 	guid_map_entry_t gmesrch;
1352 	guid_map_entry_t *gmep;
1353 	avl_index_t	where;
1354 	objset_t *ref_os = NULL;
1355 	dmu_buf_t *dbp;
1356 
1357 	if (drrwbr->drr_offset + drrwbr->drr_length < drrwbr->drr_offset)
1358 		return (SET_ERROR(EINVAL));
1359 
1360 	/*
1361 	 * If the GUID of the referenced dataset is different from the
1362 	 * GUID of the target dataset, find the referenced dataset.
1363 	 */
1364 	if (drrwbr->drr_toguid != drrwbr->drr_refguid) {
1365 		gmesrch.guid = drrwbr->drr_refguid;
1366 		if ((gmep = avl_find(ra->guid_to_ds_map, &gmesrch,
1367 		    &where)) == NULL) {
1368 			return (SET_ERROR(EINVAL));
1369 		}
1370 		if (dmu_objset_from_ds(gmep->gme_ds, &ref_os))
1371 			return (SET_ERROR(EINVAL));
1372 	} else {
1373 		ref_os = os;
1374 	}
1375 
1376 	if (err = dmu_buf_hold(ref_os, drrwbr->drr_refobject,
1377 	    drrwbr->drr_refoffset, FTAG, &dbp, DMU_READ_PREFETCH))
1378 		return (err);
1379 
1380 	tx = dmu_tx_create(os);
1381 
1382 	dmu_tx_hold_write(tx, drrwbr->drr_object,
1383 	    drrwbr->drr_offset, drrwbr->drr_length);
1384 	err = dmu_tx_assign(tx, TXG_WAIT);
1385 	if (err != 0) {
1386 		dmu_tx_abort(tx);
1387 		return (err);
1388 	}
1389 	dmu_write(os, drrwbr->drr_object,
1390 	    drrwbr->drr_offset, drrwbr->drr_length, dbp->db_data, tx);
1391 	dmu_buf_rele(dbp, FTAG);
1392 	dmu_tx_commit(tx);
1393 	return (0);
1394 }
1395 
1396 static int
1397 restore_spill(struct restorearg *ra, objset_t *os, struct drr_spill *drrs)
1398 {
1399 	dmu_tx_t *tx;
1400 	void *data;
1401 	dmu_buf_t *db, *db_spill;
1402 	int err;
1403 
1404 	if (drrs->drr_length < SPA_MINBLOCKSIZE ||
1405 	    drrs->drr_length > SPA_MAXBLOCKSIZE)
1406 		return (SET_ERROR(EINVAL));
1407 
1408 	data = restore_read(ra, drrs->drr_length);
1409 	if (data == NULL)
1410 		return (ra->err);
1411 
1412 	if (dmu_object_info(os, drrs->drr_object, NULL) != 0)
1413 		return (SET_ERROR(EINVAL));
1414 
1415 	VERIFY(0 == dmu_bonus_hold(os, drrs->drr_object, FTAG, &db));
1416 	if ((err = dmu_spill_hold_by_bonus(db, FTAG, &db_spill)) != 0) {
1417 		dmu_buf_rele(db, FTAG);
1418 		return (err);
1419 	}
1420 
1421 	tx = dmu_tx_create(os);
1422 
1423 	dmu_tx_hold_spill(tx, db->db_object);
1424 
1425 	err = dmu_tx_assign(tx, TXG_WAIT);
1426 	if (err != 0) {
1427 		dmu_buf_rele(db, FTAG);
1428 		dmu_buf_rele(db_spill, FTAG);
1429 		dmu_tx_abort(tx);
1430 		return (err);
1431 	}
1432 	dmu_buf_will_dirty(db_spill, tx);
1433 
1434 	if (db_spill->db_size < drrs->drr_length)
1435 		VERIFY(0 == dbuf_spill_set_blksz(db_spill,
1436 		    drrs->drr_length, tx));
1437 	bcopy(data, db_spill->db_data, drrs->drr_length);
1438 
1439 	dmu_buf_rele(db, FTAG);
1440 	dmu_buf_rele(db_spill, FTAG);
1441 
1442 	dmu_tx_commit(tx);
1443 	return (0);
1444 }
1445 
1446 /* ARGSUSED */
1447 static int
1448 restore_free(struct restorearg *ra, objset_t *os,
1449     struct drr_free *drrf)
1450 {
1451 	int err;
1452 
1453 	if (drrf->drr_length != -1ULL &&
1454 	    drrf->drr_offset + drrf->drr_length < drrf->drr_offset)
1455 		return (SET_ERROR(EINVAL));
1456 
1457 	if (dmu_object_info(os, drrf->drr_object, NULL) != 0)
1458 		return (SET_ERROR(EINVAL));
1459 
1460 	err = dmu_free_long_range(os, drrf->drr_object,
1461 	    drrf->drr_offset, drrf->drr_length);
1462 	return (err);
1463 }
1464 
1465 /* used to destroy the drc_ds on error */
1466 static void
1467 dmu_recv_cleanup_ds(dmu_recv_cookie_t *drc)
1468 {
1469 	char name[MAXNAMELEN];
1470 	dsl_dataset_name(drc->drc_ds, name);
1471 	dsl_dataset_disown(drc->drc_ds, dmu_recv_tag);
1472 	(void) dsl_destroy_head(name);
1473 }
1474 
1475 /*
1476  * NB: callers *must* call dmu_recv_end() if this succeeds.
1477  */
1478 int
1479 dmu_recv_stream(dmu_recv_cookie_t *drc, vnode_t *vp, offset_t *voffp,
1480     int cleanup_fd, uint64_t *action_handlep)
1481 {
1482 	struct restorearg ra = { 0 };
1483 	dmu_replay_record_t *drr;
1484 	objset_t *os;
1485 	zio_cksum_t pcksum;
1486 	int featureflags;
1487 
1488 	ra.byteswap = drc->drc_byteswap;
1489 	ra.cksum = drc->drc_cksum;
1490 	ra.vp = vp;
1491 	ra.voff = *voffp;
1492 	ra.bufsize = 1<<20;
1493 	ra.buf = kmem_alloc(ra.bufsize, KM_SLEEP);
1494 
1495 	/* these were verified in dmu_recv_begin */
1496 	ASSERT3U(DMU_GET_STREAM_HDRTYPE(drc->drc_drrb->drr_versioninfo), ==,
1497 	    DMU_SUBSTREAM);
1498 	ASSERT3U(drc->drc_drrb->drr_type, <, DMU_OST_NUMTYPES);
1499 
1500 	/*
1501 	 * Open the objset we are modifying.
1502 	 */
1503 	VERIFY0(dmu_objset_from_ds(drc->drc_ds, &os));
1504 
1505 	ASSERT(drc->drc_ds->ds_phys->ds_flags & DS_FLAG_INCONSISTENT);
1506 
1507 	featureflags = DMU_GET_FEATUREFLAGS(drc->drc_drrb->drr_versioninfo);
1508 
1509 	/* if this stream is dedup'ed, set up the avl tree for guid mapping */
1510 	if (featureflags & DMU_BACKUP_FEATURE_DEDUP) {
1511 		minor_t minor;
1512 
1513 		if (cleanup_fd == -1) {
1514 			ra.err = SET_ERROR(EBADF);
1515 			goto out;
1516 		}
1517 		ra.err = zfs_onexit_fd_hold(cleanup_fd, &minor);
1518 		if (ra.err != 0) {
1519 			cleanup_fd = -1;
1520 			goto out;
1521 		}
1522 
1523 		if (*action_handlep == 0) {
1524 			ra.guid_to_ds_map =
1525 			    kmem_alloc(sizeof (avl_tree_t), KM_SLEEP);
1526 			avl_create(ra.guid_to_ds_map, guid_compare,
1527 			    sizeof (guid_map_entry_t),
1528 			    offsetof(guid_map_entry_t, avlnode));
1529 			ra.err = zfs_onexit_add_cb(minor,
1530 			    free_guid_map_onexit, ra.guid_to_ds_map,
1531 			    action_handlep);
1532 			if (ra.err != 0)
1533 				goto out;
1534 		} else {
1535 			ra.err = zfs_onexit_cb_data(minor, *action_handlep,
1536 			    (void **)&ra.guid_to_ds_map);
1537 			if (ra.err != 0)
1538 				goto out;
1539 		}
1540 
1541 		drc->drc_guid_to_ds_map = ra.guid_to_ds_map;
1542 	}
1543 
1544 	/*
1545 	 * Read records and process them.
1546 	 */
1547 	pcksum = ra.cksum;
1548 	while (ra.err == 0 &&
1549 	    NULL != (drr = restore_read(&ra, sizeof (*drr)))) {
1550 		if (issig(JUSTLOOKING) && issig(FORREAL)) {
1551 			ra.err = SET_ERROR(EINTR);
1552 			goto out;
1553 		}
1554 
1555 		if (ra.byteswap)
1556 			backup_byteswap(drr);
1557 
1558 		switch (drr->drr_type) {
1559 		case DRR_OBJECT:
1560 		{
1561 			/*
1562 			 * We need to make a copy of the record header,
1563 			 * because restore_{object,write} may need to
1564 			 * restore_read(), which will invalidate drr.
1565 			 */
1566 			struct drr_object drro = drr->drr_u.drr_object;
1567 			ra.err = restore_object(&ra, os, &drro);
1568 			break;
1569 		}
1570 		case DRR_FREEOBJECTS:
1571 		{
1572 			struct drr_freeobjects drrfo =
1573 			    drr->drr_u.drr_freeobjects;
1574 			ra.err = restore_freeobjects(&ra, os, &drrfo);
1575 			break;
1576 		}
1577 		case DRR_WRITE:
1578 		{
1579 			struct drr_write drrw = drr->drr_u.drr_write;
1580 			ra.err = restore_write(&ra, os, &drrw);
1581 			break;
1582 		}
1583 		case DRR_WRITE_BYREF:
1584 		{
1585 			struct drr_write_byref drrwbr =
1586 			    drr->drr_u.drr_write_byref;
1587 			ra.err = restore_write_byref(&ra, os, &drrwbr);
1588 			break;
1589 		}
1590 		case DRR_FREE:
1591 		{
1592 			struct drr_free drrf = drr->drr_u.drr_free;
1593 			ra.err = restore_free(&ra, os, &drrf);
1594 			break;
1595 		}
1596 		case DRR_END:
1597 		{
1598 			struct drr_end drre = drr->drr_u.drr_end;
1599 			/*
1600 			 * We compare against the *previous* checksum
1601 			 * value, because the stored checksum is of
1602 			 * everything before the DRR_END record.
1603 			 */
1604 			if (!ZIO_CHECKSUM_EQUAL(drre.drr_checksum, pcksum))
1605 				ra.err = SET_ERROR(ECKSUM);
1606 			goto out;
1607 		}
1608 		case DRR_SPILL:
1609 		{
1610 			struct drr_spill drrs = drr->drr_u.drr_spill;
1611 			ra.err = restore_spill(&ra, os, &drrs);
1612 			break;
1613 		}
1614 		default:
1615 			ra.err = SET_ERROR(EINVAL);
1616 			goto out;
1617 		}
1618 		pcksum = ra.cksum;
1619 	}
1620 	ASSERT(ra.err != 0);
1621 
1622 out:
1623 	if ((featureflags & DMU_BACKUP_FEATURE_DEDUP) && (cleanup_fd != -1))
1624 		zfs_onexit_fd_rele(cleanup_fd);
1625 
1626 	if (ra.err != 0) {
1627 		/*
1628 		 * destroy what we created, so we don't leave it in the
1629 		 * inconsistent restoring state.
1630 		 */
1631 		dmu_recv_cleanup_ds(drc);
1632 	}
1633 
1634 	kmem_free(ra.buf, ra.bufsize);
1635 	*voffp = ra.voff;
1636 	return (ra.err);
1637 }
1638 
1639 static int
1640 dmu_recv_end_check(void *arg, dmu_tx_t *tx)
1641 {
1642 	dmu_recv_cookie_t *drc = arg;
1643 	dsl_pool_t *dp = dmu_tx_pool(tx);
1644 	int error;
1645 
1646 	ASSERT3P(drc->drc_ds->ds_owner, ==, dmu_recv_tag);
1647 
1648 	if (!drc->drc_newfs) {
1649 		dsl_dataset_t *origin_head;
1650 
1651 		error = dsl_dataset_hold(dp, drc->drc_tofs, FTAG, &origin_head);
1652 		if (error != 0)
1653 			return (error);
1654 		if (drc->drc_force) {
1655 			/*
1656 			 * We will destroy any snapshots in tofs (i.e. before
1657 			 * origin_head) that are after the origin (which is
1658 			 * the snap before drc_ds, because drc_ds can not
1659 			 * have any snaps of its own).
1660 			 */
1661 			uint64_t obj = origin_head->ds_phys->ds_prev_snap_obj;
1662 			while (obj != drc->drc_ds->ds_phys->ds_prev_snap_obj) {
1663 				dsl_dataset_t *snap;
1664 				error = dsl_dataset_hold_obj(dp, obj, FTAG,
1665 				    &snap);
1666 				if (error != 0)
1667 					return (error);
1668 				if (snap->ds_dir != origin_head->ds_dir)
1669 					error = SET_ERROR(EINVAL);
1670 				if (error == 0)  {
1671 					error = dsl_destroy_snapshot_check_impl(
1672 					    snap, B_FALSE);
1673 				}
1674 				obj = snap->ds_phys->ds_prev_snap_obj;
1675 				dsl_dataset_rele(snap, FTAG);
1676 				if (error != 0)
1677 					return (error);
1678 			}
1679 		}
1680 		error = dsl_dataset_clone_swap_check_impl(drc->drc_ds,
1681 		    origin_head, drc->drc_force, drc->drc_owner, tx);
1682 		if (error != 0) {
1683 			dsl_dataset_rele(origin_head, FTAG);
1684 			return (error);
1685 		}
1686 		error = dsl_dataset_snapshot_check_impl(origin_head,
1687 		    drc->drc_tosnap, tx, B_TRUE);
1688 		dsl_dataset_rele(origin_head, FTAG);
1689 		if (error != 0)
1690 			return (error);
1691 
1692 		error = dsl_destroy_head_check_impl(drc->drc_ds, 1);
1693 	} else {
1694 		error = dsl_dataset_snapshot_check_impl(drc->drc_ds,
1695 		    drc->drc_tosnap, tx, B_TRUE);
1696 	}
1697 	return (error);
1698 }
1699 
1700 static void
1701 dmu_recv_end_sync(void *arg, dmu_tx_t *tx)
1702 {
1703 	dmu_recv_cookie_t *drc = arg;
1704 	dsl_pool_t *dp = dmu_tx_pool(tx);
1705 
1706 	spa_history_log_internal_ds(drc->drc_ds, "finish receiving",
1707 	    tx, "snap=%s", drc->drc_tosnap);
1708 
1709 	if (!drc->drc_newfs) {
1710 		dsl_dataset_t *origin_head;
1711 
1712 		VERIFY0(dsl_dataset_hold(dp, drc->drc_tofs, FTAG,
1713 		    &origin_head));
1714 
1715 		if (drc->drc_force) {
1716 			/*
1717 			 * Destroy any snapshots of drc_tofs (origin_head)
1718 			 * after the origin (the snap before drc_ds).
1719 			 */
1720 			uint64_t obj = origin_head->ds_phys->ds_prev_snap_obj;
1721 			while (obj != drc->drc_ds->ds_phys->ds_prev_snap_obj) {
1722 				dsl_dataset_t *snap;
1723 				VERIFY0(dsl_dataset_hold_obj(dp, obj, FTAG,
1724 				    &snap));
1725 				ASSERT3P(snap->ds_dir, ==, origin_head->ds_dir);
1726 				obj = snap->ds_phys->ds_prev_snap_obj;
1727 				dsl_destroy_snapshot_sync_impl(snap,
1728 				    B_FALSE, tx);
1729 				dsl_dataset_rele(snap, FTAG);
1730 			}
1731 		}
1732 		VERIFY3P(drc->drc_ds->ds_prev, ==,
1733 		    origin_head->ds_prev);
1734 
1735 		dsl_dataset_clone_swap_sync_impl(drc->drc_ds,
1736 		    origin_head, tx);
1737 		dsl_dataset_snapshot_sync_impl(origin_head,
1738 		    drc->drc_tosnap, tx);
1739 
1740 		/* set snapshot's creation time and guid */
1741 		dmu_buf_will_dirty(origin_head->ds_prev->ds_dbuf, tx);
1742 		origin_head->ds_prev->ds_phys->ds_creation_time =
1743 		    drc->drc_drrb->drr_creation_time;
1744 		origin_head->ds_prev->ds_phys->ds_guid =
1745 		    drc->drc_drrb->drr_toguid;
1746 		origin_head->ds_prev->ds_phys->ds_flags &=
1747 		    ~DS_FLAG_INCONSISTENT;
1748 
1749 		dmu_buf_will_dirty(origin_head->ds_dbuf, tx);
1750 		origin_head->ds_phys->ds_flags &= ~DS_FLAG_INCONSISTENT;
1751 
1752 		dsl_dataset_rele(origin_head, FTAG);
1753 		dsl_destroy_head_sync_impl(drc->drc_ds, tx);
1754 
1755 		if (drc->drc_owner != NULL)
1756 			VERIFY3P(origin_head->ds_owner, ==, drc->drc_owner);
1757 	} else {
1758 		dsl_dataset_t *ds = drc->drc_ds;
1759 
1760 		dsl_dataset_snapshot_sync_impl(ds, drc->drc_tosnap, tx);
1761 
1762 		/* set snapshot's creation time and guid */
1763 		dmu_buf_will_dirty(ds->ds_prev->ds_dbuf, tx);
1764 		ds->ds_prev->ds_phys->ds_creation_time =
1765 		    drc->drc_drrb->drr_creation_time;
1766 		ds->ds_prev->ds_phys->ds_guid = drc->drc_drrb->drr_toguid;
1767 		ds->ds_prev->ds_phys->ds_flags &= ~DS_FLAG_INCONSISTENT;
1768 
1769 		dmu_buf_will_dirty(ds->ds_dbuf, tx);
1770 		ds->ds_phys->ds_flags &= ~DS_FLAG_INCONSISTENT;
1771 	}
1772 	drc->drc_newsnapobj = drc->drc_ds->ds_phys->ds_prev_snap_obj;
1773 	/*
1774 	 * Release the hold from dmu_recv_begin.  This must be done before
1775 	 * we return to open context, so that when we free the dataset's dnode,
1776 	 * we can evict its bonus buffer.
1777 	 */
1778 	dsl_dataset_disown(drc->drc_ds, dmu_recv_tag);
1779 	drc->drc_ds = NULL;
1780 }
1781 
1782 static int
1783 add_ds_to_guidmap(const char *name, avl_tree_t *guid_map, uint64_t snapobj)
1784 {
1785 	dsl_pool_t *dp;
1786 	dsl_dataset_t *snapds;
1787 	guid_map_entry_t *gmep;
1788 	int err;
1789 
1790 	ASSERT(guid_map != NULL);
1791 
1792 	err = dsl_pool_hold(name, FTAG, &dp);
1793 	if (err != 0)
1794 		return (err);
1795 	gmep = kmem_alloc(sizeof (*gmep), KM_SLEEP);
1796 	err = dsl_dataset_hold_obj(dp, snapobj, gmep, &snapds);
1797 	if (err == 0) {
1798 		gmep->guid = snapds->ds_phys->ds_guid;
1799 		gmep->gme_ds = snapds;
1800 		avl_add(guid_map, gmep);
1801 		dsl_dataset_long_hold(snapds, gmep);
1802 	} else {
1803 		kmem_free(gmep, sizeof (*gmep));
1804 	}
1805 
1806 	dsl_pool_rele(dp, FTAG);
1807 	return (err);
1808 }
1809 
1810 static int dmu_recv_end_modified_blocks = 3;
1811 
1812 static int
1813 dmu_recv_existing_end(dmu_recv_cookie_t *drc)
1814 {
1815 	int error;
1816 	char name[MAXNAMELEN];
1817 
1818 #ifdef _KERNEL
1819 	/*
1820 	 * We will be destroying the ds; make sure its origin is unmounted if
1821 	 * necessary.
1822 	 */
1823 	dsl_dataset_name(drc->drc_ds, name);
1824 	zfs_destroy_unmount_origin(name);
1825 #endif
1826 
1827 	error = dsl_sync_task(drc->drc_tofs,
1828 	    dmu_recv_end_check, dmu_recv_end_sync, drc,
1829 	    dmu_recv_end_modified_blocks);
1830 
1831 	if (error != 0)
1832 		dmu_recv_cleanup_ds(drc);
1833 	return (error);
1834 }
1835 
1836 static int
1837 dmu_recv_new_end(dmu_recv_cookie_t *drc)
1838 {
1839 	int error;
1840 
1841 	error = dsl_sync_task(drc->drc_tofs,
1842 	    dmu_recv_end_check, dmu_recv_end_sync, drc,
1843 	    dmu_recv_end_modified_blocks);
1844 
1845 	if (error != 0) {
1846 		dmu_recv_cleanup_ds(drc);
1847 	} else if (drc->drc_guid_to_ds_map != NULL) {
1848 		(void) add_ds_to_guidmap(drc->drc_tofs,
1849 		    drc->drc_guid_to_ds_map,
1850 		    drc->drc_newsnapobj);
1851 	}
1852 	return (error);
1853 }
1854 
1855 int
1856 dmu_recv_end(dmu_recv_cookie_t *drc, void *owner)
1857 {
1858 	drc->drc_owner = owner;
1859 
1860 	if (drc->drc_newfs)
1861 		return (dmu_recv_new_end(drc));
1862 	else
1863 		return (dmu_recv_existing_end(drc));
1864 }
1865 
1866 /*
1867  * Return TRUE if this objset is currently being received into.
1868  */
1869 boolean_t
1870 dmu_objset_is_receiving(objset_t *os)
1871 {
1872 	return (os->os_dsl_dataset != NULL &&
1873 	    os->os_dsl_dataset->ds_owner == dmu_recv_tag);
1874 }
1875