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