xref: /netbsd-src/external/cddl/osnet/dist/uts/common/fs/zfs/dmu_send.c (revision b7f32ae1dea5493a3c051283d277611768e93203)
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 2011 Nexenta Systems, Inc. All rights reserved.
24  * Copyright (c) 2011, 2015 by Delphix. All rights reserved.
25  * Copyright (c) 2014, Joyent, Inc. All rights reserved.
26  * Copyright (c) 2012, Martin Matuska <mm@FreeBSD.org>. All rights reserved.
27  * Copyright 2014 HybridCluster. All rights reserved.
28  * Copyright 2016 RackTop Systems.
29  * Copyright (c) 2014 Integros [integros.com]
30  */
31 
32 #include <sys/dmu.h>
33 #include <sys/dmu_impl.h>
34 #include <sys/dmu_tx.h>
35 #include <sys/dbuf.h>
36 #include <sys/dnode.h>
37 #include <sys/zfs_context.h>
38 #include <sys/dmu_objset.h>
39 #include <sys/dmu_traverse.h>
40 #include <sys/dsl_dataset.h>
41 #include <sys/dsl_dir.h>
42 #include <sys/dsl_prop.h>
43 #include <sys/dsl_pool.h>
44 #include <sys/dsl_synctask.h>
45 #include <sys/zfs_ioctl.h>
46 #include <sys/zap.h>
47 #include <sys/zio_checksum.h>
48 #include <sys/zfs_znode.h>
49 #include <zfs_fletcher.h>
50 #include <sys/avl.h>
51 #include <sys/ddt.h>
52 #include <sys/zfs_onexit.h>
53 #include <sys/dmu_send.h>
54 #include <sys/dsl_destroy.h>
55 #include <sys/blkptr.h>
56 #include <sys/dsl_bookmark.h>
57 #include <sys/zfeature.h>
58 #include <sys/bqueue.h>
59 
60 #ifdef __FreeBSD__
61 #undef dump_write
62 #define dump_write dmu_dump_write
63 #endif
64 
65 #ifdef __NetBSD__
66 #ifdef _KERNEL
67 #define FOF_OFFSET FOF_UPDATE_OFFSET
68 #define td_ucred l_cred
69 #define bwillwrite() /* nothing */
70 
71 static int
fo_write(struct file * fp,struct uio * uio,cred_t * cred,int flags,kthread_t * thr)72 fo_write(struct file *fp, struct uio *uio, cred_t *cred, int flags, kthread_t *thr)
73 {
74 
75 	if (fp->f_type == DTYPE_VNODE)
76 		flags |= FOF_UPDATE_OFFSET;
77 	return (*fp->f_ops->fo_write)(fp, &fp->f_offset, uio, cred, flags);
78 }
79 
80 static int
fo_read(struct file * fp,struct uio * uio,cred_t * cred,int flags,kthread_t * thr)81 fo_read(struct file *fp, struct uio *uio, cred_t *cred, int flags, kthread_t *thr)
82 {
83 
84 	if (fp->f_type == DTYPE_VNODE)
85 		flags |= FOF_UPDATE_OFFSET;
86 	return (*fp->f_ops->fo_read)(fp, &fp->f_offset, uio, cred, flags);
87 }
88 #endif
89 #endif
90 
91 /* Set this tunable to TRUE to replace corrupt data with 0x2f5baddb10c */
92 int zfs_send_corrupt_data = B_FALSE;
93 int zfs_send_queue_length = 16 * 1024 * 1024;
94 int zfs_recv_queue_length = 16 * 1024 * 1024;
95 /* Set this tunable to FALSE to disable setting of DRR_FLAG_FREERECORDS */
96 int zfs_send_set_freerecords_bit = B_TRUE;
97 
98 #ifdef _KERNEL
99 TUNABLE_INT("vfs.zfs.send_set_freerecords_bit", &zfs_send_set_freerecords_bit);
100 #endif
101 
102 static char *dmu_recv_tag = "dmu_recv_tag";
103 const char *recv_clone_name = "%recv";
104 
105 #define	BP_SPAN(datablkszsec, indblkshift, level) \
106 	(((uint64_t)datablkszsec) << (SPA_MINBLOCKSHIFT + \
107 	(level) * (indblkshift - SPA_BLKPTRSHIFT)))
108 
109 static void byteswap_record(dmu_replay_record_t *drr);
110 
111 struct send_thread_arg {
112 	bqueue_t	q;
113 	dsl_dataset_t	*ds;		/* Dataset to traverse */
114 	uint64_t	fromtxg;	/* Traverse from this txg */
115 	int		flags;		/* flags to pass to traverse_dataset */
116 	int		error_code;
117 	boolean_t	cancel;
118 	zbookmark_phys_t resume;
119 };
120 
121 struct send_block_record {
122 	boolean_t		eos_marker; /* Marks the end of the stream */
123 	blkptr_t		bp;
124 	zbookmark_phys_t	zb;
125 	uint8_t			indblkshift;
126 	uint16_t		datablkszsec;
127 	bqueue_node_t		ln;
128 };
129 
130 static int
dump_bytes(dmu_sendarg_t * dsp,void * buf,int len)131 dump_bytes(dmu_sendarg_t *dsp, void *buf, int len)
132 {
133 	dsl_dataset_t *ds = dmu_objset_ds(dsp->dsa_os);
134 	struct uio auio;
135 	struct iovec aiov;
136 
137 	/*
138 	 * The code does not rely on this (len being a multiple of 8).  We keep
139 	 * this assertion because of the corresponding assertion in
140 	 * receive_read().  Keeping this assertion ensures that we do not
141 	 * inadvertently break backwards compatibility (causing the assertion
142 	 * in receive_read() to trigger on old software).
143 	 *
144 	 * Removing the assertions could be rolled into a new feature that uses
145 	 * data that isn't 8-byte aligned; if the assertions were removed, a
146 	 * feature flag would have to be added.
147 	 */
148 
149 	ASSERT0(len % 8);
150 
151 	aiov.iov_base = buf;
152 	aiov.iov_len = len;
153 	auio.uio_iov = &aiov;
154 	auio.uio_iovcnt = 1;
155 	auio.uio_resid = len;
156 #ifdef __NetBSD__
157 #ifdef _KERNEL
158 	auio.uio_vmspace = vmspace_kernel();
159 #endif
160 #else
161 	auio.uio_segflg = UIO_SYSSPACE;
162 #endif
163 	auio.uio_rw = UIO_WRITE;
164 	auio.uio_offset = (off_t)-1;
165 #ifdef __FreeBSD__
166 	auio.uio_td = dsp->dsa_td;
167 #endif
168 #ifdef _KERNEL
169 	if (dsp->dsa_fp->f_type == DTYPE_VNODE)
170 		bwillwrite();
171 	dsp->dsa_err = fo_write(dsp->dsa_fp, &auio, dsp->dsa_td->td_ucred, 0,
172 	    dsp->dsa_td);
173 #else
174 	fprintf(stderr, "%s: returning EOPNOTSUPP\n", __func__);
175 	dsp->dsa_err = EOPNOTSUPP;
176 #endif
177 	mutex_enter(&ds->ds_sendstream_lock);
178 	*dsp->dsa_off += len;
179 	mutex_exit(&ds->ds_sendstream_lock);
180 
181 	return (dsp->dsa_err);
182 }
183 
184 /*
185  * For all record types except BEGIN, fill in the checksum (overlaid in
186  * drr_u.drr_checksum.drr_checksum).  The checksum verifies everything
187  * up to the start of the checksum itself.
188  */
189 static int
dump_record(dmu_sendarg_t * dsp,void * payload,int payload_len)190 dump_record(dmu_sendarg_t *dsp, void *payload, int payload_len)
191 {
192 	ASSERT3U(offsetof(dmu_replay_record_t, drr_u.drr_checksum.drr_checksum),
193 	    ==, sizeof (dmu_replay_record_t) - sizeof (zio_cksum_t));
194 	fletcher_4_incremental_native(dsp->dsa_drr,
195 	    offsetof(dmu_replay_record_t, drr_u.drr_checksum.drr_checksum),
196 	    &dsp->dsa_zc);
197 	if (dsp->dsa_drr->drr_type == DRR_BEGIN) {
198 		dsp->dsa_sent_begin = B_TRUE;
199 	} else {
200 		ASSERT(ZIO_CHECKSUM_IS_ZERO(&dsp->dsa_drr->drr_u.
201 		    drr_checksum.drr_checksum));
202 		dsp->dsa_drr->drr_u.drr_checksum.drr_checksum = dsp->dsa_zc;
203 	}
204 	if (dsp->dsa_drr->drr_type == DRR_END) {
205 		dsp->dsa_sent_end = B_TRUE;
206 	}
207 	fletcher_4_incremental_native(&dsp->dsa_drr->
208 	    drr_u.drr_checksum.drr_checksum,
209 	    sizeof (zio_cksum_t), &dsp->dsa_zc);
210 	if (dump_bytes(dsp, dsp->dsa_drr, sizeof (dmu_replay_record_t)) != 0)
211 		return (SET_ERROR(EINTR));
212 	if (payload_len != 0) {
213 		fletcher_4_incremental_native(payload, payload_len,
214 		    &dsp->dsa_zc);
215 		if (dump_bytes(dsp, payload, payload_len) != 0)
216 			return (SET_ERROR(EINTR));
217 	}
218 	return (0);
219 }
220 
221 /*
222  * Fill in the drr_free struct, or perform aggregation if the previous record is
223  * also a free record, and the two are adjacent.
224  *
225  * Note that we send free records even for a full send, because we want to be
226  * able to receive a full send as a clone, which requires a list of all the free
227  * and freeobject records that were generated on the source.
228  */
229 static int
dump_free(dmu_sendarg_t * dsp,uint64_t object,uint64_t offset,uint64_t length)230 dump_free(dmu_sendarg_t *dsp, uint64_t object, uint64_t offset,
231     uint64_t length)
232 {
233 	struct drr_free *drrf = &(dsp->dsa_drr->drr_u.drr_free);
234 
235 	/*
236 	 * When we receive a free record, dbuf_free_range() assumes
237 	 * that the receiving system doesn't have any dbufs in the range
238 	 * being freed.  This is always true because there is a one-record
239 	 * constraint: we only send one WRITE record for any given
240 	 * object,offset.  We know that the one-record constraint is
241 	 * true because we always send data in increasing order by
242 	 * object,offset.
243 	 *
244 	 * If the increasing-order constraint ever changes, we should find
245 	 * another way to assert that the one-record constraint is still
246 	 * satisfied.
247 	 */
248 	ASSERT(object > dsp->dsa_last_data_object ||
249 	    (object == dsp->dsa_last_data_object &&
250 	    offset > dsp->dsa_last_data_offset));
251 
252 	if (length != -1ULL && offset + length < offset)
253 		length = -1ULL;
254 
255 	/*
256 	 * If there is a pending op, but it's not PENDING_FREE, push it out,
257 	 * since free block aggregation can only be done for blocks of the
258 	 * same type (i.e., DRR_FREE records can only be aggregated with
259 	 * other DRR_FREE records.  DRR_FREEOBJECTS records can only be
260 	 * aggregated with other DRR_FREEOBJECTS records.
261 	 */
262 	if (dsp->dsa_pending_op != PENDING_NONE &&
263 	    dsp->dsa_pending_op != PENDING_FREE) {
264 		if (dump_record(dsp, NULL, 0) != 0)
265 			return (SET_ERROR(EINTR));
266 		dsp->dsa_pending_op = PENDING_NONE;
267 	}
268 
269 	if (dsp->dsa_pending_op == PENDING_FREE) {
270 		/*
271 		 * There should never be a PENDING_FREE if length is -1
272 		 * (because dump_dnode is the only place where this
273 		 * function is called with a -1, and only after flushing
274 		 * any pending record).
275 		 */
276 		ASSERT(length != -1ULL);
277 		/*
278 		 * Check to see whether this free block can be aggregated
279 		 * with pending one.
280 		 */
281 		if (drrf->drr_object == object && drrf->drr_offset +
282 		    drrf->drr_length == offset) {
283 			drrf->drr_length += length;
284 			return (0);
285 		} else {
286 			/* not a continuation.  Push out pending record */
287 			if (dump_record(dsp, NULL, 0) != 0)
288 				return (SET_ERROR(EINTR));
289 			dsp->dsa_pending_op = PENDING_NONE;
290 		}
291 	}
292 	/* create a FREE record and make it pending */
293 	bzero(dsp->dsa_drr, sizeof (dmu_replay_record_t));
294 	dsp->dsa_drr->drr_type = DRR_FREE;
295 	drrf->drr_object = object;
296 	drrf->drr_offset = offset;
297 	drrf->drr_length = length;
298 	drrf->drr_toguid = dsp->dsa_toguid;
299 	if (length == -1ULL) {
300 		if (dump_record(dsp, NULL, 0) != 0)
301 			return (SET_ERROR(EINTR));
302 	} else {
303 		dsp->dsa_pending_op = PENDING_FREE;
304 	}
305 
306 	return (0);
307 }
308 
309 static int
dump_write(dmu_sendarg_t * dsp,dmu_object_type_t type,uint64_t object,uint64_t offset,int blksz,const blkptr_t * bp,void * data)310 dump_write(dmu_sendarg_t *dsp, dmu_object_type_t type,
311     uint64_t object, uint64_t offset, int blksz, const blkptr_t *bp, void *data)
312 {
313 	struct drr_write *drrw = &(dsp->dsa_drr->drr_u.drr_write);
314 
315 	/*
316 	 * We send data in increasing object, offset order.
317 	 * See comment in dump_free() for details.
318 	 */
319 	ASSERT(object > dsp->dsa_last_data_object ||
320 	    (object == dsp->dsa_last_data_object &&
321 	    offset > dsp->dsa_last_data_offset));
322 	dsp->dsa_last_data_object = object;
323 	dsp->dsa_last_data_offset = offset + blksz - 1;
324 
325 	/*
326 	 * If there is any kind of pending aggregation (currently either
327 	 * a grouping of free objects or free blocks), push it out to
328 	 * the stream, since aggregation can't be done across operations
329 	 * of different types.
330 	 */
331 	if (dsp->dsa_pending_op != PENDING_NONE) {
332 		if (dump_record(dsp, NULL, 0) != 0)
333 			return (SET_ERROR(EINTR));
334 		dsp->dsa_pending_op = PENDING_NONE;
335 	}
336 	/* write a WRITE record */
337 	bzero(dsp->dsa_drr, sizeof (dmu_replay_record_t));
338 	dsp->dsa_drr->drr_type = DRR_WRITE;
339 	drrw->drr_object = object;
340 	drrw->drr_type = type;
341 	drrw->drr_offset = offset;
342 	drrw->drr_length = blksz;
343 	drrw->drr_toguid = dsp->dsa_toguid;
344 	if (bp == NULL || BP_IS_EMBEDDED(bp)) {
345 		/*
346 		 * There's no pre-computed checksum for partial-block
347 		 * writes or embedded BP's, so (like
348 		 * fletcher4-checkummed blocks) userland will have to
349 		 * compute a dedup-capable checksum itself.
350 		 */
351 		drrw->drr_checksumtype = ZIO_CHECKSUM_OFF;
352 	} else {
353 		drrw->drr_checksumtype = BP_GET_CHECKSUM(bp);
354 		if (zio_checksum_table[drrw->drr_checksumtype].ci_flags &
355 		    ZCHECKSUM_FLAG_DEDUP)
356 			drrw->drr_checksumflags |= DRR_CHECKSUM_DEDUP;
357 		DDK_SET_LSIZE(&drrw->drr_key, BP_GET_LSIZE(bp));
358 		DDK_SET_PSIZE(&drrw->drr_key, BP_GET_PSIZE(bp));
359 		DDK_SET_COMPRESS(&drrw->drr_key, BP_GET_COMPRESS(bp));
360 		drrw->drr_key.ddk_cksum = bp->blk_cksum;
361 	}
362 
363 	if (dump_record(dsp, data, blksz) != 0)
364 		return (SET_ERROR(EINTR));
365 	return (0);
366 }
367 
368 static int
dump_write_embedded(dmu_sendarg_t * dsp,uint64_t object,uint64_t offset,int blksz,const blkptr_t * bp)369 dump_write_embedded(dmu_sendarg_t *dsp, uint64_t object, uint64_t offset,
370     int blksz, const blkptr_t *bp)
371 {
372 	char buf[BPE_PAYLOAD_SIZE];
373 	struct drr_write_embedded *drrw =
374 	    &(dsp->dsa_drr->drr_u.drr_write_embedded);
375 
376 	if (dsp->dsa_pending_op != PENDING_NONE) {
377 		if (dump_record(dsp, NULL, 0) != 0)
378 			return (EINTR);
379 		dsp->dsa_pending_op = PENDING_NONE;
380 	}
381 
382 	ASSERT(BP_IS_EMBEDDED(bp));
383 
384 	bzero(dsp->dsa_drr, sizeof (dmu_replay_record_t));
385 	dsp->dsa_drr->drr_type = DRR_WRITE_EMBEDDED;
386 	drrw->drr_object = object;
387 	drrw->drr_offset = offset;
388 	drrw->drr_length = blksz;
389 	drrw->drr_toguid = dsp->dsa_toguid;
390 	drrw->drr_compression = BP_GET_COMPRESS(bp);
391 	drrw->drr_etype = BPE_GET_ETYPE(bp);
392 	drrw->drr_lsize = BPE_GET_LSIZE(bp);
393 	drrw->drr_psize = BPE_GET_PSIZE(bp);
394 
395 	decode_embedded_bp_compressed(bp, buf);
396 
397 	if (dump_record(dsp, buf, P2ROUNDUP(drrw->drr_psize, 8)) != 0)
398 		return (EINTR);
399 	return (0);
400 }
401 
402 static int
dump_spill(dmu_sendarg_t * dsp,uint64_t object,int blksz,void * data)403 dump_spill(dmu_sendarg_t *dsp, uint64_t object, int blksz, void *data)
404 {
405 	struct drr_spill *drrs = &(dsp->dsa_drr->drr_u.drr_spill);
406 
407 	if (dsp->dsa_pending_op != PENDING_NONE) {
408 		if (dump_record(dsp, NULL, 0) != 0)
409 			return (SET_ERROR(EINTR));
410 		dsp->dsa_pending_op = PENDING_NONE;
411 	}
412 
413 	/* write a SPILL record */
414 	bzero(dsp->dsa_drr, sizeof (dmu_replay_record_t));
415 	dsp->dsa_drr->drr_type = DRR_SPILL;
416 	drrs->drr_object = object;
417 	drrs->drr_length = blksz;
418 	drrs->drr_toguid = dsp->dsa_toguid;
419 
420 	if (dump_record(dsp, data, blksz) != 0)
421 		return (SET_ERROR(EINTR));
422 	return (0);
423 }
424 
425 static int
dump_freeobjects(dmu_sendarg_t * dsp,uint64_t firstobj,uint64_t numobjs)426 dump_freeobjects(dmu_sendarg_t *dsp, uint64_t firstobj, uint64_t numobjs)
427 {
428 	struct drr_freeobjects *drrfo = &(dsp->dsa_drr->drr_u.drr_freeobjects);
429 
430 	/*
431 	 * If there is a pending op, but it's not PENDING_FREEOBJECTS,
432 	 * push it out, since free block aggregation can only be done for
433 	 * blocks of the same type (i.e., DRR_FREE records can only be
434 	 * aggregated with other DRR_FREE records.  DRR_FREEOBJECTS records
435 	 * can only be aggregated with other DRR_FREEOBJECTS records.
436 	 */
437 	if (dsp->dsa_pending_op != PENDING_NONE &&
438 	    dsp->dsa_pending_op != PENDING_FREEOBJECTS) {
439 		if (dump_record(dsp, NULL, 0) != 0)
440 			return (SET_ERROR(EINTR));
441 		dsp->dsa_pending_op = PENDING_NONE;
442 	}
443 	if (dsp->dsa_pending_op == PENDING_FREEOBJECTS) {
444 		/*
445 		 * See whether this free object array can be aggregated
446 		 * with pending one
447 		 */
448 		if (drrfo->drr_firstobj + drrfo->drr_numobjs == firstobj) {
449 			drrfo->drr_numobjs += numobjs;
450 			return (0);
451 		} else {
452 			/* can't be aggregated.  Push out pending record */
453 			if (dump_record(dsp, NULL, 0) != 0)
454 				return (SET_ERROR(EINTR));
455 			dsp->dsa_pending_op = PENDING_NONE;
456 		}
457 	}
458 
459 	/* write a FREEOBJECTS record */
460 	bzero(dsp->dsa_drr, sizeof (dmu_replay_record_t));
461 	dsp->dsa_drr->drr_type = DRR_FREEOBJECTS;
462 	drrfo->drr_firstobj = firstobj;
463 	drrfo->drr_numobjs = numobjs;
464 	drrfo->drr_toguid = dsp->dsa_toguid;
465 
466 	dsp->dsa_pending_op = PENDING_FREEOBJECTS;
467 
468 	return (0);
469 }
470 
471 static int
dump_dnode(dmu_sendarg_t * dsp,uint64_t object,dnode_phys_t * dnp)472 dump_dnode(dmu_sendarg_t *dsp, uint64_t object, dnode_phys_t *dnp)
473 {
474 	struct drr_object *drro = &(dsp->dsa_drr->drr_u.drr_object);
475 
476 	if (object < dsp->dsa_resume_object) {
477 		/*
478 		 * Note: when resuming, we will visit all the dnodes in
479 		 * the block of dnodes that we are resuming from.  In
480 		 * this case it's unnecessary to send the dnodes prior to
481 		 * the one we are resuming from.  We should be at most one
482 		 * block's worth of dnodes behind the resume point.
483 		 */
484 		ASSERT3U(dsp->dsa_resume_object - object, <,
485 		    1 << (DNODE_BLOCK_SHIFT - DNODE_SHIFT));
486 		return (0);
487 	}
488 
489 	if (dnp == NULL || dnp->dn_type == DMU_OT_NONE)
490 		return (dump_freeobjects(dsp, object, 1));
491 
492 	if (dsp->dsa_pending_op != PENDING_NONE) {
493 		if (dump_record(dsp, NULL, 0) != 0)
494 			return (SET_ERROR(EINTR));
495 		dsp->dsa_pending_op = PENDING_NONE;
496 	}
497 
498 	/* write an OBJECT record */
499 	bzero(dsp->dsa_drr, sizeof (dmu_replay_record_t));
500 	dsp->dsa_drr->drr_type = DRR_OBJECT;
501 	drro->drr_object = object;
502 	drro->drr_type = dnp->dn_type;
503 	drro->drr_bonustype = dnp->dn_bonustype;
504 	drro->drr_blksz = dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT;
505 	drro->drr_bonuslen = dnp->dn_bonuslen;
506 	drro->drr_checksumtype = dnp->dn_checksum;
507 	drro->drr_compress = dnp->dn_compress;
508 	drro->drr_toguid = dsp->dsa_toguid;
509 
510 	if (!(dsp->dsa_featureflags & DMU_BACKUP_FEATURE_LARGE_BLOCKS) &&
511 	    drro->drr_blksz > SPA_OLD_MAXBLOCKSIZE)
512 		drro->drr_blksz = SPA_OLD_MAXBLOCKSIZE;
513 
514 	if (dump_record(dsp, DN_BONUS(dnp),
515 	    P2ROUNDUP(dnp->dn_bonuslen, 8)) != 0) {
516 		return (SET_ERROR(EINTR));
517 	}
518 
519 	/* Free anything past the end of the file. */
520 	if (dump_free(dsp, object, (dnp->dn_maxblkid + 1) *
521 	    (dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT), -1ULL) != 0)
522 		return (SET_ERROR(EINTR));
523 	if (dsp->dsa_err != 0)
524 		return (SET_ERROR(EINTR));
525 	return (0);
526 }
527 
528 static boolean_t
backup_do_embed(dmu_sendarg_t * dsp,const blkptr_t * bp)529 backup_do_embed(dmu_sendarg_t *dsp, const blkptr_t *bp)
530 {
531 	if (!BP_IS_EMBEDDED(bp))
532 		return (B_FALSE);
533 
534 	/*
535 	 * Compression function must be legacy, or explicitly enabled.
536 	 */
537 	if ((BP_GET_COMPRESS(bp) >= ZIO_COMPRESS_LEGACY_FUNCTIONS &&
538 	    !(dsp->dsa_featureflags & DMU_BACKUP_FEATURE_EMBED_DATA_LZ4)))
539 		return (B_FALSE);
540 
541 	/*
542 	 * Embed type must be explicitly enabled.
543 	 */
544 	switch (BPE_GET_ETYPE(bp)) {
545 	case BP_EMBEDDED_TYPE_DATA:
546 		if (dsp->dsa_featureflags & DMU_BACKUP_FEATURE_EMBED_DATA)
547 			return (B_TRUE);
548 		break;
549 	default:
550 		return (B_FALSE);
551 	}
552 	return (B_FALSE);
553 }
554 
555 /*
556  * This is the callback function to traverse_dataset that acts as the worker
557  * thread for dmu_send_impl.
558  */
559 /*ARGSUSED*/
560 static int
send_cb(spa_t * spa,zilog_t * zilog,const blkptr_t * bp,const zbookmark_phys_t * zb,const struct dnode_phys * dnp,void * arg)561 send_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
562     const zbookmark_phys_t *zb, const struct dnode_phys *dnp, void *arg)
563 {
564 	struct send_thread_arg *sta = arg;
565 	struct send_block_record *record;
566 	uint64_t record_size;
567 	int err = 0;
568 
569 	ASSERT(zb->zb_object == DMU_META_DNODE_OBJECT ||
570 	    zb->zb_object >= sta->resume.zb_object);
571 
572 	if (sta->cancel)
573 		return (SET_ERROR(EINTR));
574 
575 	if (bp == NULL) {
576 		ASSERT3U(zb->zb_level, ==, ZB_DNODE_LEVEL);
577 		return (0);
578 	} else if (zb->zb_level < 0) {
579 		return (0);
580 	}
581 
582 	record = kmem_zalloc(sizeof (struct send_block_record), KM_SLEEP);
583 	record->eos_marker = B_FALSE;
584 	record->bp = *bp;
585 	record->zb = *zb;
586 	record->indblkshift = dnp->dn_indblkshift;
587 	record->datablkszsec = dnp->dn_datablkszsec;
588 	record_size = dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT;
589 	bqueue_enqueue(&sta->q, record, record_size);
590 
591 	return (err);
592 }
593 
594 /*
595  * This function kicks off the traverse_dataset.  It also handles setting the
596  * error code of the thread in case something goes wrong, and pushes the End of
597  * Stream record when the traverse_dataset call has finished.  If there is no
598  * dataset to traverse, the thread immediately pushes End of Stream marker.
599  */
600 static void
send_traverse_thread(void * arg)601 send_traverse_thread(void *arg)
602 {
603 	struct send_thread_arg *st_arg = arg;
604 	int err;
605 	struct send_block_record *data;
606 
607 	if (st_arg->ds != NULL) {
608 		err = traverse_dataset_resume(st_arg->ds,
609 		    st_arg->fromtxg, &st_arg->resume,
610 		    st_arg->flags, send_cb, st_arg);
611 
612 		if (err != EINTR)
613 			st_arg->error_code = err;
614 	}
615 	data = kmem_zalloc(sizeof (*data), KM_SLEEP);
616 	data->eos_marker = B_TRUE;
617 	bqueue_enqueue(&st_arg->q, data, 1);
618 	thread_exit();
619 }
620 
621 /*
622  * This function actually handles figuring out what kind of record needs to be
623  * dumped, reading the data (which has hopefully been prefetched), and calling
624  * the appropriate helper function.
625  */
626 static int
do_dump(dmu_sendarg_t * dsa,struct send_block_record * data)627 do_dump(dmu_sendarg_t *dsa, struct send_block_record *data)
628 {
629 	dsl_dataset_t *ds = dmu_objset_ds(dsa->dsa_os);
630 	const blkptr_t *bp = &data->bp;
631 	const zbookmark_phys_t *zb = &data->zb;
632 	uint8_t indblkshift = data->indblkshift;
633 	uint16_t dblkszsec = data->datablkszsec;
634 	spa_t *spa = ds->ds_dir->dd_pool->dp_spa;
635 	dmu_object_type_t type = bp ? BP_GET_TYPE(bp) : DMU_OT_NONE;
636 	int err = 0;
637 
638 	ASSERT3U(zb->zb_level, >=, 0);
639 
640 	ASSERT(zb->zb_object == DMU_META_DNODE_OBJECT ||
641 	    zb->zb_object >= dsa->dsa_resume_object);
642 
643 	if (zb->zb_object != DMU_META_DNODE_OBJECT &&
644 	    DMU_OBJECT_IS_SPECIAL(zb->zb_object)) {
645 		return (0);
646 	} else if (BP_IS_HOLE(bp) &&
647 	    zb->zb_object == DMU_META_DNODE_OBJECT) {
648 		uint64_t span = BP_SPAN(dblkszsec, indblkshift, zb->zb_level);
649 		uint64_t dnobj = (zb->zb_blkid * span) >> DNODE_SHIFT;
650 		err = dump_freeobjects(dsa, dnobj, span >> DNODE_SHIFT);
651 	} else if (BP_IS_HOLE(bp)) {
652 		uint64_t span = BP_SPAN(dblkszsec, indblkshift, zb->zb_level);
653 		uint64_t offset = zb->zb_blkid * span;
654 		err = dump_free(dsa, zb->zb_object, offset, span);
655 	} else if (zb->zb_level > 0 || type == DMU_OT_OBJSET) {
656 		return (0);
657 	} else if (type == DMU_OT_DNODE) {
658 		int blksz = BP_GET_LSIZE(bp);
659 		arc_flags_t aflags = ARC_FLAG_WAIT;
660 		arc_buf_t *abuf;
661 
662 		ASSERT0(zb->zb_level);
663 
664 		if (arc_read(NULL, spa, bp, arc_getbuf_func, &abuf,
665 		    ZIO_PRIORITY_ASYNC_READ, ZIO_FLAG_CANFAIL,
666 		    &aflags, zb) != 0)
667 			return (SET_ERROR(EIO));
668 
669 		dnode_phys_t *blk = abuf->b_data;
670 		uint64_t dnobj = zb->zb_blkid * (blksz >> DNODE_SHIFT);
671 		for (int i = 0; i < blksz >> DNODE_SHIFT; i++) {
672 			err = dump_dnode(dsa, dnobj + i, blk + i);
673 			if (err != 0)
674 				break;
675 		}
676 		arc_buf_destroy(abuf, &abuf);
677 	} else if (type == DMU_OT_SA) {
678 		arc_flags_t aflags = ARC_FLAG_WAIT;
679 		arc_buf_t *abuf;
680 		int blksz = BP_GET_LSIZE(bp);
681 
682 		if (arc_read(NULL, spa, bp, arc_getbuf_func, &abuf,
683 		    ZIO_PRIORITY_ASYNC_READ, ZIO_FLAG_CANFAIL,
684 		    &aflags, zb) != 0)
685 			return (SET_ERROR(EIO));
686 
687 		err = dump_spill(dsa, zb->zb_object, blksz, abuf->b_data);
688 		arc_buf_destroy(abuf, &abuf);
689 	} else if (backup_do_embed(dsa, bp)) {
690 		/* it's an embedded level-0 block of a regular object */
691 		int blksz = dblkszsec << SPA_MINBLOCKSHIFT;
692 		ASSERT0(zb->zb_level);
693 		err = dump_write_embedded(dsa, zb->zb_object,
694 		    zb->zb_blkid * blksz, blksz, bp);
695 	} else {
696 		/* it's a level-0 block of a regular object */
697 		arc_flags_t aflags = ARC_FLAG_WAIT;
698 		arc_buf_t *abuf;
699 		int blksz = dblkszsec << SPA_MINBLOCKSHIFT;
700 		uint64_t offset;
701 
702 		ASSERT0(zb->zb_level);
703 		ASSERT(zb->zb_object > dsa->dsa_resume_object ||
704 		    (zb->zb_object == dsa->dsa_resume_object &&
705 		    zb->zb_blkid * blksz >= dsa->dsa_resume_offset));
706 
707 		if (arc_read(NULL, spa, bp, arc_getbuf_func, &abuf,
708 		    ZIO_PRIORITY_ASYNC_READ, ZIO_FLAG_CANFAIL,
709 		    &aflags, zb) != 0) {
710 			if (zfs_send_corrupt_data) {
711 				/* Send a block filled with 0x"zfs badd bloc" */
712 				abuf = arc_alloc_buf(spa, blksz, &abuf,
713 				    ARC_BUFC_DATA);
714 				uint64_t *ptr;
715 				for (ptr = abuf->b_data;
716 				    (char *)ptr < (char *)abuf->b_data + blksz;
717 				    ptr++)
718 					*ptr = 0x2f5baddb10cULL;
719 			} else {
720 				return (SET_ERROR(EIO));
721 			}
722 		}
723 
724 		offset = zb->zb_blkid * blksz;
725 
726 		if (!(dsa->dsa_featureflags &
727 		    DMU_BACKUP_FEATURE_LARGE_BLOCKS) &&
728 		    blksz > SPA_OLD_MAXBLOCKSIZE) {
729 			char *buf = abuf->b_data;
730 			while (blksz > 0 && err == 0) {
731 				int n = MIN(blksz, SPA_OLD_MAXBLOCKSIZE);
732 				err = dump_write(dsa, type, zb->zb_object,
733 				    offset, n, NULL, buf);
734 				offset += n;
735 				buf += n;
736 				blksz -= n;
737 			}
738 		} else {
739 			err = dump_write(dsa, type, zb->zb_object,
740 			    offset, blksz, bp, abuf->b_data);
741 		}
742 		arc_buf_destroy(abuf, &abuf);
743 	}
744 
745 	ASSERT(err == 0 || err == EINTR);
746 	return (err);
747 }
748 
749 /*
750  * Pop the new data off the queue, and free the old data.
751  */
752 static struct send_block_record *
get_next_record(bqueue_t * bq,struct send_block_record * data)753 get_next_record(bqueue_t *bq, struct send_block_record *data)
754 {
755 	struct send_block_record *tmp = bqueue_dequeue(bq);
756 	kmem_free(data, sizeof (*data));
757 	return (tmp);
758 }
759 
760 /*
761  * Actually do the bulk of the work in a zfs send.
762  *
763  * Note: Releases dp using the specified tag.
764  */
765 static int
dmu_send_impl(void * tag,dsl_pool_t * dp,dsl_dataset_t * to_ds,zfs_bookmark_phys_t * ancestor_zb,boolean_t is_clone,boolean_t embedok,boolean_t large_block_ok,int outfd,uint64_t resumeobj,uint64_t resumeoff,vnode_t * vp,offset_t * off)766 dmu_send_impl(void *tag, dsl_pool_t *dp, dsl_dataset_t *to_ds,
767     zfs_bookmark_phys_t *ancestor_zb,
768     boolean_t is_clone, boolean_t embedok, boolean_t large_block_ok, int outfd,
769     uint64_t resumeobj, uint64_t resumeoff,
770 #ifdef illumos
771     vnode_t *vp, offset_t *off)
772 #else
773     struct file *fp, offset_t *off)
774 #endif
775 {
776 	objset_t *os;
777 	dmu_replay_record_t *drr;
778 	dmu_sendarg_t *dsp;
779 	int err;
780 	uint64_t fromtxg = 0;
781 	uint64_t featureflags = 0;
782 	struct send_thread_arg to_arg = { 0 };
783 
784 	err = dmu_objset_from_ds(to_ds, &os);
785 	if (err != 0) {
786 		dsl_pool_rele(dp, tag);
787 		return (err);
788 	}
789 
790 	drr = kmem_zalloc(sizeof (dmu_replay_record_t), KM_SLEEP);
791 	drr->drr_type = DRR_BEGIN;
792 	drr->drr_u.drr_begin.drr_magic = DMU_BACKUP_MAGIC;
793 	DMU_SET_STREAM_HDRTYPE(drr->drr_u.drr_begin.drr_versioninfo,
794 	    DMU_SUBSTREAM);
795 
796 #ifdef _KERNEL
797 	if (dmu_objset_type(os) == DMU_OST_ZFS) {
798 		uint64_t version;
799 		if (zfs_get_zplprop(os, ZFS_PROP_VERSION, &version) != 0) {
800 			kmem_free(drr, sizeof (dmu_replay_record_t));
801 			dsl_pool_rele(dp, tag);
802 			return (SET_ERROR(EINVAL));
803 		}
804 		if (version >= ZPL_VERSION_SA) {
805 			featureflags |= DMU_BACKUP_FEATURE_SA_SPILL;
806 		}
807 	}
808 #endif
809 
810 	if (large_block_ok && to_ds->ds_feature_inuse[SPA_FEATURE_LARGE_BLOCKS])
811 		featureflags |= DMU_BACKUP_FEATURE_LARGE_BLOCKS;
812 	if (embedok &&
813 	    spa_feature_is_active(dp->dp_spa, SPA_FEATURE_EMBEDDED_DATA)) {
814 		featureflags |= DMU_BACKUP_FEATURE_EMBED_DATA;
815 		if (spa_feature_is_active(dp->dp_spa, SPA_FEATURE_LZ4_COMPRESS))
816 			featureflags |= DMU_BACKUP_FEATURE_EMBED_DATA_LZ4;
817 	}
818 
819 	if (resumeobj != 0 || resumeoff != 0) {
820 		featureflags |= DMU_BACKUP_FEATURE_RESUMING;
821 	}
822 
823 	DMU_SET_FEATUREFLAGS(drr->drr_u.drr_begin.drr_versioninfo,
824 	    featureflags);
825 
826 	drr->drr_u.drr_begin.drr_creation_time =
827 	    dsl_dataset_phys(to_ds)->ds_creation_time;
828 	drr->drr_u.drr_begin.drr_type = dmu_objset_type(os);
829 	if (is_clone)
830 		drr->drr_u.drr_begin.drr_flags |= DRR_FLAG_CLONE;
831 	drr->drr_u.drr_begin.drr_toguid = dsl_dataset_phys(to_ds)->ds_guid;
832 	if (dsl_dataset_phys(to_ds)->ds_flags & DS_FLAG_CI_DATASET)
833 		drr->drr_u.drr_begin.drr_flags |= DRR_FLAG_CI_DATA;
834 	if (zfs_send_set_freerecords_bit)
835 		drr->drr_u.drr_begin.drr_flags |= DRR_FLAG_FREERECORDS;
836 
837 	if (ancestor_zb != NULL) {
838 		drr->drr_u.drr_begin.drr_fromguid =
839 		    ancestor_zb->zbm_guid;
840 		fromtxg = ancestor_zb->zbm_creation_txg;
841 	}
842 	dsl_dataset_name(to_ds, drr->drr_u.drr_begin.drr_toname);
843 	if (!to_ds->ds_is_snapshot) {
844 		(void) strlcat(drr->drr_u.drr_begin.drr_toname, "@--head--",
845 		    sizeof (drr->drr_u.drr_begin.drr_toname));
846 	}
847 
848 	dsp = kmem_zalloc(sizeof (dmu_sendarg_t), KM_SLEEP);
849 
850 	dsp->dsa_drr = drr;
851 	dsp->dsa_outfd = outfd;
852 	dsp->dsa_proc = curproc;
853 	dsp->dsa_td = curthread;
854 	dsp->dsa_fp = fp;
855 	dsp->dsa_os = os;
856 	dsp->dsa_off = off;
857 	dsp->dsa_toguid = dsl_dataset_phys(to_ds)->ds_guid;
858 	dsp->dsa_pending_op = PENDING_NONE;
859 	dsp->dsa_featureflags = featureflags;
860 	dsp->dsa_resume_object = resumeobj;
861 	dsp->dsa_resume_offset = resumeoff;
862 
863 	mutex_enter(&to_ds->ds_sendstream_lock);
864 	list_insert_head(&to_ds->ds_sendstreams, dsp);
865 	mutex_exit(&to_ds->ds_sendstream_lock);
866 
867 	dsl_dataset_long_hold(to_ds, FTAG);
868 	dsl_pool_rele(dp, tag);
869 
870 	void *payload = NULL;
871 	size_t payload_len = 0;
872 	if (resumeobj != 0 || resumeoff != 0) {
873 		dmu_object_info_t to_doi;
874 		err = dmu_object_info(os, resumeobj, &to_doi);
875 		if (err != 0)
876 			goto out;
877 		SET_BOOKMARK(&to_arg.resume, to_ds->ds_object, resumeobj, 0,
878 		    resumeoff / to_doi.doi_data_block_size);
879 
880 		nvlist_t *nvl = fnvlist_alloc();
881 		fnvlist_add_uint64(nvl, "resume_object", resumeobj);
882 		fnvlist_add_uint64(nvl, "resume_offset", resumeoff);
883 		payload = fnvlist_pack(nvl, &payload_len);
884 		drr->drr_payloadlen = payload_len;
885 		fnvlist_free(nvl);
886 	}
887 
888 	err = dump_record(dsp, payload, payload_len);
889 	fnvlist_pack_free(payload, payload_len);
890 	if (err != 0) {
891 		err = dsp->dsa_err;
892 		goto out;
893 	}
894 
895 	err = bqueue_init(&to_arg.q, zfs_send_queue_length,
896 	    offsetof(struct send_block_record, ln));
897 	to_arg.error_code = 0;
898 	to_arg.cancel = B_FALSE;
899 	to_arg.ds = to_ds;
900 	to_arg.fromtxg = fromtxg;
901 	to_arg.flags = TRAVERSE_PRE | TRAVERSE_PREFETCH;
902 	(void) thread_create(NULL, 0, send_traverse_thread, &to_arg, 0, &p0,
903 	    TS_RUN, minclsyspri);
904 
905 	struct send_block_record *to_data;
906 	to_data = bqueue_dequeue(&to_arg.q);
907 
908 	while (!to_data->eos_marker && err == 0) {
909 		err = do_dump(dsp, to_data);
910 		to_data = get_next_record(&to_arg.q, to_data);
911 		if (issig(JUSTLOOKING) && issig(FORREAL))
912 			err = EINTR;
913 	}
914 
915 	if (err != 0) {
916 		to_arg.cancel = B_TRUE;
917 		while (!to_data->eos_marker) {
918 			to_data = get_next_record(&to_arg.q, to_data);
919 		}
920 	}
921 	kmem_free(to_data, sizeof (*to_data));
922 
923 	bqueue_destroy(&to_arg.q);
924 
925 	if (err == 0 && to_arg.error_code != 0)
926 		err = to_arg.error_code;
927 
928 	if (err != 0)
929 		goto out;
930 
931 	if (dsp->dsa_pending_op != PENDING_NONE)
932 		if (dump_record(dsp, NULL, 0) != 0)
933 			err = SET_ERROR(EINTR);
934 
935 	if (err != 0) {
936 		if (err == EINTR && dsp->dsa_err != 0)
937 			err = dsp->dsa_err;
938 		goto out;
939 	}
940 
941 	bzero(drr, sizeof (dmu_replay_record_t));
942 	drr->drr_type = DRR_END;
943 	drr->drr_u.drr_end.drr_checksum = dsp->dsa_zc;
944 	drr->drr_u.drr_end.drr_toguid = dsp->dsa_toguid;
945 
946 	if (dump_record(dsp, NULL, 0) != 0)
947 		err = dsp->dsa_err;
948 
949 out:
950 	mutex_enter(&to_ds->ds_sendstream_lock);
951 	list_remove(&to_ds->ds_sendstreams, dsp);
952 	mutex_exit(&to_ds->ds_sendstream_lock);
953 
954 	VERIFY(err != 0 || (dsp->dsa_sent_begin && dsp->dsa_sent_end));
955 
956 	kmem_free(drr, sizeof (dmu_replay_record_t));
957 	kmem_free(dsp, sizeof (dmu_sendarg_t));
958 
959 	dsl_dataset_long_rele(to_ds, FTAG);
960 
961 	return (err);
962 }
963 
964 int
dmu_send_obj(const char * pool,uint64_t tosnap,uint64_t fromsnap,boolean_t embedok,boolean_t large_block_ok,int outfd,vnode_t * vp,offset_t * off)965 dmu_send_obj(const char *pool, uint64_t tosnap, uint64_t fromsnap,
966     boolean_t embedok, boolean_t large_block_ok,
967 #ifdef illumos
968     int outfd, vnode_t *vp, offset_t *off)
969 #else
970     int outfd, struct file *fp, offset_t *off)
971 #endif
972 {
973 	dsl_pool_t *dp;
974 	dsl_dataset_t *ds;
975 	dsl_dataset_t *fromds = NULL;
976 	int err;
977 
978 	err = dsl_pool_hold(pool, FTAG, &dp);
979 	if (err != 0)
980 		return (err);
981 
982 	err = dsl_dataset_hold_obj(dp, tosnap, FTAG, &ds);
983 	if (err != 0) {
984 		dsl_pool_rele(dp, FTAG);
985 		return (err);
986 	}
987 
988 	if (fromsnap != 0) {
989 		zfs_bookmark_phys_t zb;
990 		boolean_t is_clone;
991 
992 		err = dsl_dataset_hold_obj(dp, fromsnap, FTAG, &fromds);
993 		if (err != 0) {
994 			dsl_dataset_rele(ds, FTAG);
995 			dsl_pool_rele(dp, FTAG);
996 			return (err);
997 		}
998 		if (!dsl_dataset_is_before(ds, fromds, 0))
999 			err = SET_ERROR(EXDEV);
1000 		zb.zbm_creation_time =
1001 		    dsl_dataset_phys(fromds)->ds_creation_time;
1002 		zb.zbm_creation_txg = dsl_dataset_phys(fromds)->ds_creation_txg;
1003 		zb.zbm_guid = dsl_dataset_phys(fromds)->ds_guid;
1004 		is_clone = (fromds->ds_dir != ds->ds_dir);
1005 		dsl_dataset_rele(fromds, FTAG);
1006 		err = dmu_send_impl(FTAG, dp, ds, &zb, is_clone,
1007 		    embedok, large_block_ok, outfd, 0, 0, fp, off);
1008 	} else {
1009 		err = dmu_send_impl(FTAG, dp, ds, NULL, B_FALSE,
1010 		    embedok, large_block_ok, outfd, 0, 0, fp, off);
1011 	}
1012 	dsl_dataset_rele(ds, FTAG);
1013 	return (err);
1014 }
1015 
1016 int
dmu_send(const char * tosnap,const char * fromsnap,boolean_t embedok,boolean_t large_block_ok,int outfd,uint64_t resumeobj,uint64_t resumeoff,vnode_t * vp,offset_t * off)1017 dmu_send(const char *tosnap, const char *fromsnap, boolean_t embedok,
1018     boolean_t large_block_ok, int outfd, uint64_t resumeobj, uint64_t resumeoff,
1019 #ifdef illumos
1020     vnode_t *vp, offset_t *off)
1021 #else
1022     struct file *fp, offset_t *off)
1023 #endif
1024 {
1025 	dsl_pool_t *dp;
1026 	dsl_dataset_t *ds;
1027 	int err;
1028 	boolean_t owned = B_FALSE;
1029 
1030 	if (fromsnap != NULL && strpbrk(fromsnap, "@#") == NULL)
1031 		return (SET_ERROR(EINVAL));
1032 
1033 	err = dsl_pool_hold(tosnap, FTAG, &dp);
1034 	if (err != 0)
1035 		return (err);
1036 
1037 	if (strchr(tosnap, '@') == NULL && spa_writeable(dp->dp_spa)) {
1038 		/*
1039 		 * We are sending a filesystem or volume.  Ensure
1040 		 * that it doesn't change by owning the dataset.
1041 		 */
1042 		err = dsl_dataset_own(dp, tosnap, FTAG, &ds);
1043 		owned = B_TRUE;
1044 	} else {
1045 		err = dsl_dataset_hold(dp, tosnap, FTAG, &ds);
1046 	}
1047 	if (err != 0) {
1048 		dsl_pool_rele(dp, FTAG);
1049 		return (err);
1050 	}
1051 
1052 	if (fromsnap != NULL) {
1053 		zfs_bookmark_phys_t zb;
1054 		boolean_t is_clone = B_FALSE;
1055 		int fsnamelen = strchr(tosnap, '@') - tosnap;
1056 
1057 		/*
1058 		 * If the fromsnap is in a different filesystem, then
1059 		 * mark the send stream as a clone.
1060 		 */
1061 		if (strncmp(tosnap, fromsnap, fsnamelen) != 0 ||
1062 		    (fromsnap[fsnamelen] != '@' &&
1063 		    fromsnap[fsnamelen] != '#')) {
1064 			is_clone = B_TRUE;
1065 		}
1066 
1067 		if (strchr(fromsnap, '@')) {
1068 			dsl_dataset_t *fromds;
1069 			err = dsl_dataset_hold(dp, fromsnap, FTAG, &fromds);
1070 			if (err == 0) {
1071 				if (!dsl_dataset_is_before(ds, fromds, 0))
1072 					err = SET_ERROR(EXDEV);
1073 				zb.zbm_creation_time =
1074 				    dsl_dataset_phys(fromds)->ds_creation_time;
1075 				zb.zbm_creation_txg =
1076 				    dsl_dataset_phys(fromds)->ds_creation_txg;
1077 				zb.zbm_guid = dsl_dataset_phys(fromds)->ds_guid;
1078 				is_clone = (ds->ds_dir != fromds->ds_dir);
1079 				dsl_dataset_rele(fromds, FTAG);
1080 			}
1081 		} else {
1082 			err = dsl_bookmark_lookup(dp, fromsnap, ds, &zb);
1083 		}
1084 		if (err != 0) {
1085 			dsl_dataset_rele(ds, FTAG);
1086 			dsl_pool_rele(dp, FTAG);
1087 			return (err);
1088 		}
1089 		err = dmu_send_impl(FTAG, dp, ds, &zb, is_clone,
1090 		    embedok, large_block_ok,
1091 		    outfd, resumeobj, resumeoff, fp, off);
1092 	} else {
1093 		err = dmu_send_impl(FTAG, dp, ds, NULL, B_FALSE,
1094 		    embedok, large_block_ok,
1095 		    outfd, resumeobj, resumeoff, fp, off);
1096 	}
1097 	if (owned)
1098 		dsl_dataset_disown(ds, FTAG);
1099 	else
1100 		dsl_dataset_rele(ds, FTAG);
1101 	return (err);
1102 }
1103 
1104 static int
dmu_adjust_send_estimate_for_indirects(dsl_dataset_t * ds,uint64_t size,uint64_t * sizep)1105 dmu_adjust_send_estimate_for_indirects(dsl_dataset_t *ds, uint64_t size,
1106     uint64_t *sizep)
1107 {
1108 	int err;
1109 	/*
1110 	 * Assume that space (both on-disk and in-stream) is dominated by
1111 	 * data.  We will adjust for indirect blocks and the copies property,
1112 	 * but ignore per-object space used (eg, dnodes and DRR_OBJECT records).
1113 	 */
1114 
1115 	/*
1116 	 * Subtract out approximate space used by indirect blocks.
1117 	 * Assume most space is used by data blocks (non-indirect, non-dnode).
1118 	 * Assume all blocks are recordsize.  Assume ditto blocks and
1119 	 * internal fragmentation counter out compression.
1120 	 *
1121 	 * Therefore, space used by indirect blocks is sizeof(blkptr_t) per
1122 	 * block, which we observe in practice.
1123 	 */
1124 	uint64_t recordsize;
1125 	err = dsl_prop_get_int_ds(ds, "recordsize", &recordsize);
1126 	if (err != 0)
1127 		return (err);
1128 	size -= size / recordsize * sizeof (blkptr_t);
1129 
1130 	/* Add in the space for the record associated with each block. */
1131 	size += size / recordsize * sizeof (dmu_replay_record_t);
1132 
1133 	*sizep = size;
1134 
1135 	return (0);
1136 }
1137 
1138 int
dmu_send_estimate(dsl_dataset_t * ds,dsl_dataset_t * fromds,uint64_t * sizep)1139 dmu_send_estimate(dsl_dataset_t *ds, dsl_dataset_t *fromds, uint64_t *sizep)
1140 {
1141 	dsl_pool_t *dp = ds->ds_dir->dd_pool;
1142 	int err;
1143 	uint64_t size;
1144 
1145 	ASSERT(dsl_pool_config_held(dp));
1146 
1147 	/* tosnap must be a snapshot */
1148 	if (!ds->ds_is_snapshot)
1149 		return (SET_ERROR(EINVAL));
1150 
1151 	/* fromsnap, if provided, must be a snapshot */
1152 	if (fromds != NULL && !fromds->ds_is_snapshot)
1153 		return (SET_ERROR(EINVAL));
1154 
1155 	/*
1156 	 * fromsnap must be an earlier snapshot from the same fs as tosnap,
1157 	 * or the origin's fs.
1158 	 */
1159 	if (fromds != NULL && !dsl_dataset_is_before(ds, fromds, 0))
1160 		return (SET_ERROR(EXDEV));
1161 
1162 	/* Get uncompressed size estimate of changed data. */
1163 	if (fromds == NULL) {
1164 		size = dsl_dataset_phys(ds)->ds_uncompressed_bytes;
1165 	} else {
1166 		uint64_t used, comp;
1167 		err = dsl_dataset_space_written(fromds, ds,
1168 		    &used, &comp, &size);
1169 		if (err != 0)
1170 			return (err);
1171 	}
1172 
1173 	err = dmu_adjust_send_estimate_for_indirects(ds, size, sizep);
1174 	return (err);
1175 }
1176 
1177 /*
1178  * Simple callback used to traverse the blocks of a snapshot and sum their
1179  * uncompressed size
1180  */
1181 /* ARGSUSED */
1182 static int
dmu_calculate_send_traversal(spa_t * spa,zilog_t * zilog,const blkptr_t * bp,const zbookmark_phys_t * zb,const dnode_phys_t * dnp,void * arg)1183 dmu_calculate_send_traversal(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
1184     const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
1185 {
1186 	uint64_t *spaceptr = arg;
1187 	if (bp != NULL && !BP_IS_HOLE(bp)) {
1188 		*spaceptr += BP_GET_UCSIZE(bp);
1189 	}
1190 	return (0);
1191 }
1192 
1193 /*
1194  * Given a desination snapshot and a TXG, calculate the approximate size of a
1195  * send stream sent from that TXG. from_txg may be zero, indicating that the
1196  * whole snapshot will be sent.
1197  */
1198 int
dmu_send_estimate_from_txg(dsl_dataset_t * ds,uint64_t from_txg,uint64_t * sizep)1199 dmu_send_estimate_from_txg(dsl_dataset_t *ds, uint64_t from_txg,
1200     uint64_t *sizep)
1201 {
1202 	dsl_pool_t *dp = ds->ds_dir->dd_pool;
1203 	int err;
1204 	uint64_t size = 0;
1205 
1206 	ASSERT(dsl_pool_config_held(dp));
1207 
1208 	/* tosnap must be a snapshot */
1209 	if (!dsl_dataset_is_snapshot(ds))
1210 		return (SET_ERROR(EINVAL));
1211 
1212 	/* verify that from_txg is before the provided snapshot was taken */
1213 	if (from_txg >= dsl_dataset_phys(ds)->ds_creation_txg) {
1214 		return (SET_ERROR(EXDEV));
1215 	}
1216 
1217 	/*
1218 	 * traverse the blocks of the snapshot with birth times after
1219 	 * from_txg, summing their uncompressed size
1220 	 */
1221 	err = traverse_dataset(ds, from_txg, TRAVERSE_POST,
1222 	    dmu_calculate_send_traversal, &size);
1223 	if (err)
1224 		return (err);
1225 
1226 	err = dmu_adjust_send_estimate_for_indirects(ds, size, sizep);
1227 	return (err);
1228 }
1229 
1230 typedef struct dmu_recv_begin_arg {
1231 	const char *drba_origin;
1232 	dmu_recv_cookie_t *drba_cookie;
1233 	cred_t *drba_cred;
1234 	uint64_t drba_snapobj;
1235 } dmu_recv_begin_arg_t;
1236 
1237 static int
recv_begin_check_existing_impl(dmu_recv_begin_arg_t * drba,dsl_dataset_t * ds,uint64_t fromguid)1238 recv_begin_check_existing_impl(dmu_recv_begin_arg_t *drba, dsl_dataset_t *ds,
1239     uint64_t fromguid)
1240 {
1241 	uint64_t val;
1242 	int error;
1243 	dsl_pool_t *dp = ds->ds_dir->dd_pool;
1244 
1245 	/* temporary clone name must not exist */
1246 	error = zap_lookup(dp->dp_meta_objset,
1247 	    dsl_dir_phys(ds->ds_dir)->dd_child_dir_zapobj, recv_clone_name,
1248 	    8, 1, &val);
1249 	if (error != ENOENT)
1250 		return (error == 0 ? EBUSY : error);
1251 
1252 	/* new snapshot name must not exist */
1253 	error = zap_lookup(dp->dp_meta_objset,
1254 	    dsl_dataset_phys(ds)->ds_snapnames_zapobj,
1255 	    drba->drba_cookie->drc_tosnap, 8, 1, &val);
1256 	if (error != ENOENT)
1257 		return (error == 0 ? EEXIST : error);
1258 
1259 	/*
1260 	 * Check snapshot limit before receiving. We'll recheck again at the
1261 	 * end, but might as well abort before receiving if we're already over
1262 	 * the limit.
1263 	 *
1264 	 * Note that we do not check the file system limit with
1265 	 * dsl_dir_fscount_check because the temporary %clones don't count
1266 	 * against that limit.
1267 	 */
1268 	error = dsl_fs_ss_limit_check(ds->ds_dir, 1, ZFS_PROP_SNAPSHOT_LIMIT,
1269 	    NULL, drba->drba_cred);
1270 	if (error != 0)
1271 		return (error);
1272 
1273 	if (fromguid != 0) {
1274 		dsl_dataset_t *snap;
1275 		uint64_t obj = dsl_dataset_phys(ds)->ds_prev_snap_obj;
1276 
1277 		/* Find snapshot in this dir that matches fromguid. */
1278 		while (obj != 0) {
1279 			error = dsl_dataset_hold_obj(dp, obj, FTAG,
1280 			    &snap);
1281 			if (error != 0)
1282 				return (SET_ERROR(ENODEV));
1283 			if (snap->ds_dir != ds->ds_dir) {
1284 				dsl_dataset_rele(snap, FTAG);
1285 				return (SET_ERROR(ENODEV));
1286 			}
1287 			if (dsl_dataset_phys(snap)->ds_guid == fromguid)
1288 				break;
1289 			obj = dsl_dataset_phys(snap)->ds_prev_snap_obj;
1290 			dsl_dataset_rele(snap, FTAG);
1291 		}
1292 		if (obj == 0)
1293 			return (SET_ERROR(ENODEV));
1294 
1295 		if (drba->drba_cookie->drc_force) {
1296 			drba->drba_snapobj = obj;
1297 		} else {
1298 			/*
1299 			 * If we are not forcing, there must be no
1300 			 * changes since fromsnap.
1301 			 */
1302 			if (dsl_dataset_modified_since_snap(ds, snap)) {
1303 				dsl_dataset_rele(snap, FTAG);
1304 				return (SET_ERROR(ETXTBSY));
1305 			}
1306 			drba->drba_snapobj = ds->ds_prev->ds_object;
1307 		}
1308 
1309 		dsl_dataset_rele(snap, FTAG);
1310 	} else {
1311 		/* if full, then must be forced */
1312 		if (!drba->drba_cookie->drc_force)
1313 			return (SET_ERROR(EEXIST));
1314 		/* start from $ORIGIN@$ORIGIN, if supported */
1315 		drba->drba_snapobj = dp->dp_origin_snap != NULL ?
1316 		    dp->dp_origin_snap->ds_object : 0;
1317 	}
1318 
1319 	return (0);
1320 
1321 }
1322 
1323 static int
dmu_recv_begin_check(void * arg,dmu_tx_t * tx)1324 dmu_recv_begin_check(void *arg, dmu_tx_t *tx)
1325 {
1326 	dmu_recv_begin_arg_t *drba = arg;
1327 	dsl_pool_t *dp = dmu_tx_pool(tx);
1328 	struct drr_begin *drrb = drba->drba_cookie->drc_drrb;
1329 	uint64_t fromguid = drrb->drr_fromguid;
1330 	int flags = drrb->drr_flags;
1331 	int error;
1332 	uint64_t featureflags = DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo);
1333 	dsl_dataset_t *ds;
1334 	const char *tofs = drba->drba_cookie->drc_tofs;
1335 
1336 	/* already checked */
1337 	ASSERT3U(drrb->drr_magic, ==, DMU_BACKUP_MAGIC);
1338 	ASSERT(!(featureflags & DMU_BACKUP_FEATURE_RESUMING));
1339 
1340 	if (DMU_GET_STREAM_HDRTYPE(drrb->drr_versioninfo) ==
1341 	    DMU_COMPOUNDSTREAM ||
1342 	    drrb->drr_type >= DMU_OST_NUMTYPES ||
1343 	    ((flags & DRR_FLAG_CLONE) && drba->drba_origin == NULL))
1344 		return (SET_ERROR(EINVAL));
1345 
1346 	/* Verify pool version supports SA if SA_SPILL feature set */
1347 	if ((featureflags & DMU_BACKUP_FEATURE_SA_SPILL) &&
1348 	    spa_version(dp->dp_spa) < SPA_VERSION_SA)
1349 		return (SET_ERROR(ENOTSUP));
1350 
1351 	if (drba->drba_cookie->drc_resumable &&
1352 	    !spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_EXTENSIBLE_DATASET))
1353 		return (SET_ERROR(ENOTSUP));
1354 
1355 	/*
1356 	 * The receiving code doesn't know how to translate a WRITE_EMBEDDED
1357 	 * record to a plan WRITE record, so the pool must have the
1358 	 * EMBEDDED_DATA feature enabled if the stream has WRITE_EMBEDDED
1359 	 * records.  Same with WRITE_EMBEDDED records that use LZ4 compression.
1360 	 */
1361 	if ((featureflags & DMU_BACKUP_FEATURE_EMBED_DATA) &&
1362 	    !spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_EMBEDDED_DATA))
1363 		return (SET_ERROR(ENOTSUP));
1364 	if ((featureflags & DMU_BACKUP_FEATURE_EMBED_DATA_LZ4) &&
1365 	    !spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_LZ4_COMPRESS))
1366 		return (SET_ERROR(ENOTSUP));
1367 
1368 	/*
1369 	 * The receiving code doesn't know how to translate large blocks
1370 	 * to smaller ones, so the pool must have the LARGE_BLOCKS
1371 	 * feature enabled if the stream has LARGE_BLOCKS.
1372 	 */
1373 	if ((featureflags & DMU_BACKUP_FEATURE_LARGE_BLOCKS) &&
1374 	    !spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_LARGE_BLOCKS))
1375 		return (SET_ERROR(ENOTSUP));
1376 
1377 	error = dsl_dataset_hold(dp, tofs, FTAG, &ds);
1378 	if (error == 0) {
1379 		/* target fs already exists; recv into temp clone */
1380 
1381 		/* Can't recv a clone into an existing fs */
1382 		if (flags & DRR_FLAG_CLONE || drba->drba_origin) {
1383 			dsl_dataset_rele(ds, FTAG);
1384 			return (SET_ERROR(EINVAL));
1385 		}
1386 
1387 		error = recv_begin_check_existing_impl(drba, ds, fromguid);
1388 		dsl_dataset_rele(ds, FTAG);
1389 	} else if (error == ENOENT) {
1390 		/* target fs does not exist; must be a full backup or clone */
1391 		char buf[ZFS_MAX_DATASET_NAME_LEN];
1392 
1393 		/*
1394 		 * If it's a non-clone incremental, we are missing the
1395 		 * target fs, so fail the recv.
1396 		 */
1397 		if (fromguid != 0 && !(flags & DRR_FLAG_CLONE ||
1398 		    drba->drba_origin))
1399 			return (SET_ERROR(ENOENT));
1400 
1401 		/*
1402 		 * If we're receiving a full send as a clone, and it doesn't
1403 		 * contain all the necessary free records and freeobject
1404 		 * records, reject it.
1405 		 */
1406 		if (fromguid == 0 && drba->drba_origin &&
1407 		    !(flags & DRR_FLAG_FREERECORDS))
1408 			return (SET_ERROR(EINVAL));
1409 
1410 		/* Open the parent of tofs */
1411 		ASSERT3U(strlen(tofs), <, sizeof (buf));
1412 		(void) strlcpy(buf, tofs, strrchr(tofs, '/') - tofs + 1);
1413 		error = dsl_dataset_hold(dp, buf, FTAG, &ds);
1414 		if (error != 0)
1415 			return (error);
1416 
1417 		/*
1418 		 * Check filesystem and snapshot limits before receiving. We'll
1419 		 * recheck snapshot limits again at the end (we create the
1420 		 * filesystems and increment those counts during begin_sync).
1421 		 */
1422 		error = dsl_fs_ss_limit_check(ds->ds_dir, 1,
1423 		    ZFS_PROP_FILESYSTEM_LIMIT, NULL, drba->drba_cred);
1424 		if (error != 0) {
1425 			dsl_dataset_rele(ds, FTAG);
1426 			return (error);
1427 		}
1428 
1429 		error = dsl_fs_ss_limit_check(ds->ds_dir, 1,
1430 		    ZFS_PROP_SNAPSHOT_LIMIT, NULL, drba->drba_cred);
1431 		if (error != 0) {
1432 			dsl_dataset_rele(ds, FTAG);
1433 			return (error);
1434 		}
1435 
1436 		if (drba->drba_origin != NULL) {
1437 			dsl_dataset_t *origin;
1438 			error = dsl_dataset_hold(dp, drba->drba_origin,
1439 			    FTAG, &origin);
1440 			if (error != 0) {
1441 				dsl_dataset_rele(ds, FTAG);
1442 				return (error);
1443 			}
1444 			if (!origin->ds_is_snapshot) {
1445 				dsl_dataset_rele(origin, FTAG);
1446 				dsl_dataset_rele(ds, FTAG);
1447 				return (SET_ERROR(EINVAL));
1448 			}
1449 			if (dsl_dataset_phys(origin)->ds_guid != fromguid &&
1450 			    fromguid != 0) {
1451 				dsl_dataset_rele(origin, FTAG);
1452 				dsl_dataset_rele(ds, FTAG);
1453 				return (SET_ERROR(ENODEV));
1454 			}
1455 			dsl_dataset_rele(origin, FTAG);
1456 		}
1457 		dsl_dataset_rele(ds, FTAG);
1458 		error = 0;
1459 	}
1460 	return (error);
1461 }
1462 
1463 static void
dmu_recv_begin_sync(void * arg,dmu_tx_t * tx)1464 dmu_recv_begin_sync(void *arg, dmu_tx_t *tx)
1465 {
1466 	dmu_recv_begin_arg_t *drba = arg;
1467 	dsl_pool_t *dp = dmu_tx_pool(tx);
1468 	objset_t *mos = dp->dp_meta_objset;
1469 	struct drr_begin *drrb = drba->drba_cookie->drc_drrb;
1470 	const char *tofs = drba->drba_cookie->drc_tofs;
1471 	dsl_dataset_t *ds, *newds;
1472 	uint64_t dsobj;
1473 	int error;
1474 	uint64_t crflags = 0;
1475 
1476 	if (drrb->drr_flags & DRR_FLAG_CI_DATA)
1477 		crflags |= DS_FLAG_CI_DATASET;
1478 
1479 	error = dsl_dataset_hold(dp, tofs, FTAG, &ds);
1480 	if (error == 0) {
1481 		/* create temporary clone */
1482 		dsl_dataset_t *snap = NULL;
1483 		if (drba->drba_snapobj != 0) {
1484 			VERIFY0(dsl_dataset_hold_obj(dp,
1485 			    drba->drba_snapobj, FTAG, &snap));
1486 		}
1487 		dsobj = dsl_dataset_create_sync(ds->ds_dir, recv_clone_name,
1488 		    snap, crflags, drba->drba_cred, tx);
1489 		if (drba->drba_snapobj != 0)
1490 			dsl_dataset_rele(snap, FTAG);
1491 		dsl_dataset_rele(ds, FTAG);
1492 	} else {
1493 		dsl_dir_t *dd;
1494 		const char *tail;
1495 		dsl_dataset_t *origin = NULL;
1496 
1497 		VERIFY0(dsl_dir_hold(dp, tofs, FTAG, &dd, &tail));
1498 
1499 		if (drba->drba_origin != NULL) {
1500 			VERIFY0(dsl_dataset_hold(dp, drba->drba_origin,
1501 			    FTAG, &origin));
1502 		}
1503 
1504 		/* Create new dataset. */
1505 		dsobj = dsl_dataset_create_sync(dd,
1506 		    strrchr(tofs, '/') + 1,
1507 		    origin, crflags, drba->drba_cred, tx);
1508 		if (origin != NULL)
1509 			dsl_dataset_rele(origin, FTAG);
1510 		dsl_dir_rele(dd, FTAG);
1511 		drba->drba_cookie->drc_newfs = B_TRUE;
1512 	}
1513 	VERIFY0(dsl_dataset_own_obj(dp, dsobj, dmu_recv_tag, &newds));
1514 
1515 	if (drba->drba_cookie->drc_resumable) {
1516 		dsl_dataset_zapify(newds, tx);
1517 		if (drrb->drr_fromguid != 0) {
1518 			VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_FROMGUID,
1519 			    8, 1, &drrb->drr_fromguid, tx));
1520 		}
1521 		VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_TOGUID,
1522 		    8, 1, &drrb->drr_toguid, tx));
1523 		VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_TONAME,
1524 		    1, strlen(drrb->drr_toname) + 1, drrb->drr_toname, tx));
1525 		uint64_t one = 1;
1526 		uint64_t zero = 0;
1527 		VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_OBJECT,
1528 		    8, 1, &one, tx));
1529 		VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_OFFSET,
1530 		    8, 1, &zero, tx));
1531 		VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_BYTES,
1532 		    8, 1, &zero, tx));
1533 		if (DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo) &
1534 		    DMU_BACKUP_FEATURE_EMBED_DATA) {
1535 			VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_EMBEDOK,
1536 			    8, 1, &one, tx));
1537 		}
1538 	}
1539 
1540 	dmu_buf_will_dirty(newds->ds_dbuf, tx);
1541 	dsl_dataset_phys(newds)->ds_flags |= DS_FLAG_INCONSISTENT;
1542 
1543 	/*
1544 	 * If we actually created a non-clone, we need to create the
1545 	 * objset in our new dataset.
1546 	 */
1547 	rrw_enter(&newds->ds_bp_rwlock, RW_READER, FTAG);
1548 	if (BP_IS_HOLE(dsl_dataset_get_blkptr(newds))) {
1549 		(void) dmu_objset_create_impl(dp->dp_spa,
1550 		    newds, dsl_dataset_get_blkptr(newds), drrb->drr_type, tx);
1551 	}
1552 	rrw_exit(&newds->ds_bp_rwlock, FTAG);
1553 
1554 	drba->drba_cookie->drc_ds = newds;
1555 
1556 	spa_history_log_internal_ds(newds, "receive", tx, "");
1557 }
1558 
1559 static int
dmu_recv_resume_begin_check(void * arg,dmu_tx_t * tx)1560 dmu_recv_resume_begin_check(void *arg, dmu_tx_t *tx)
1561 {
1562 	dmu_recv_begin_arg_t *drba = arg;
1563 	dsl_pool_t *dp = dmu_tx_pool(tx);
1564 	struct drr_begin *drrb = drba->drba_cookie->drc_drrb;
1565 	int error;
1566 	uint64_t featureflags = DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo);
1567 	dsl_dataset_t *ds;
1568 	const char *tofs = drba->drba_cookie->drc_tofs;
1569 
1570 	/* already checked */
1571 	ASSERT3U(drrb->drr_magic, ==, DMU_BACKUP_MAGIC);
1572 	ASSERT(featureflags & DMU_BACKUP_FEATURE_RESUMING);
1573 
1574 	if (DMU_GET_STREAM_HDRTYPE(drrb->drr_versioninfo) ==
1575 	    DMU_COMPOUNDSTREAM ||
1576 	    drrb->drr_type >= DMU_OST_NUMTYPES)
1577 		return (SET_ERROR(EINVAL));
1578 
1579 	/* Verify pool version supports SA if SA_SPILL feature set */
1580 	if ((featureflags & DMU_BACKUP_FEATURE_SA_SPILL) &&
1581 	    spa_version(dp->dp_spa) < SPA_VERSION_SA)
1582 		return (SET_ERROR(ENOTSUP));
1583 
1584 	/*
1585 	 * The receiving code doesn't know how to translate a WRITE_EMBEDDED
1586 	 * record to a plain WRITE record, so the pool must have the
1587 	 * EMBEDDED_DATA feature enabled if the stream has WRITE_EMBEDDED
1588 	 * records.  Same with WRITE_EMBEDDED records that use LZ4 compression.
1589 	 */
1590 	if ((featureflags & DMU_BACKUP_FEATURE_EMBED_DATA) &&
1591 	    !spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_EMBEDDED_DATA))
1592 		return (SET_ERROR(ENOTSUP));
1593 	if ((featureflags & DMU_BACKUP_FEATURE_EMBED_DATA_LZ4) &&
1594 	    !spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_LZ4_COMPRESS))
1595 		return (SET_ERROR(ENOTSUP));
1596 
1597 	/* 6 extra bytes for /%recv */
1598 	char recvname[ZFS_MAX_DATASET_NAME_LEN + 6];
1599 
1600 	(void) snprintf(recvname, sizeof (recvname), "%s/%s",
1601 	    tofs, recv_clone_name);
1602 
1603 	if (dsl_dataset_hold(dp, recvname, FTAG, &ds) != 0) {
1604 		/* %recv does not exist; continue in tofs */
1605 		error = dsl_dataset_hold(dp, tofs, FTAG, &ds);
1606 		if (error != 0)
1607 			return (error);
1608 	}
1609 
1610 	/* check that ds is marked inconsistent */
1611 	if (!DS_IS_INCONSISTENT(ds)) {
1612 		dsl_dataset_rele(ds, FTAG);
1613 		return (SET_ERROR(EINVAL));
1614 	}
1615 
1616 	/* check that there is resuming data, and that the toguid matches */
1617 	if (!dsl_dataset_is_zapified(ds)) {
1618 		dsl_dataset_rele(ds, FTAG);
1619 		return (SET_ERROR(EINVAL));
1620 	}
1621 	uint64_t val;
1622 	error = zap_lookup(dp->dp_meta_objset, ds->ds_object,
1623 	    DS_FIELD_RESUME_TOGUID, sizeof (val), 1, &val);
1624 	if (error != 0 || drrb->drr_toguid != val) {
1625 		dsl_dataset_rele(ds, FTAG);
1626 		return (SET_ERROR(EINVAL));
1627 	}
1628 
1629 	/*
1630 	 * Check if the receive is still running.  If so, it will be owned.
1631 	 * Note that nothing else can own the dataset (e.g. after the receive
1632 	 * fails) because it will be marked inconsistent.
1633 	 */
1634 	if (dsl_dataset_has_owner(ds)) {
1635 		dsl_dataset_rele(ds, FTAG);
1636 		return (SET_ERROR(EBUSY));
1637 	}
1638 
1639 	/* There should not be any snapshots of this fs yet. */
1640 	if (ds->ds_prev != NULL && ds->ds_prev->ds_dir == ds->ds_dir) {
1641 		dsl_dataset_rele(ds, FTAG);
1642 		return (SET_ERROR(EINVAL));
1643 	}
1644 
1645 	/*
1646 	 * Note: resume point will be checked when we process the first WRITE
1647 	 * record.
1648 	 */
1649 
1650 	/* check that the origin matches */
1651 	val = 0;
1652 	(void) zap_lookup(dp->dp_meta_objset, ds->ds_object,
1653 	    DS_FIELD_RESUME_FROMGUID, sizeof (val), 1, &val);
1654 	if (drrb->drr_fromguid != val) {
1655 		dsl_dataset_rele(ds, FTAG);
1656 		return (SET_ERROR(EINVAL));
1657 	}
1658 
1659 	dsl_dataset_rele(ds, FTAG);
1660 	return (0);
1661 }
1662 
1663 static void
dmu_recv_resume_begin_sync(void * arg,dmu_tx_t * tx)1664 dmu_recv_resume_begin_sync(void *arg, dmu_tx_t *tx)
1665 {
1666 	dmu_recv_begin_arg_t *drba = arg;
1667 	dsl_pool_t *dp = dmu_tx_pool(tx);
1668 	const char *tofs = drba->drba_cookie->drc_tofs;
1669 	dsl_dataset_t *ds;
1670 	uint64_t dsobj;
1671 	/* 6 extra bytes for /%recv */
1672 	char recvname[ZFS_MAX_DATASET_NAME_LEN + 6];
1673 
1674 	(void) snprintf(recvname, sizeof (recvname), "%s/%s",
1675 	    tofs, recv_clone_name);
1676 
1677 	if (dsl_dataset_hold(dp, recvname, FTAG, &ds) != 0) {
1678 		/* %recv does not exist; continue in tofs */
1679 		VERIFY0(dsl_dataset_hold(dp, tofs, FTAG, &ds));
1680 		drba->drba_cookie->drc_newfs = B_TRUE;
1681 	}
1682 
1683 	/* clear the inconsistent flag so that we can own it */
1684 	ASSERT(DS_IS_INCONSISTENT(ds));
1685 	dmu_buf_will_dirty(ds->ds_dbuf, tx);
1686 	dsl_dataset_phys(ds)->ds_flags &= ~DS_FLAG_INCONSISTENT;
1687 	dsobj = ds->ds_object;
1688 	dsl_dataset_rele(ds, FTAG);
1689 
1690 	VERIFY0(dsl_dataset_own_obj(dp, dsobj, dmu_recv_tag, &ds));
1691 
1692 	dmu_buf_will_dirty(ds->ds_dbuf, tx);
1693 	dsl_dataset_phys(ds)->ds_flags |= DS_FLAG_INCONSISTENT;
1694 
1695 	rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);
1696 	ASSERT(!BP_IS_HOLE(dsl_dataset_get_blkptr(ds)));
1697 	rrw_exit(&ds->ds_bp_rwlock, FTAG);
1698 
1699 	drba->drba_cookie->drc_ds = ds;
1700 
1701 	spa_history_log_internal_ds(ds, "resume receive", tx, "");
1702 }
1703 
1704 /*
1705  * NB: callers *MUST* call dmu_recv_stream() if dmu_recv_begin()
1706  * succeeds; otherwise we will leak the holds on the datasets.
1707  */
1708 int
dmu_recv_begin(char * tofs,char * tosnap,dmu_replay_record_t * drr_begin,boolean_t force,boolean_t resumable,char * origin,dmu_recv_cookie_t * drc)1709 dmu_recv_begin(char *tofs, char *tosnap, dmu_replay_record_t *drr_begin,
1710     boolean_t force, boolean_t resumable, char *origin, dmu_recv_cookie_t *drc)
1711 {
1712 	dmu_recv_begin_arg_t drba = { 0 };
1713 
1714 	bzero(drc, sizeof (dmu_recv_cookie_t));
1715 	drc->drc_drr_begin = drr_begin;
1716 	drc->drc_drrb = &drr_begin->drr_u.drr_begin;
1717 	drc->drc_tosnap = tosnap;
1718 	drc->drc_tofs = tofs;
1719 	drc->drc_force = force;
1720 	drc->drc_resumable = resumable;
1721 	drc->drc_cred = CRED();
1722 
1723 	if (drc->drc_drrb->drr_magic == BSWAP_64(DMU_BACKUP_MAGIC)) {
1724 		drc->drc_byteswap = B_TRUE;
1725 		fletcher_4_incremental_byteswap(drr_begin,
1726 		    sizeof (dmu_replay_record_t), &drc->drc_cksum);
1727 		byteswap_record(drr_begin);
1728 	} else if (drc->drc_drrb->drr_magic == DMU_BACKUP_MAGIC) {
1729 		fletcher_4_incremental_native(drr_begin,
1730 		    sizeof (dmu_replay_record_t), &drc->drc_cksum);
1731 	} else {
1732 		return (SET_ERROR(EINVAL));
1733 	}
1734 
1735 	drba.drba_origin = origin;
1736 	drba.drba_cookie = drc;
1737 	drba.drba_cred = CRED();
1738 
1739 	if (DMU_GET_FEATUREFLAGS(drc->drc_drrb->drr_versioninfo) &
1740 	    DMU_BACKUP_FEATURE_RESUMING) {
1741 		return (dsl_sync_task(tofs,
1742 		    dmu_recv_resume_begin_check, dmu_recv_resume_begin_sync,
1743 		    &drba, 5, ZFS_SPACE_CHECK_NORMAL));
1744 	} else  {
1745 		return (dsl_sync_task(tofs,
1746 		    dmu_recv_begin_check, dmu_recv_begin_sync,
1747 		    &drba, 5, ZFS_SPACE_CHECK_NORMAL));
1748 	}
1749 }
1750 
1751 struct receive_record_arg {
1752 	dmu_replay_record_t header;
1753 	void *payload; /* Pointer to a buffer containing the payload */
1754 	/*
1755 	 * If the record is a write, pointer to the arc_buf_t containing the
1756 	 * payload.
1757 	 */
1758 	arc_buf_t *write_buf;
1759 	int payload_size;
1760 	uint64_t bytes_read; /* bytes read from stream when record created */
1761 	boolean_t eos_marker; /* Marks the end of the stream */
1762 	bqueue_node_t node;
1763 };
1764 
1765 struct receive_writer_arg {
1766 	objset_t *os;
1767 	boolean_t byteswap;
1768 	bqueue_t q;
1769 
1770 	/*
1771 	 * These three args are used to signal to the main thread that we're
1772 	 * done.
1773 	 */
1774 	kmutex_t mutex;
1775 	kcondvar_t cv;
1776 	boolean_t done;
1777 
1778 	int err;
1779 	/* A map from guid to dataset to help handle dedup'd streams. */
1780 	avl_tree_t *guid_to_ds_map;
1781 	boolean_t resumable;
1782 	uint64_t last_object, last_offset;
1783 	uint64_t bytes_read; /* bytes read when current record created */
1784 };
1785 
1786 struct objlist {
1787 	list_t list; /* List of struct receive_objnode. */
1788 	/*
1789 	 * Last object looked up. Used to assert that objects are being looked
1790 	 * up in ascending order.
1791 	 */
1792 	uint64_t last_lookup;
1793 };
1794 
1795 struct receive_objnode {
1796 	list_node_t node;
1797 	uint64_t object;
1798 };
1799 
1800 struct receive_arg  {
1801 	objset_t *os;
1802 	kthread_t *td;
1803 	struct file *fp;
1804 	uint64_t voff; /* The current offset in the stream */
1805 	uint64_t bytes_read;
1806 	/*
1807 	 * A record that has had its payload read in, but hasn't yet been handed
1808 	 * off to the worker thread.
1809 	 */
1810 	struct receive_record_arg *rrd;
1811 	/* A record that has had its header read in, but not its payload. */
1812 	struct receive_record_arg *next_rrd;
1813 	zio_cksum_t cksum;
1814 	zio_cksum_t prev_cksum;
1815 	int err;
1816 	boolean_t byteswap;
1817 	/* Sorted list of objects not to issue prefetches for. */
1818 	struct objlist ignore_objlist;
1819 };
1820 
1821 typedef struct guid_map_entry {
1822 	uint64_t	guid;
1823 	dsl_dataset_t	*gme_ds;
1824 	avl_node_t	avlnode;
1825 } guid_map_entry_t;
1826 
1827 static int
guid_compare(const void * arg1,const void * arg2)1828 guid_compare(const void *arg1, const void *arg2)
1829 {
1830 	const guid_map_entry_t *gmep1 = arg1;
1831 	const guid_map_entry_t *gmep2 = arg2;
1832 
1833 	if (gmep1->guid < gmep2->guid)
1834 		return (-1);
1835 	else if (gmep1->guid > gmep2->guid)
1836 		return (1);
1837 	return (0);
1838 }
1839 
1840 static void
free_guid_map_onexit(void * arg)1841 free_guid_map_onexit(void *arg)
1842 {
1843 	avl_tree_t *ca = arg;
1844 	void *cookie = NULL;
1845 	guid_map_entry_t *gmep;
1846 
1847 	while ((gmep = avl_destroy_nodes(ca, &cookie)) != NULL) {
1848 		dsl_dataset_long_rele(gmep->gme_ds, gmep);
1849 		dsl_dataset_rele(gmep->gme_ds, gmep);
1850 		kmem_free(gmep, sizeof (guid_map_entry_t));
1851 	}
1852 	avl_destroy(ca);
1853 	kmem_free(ca, sizeof (avl_tree_t));
1854 }
1855 
1856 static int
restore_bytes(struct receive_arg * ra,void * buf,int len,off_t off,ssize_t * resid)1857 restore_bytes(struct receive_arg *ra, void *buf, int len, off_t off, ssize_t *resid)
1858 {
1859 	struct uio auio;
1860 	struct iovec aiov;
1861 	int error;
1862 
1863 	aiov.iov_base = buf;
1864 	aiov.iov_len = len;
1865 	auio.uio_iov = &aiov;
1866 	auio.uio_iovcnt = 1;
1867 	auio.uio_resid = len;
1868 #ifdef __NetBSD__
1869 #ifdef _KERNEL
1870 	auio.uio_vmspace = vmspace_kernel();
1871 #endif
1872 #else
1873 	auio.uio_segflg = UIO_SYSSPACE;
1874 #endif
1875 	auio.uio_rw = UIO_READ;
1876 	auio.uio_offset = off;
1877 #ifdef __FreeBSD__
1878 	auio.uio_td = ra->td;
1879 #endif
1880 #ifdef _KERNEL
1881 	error = fo_read(ra->fp, &auio, ra->td->td_ucred, FOF_OFFSET, ra->td);
1882 #else
1883 	fprintf(stderr, "%s: returning EOPNOTSUPP\n", __func__);
1884 	error = EOPNOTSUPP;
1885 #endif
1886 	*resid = auio.uio_resid;
1887 	return (error);
1888 }
1889 
1890 static int
receive_read(struct receive_arg * ra,int len,void * buf)1891 receive_read(struct receive_arg *ra, int len, void *buf)
1892 {
1893 	int done = 0;
1894 
1895 	/*
1896 	 * The code doesn't rely on this (lengths being multiples of 8).  See
1897 	 * comment in dump_bytes.
1898 	 */
1899 	ASSERT0(len % 8);
1900 
1901 	while (done < len) {
1902 		ssize_t resid;
1903 
1904 		ra->err = restore_bytes(ra, buf + done,
1905 		    len - done, ra->voff, &resid);
1906 
1907 		if (resid == len - done) {
1908 			/*
1909 			 * Note: ECKSUM indicates that the receive
1910 			 * was interrupted and can potentially be resumed.
1911 			 */
1912 			ra->err = SET_ERROR(ECKSUM);
1913 		}
1914 		ra->voff += len - done - resid;
1915 		done = len - resid;
1916 		if (ra->err != 0)
1917 			return (ra->err);
1918 	}
1919 
1920 	ra->bytes_read += len;
1921 
1922 	ASSERT3U(done, ==, len);
1923 	return (0);
1924 }
1925 
1926 static void
byteswap_record(dmu_replay_record_t * drr)1927 byteswap_record(dmu_replay_record_t *drr)
1928 {
1929 #define	DO64(X) (drr->drr_u.X = BSWAP_64(drr->drr_u.X))
1930 #define	DO32(X) (drr->drr_u.X = BSWAP_32(drr->drr_u.X))
1931 	drr->drr_type = BSWAP_32(drr->drr_type);
1932 	drr->drr_payloadlen = BSWAP_32(drr->drr_payloadlen);
1933 
1934 	switch (drr->drr_type) {
1935 	case DRR_BEGIN:
1936 		DO64(drr_begin.drr_magic);
1937 		DO64(drr_begin.drr_versioninfo);
1938 		DO64(drr_begin.drr_creation_time);
1939 		DO32(drr_begin.drr_type);
1940 		DO32(drr_begin.drr_flags);
1941 		DO64(drr_begin.drr_toguid);
1942 		DO64(drr_begin.drr_fromguid);
1943 		break;
1944 	case DRR_OBJECT:
1945 		DO64(drr_object.drr_object);
1946 		DO32(drr_object.drr_type);
1947 		DO32(drr_object.drr_bonustype);
1948 		DO32(drr_object.drr_blksz);
1949 		DO32(drr_object.drr_bonuslen);
1950 		DO64(drr_object.drr_toguid);
1951 		break;
1952 	case DRR_FREEOBJECTS:
1953 		DO64(drr_freeobjects.drr_firstobj);
1954 		DO64(drr_freeobjects.drr_numobjs);
1955 		DO64(drr_freeobjects.drr_toguid);
1956 		break;
1957 	case DRR_WRITE:
1958 		DO64(drr_write.drr_object);
1959 		DO32(drr_write.drr_type);
1960 		DO64(drr_write.drr_offset);
1961 		DO64(drr_write.drr_length);
1962 		DO64(drr_write.drr_toguid);
1963 		ZIO_CHECKSUM_BSWAP(&drr->drr_u.drr_write.drr_key.ddk_cksum);
1964 		DO64(drr_write.drr_key.ddk_prop);
1965 		break;
1966 	case DRR_WRITE_BYREF:
1967 		DO64(drr_write_byref.drr_object);
1968 		DO64(drr_write_byref.drr_offset);
1969 		DO64(drr_write_byref.drr_length);
1970 		DO64(drr_write_byref.drr_toguid);
1971 		DO64(drr_write_byref.drr_refguid);
1972 		DO64(drr_write_byref.drr_refobject);
1973 		DO64(drr_write_byref.drr_refoffset);
1974 		ZIO_CHECKSUM_BSWAP(&drr->drr_u.drr_write_byref.
1975 		    drr_key.ddk_cksum);
1976 		DO64(drr_write_byref.drr_key.ddk_prop);
1977 		break;
1978 	case DRR_WRITE_EMBEDDED:
1979 		DO64(drr_write_embedded.drr_object);
1980 		DO64(drr_write_embedded.drr_offset);
1981 		DO64(drr_write_embedded.drr_length);
1982 		DO64(drr_write_embedded.drr_toguid);
1983 		DO32(drr_write_embedded.drr_lsize);
1984 		DO32(drr_write_embedded.drr_psize);
1985 		break;
1986 	case DRR_FREE:
1987 		DO64(drr_free.drr_object);
1988 		DO64(drr_free.drr_offset);
1989 		DO64(drr_free.drr_length);
1990 		DO64(drr_free.drr_toguid);
1991 		break;
1992 	case DRR_SPILL:
1993 		DO64(drr_spill.drr_object);
1994 		DO64(drr_spill.drr_length);
1995 		DO64(drr_spill.drr_toguid);
1996 		break;
1997 	case DRR_END:
1998 		DO64(drr_end.drr_toguid);
1999 		ZIO_CHECKSUM_BSWAP(&drr->drr_u.drr_end.drr_checksum);
2000 		break;
2001 	}
2002 
2003 	if (drr->drr_type != DRR_BEGIN) {
2004 		ZIO_CHECKSUM_BSWAP(&drr->drr_u.drr_checksum.drr_checksum);
2005 	}
2006 
2007 #undef DO64
2008 #undef DO32
2009 }
2010 
2011 static inline uint8_t
deduce_nblkptr(dmu_object_type_t bonus_type,uint64_t bonus_size)2012 deduce_nblkptr(dmu_object_type_t bonus_type, uint64_t bonus_size)
2013 {
2014 	if (bonus_type == DMU_OT_SA) {
2015 		return (1);
2016 	} else {
2017 		return (1 +
2018 		    ((DN_MAX_BONUSLEN - bonus_size) >> SPA_BLKPTRSHIFT));
2019 	}
2020 }
2021 
2022 static void
save_resume_state(struct receive_writer_arg * rwa,uint64_t object,uint64_t offset,dmu_tx_t * tx)2023 save_resume_state(struct receive_writer_arg *rwa,
2024     uint64_t object, uint64_t offset, dmu_tx_t *tx)
2025 {
2026 	int txgoff = dmu_tx_get_txg(tx) & TXG_MASK;
2027 
2028 	if (!rwa->resumable)
2029 		return;
2030 
2031 	/*
2032 	 * We use ds_resume_bytes[] != 0 to indicate that we need to
2033 	 * update this on disk, so it must not be 0.
2034 	 */
2035 	ASSERT(rwa->bytes_read != 0);
2036 
2037 	/*
2038 	 * We only resume from write records, which have a valid
2039 	 * (non-meta-dnode) object number.
2040 	 */
2041 	ASSERT(object != 0);
2042 
2043 	/*
2044 	 * For resuming to work correctly, we must receive records in order,
2045 	 * sorted by object,offset.  This is checked by the callers, but
2046 	 * assert it here for good measure.
2047 	 */
2048 	ASSERT3U(object, >=, rwa->os->os_dsl_dataset->ds_resume_object[txgoff]);
2049 	ASSERT(object != rwa->os->os_dsl_dataset->ds_resume_object[txgoff] ||
2050 	    offset >= rwa->os->os_dsl_dataset->ds_resume_offset[txgoff]);
2051 	ASSERT3U(rwa->bytes_read, >=,
2052 	    rwa->os->os_dsl_dataset->ds_resume_bytes[txgoff]);
2053 
2054 	rwa->os->os_dsl_dataset->ds_resume_object[txgoff] = object;
2055 	rwa->os->os_dsl_dataset->ds_resume_offset[txgoff] = offset;
2056 	rwa->os->os_dsl_dataset->ds_resume_bytes[txgoff] = rwa->bytes_read;
2057 }
2058 
2059 static int
receive_object(struct receive_writer_arg * rwa,struct drr_object * drro,void * data)2060 receive_object(struct receive_writer_arg *rwa, struct drr_object *drro,
2061     void *data)
2062 {
2063 	dmu_object_info_t doi;
2064 	dmu_tx_t *tx;
2065 	uint64_t object;
2066 	int err;
2067 
2068 	if (drro->drr_type == DMU_OT_NONE ||
2069 	    !DMU_OT_IS_VALID(drro->drr_type) ||
2070 	    !DMU_OT_IS_VALID(drro->drr_bonustype) ||
2071 	    drro->drr_checksumtype >= ZIO_CHECKSUM_FUNCTIONS ||
2072 	    drro->drr_compress >= ZIO_COMPRESS_FUNCTIONS ||
2073 	    P2PHASE(drro->drr_blksz, SPA_MINBLOCKSIZE) ||
2074 	    drro->drr_blksz < SPA_MINBLOCKSIZE ||
2075 	    drro->drr_blksz > spa_maxblocksize(dmu_objset_spa(rwa->os)) ||
2076 	    drro->drr_bonuslen > DN_MAX_BONUSLEN) {
2077 		return (SET_ERROR(EINVAL));
2078 	}
2079 
2080 	err = dmu_object_info(rwa->os, drro->drr_object, &doi);
2081 
2082 	if (err != 0 && err != ENOENT)
2083 		return (SET_ERROR(EINVAL));
2084 	object = err == 0 ? drro->drr_object : DMU_NEW_OBJECT;
2085 
2086 	/*
2087 	 * If we are losing blkptrs or changing the block size this must
2088 	 * be a new file instance.  We must clear out the previous file
2089 	 * contents before we can change this type of metadata in the dnode.
2090 	 */
2091 	if (err == 0) {
2092 		int nblkptr;
2093 
2094 		nblkptr = deduce_nblkptr(drro->drr_bonustype,
2095 		    drro->drr_bonuslen);
2096 
2097 		if (drro->drr_blksz != doi.doi_data_block_size ||
2098 		    nblkptr < doi.doi_nblkptr) {
2099 			err = dmu_free_long_range(rwa->os, drro->drr_object,
2100 			    0, DMU_OBJECT_END);
2101 			if (err != 0)
2102 				return (SET_ERROR(EINVAL));
2103 		}
2104 	}
2105 
2106 	tx = dmu_tx_create(rwa->os);
2107 	dmu_tx_hold_bonus(tx, object);
2108 	err = dmu_tx_assign(tx, TXG_WAIT);
2109 	if (err != 0) {
2110 		dmu_tx_abort(tx);
2111 		return (err);
2112 	}
2113 
2114 	if (object == DMU_NEW_OBJECT) {
2115 		/* currently free, want to be allocated */
2116 		err = dmu_object_claim(rwa->os, drro->drr_object,
2117 		    drro->drr_type, drro->drr_blksz,
2118 		    drro->drr_bonustype, drro->drr_bonuslen, tx);
2119 	} else if (drro->drr_type != doi.doi_type ||
2120 	    drro->drr_blksz != doi.doi_data_block_size ||
2121 	    drro->drr_bonustype != doi.doi_bonus_type ||
2122 	    drro->drr_bonuslen != doi.doi_bonus_size) {
2123 		/* currently allocated, but with different properties */
2124 		err = dmu_object_reclaim(rwa->os, drro->drr_object,
2125 		    drro->drr_type, drro->drr_blksz,
2126 		    drro->drr_bonustype, drro->drr_bonuslen, tx);
2127 	}
2128 	if (err != 0) {
2129 		dmu_tx_commit(tx);
2130 		return (SET_ERROR(EINVAL));
2131 	}
2132 
2133 	dmu_object_set_checksum(rwa->os, drro->drr_object,
2134 	    drro->drr_checksumtype, tx);
2135 	dmu_object_set_compress(rwa->os, drro->drr_object,
2136 	    drro->drr_compress, tx);
2137 
2138 	if (data != NULL) {
2139 		dmu_buf_t *db;
2140 
2141 		VERIFY0(dmu_bonus_hold(rwa->os, drro->drr_object, FTAG, &db));
2142 		dmu_buf_will_dirty(db, tx);
2143 
2144 		ASSERT3U(db->db_size, >=, drro->drr_bonuslen);
2145 		bcopy(data, db->db_data, drro->drr_bonuslen);
2146 		if (rwa->byteswap) {
2147 			dmu_object_byteswap_t byteswap =
2148 			    DMU_OT_BYTESWAP(drro->drr_bonustype);
2149 			dmu_ot_byteswap[byteswap].ob_func(db->db_data,
2150 			    drro->drr_bonuslen);
2151 		}
2152 		dmu_buf_rele(db, FTAG);
2153 	}
2154 	dmu_tx_commit(tx);
2155 
2156 	return (0);
2157 }
2158 
2159 /* ARGSUSED */
2160 static int
receive_freeobjects(struct receive_writer_arg * rwa,struct drr_freeobjects * drrfo)2161 receive_freeobjects(struct receive_writer_arg *rwa,
2162     struct drr_freeobjects *drrfo)
2163 {
2164 	uint64_t obj;
2165 	int next_err = 0;
2166 
2167 	if (drrfo->drr_firstobj + drrfo->drr_numobjs < drrfo->drr_firstobj)
2168 		return (SET_ERROR(EINVAL));
2169 
2170 	for (obj = drrfo->drr_firstobj;
2171 	    obj < drrfo->drr_firstobj + drrfo->drr_numobjs && next_err == 0;
2172 	    next_err = dmu_object_next(rwa->os, &obj, FALSE, 0)) {
2173 		int err;
2174 
2175 		if (dmu_object_info(rwa->os, obj, NULL) != 0)
2176 			continue;
2177 
2178 		err = dmu_free_long_object(rwa->os, obj);
2179 		if (err != 0)
2180 			return (err);
2181 	}
2182 	if (next_err != ESRCH)
2183 		return (next_err);
2184 	return (0);
2185 }
2186 
2187 static int
receive_write(struct receive_writer_arg * rwa,struct drr_write * drrw,arc_buf_t * abuf)2188 receive_write(struct receive_writer_arg *rwa, struct drr_write *drrw,
2189     arc_buf_t *abuf)
2190 {
2191 	dmu_tx_t *tx;
2192 	int err;
2193 
2194 	if (drrw->drr_offset + drrw->drr_length < drrw->drr_offset ||
2195 	    !DMU_OT_IS_VALID(drrw->drr_type))
2196 		return (SET_ERROR(EINVAL));
2197 
2198 	/*
2199 	 * For resuming to work, records must be in increasing order
2200 	 * by (object, offset).
2201 	 */
2202 	if (drrw->drr_object < rwa->last_object ||
2203 	    (drrw->drr_object == rwa->last_object &&
2204 	    drrw->drr_offset < rwa->last_offset)) {
2205 		return (SET_ERROR(EINVAL));
2206 	}
2207 	rwa->last_object = drrw->drr_object;
2208 	rwa->last_offset = drrw->drr_offset;
2209 
2210 	if (dmu_object_info(rwa->os, drrw->drr_object, NULL) != 0)
2211 		return (SET_ERROR(EINVAL));
2212 
2213 	tx = dmu_tx_create(rwa->os);
2214 
2215 	dmu_tx_hold_write(tx, drrw->drr_object,
2216 	    drrw->drr_offset, drrw->drr_length);
2217 	err = dmu_tx_assign(tx, TXG_WAIT);
2218 	if (err != 0) {
2219 		dmu_tx_abort(tx);
2220 		return (err);
2221 	}
2222 	if (rwa->byteswap) {
2223 		dmu_object_byteswap_t byteswap =
2224 		    DMU_OT_BYTESWAP(drrw->drr_type);
2225 		dmu_ot_byteswap[byteswap].ob_func(abuf->b_data,
2226 		    drrw->drr_length);
2227 	}
2228 
2229 	dmu_buf_t *bonus;
2230 	if (dmu_bonus_hold(rwa->os, drrw->drr_object, FTAG, &bonus) != 0)
2231 		return (SET_ERROR(EINVAL));
2232 	dmu_assign_arcbuf(bonus, drrw->drr_offset, abuf, tx);
2233 
2234 	/*
2235 	 * Note: If the receive fails, we want the resume stream to start
2236 	 * with the same record that we last successfully received (as opposed
2237 	 * to the next record), so that we can verify that we are
2238 	 * resuming from the correct location.
2239 	 */
2240 	save_resume_state(rwa, drrw->drr_object, drrw->drr_offset, tx);
2241 	dmu_tx_commit(tx);
2242 	dmu_buf_rele(bonus, FTAG);
2243 
2244 	return (0);
2245 }
2246 
2247 /*
2248  * Handle a DRR_WRITE_BYREF record.  This record is used in dedup'ed
2249  * streams to refer to a copy of the data that is already on the
2250  * system because it came in earlier in the stream.  This function
2251  * finds the earlier copy of the data, and uses that copy instead of
2252  * data from the stream to fulfill this write.
2253  */
2254 static int
receive_write_byref(struct receive_writer_arg * rwa,struct drr_write_byref * drrwbr)2255 receive_write_byref(struct receive_writer_arg *rwa,
2256     struct drr_write_byref *drrwbr)
2257 {
2258 	dmu_tx_t *tx;
2259 	int err;
2260 	guid_map_entry_t gmesrch;
2261 	guid_map_entry_t *gmep;
2262 	avl_index_t where;
2263 	objset_t *ref_os = NULL;
2264 	dmu_buf_t *dbp;
2265 
2266 	if (drrwbr->drr_offset + drrwbr->drr_length < drrwbr->drr_offset)
2267 		return (SET_ERROR(EINVAL));
2268 
2269 	/*
2270 	 * If the GUID of the referenced dataset is different from the
2271 	 * GUID of the target dataset, find the referenced dataset.
2272 	 */
2273 	if (drrwbr->drr_toguid != drrwbr->drr_refguid) {
2274 		gmesrch.guid = drrwbr->drr_refguid;
2275 		if ((gmep = avl_find(rwa->guid_to_ds_map, &gmesrch,
2276 		    &where)) == NULL) {
2277 			return (SET_ERROR(EINVAL));
2278 		}
2279 		if (dmu_objset_from_ds(gmep->gme_ds, &ref_os))
2280 			return (SET_ERROR(EINVAL));
2281 	} else {
2282 		ref_os = rwa->os;
2283 	}
2284 
2285 	err = dmu_buf_hold(ref_os, drrwbr->drr_refobject,
2286 	    drrwbr->drr_refoffset, FTAG, &dbp, DMU_READ_PREFETCH);
2287 	if (err != 0)
2288 		return (err);
2289 
2290 	tx = dmu_tx_create(rwa->os);
2291 
2292 	dmu_tx_hold_write(tx, drrwbr->drr_object,
2293 	    drrwbr->drr_offset, drrwbr->drr_length);
2294 	err = dmu_tx_assign(tx, TXG_WAIT);
2295 	if (err != 0) {
2296 		dmu_tx_abort(tx);
2297 		return (err);
2298 	}
2299 	dmu_write(rwa->os, drrwbr->drr_object,
2300 	    drrwbr->drr_offset, drrwbr->drr_length, dbp->db_data, tx);
2301 	dmu_buf_rele(dbp, FTAG);
2302 
2303 	/* See comment in restore_write. */
2304 	save_resume_state(rwa, drrwbr->drr_object, drrwbr->drr_offset, tx);
2305 	dmu_tx_commit(tx);
2306 	return (0);
2307 }
2308 
2309 static int
receive_write_embedded(struct receive_writer_arg * rwa,struct drr_write_embedded * drrwe,void * data)2310 receive_write_embedded(struct receive_writer_arg *rwa,
2311     struct drr_write_embedded *drrwe, void *data)
2312 {
2313 	dmu_tx_t *tx;
2314 	int err;
2315 
2316 	if (drrwe->drr_offset + drrwe->drr_length < drrwe->drr_offset)
2317 		return (EINVAL);
2318 
2319 	if (drrwe->drr_psize > BPE_PAYLOAD_SIZE)
2320 		return (EINVAL);
2321 
2322 	if (drrwe->drr_etype >= NUM_BP_EMBEDDED_TYPES)
2323 		return (EINVAL);
2324 	if (drrwe->drr_compression >= ZIO_COMPRESS_FUNCTIONS)
2325 		return (EINVAL);
2326 
2327 	tx = dmu_tx_create(rwa->os);
2328 
2329 	dmu_tx_hold_write(tx, drrwe->drr_object,
2330 	    drrwe->drr_offset, drrwe->drr_length);
2331 	err = dmu_tx_assign(tx, TXG_WAIT);
2332 	if (err != 0) {
2333 		dmu_tx_abort(tx);
2334 		return (err);
2335 	}
2336 
2337 	dmu_write_embedded(rwa->os, drrwe->drr_object,
2338 	    drrwe->drr_offset, data, drrwe->drr_etype,
2339 	    drrwe->drr_compression, drrwe->drr_lsize, drrwe->drr_psize,
2340 	    rwa->byteswap ^ ZFS_HOST_BYTEORDER, tx);
2341 
2342 	/* See comment in restore_write. */
2343 	save_resume_state(rwa, drrwe->drr_object, drrwe->drr_offset, tx);
2344 	dmu_tx_commit(tx);
2345 	return (0);
2346 }
2347 
2348 static int
receive_spill(struct receive_writer_arg * rwa,struct drr_spill * drrs,void * data)2349 receive_spill(struct receive_writer_arg *rwa, struct drr_spill *drrs,
2350     void *data)
2351 {
2352 	dmu_tx_t *tx;
2353 	dmu_buf_t *db, *db_spill;
2354 	int err;
2355 
2356 	if (drrs->drr_length < SPA_MINBLOCKSIZE ||
2357 	    drrs->drr_length > spa_maxblocksize(dmu_objset_spa(rwa->os)))
2358 		return (SET_ERROR(EINVAL));
2359 
2360 	if (dmu_object_info(rwa->os, drrs->drr_object, NULL) != 0)
2361 		return (SET_ERROR(EINVAL));
2362 
2363 	VERIFY0(dmu_bonus_hold(rwa->os, drrs->drr_object, FTAG, &db));
2364 	if ((err = dmu_spill_hold_by_bonus(db, FTAG, &db_spill)) != 0) {
2365 		dmu_buf_rele(db, FTAG);
2366 		return (err);
2367 	}
2368 
2369 	tx = dmu_tx_create(rwa->os);
2370 
2371 	dmu_tx_hold_spill(tx, db->db_object);
2372 
2373 	err = dmu_tx_assign(tx, TXG_WAIT);
2374 	if (err != 0) {
2375 		dmu_buf_rele(db, FTAG);
2376 		dmu_buf_rele(db_spill, FTAG);
2377 		dmu_tx_abort(tx);
2378 		return (err);
2379 	}
2380 	dmu_buf_will_dirty(db_spill, tx);
2381 
2382 	if (db_spill->db_size < drrs->drr_length)
2383 		VERIFY(0 == dbuf_spill_set_blksz(db_spill,
2384 		    drrs->drr_length, tx));
2385 	bcopy(data, db_spill->db_data, drrs->drr_length);
2386 
2387 	dmu_buf_rele(db, FTAG);
2388 	dmu_buf_rele(db_spill, FTAG);
2389 
2390 	dmu_tx_commit(tx);
2391 	return (0);
2392 }
2393 
2394 /* ARGSUSED */
2395 static int
receive_free(struct receive_writer_arg * rwa,struct drr_free * drrf)2396 receive_free(struct receive_writer_arg *rwa, struct drr_free *drrf)
2397 {
2398 	int err;
2399 
2400 	if (drrf->drr_length != -1ULL &&
2401 	    drrf->drr_offset + drrf->drr_length < drrf->drr_offset)
2402 		return (SET_ERROR(EINVAL));
2403 
2404 	if (dmu_object_info(rwa->os, drrf->drr_object, NULL) != 0)
2405 		return (SET_ERROR(EINVAL));
2406 
2407 	err = dmu_free_long_range(rwa->os, drrf->drr_object,
2408 	    drrf->drr_offset, drrf->drr_length);
2409 
2410 	return (err);
2411 }
2412 
2413 /* used to destroy the drc_ds on error */
2414 static void
dmu_recv_cleanup_ds(dmu_recv_cookie_t * drc)2415 dmu_recv_cleanup_ds(dmu_recv_cookie_t *drc)
2416 {
2417 	if (drc->drc_resumable) {
2418 		/* wait for our resume state to be written to disk */
2419 		txg_wait_synced(drc->drc_ds->ds_dir->dd_pool, 0);
2420 		dsl_dataset_disown(drc->drc_ds, dmu_recv_tag);
2421 	} else {
2422 		char name[ZFS_MAX_DATASET_NAME_LEN];
2423 		dsl_dataset_name(drc->drc_ds, name);
2424 		dsl_dataset_disown(drc->drc_ds, dmu_recv_tag);
2425 		(void) dsl_destroy_head(name);
2426 	}
2427 }
2428 
2429 static void
receive_cksum(struct receive_arg * ra,int len,void * buf)2430 receive_cksum(struct receive_arg *ra, int len, void *buf)
2431 {
2432 	if (ra->byteswap) {
2433 		fletcher_4_incremental_byteswap(buf, len, &ra->cksum);
2434 	} else {
2435 		fletcher_4_incremental_native(buf, len, &ra->cksum);
2436 	}
2437 }
2438 
2439 /*
2440  * Read the payload into a buffer of size len, and update the current record's
2441  * payload field.
2442  * Allocate ra->next_rrd and read the next record's header into
2443  * ra->next_rrd->header.
2444  * Verify checksum of payload and next record.
2445  */
2446 static int
receive_read_payload_and_next_header(struct receive_arg * ra,int len,void * buf)2447 receive_read_payload_and_next_header(struct receive_arg *ra, int len, void *buf)
2448 {
2449 	int err;
2450 
2451 	if (len != 0) {
2452 		ASSERT3U(len, <=, SPA_MAXBLOCKSIZE);
2453 		err = receive_read(ra, len, buf);
2454 		if (err != 0)
2455 			return (err);
2456 		receive_cksum(ra, len, buf);
2457 
2458 		/* note: rrd is NULL when reading the begin record's payload */
2459 		if (ra->rrd != NULL) {
2460 			ra->rrd->payload = buf;
2461 			ra->rrd->payload_size = len;
2462 			ra->rrd->bytes_read = ra->bytes_read;
2463 		}
2464 	}
2465 
2466 	ra->prev_cksum = ra->cksum;
2467 
2468 	ra->next_rrd = kmem_zalloc(sizeof (*ra->next_rrd), KM_SLEEP);
2469 	err = receive_read(ra, sizeof (ra->next_rrd->header),
2470 	    &ra->next_rrd->header);
2471 	ra->next_rrd->bytes_read = ra->bytes_read;
2472 	if (err != 0) {
2473 		kmem_free(ra->next_rrd, sizeof (*ra->next_rrd));
2474 		ra->next_rrd = NULL;
2475 		return (err);
2476 	}
2477 	if (ra->next_rrd->header.drr_type == DRR_BEGIN) {
2478 		kmem_free(ra->next_rrd, sizeof (*ra->next_rrd));
2479 		ra->next_rrd = NULL;
2480 		return (SET_ERROR(EINVAL));
2481 	}
2482 
2483 	/*
2484 	 * Note: checksum is of everything up to but not including the
2485 	 * checksum itself.
2486 	 */
2487 	ASSERT3U(offsetof(dmu_replay_record_t, drr_u.drr_checksum.drr_checksum),
2488 	    ==, sizeof (dmu_replay_record_t) - sizeof (zio_cksum_t));
2489 	receive_cksum(ra,
2490 	    offsetof(dmu_replay_record_t, drr_u.drr_checksum.drr_checksum),
2491 	    &ra->next_rrd->header);
2492 
2493 	zio_cksum_t cksum_orig =
2494 	    ra->next_rrd->header.drr_u.drr_checksum.drr_checksum;
2495 	zio_cksum_t *cksump =
2496 	    &ra->next_rrd->header.drr_u.drr_checksum.drr_checksum;
2497 
2498 	if (ra->byteswap)
2499 		byteswap_record(&ra->next_rrd->header);
2500 
2501 	if ((!ZIO_CHECKSUM_IS_ZERO(cksump)) &&
2502 	    !ZIO_CHECKSUM_EQUAL(ra->cksum, *cksump)) {
2503 		kmem_free(ra->next_rrd, sizeof (*ra->next_rrd));
2504 		ra->next_rrd = NULL;
2505 		return (SET_ERROR(ECKSUM));
2506 	}
2507 
2508 	receive_cksum(ra, sizeof (cksum_orig), &cksum_orig);
2509 
2510 	return (0);
2511 }
2512 
2513 static void
objlist_create(struct objlist * list)2514 objlist_create(struct objlist *list)
2515 {
2516 	list_create(&list->list, sizeof (struct receive_objnode),
2517 	    offsetof(struct receive_objnode, node));
2518 	list->last_lookup = 0;
2519 }
2520 
2521 static void
objlist_destroy(struct objlist * list)2522 objlist_destroy(struct objlist *list)
2523 {
2524 	for (struct receive_objnode *n = list_remove_head(&list->list);
2525 	    n != NULL; n = list_remove_head(&list->list)) {
2526 		kmem_free(n, sizeof (*n));
2527 	}
2528 	list_destroy(&list->list);
2529 }
2530 
2531 /*
2532  * This function looks through the objlist to see if the specified object number
2533  * is contained in the objlist.  In the process, it will remove all object
2534  * numbers in the list that are smaller than the specified object number.  Thus,
2535  * any lookup of an object number smaller than a previously looked up object
2536  * number will always return false; therefore, all lookups should be done in
2537  * ascending order.
2538  */
2539 static boolean_t
objlist_exists(struct objlist * list,uint64_t object)2540 objlist_exists(struct objlist *list, uint64_t object)
2541 {
2542 	struct receive_objnode *node = list_head(&list->list);
2543 	ASSERT3U(object, >=, list->last_lookup);
2544 	list->last_lookup = object;
2545 	while (node != NULL && node->object < object) {
2546 		VERIFY3P(node, ==, list_remove_head(&list->list));
2547 		kmem_free(node, sizeof (*node));
2548 		node = list_head(&list->list);
2549 	}
2550 	return (node != NULL && node->object == object);
2551 }
2552 
2553 /*
2554  * The objlist is a list of object numbers stored in ascending order.  However,
2555  * the insertion of new object numbers does not seek out the correct location to
2556  * store a new object number; instead, it appends it to the list for simplicity.
2557  * Thus, any users must take care to only insert new object numbers in ascending
2558  * order.
2559  */
2560 static void
objlist_insert(struct objlist * list,uint64_t object)2561 objlist_insert(struct objlist *list, uint64_t object)
2562 {
2563 	struct receive_objnode *node = kmem_zalloc(sizeof (*node), KM_SLEEP);
2564 	node->object = object;
2565 #ifdef ZFS_DEBUG
2566 	struct receive_objnode *last_object = list_tail(&list->list);
2567 	uint64_t last_objnum = (last_object != NULL ? last_object->object : 0);
2568 	ASSERT3U(node->object, >, last_objnum);
2569 #endif
2570 	list_insert_tail(&list->list, node);
2571 }
2572 
2573 /*
2574  * Issue the prefetch reads for any necessary indirect blocks.
2575  *
2576  * We use the object ignore list to tell us whether or not to issue prefetches
2577  * for a given object.  We do this for both correctness (in case the blocksize
2578  * of an object has changed) and performance (if the object doesn't exist, don't
2579  * needlessly try to issue prefetches).  We also trim the list as we go through
2580  * the stream to prevent it from growing to an unbounded size.
2581  *
2582  * The object numbers within will always be in sorted order, and any write
2583  * records we see will also be in sorted order, but they're not sorted with
2584  * respect to each other (i.e. we can get several object records before
2585  * receiving each object's write records).  As a result, once we've reached a
2586  * given object number, we can safely remove any reference to lower object
2587  * numbers in the ignore list. In practice, we receive up to 32 object records
2588  * before receiving write records, so the list can have up to 32 nodes in it.
2589  */
2590 /* ARGSUSED */
2591 static void
receive_read_prefetch(struct receive_arg * ra,uint64_t object,uint64_t offset,uint64_t length)2592 receive_read_prefetch(struct receive_arg *ra,
2593     uint64_t object, uint64_t offset, uint64_t length)
2594 {
2595 	if (!objlist_exists(&ra->ignore_objlist, object)) {
2596 		dmu_prefetch(ra->os, object, 1, offset, length,
2597 		    ZIO_PRIORITY_SYNC_READ);
2598 	}
2599 }
2600 
2601 /*
2602  * Read records off the stream, issuing any necessary prefetches.
2603  */
2604 static int
receive_read_record(struct receive_arg * ra)2605 receive_read_record(struct receive_arg *ra)
2606 {
2607 	int err;
2608 
2609 	switch (ra->rrd->header.drr_type) {
2610 	case DRR_OBJECT:
2611 	{
2612 		struct drr_object *drro = &ra->rrd->header.drr_u.drr_object;
2613 		uint32_t size = P2ROUNDUP(drro->drr_bonuslen, 8);
2614 		void *buf = kmem_zalloc(size, KM_SLEEP);
2615 		dmu_object_info_t doi;
2616 		err = receive_read_payload_and_next_header(ra, size, buf);
2617 		if (err != 0) {
2618 			kmem_free(buf, size);
2619 			return (err);
2620 		}
2621 		err = dmu_object_info(ra->os, drro->drr_object, &doi);
2622 		/*
2623 		 * See receive_read_prefetch for an explanation why we're
2624 		 * storing this object in the ignore_obj_list.
2625 		 */
2626 		if (err == ENOENT ||
2627 		    (err == 0 && doi.doi_data_block_size != drro->drr_blksz)) {
2628 			objlist_insert(&ra->ignore_objlist, drro->drr_object);
2629 			err = 0;
2630 		}
2631 		return (err);
2632 	}
2633 	case DRR_FREEOBJECTS:
2634 	{
2635 		err = receive_read_payload_and_next_header(ra, 0, NULL);
2636 		return (err);
2637 	}
2638 	case DRR_WRITE:
2639 	{
2640 		struct drr_write *drrw = &ra->rrd->header.drr_u.drr_write;
2641 		arc_buf_t *abuf = arc_loan_buf(dmu_objset_spa(ra->os),
2642 		    drrw->drr_length);
2643 
2644 		err = receive_read_payload_and_next_header(ra,
2645 		    drrw->drr_length, abuf->b_data);
2646 		if (err != 0) {
2647 			dmu_return_arcbuf(abuf);
2648 			return (err);
2649 		}
2650 		ra->rrd->write_buf = abuf;
2651 		receive_read_prefetch(ra, drrw->drr_object, drrw->drr_offset,
2652 		    drrw->drr_length);
2653 		return (err);
2654 	}
2655 	case DRR_WRITE_BYREF:
2656 	{
2657 		struct drr_write_byref *drrwb =
2658 		    &ra->rrd->header.drr_u.drr_write_byref;
2659 		err = receive_read_payload_and_next_header(ra, 0, NULL);
2660 		receive_read_prefetch(ra, drrwb->drr_object, drrwb->drr_offset,
2661 		    drrwb->drr_length);
2662 		return (err);
2663 	}
2664 	case DRR_WRITE_EMBEDDED:
2665 	{
2666 		struct drr_write_embedded *drrwe =
2667 		    &ra->rrd->header.drr_u.drr_write_embedded;
2668 		uint32_t size = P2ROUNDUP(drrwe->drr_psize, 8);
2669 		void *buf = kmem_zalloc(size, KM_SLEEP);
2670 
2671 		err = receive_read_payload_and_next_header(ra, size, buf);
2672 		if (err != 0) {
2673 			kmem_free(buf, size);
2674 			return (err);
2675 		}
2676 
2677 		receive_read_prefetch(ra, drrwe->drr_object, drrwe->drr_offset,
2678 		    drrwe->drr_length);
2679 		return (err);
2680 	}
2681 	case DRR_FREE:
2682 	{
2683 		/*
2684 		 * It might be beneficial to prefetch indirect blocks here, but
2685 		 * we don't really have the data to decide for sure.
2686 		 */
2687 		err = receive_read_payload_and_next_header(ra, 0, NULL);
2688 		return (err);
2689 	}
2690 	case DRR_END:
2691 	{
2692 		struct drr_end *drre = &ra->rrd->header.drr_u.drr_end;
2693 		if (!ZIO_CHECKSUM_EQUAL(ra->prev_cksum, drre->drr_checksum))
2694 			return (SET_ERROR(ECKSUM));
2695 		return (0);
2696 	}
2697 	case DRR_SPILL:
2698 	{
2699 		struct drr_spill *drrs = &ra->rrd->header.drr_u.drr_spill;
2700 		void *buf = kmem_zalloc(drrs->drr_length, KM_SLEEP);
2701 		err = receive_read_payload_and_next_header(ra, drrs->drr_length,
2702 		    buf);
2703 		if (err != 0)
2704 			kmem_free(buf, drrs->drr_length);
2705 		return (err);
2706 	}
2707 	default:
2708 		return (SET_ERROR(EINVAL));
2709 	}
2710 }
2711 
2712 /*
2713  * Commit the records to the pool.
2714  */
2715 static int
receive_process_record(struct receive_writer_arg * rwa,struct receive_record_arg * rrd)2716 receive_process_record(struct receive_writer_arg *rwa,
2717     struct receive_record_arg *rrd)
2718 {
2719 	int err;
2720 
2721 	/* Processing in order, therefore bytes_read should be increasing. */
2722 	ASSERT3U(rrd->bytes_read, >=, rwa->bytes_read);
2723 	rwa->bytes_read = rrd->bytes_read;
2724 
2725 	switch (rrd->header.drr_type) {
2726 	case DRR_OBJECT:
2727 	{
2728 		struct drr_object *drro = &rrd->header.drr_u.drr_object;
2729 		err = receive_object(rwa, drro, rrd->payload);
2730 		kmem_free(rrd->payload, rrd->payload_size);
2731 		rrd->payload = NULL;
2732 		return (err);
2733 	}
2734 	case DRR_FREEOBJECTS:
2735 	{
2736 		struct drr_freeobjects *drrfo =
2737 		    &rrd->header.drr_u.drr_freeobjects;
2738 		return (receive_freeobjects(rwa, drrfo));
2739 	}
2740 	case DRR_WRITE:
2741 	{
2742 		struct drr_write *drrw = &rrd->header.drr_u.drr_write;
2743 		err = receive_write(rwa, drrw, rrd->write_buf);
2744 		/* if receive_write() is successful, it consumes the arc_buf */
2745 		if (err != 0)
2746 			dmu_return_arcbuf(rrd->write_buf);
2747 		rrd->write_buf = NULL;
2748 		rrd->payload = NULL;
2749 		return (err);
2750 	}
2751 	case DRR_WRITE_BYREF:
2752 	{
2753 		struct drr_write_byref *drrwbr =
2754 		    &rrd->header.drr_u.drr_write_byref;
2755 		return (receive_write_byref(rwa, drrwbr));
2756 	}
2757 	case DRR_WRITE_EMBEDDED:
2758 	{
2759 		struct drr_write_embedded *drrwe =
2760 		    &rrd->header.drr_u.drr_write_embedded;
2761 		err = receive_write_embedded(rwa, drrwe, rrd->payload);
2762 		kmem_free(rrd->payload, rrd->payload_size);
2763 		rrd->payload = NULL;
2764 		return (err);
2765 	}
2766 	case DRR_FREE:
2767 	{
2768 		struct drr_free *drrf = &rrd->header.drr_u.drr_free;
2769 		return (receive_free(rwa, drrf));
2770 	}
2771 	case DRR_SPILL:
2772 	{
2773 		struct drr_spill *drrs = &rrd->header.drr_u.drr_spill;
2774 		err = receive_spill(rwa, drrs, rrd->payload);
2775 		kmem_free(rrd->payload, rrd->payload_size);
2776 		rrd->payload = NULL;
2777 		return (err);
2778 	}
2779 	default:
2780 		return (SET_ERROR(EINVAL));
2781 	}
2782 }
2783 
2784 /*
2785  * dmu_recv_stream's worker thread; pull records off the queue, and then call
2786  * receive_process_record  When we're done, signal the main thread and exit.
2787  */
2788 static void
receive_writer_thread(void * arg)2789 receive_writer_thread(void *arg)
2790 {
2791 	struct receive_writer_arg *rwa = arg;
2792 	struct receive_record_arg *rrd;
2793 	for (rrd = bqueue_dequeue(&rwa->q); !rrd->eos_marker;
2794 	    rrd = bqueue_dequeue(&rwa->q)) {
2795 		/*
2796 		 * If there's an error, the main thread will stop putting things
2797 		 * on the queue, but we need to clear everything in it before we
2798 		 * can exit.
2799 		 */
2800 		if (rwa->err == 0) {
2801 			rwa->err = receive_process_record(rwa, rrd);
2802 		} else if (rrd->write_buf != NULL) {
2803 			dmu_return_arcbuf(rrd->write_buf);
2804 			rrd->write_buf = NULL;
2805 			rrd->payload = NULL;
2806 		} else if (rrd->payload != NULL) {
2807 			kmem_free(rrd->payload, rrd->payload_size);
2808 			rrd->payload = NULL;
2809 		}
2810 		kmem_free(rrd, sizeof (*rrd));
2811 	}
2812 	kmem_free(rrd, sizeof (*rrd));
2813 	mutex_enter(&rwa->mutex);
2814 	rwa->done = B_TRUE;
2815 	cv_signal(&rwa->cv);
2816 	mutex_exit(&rwa->mutex);
2817 	thread_exit();
2818 }
2819 
2820 static int
resume_check(struct receive_arg * ra,nvlist_t * begin_nvl)2821 resume_check(struct receive_arg *ra, nvlist_t *begin_nvl)
2822 {
2823 	uint64_t val;
2824 	objset_t *mos = dmu_objset_pool(ra->os)->dp_meta_objset;
2825 	uint64_t dsobj = dmu_objset_id(ra->os);
2826 	uint64_t resume_obj, resume_off;
2827 
2828 	if (nvlist_lookup_uint64(begin_nvl,
2829 	    "resume_object", &resume_obj) != 0 ||
2830 	    nvlist_lookup_uint64(begin_nvl,
2831 	    "resume_offset", &resume_off) != 0) {
2832 		return (SET_ERROR(EINVAL));
2833 	}
2834 	VERIFY0(zap_lookup(mos, dsobj,
2835 	    DS_FIELD_RESUME_OBJECT, sizeof (val), 1, &val));
2836 	if (resume_obj != val)
2837 		return (SET_ERROR(EINVAL));
2838 	VERIFY0(zap_lookup(mos, dsobj,
2839 	    DS_FIELD_RESUME_OFFSET, sizeof (val), 1, &val));
2840 	if (resume_off != val)
2841 		return (SET_ERROR(EINVAL));
2842 
2843 	return (0);
2844 }
2845 
2846 /*
2847  * Read in the stream's records, one by one, and apply them to the pool.  There
2848  * are two threads involved; the thread that calls this function will spin up a
2849  * worker thread, read the records off the stream one by one, and issue
2850  * prefetches for any necessary indirect blocks.  It will then push the records
2851  * onto an internal blocking queue.  The worker thread will pull the records off
2852  * the queue, and actually write the data into the DMU.  This way, the worker
2853  * thread doesn't have to wait for reads to complete, since everything it needs
2854  * (the indirect blocks) will be prefetched.
2855  *
2856  * NB: callers *must* call dmu_recv_end() if this succeeds.
2857  */
2858 int
dmu_recv_stream(dmu_recv_cookie_t * drc,struct file * fp,offset_t * voffp,int cleanup_fd,uint64_t * action_handlep)2859 dmu_recv_stream(dmu_recv_cookie_t *drc, struct file *fp, offset_t *voffp,
2860     int cleanup_fd, uint64_t *action_handlep)
2861 {
2862 	int err = 0;
2863 	struct receive_arg ra = { 0 };
2864 	struct receive_writer_arg rwa = { 0 };
2865 	int featureflags;
2866 	nvlist_t *begin_nvl = NULL;
2867 
2868 	ra.byteswap = drc->drc_byteswap;
2869 	ra.cksum = drc->drc_cksum;
2870 	ra.td = curthread;
2871 	ra.fp = fp;
2872 	ra.voff = *voffp;
2873 
2874 	if (dsl_dataset_is_zapified(drc->drc_ds)) {
2875 		(void) zap_lookup(drc->drc_ds->ds_dir->dd_pool->dp_meta_objset,
2876 		    drc->drc_ds->ds_object, DS_FIELD_RESUME_BYTES,
2877 		    sizeof (ra.bytes_read), 1, &ra.bytes_read);
2878 	}
2879 
2880 	objlist_create(&ra.ignore_objlist);
2881 
2882 	/* these were verified in dmu_recv_begin */
2883 	ASSERT3U(DMU_GET_STREAM_HDRTYPE(drc->drc_drrb->drr_versioninfo), ==,
2884 	    DMU_SUBSTREAM);
2885 	ASSERT3U(drc->drc_drrb->drr_type, <, DMU_OST_NUMTYPES);
2886 
2887 	/*
2888 	 * Open the objset we are modifying.
2889 	 */
2890 	VERIFY0(dmu_objset_from_ds(drc->drc_ds, &ra.os));
2891 
2892 	ASSERT(dsl_dataset_phys(drc->drc_ds)->ds_flags & DS_FLAG_INCONSISTENT);
2893 
2894 	featureflags = DMU_GET_FEATUREFLAGS(drc->drc_drrb->drr_versioninfo);
2895 
2896 	/* if this stream is dedup'ed, set up the avl tree for guid mapping */
2897 	if (featureflags & DMU_BACKUP_FEATURE_DEDUP) {
2898 		minor_t minor;
2899 
2900 		if (cleanup_fd == -1) {
2901 			ra.err = SET_ERROR(EBADF);
2902 			goto out;
2903 		}
2904 		ra.err = zfs_onexit_fd_hold(cleanup_fd, &minor);
2905 		if (ra.err != 0) {
2906 			cleanup_fd = -1;
2907 			goto out;
2908 		}
2909 
2910 		if (*action_handlep == 0) {
2911 			rwa.guid_to_ds_map =
2912 			    kmem_alloc(sizeof (avl_tree_t), KM_SLEEP);
2913 			avl_create(rwa.guid_to_ds_map, guid_compare,
2914 			    sizeof (guid_map_entry_t),
2915 			    offsetof(guid_map_entry_t, avlnode));
2916 			err = zfs_onexit_add_cb(minor,
2917 			    free_guid_map_onexit, rwa.guid_to_ds_map,
2918 			    action_handlep);
2919 			if (ra.err != 0)
2920 				goto out;
2921 		} else {
2922 			err = zfs_onexit_cb_data(minor, *action_handlep,
2923 			    (void **)&rwa.guid_to_ds_map);
2924 			if (ra.err != 0)
2925 				goto out;
2926 		}
2927 
2928 		drc->drc_guid_to_ds_map = rwa.guid_to_ds_map;
2929 	}
2930 
2931 	uint32_t payloadlen = drc->drc_drr_begin->drr_payloadlen;
2932 	void *payload = NULL;
2933 	if (payloadlen != 0)
2934 		payload = kmem_alloc(payloadlen, KM_SLEEP);
2935 
2936 	err = receive_read_payload_and_next_header(&ra, payloadlen, payload);
2937 	if (err != 0) {
2938 		if (payloadlen != 0)
2939 			kmem_free(payload, payloadlen);
2940 		goto out;
2941 	}
2942 	if (payloadlen != 0) {
2943 		err = nvlist_unpack(payload, payloadlen, &begin_nvl, KM_SLEEP);
2944 		kmem_free(payload, payloadlen);
2945 		if (err != 0)
2946 			goto out;
2947 	}
2948 
2949 	if (featureflags & DMU_BACKUP_FEATURE_RESUMING) {
2950 		err = resume_check(&ra, begin_nvl);
2951 		if (err != 0)
2952 			goto out;
2953 	}
2954 
2955 	(void) bqueue_init(&rwa.q, zfs_recv_queue_length,
2956 	    offsetof(struct receive_record_arg, node));
2957 	cv_init(&rwa.cv, NULL, CV_DEFAULT, NULL);
2958 	mutex_init(&rwa.mutex, NULL, MUTEX_DEFAULT, NULL);
2959 	rwa.os = ra.os;
2960 	rwa.byteswap = drc->drc_byteswap;
2961 	rwa.resumable = drc->drc_resumable;
2962 
2963 	(void) thread_create(NULL, 0, receive_writer_thread, &rwa, 0, &p0,
2964 	    TS_RUN, minclsyspri);
2965 	/*
2966 	 * We're reading rwa.err without locks, which is safe since we are the
2967 	 * only reader, and the worker thread is the only writer.  It's ok if we
2968 	 * miss a write for an iteration or two of the loop, since the writer
2969 	 * thread will keep freeing records we send it until we send it an eos
2970 	 * marker.
2971 	 *
2972 	 * We can leave this loop in 3 ways:  First, if rwa.err is
2973 	 * non-zero.  In that case, the writer thread will free the rrd we just
2974 	 * pushed.  Second, if  we're interrupted; in that case, either it's the
2975 	 * first loop and ra.rrd was never allocated, or it's later, and ra.rrd
2976 	 * has been handed off to the writer thread who will free it.  Finally,
2977 	 * if receive_read_record fails or we're at the end of the stream, then
2978 	 * we free ra.rrd and exit.
2979 	 */
2980 	while (rwa.err == 0) {
2981 		if (issig(JUSTLOOKING) && issig(FORREAL)) {
2982 			err = SET_ERROR(EINTR);
2983 			break;
2984 		}
2985 
2986 		ASSERT3P(ra.rrd, ==, NULL);
2987 		ra.rrd = ra.next_rrd;
2988 		ra.next_rrd = NULL;
2989 		/* Allocates and loads header into ra.next_rrd */
2990 		err = receive_read_record(&ra);
2991 
2992 		if (ra.rrd->header.drr_type == DRR_END || err != 0) {
2993 			kmem_free(ra.rrd, sizeof (*ra.rrd));
2994 			ra.rrd = NULL;
2995 			break;
2996 		}
2997 
2998 		bqueue_enqueue(&rwa.q, ra.rrd,
2999 		    sizeof (struct receive_record_arg) + ra.rrd->payload_size);
3000 		ra.rrd = NULL;
3001 	}
3002 	if (ra.next_rrd == NULL)
3003 		ra.next_rrd = kmem_zalloc(sizeof (*ra.next_rrd), KM_SLEEP);
3004 	ra.next_rrd->eos_marker = B_TRUE;
3005 	bqueue_enqueue(&rwa.q, ra.next_rrd, 1);
3006 
3007 	mutex_enter(&rwa.mutex);
3008 	while (!rwa.done) {
3009 		cv_wait(&rwa.cv, &rwa.mutex);
3010 	}
3011 	mutex_exit(&rwa.mutex);
3012 
3013 	cv_destroy(&rwa.cv);
3014 	mutex_destroy(&rwa.mutex);
3015 	bqueue_destroy(&rwa.q);
3016 	if (err == 0)
3017 		err = rwa.err;
3018 
3019 out:
3020 	nvlist_free(begin_nvl);
3021 	if ((featureflags & DMU_BACKUP_FEATURE_DEDUP) && (cleanup_fd != -1))
3022 		zfs_onexit_fd_rele(cleanup_fd);
3023 
3024 	if (err != 0) {
3025 		/*
3026 		 * Clean up references. If receive is not resumable,
3027 		 * destroy what we created, so we don't leave it in
3028 		 * the inconsistent state.
3029 		 */
3030 		dmu_recv_cleanup_ds(drc);
3031 	}
3032 
3033 	*voffp = ra.voff;
3034 	objlist_destroy(&ra.ignore_objlist);
3035 	return (err);
3036 }
3037 
3038 static int
dmu_recv_end_check(void * arg,dmu_tx_t * tx)3039 dmu_recv_end_check(void *arg, dmu_tx_t *tx)
3040 {
3041 	dmu_recv_cookie_t *drc = arg;
3042 	dsl_pool_t *dp = dmu_tx_pool(tx);
3043 	int error;
3044 
3045 	ASSERT3P(drc->drc_ds->ds_owner, ==, dmu_recv_tag);
3046 
3047 	if (!drc->drc_newfs) {
3048 		dsl_dataset_t *origin_head;
3049 
3050 		error = dsl_dataset_hold(dp, drc->drc_tofs, FTAG, &origin_head);
3051 		if (error != 0)
3052 			return (error);
3053 		if (drc->drc_force) {
3054 			/*
3055 			 * We will destroy any snapshots in tofs (i.e. before
3056 			 * origin_head) that are after the origin (which is
3057 			 * the snap before drc_ds, because drc_ds can not
3058 			 * have any snaps of its own).
3059 			 */
3060 			uint64_t obj;
3061 
3062 			obj = dsl_dataset_phys(origin_head)->ds_prev_snap_obj;
3063 			while (obj !=
3064 			    dsl_dataset_phys(drc->drc_ds)->ds_prev_snap_obj) {
3065 				dsl_dataset_t *snap;
3066 				error = dsl_dataset_hold_obj(dp, obj, FTAG,
3067 				    &snap);
3068 				if (error != 0)
3069 					break;
3070 				if (snap->ds_dir != origin_head->ds_dir)
3071 					error = SET_ERROR(EINVAL);
3072 				if (error == 0)  {
3073 					error = dsl_destroy_snapshot_check_impl(
3074 					    snap, B_FALSE);
3075 				}
3076 				obj = dsl_dataset_phys(snap)->ds_prev_snap_obj;
3077 				dsl_dataset_rele(snap, FTAG);
3078 				if (error != 0)
3079 					break;
3080 			}
3081 			if (error != 0) {
3082 				dsl_dataset_rele(origin_head, FTAG);
3083 				return (error);
3084 			}
3085 		}
3086 		error = dsl_dataset_clone_swap_check_impl(drc->drc_ds,
3087 		    origin_head, drc->drc_force, drc->drc_owner, tx);
3088 		if (error != 0) {
3089 			dsl_dataset_rele(origin_head, FTAG);
3090 			return (error);
3091 		}
3092 		error = dsl_dataset_snapshot_check_impl(origin_head,
3093 		    drc->drc_tosnap, tx, B_TRUE, 1, drc->drc_cred);
3094 		dsl_dataset_rele(origin_head, FTAG);
3095 		if (error != 0)
3096 			return (error);
3097 
3098 		error = dsl_destroy_head_check_impl(drc->drc_ds, 1);
3099 	} else {
3100 		error = dsl_dataset_snapshot_check_impl(drc->drc_ds,
3101 		    drc->drc_tosnap, tx, B_TRUE, 1, drc->drc_cred);
3102 	}
3103 	return (error);
3104 }
3105 
3106 static void
dmu_recv_end_sync(void * arg,dmu_tx_t * tx)3107 dmu_recv_end_sync(void *arg, dmu_tx_t *tx)
3108 {
3109 	dmu_recv_cookie_t *drc = arg;
3110 	dsl_pool_t *dp = dmu_tx_pool(tx);
3111 
3112 	spa_history_log_internal_ds(drc->drc_ds, "finish receiving",
3113 	    tx, "snap=%s", drc->drc_tosnap);
3114 
3115 	if (!drc->drc_newfs) {
3116 		dsl_dataset_t *origin_head;
3117 
3118 		VERIFY0(dsl_dataset_hold(dp, drc->drc_tofs, FTAG,
3119 		    &origin_head));
3120 
3121 		if (drc->drc_force) {
3122 			/*
3123 			 * Destroy any snapshots of drc_tofs (origin_head)
3124 			 * after the origin (the snap before drc_ds).
3125 			 */
3126 			uint64_t obj;
3127 
3128 			obj = dsl_dataset_phys(origin_head)->ds_prev_snap_obj;
3129 			while (obj !=
3130 			    dsl_dataset_phys(drc->drc_ds)->ds_prev_snap_obj) {
3131 				dsl_dataset_t *snap;
3132 				VERIFY0(dsl_dataset_hold_obj(dp, obj, FTAG,
3133 				    &snap));
3134 				ASSERT3P(snap->ds_dir, ==, origin_head->ds_dir);
3135 				obj = dsl_dataset_phys(snap)->ds_prev_snap_obj;
3136 				dsl_destroy_snapshot_sync_impl(snap,
3137 				    B_FALSE, tx);
3138 				dsl_dataset_rele(snap, FTAG);
3139 			}
3140 		}
3141 		VERIFY3P(drc->drc_ds->ds_prev, ==,
3142 		    origin_head->ds_prev);
3143 
3144 		dsl_dataset_clone_swap_sync_impl(drc->drc_ds,
3145 		    origin_head, tx);
3146 		dsl_dataset_snapshot_sync_impl(origin_head,
3147 		    drc->drc_tosnap, tx);
3148 
3149 		/* set snapshot's creation time and guid */
3150 		dmu_buf_will_dirty(origin_head->ds_prev->ds_dbuf, tx);
3151 		dsl_dataset_phys(origin_head->ds_prev)->ds_creation_time =
3152 		    drc->drc_drrb->drr_creation_time;
3153 		dsl_dataset_phys(origin_head->ds_prev)->ds_guid =
3154 		    drc->drc_drrb->drr_toguid;
3155 		dsl_dataset_phys(origin_head->ds_prev)->ds_flags &=
3156 		    ~DS_FLAG_INCONSISTENT;
3157 
3158 		dmu_buf_will_dirty(origin_head->ds_dbuf, tx);
3159 		dsl_dataset_phys(origin_head)->ds_flags &=
3160 		    ~DS_FLAG_INCONSISTENT;
3161 
3162 		drc->drc_newsnapobj =
3163 		    dsl_dataset_phys(origin_head)->ds_prev_snap_obj;
3164 
3165 		dsl_dataset_rele(origin_head, FTAG);
3166 		dsl_destroy_head_sync_impl(drc->drc_ds, tx);
3167 
3168 		if (drc->drc_owner != NULL)
3169 			VERIFY3P(origin_head->ds_owner, ==, drc->drc_owner);
3170 	} else {
3171 		dsl_dataset_t *ds = drc->drc_ds;
3172 
3173 		dsl_dataset_snapshot_sync_impl(ds, drc->drc_tosnap, tx);
3174 
3175 		/* set snapshot's creation time and guid */
3176 		dmu_buf_will_dirty(ds->ds_prev->ds_dbuf, tx);
3177 		dsl_dataset_phys(ds->ds_prev)->ds_creation_time =
3178 		    drc->drc_drrb->drr_creation_time;
3179 		dsl_dataset_phys(ds->ds_prev)->ds_guid =
3180 		    drc->drc_drrb->drr_toguid;
3181 		dsl_dataset_phys(ds->ds_prev)->ds_flags &=
3182 		    ~DS_FLAG_INCONSISTENT;
3183 
3184 		dmu_buf_will_dirty(ds->ds_dbuf, tx);
3185 		dsl_dataset_phys(ds)->ds_flags &= ~DS_FLAG_INCONSISTENT;
3186 		if (dsl_dataset_has_resume_receive_state(ds)) {
3187 			(void) zap_remove(dp->dp_meta_objset, ds->ds_object,
3188 			    DS_FIELD_RESUME_FROMGUID, tx);
3189 			(void) zap_remove(dp->dp_meta_objset, ds->ds_object,
3190 			    DS_FIELD_RESUME_OBJECT, tx);
3191 			(void) zap_remove(dp->dp_meta_objset, ds->ds_object,
3192 			    DS_FIELD_RESUME_OFFSET, tx);
3193 			(void) zap_remove(dp->dp_meta_objset, ds->ds_object,
3194 			    DS_FIELD_RESUME_BYTES, tx);
3195 			(void) zap_remove(dp->dp_meta_objset, ds->ds_object,
3196 			    DS_FIELD_RESUME_TOGUID, tx);
3197 			(void) zap_remove(dp->dp_meta_objset, ds->ds_object,
3198 			    DS_FIELD_RESUME_TONAME, tx);
3199 		}
3200 		drc->drc_newsnapobj =
3201 		    dsl_dataset_phys(drc->drc_ds)->ds_prev_snap_obj;
3202 	}
3203 	/*
3204 	 * Release the hold from dmu_recv_begin.  This must be done before
3205 	 * we return to open context, so that when we free the dataset's dnode,
3206 	 * we can evict its bonus buffer.
3207 	 */
3208 	dsl_dataset_disown(drc->drc_ds, dmu_recv_tag);
3209 	drc->drc_ds = NULL;
3210 }
3211 
3212 static int
add_ds_to_guidmap(const char * name,avl_tree_t * guid_map,uint64_t snapobj)3213 add_ds_to_guidmap(const char *name, avl_tree_t *guid_map, uint64_t snapobj)
3214 {
3215 	dsl_pool_t *dp;
3216 	dsl_dataset_t *snapds;
3217 	guid_map_entry_t *gmep;
3218 	int err;
3219 
3220 	ASSERT(guid_map != NULL);
3221 
3222 	err = dsl_pool_hold(name, FTAG, &dp);
3223 	if (err != 0)
3224 		return (err);
3225 	gmep = kmem_alloc(sizeof (*gmep), KM_SLEEP);
3226 	err = dsl_dataset_hold_obj(dp, snapobj, gmep, &snapds);
3227 	if (err == 0) {
3228 		gmep->guid = dsl_dataset_phys(snapds)->ds_guid;
3229 		gmep->gme_ds = snapds;
3230 		avl_add(guid_map, gmep);
3231 		dsl_dataset_long_hold(snapds, gmep);
3232 	} else
3233 		kmem_free(gmep, sizeof (*gmep));
3234 
3235 	dsl_pool_rele(dp, FTAG);
3236 	return (err);
3237 }
3238 
3239 static int dmu_recv_end_modified_blocks = 3;
3240 
3241 static int
dmu_recv_existing_end(dmu_recv_cookie_t * drc)3242 dmu_recv_existing_end(dmu_recv_cookie_t *drc)
3243 {
3244 #ifdef _KERNEL
3245 	/*
3246 	 * We will be destroying the ds; make sure its origin is unmounted if
3247 	 * necessary.
3248 	 */
3249 	char name[ZFS_MAX_DATASET_NAME_LEN];
3250 	dsl_dataset_name(drc->drc_ds, name);
3251 	zfs_destroy_unmount_origin(name);
3252 #endif
3253 
3254 	return (dsl_sync_task(drc->drc_tofs,
3255 	    dmu_recv_end_check, dmu_recv_end_sync, drc,
3256 	    dmu_recv_end_modified_blocks, ZFS_SPACE_CHECK_NORMAL));
3257 }
3258 
3259 static int
dmu_recv_new_end(dmu_recv_cookie_t * drc)3260 dmu_recv_new_end(dmu_recv_cookie_t *drc)
3261 {
3262 	return (dsl_sync_task(drc->drc_tofs,
3263 	    dmu_recv_end_check, dmu_recv_end_sync, drc,
3264 	    dmu_recv_end_modified_blocks, ZFS_SPACE_CHECK_NORMAL));
3265 }
3266 
3267 int
dmu_recv_end(dmu_recv_cookie_t * drc,void * owner)3268 dmu_recv_end(dmu_recv_cookie_t *drc, void *owner)
3269 {
3270 	int error;
3271 
3272 	drc->drc_owner = owner;
3273 
3274 	if (drc->drc_newfs)
3275 		error = dmu_recv_new_end(drc);
3276 	else
3277 		error = dmu_recv_existing_end(drc);
3278 
3279 	if (error != 0) {
3280 		dmu_recv_cleanup_ds(drc);
3281 	} else if (drc->drc_guid_to_ds_map != NULL) {
3282 		(void) add_ds_to_guidmap(drc->drc_tofs,
3283 		    drc->drc_guid_to_ds_map,
3284 		    drc->drc_newsnapobj);
3285 	}
3286 	return (error);
3287 }
3288 
3289 /*
3290  * Return TRUE if this objset is currently being received into.
3291  */
3292 boolean_t
dmu_objset_is_receiving(objset_t * os)3293 dmu_objset_is_receiving(objset_t *os)
3294 {
3295 	return (os->os_dsl_dataset != NULL &&
3296 	    os->os_dsl_dataset->ds_owner == dmu_recv_tag);
3297 }
3298