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