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