xref: /illumos-gate/usr/src/uts/common/fs/zfs/dmu_send.c (revision 9e69d7d0feb2a0394435ca1d9746c4c3d7bf9b22)
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 2009 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #include <sys/dmu.h>
27 #include <sys/dmu_impl.h>
28 #include <sys/dmu_tx.h>
29 #include <sys/dbuf.h>
30 #include <sys/dnode.h>
31 #include <sys/zfs_context.h>
32 #include <sys/dmu_objset.h>
33 #include <sys/dmu_traverse.h>
34 #include <sys/dsl_dataset.h>
35 #include <sys/dsl_dir.h>
36 #include <sys/dsl_pool.h>
37 #include <sys/dsl_synctask.h>
38 #include <sys/zfs_ioctl.h>
39 #include <sys/zap.h>
40 #include <sys/zio_checksum.h>
41 #include <sys/avl.h>
42 
43 static char *dmu_recv_tag = "dmu_recv_tag";
44 
45 /*
46  * The list of data whose inclusion in a send stream can be pending from
47  * one call to backup_cb to another.  Multiple calls to dump_free() and
48  * dump_freeobjects() can be aggregated into a single DRR_FREE or
49  * DRR_FREEOBJECTS replay record.
50  */
51 typedef enum {
52 	PENDING_NONE,
53 	PENDING_FREE,
54 	PENDING_FREEOBJECTS
55 } pendop_t;
56 
57 struct backuparg {
58 	dmu_replay_record_t *drr;
59 	vnode_t *vp;
60 	offset_t *off;
61 	objset_t *os;
62 	zio_cksum_t zc;
63 	uint64_t toguid;
64 	int err;
65 	pendop_t pending_op;
66 };
67 
68 static int
69 dump_bytes(struct backuparg *ba, void *buf, int len)
70 {
71 	ssize_t resid; /* have to get resid to get detailed errno */
72 	ASSERT3U(len % 8, ==, 0);
73 
74 	fletcher_4_incremental_native(buf, len, &ba->zc);
75 	ba->err = vn_rdwr(UIO_WRITE, ba->vp,
76 	    (caddr_t)buf, len,
77 	    0, UIO_SYSSPACE, FAPPEND, RLIM64_INFINITY, CRED(), &resid);
78 	*ba->off += len;
79 	return (ba->err);
80 }
81 
82 static int
83 dump_free(struct backuparg *ba, uint64_t object, uint64_t offset,
84     uint64_t length)
85 {
86 	struct drr_free *drrf = &(ba->drr->drr_u.drr_free);
87 
88 	/*
89 	 * If there is a pending op, but it's not PENDING_FREE, push it out,
90 	 * since free block aggregation can only be done for blocks of the
91 	 * same type (i.e., DRR_FREE records can only be aggregated with
92 	 * other DRR_FREE records.  DRR_FREEOBJECTS records can only be
93 	 * aggregated with other DRR_FREEOBJECTS records.
94 	 */
95 	if (ba->pending_op != PENDING_NONE && ba->pending_op != PENDING_FREE) {
96 		if (dump_bytes(ba, ba->drr, sizeof (dmu_replay_record_t)) != 0)
97 			return (EINTR);
98 		ba->pending_op = PENDING_NONE;
99 	}
100 
101 	if (ba->pending_op == PENDING_FREE) {
102 		/*
103 		 * There should never be a PENDING_FREE if length is -1
104 		 * (because dump_dnode is the only place where this
105 		 * function is called with a -1, and only after flushing
106 		 * any pending record).
107 		 */
108 		ASSERT(length != -1ULL);
109 		/*
110 		 * Check to see whether this free block can be aggregated
111 		 * with pending one.
112 		 */
113 		if (drrf->drr_object == object && drrf->drr_offset +
114 		    drrf->drr_length == offset) {
115 			drrf->drr_length += length;
116 			return (0);
117 		} else {
118 			/* not a continuation.  Push out pending record */
119 			if (dump_bytes(ba, ba->drr,
120 			    sizeof (dmu_replay_record_t)) != 0)
121 				return (EINTR);
122 			ba->pending_op = PENDING_NONE;
123 		}
124 	}
125 	/* create a FREE record and make it pending */
126 	bzero(ba->drr, sizeof (dmu_replay_record_t));
127 	ba->drr->drr_type = DRR_FREE;
128 	drrf->drr_object = object;
129 	drrf->drr_offset = offset;
130 	drrf->drr_length = length;
131 	drrf->drr_toguid = ba->toguid;
132 	if (length == -1ULL) {
133 		if (dump_bytes(ba, ba->drr, sizeof (dmu_replay_record_t)) != 0)
134 			return (EINTR);
135 	} else {
136 		ba->pending_op = PENDING_FREE;
137 	}
138 
139 	return (0);
140 }
141 
142 static int
143 dump_data(struct backuparg *ba, dmu_object_type_t type,
144     uint64_t object, uint64_t offset, int blksz, void *data)
145 {
146 	struct drr_write *drrw = &(ba->drr->drr_u.drr_write);
147 
148 	/*
149 	 * If there is any kind of pending aggregation (currently either
150 	 * a grouping of free objects or free blocks), push it out to
151 	 * the stream, since aggregation can't be done across operations
152 	 * of different types.
153 	 */
154 	if (ba->pending_op != PENDING_NONE) {
155 		if (dump_bytes(ba, ba->drr, sizeof (dmu_replay_record_t)) != 0)
156 			return (EINTR);
157 		ba->pending_op = PENDING_NONE;
158 	}
159 	/* write a DATA record */
160 	bzero(ba->drr, sizeof (dmu_replay_record_t));
161 	ba->drr->drr_type = DRR_WRITE;
162 	drrw->drr_object = object;
163 	drrw->drr_type = type;
164 	drrw->drr_offset = offset;
165 	drrw->drr_length = blksz;
166 	drrw->drr_toguid = ba->toguid;
167 
168 	if (dump_bytes(ba, ba->drr, sizeof (dmu_replay_record_t)) != 0)
169 		return (EINTR);
170 	if (dump_bytes(ba, data, blksz) != 0)
171 		return (EINTR);
172 	return (0);
173 }
174 
175 static int
176 dump_freeobjects(struct backuparg *ba, uint64_t firstobj, uint64_t numobjs)
177 {
178 	struct drr_freeobjects *drrfo = &(ba->drr->drr_u.drr_freeobjects);
179 
180 	/*
181 	 * If there is a pending op, but it's not PENDING_FREEOBJECTS,
182 	 * push it out, since free block aggregation can only be done for
183 	 * blocks of the same type (i.e., DRR_FREE records can only be
184 	 * aggregated with other DRR_FREE records.  DRR_FREEOBJECTS records
185 	 * can only be aggregated with other DRR_FREEOBJECTS records.
186 	 */
187 	if (ba->pending_op != PENDING_NONE &&
188 	    ba->pending_op != PENDING_FREEOBJECTS) {
189 		if (dump_bytes(ba, ba->drr, sizeof (dmu_replay_record_t)) != 0)
190 			return (EINTR);
191 		ba->pending_op = PENDING_NONE;
192 	}
193 	if (ba->pending_op == PENDING_FREEOBJECTS) {
194 		/*
195 		 * See whether this free object array can be aggregated
196 		 * with pending one
197 		 */
198 		if (drrfo->drr_firstobj + drrfo->drr_numobjs == firstobj) {
199 			drrfo->drr_numobjs += numobjs;
200 			return (0);
201 		} else {
202 			/* can't be aggregated.  Push out pending record */
203 			if (dump_bytes(ba, ba->drr,
204 			    sizeof (dmu_replay_record_t)) != 0)
205 				return (EINTR);
206 			ba->pending_op = PENDING_NONE;
207 		}
208 	}
209 
210 	/* write a FREEOBJECTS record */
211 	bzero(ba->drr, sizeof (dmu_replay_record_t));
212 	ba->drr->drr_type = DRR_FREEOBJECTS;
213 	drrfo->drr_firstobj = firstobj;
214 	drrfo->drr_numobjs = numobjs;
215 	drrfo->drr_toguid = ba->toguid;
216 
217 	ba->pending_op = PENDING_FREEOBJECTS;
218 
219 	return (0);
220 }
221 
222 static int
223 dump_dnode(struct backuparg *ba, uint64_t object, dnode_phys_t *dnp)
224 {
225 	struct drr_object *drro = &(ba->drr->drr_u.drr_object);
226 
227 	if (dnp == NULL || dnp->dn_type == DMU_OT_NONE)
228 		return (dump_freeobjects(ba, object, 1));
229 
230 	if (ba->pending_op != PENDING_NONE) {
231 		if (dump_bytes(ba, ba->drr, sizeof (dmu_replay_record_t)) != 0)
232 			return (EINTR);
233 		ba->pending_op = PENDING_NONE;
234 	}
235 
236 	/* write an OBJECT record */
237 	bzero(ba->drr, sizeof (dmu_replay_record_t));
238 	ba->drr->drr_type = DRR_OBJECT;
239 	drro->drr_object = object;
240 	drro->drr_type = dnp->dn_type;
241 	drro->drr_bonustype = dnp->dn_bonustype;
242 	drro->drr_blksz = dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT;
243 	drro->drr_bonuslen = dnp->dn_bonuslen;
244 	drro->drr_checksumtype = dnp->dn_checksum;
245 	drro->drr_compress = dnp->dn_compress;
246 	drro->drr_toguid = ba->toguid;
247 
248 	if (dump_bytes(ba, ba->drr, sizeof (dmu_replay_record_t)) != 0)
249 		return (EINTR);
250 
251 	if (dump_bytes(ba, DN_BONUS(dnp), P2ROUNDUP(dnp->dn_bonuslen, 8)) != 0)
252 		return (EINTR);
253 
254 	/* free anything past the end of the file */
255 	if (dump_free(ba, object, (dnp->dn_maxblkid + 1) *
256 	    (dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT), -1ULL))
257 		return (EINTR);
258 	if (ba->err)
259 		return (EINTR);
260 	return (0);
261 }
262 
263 #define	BP_SPAN(dnp, level) \
264 	(((uint64_t)dnp->dn_datablkszsec) << (SPA_MINBLOCKSHIFT + \
265 	(level) * (dnp->dn_indblkshift - SPA_BLKPTRSHIFT)))
266 
267 /* ARGSUSED */
268 static int
269 backup_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
270     const zbookmark_t *zb, const dnode_phys_t *dnp, void *arg)
271 {
272 	struct backuparg *ba = arg;
273 	dmu_object_type_t type = bp ? BP_GET_TYPE(bp) : DMU_OT_NONE;
274 	int err = 0;
275 
276 	if (issig(JUSTLOOKING) && issig(FORREAL))
277 		return (EINTR);
278 
279 	if (zb->zb_object != DMU_META_DNODE_OBJECT &&
280 	    DMU_OBJECT_IS_SPECIAL(zb->zb_object)) {
281 		return (0);
282 	} else if (bp == NULL && zb->zb_object == DMU_META_DNODE_OBJECT) {
283 		uint64_t span = BP_SPAN(dnp, zb->zb_level);
284 		uint64_t dnobj = (zb->zb_blkid * span) >> DNODE_SHIFT;
285 		err = dump_freeobjects(ba, dnobj, span >> DNODE_SHIFT);
286 	} else if (bp == NULL) {
287 		uint64_t span = BP_SPAN(dnp, zb->zb_level);
288 		err = dump_free(ba, zb->zb_object, zb->zb_blkid * span, span);
289 	} else if (zb->zb_level > 0 || type == DMU_OT_OBJSET) {
290 		return (0);
291 	} else if (type == DMU_OT_DNODE) {
292 		dnode_phys_t *blk;
293 		int i;
294 		int blksz = BP_GET_LSIZE(bp);
295 		uint32_t aflags = ARC_WAIT;
296 		arc_buf_t *abuf;
297 
298 		if (arc_read_nolock(NULL, spa, bp,
299 		    arc_getbuf_func, &abuf, ZIO_PRIORITY_ASYNC_READ,
300 		    ZIO_FLAG_CANFAIL, &aflags, zb) != 0)
301 			return (EIO);
302 
303 		blk = abuf->b_data;
304 		for (i = 0; i < blksz >> DNODE_SHIFT; i++) {
305 			uint64_t dnobj = (zb->zb_blkid <<
306 			    (DNODE_BLOCK_SHIFT - DNODE_SHIFT)) + i;
307 			err = dump_dnode(ba, dnobj, blk+i);
308 			if (err)
309 				break;
310 		}
311 		(void) arc_buf_remove_ref(abuf, &abuf);
312 	} else { /* it's a level-0 block of a regular object */
313 		uint32_t aflags = ARC_WAIT;
314 		arc_buf_t *abuf;
315 		int blksz = BP_GET_LSIZE(bp);
316 
317 		if (arc_read_nolock(NULL, spa, bp,
318 		    arc_getbuf_func, &abuf, ZIO_PRIORITY_ASYNC_READ,
319 		    ZIO_FLAG_CANFAIL, &aflags, zb) != 0)
320 			return (EIO);
321 
322 		err = dump_data(ba, type, zb->zb_object, zb->zb_blkid * blksz,
323 		    blksz, abuf->b_data);
324 		(void) arc_buf_remove_ref(abuf, &abuf);
325 	}
326 
327 	ASSERT(err == 0 || err == EINTR);
328 	return (err);
329 }
330 
331 int
332 dmu_sendbackup(objset_t *tosnap, objset_t *fromsnap, boolean_t fromorigin,
333     vnode_t *vp, offset_t *off)
334 {
335 	dsl_dataset_t *ds = tosnap->os_dsl_dataset;
336 	dsl_dataset_t *fromds = fromsnap ? fromsnap->os_dsl_dataset : NULL;
337 	dmu_replay_record_t *drr;
338 	struct backuparg ba;
339 	int err;
340 	uint64_t fromtxg = 0;
341 
342 	/* tosnap must be a snapshot */
343 	if (ds->ds_phys->ds_next_snap_obj == 0)
344 		return (EINVAL);
345 
346 	/* fromsnap must be an earlier snapshot from the same fs as tosnap */
347 	if (fromds && (ds->ds_dir != fromds->ds_dir ||
348 	    fromds->ds_phys->ds_creation_txg >= ds->ds_phys->ds_creation_txg))
349 		return (EXDEV);
350 
351 	if (fromorigin) {
352 		dsl_pool_t *dp = ds->ds_dir->dd_pool;
353 
354 		if (fromsnap)
355 			return (EINVAL);
356 
357 		if (dsl_dir_is_clone(ds->ds_dir)) {
358 			rw_enter(&dp->dp_config_rwlock, RW_READER);
359 			err = dsl_dataset_hold_obj(dp,
360 			    ds->ds_dir->dd_phys->dd_origin_obj, FTAG, &fromds);
361 			rw_exit(&dp->dp_config_rwlock);
362 			if (err)
363 				return (err);
364 		} else {
365 			fromorigin = B_FALSE;
366 		}
367 	}
368 
369 
370 	drr = kmem_zalloc(sizeof (dmu_replay_record_t), KM_SLEEP);
371 	drr->drr_type = DRR_BEGIN;
372 	drr->drr_u.drr_begin.drr_magic = DMU_BACKUP_MAGIC;
373 	DMU_SET_STREAM_HDRTYPE(drr->drr_u.drr_begin.drr_versioninfo,
374 	    DMU_SUBSTREAM);
375 	drr->drr_u.drr_begin.drr_creation_time =
376 	    ds->ds_phys->ds_creation_time;
377 	drr->drr_u.drr_begin.drr_type = tosnap->os_phys->os_type;
378 	if (fromorigin)
379 		drr->drr_u.drr_begin.drr_flags |= DRR_FLAG_CLONE;
380 	drr->drr_u.drr_begin.drr_toguid = ds->ds_phys->ds_guid;
381 	if (ds->ds_phys->ds_flags & DS_FLAG_CI_DATASET)
382 		drr->drr_u.drr_begin.drr_flags |= DRR_FLAG_CI_DATA;
383 
384 	if (fromds)
385 		drr->drr_u.drr_begin.drr_fromguid = fromds->ds_phys->ds_guid;
386 	dsl_dataset_name(ds, drr->drr_u.drr_begin.drr_toname);
387 
388 	if (fromds)
389 		fromtxg = fromds->ds_phys->ds_creation_txg;
390 	if (fromorigin)
391 		dsl_dataset_rele(fromds, FTAG);
392 
393 	ba.drr = drr;
394 	ba.vp = vp;
395 	ba.os = tosnap;
396 	ba.off = off;
397 	ba.toguid = ds->ds_phys->ds_guid;
398 	ZIO_SET_CHECKSUM(&ba.zc, 0, 0, 0, 0);
399 	ba.pending_op = PENDING_NONE;
400 
401 	if (dump_bytes(&ba, drr, sizeof (dmu_replay_record_t)) != 0) {
402 		kmem_free(drr, sizeof (dmu_replay_record_t));
403 		return (ba.err);
404 	}
405 
406 	err = traverse_dataset(ds, fromtxg, TRAVERSE_PRE | TRAVERSE_PREFETCH,
407 	    backup_cb, &ba);
408 
409 	if (ba.pending_op != PENDING_NONE)
410 		if (dump_bytes(&ba, drr, sizeof (dmu_replay_record_t)) != 0)
411 			err = EINTR;
412 
413 	if (err) {
414 		if (err == EINTR && ba.err)
415 			err = ba.err;
416 		kmem_free(drr, sizeof (dmu_replay_record_t));
417 		return (err);
418 	}
419 
420 	bzero(drr, sizeof (dmu_replay_record_t));
421 	drr->drr_type = DRR_END;
422 	drr->drr_u.drr_end.drr_checksum = ba.zc;
423 	drr->drr_u.drr_end.drr_toguid = ba.toguid;
424 
425 	if (dump_bytes(&ba, drr, sizeof (dmu_replay_record_t)) != 0) {
426 		kmem_free(drr, sizeof (dmu_replay_record_t));
427 		return (ba.err);
428 	}
429 
430 	kmem_free(drr, sizeof (dmu_replay_record_t));
431 
432 	return (0);
433 }
434 
435 struct recvbeginsyncarg {
436 	const char *tofs;
437 	const char *tosnap;
438 	dsl_dataset_t *origin;
439 	uint64_t fromguid;
440 	dmu_objset_type_t type;
441 	void *tag;
442 	boolean_t force;
443 	uint64_t dsflags;
444 	char clonelastname[MAXNAMELEN];
445 	dsl_dataset_t *ds; /* the ds to recv into; returned from the syncfunc */
446 };
447 
448 /* ARGSUSED */
449 static int
450 recv_new_check(void *arg1, void *arg2, dmu_tx_t *tx)
451 {
452 	dsl_dir_t *dd = arg1;
453 	struct recvbeginsyncarg *rbsa = arg2;
454 	objset_t *mos = dd->dd_pool->dp_meta_objset;
455 	uint64_t val;
456 	int err;
457 
458 	err = zap_lookup(mos, dd->dd_phys->dd_child_dir_zapobj,
459 	    strrchr(rbsa->tofs, '/') + 1, sizeof (uint64_t), 1, &val);
460 
461 	if (err != ENOENT)
462 		return (err ? err : EEXIST);
463 
464 	if (rbsa->origin) {
465 		/* make sure it's a snap in the same pool */
466 		if (rbsa->origin->ds_dir->dd_pool != dd->dd_pool)
467 			return (EXDEV);
468 		if (!dsl_dataset_is_snapshot(rbsa->origin))
469 			return (EINVAL);
470 		if (rbsa->origin->ds_phys->ds_guid != rbsa->fromguid)
471 			return (ENODEV);
472 	}
473 
474 	return (0);
475 }
476 
477 static void
478 recv_new_sync(void *arg1, void *arg2, cred_t *cr, dmu_tx_t *tx)
479 {
480 	dsl_dir_t *dd = arg1;
481 	struct recvbeginsyncarg *rbsa = arg2;
482 	uint64_t flags = DS_FLAG_INCONSISTENT | rbsa->dsflags;
483 	uint64_t dsobj;
484 
485 	/* Create and open new dataset. */
486 	dsobj = dsl_dataset_create_sync(dd, strrchr(rbsa->tofs, '/') + 1,
487 	    rbsa->origin, flags, cr, tx);
488 	VERIFY(0 == dsl_dataset_own_obj(dd->dd_pool, dsobj,
489 	    B_TRUE, dmu_recv_tag, &rbsa->ds));
490 
491 	if (rbsa->origin == NULL) {
492 		(void) dmu_objset_create_impl(dd->dd_pool->dp_spa,
493 		    rbsa->ds, &rbsa->ds->ds_phys->ds_bp, rbsa->type, tx);
494 	}
495 
496 	spa_history_internal_log(LOG_DS_REPLAY_FULL_SYNC,
497 	    dd->dd_pool->dp_spa, tx, cr, "dataset = %lld", dsobj);
498 }
499 
500 /* ARGSUSED */
501 static int
502 recv_existing_check(void *arg1, void *arg2, dmu_tx_t *tx)
503 {
504 	dsl_dataset_t *ds = arg1;
505 	struct recvbeginsyncarg *rbsa = arg2;
506 	int err;
507 	uint64_t val;
508 
509 	/* must not have any changes since most recent snapshot */
510 	if (!rbsa->force && dsl_dataset_modified_since_lastsnap(ds))
511 		return (ETXTBSY);
512 
513 	if (rbsa->fromguid) {
514 		/* if incremental, most recent snapshot must match fromguid */
515 		if (ds->ds_prev == NULL)
516 			return (ENODEV);
517 		if (ds->ds_prev->ds_phys->ds_guid != rbsa->fromguid)
518 			return (ENODEV);
519 	} else {
520 		/* if full, most recent snapshot must be $ORIGIN */
521 		if (ds->ds_phys->ds_prev_snap_txg >= TXG_INITIAL)
522 			return (ENODEV);
523 	}
524 
525 	/* temporary clone name must not exist */
526 	err = zap_lookup(ds->ds_dir->dd_pool->dp_meta_objset,
527 	    ds->ds_dir->dd_phys->dd_child_dir_zapobj,
528 	    rbsa->clonelastname, 8, 1, &val);
529 	if (err == 0)
530 		return (EEXIST);
531 	if (err != ENOENT)
532 		return (err);
533 
534 	/* new snapshot name must not exist */
535 	err = zap_lookup(ds->ds_dir->dd_pool->dp_meta_objset,
536 	    ds->ds_phys->ds_snapnames_zapobj, rbsa->tosnap, 8, 1, &val);
537 	if (err == 0)
538 		return (EEXIST);
539 	if (err != ENOENT)
540 		return (err);
541 	return (0);
542 }
543 
544 /* ARGSUSED */
545 static void
546 recv_existing_sync(void *arg1, void *arg2, cred_t *cr, dmu_tx_t *tx)
547 {
548 	dsl_dataset_t *ohds = arg1;
549 	struct recvbeginsyncarg *rbsa = arg2;
550 	dsl_pool_t *dp = ohds->ds_dir->dd_pool;
551 	dsl_dataset_t *cds;
552 	uint64_t flags = DS_FLAG_INCONSISTENT | rbsa->dsflags;
553 	uint64_t dsobj;
554 
555 	/* create and open the temporary clone */
556 	dsobj = dsl_dataset_create_sync(ohds->ds_dir, rbsa->clonelastname,
557 	    ohds->ds_prev, flags, cr, tx);
558 	VERIFY(0 == dsl_dataset_own_obj(dp, dsobj, B_TRUE, dmu_recv_tag, &cds));
559 
560 	/*
561 	 * If we actually created a non-clone, we need to create the
562 	 * objset in our new dataset.
563 	 */
564 	if (BP_IS_HOLE(dsl_dataset_get_blkptr(cds))) {
565 		(void) dmu_objset_create_impl(dp->dp_spa,
566 		    cds, dsl_dataset_get_blkptr(cds), rbsa->type, tx);
567 	}
568 
569 	/* copy the refquota from the target fs to the clone */
570 	if (ohds->ds_quota > 0)
571 		dsl_dataset_set_quota_sync(cds, &ohds->ds_quota, cr, tx);
572 
573 	rbsa->ds = cds;
574 
575 	spa_history_internal_log(LOG_DS_REPLAY_INC_SYNC,
576 	    dp->dp_spa, tx, cr, "dataset = %lld", dsobj);
577 }
578 
579 /*
580  * NB: callers *MUST* call dmu_recv_stream() if dmu_recv_begin()
581  * succeeds; otherwise we will leak the holds on the datasets.
582  */
583 int
584 dmu_recv_begin(char *tofs, char *tosnap, char *top_ds, struct drr_begin *drrb,
585     boolean_t force, objset_t *origin, dmu_recv_cookie_t *drc)
586 {
587 	int err = 0;
588 	boolean_t byteswap;
589 	struct recvbeginsyncarg rbsa = { 0 };
590 	uint64_t versioninfo;
591 	int flags;
592 	dsl_dataset_t *ds;
593 
594 	if (drrb->drr_magic == DMU_BACKUP_MAGIC)
595 		byteswap = FALSE;
596 	else if (drrb->drr_magic == BSWAP_64(DMU_BACKUP_MAGIC))
597 		byteswap = TRUE;
598 	else
599 		return (EINVAL);
600 
601 	rbsa.tofs = tofs;
602 	rbsa.tosnap = tosnap;
603 	rbsa.origin = origin ? origin->os_dsl_dataset : NULL;
604 	rbsa.fromguid = drrb->drr_fromguid;
605 	rbsa.type = drrb->drr_type;
606 	rbsa.tag = FTAG;
607 	rbsa.dsflags = 0;
608 	versioninfo = drrb->drr_versioninfo;
609 	flags = drrb->drr_flags;
610 
611 	if (byteswap) {
612 		rbsa.type = BSWAP_32(rbsa.type);
613 		rbsa.fromguid = BSWAP_64(rbsa.fromguid);
614 		versioninfo = BSWAP_64(versioninfo);
615 		flags = BSWAP_32(flags);
616 	}
617 
618 	if (DMU_GET_STREAM_HDRTYPE(versioninfo) == DMU_COMPOUNDSTREAM ||
619 	    rbsa.type >= DMU_OST_NUMTYPES ||
620 	    ((flags & DRR_FLAG_CLONE) && origin == NULL))
621 		return (EINVAL);
622 
623 	if (flags & DRR_FLAG_CI_DATA)
624 		rbsa.dsflags = DS_FLAG_CI_DATASET;
625 
626 	bzero(drc, sizeof (dmu_recv_cookie_t));
627 	drc->drc_drrb = drrb;
628 	drc->drc_tosnap = tosnap;
629 	drc->drc_top_ds = top_ds;
630 	drc->drc_force = force;
631 
632 	/*
633 	 * Process the begin in syncing context.
634 	 */
635 
636 	/* open the dataset we are logically receiving into */
637 	err = dsl_dataset_hold(tofs, dmu_recv_tag, &ds);
638 	if (err == 0) {
639 		/* target fs already exists; recv into temp clone */
640 
641 		/* Can't recv a clone into an existing fs */
642 		if (flags & DRR_FLAG_CLONE) {
643 			dsl_dataset_rele(ds, dmu_recv_tag);
644 			return (EINVAL);
645 		}
646 
647 		/* must not have an incremental recv already in progress */
648 		if (!mutex_tryenter(&ds->ds_recvlock)) {
649 			dsl_dataset_rele(ds, dmu_recv_tag);
650 			return (EBUSY);
651 		}
652 
653 		/* tmp clone name is: tofs/%tosnap" */
654 		(void) snprintf(rbsa.clonelastname, sizeof (rbsa.clonelastname),
655 		    "%%%s", tosnap);
656 		rbsa.force = force;
657 		err = dsl_sync_task_do(ds->ds_dir->dd_pool,
658 		    recv_existing_check, recv_existing_sync, ds, &rbsa, 5);
659 		if (err) {
660 			mutex_exit(&ds->ds_recvlock);
661 			dsl_dataset_rele(ds, dmu_recv_tag);
662 			return (err);
663 		}
664 		drc->drc_logical_ds = ds;
665 		drc->drc_real_ds = rbsa.ds;
666 	} else if (err == ENOENT) {
667 		/* target fs does not exist; must be a full backup or clone */
668 		char *cp;
669 
670 		/*
671 		 * If it's a non-clone incremental, we are missing the
672 		 * target fs, so fail the recv.
673 		 */
674 		if (rbsa.fromguid && !(flags & DRR_FLAG_CLONE))
675 			return (ENOENT);
676 
677 		/* Open the parent of tofs */
678 		cp = strrchr(tofs, '/');
679 		*cp = '\0';
680 		err = dsl_dataset_hold(tofs, FTAG, &ds);
681 		*cp = '/';
682 		if (err)
683 			return (err);
684 
685 		err = dsl_sync_task_do(ds->ds_dir->dd_pool,
686 		    recv_new_check, recv_new_sync, ds->ds_dir, &rbsa, 5);
687 		dsl_dataset_rele(ds, FTAG);
688 		if (err)
689 			return (err);
690 		drc->drc_logical_ds = drc->drc_real_ds = rbsa.ds;
691 		drc->drc_newfs = B_TRUE;
692 	}
693 
694 	return (err);
695 }
696 
697 struct restorearg {
698 	int err;
699 	int byteswap;
700 	vnode_t *vp;
701 	char *buf;
702 	uint64_t voff;
703 	int bufsize; /* amount of memory allocated for buf */
704 	zio_cksum_t cksum;
705 	avl_tree_t guid_to_ds_map;
706 };
707 
708 typedef struct guid_map_entry {
709 	uint64_t	guid;
710 	dsl_dataset_t	*gme_ds;
711 	avl_node_t	avlnode;
712 } guid_map_entry_t;
713 
714 static int
715 guid_compare(const void *arg1, const void *arg2)
716 {
717 	const guid_map_entry_t *gmep1 = arg1;
718 	const guid_map_entry_t *gmep2 = arg2;
719 
720 	if (gmep1->guid < gmep2->guid)
721 		return (-1);
722 	else if (gmep1->guid > gmep2->guid)
723 		return (1);
724 	return (0);
725 }
726 
727 /*
728  * This function is a callback used by dmu_objset_find() (which
729  * enumerates the object sets) to build an avl tree that maps guids
730  * to datasets.  The resulting table is used when processing DRR_WRITE_BYREF
731  * send stream records.  These records, which are used in dedup'ed
732  * streams, do not contain data themselves, but refer to a copy
733  * of the data block that has already been written because it was
734  * earlier in the stream.  That previous copy is identified by the
735  * guid of the dataset with the referenced data.
736  */
737 int
738 find_ds_by_guid(char *name, void *arg)
739 {
740 	dsl_dataset_t *ds, *snapds;
741 	avl_tree_t *guid_map = arg;
742 	guid_map_entry_t *gmep;
743 	guid_map_entry_t gmesrch;
744 	dsl_pool_t	*dp;
745 	int err;
746 	uint64_t lastobj, firstobj;
747 
748 	if (dsl_dataset_hold(name, FTAG, &ds) != 0)
749 		return (0);
750 
751 	dp = ds->ds_dir->dd_pool;
752 	rw_enter(&dp->dp_config_rwlock, RW_READER);
753 	firstobj = ds->ds_dir->dd_phys->dd_origin_obj;
754 	lastobj = ds->ds_phys->ds_prev_snap_obj;
755 
756 	while (lastobj != firstobj) {
757 		err = dsl_dataset_hold_obj(dp, lastobj, guid_map, &snapds);
758 		if (err) {
759 			/*
760 			 * Skip this snapshot and move on. It's not
761 			 * clear why this would ever happen, but the
762 			 * remainder of the snapshot streadm can be
763 			 * processed.
764 			 */
765 			rw_exit(&dp->dp_config_rwlock);
766 			dsl_dataset_rele(ds, FTAG);
767 			return (0);
768 		}
769 
770 		gmesrch.guid = snapds->ds_phys->ds_guid;
771 		gmep = kmem_alloc(sizeof (guid_map_entry_t), KM_SLEEP);
772 		gmep->guid = snapds->ds_phys->ds_guid;
773 		gmep->gme_ds = snapds;
774 		avl_add(guid_map, gmep);
775 		lastobj = snapds->ds_phys->ds_prev_snap_obj;
776 	}
777 
778 	rw_exit(&dp->dp_config_rwlock);
779 	dsl_dataset_rele(ds, FTAG);
780 
781 	return (0);
782 }
783 
784 static void *
785 restore_read(struct restorearg *ra, int len)
786 {
787 	void *rv;
788 	int done = 0;
789 
790 	/* some things will require 8-byte alignment, so everything must */
791 	ASSERT3U(len % 8, ==, 0);
792 
793 	while (done < len) {
794 		ssize_t resid;
795 
796 		ra->err = vn_rdwr(UIO_READ, ra->vp,
797 		    (caddr_t)ra->buf + done, len - done,
798 		    ra->voff, UIO_SYSSPACE, FAPPEND,
799 		    RLIM64_INFINITY, CRED(), &resid);
800 
801 		if (resid == len - done)
802 			ra->err = EINVAL;
803 		ra->voff += len - done - resid;
804 		done = len - resid;
805 		if (ra->err)
806 			return (NULL);
807 	}
808 
809 	ASSERT3U(done, ==, len);
810 	rv = ra->buf;
811 	if (ra->byteswap)
812 		fletcher_4_incremental_byteswap(rv, len, &ra->cksum);
813 	else
814 		fletcher_4_incremental_native(rv, len, &ra->cksum);
815 	return (rv);
816 }
817 
818 static void
819 backup_byteswap(dmu_replay_record_t *drr)
820 {
821 #define	DO64(X) (drr->drr_u.X = BSWAP_64(drr->drr_u.X))
822 #define	DO32(X) (drr->drr_u.X = BSWAP_32(drr->drr_u.X))
823 	drr->drr_type = BSWAP_32(drr->drr_type);
824 	drr->drr_payloadlen = BSWAP_32(drr->drr_payloadlen);
825 	switch (drr->drr_type) {
826 	case DRR_BEGIN:
827 		DO64(drr_begin.drr_magic);
828 		DO64(drr_begin.drr_versioninfo);
829 		DO64(drr_begin.drr_creation_time);
830 		DO32(drr_begin.drr_type);
831 		DO32(drr_begin.drr_flags);
832 		DO64(drr_begin.drr_toguid);
833 		DO64(drr_begin.drr_fromguid);
834 		break;
835 	case DRR_OBJECT:
836 		DO64(drr_object.drr_object);
837 		/* DO64(drr_object.drr_allocation_txg); */
838 		DO32(drr_object.drr_type);
839 		DO32(drr_object.drr_bonustype);
840 		DO32(drr_object.drr_blksz);
841 		DO32(drr_object.drr_bonuslen);
842 		DO64(drr_object.drr_toguid);
843 		break;
844 	case DRR_FREEOBJECTS:
845 		DO64(drr_freeobjects.drr_firstobj);
846 		DO64(drr_freeobjects.drr_numobjs);
847 		DO64(drr_freeobjects.drr_toguid);
848 		break;
849 	case DRR_WRITE:
850 		DO64(drr_write.drr_object);
851 		DO32(drr_write.drr_type);
852 		DO64(drr_write.drr_offset);
853 		DO64(drr_write.drr_length);
854 		DO64(drr_write.drr_toguid);
855 		DO64(drr_write.drr_blkcksum.zc_word[0]);
856 		DO64(drr_write.drr_blkcksum.zc_word[1]);
857 		DO64(drr_write.drr_blkcksum.zc_word[2]);
858 		DO64(drr_write.drr_blkcksum.zc_word[3]);
859 		break;
860 	case DRR_WRITE_BYREF:
861 		DO64(drr_write_byref.drr_object);
862 		DO64(drr_write_byref.drr_offset);
863 		DO64(drr_write_byref.drr_length);
864 		DO64(drr_write_byref.drr_toguid);
865 		DO64(drr_write_byref.drr_refguid);
866 		DO64(drr_write_byref.drr_refobject);
867 		DO64(drr_write_byref.drr_refoffset);
868 		DO64(drr_write_byref.drr_blkcksum.zc_word[0]);
869 		DO64(drr_write_byref.drr_blkcksum.zc_word[1]);
870 		DO64(drr_write_byref.drr_blkcksum.zc_word[2]);
871 		DO64(drr_write_byref.drr_blkcksum.zc_word[3]);
872 		break;
873 	case DRR_FREE:
874 		DO64(drr_free.drr_object);
875 		DO64(drr_free.drr_offset);
876 		DO64(drr_free.drr_length);
877 		DO64(drr_free.drr_toguid);
878 		break;
879 	case DRR_END:
880 		DO64(drr_end.drr_checksum.zc_word[0]);
881 		DO64(drr_end.drr_checksum.zc_word[1]);
882 		DO64(drr_end.drr_checksum.zc_word[2]);
883 		DO64(drr_end.drr_checksum.zc_word[3]);
884 		DO64(drr_end.drr_toguid);
885 		break;
886 	}
887 #undef DO64
888 #undef DO32
889 }
890 
891 static int
892 restore_object(struct restorearg *ra, objset_t *os, struct drr_object *drro)
893 {
894 	int err;
895 	dmu_tx_t *tx;
896 	void *data = NULL;
897 
898 	if (drro->drr_type == DMU_OT_NONE ||
899 	    drro->drr_type >= DMU_OT_NUMTYPES ||
900 	    drro->drr_bonustype >= DMU_OT_NUMTYPES ||
901 	    drro->drr_checksumtype >= ZIO_CHECKSUM_FUNCTIONS ||
902 	    drro->drr_compress >= ZIO_COMPRESS_FUNCTIONS ||
903 	    P2PHASE(drro->drr_blksz, SPA_MINBLOCKSIZE) ||
904 	    drro->drr_blksz < SPA_MINBLOCKSIZE ||
905 	    drro->drr_blksz > SPA_MAXBLOCKSIZE ||
906 	    drro->drr_bonuslen > DN_MAX_BONUSLEN) {
907 		return (EINVAL);
908 	}
909 
910 	err = dmu_object_info(os, drro->drr_object, NULL);
911 
912 	if (err != 0 && err != ENOENT)
913 		return (EINVAL);
914 
915 	if (drro->drr_bonuslen) {
916 		data = restore_read(ra, P2ROUNDUP(drro->drr_bonuslen, 8));
917 		if (ra->err)
918 			return (ra->err);
919 	}
920 
921 	if (err == ENOENT) {
922 		/* currently free, want to be allocated */
923 		tx = dmu_tx_create(os);
924 		dmu_tx_hold_bonus(tx, DMU_NEW_OBJECT);
925 		err = dmu_tx_assign(tx, TXG_WAIT);
926 		if (err) {
927 			dmu_tx_abort(tx);
928 			return (err);
929 		}
930 		err = dmu_object_claim(os, drro->drr_object,
931 		    drro->drr_type, drro->drr_blksz,
932 		    drro->drr_bonustype, drro->drr_bonuslen, tx);
933 		dmu_tx_commit(tx);
934 	} else {
935 		/* currently allocated, want to be allocated */
936 		err = dmu_object_reclaim(os, drro->drr_object,
937 		    drro->drr_type, drro->drr_blksz,
938 		    drro->drr_bonustype, drro->drr_bonuslen);
939 	}
940 	if (err)
941 		return (EINVAL);
942 
943 	tx = dmu_tx_create(os);
944 	dmu_tx_hold_bonus(tx, drro->drr_object);
945 	err = dmu_tx_assign(tx, TXG_WAIT);
946 	if (err) {
947 		dmu_tx_abort(tx);
948 		return (err);
949 	}
950 
951 	dmu_object_set_checksum(os, drro->drr_object, drro->drr_checksumtype,
952 	    tx);
953 	dmu_object_set_compress(os, drro->drr_object, drro->drr_compress, tx);
954 
955 	if (data != NULL) {
956 		dmu_buf_t *db;
957 
958 		VERIFY(0 == dmu_bonus_hold(os, drro->drr_object, FTAG, &db));
959 		dmu_buf_will_dirty(db, tx);
960 
961 		ASSERT3U(db->db_size, >=, drro->drr_bonuslen);
962 		bcopy(data, db->db_data, drro->drr_bonuslen);
963 		if (ra->byteswap) {
964 			dmu_ot[drro->drr_bonustype].ot_byteswap(db->db_data,
965 			    drro->drr_bonuslen);
966 		}
967 		dmu_buf_rele(db, FTAG);
968 	}
969 	dmu_tx_commit(tx);
970 	return (0);
971 }
972 
973 /* ARGSUSED */
974 static int
975 restore_freeobjects(struct restorearg *ra, objset_t *os,
976     struct drr_freeobjects *drrfo)
977 {
978 	uint64_t obj;
979 
980 	if (drrfo->drr_firstobj + drrfo->drr_numobjs < drrfo->drr_firstobj)
981 		return (EINVAL);
982 
983 	for (obj = drrfo->drr_firstobj;
984 	    obj < drrfo->drr_firstobj + drrfo->drr_numobjs;
985 	    (void) dmu_object_next(os, &obj, FALSE, 0)) {
986 		int err;
987 
988 		if (dmu_object_info(os, obj, NULL) != 0)
989 			continue;
990 
991 		err = dmu_free_object(os, obj);
992 		if (err)
993 			return (err);
994 	}
995 	return (0);
996 }
997 
998 static int
999 restore_write(struct restorearg *ra, objset_t *os,
1000     struct drr_write *drrw)
1001 {
1002 	dmu_tx_t *tx;
1003 	void *data;
1004 	int err;
1005 
1006 	if (drrw->drr_offset + drrw->drr_length < drrw->drr_offset ||
1007 	    drrw->drr_type >= DMU_OT_NUMTYPES)
1008 		return (EINVAL);
1009 
1010 	data = restore_read(ra, drrw->drr_length);
1011 	if (data == NULL)
1012 		return (ra->err);
1013 
1014 	if (dmu_object_info(os, drrw->drr_object, NULL) != 0)
1015 		return (EINVAL);
1016 
1017 	tx = dmu_tx_create(os);
1018 
1019 	dmu_tx_hold_write(tx, drrw->drr_object,
1020 	    drrw->drr_offset, drrw->drr_length);
1021 	err = dmu_tx_assign(tx, TXG_WAIT);
1022 	if (err) {
1023 		dmu_tx_abort(tx);
1024 		return (err);
1025 	}
1026 	if (ra->byteswap)
1027 		dmu_ot[drrw->drr_type].ot_byteswap(data, drrw->drr_length);
1028 	dmu_write(os, drrw->drr_object,
1029 	    drrw->drr_offset, drrw->drr_length, data, tx);
1030 	dmu_tx_commit(tx);
1031 	return (0);
1032 }
1033 
1034 /*
1035  * Handle a DRR_WRITE_BYREF record.  This record is used in dedup'ed
1036  * streams to refer to a copy of the data that is already on the
1037  * system because it came in earlier in the stream.  This function
1038  * finds the earlier copy of the data, and uses that copy instead of
1039  * data from the stream to fulfill this write.
1040  */
1041 static int
1042 restore_write_byref(struct restorearg *ra, objset_t *os,
1043     struct drr_write_byref *drrwbr)
1044 {
1045 	dmu_tx_t *tx;
1046 	int err;
1047 	guid_map_entry_t gmesrch;
1048 	guid_map_entry_t *gmep;
1049 	avl_index_t	where;
1050 	objset_t *ref_os = NULL;
1051 	dmu_buf_t *dbp;
1052 
1053 	if (drrwbr->drr_offset + drrwbr->drr_length < drrwbr->drr_offset)
1054 		return (EINVAL);
1055 
1056 	/*
1057 	 * If the GUID of the referenced dataset is different from the
1058 	 * GUID of the target dataset, find the referenced dataset.
1059 	 */
1060 	if (drrwbr->drr_toguid != drrwbr->drr_refguid) {
1061 		gmesrch.guid = drrwbr->drr_refguid;
1062 		if ((gmep = avl_find(&ra->guid_to_ds_map, &gmesrch,
1063 		    &where)) == NULL) {
1064 			return (EINVAL);
1065 		}
1066 		if (dmu_objset_from_ds(gmep->gme_ds, &ref_os))
1067 			return (EINVAL);
1068 	} else {
1069 		ref_os = os;
1070 	}
1071 
1072 	if (err = dmu_buf_hold(ref_os, drrwbr->drr_refobject,
1073 	    drrwbr->drr_refoffset, FTAG, &dbp))
1074 		return (err);
1075 
1076 	tx = dmu_tx_create(os);
1077 
1078 	dmu_tx_hold_write(tx, drrwbr->drr_object,
1079 	    drrwbr->drr_offset, drrwbr->drr_length);
1080 	err = dmu_tx_assign(tx, TXG_WAIT);
1081 	if (err) {
1082 		dmu_tx_abort(tx);
1083 		return (err);
1084 	}
1085 	dmu_write(os, drrwbr->drr_object,
1086 	    drrwbr->drr_offset, drrwbr->drr_length, dbp->db_data, tx);
1087 	dmu_buf_rele(dbp, FTAG);
1088 	dmu_tx_commit(tx);
1089 	return (0);
1090 }
1091 
1092 /* ARGSUSED */
1093 static int
1094 restore_free(struct restorearg *ra, objset_t *os,
1095     struct drr_free *drrf)
1096 {
1097 	int err;
1098 
1099 	if (drrf->drr_length != -1ULL &&
1100 	    drrf->drr_offset + drrf->drr_length < drrf->drr_offset)
1101 		return (EINVAL);
1102 
1103 	if (dmu_object_info(os, drrf->drr_object, NULL) != 0)
1104 		return (EINVAL);
1105 
1106 	err = dmu_free_long_range(os, drrf->drr_object,
1107 	    drrf->drr_offset, drrf->drr_length);
1108 	return (err);
1109 }
1110 
1111 /*
1112  * NB: callers *must* call dmu_recv_end() if this succeeds.
1113  */
1114 int
1115 dmu_recv_stream(dmu_recv_cookie_t *drc, vnode_t *vp, offset_t *voffp)
1116 {
1117 	struct restorearg ra = { 0 };
1118 	dmu_replay_record_t *drr;
1119 	objset_t *os;
1120 	zio_cksum_t pcksum;
1121 	guid_map_entry_t *gmep;
1122 	int featureflags;
1123 
1124 	if (drc->drc_drrb->drr_magic == BSWAP_64(DMU_BACKUP_MAGIC))
1125 		ra.byteswap = TRUE;
1126 
1127 	{
1128 		/* compute checksum of drr_begin record */
1129 		dmu_replay_record_t *drr;
1130 		drr = kmem_zalloc(sizeof (dmu_replay_record_t), KM_SLEEP);
1131 
1132 		drr->drr_type = DRR_BEGIN;
1133 		drr->drr_u.drr_begin = *drc->drc_drrb;
1134 		if (ra.byteswap) {
1135 			fletcher_4_incremental_byteswap(drr,
1136 			    sizeof (dmu_replay_record_t), &ra.cksum);
1137 		} else {
1138 			fletcher_4_incremental_native(drr,
1139 			    sizeof (dmu_replay_record_t), &ra.cksum);
1140 		}
1141 		kmem_free(drr, sizeof (dmu_replay_record_t));
1142 	}
1143 
1144 	if (ra.byteswap) {
1145 		struct drr_begin *drrb = drc->drc_drrb;
1146 		drrb->drr_magic = BSWAP_64(drrb->drr_magic);
1147 		drrb->drr_versioninfo = BSWAP_64(drrb->drr_versioninfo);
1148 		drrb->drr_creation_time = BSWAP_64(drrb->drr_creation_time);
1149 		drrb->drr_type = BSWAP_32(drrb->drr_type);
1150 		drrb->drr_toguid = BSWAP_64(drrb->drr_toguid);
1151 		drrb->drr_fromguid = BSWAP_64(drrb->drr_fromguid);
1152 	}
1153 
1154 	ra.vp = vp;
1155 	ra.voff = *voffp;
1156 	ra.bufsize = 1<<20;
1157 	ra.buf = kmem_alloc(ra.bufsize, KM_SLEEP);
1158 
1159 	/* these were verified in dmu_recv_begin */
1160 	ASSERT(DMU_GET_STREAM_HDRTYPE(drc->drc_drrb->drr_versioninfo) ==
1161 	    DMU_SUBSTREAM);
1162 	ASSERT(drc->drc_drrb->drr_type < DMU_OST_NUMTYPES);
1163 
1164 	/*
1165 	 * Open the objset we are modifying.
1166 	 */
1167 	VERIFY(dmu_objset_from_ds(drc->drc_real_ds, &os) == 0);
1168 
1169 	ASSERT(drc->drc_real_ds->ds_phys->ds_flags & DS_FLAG_INCONSISTENT);
1170 
1171 	featureflags = DMU_GET_FEATUREFLAGS(drc->drc_drrb->drr_versioninfo);
1172 
1173 	/* if this stream is dedup'ed, set up the avl tree for guid mapping */
1174 	if (featureflags & DMU_BACKUP_FEATURE_DEDUP) {
1175 		avl_create(&ra.guid_to_ds_map, guid_compare,
1176 		    sizeof (guid_map_entry_t),
1177 		    offsetof(guid_map_entry_t, avlnode));
1178 		(void) dmu_objset_find(drc->drc_top_ds, find_ds_by_guid,
1179 		    (void *)&ra.guid_to_ds_map,
1180 		    DS_FIND_CHILDREN);
1181 	}
1182 
1183 	/*
1184 	 * Read records and process them.
1185 	 */
1186 	pcksum = ra.cksum;
1187 	while (ra.err == 0 &&
1188 	    NULL != (drr = restore_read(&ra, sizeof (*drr)))) {
1189 		if (issig(JUSTLOOKING) && issig(FORREAL)) {
1190 			ra.err = EINTR;
1191 			goto out;
1192 		}
1193 
1194 		if (ra.byteswap)
1195 			backup_byteswap(drr);
1196 
1197 		switch (drr->drr_type) {
1198 		case DRR_OBJECT:
1199 		{
1200 			/*
1201 			 * We need to make a copy of the record header,
1202 			 * because restore_{object,write} may need to
1203 			 * restore_read(), which will invalidate drr.
1204 			 */
1205 			struct drr_object drro = drr->drr_u.drr_object;
1206 			ra.err = restore_object(&ra, os, &drro);
1207 			break;
1208 		}
1209 		case DRR_FREEOBJECTS:
1210 		{
1211 			struct drr_freeobjects drrfo =
1212 			    drr->drr_u.drr_freeobjects;
1213 			ra.err = restore_freeobjects(&ra, os, &drrfo);
1214 			break;
1215 		}
1216 		case DRR_WRITE:
1217 		{
1218 			struct drr_write drrw = drr->drr_u.drr_write;
1219 			ra.err = restore_write(&ra, os, &drrw);
1220 			break;
1221 		}
1222 		case DRR_WRITE_BYREF:
1223 		{
1224 			struct drr_write_byref drrwbr =
1225 			    drr->drr_u.drr_write_byref;
1226 			ra.err = restore_write_byref(&ra, os, &drrwbr);
1227 			break;
1228 		}
1229 		case DRR_FREE:
1230 		{
1231 			struct drr_free drrf = drr->drr_u.drr_free;
1232 			ra.err = restore_free(&ra, os, &drrf);
1233 			break;
1234 		}
1235 		case DRR_END:
1236 		{
1237 			struct drr_end drre = drr->drr_u.drr_end;
1238 			/*
1239 			 * We compare against the *previous* checksum
1240 			 * value, because the stored checksum is of
1241 			 * everything before the DRR_END record.
1242 			 */
1243 			if (!ZIO_CHECKSUM_EQUAL(drre.drr_checksum, pcksum))
1244 				ra.err = ECKSUM;
1245 			goto out;
1246 		}
1247 		default:
1248 			ra.err = EINVAL;
1249 			goto out;
1250 		}
1251 		pcksum = ra.cksum;
1252 	}
1253 	ASSERT(ra.err != 0);
1254 
1255 out:
1256 	if (ra.err != 0) {
1257 		/*
1258 		 * destroy what we created, so we don't leave it in the
1259 		 * inconsistent restoring state.
1260 		 */
1261 		txg_wait_synced(drc->drc_real_ds->ds_dir->dd_pool, 0);
1262 
1263 		(void) dsl_dataset_destroy(drc->drc_real_ds, dmu_recv_tag,
1264 		    B_FALSE);
1265 		if (drc->drc_real_ds != drc->drc_logical_ds) {
1266 			mutex_exit(&drc->drc_logical_ds->ds_recvlock);
1267 			dsl_dataset_rele(drc->drc_logical_ds, dmu_recv_tag);
1268 		}
1269 	}
1270 
1271 	if (featureflags & DMU_BACKUP_FEATURE_DEDUP) {
1272 		void *cookie = NULL;
1273 
1274 		while (gmep = avl_destroy_nodes(&ra.guid_to_ds_map, &cookie)) {
1275 			dsl_dataset_rele(gmep->gme_ds, &ra.guid_to_ds_map);
1276 			kmem_free(gmep, sizeof (guid_map_entry_t));
1277 		}
1278 		avl_destroy(&ra.guid_to_ds_map);
1279 	}
1280 
1281 	kmem_free(ra.buf, ra.bufsize);
1282 	*voffp = ra.voff;
1283 	return (ra.err);
1284 }
1285 
1286 struct recvendsyncarg {
1287 	char *tosnap;
1288 	uint64_t creation_time;
1289 	uint64_t toguid;
1290 };
1291 
1292 static int
1293 recv_end_check(void *arg1, void *arg2, dmu_tx_t *tx)
1294 {
1295 	dsl_dataset_t *ds = arg1;
1296 	struct recvendsyncarg *resa = arg2;
1297 
1298 	return (dsl_dataset_snapshot_check(ds, resa->tosnap, tx));
1299 }
1300 
1301 static void
1302 recv_end_sync(void *arg1, void *arg2, cred_t *cr, dmu_tx_t *tx)
1303 {
1304 	dsl_dataset_t *ds = arg1;
1305 	struct recvendsyncarg *resa = arg2;
1306 
1307 	dsl_dataset_snapshot_sync(ds, resa->tosnap, cr, tx);
1308 
1309 	/* set snapshot's creation time and guid */
1310 	dmu_buf_will_dirty(ds->ds_prev->ds_dbuf, tx);
1311 	ds->ds_prev->ds_phys->ds_creation_time = resa->creation_time;
1312 	ds->ds_prev->ds_phys->ds_guid = resa->toguid;
1313 	ds->ds_prev->ds_phys->ds_flags &= ~DS_FLAG_INCONSISTENT;
1314 
1315 	dmu_buf_will_dirty(ds->ds_dbuf, tx);
1316 	ds->ds_phys->ds_flags &= ~DS_FLAG_INCONSISTENT;
1317 }
1318 
1319 static int
1320 dmu_recv_existing_end(dmu_recv_cookie_t *drc)
1321 {
1322 	struct recvendsyncarg resa;
1323 	dsl_dataset_t *ds = drc->drc_logical_ds;
1324 	int err;
1325 
1326 	/*
1327 	 * XXX hack; seems the ds is still dirty and dsl_pool_zil_clean()
1328 	 * expects it to have a ds_user_ptr (and zil), but clone_swap()
1329 	 * can close it.
1330 	 */
1331 	txg_wait_synced(ds->ds_dir->dd_pool, 0);
1332 
1333 	if (dsl_dataset_tryown(ds, FALSE, dmu_recv_tag)) {
1334 		err = dsl_dataset_clone_swap(drc->drc_real_ds, ds,
1335 		    drc->drc_force);
1336 		if (err)
1337 			goto out;
1338 	} else {
1339 		mutex_exit(&ds->ds_recvlock);
1340 		dsl_dataset_rele(ds, dmu_recv_tag);
1341 		(void) dsl_dataset_destroy(drc->drc_real_ds, dmu_recv_tag,
1342 		    B_FALSE);
1343 		return (EBUSY);
1344 	}
1345 
1346 	resa.creation_time = drc->drc_drrb->drr_creation_time;
1347 	resa.toguid = drc->drc_drrb->drr_toguid;
1348 	resa.tosnap = drc->drc_tosnap;
1349 
1350 	err = dsl_sync_task_do(ds->ds_dir->dd_pool,
1351 	    recv_end_check, recv_end_sync, ds, &resa, 3);
1352 	if (err) {
1353 		/* swap back */
1354 		(void) dsl_dataset_clone_swap(drc->drc_real_ds, ds, B_TRUE);
1355 	}
1356 
1357 out:
1358 	mutex_exit(&ds->ds_recvlock);
1359 	dsl_dataset_disown(ds, dmu_recv_tag);
1360 	(void) dsl_dataset_destroy(drc->drc_real_ds, dmu_recv_tag, B_FALSE);
1361 	return (err);
1362 }
1363 
1364 static int
1365 dmu_recv_new_end(dmu_recv_cookie_t *drc)
1366 {
1367 	struct recvendsyncarg resa;
1368 	dsl_dataset_t *ds = drc->drc_logical_ds;
1369 	int err;
1370 
1371 	/*
1372 	 * XXX hack; seems the ds is still dirty and dsl_pool_zil_clean()
1373 	 * expects it to have a ds_user_ptr (and zil), but clone_swap()
1374 	 * can close it.
1375 	 */
1376 	txg_wait_synced(ds->ds_dir->dd_pool, 0);
1377 
1378 	resa.creation_time = drc->drc_drrb->drr_creation_time;
1379 	resa.toguid = drc->drc_drrb->drr_toguid;
1380 	resa.tosnap = drc->drc_tosnap;
1381 
1382 	err = dsl_sync_task_do(ds->ds_dir->dd_pool,
1383 	    recv_end_check, recv_end_sync, ds, &resa, 3);
1384 	if (err) {
1385 		/* clean up the fs we just recv'd into */
1386 		(void) dsl_dataset_destroy(ds, dmu_recv_tag, B_FALSE);
1387 	} else {
1388 		/* release the hold from dmu_recv_begin */
1389 		dsl_dataset_disown(ds, dmu_recv_tag);
1390 	}
1391 	return (err);
1392 }
1393 
1394 int
1395 dmu_recv_end(dmu_recv_cookie_t *drc)
1396 {
1397 	if (drc->drc_logical_ds != drc->drc_real_ds)
1398 		return (dmu_recv_existing_end(drc));
1399 	else
1400 		return (dmu_recv_new_end(drc));
1401 }
1402