xref: /titanic_50/usr/src/uts/common/fs/zfs/dmu_send.c (revision e1d3217b9afde782c4d3e946fda0e6ef36a61306)
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) 2014, 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 	/*
780 	 * Check snapshot limit before receiving. We'll recheck again at the
781 	 * end, but might as well abort before receiving if we're already over
782 	 * the limit.
783 	 *
784 	 * Note that we do not check the file system limit with
785 	 * dsl_dir_fscount_check because the temporary %clones don't count
786 	 * against that limit.
787 	 */
788 	error = dsl_fs_ss_limit_check(ds->ds_dir, 1, ZFS_PROP_SNAPSHOT_LIMIT,
789 	    NULL, drba->drba_cred);
790 	if (error != 0)
791 		return (error);
792 
793 	if (fromguid != 0) {
794 		dsl_dataset_t *snap;
795 		uint64_t obj = ds->ds_phys->ds_prev_snap_obj;
796 
797 		/* Find snapshot in this dir that matches fromguid. */
798 		while (obj != 0) {
799 			error = dsl_dataset_hold_obj(dp, obj, FTAG,
800 			    &snap);
801 			if (error != 0)
802 				return (SET_ERROR(ENODEV));
803 			if (snap->ds_dir != ds->ds_dir) {
804 				dsl_dataset_rele(snap, FTAG);
805 				return (SET_ERROR(ENODEV));
806 			}
807 			if (snap->ds_phys->ds_guid == fromguid)
808 				break;
809 			obj = snap->ds_phys->ds_prev_snap_obj;
810 			dsl_dataset_rele(snap, FTAG);
811 		}
812 		if (obj == 0)
813 			return (SET_ERROR(ENODEV));
814 
815 		if (drba->drba_cookie->drc_force) {
816 			drba->drba_snapobj = obj;
817 		} else {
818 			/*
819 			 * If we are not forcing, there must be no
820 			 * changes since fromsnap.
821 			 */
822 			if (dsl_dataset_modified_since_snap(ds, snap)) {
823 				dsl_dataset_rele(snap, FTAG);
824 				return (SET_ERROR(ETXTBSY));
825 			}
826 			drba->drba_snapobj = ds->ds_prev->ds_object;
827 		}
828 
829 		dsl_dataset_rele(snap, FTAG);
830 	} else {
831 		/* if full, most recent snapshot must be $ORIGIN */
832 		if (ds->ds_phys->ds_prev_snap_txg >= TXG_INITIAL)
833 			return (SET_ERROR(ENODEV));
834 		drba->drba_snapobj = ds->ds_phys->ds_prev_snap_obj;
835 	}
836 
837 	return (0);
838 
839 }
840 
841 static int
842 dmu_recv_begin_check(void *arg, dmu_tx_t *tx)
843 {
844 	dmu_recv_begin_arg_t *drba = arg;
845 	dsl_pool_t *dp = dmu_tx_pool(tx);
846 	struct drr_begin *drrb = drba->drba_cookie->drc_drrb;
847 	uint64_t fromguid = drrb->drr_fromguid;
848 	int flags = drrb->drr_flags;
849 	int error;
850 	dsl_dataset_t *ds;
851 	const char *tofs = drba->drba_cookie->drc_tofs;
852 
853 	/* already checked */
854 	ASSERT3U(drrb->drr_magic, ==, DMU_BACKUP_MAGIC);
855 
856 	if (DMU_GET_STREAM_HDRTYPE(drrb->drr_versioninfo) ==
857 	    DMU_COMPOUNDSTREAM ||
858 	    drrb->drr_type >= DMU_OST_NUMTYPES ||
859 	    ((flags & DRR_FLAG_CLONE) && drba->drba_origin == NULL))
860 		return (SET_ERROR(EINVAL));
861 
862 	/* Verify pool version supports SA if SA_SPILL feature set */
863 	if ((DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo) &
864 	    DMU_BACKUP_FEATURE_SA_SPILL) &&
865 	    spa_version(dp->dp_spa) < SPA_VERSION_SA) {
866 		return (SET_ERROR(ENOTSUP));
867 	}
868 
869 	error = dsl_dataset_hold(dp, tofs, FTAG, &ds);
870 	if (error == 0) {
871 		/* target fs already exists; recv into temp clone */
872 
873 		/* Can't recv a clone into an existing fs */
874 		if (flags & DRR_FLAG_CLONE) {
875 			dsl_dataset_rele(ds, FTAG);
876 			return (SET_ERROR(EINVAL));
877 		}
878 
879 		error = recv_begin_check_existing_impl(drba, ds, fromguid);
880 		dsl_dataset_rele(ds, FTAG);
881 	} else if (error == ENOENT) {
882 		/* target fs does not exist; must be a full backup or clone */
883 		char buf[MAXNAMELEN];
884 
885 		/*
886 		 * If it's a non-clone incremental, we are missing the
887 		 * target fs, so fail the recv.
888 		 */
889 		if (fromguid != 0 && !(flags & DRR_FLAG_CLONE))
890 			return (SET_ERROR(ENOENT));
891 
892 		/* Open the parent of tofs */
893 		ASSERT3U(strlen(tofs), <, MAXNAMELEN);
894 		(void) strlcpy(buf, tofs, strrchr(tofs, '/') - tofs + 1);
895 		error = dsl_dataset_hold(dp, buf, FTAG, &ds);
896 		if (error != 0)
897 			return (error);
898 
899 		/*
900 		 * Check filesystem and snapshot limits before receiving. We'll
901 		 * recheck snapshot limits again at the end (we create the
902 		 * filesystems and increment those counts during begin_sync).
903 		 */
904 		error = dsl_fs_ss_limit_check(ds->ds_dir, 1,
905 		    ZFS_PROP_FILESYSTEM_LIMIT, NULL, drba->drba_cred);
906 		if (error != 0) {
907 			dsl_dataset_rele(ds, FTAG);
908 			return (error);
909 		}
910 
911 		error = dsl_fs_ss_limit_check(ds->ds_dir, 1,
912 		    ZFS_PROP_SNAPSHOT_LIMIT, NULL, drba->drba_cred);
913 		if (error != 0) {
914 			dsl_dataset_rele(ds, FTAG);
915 			return (error);
916 		}
917 
918 		if (drba->drba_origin != NULL) {
919 			dsl_dataset_t *origin;
920 			error = dsl_dataset_hold(dp, drba->drba_origin,
921 			    FTAG, &origin);
922 			if (error != 0) {
923 				dsl_dataset_rele(ds, FTAG);
924 				return (error);
925 			}
926 			if (!dsl_dataset_is_snapshot(origin)) {
927 				dsl_dataset_rele(origin, FTAG);
928 				dsl_dataset_rele(ds, FTAG);
929 				return (SET_ERROR(EINVAL));
930 			}
931 			if (origin->ds_phys->ds_guid != fromguid) {
932 				dsl_dataset_rele(origin, FTAG);
933 				dsl_dataset_rele(ds, FTAG);
934 				return (SET_ERROR(ENODEV));
935 			}
936 			dsl_dataset_rele(origin, FTAG);
937 		}
938 		dsl_dataset_rele(ds, FTAG);
939 		error = 0;
940 	}
941 	return (error);
942 }
943 
944 static void
945 dmu_recv_begin_sync(void *arg, dmu_tx_t *tx)
946 {
947 	dmu_recv_begin_arg_t *drba = arg;
948 	dsl_pool_t *dp = dmu_tx_pool(tx);
949 	struct drr_begin *drrb = drba->drba_cookie->drc_drrb;
950 	const char *tofs = drba->drba_cookie->drc_tofs;
951 	dsl_dataset_t *ds, *newds;
952 	uint64_t dsobj;
953 	int error;
954 	uint64_t crflags;
955 
956 	crflags = (drrb->drr_flags & DRR_FLAG_CI_DATA) ?
957 	    DS_FLAG_CI_DATASET : 0;
958 
959 	error = dsl_dataset_hold(dp, tofs, FTAG, &ds);
960 	if (error == 0) {
961 		/* create temporary clone */
962 		dsl_dataset_t *snap = NULL;
963 		if (drba->drba_snapobj != 0) {
964 			VERIFY0(dsl_dataset_hold_obj(dp,
965 			    drba->drba_snapobj, FTAG, &snap));
966 		}
967 		dsobj = dsl_dataset_create_sync(ds->ds_dir, recv_clone_name,
968 		    snap, crflags, drba->drba_cred, tx);
969 		dsl_dataset_rele(snap, FTAG);
970 		dsl_dataset_rele(ds, FTAG);
971 	} else {
972 		dsl_dir_t *dd;
973 		const char *tail;
974 		dsl_dataset_t *origin = NULL;
975 
976 		VERIFY0(dsl_dir_hold(dp, tofs, FTAG, &dd, &tail));
977 
978 		if (drba->drba_origin != NULL) {
979 			VERIFY0(dsl_dataset_hold(dp, drba->drba_origin,
980 			    FTAG, &origin));
981 		}
982 
983 		/* Create new dataset. */
984 		dsobj = dsl_dataset_create_sync(dd,
985 		    strrchr(tofs, '/') + 1,
986 		    origin, crflags, drba->drba_cred, tx);
987 		if (origin != NULL)
988 			dsl_dataset_rele(origin, FTAG);
989 		dsl_dir_rele(dd, FTAG);
990 		drba->drba_cookie->drc_newfs = B_TRUE;
991 	}
992 	VERIFY0(dsl_dataset_own_obj(dp, dsobj, dmu_recv_tag, &newds));
993 
994 	dmu_buf_will_dirty(newds->ds_dbuf, tx);
995 	newds->ds_phys->ds_flags |= DS_FLAG_INCONSISTENT;
996 
997 	/*
998 	 * If we actually created a non-clone, we need to create the
999 	 * objset in our new dataset.
1000 	 */
1001 	if (BP_IS_HOLE(dsl_dataset_get_blkptr(newds))) {
1002 		(void) dmu_objset_create_impl(dp->dp_spa,
1003 		    newds, dsl_dataset_get_blkptr(newds), drrb->drr_type, tx);
1004 	}
1005 
1006 	drba->drba_cookie->drc_ds = newds;
1007 
1008 	spa_history_log_internal_ds(newds, "receive", tx, "");
1009 }
1010 
1011 /*
1012  * NB: callers *MUST* call dmu_recv_stream() if dmu_recv_begin()
1013  * succeeds; otherwise we will leak the holds on the datasets.
1014  */
1015 int
1016 dmu_recv_begin(char *tofs, char *tosnap, struct drr_begin *drrb,
1017     boolean_t force, char *origin, dmu_recv_cookie_t *drc)
1018 {
1019 	dmu_recv_begin_arg_t drba = { 0 };
1020 	dmu_replay_record_t *drr;
1021 
1022 	bzero(drc, sizeof (dmu_recv_cookie_t));
1023 	drc->drc_drrb = drrb;
1024 	drc->drc_tosnap = tosnap;
1025 	drc->drc_tofs = tofs;
1026 	drc->drc_force = force;
1027 	drc->drc_cred = CRED();
1028 
1029 	if (drrb->drr_magic == BSWAP_64(DMU_BACKUP_MAGIC))
1030 		drc->drc_byteswap = B_TRUE;
1031 	else if (drrb->drr_magic != DMU_BACKUP_MAGIC)
1032 		return (SET_ERROR(EINVAL));
1033 
1034 	drr = kmem_zalloc(sizeof (dmu_replay_record_t), KM_SLEEP);
1035 	drr->drr_type = DRR_BEGIN;
1036 	drr->drr_u.drr_begin = *drc->drc_drrb;
1037 	if (drc->drc_byteswap) {
1038 		fletcher_4_incremental_byteswap(drr,
1039 		    sizeof (dmu_replay_record_t), &drc->drc_cksum);
1040 	} else {
1041 		fletcher_4_incremental_native(drr,
1042 		    sizeof (dmu_replay_record_t), &drc->drc_cksum);
1043 	}
1044 	kmem_free(drr, sizeof (dmu_replay_record_t));
1045 
1046 	if (drc->drc_byteswap) {
1047 		drrb->drr_magic = BSWAP_64(drrb->drr_magic);
1048 		drrb->drr_versioninfo = BSWAP_64(drrb->drr_versioninfo);
1049 		drrb->drr_creation_time = BSWAP_64(drrb->drr_creation_time);
1050 		drrb->drr_type = BSWAP_32(drrb->drr_type);
1051 		drrb->drr_toguid = BSWAP_64(drrb->drr_toguid);
1052 		drrb->drr_fromguid = BSWAP_64(drrb->drr_fromguid);
1053 	}
1054 
1055 	drba.drba_origin = origin;
1056 	drba.drba_cookie = drc;
1057 	drba.drba_cred = CRED();
1058 
1059 	return (dsl_sync_task(tofs, dmu_recv_begin_check, dmu_recv_begin_sync,
1060 	    &drba, 5));
1061 }
1062 
1063 struct restorearg {
1064 	int err;
1065 	boolean_t byteswap;
1066 	vnode_t *vp;
1067 	char *buf;
1068 	uint64_t voff;
1069 	int bufsize; /* amount of memory allocated for buf */
1070 	zio_cksum_t cksum;
1071 	avl_tree_t *guid_to_ds_map;
1072 };
1073 
1074 typedef struct guid_map_entry {
1075 	uint64_t	guid;
1076 	dsl_dataset_t	*gme_ds;
1077 	avl_node_t	avlnode;
1078 } guid_map_entry_t;
1079 
1080 static int
1081 guid_compare(const void *arg1, const void *arg2)
1082 {
1083 	const guid_map_entry_t *gmep1 = arg1;
1084 	const guid_map_entry_t *gmep2 = arg2;
1085 
1086 	if (gmep1->guid < gmep2->guid)
1087 		return (-1);
1088 	else if (gmep1->guid > gmep2->guid)
1089 		return (1);
1090 	return (0);
1091 }
1092 
1093 static void
1094 free_guid_map_onexit(void *arg)
1095 {
1096 	avl_tree_t *ca = arg;
1097 	void *cookie = NULL;
1098 	guid_map_entry_t *gmep;
1099 
1100 	while ((gmep = avl_destroy_nodes(ca, &cookie)) != NULL) {
1101 		dsl_dataset_long_rele(gmep->gme_ds, gmep);
1102 		dsl_dataset_rele(gmep->gme_ds, gmep);
1103 		kmem_free(gmep, sizeof (guid_map_entry_t));
1104 	}
1105 	avl_destroy(ca);
1106 	kmem_free(ca, sizeof (avl_tree_t));
1107 }
1108 
1109 static void *
1110 restore_read(struct restorearg *ra, int len)
1111 {
1112 	void *rv;
1113 	int done = 0;
1114 
1115 	/* some things will require 8-byte alignment, so everything must */
1116 	ASSERT0(len % 8);
1117 
1118 	while (done < len) {
1119 		ssize_t resid;
1120 
1121 		ra->err = vn_rdwr(UIO_READ, ra->vp,
1122 		    (caddr_t)ra->buf + done, len - done,
1123 		    ra->voff, UIO_SYSSPACE, FAPPEND,
1124 		    RLIM64_INFINITY, CRED(), &resid);
1125 
1126 		if (resid == len - done)
1127 			ra->err = SET_ERROR(EINVAL);
1128 		ra->voff += len - done - resid;
1129 		done = len - resid;
1130 		if (ra->err != 0)
1131 			return (NULL);
1132 	}
1133 
1134 	ASSERT3U(done, ==, len);
1135 	rv = ra->buf;
1136 	if (ra->byteswap)
1137 		fletcher_4_incremental_byteswap(rv, len, &ra->cksum);
1138 	else
1139 		fletcher_4_incremental_native(rv, len, &ra->cksum);
1140 	return (rv);
1141 }
1142 
1143 static void
1144 backup_byteswap(dmu_replay_record_t *drr)
1145 {
1146 #define	DO64(X) (drr->drr_u.X = BSWAP_64(drr->drr_u.X))
1147 #define	DO32(X) (drr->drr_u.X = BSWAP_32(drr->drr_u.X))
1148 	drr->drr_type = BSWAP_32(drr->drr_type);
1149 	drr->drr_payloadlen = BSWAP_32(drr->drr_payloadlen);
1150 	switch (drr->drr_type) {
1151 	case DRR_BEGIN:
1152 		DO64(drr_begin.drr_magic);
1153 		DO64(drr_begin.drr_versioninfo);
1154 		DO64(drr_begin.drr_creation_time);
1155 		DO32(drr_begin.drr_type);
1156 		DO32(drr_begin.drr_flags);
1157 		DO64(drr_begin.drr_toguid);
1158 		DO64(drr_begin.drr_fromguid);
1159 		break;
1160 	case DRR_OBJECT:
1161 		DO64(drr_object.drr_object);
1162 		/* DO64(drr_object.drr_allocation_txg); */
1163 		DO32(drr_object.drr_type);
1164 		DO32(drr_object.drr_bonustype);
1165 		DO32(drr_object.drr_blksz);
1166 		DO32(drr_object.drr_bonuslen);
1167 		DO64(drr_object.drr_toguid);
1168 		break;
1169 	case DRR_FREEOBJECTS:
1170 		DO64(drr_freeobjects.drr_firstobj);
1171 		DO64(drr_freeobjects.drr_numobjs);
1172 		DO64(drr_freeobjects.drr_toguid);
1173 		break;
1174 	case DRR_WRITE:
1175 		DO64(drr_write.drr_object);
1176 		DO32(drr_write.drr_type);
1177 		DO64(drr_write.drr_offset);
1178 		DO64(drr_write.drr_length);
1179 		DO64(drr_write.drr_toguid);
1180 		DO64(drr_write.drr_key.ddk_cksum.zc_word[0]);
1181 		DO64(drr_write.drr_key.ddk_cksum.zc_word[1]);
1182 		DO64(drr_write.drr_key.ddk_cksum.zc_word[2]);
1183 		DO64(drr_write.drr_key.ddk_cksum.zc_word[3]);
1184 		DO64(drr_write.drr_key.ddk_prop);
1185 		break;
1186 	case DRR_WRITE_BYREF:
1187 		DO64(drr_write_byref.drr_object);
1188 		DO64(drr_write_byref.drr_offset);
1189 		DO64(drr_write_byref.drr_length);
1190 		DO64(drr_write_byref.drr_toguid);
1191 		DO64(drr_write_byref.drr_refguid);
1192 		DO64(drr_write_byref.drr_refobject);
1193 		DO64(drr_write_byref.drr_refoffset);
1194 		DO64(drr_write_byref.drr_key.ddk_cksum.zc_word[0]);
1195 		DO64(drr_write_byref.drr_key.ddk_cksum.zc_word[1]);
1196 		DO64(drr_write_byref.drr_key.ddk_cksum.zc_word[2]);
1197 		DO64(drr_write_byref.drr_key.ddk_cksum.zc_word[3]);
1198 		DO64(drr_write_byref.drr_key.ddk_prop);
1199 		break;
1200 	case DRR_FREE:
1201 		DO64(drr_free.drr_object);
1202 		DO64(drr_free.drr_offset);
1203 		DO64(drr_free.drr_length);
1204 		DO64(drr_free.drr_toguid);
1205 		break;
1206 	case DRR_SPILL:
1207 		DO64(drr_spill.drr_object);
1208 		DO64(drr_spill.drr_length);
1209 		DO64(drr_spill.drr_toguid);
1210 		break;
1211 	case DRR_END:
1212 		DO64(drr_end.drr_checksum.zc_word[0]);
1213 		DO64(drr_end.drr_checksum.zc_word[1]);
1214 		DO64(drr_end.drr_checksum.zc_word[2]);
1215 		DO64(drr_end.drr_checksum.zc_word[3]);
1216 		DO64(drr_end.drr_toguid);
1217 		break;
1218 	}
1219 #undef DO64
1220 #undef DO32
1221 }
1222 
1223 static int
1224 restore_object(struct restorearg *ra, objset_t *os, struct drr_object *drro)
1225 {
1226 	int err;
1227 	dmu_tx_t *tx;
1228 	void *data = NULL;
1229 
1230 	if (drro->drr_type == DMU_OT_NONE ||
1231 	    !DMU_OT_IS_VALID(drro->drr_type) ||
1232 	    !DMU_OT_IS_VALID(drro->drr_bonustype) ||
1233 	    drro->drr_checksumtype >= ZIO_CHECKSUM_FUNCTIONS ||
1234 	    drro->drr_compress >= ZIO_COMPRESS_FUNCTIONS ||
1235 	    P2PHASE(drro->drr_blksz, SPA_MINBLOCKSIZE) ||
1236 	    drro->drr_blksz < SPA_MINBLOCKSIZE ||
1237 	    drro->drr_blksz > SPA_MAXBLOCKSIZE ||
1238 	    drro->drr_bonuslen > DN_MAX_BONUSLEN) {
1239 		return (SET_ERROR(EINVAL));
1240 	}
1241 
1242 	err = dmu_object_info(os, drro->drr_object, NULL);
1243 
1244 	if (err != 0 && err != ENOENT)
1245 		return (SET_ERROR(EINVAL));
1246 
1247 	if (drro->drr_bonuslen) {
1248 		data = restore_read(ra, P2ROUNDUP(drro->drr_bonuslen, 8));
1249 		if (ra->err != 0)
1250 			return (ra->err);
1251 	}
1252 
1253 	if (err == ENOENT) {
1254 		/* currently free, want to be allocated */
1255 		tx = dmu_tx_create(os);
1256 		dmu_tx_hold_bonus(tx, DMU_NEW_OBJECT);
1257 		err = dmu_tx_assign(tx, TXG_WAIT);
1258 		if (err != 0) {
1259 			dmu_tx_abort(tx);
1260 			return (err);
1261 		}
1262 		err = dmu_object_claim(os, drro->drr_object,
1263 		    drro->drr_type, drro->drr_blksz,
1264 		    drro->drr_bonustype, drro->drr_bonuslen, tx);
1265 		dmu_tx_commit(tx);
1266 	} else {
1267 		/* currently allocated, want to be allocated */
1268 		err = dmu_object_reclaim(os, drro->drr_object,
1269 		    drro->drr_type, drro->drr_blksz,
1270 		    drro->drr_bonustype, drro->drr_bonuslen);
1271 	}
1272 	if (err != 0) {
1273 		return (SET_ERROR(EINVAL));
1274 	}
1275 
1276 	tx = dmu_tx_create(os);
1277 	dmu_tx_hold_bonus(tx, drro->drr_object);
1278 	err = dmu_tx_assign(tx, TXG_WAIT);
1279 	if (err != 0) {
1280 		dmu_tx_abort(tx);
1281 		return (err);
1282 	}
1283 
1284 	dmu_object_set_checksum(os, drro->drr_object, drro->drr_checksumtype,
1285 	    tx);
1286 	dmu_object_set_compress(os, drro->drr_object, drro->drr_compress, tx);
1287 
1288 	if (data != NULL) {
1289 		dmu_buf_t *db;
1290 
1291 		VERIFY(0 == dmu_bonus_hold(os, drro->drr_object, FTAG, &db));
1292 		dmu_buf_will_dirty(db, tx);
1293 
1294 		ASSERT3U(db->db_size, >=, drro->drr_bonuslen);
1295 		bcopy(data, db->db_data, drro->drr_bonuslen);
1296 		if (ra->byteswap) {
1297 			dmu_object_byteswap_t byteswap =
1298 			    DMU_OT_BYTESWAP(drro->drr_bonustype);
1299 			dmu_ot_byteswap[byteswap].ob_func(db->db_data,
1300 			    drro->drr_bonuslen);
1301 		}
1302 		dmu_buf_rele(db, FTAG);
1303 	}
1304 	dmu_tx_commit(tx);
1305 	return (0);
1306 }
1307 
1308 /* ARGSUSED */
1309 static int
1310 restore_freeobjects(struct restorearg *ra, objset_t *os,
1311     struct drr_freeobjects *drrfo)
1312 {
1313 	uint64_t obj;
1314 
1315 	if (drrfo->drr_firstobj + drrfo->drr_numobjs < drrfo->drr_firstobj)
1316 		return (SET_ERROR(EINVAL));
1317 
1318 	for (obj = drrfo->drr_firstobj;
1319 	    obj < drrfo->drr_firstobj + drrfo->drr_numobjs;
1320 	    (void) dmu_object_next(os, &obj, FALSE, 0)) {
1321 		int err;
1322 
1323 		if (dmu_object_info(os, obj, NULL) != 0)
1324 			continue;
1325 
1326 		err = dmu_free_long_object(os, obj);
1327 		if (err != 0)
1328 			return (err);
1329 	}
1330 	return (0);
1331 }
1332 
1333 static int
1334 restore_write(struct restorearg *ra, objset_t *os,
1335     struct drr_write *drrw)
1336 {
1337 	dmu_tx_t *tx;
1338 	void *data;
1339 	int err;
1340 
1341 	if (drrw->drr_offset + drrw->drr_length < drrw->drr_offset ||
1342 	    !DMU_OT_IS_VALID(drrw->drr_type))
1343 		return (SET_ERROR(EINVAL));
1344 
1345 	data = restore_read(ra, drrw->drr_length);
1346 	if (data == NULL)
1347 		return (ra->err);
1348 
1349 	if (dmu_object_info(os, drrw->drr_object, NULL) != 0)
1350 		return (SET_ERROR(EINVAL));
1351 
1352 	tx = dmu_tx_create(os);
1353 
1354 	dmu_tx_hold_write(tx, drrw->drr_object,
1355 	    drrw->drr_offset, drrw->drr_length);
1356 	err = dmu_tx_assign(tx, TXG_WAIT);
1357 	if (err != 0) {
1358 		dmu_tx_abort(tx);
1359 		return (err);
1360 	}
1361 	if (ra->byteswap) {
1362 		dmu_object_byteswap_t byteswap =
1363 		    DMU_OT_BYTESWAP(drrw->drr_type);
1364 		dmu_ot_byteswap[byteswap].ob_func(data, drrw->drr_length);
1365 	}
1366 	dmu_write(os, drrw->drr_object,
1367 	    drrw->drr_offset, drrw->drr_length, data, tx);
1368 	dmu_tx_commit(tx);
1369 	return (0);
1370 }
1371 
1372 /*
1373  * Handle a DRR_WRITE_BYREF record.  This record is used in dedup'ed
1374  * streams to refer to a copy of the data that is already on the
1375  * system because it came in earlier in the stream.  This function
1376  * finds the earlier copy of the data, and uses that copy instead of
1377  * data from the stream to fulfill this write.
1378  */
1379 static int
1380 restore_write_byref(struct restorearg *ra, objset_t *os,
1381     struct drr_write_byref *drrwbr)
1382 {
1383 	dmu_tx_t *tx;
1384 	int err;
1385 	guid_map_entry_t gmesrch;
1386 	guid_map_entry_t *gmep;
1387 	avl_index_t	where;
1388 	objset_t *ref_os = NULL;
1389 	dmu_buf_t *dbp;
1390 
1391 	if (drrwbr->drr_offset + drrwbr->drr_length < drrwbr->drr_offset)
1392 		return (SET_ERROR(EINVAL));
1393 
1394 	/*
1395 	 * If the GUID of the referenced dataset is different from the
1396 	 * GUID of the target dataset, find the referenced dataset.
1397 	 */
1398 	if (drrwbr->drr_toguid != drrwbr->drr_refguid) {
1399 		gmesrch.guid = drrwbr->drr_refguid;
1400 		if ((gmep = avl_find(ra->guid_to_ds_map, &gmesrch,
1401 		    &where)) == NULL) {
1402 			return (SET_ERROR(EINVAL));
1403 		}
1404 		if (dmu_objset_from_ds(gmep->gme_ds, &ref_os))
1405 			return (SET_ERROR(EINVAL));
1406 	} else {
1407 		ref_os = os;
1408 	}
1409 
1410 	if (err = dmu_buf_hold(ref_os, drrwbr->drr_refobject,
1411 	    drrwbr->drr_refoffset, FTAG, &dbp, DMU_READ_PREFETCH))
1412 		return (err);
1413 
1414 	tx = dmu_tx_create(os);
1415 
1416 	dmu_tx_hold_write(tx, drrwbr->drr_object,
1417 	    drrwbr->drr_offset, drrwbr->drr_length);
1418 	err = dmu_tx_assign(tx, TXG_WAIT);
1419 	if (err != 0) {
1420 		dmu_tx_abort(tx);
1421 		return (err);
1422 	}
1423 	dmu_write(os, drrwbr->drr_object,
1424 	    drrwbr->drr_offset, drrwbr->drr_length, dbp->db_data, tx);
1425 	dmu_buf_rele(dbp, FTAG);
1426 	dmu_tx_commit(tx);
1427 	return (0);
1428 }
1429 
1430 static int
1431 restore_spill(struct restorearg *ra, objset_t *os, struct drr_spill *drrs)
1432 {
1433 	dmu_tx_t *tx;
1434 	void *data;
1435 	dmu_buf_t *db, *db_spill;
1436 	int err;
1437 
1438 	if (drrs->drr_length < SPA_MINBLOCKSIZE ||
1439 	    drrs->drr_length > SPA_MAXBLOCKSIZE)
1440 		return (SET_ERROR(EINVAL));
1441 
1442 	data = restore_read(ra, drrs->drr_length);
1443 	if (data == NULL)
1444 		return (ra->err);
1445 
1446 	if (dmu_object_info(os, drrs->drr_object, NULL) != 0)
1447 		return (SET_ERROR(EINVAL));
1448 
1449 	VERIFY(0 == dmu_bonus_hold(os, drrs->drr_object, FTAG, &db));
1450 	if ((err = dmu_spill_hold_by_bonus(db, FTAG, &db_spill)) != 0) {
1451 		dmu_buf_rele(db, FTAG);
1452 		return (err);
1453 	}
1454 
1455 	tx = dmu_tx_create(os);
1456 
1457 	dmu_tx_hold_spill(tx, db->db_object);
1458 
1459 	err = dmu_tx_assign(tx, TXG_WAIT);
1460 	if (err != 0) {
1461 		dmu_buf_rele(db, FTAG);
1462 		dmu_buf_rele(db_spill, FTAG);
1463 		dmu_tx_abort(tx);
1464 		return (err);
1465 	}
1466 	dmu_buf_will_dirty(db_spill, tx);
1467 
1468 	if (db_spill->db_size < drrs->drr_length)
1469 		VERIFY(0 == dbuf_spill_set_blksz(db_spill,
1470 		    drrs->drr_length, tx));
1471 	bcopy(data, db_spill->db_data, drrs->drr_length);
1472 
1473 	dmu_buf_rele(db, FTAG);
1474 	dmu_buf_rele(db_spill, FTAG);
1475 
1476 	dmu_tx_commit(tx);
1477 	return (0);
1478 }
1479 
1480 /* ARGSUSED */
1481 static int
1482 restore_free(struct restorearg *ra, objset_t *os,
1483     struct drr_free *drrf)
1484 {
1485 	int err;
1486 
1487 	if (drrf->drr_length != -1ULL &&
1488 	    drrf->drr_offset + drrf->drr_length < drrf->drr_offset)
1489 		return (SET_ERROR(EINVAL));
1490 
1491 	if (dmu_object_info(os, drrf->drr_object, NULL) != 0)
1492 		return (SET_ERROR(EINVAL));
1493 
1494 	err = dmu_free_long_range(os, drrf->drr_object,
1495 	    drrf->drr_offset, drrf->drr_length);
1496 	return (err);
1497 }
1498 
1499 /* used to destroy the drc_ds on error */
1500 static void
1501 dmu_recv_cleanup_ds(dmu_recv_cookie_t *drc)
1502 {
1503 	char name[MAXNAMELEN];
1504 	dsl_dataset_name(drc->drc_ds, name);
1505 	dsl_dataset_disown(drc->drc_ds, dmu_recv_tag);
1506 	(void) dsl_destroy_head(name);
1507 }
1508 
1509 /*
1510  * NB: callers *must* call dmu_recv_end() if this succeeds.
1511  */
1512 int
1513 dmu_recv_stream(dmu_recv_cookie_t *drc, vnode_t *vp, offset_t *voffp,
1514     int cleanup_fd, uint64_t *action_handlep)
1515 {
1516 	struct restorearg ra = { 0 };
1517 	dmu_replay_record_t *drr;
1518 	objset_t *os;
1519 	zio_cksum_t pcksum;
1520 	int featureflags;
1521 
1522 	ra.byteswap = drc->drc_byteswap;
1523 	ra.cksum = drc->drc_cksum;
1524 	ra.vp = vp;
1525 	ra.voff = *voffp;
1526 	ra.bufsize = 1<<20;
1527 	ra.buf = kmem_alloc(ra.bufsize, KM_SLEEP);
1528 
1529 	/* these were verified in dmu_recv_begin */
1530 	ASSERT3U(DMU_GET_STREAM_HDRTYPE(drc->drc_drrb->drr_versioninfo), ==,
1531 	    DMU_SUBSTREAM);
1532 	ASSERT3U(drc->drc_drrb->drr_type, <, DMU_OST_NUMTYPES);
1533 
1534 	/*
1535 	 * Open the objset we are modifying.
1536 	 */
1537 	VERIFY0(dmu_objset_from_ds(drc->drc_ds, &os));
1538 
1539 	ASSERT(drc->drc_ds->ds_phys->ds_flags & DS_FLAG_INCONSISTENT);
1540 
1541 	featureflags = DMU_GET_FEATUREFLAGS(drc->drc_drrb->drr_versioninfo);
1542 
1543 	/* if this stream is dedup'ed, set up the avl tree for guid mapping */
1544 	if (featureflags & DMU_BACKUP_FEATURE_DEDUP) {
1545 		minor_t minor;
1546 
1547 		if (cleanup_fd == -1) {
1548 			ra.err = SET_ERROR(EBADF);
1549 			goto out;
1550 		}
1551 		ra.err = zfs_onexit_fd_hold(cleanup_fd, &minor);
1552 		if (ra.err != 0) {
1553 			cleanup_fd = -1;
1554 			goto out;
1555 		}
1556 
1557 		if (*action_handlep == 0) {
1558 			ra.guid_to_ds_map =
1559 			    kmem_alloc(sizeof (avl_tree_t), KM_SLEEP);
1560 			avl_create(ra.guid_to_ds_map, guid_compare,
1561 			    sizeof (guid_map_entry_t),
1562 			    offsetof(guid_map_entry_t, avlnode));
1563 			ra.err = zfs_onexit_add_cb(minor,
1564 			    free_guid_map_onexit, ra.guid_to_ds_map,
1565 			    action_handlep);
1566 			if (ra.err != 0)
1567 				goto out;
1568 		} else {
1569 			ra.err = zfs_onexit_cb_data(minor, *action_handlep,
1570 			    (void **)&ra.guid_to_ds_map);
1571 			if (ra.err != 0)
1572 				goto out;
1573 		}
1574 
1575 		drc->drc_guid_to_ds_map = ra.guid_to_ds_map;
1576 	}
1577 
1578 	/*
1579 	 * Read records and process them.
1580 	 */
1581 	pcksum = ra.cksum;
1582 	while (ra.err == 0 &&
1583 	    NULL != (drr = restore_read(&ra, sizeof (*drr)))) {
1584 		if (issig(JUSTLOOKING) && issig(FORREAL)) {
1585 			ra.err = SET_ERROR(EINTR);
1586 			goto out;
1587 		}
1588 
1589 		if (ra.byteswap)
1590 			backup_byteswap(drr);
1591 
1592 		switch (drr->drr_type) {
1593 		case DRR_OBJECT:
1594 		{
1595 			/*
1596 			 * We need to make a copy of the record header,
1597 			 * because restore_{object,write} may need to
1598 			 * restore_read(), which will invalidate drr.
1599 			 */
1600 			struct drr_object drro = drr->drr_u.drr_object;
1601 			ra.err = restore_object(&ra, os, &drro);
1602 			break;
1603 		}
1604 		case DRR_FREEOBJECTS:
1605 		{
1606 			struct drr_freeobjects drrfo =
1607 			    drr->drr_u.drr_freeobjects;
1608 			ra.err = restore_freeobjects(&ra, os, &drrfo);
1609 			break;
1610 		}
1611 		case DRR_WRITE:
1612 		{
1613 			struct drr_write drrw = drr->drr_u.drr_write;
1614 			ra.err = restore_write(&ra, os, &drrw);
1615 			break;
1616 		}
1617 		case DRR_WRITE_BYREF:
1618 		{
1619 			struct drr_write_byref drrwbr =
1620 			    drr->drr_u.drr_write_byref;
1621 			ra.err = restore_write_byref(&ra, os, &drrwbr);
1622 			break;
1623 		}
1624 		case DRR_FREE:
1625 		{
1626 			struct drr_free drrf = drr->drr_u.drr_free;
1627 			ra.err = restore_free(&ra, os, &drrf);
1628 			break;
1629 		}
1630 		case DRR_END:
1631 		{
1632 			struct drr_end drre = drr->drr_u.drr_end;
1633 			/*
1634 			 * We compare against the *previous* checksum
1635 			 * value, because the stored checksum is of
1636 			 * everything before the DRR_END record.
1637 			 */
1638 			if (!ZIO_CHECKSUM_EQUAL(drre.drr_checksum, pcksum))
1639 				ra.err = SET_ERROR(ECKSUM);
1640 			goto out;
1641 		}
1642 		case DRR_SPILL:
1643 		{
1644 			struct drr_spill drrs = drr->drr_u.drr_spill;
1645 			ra.err = restore_spill(&ra, os, &drrs);
1646 			break;
1647 		}
1648 		default:
1649 			ra.err = SET_ERROR(EINVAL);
1650 			goto out;
1651 		}
1652 		pcksum = ra.cksum;
1653 	}
1654 	ASSERT(ra.err != 0);
1655 
1656 out:
1657 	if ((featureflags & DMU_BACKUP_FEATURE_DEDUP) && (cleanup_fd != -1))
1658 		zfs_onexit_fd_rele(cleanup_fd);
1659 
1660 	if (ra.err != 0) {
1661 		/*
1662 		 * destroy what we created, so we don't leave it in the
1663 		 * inconsistent restoring state.
1664 		 */
1665 		dmu_recv_cleanup_ds(drc);
1666 	}
1667 
1668 	kmem_free(ra.buf, ra.bufsize);
1669 	*voffp = ra.voff;
1670 	return (ra.err);
1671 }
1672 
1673 static int
1674 dmu_recv_end_check(void *arg, dmu_tx_t *tx)
1675 {
1676 	dmu_recv_cookie_t *drc = arg;
1677 	dsl_pool_t *dp = dmu_tx_pool(tx);
1678 	int error;
1679 
1680 	ASSERT3P(drc->drc_ds->ds_owner, ==, dmu_recv_tag);
1681 
1682 	if (!drc->drc_newfs) {
1683 		dsl_dataset_t *origin_head;
1684 
1685 		error = dsl_dataset_hold(dp, drc->drc_tofs, FTAG, &origin_head);
1686 		if (error != 0)
1687 			return (error);
1688 		if (drc->drc_force) {
1689 			/*
1690 			 * We will destroy any snapshots in tofs (i.e. before
1691 			 * origin_head) that are after the origin (which is
1692 			 * the snap before drc_ds, because drc_ds can not
1693 			 * have any snaps of its own).
1694 			 */
1695 			uint64_t obj = origin_head->ds_phys->ds_prev_snap_obj;
1696 			while (obj != drc->drc_ds->ds_phys->ds_prev_snap_obj) {
1697 				dsl_dataset_t *snap;
1698 				error = dsl_dataset_hold_obj(dp, obj, FTAG,
1699 				    &snap);
1700 				if (error != 0)
1701 					return (error);
1702 				if (snap->ds_dir != origin_head->ds_dir)
1703 					error = SET_ERROR(EINVAL);
1704 				if (error == 0)  {
1705 					error = dsl_destroy_snapshot_check_impl(
1706 					    snap, B_FALSE);
1707 				}
1708 				obj = snap->ds_phys->ds_prev_snap_obj;
1709 				dsl_dataset_rele(snap, FTAG);
1710 				if (error != 0)
1711 					return (error);
1712 			}
1713 		}
1714 		error = dsl_dataset_clone_swap_check_impl(drc->drc_ds,
1715 		    origin_head, drc->drc_force, drc->drc_owner, tx);
1716 		if (error != 0) {
1717 			dsl_dataset_rele(origin_head, FTAG);
1718 			return (error);
1719 		}
1720 		error = dsl_dataset_snapshot_check_impl(origin_head,
1721 		    drc->drc_tosnap, tx, B_TRUE, 1, drc->drc_cred);
1722 		dsl_dataset_rele(origin_head, FTAG);
1723 		if (error != 0)
1724 			return (error);
1725 
1726 		error = dsl_destroy_head_check_impl(drc->drc_ds, 1);
1727 	} else {
1728 		error = dsl_dataset_snapshot_check_impl(drc->drc_ds,
1729 		    drc->drc_tosnap, tx, B_TRUE, 1, drc->drc_cred);
1730 	}
1731 	return (error);
1732 }
1733 
1734 static void
1735 dmu_recv_end_sync(void *arg, dmu_tx_t *tx)
1736 {
1737 	dmu_recv_cookie_t *drc = arg;
1738 	dsl_pool_t *dp = dmu_tx_pool(tx);
1739 
1740 	spa_history_log_internal_ds(drc->drc_ds, "finish receiving",
1741 	    tx, "snap=%s", drc->drc_tosnap);
1742 
1743 	if (!drc->drc_newfs) {
1744 		dsl_dataset_t *origin_head;
1745 
1746 		VERIFY0(dsl_dataset_hold(dp, drc->drc_tofs, FTAG,
1747 		    &origin_head));
1748 
1749 		if (drc->drc_force) {
1750 			/*
1751 			 * Destroy any snapshots of drc_tofs (origin_head)
1752 			 * after the origin (the snap before drc_ds).
1753 			 */
1754 			uint64_t obj = origin_head->ds_phys->ds_prev_snap_obj;
1755 			while (obj != drc->drc_ds->ds_phys->ds_prev_snap_obj) {
1756 				dsl_dataset_t *snap;
1757 				VERIFY0(dsl_dataset_hold_obj(dp, obj, FTAG,
1758 				    &snap));
1759 				ASSERT3P(snap->ds_dir, ==, origin_head->ds_dir);
1760 				obj = snap->ds_phys->ds_prev_snap_obj;
1761 				dsl_destroy_snapshot_sync_impl(snap,
1762 				    B_FALSE, tx);
1763 				dsl_dataset_rele(snap, FTAG);
1764 			}
1765 		}
1766 		VERIFY3P(drc->drc_ds->ds_prev, ==,
1767 		    origin_head->ds_prev);
1768 
1769 		dsl_dataset_clone_swap_sync_impl(drc->drc_ds,
1770 		    origin_head, tx);
1771 		dsl_dataset_snapshot_sync_impl(origin_head,
1772 		    drc->drc_tosnap, tx);
1773 
1774 		/* set snapshot's creation time and guid */
1775 		dmu_buf_will_dirty(origin_head->ds_prev->ds_dbuf, tx);
1776 		origin_head->ds_prev->ds_phys->ds_creation_time =
1777 		    drc->drc_drrb->drr_creation_time;
1778 		origin_head->ds_prev->ds_phys->ds_guid =
1779 		    drc->drc_drrb->drr_toguid;
1780 		origin_head->ds_prev->ds_phys->ds_flags &=
1781 		    ~DS_FLAG_INCONSISTENT;
1782 
1783 		dmu_buf_will_dirty(origin_head->ds_dbuf, tx);
1784 		origin_head->ds_phys->ds_flags &= ~DS_FLAG_INCONSISTENT;
1785 
1786 		dsl_dataset_rele(origin_head, FTAG);
1787 		dsl_destroy_head_sync_impl(drc->drc_ds, tx);
1788 
1789 		if (drc->drc_owner != NULL)
1790 			VERIFY3P(origin_head->ds_owner, ==, drc->drc_owner);
1791 	} else {
1792 		dsl_dataset_t *ds = drc->drc_ds;
1793 
1794 		dsl_dataset_snapshot_sync_impl(ds, drc->drc_tosnap, tx);
1795 
1796 		/* set snapshot's creation time and guid */
1797 		dmu_buf_will_dirty(ds->ds_prev->ds_dbuf, tx);
1798 		ds->ds_prev->ds_phys->ds_creation_time =
1799 		    drc->drc_drrb->drr_creation_time;
1800 		ds->ds_prev->ds_phys->ds_guid = drc->drc_drrb->drr_toguid;
1801 		ds->ds_prev->ds_phys->ds_flags &= ~DS_FLAG_INCONSISTENT;
1802 
1803 		dmu_buf_will_dirty(ds->ds_dbuf, tx);
1804 		ds->ds_phys->ds_flags &= ~DS_FLAG_INCONSISTENT;
1805 	}
1806 	drc->drc_newsnapobj = drc->drc_ds->ds_phys->ds_prev_snap_obj;
1807 	/*
1808 	 * Release the hold from dmu_recv_begin.  This must be done before
1809 	 * we return to open context, so that when we free the dataset's dnode,
1810 	 * we can evict its bonus buffer.
1811 	 */
1812 	dsl_dataset_disown(drc->drc_ds, dmu_recv_tag);
1813 	drc->drc_ds = NULL;
1814 }
1815 
1816 static int
1817 add_ds_to_guidmap(const char *name, avl_tree_t *guid_map, uint64_t snapobj)
1818 {
1819 	dsl_pool_t *dp;
1820 	dsl_dataset_t *snapds;
1821 	guid_map_entry_t *gmep;
1822 	int err;
1823 
1824 	ASSERT(guid_map != NULL);
1825 
1826 	err = dsl_pool_hold(name, FTAG, &dp);
1827 	if (err != 0)
1828 		return (err);
1829 	gmep = kmem_alloc(sizeof (*gmep), KM_SLEEP);
1830 	err = dsl_dataset_hold_obj(dp, snapobj, gmep, &snapds);
1831 	if (err == 0) {
1832 		gmep->guid = snapds->ds_phys->ds_guid;
1833 		gmep->gme_ds = snapds;
1834 		avl_add(guid_map, gmep);
1835 		dsl_dataset_long_hold(snapds, gmep);
1836 	} else {
1837 		kmem_free(gmep, sizeof (*gmep));
1838 	}
1839 
1840 	dsl_pool_rele(dp, FTAG);
1841 	return (err);
1842 }
1843 
1844 static int dmu_recv_end_modified_blocks = 3;
1845 
1846 static int
1847 dmu_recv_existing_end(dmu_recv_cookie_t *drc)
1848 {
1849 	int error;
1850 	char name[MAXNAMELEN];
1851 
1852 #ifdef _KERNEL
1853 	/*
1854 	 * We will be destroying the ds; make sure its origin is unmounted if
1855 	 * necessary.
1856 	 */
1857 	dsl_dataset_name(drc->drc_ds, name);
1858 	zfs_destroy_unmount_origin(name);
1859 #endif
1860 
1861 	error = dsl_sync_task(drc->drc_tofs,
1862 	    dmu_recv_end_check, dmu_recv_end_sync, drc,
1863 	    dmu_recv_end_modified_blocks);
1864 
1865 	if (error != 0)
1866 		dmu_recv_cleanup_ds(drc);
1867 	return (error);
1868 }
1869 
1870 static int
1871 dmu_recv_new_end(dmu_recv_cookie_t *drc)
1872 {
1873 	int error;
1874 
1875 	error = dsl_sync_task(drc->drc_tofs,
1876 	    dmu_recv_end_check, dmu_recv_end_sync, drc,
1877 	    dmu_recv_end_modified_blocks);
1878 
1879 	if (error != 0) {
1880 		dmu_recv_cleanup_ds(drc);
1881 	} else if (drc->drc_guid_to_ds_map != NULL) {
1882 		(void) add_ds_to_guidmap(drc->drc_tofs,
1883 		    drc->drc_guid_to_ds_map,
1884 		    drc->drc_newsnapobj);
1885 	}
1886 	return (error);
1887 }
1888 
1889 int
1890 dmu_recv_end(dmu_recv_cookie_t *drc, void *owner)
1891 {
1892 	drc->drc_owner = owner;
1893 
1894 	if (drc->drc_newfs)
1895 		return (dmu_recv_new_end(drc));
1896 	else
1897 		return (dmu_recv_existing_end(drc));
1898 }
1899 
1900 /*
1901  * Return TRUE if this objset is currently being received into.
1902  */
1903 boolean_t
1904 dmu_objset_is_receiving(objset_t *os)
1905 {
1906 	return (os->os_dsl_dataset != NULL &&
1907 	    os->os_dsl_dataset->ds_owner == dmu_recv_tag);
1908 }
1909