xref: /titanic_44/usr/src/uts/common/fs/zfs/dmu_send.c (revision 8339b41da2395f0525c46ceedfeb01961893ec44)
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, arc_buf_t *pbuf,
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 (dsl_read(NULL, spa, bp, pbuf,
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 (dsl_read(NULL, spa, bp, pbuf,
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 	cred_t *cr;
508 };
509 
510 /* ARGSUSED */
511 static int
512 recv_new_check(void *arg1, void *arg2, dmu_tx_t *tx)
513 {
514 	dsl_dir_t *dd = arg1;
515 	struct recvbeginsyncarg *rbsa = arg2;
516 	objset_t *mos = dd->dd_pool->dp_meta_objset;
517 	uint64_t val;
518 	int err;
519 
520 	err = zap_lookup(mos, dd->dd_phys->dd_child_dir_zapobj,
521 	    strrchr(rbsa->tofs, '/') + 1, sizeof (uint64_t), 1, &val);
522 
523 	if (err != ENOENT)
524 		return (err ? err : EEXIST);
525 
526 	if (rbsa->origin) {
527 		/* make sure it's a snap in the same pool */
528 		if (rbsa->origin->ds_dir->dd_pool != dd->dd_pool)
529 			return (EXDEV);
530 		if (!dsl_dataset_is_snapshot(rbsa->origin))
531 			return (EINVAL);
532 		if (rbsa->origin->ds_phys->ds_guid != rbsa->fromguid)
533 			return (ENODEV);
534 	}
535 
536 	return (0);
537 }
538 
539 static void
540 recv_new_sync(void *arg1, void *arg2, dmu_tx_t *tx)
541 {
542 	dsl_dir_t *dd = arg1;
543 	struct recvbeginsyncarg *rbsa = arg2;
544 	uint64_t flags = DS_FLAG_INCONSISTENT | rbsa->dsflags;
545 	uint64_t dsobj;
546 
547 	/* Create and open new dataset. */
548 	dsobj = dsl_dataset_create_sync(dd, strrchr(rbsa->tofs, '/') + 1,
549 	    rbsa->origin, flags, rbsa->cr, tx);
550 	VERIFY(0 == dsl_dataset_own_obj(dd->dd_pool, dsobj,
551 	    B_TRUE, dmu_recv_tag, &rbsa->ds));
552 
553 	if (rbsa->origin == NULL) {
554 		(void) dmu_objset_create_impl(dd->dd_pool->dp_spa,
555 		    rbsa->ds, &rbsa->ds->ds_phys->ds_bp, rbsa->type, tx);
556 	}
557 
558 	spa_history_log_internal(LOG_DS_REPLAY_FULL_SYNC,
559 	    dd->dd_pool->dp_spa, tx, "dataset = %lld", dsobj);
560 }
561 
562 /* ARGSUSED */
563 static int
564 recv_existing_check(void *arg1, void *arg2, dmu_tx_t *tx)
565 {
566 	dsl_dataset_t *ds = arg1;
567 	struct recvbeginsyncarg *rbsa = arg2;
568 	int err;
569 	uint64_t val;
570 
571 	/* must not have any changes since most recent snapshot */
572 	if (!rbsa->force && dsl_dataset_modified_since_lastsnap(ds))
573 		return (ETXTBSY);
574 
575 	if (rbsa->fromguid) {
576 		/* if incremental, most recent snapshot must match fromguid */
577 		if (ds->ds_prev == NULL)
578 			return (ENODEV);
579 
580 		/*
581 		 * most recent snapshot must match fromguid, or there are no
582 		 * changes since the fromguid one
583 		 */
584 		if (ds->ds_prev->ds_phys->ds_guid != rbsa->fromguid) {
585 			uint64_t birth = ds->ds_prev->ds_phys->ds_bp.blk_birth;
586 			uint64_t obj = ds->ds_prev->ds_phys->ds_prev_snap_obj;
587 			while (obj != 0) {
588 				dsl_dataset_t *snap;
589 				err = dsl_dataset_hold_obj(ds->ds_dir->dd_pool,
590 				    obj, FTAG, &snap);
591 				if (err)
592 					return (ENODEV);
593 				if (snap->ds_phys->ds_creation_txg < birth) {
594 					dsl_dataset_rele(snap, FTAG);
595 					return (ENODEV);
596 				}
597 				if (snap->ds_phys->ds_guid == rbsa->fromguid) {
598 					dsl_dataset_rele(snap, FTAG);
599 					break; /* it's ok */
600 				}
601 				obj = snap->ds_phys->ds_prev_snap_obj;
602 				dsl_dataset_rele(snap, FTAG);
603 			}
604 			if (obj == 0)
605 				return (ENODEV);
606 		}
607 	} else {
608 		/* if full, most recent snapshot must be $ORIGIN */
609 		if (ds->ds_phys->ds_prev_snap_txg >= TXG_INITIAL)
610 			return (ENODEV);
611 	}
612 
613 	/* temporary clone name must not exist */
614 	err = zap_lookup(ds->ds_dir->dd_pool->dp_meta_objset,
615 	    ds->ds_dir->dd_phys->dd_child_dir_zapobj,
616 	    rbsa->clonelastname, 8, 1, &val);
617 	if (err == 0)
618 		return (EEXIST);
619 	if (err != ENOENT)
620 		return (err);
621 
622 	/* new snapshot name must not exist */
623 	err = zap_lookup(ds->ds_dir->dd_pool->dp_meta_objset,
624 	    ds->ds_phys->ds_snapnames_zapobj, rbsa->tosnap, 8, 1, &val);
625 	if (err == 0)
626 		return (EEXIST);
627 	if (err != ENOENT)
628 		return (err);
629 	return (0);
630 }
631 
632 /* ARGSUSED */
633 static void
634 recv_existing_sync(void *arg1, void *arg2, dmu_tx_t *tx)
635 {
636 	dsl_dataset_t *ohds = arg1;
637 	struct recvbeginsyncarg *rbsa = arg2;
638 	dsl_pool_t *dp = ohds->ds_dir->dd_pool;
639 	dsl_dataset_t *cds;
640 	uint64_t flags = DS_FLAG_INCONSISTENT | rbsa->dsflags;
641 	uint64_t dsobj;
642 
643 	/* create and open the temporary clone */
644 	dsobj = dsl_dataset_create_sync(ohds->ds_dir, rbsa->clonelastname,
645 	    ohds->ds_prev, flags, rbsa->cr, tx);
646 	VERIFY(0 == dsl_dataset_own_obj(dp, dsobj, B_TRUE, dmu_recv_tag, &cds));
647 
648 	/*
649 	 * If we actually created a non-clone, we need to create the
650 	 * objset in our new dataset.
651 	 */
652 	if (BP_IS_HOLE(dsl_dataset_get_blkptr(cds))) {
653 		(void) dmu_objset_create_impl(dp->dp_spa,
654 		    cds, dsl_dataset_get_blkptr(cds), rbsa->type, tx);
655 	}
656 
657 	rbsa->ds = cds;
658 
659 	spa_history_log_internal(LOG_DS_REPLAY_INC_SYNC,
660 	    dp->dp_spa, tx, "dataset = %lld", dsobj);
661 }
662 
663 
664 static boolean_t
665 dmu_recv_verify_features(dsl_dataset_t *ds, struct drr_begin *drrb)
666 {
667 	int featureflags;
668 
669 	featureflags = DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo);
670 
671 	/* Verify pool version supports SA if SA_SPILL feature set */
672 	return ((featureflags & DMU_BACKUP_FEATURE_SA_SPILL) &&
673 	    (spa_version(dsl_dataset_get_spa(ds)) < SPA_VERSION_SA));
674 }
675 
676 /*
677  * NB: callers *MUST* call dmu_recv_stream() if dmu_recv_begin()
678  * succeeds; otherwise we will leak the holds on the datasets.
679  */
680 int
681 dmu_recv_begin(char *tofs, char *tosnap, char *top_ds, struct drr_begin *drrb,
682     boolean_t force, objset_t *origin, dmu_recv_cookie_t *drc)
683 {
684 	int err = 0;
685 	boolean_t byteswap;
686 	struct recvbeginsyncarg rbsa = { 0 };
687 	uint64_t versioninfo;
688 	int flags;
689 	dsl_dataset_t *ds;
690 
691 	if (drrb->drr_magic == DMU_BACKUP_MAGIC)
692 		byteswap = FALSE;
693 	else if (drrb->drr_magic == BSWAP_64(DMU_BACKUP_MAGIC))
694 		byteswap = TRUE;
695 	else
696 		return (EINVAL);
697 
698 	rbsa.tofs = tofs;
699 	rbsa.tosnap = tosnap;
700 	rbsa.origin = origin ? origin->os_dsl_dataset : NULL;
701 	rbsa.fromguid = drrb->drr_fromguid;
702 	rbsa.type = drrb->drr_type;
703 	rbsa.tag = FTAG;
704 	rbsa.dsflags = 0;
705 	rbsa.cr = CRED();
706 	versioninfo = drrb->drr_versioninfo;
707 	flags = drrb->drr_flags;
708 
709 	if (byteswap) {
710 		rbsa.type = BSWAP_32(rbsa.type);
711 		rbsa.fromguid = BSWAP_64(rbsa.fromguid);
712 		versioninfo = BSWAP_64(versioninfo);
713 		flags = BSWAP_32(flags);
714 	}
715 
716 	if (DMU_GET_STREAM_HDRTYPE(versioninfo) == DMU_COMPOUNDSTREAM ||
717 	    rbsa.type >= DMU_OST_NUMTYPES ||
718 	    ((flags & DRR_FLAG_CLONE) && origin == NULL))
719 		return (EINVAL);
720 
721 	if (flags & DRR_FLAG_CI_DATA)
722 		rbsa.dsflags = DS_FLAG_CI_DATASET;
723 
724 	bzero(drc, sizeof (dmu_recv_cookie_t));
725 	drc->drc_drrb = drrb;
726 	drc->drc_tosnap = tosnap;
727 	drc->drc_top_ds = top_ds;
728 	drc->drc_force = force;
729 
730 	/*
731 	 * Process the begin in syncing context.
732 	 */
733 
734 	/* open the dataset we are logically receiving into */
735 	err = dsl_dataset_hold(tofs, dmu_recv_tag, &ds);
736 	if (err == 0) {
737 		if (dmu_recv_verify_features(ds, drrb)) {
738 			dsl_dataset_rele(ds, dmu_recv_tag);
739 			return (ENOTSUP);
740 		}
741 		/* target fs already exists; recv into temp clone */
742 
743 		/* Can't recv a clone into an existing fs */
744 		if (flags & DRR_FLAG_CLONE) {
745 			dsl_dataset_rele(ds, dmu_recv_tag);
746 			return (EINVAL);
747 		}
748 
749 		/* must not have an incremental recv already in progress */
750 		if (!mutex_tryenter(&ds->ds_recvlock)) {
751 			dsl_dataset_rele(ds, dmu_recv_tag);
752 			return (EBUSY);
753 		}
754 
755 		/* tmp clone name is: tofs/%tosnap" */
756 		(void) snprintf(rbsa.clonelastname, sizeof (rbsa.clonelastname),
757 		    "%%%s", tosnap);
758 		rbsa.force = force;
759 		err = dsl_sync_task_do(ds->ds_dir->dd_pool,
760 		    recv_existing_check, recv_existing_sync, ds, &rbsa, 5);
761 		if (err) {
762 			mutex_exit(&ds->ds_recvlock);
763 			dsl_dataset_rele(ds, dmu_recv_tag);
764 			return (err);
765 		}
766 		drc->drc_logical_ds = ds;
767 		drc->drc_real_ds = rbsa.ds;
768 	} else if (err == ENOENT) {
769 		/* target fs does not exist; must be a full backup or clone */
770 		char *cp;
771 
772 		/*
773 		 * If it's a non-clone incremental, we are missing the
774 		 * target fs, so fail the recv.
775 		 */
776 		if (rbsa.fromguid && !(flags & DRR_FLAG_CLONE))
777 			return (ENOENT);
778 
779 		/* Open the parent of tofs */
780 		cp = strrchr(tofs, '/');
781 		*cp = '\0';
782 		err = dsl_dataset_hold(tofs, FTAG, &ds);
783 		*cp = '/';
784 		if (err)
785 			return (err);
786 
787 		if (dmu_recv_verify_features(ds, drrb)) {
788 			dsl_dataset_rele(ds, dmu_recv_tag);
789 			return (ENOTSUP);
790 		}
791 
792 		err = dsl_sync_task_do(ds->ds_dir->dd_pool,
793 		    recv_new_check, recv_new_sync, ds->ds_dir, &rbsa, 5);
794 		dsl_dataset_rele(ds, FTAG);
795 		if (err)
796 			return (err);
797 		drc->drc_logical_ds = drc->drc_real_ds = rbsa.ds;
798 		drc->drc_newfs = B_TRUE;
799 	}
800 
801 	return (err);
802 }
803 
804 struct restorearg {
805 	int err;
806 	int byteswap;
807 	vnode_t *vp;
808 	char *buf;
809 	uint64_t voff;
810 	int bufsize; /* amount of memory allocated for buf */
811 	zio_cksum_t cksum;
812 	avl_tree_t guid_to_ds_map;
813 };
814 
815 typedef struct guid_map_entry {
816 	uint64_t	guid;
817 	dsl_dataset_t	*gme_ds;
818 	avl_node_t	avlnode;
819 } guid_map_entry_t;
820 
821 static int
822 guid_compare(const void *arg1, const void *arg2)
823 {
824 	const guid_map_entry_t *gmep1 = arg1;
825 	const guid_map_entry_t *gmep2 = arg2;
826 
827 	if (gmep1->guid < gmep2->guid)
828 		return (-1);
829 	else if (gmep1->guid > gmep2->guid)
830 		return (1);
831 	return (0);
832 }
833 
834 /*
835  * This function is a callback used by dmu_objset_find() (which
836  * enumerates the object sets) to build an avl tree that maps guids
837  * to datasets.  The resulting table is used when processing DRR_WRITE_BYREF
838  * send stream records.  These records, which are used in dedup'ed
839  * streams, do not contain data themselves, but refer to a copy
840  * of the data block that has already been written because it was
841  * earlier in the stream.  That previous copy is identified by the
842  * guid of the dataset with the referenced data.
843  */
844 int
845 find_ds_by_guid(const char *name, void *arg)
846 {
847 	avl_tree_t *guid_map = arg;
848 	dsl_dataset_t *ds, *snapds;
849 	guid_map_entry_t *gmep;
850 	dsl_pool_t *dp;
851 	int err;
852 	uint64_t lastobj, firstobj;
853 
854 	if (dsl_dataset_hold(name, FTAG, &ds) != 0)
855 		return (0);
856 
857 	dp = ds->ds_dir->dd_pool;
858 	rw_enter(&dp->dp_config_rwlock, RW_READER);
859 	firstobj = ds->ds_dir->dd_phys->dd_origin_obj;
860 	lastobj = ds->ds_phys->ds_prev_snap_obj;
861 
862 	while (lastobj != firstobj) {
863 		err = dsl_dataset_hold_obj(dp, lastobj, guid_map, &snapds);
864 		if (err) {
865 			/*
866 			 * Skip this snapshot and move on. It's not
867 			 * clear why this would ever happen, but the
868 			 * remainder of the snapshot streadm can be
869 			 * processed.
870 			 */
871 			rw_exit(&dp->dp_config_rwlock);
872 			dsl_dataset_rele(ds, FTAG);
873 			return (0);
874 		}
875 
876 		gmep = kmem_alloc(sizeof (guid_map_entry_t), KM_SLEEP);
877 		gmep->guid = snapds->ds_phys->ds_guid;
878 		gmep->gme_ds = snapds;
879 		avl_add(guid_map, gmep);
880 		lastobj = snapds->ds_phys->ds_prev_snap_obj;
881 	}
882 
883 	rw_exit(&dp->dp_config_rwlock);
884 	dsl_dataset_rele(ds, FTAG);
885 
886 	return (0);
887 }
888 
889 static void *
890 restore_read(struct restorearg *ra, int len)
891 {
892 	void *rv;
893 	int done = 0;
894 
895 	/* some things will require 8-byte alignment, so everything must */
896 	ASSERT3U(len % 8, ==, 0);
897 
898 	while (done < len) {
899 		ssize_t resid;
900 
901 		ra->err = vn_rdwr(UIO_READ, ra->vp,
902 		    (caddr_t)ra->buf + done, len - done,
903 		    ra->voff, UIO_SYSSPACE, FAPPEND,
904 		    RLIM64_INFINITY, CRED(), &resid);
905 
906 		if (resid == len - done)
907 			ra->err = EINVAL;
908 		ra->voff += len - done - resid;
909 		done = len - resid;
910 		if (ra->err)
911 			return (NULL);
912 	}
913 
914 	ASSERT3U(done, ==, len);
915 	rv = ra->buf;
916 	if (ra->byteswap)
917 		fletcher_4_incremental_byteswap(rv, len, &ra->cksum);
918 	else
919 		fletcher_4_incremental_native(rv, len, &ra->cksum);
920 	return (rv);
921 }
922 
923 static void
924 backup_byteswap(dmu_replay_record_t *drr)
925 {
926 #define	DO64(X) (drr->drr_u.X = BSWAP_64(drr->drr_u.X))
927 #define	DO32(X) (drr->drr_u.X = BSWAP_32(drr->drr_u.X))
928 	drr->drr_type = BSWAP_32(drr->drr_type);
929 	drr->drr_payloadlen = BSWAP_32(drr->drr_payloadlen);
930 	switch (drr->drr_type) {
931 	case DRR_BEGIN:
932 		DO64(drr_begin.drr_magic);
933 		DO64(drr_begin.drr_versioninfo);
934 		DO64(drr_begin.drr_creation_time);
935 		DO32(drr_begin.drr_type);
936 		DO32(drr_begin.drr_flags);
937 		DO64(drr_begin.drr_toguid);
938 		DO64(drr_begin.drr_fromguid);
939 		break;
940 	case DRR_OBJECT:
941 		DO64(drr_object.drr_object);
942 		/* DO64(drr_object.drr_allocation_txg); */
943 		DO32(drr_object.drr_type);
944 		DO32(drr_object.drr_bonustype);
945 		DO32(drr_object.drr_blksz);
946 		DO32(drr_object.drr_bonuslen);
947 		DO64(drr_object.drr_toguid);
948 		break;
949 	case DRR_FREEOBJECTS:
950 		DO64(drr_freeobjects.drr_firstobj);
951 		DO64(drr_freeobjects.drr_numobjs);
952 		DO64(drr_freeobjects.drr_toguid);
953 		break;
954 	case DRR_WRITE:
955 		DO64(drr_write.drr_object);
956 		DO32(drr_write.drr_type);
957 		DO64(drr_write.drr_offset);
958 		DO64(drr_write.drr_length);
959 		DO64(drr_write.drr_toguid);
960 		DO64(drr_write.drr_key.ddk_cksum.zc_word[0]);
961 		DO64(drr_write.drr_key.ddk_cksum.zc_word[1]);
962 		DO64(drr_write.drr_key.ddk_cksum.zc_word[2]);
963 		DO64(drr_write.drr_key.ddk_cksum.zc_word[3]);
964 		DO64(drr_write.drr_key.ddk_prop);
965 		break;
966 	case DRR_WRITE_BYREF:
967 		DO64(drr_write_byref.drr_object);
968 		DO64(drr_write_byref.drr_offset);
969 		DO64(drr_write_byref.drr_length);
970 		DO64(drr_write_byref.drr_toguid);
971 		DO64(drr_write_byref.drr_refguid);
972 		DO64(drr_write_byref.drr_refobject);
973 		DO64(drr_write_byref.drr_refoffset);
974 		DO64(drr_write_byref.drr_key.ddk_cksum.zc_word[0]);
975 		DO64(drr_write_byref.drr_key.ddk_cksum.zc_word[1]);
976 		DO64(drr_write_byref.drr_key.ddk_cksum.zc_word[2]);
977 		DO64(drr_write_byref.drr_key.ddk_cksum.zc_word[3]);
978 		DO64(drr_write_byref.drr_key.ddk_prop);
979 		break;
980 	case DRR_FREE:
981 		DO64(drr_free.drr_object);
982 		DO64(drr_free.drr_offset);
983 		DO64(drr_free.drr_length);
984 		DO64(drr_free.drr_toguid);
985 		break;
986 	case DRR_SPILL:
987 		DO64(drr_spill.drr_object);
988 		DO64(drr_spill.drr_length);
989 		DO64(drr_spill.drr_toguid);
990 		break;
991 	case DRR_END:
992 		DO64(drr_end.drr_checksum.zc_word[0]);
993 		DO64(drr_end.drr_checksum.zc_word[1]);
994 		DO64(drr_end.drr_checksum.zc_word[2]);
995 		DO64(drr_end.drr_checksum.zc_word[3]);
996 		DO64(drr_end.drr_toguid);
997 		break;
998 	}
999 #undef DO64
1000 #undef DO32
1001 }
1002 
1003 static int
1004 restore_object(struct restorearg *ra, objset_t *os, struct drr_object *drro)
1005 {
1006 	int err;
1007 	dmu_tx_t *tx;
1008 	void *data = NULL;
1009 
1010 	if (drro->drr_type == DMU_OT_NONE ||
1011 	    drro->drr_type >= DMU_OT_NUMTYPES ||
1012 	    drro->drr_bonustype >= DMU_OT_NUMTYPES ||
1013 	    drro->drr_checksumtype >= ZIO_CHECKSUM_FUNCTIONS ||
1014 	    drro->drr_compress >= ZIO_COMPRESS_FUNCTIONS ||
1015 	    P2PHASE(drro->drr_blksz, SPA_MINBLOCKSIZE) ||
1016 	    drro->drr_blksz < SPA_MINBLOCKSIZE ||
1017 	    drro->drr_blksz > SPA_MAXBLOCKSIZE ||
1018 	    drro->drr_bonuslen > DN_MAX_BONUSLEN) {
1019 		return (EINVAL);
1020 	}
1021 
1022 	err = dmu_object_info(os, drro->drr_object, NULL);
1023 
1024 	if (err != 0 && err != ENOENT)
1025 		return (EINVAL);
1026 
1027 	if (drro->drr_bonuslen) {
1028 		data = restore_read(ra, P2ROUNDUP(drro->drr_bonuslen, 8));
1029 		if (ra->err)
1030 			return (ra->err);
1031 	}
1032 
1033 	if (err == ENOENT) {
1034 		/* currently free, want to be allocated */
1035 		tx = dmu_tx_create(os);
1036 		dmu_tx_hold_bonus(tx, DMU_NEW_OBJECT);
1037 		err = dmu_tx_assign(tx, TXG_WAIT);
1038 		if (err) {
1039 			dmu_tx_abort(tx);
1040 			return (err);
1041 		}
1042 		err = dmu_object_claim(os, drro->drr_object,
1043 		    drro->drr_type, drro->drr_blksz,
1044 		    drro->drr_bonustype, drro->drr_bonuslen, tx);
1045 		dmu_tx_commit(tx);
1046 	} else {
1047 		/* currently allocated, want to be allocated */
1048 		err = dmu_object_reclaim(os, drro->drr_object,
1049 		    drro->drr_type, drro->drr_blksz,
1050 		    drro->drr_bonustype, drro->drr_bonuslen);
1051 	}
1052 	if (err) {
1053 		return (EINVAL);
1054 	}
1055 
1056 	tx = dmu_tx_create(os);
1057 	dmu_tx_hold_bonus(tx, drro->drr_object);
1058 	err = dmu_tx_assign(tx, TXG_WAIT);
1059 	if (err) {
1060 		dmu_tx_abort(tx);
1061 		return (err);
1062 	}
1063 
1064 	dmu_object_set_checksum(os, drro->drr_object, drro->drr_checksumtype,
1065 	    tx);
1066 	dmu_object_set_compress(os, drro->drr_object, drro->drr_compress, tx);
1067 
1068 	if (data != NULL) {
1069 		dmu_buf_t *db;
1070 
1071 		VERIFY(0 == dmu_bonus_hold(os, drro->drr_object, FTAG, &db));
1072 		dmu_buf_will_dirty(db, tx);
1073 
1074 		ASSERT3U(db->db_size, >=, drro->drr_bonuslen);
1075 		bcopy(data, db->db_data, drro->drr_bonuslen);
1076 		if (ra->byteswap) {
1077 			dmu_ot[drro->drr_bonustype].ot_byteswap(db->db_data,
1078 			    drro->drr_bonuslen);
1079 		}
1080 		dmu_buf_rele(db, FTAG);
1081 	}
1082 	dmu_tx_commit(tx);
1083 	return (0);
1084 }
1085 
1086 /* ARGSUSED */
1087 static int
1088 restore_freeobjects(struct restorearg *ra, objset_t *os,
1089     struct drr_freeobjects *drrfo)
1090 {
1091 	uint64_t obj;
1092 
1093 	if (drrfo->drr_firstobj + drrfo->drr_numobjs < drrfo->drr_firstobj)
1094 		return (EINVAL);
1095 
1096 	for (obj = drrfo->drr_firstobj;
1097 	    obj < drrfo->drr_firstobj + drrfo->drr_numobjs;
1098 	    (void) dmu_object_next(os, &obj, FALSE, 0)) {
1099 		int err;
1100 
1101 		if (dmu_object_info(os, obj, NULL) != 0)
1102 			continue;
1103 
1104 		err = dmu_free_object(os, obj);
1105 		if (err)
1106 			return (err);
1107 	}
1108 	return (0);
1109 }
1110 
1111 static int
1112 restore_write(struct restorearg *ra, objset_t *os,
1113     struct drr_write *drrw)
1114 {
1115 	dmu_tx_t *tx;
1116 	void *data;
1117 	int err;
1118 
1119 	if (drrw->drr_offset + drrw->drr_length < drrw->drr_offset ||
1120 	    drrw->drr_type >= DMU_OT_NUMTYPES)
1121 		return (EINVAL);
1122 
1123 	data = restore_read(ra, drrw->drr_length);
1124 	if (data == NULL)
1125 		return (ra->err);
1126 
1127 	if (dmu_object_info(os, drrw->drr_object, NULL) != 0)
1128 		return (EINVAL);
1129 
1130 	tx = dmu_tx_create(os);
1131 
1132 	dmu_tx_hold_write(tx, drrw->drr_object,
1133 	    drrw->drr_offset, drrw->drr_length);
1134 	err = dmu_tx_assign(tx, TXG_WAIT);
1135 	if (err) {
1136 		dmu_tx_abort(tx);
1137 		return (err);
1138 	}
1139 	if (ra->byteswap)
1140 		dmu_ot[drrw->drr_type].ot_byteswap(data, drrw->drr_length);
1141 	dmu_write(os, drrw->drr_object,
1142 	    drrw->drr_offset, drrw->drr_length, data, tx);
1143 	dmu_tx_commit(tx);
1144 	return (0);
1145 }
1146 
1147 /*
1148  * Handle a DRR_WRITE_BYREF record.  This record is used in dedup'ed
1149  * streams to refer to a copy of the data that is already on the
1150  * system because it came in earlier in the stream.  This function
1151  * finds the earlier copy of the data, and uses that copy instead of
1152  * data from the stream to fulfill this write.
1153  */
1154 static int
1155 restore_write_byref(struct restorearg *ra, objset_t *os,
1156     struct drr_write_byref *drrwbr)
1157 {
1158 	dmu_tx_t *tx;
1159 	int err;
1160 	guid_map_entry_t gmesrch;
1161 	guid_map_entry_t *gmep;
1162 	avl_index_t	where;
1163 	objset_t *ref_os = NULL;
1164 	dmu_buf_t *dbp;
1165 
1166 	if (drrwbr->drr_offset + drrwbr->drr_length < drrwbr->drr_offset)
1167 		return (EINVAL);
1168 
1169 	/*
1170 	 * If the GUID of the referenced dataset is different from the
1171 	 * GUID of the target dataset, find the referenced dataset.
1172 	 */
1173 	if (drrwbr->drr_toguid != drrwbr->drr_refguid) {
1174 		gmesrch.guid = drrwbr->drr_refguid;
1175 		if ((gmep = avl_find(&ra->guid_to_ds_map, &gmesrch,
1176 		    &where)) == NULL) {
1177 			return (EINVAL);
1178 		}
1179 		if (dmu_objset_from_ds(gmep->gme_ds, &ref_os))
1180 			return (EINVAL);
1181 	} else {
1182 		ref_os = os;
1183 	}
1184 
1185 	if (err = dmu_buf_hold(ref_os, drrwbr->drr_refobject,
1186 	    drrwbr->drr_refoffset, FTAG, &dbp, DMU_READ_PREFETCH))
1187 		return (err);
1188 
1189 	tx = dmu_tx_create(os);
1190 
1191 	dmu_tx_hold_write(tx, drrwbr->drr_object,
1192 	    drrwbr->drr_offset, drrwbr->drr_length);
1193 	err = dmu_tx_assign(tx, TXG_WAIT);
1194 	if (err) {
1195 		dmu_tx_abort(tx);
1196 		return (err);
1197 	}
1198 	dmu_write(os, drrwbr->drr_object,
1199 	    drrwbr->drr_offset, drrwbr->drr_length, dbp->db_data, tx);
1200 	dmu_buf_rele(dbp, FTAG);
1201 	dmu_tx_commit(tx);
1202 	return (0);
1203 }
1204 
1205 static int
1206 restore_spill(struct restorearg *ra, objset_t *os, struct drr_spill *drrs)
1207 {
1208 	dmu_tx_t *tx;
1209 	void *data;
1210 	dmu_buf_t *db, *db_spill;
1211 	int err;
1212 
1213 	if (drrs->drr_length < SPA_MINBLOCKSIZE ||
1214 	    drrs->drr_length > SPA_MAXBLOCKSIZE)
1215 		return (EINVAL);
1216 
1217 	data = restore_read(ra, drrs->drr_length);
1218 	if (data == NULL)
1219 		return (ra->err);
1220 
1221 	if (dmu_object_info(os, drrs->drr_object, NULL) != 0)
1222 		return (EINVAL);
1223 
1224 	VERIFY(0 == dmu_bonus_hold(os, drrs->drr_object, FTAG, &db));
1225 	if ((err = dmu_spill_hold_by_bonus(db, FTAG, &db_spill)) != 0) {
1226 		dmu_buf_rele(db, FTAG);
1227 		return (err);
1228 	}
1229 
1230 	tx = dmu_tx_create(os);
1231 
1232 	dmu_tx_hold_spill(tx, db->db_object);
1233 
1234 	err = dmu_tx_assign(tx, TXG_WAIT);
1235 	if (err) {
1236 		dmu_buf_rele(db, FTAG);
1237 		dmu_buf_rele(db_spill, FTAG);
1238 		dmu_tx_abort(tx);
1239 		return (err);
1240 	}
1241 	dmu_buf_will_dirty(db_spill, tx);
1242 
1243 	if (db_spill->db_size < drrs->drr_length)
1244 		VERIFY(0 == dbuf_spill_set_blksz(db_spill,
1245 		    drrs->drr_length, tx));
1246 	bcopy(data, db_spill->db_data, drrs->drr_length);
1247 
1248 	dmu_buf_rele(db, FTAG);
1249 	dmu_buf_rele(db_spill, FTAG);
1250 
1251 	dmu_tx_commit(tx);
1252 	return (0);
1253 }
1254 
1255 /* ARGSUSED */
1256 static int
1257 restore_free(struct restorearg *ra, objset_t *os,
1258     struct drr_free *drrf)
1259 {
1260 	int err;
1261 
1262 	if (drrf->drr_length != -1ULL &&
1263 	    drrf->drr_offset + drrf->drr_length < drrf->drr_offset)
1264 		return (EINVAL);
1265 
1266 	if (dmu_object_info(os, drrf->drr_object, NULL) != 0)
1267 		return (EINVAL);
1268 
1269 	err = dmu_free_long_range(os, drrf->drr_object,
1270 	    drrf->drr_offset, drrf->drr_length);
1271 	return (err);
1272 }
1273 
1274 /*
1275  * NB: callers *must* call dmu_recv_end() if this succeeds.
1276  */
1277 int
1278 dmu_recv_stream(dmu_recv_cookie_t *drc, vnode_t *vp, offset_t *voffp)
1279 {
1280 	struct restorearg ra = { 0 };
1281 	dmu_replay_record_t *drr;
1282 	objset_t *os;
1283 	zio_cksum_t pcksum;
1284 	guid_map_entry_t *gmep;
1285 	int featureflags;
1286 
1287 	if (drc->drc_drrb->drr_magic == BSWAP_64(DMU_BACKUP_MAGIC))
1288 		ra.byteswap = TRUE;
1289 
1290 	{
1291 		/* compute checksum of drr_begin record */
1292 		dmu_replay_record_t *drr;
1293 		drr = kmem_zalloc(sizeof (dmu_replay_record_t), KM_SLEEP);
1294 
1295 		drr->drr_type = DRR_BEGIN;
1296 		drr->drr_u.drr_begin = *drc->drc_drrb;
1297 		if (ra.byteswap) {
1298 			fletcher_4_incremental_byteswap(drr,
1299 			    sizeof (dmu_replay_record_t), &ra.cksum);
1300 		} else {
1301 			fletcher_4_incremental_native(drr,
1302 			    sizeof (dmu_replay_record_t), &ra.cksum);
1303 		}
1304 		kmem_free(drr, sizeof (dmu_replay_record_t));
1305 	}
1306 
1307 	if (ra.byteswap) {
1308 		struct drr_begin *drrb = drc->drc_drrb;
1309 		drrb->drr_magic = BSWAP_64(drrb->drr_magic);
1310 		drrb->drr_versioninfo = BSWAP_64(drrb->drr_versioninfo);
1311 		drrb->drr_creation_time = BSWAP_64(drrb->drr_creation_time);
1312 		drrb->drr_type = BSWAP_32(drrb->drr_type);
1313 		drrb->drr_toguid = BSWAP_64(drrb->drr_toguid);
1314 		drrb->drr_fromguid = BSWAP_64(drrb->drr_fromguid);
1315 	}
1316 
1317 	ra.vp = vp;
1318 	ra.voff = *voffp;
1319 	ra.bufsize = 1<<20;
1320 	ra.buf = kmem_alloc(ra.bufsize, KM_SLEEP);
1321 
1322 	/* these were verified in dmu_recv_begin */
1323 	ASSERT(DMU_GET_STREAM_HDRTYPE(drc->drc_drrb->drr_versioninfo) ==
1324 	    DMU_SUBSTREAM);
1325 	ASSERT(drc->drc_drrb->drr_type < DMU_OST_NUMTYPES);
1326 
1327 	/*
1328 	 * Open the objset we are modifying.
1329 	 */
1330 	VERIFY(dmu_objset_from_ds(drc->drc_real_ds, &os) == 0);
1331 
1332 	ASSERT(drc->drc_real_ds->ds_phys->ds_flags & DS_FLAG_INCONSISTENT);
1333 
1334 	featureflags = DMU_GET_FEATUREFLAGS(drc->drc_drrb->drr_versioninfo);
1335 
1336 	/* if this stream is dedup'ed, set up the avl tree for guid mapping */
1337 	if (featureflags & DMU_BACKUP_FEATURE_DEDUP) {
1338 		avl_create(&ra.guid_to_ds_map, guid_compare,
1339 		    sizeof (guid_map_entry_t),
1340 		    offsetof(guid_map_entry_t, avlnode));
1341 		(void) dmu_objset_find(drc->drc_top_ds, find_ds_by_guid,
1342 		    (void *)&ra.guid_to_ds_map,
1343 		    DS_FIND_CHILDREN);
1344 	}
1345 
1346 	/*
1347 	 * Read records and process them.
1348 	 */
1349 	pcksum = ra.cksum;
1350 	while (ra.err == 0 &&
1351 	    NULL != (drr = restore_read(&ra, sizeof (*drr)))) {
1352 		if (issig(JUSTLOOKING) && issig(FORREAL)) {
1353 			ra.err = EINTR;
1354 			goto out;
1355 		}
1356 
1357 		if (ra.byteswap)
1358 			backup_byteswap(drr);
1359 
1360 		switch (drr->drr_type) {
1361 		case DRR_OBJECT:
1362 		{
1363 			/*
1364 			 * We need to make a copy of the record header,
1365 			 * because restore_{object,write} may need to
1366 			 * restore_read(), which will invalidate drr.
1367 			 */
1368 			struct drr_object drro = drr->drr_u.drr_object;
1369 			ra.err = restore_object(&ra, os, &drro);
1370 			break;
1371 		}
1372 		case DRR_FREEOBJECTS:
1373 		{
1374 			struct drr_freeobjects drrfo =
1375 			    drr->drr_u.drr_freeobjects;
1376 			ra.err = restore_freeobjects(&ra, os, &drrfo);
1377 			break;
1378 		}
1379 		case DRR_WRITE:
1380 		{
1381 			struct drr_write drrw = drr->drr_u.drr_write;
1382 			ra.err = restore_write(&ra, os, &drrw);
1383 			break;
1384 		}
1385 		case DRR_WRITE_BYREF:
1386 		{
1387 			struct drr_write_byref drrwbr =
1388 			    drr->drr_u.drr_write_byref;
1389 			ra.err = restore_write_byref(&ra, os, &drrwbr);
1390 			break;
1391 		}
1392 		case DRR_FREE:
1393 		{
1394 			struct drr_free drrf = drr->drr_u.drr_free;
1395 			ra.err = restore_free(&ra, os, &drrf);
1396 			break;
1397 		}
1398 		case DRR_END:
1399 		{
1400 			struct drr_end drre = drr->drr_u.drr_end;
1401 			/*
1402 			 * We compare against the *previous* checksum
1403 			 * value, because the stored checksum is of
1404 			 * everything before the DRR_END record.
1405 			 */
1406 			if (!ZIO_CHECKSUM_EQUAL(drre.drr_checksum, pcksum))
1407 				ra.err = ECKSUM;
1408 			goto out;
1409 		}
1410 		case DRR_SPILL:
1411 		{
1412 			struct drr_spill drrs = drr->drr_u.drr_spill;
1413 			ra.err = restore_spill(&ra, os, &drrs);
1414 			break;
1415 		}
1416 		default:
1417 			ra.err = EINVAL;
1418 			goto out;
1419 		}
1420 		pcksum = ra.cksum;
1421 	}
1422 	ASSERT(ra.err != 0);
1423 
1424 out:
1425 	if (ra.err != 0) {
1426 		/*
1427 		 * destroy what we created, so we don't leave it in the
1428 		 * inconsistent restoring state.
1429 		 */
1430 		txg_wait_synced(drc->drc_real_ds->ds_dir->dd_pool, 0);
1431 
1432 		(void) dsl_dataset_destroy(drc->drc_real_ds, dmu_recv_tag,
1433 		    B_FALSE);
1434 		if (drc->drc_real_ds != drc->drc_logical_ds) {
1435 			mutex_exit(&drc->drc_logical_ds->ds_recvlock);
1436 			dsl_dataset_rele(drc->drc_logical_ds, dmu_recv_tag);
1437 		}
1438 	}
1439 
1440 	if (featureflags & DMU_BACKUP_FEATURE_DEDUP) {
1441 		void *cookie = NULL;
1442 
1443 		while (gmep = avl_destroy_nodes(&ra.guid_to_ds_map, &cookie)) {
1444 			dsl_dataset_rele(gmep->gme_ds, &ra.guid_to_ds_map);
1445 			kmem_free(gmep, sizeof (guid_map_entry_t));
1446 		}
1447 		avl_destroy(&ra.guid_to_ds_map);
1448 	}
1449 
1450 	kmem_free(ra.buf, ra.bufsize);
1451 	*voffp = ra.voff;
1452 	return (ra.err);
1453 }
1454 
1455 struct recvendsyncarg {
1456 	char *tosnap;
1457 	uint64_t creation_time;
1458 	uint64_t toguid;
1459 };
1460 
1461 static int
1462 recv_end_check(void *arg1, void *arg2, dmu_tx_t *tx)
1463 {
1464 	dsl_dataset_t *ds = arg1;
1465 	struct recvendsyncarg *resa = arg2;
1466 
1467 	return (dsl_dataset_snapshot_check(ds, resa->tosnap, tx));
1468 }
1469 
1470 static void
1471 recv_end_sync(void *arg1, void *arg2, dmu_tx_t *tx)
1472 {
1473 	dsl_dataset_t *ds = arg1;
1474 	struct recvendsyncarg *resa = arg2;
1475 
1476 	dsl_dataset_snapshot_sync(ds, resa->tosnap, tx);
1477 
1478 	/* set snapshot's creation time and guid */
1479 	dmu_buf_will_dirty(ds->ds_prev->ds_dbuf, tx);
1480 	ds->ds_prev->ds_phys->ds_creation_time = resa->creation_time;
1481 	ds->ds_prev->ds_phys->ds_guid = resa->toguid;
1482 	ds->ds_prev->ds_phys->ds_flags &= ~DS_FLAG_INCONSISTENT;
1483 
1484 	dmu_buf_will_dirty(ds->ds_dbuf, tx);
1485 	ds->ds_phys->ds_flags &= ~DS_FLAG_INCONSISTENT;
1486 }
1487 
1488 static int
1489 dmu_recv_existing_end(dmu_recv_cookie_t *drc)
1490 {
1491 	struct recvendsyncarg resa;
1492 	dsl_dataset_t *ds = drc->drc_logical_ds;
1493 	int err;
1494 
1495 	/*
1496 	 * XXX hack; seems the ds is still dirty and dsl_pool_zil_clean()
1497 	 * expects it to have a ds_user_ptr (and zil), but clone_swap()
1498 	 * can close it.
1499 	 */
1500 	txg_wait_synced(ds->ds_dir->dd_pool, 0);
1501 
1502 	if (dsl_dataset_tryown(ds, FALSE, dmu_recv_tag)) {
1503 		err = dsl_dataset_clone_swap(drc->drc_real_ds, ds,
1504 		    drc->drc_force);
1505 		if (err)
1506 			goto out;
1507 	} else {
1508 		mutex_exit(&ds->ds_recvlock);
1509 		dsl_dataset_rele(ds, dmu_recv_tag);
1510 		(void) dsl_dataset_destroy(drc->drc_real_ds, dmu_recv_tag,
1511 		    B_FALSE);
1512 		return (EBUSY);
1513 	}
1514 
1515 	resa.creation_time = drc->drc_drrb->drr_creation_time;
1516 	resa.toguid = drc->drc_drrb->drr_toguid;
1517 	resa.tosnap = drc->drc_tosnap;
1518 
1519 	err = dsl_sync_task_do(ds->ds_dir->dd_pool,
1520 	    recv_end_check, recv_end_sync, ds, &resa, 3);
1521 	if (err) {
1522 		/* swap back */
1523 		(void) dsl_dataset_clone_swap(drc->drc_real_ds, ds, B_TRUE);
1524 	}
1525 
1526 out:
1527 	mutex_exit(&ds->ds_recvlock);
1528 	dsl_dataset_disown(ds, dmu_recv_tag);
1529 	(void) dsl_dataset_destroy(drc->drc_real_ds, dmu_recv_tag, B_FALSE);
1530 	return (err);
1531 }
1532 
1533 static int
1534 dmu_recv_new_end(dmu_recv_cookie_t *drc)
1535 {
1536 	struct recvendsyncarg resa;
1537 	dsl_dataset_t *ds = drc->drc_logical_ds;
1538 	int err;
1539 
1540 	/*
1541 	 * XXX hack; seems the ds is still dirty and dsl_pool_zil_clean()
1542 	 * expects it to have a ds_user_ptr (and zil), but clone_swap()
1543 	 * can close it.
1544 	 */
1545 	txg_wait_synced(ds->ds_dir->dd_pool, 0);
1546 
1547 	resa.creation_time = drc->drc_drrb->drr_creation_time;
1548 	resa.toguid = drc->drc_drrb->drr_toguid;
1549 	resa.tosnap = drc->drc_tosnap;
1550 
1551 	err = dsl_sync_task_do(ds->ds_dir->dd_pool,
1552 	    recv_end_check, recv_end_sync, ds, &resa, 3);
1553 	if (err) {
1554 		/* clean up the fs we just recv'd into */
1555 		(void) dsl_dataset_destroy(ds, dmu_recv_tag, B_FALSE);
1556 	} else {
1557 		/* release the hold from dmu_recv_begin */
1558 		dsl_dataset_disown(ds, dmu_recv_tag);
1559 	}
1560 	return (err);
1561 }
1562 
1563 int
1564 dmu_recv_end(dmu_recv_cookie_t *drc)
1565 {
1566 	if (drc->drc_logical_ds != drc->drc_real_ds)
1567 		return (dmu_recv_existing_end(drc));
1568 	else
1569 		return (dmu_recv_new_end(drc));
1570 }
1571