]> git.proxmox.com Git - mirror_zfs.git/blame - module/zfs/dmu_send.c
Fix arc_release() refcount
[mirror_zfs.git] / module / zfs / dmu_send.c
CommitLineData
34dc7c2f
BB
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/*
428870ff 22 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
8d35c149 23 * Copyright 2011 Nexenta Systems, Inc. All rights reserved.
e6d3a843 24 * Copyright (c) 2011, 2015 by Delphix. All rights reserved.
788eb90c 25 * Copyright (c) 2014, Joyent, Inc. All rights reserved.
47dfff3b 26 * Copyright 2014 HybridCluster. All rights reserved.
b607405f 27 * Copyright 2016 RackTop Systems.
a0bd735a 28 * Copyright (c) 2016 Actifio, Inc. All rights reserved.
8d35c149 29 */
34dc7c2f 30
34dc7c2f
BB
31#include <sys/dmu.h>
32#include <sys/dmu_impl.h>
33#include <sys/dmu_tx.h>
34#include <sys/dbuf.h>
35#include <sys/dnode.h>
36#include <sys/zfs_context.h>
37#include <sys/dmu_objset.h>
38#include <sys/dmu_traverse.h>
39#include <sys/dsl_dataset.h>
40#include <sys/dsl_dir.h>
428870ff 41#include <sys/dsl_prop.h>
34dc7c2f
BB
42#include <sys/dsl_pool.h>
43#include <sys/dsl_synctask.h>
044baf00 44#include <sys/spa_impl.h>
34dc7c2f
BB
45#include <sys/zfs_ioctl.h>
46#include <sys/zap.h>
47#include <sys/zio_checksum.h>
428870ff
BB
48#include <sys/zfs_znode.h>
49#include <zfs_fletcher.h>
50#include <sys/avl.h>
51#include <sys/ddt.h>
572e2857 52#include <sys/zfs_onexit.h>
13fe0198
MA
53#include <sys/dmu_send.h>
54#include <sys/dsl_destroy.h>
9b67f605 55#include <sys/blkptr.h>
da536844 56#include <sys/dsl_bookmark.h>
9b67f605 57#include <sys/zfeature.h>
fcff0f35 58#include <sys/bqueue.h>
a0bd735a 59#include <sys/zvol.h>
f74b821a 60#include <sys/policy.h>
34dc7c2f 61
330d06f9
MA
62/* Set this tunable to TRUE to replace corrupt data with 0x2f5baddb10c */
63int zfs_send_corrupt_data = B_FALSE;
3b0d9928
BB
64int zfs_send_queue_length = SPA_MAXBLOCKSIZE;
65int zfs_recv_queue_length = SPA_MAXBLOCKSIZE;
b607405f
AS
66/* Set this tunable to FALSE to disable setting of DRR_FLAG_FREERECORDS */
67int zfs_send_set_freerecords_bit = B_TRUE;
330d06f9 68
34dc7c2f 69static char *dmu_recv_tag = "dmu_recv_tag";
47dfff3b 70const char *recv_clone_name = "%recv";
34dc7c2f 71
ca0845d5
PD
72/*
73 * Use this to override the recordsize calculation for fast zfs send estimates.
74 */
75unsigned long zfs_override_estimate_recordsize = 0;
76
fcff0f35
PD
77#define BP_SPAN(datablkszsec, indblkshift, level) \
78 (((uint64_t)datablkszsec) << (SPA_MINBLOCKSHIFT + \
79 (level) * (indblkshift - SPA_BLKPTRSHIFT)))
80
47dfff3b
MA
81static void byteswap_record(dmu_replay_record_t *drr);
82
fcff0f35
PD
83struct send_thread_arg {
84 bqueue_t q;
85 dsl_dataset_t *ds; /* Dataset to traverse */
86 uint64_t fromtxg; /* Traverse from this txg */
87 int flags; /* flags to pass to traverse_dataset */
88 int error_code;
89 boolean_t cancel;
47dfff3b 90 zbookmark_phys_t resume;
fcff0f35
PD
91};
92
93struct send_block_record {
94 boolean_t eos_marker; /* Marks the end of the stream */
95 blkptr_t bp;
96 zbookmark_phys_t zb;
97 uint8_t indblkshift;
98 uint16_t datablkszsec;
99 bqueue_node_t ln;
100};
101
044baf00
BB
102typedef struct dump_bytes_io {
103 dmu_sendarg_t *dbi_dsp;
104 void *dbi_buf;
105 int dbi_len;
106} dump_bytes_io_t;
107
108static void
b58986ee 109dump_bytes_cb(void *arg)
34dc7c2f 110{
044baf00
BB
111 dump_bytes_io_t *dbi = (dump_bytes_io_t *)arg;
112 dmu_sendarg_t *dsp = dbi->dbi_dsp;
47dfff3b 113 dsl_dataset_t *ds = dmu_objset_ds(dsp->dsa_os);
34dc7c2f 114 ssize_t resid; /* have to get resid to get detailed errno */
f8866f8a
ER
115
116 /*
b5256303 117 * The code does not rely on len being a multiple of 8. We keep
f8866f8a
ER
118 * this assertion because of the corresponding assertion in
119 * receive_read(). Keeping this assertion ensures that we do not
120 * inadvertently break backwards compatibility (causing the assertion
b5256303
TC
121 * in receive_read() to trigger on old software). Newer feature flags
122 * (such as raw send) may break this assertion since they were
123 * introduced after the requirement was made obsolete.
f8866f8a
ER
124 */
125
b5256303
TC
126 ASSERT(dbi->dbi_len % 8 == 0 ||
127 (dsp->dsa_featureflags & DMU_BACKUP_FEATURE_RAW) != 0);
34dc7c2f 128
37abac6d 129 dsp->dsa_err = vn_rdwr(UIO_WRITE, dsp->dsa_vp,
044baf00 130 (caddr_t)dbi->dbi_buf, dbi->dbi_len,
34dc7c2f 131 0, UIO_SYSSPACE, FAPPEND, RLIM64_INFINITY, CRED(), &resid);
37abac6d
BP
132
133 mutex_enter(&ds->ds_sendstream_lock);
044baf00 134 *dsp->dsa_off += dbi->dbi_len;
37abac6d 135 mutex_exit(&ds->ds_sendstream_lock);
044baf00
BB
136}
137
138static int
139dump_bytes(dmu_sendarg_t *dsp, void *buf, int len)
140{
141 dump_bytes_io_t dbi;
142
143 dbi.dbi_dsp = dsp;
144 dbi.dbi_buf = buf;
145 dbi.dbi_len = len;
146
b58986ee
BB
147#if defined(HAVE_LARGE_STACKS)
148 dump_bytes_cb(&dbi);
149#else
044baf00
BB
150 /*
151 * The vn_rdwr() call is performed in a taskq to ensure that there is
152 * always enough stack space to write safely to the target filesystem.
153 * The ZIO_TYPE_FREE threads are used because there can be a lot of
154 * them and they are used in vdev_file.c for a similar purpose.
155 */
156 spa_taskq_dispatch_sync(dmu_objset_spa(dsp->dsa_os), ZIO_TYPE_FREE,
b58986ee
BB
157 ZIO_TASKQ_ISSUE, dump_bytes_cb, &dbi, TQ_SLEEP);
158#endif /* HAVE_LARGE_STACKS */
37abac6d
BP
159
160 return (dsp->dsa_err);
34dc7c2f
BB
161}
162
37f8a883
MA
163/*
164 * For all record types except BEGIN, fill in the checksum (overlaid in
165 * drr_u.drr_checksum.drr_checksum). The checksum verifies everything
166 * up to the start of the checksum itself.
167 */
168static int
169dump_record(dmu_sendarg_t *dsp, void *payload, int payload_len)
170{
171 ASSERT3U(offsetof(dmu_replay_record_t, drr_u.drr_checksum.drr_checksum),
172 ==, sizeof (dmu_replay_record_t) - sizeof (zio_cksum_t));
a6255b7f 173 (void) fletcher_4_incremental_native(dsp->dsa_drr,
37f8a883
MA
174 offsetof(dmu_replay_record_t, drr_u.drr_checksum.drr_checksum),
175 &dsp->dsa_zc);
51907a31
K
176 if (dsp->dsa_drr->drr_type == DRR_BEGIN) {
177 dsp->dsa_sent_begin = B_TRUE;
178 } else {
37f8a883
MA
179 ASSERT(ZIO_CHECKSUM_IS_ZERO(&dsp->dsa_drr->drr_u.
180 drr_checksum.drr_checksum));
181 dsp->dsa_drr->drr_u.drr_checksum.drr_checksum = dsp->dsa_zc;
182 }
51907a31
K
183 if (dsp->dsa_drr->drr_type == DRR_END) {
184 dsp->dsa_sent_end = B_TRUE;
185 }
a6255b7f 186 (void) fletcher_4_incremental_native(&dsp->dsa_drr->
37f8a883
MA
187 drr_u.drr_checksum.drr_checksum,
188 sizeof (zio_cksum_t), &dsp->dsa_zc);
189 if (dump_bytes(dsp, dsp->dsa_drr, sizeof (dmu_replay_record_t)) != 0)
190 return (SET_ERROR(EINTR));
191 if (payload_len != 0) {
a6255b7f 192 (void) fletcher_4_incremental_native(payload, payload_len,
37f8a883
MA
193 &dsp->dsa_zc);
194 if (dump_bytes(dsp, payload, payload_len) != 0)
195 return (SET_ERROR(EINTR));
196 }
197 return (0);
198}
199
e6d3a843
PD
200/*
201 * Fill in the drr_free struct, or perform aggregation if the previous record is
202 * also a free record, and the two are adjacent.
203 *
204 * Note that we send free records even for a full send, because we want to be
205 * able to receive a full send as a clone, which requires a list of all the free
206 * and freeobject records that were generated on the source.
207 */
34dc7c2f 208static int
37abac6d 209dump_free(dmu_sendarg_t *dsp, uint64_t object, uint64_t offset,
34dc7c2f
BB
210 uint64_t length)
211{
37abac6d 212 struct drr_free *drrf = &(dsp->dsa_drr->drr_u.drr_free);
428870ff 213
ea97f8ce
MA
214 /*
215 * When we receive a free record, dbuf_free_range() assumes
216 * that the receiving system doesn't have any dbufs in the range
217 * being freed. This is always true because there is a one-record
218 * constraint: we only send one WRITE record for any given
47dfff3b 219 * object,offset. We know that the one-record constraint is
ea97f8ce
MA
220 * true because we always send data in increasing order by
221 * object,offset.
222 *
223 * If the increasing-order constraint ever changes, we should find
224 * another way to assert that the one-record constraint is still
225 * satisfied.
226 */
227 ASSERT(object > dsp->dsa_last_data_object ||
228 (object == dsp->dsa_last_data_object &&
229 offset > dsp->dsa_last_data_offset));
230
428870ff
BB
231 /*
232 * If there is a pending op, but it's not PENDING_FREE, push it out,
233 * since free block aggregation can only be done for blocks of the
234 * same type (i.e., DRR_FREE records can only be aggregated with
235 * other DRR_FREE records. DRR_FREEOBJECTS records can only be
236 * aggregated with other DRR_FREEOBJECTS records.
237 */
37abac6d
BP
238 if (dsp->dsa_pending_op != PENDING_NONE &&
239 dsp->dsa_pending_op != PENDING_FREE) {
37f8a883 240 if (dump_record(dsp, NULL, 0) != 0)
2e528b49 241 return (SET_ERROR(EINTR));
37abac6d 242 dsp->dsa_pending_op = PENDING_NONE;
428870ff
BB
243 }
244
37abac6d 245 if (dsp->dsa_pending_op == PENDING_FREE) {
428870ff 246 /*
ee45fbd8 247 * There should never be a PENDING_FREE if length is
248 * DMU_OBJECT_END (because dump_dnode is the only place where
249 * this function is called with a DMU_OBJECT_END, and only after
250 * flushing any pending record).
428870ff 251 */
ee45fbd8 252 ASSERT(length != DMU_OBJECT_END);
428870ff
BB
253 /*
254 * Check to see whether this free block can be aggregated
255 * with pending one.
256 */
257 if (drrf->drr_object == object && drrf->drr_offset +
258 drrf->drr_length == offset) {
ee45fbd8 259 if (offset + length < offset)
260 drrf->drr_length = DMU_OBJECT_END;
261 else
262 drrf->drr_length += length;
428870ff
BB
263 return (0);
264 } else {
265 /* not a continuation. Push out pending record */
37f8a883 266 if (dump_record(dsp, NULL, 0) != 0)
2e528b49 267 return (SET_ERROR(EINTR));
37abac6d 268 dsp->dsa_pending_op = PENDING_NONE;
428870ff
BB
269 }
270 }
271 /* create a FREE record and make it pending */
37abac6d
BP
272 bzero(dsp->dsa_drr, sizeof (dmu_replay_record_t));
273 dsp->dsa_drr->drr_type = DRR_FREE;
428870ff
BB
274 drrf->drr_object = object;
275 drrf->drr_offset = offset;
ee45fbd8 276 if (offset + length < offset)
277 drrf->drr_length = DMU_OBJECT_END;
278 else
279 drrf->drr_length = length;
37abac6d 280 drrf->drr_toguid = dsp->dsa_toguid;
ee45fbd8 281 if (length == DMU_OBJECT_END) {
37f8a883 282 if (dump_record(dsp, NULL, 0) != 0)
2e528b49 283 return (SET_ERROR(EINTR));
428870ff 284 } else {
37abac6d 285 dsp->dsa_pending_op = PENDING_FREE;
428870ff 286 }
34dc7c2f 287
34dc7c2f
BB
288 return (0);
289}
290
291static int
b5256303
TC
292dump_write(dmu_sendarg_t *dsp, dmu_object_type_t type, uint64_t object,
293 uint64_t offset, int lsize, int psize, const blkptr_t *bp, void *data)
34dc7c2f 294{
2aa34383 295 uint64_t payload_size;
b5256303 296 boolean_t raw = (dsp->dsa_featureflags & DMU_BACKUP_FEATURE_RAW);
37abac6d 297 struct drr_write *drrw = &(dsp->dsa_drr->drr_u.drr_write);
428870ff 298
ea97f8ce
MA
299 /*
300 * We send data in increasing object, offset order.
301 * See comment in dump_free() for details.
302 */
303 ASSERT(object > dsp->dsa_last_data_object ||
304 (object == dsp->dsa_last_data_object &&
305 offset > dsp->dsa_last_data_offset));
306 dsp->dsa_last_data_object = object;
2aa34383 307 dsp->dsa_last_data_offset = offset + lsize - 1;
428870ff
BB
308
309 /*
310 * If there is any kind of pending aggregation (currently either
311 * a grouping of free objects or free blocks), push it out to
312 * the stream, since aggregation can't be done across operations
313 * of different types.
314 */
37abac6d 315 if (dsp->dsa_pending_op != PENDING_NONE) {
37f8a883 316 if (dump_record(dsp, NULL, 0) != 0)
2e528b49 317 return (SET_ERROR(EINTR));
37abac6d 318 dsp->dsa_pending_op = PENDING_NONE;
428870ff 319 }
37f8a883 320 /* write a WRITE record */
37abac6d
BP
321 bzero(dsp->dsa_drr, sizeof (dmu_replay_record_t));
322 dsp->dsa_drr->drr_type = DRR_WRITE;
428870ff
BB
323 drrw->drr_object = object;
324 drrw->drr_type = type;
325 drrw->drr_offset = offset;
37abac6d 326 drrw->drr_toguid = dsp->dsa_toguid;
2aa34383
DK
327 drrw->drr_logical_size = lsize;
328
b5256303
TC
329 /* only set the compression fields if the buf is compressed or raw */
330 if (raw || lsize != psize) {
2aa34383 331 ASSERT(!BP_IS_EMBEDDED(bp));
2aa34383 332 ASSERT3S(psize, >, 0);
2aa34383 333
b5256303
TC
334 if (raw) {
335 ASSERT(BP_IS_PROTECTED(bp));
336
337 /*
9b840763
TC
338 * This is a raw protected block so we need to pass
339 * along everything the receiving side will need to
340 * interpret this block, including the byteswap, salt,
341 * IV, and MAC.
b5256303 342 */
b5256303
TC
343 if (BP_SHOULD_BYTESWAP(bp))
344 drrw->drr_flags |= DRR_RAW_BYTESWAP;
345 zio_crypt_decode_params_bp(bp, drrw->drr_salt,
346 drrw->drr_iv);
347 zio_crypt_decode_mac_bp(bp, drrw->drr_mac);
348 } else {
349 /* this is a compressed block */
350 ASSERT(dsp->dsa_featureflags &
351 DMU_BACKUP_FEATURE_COMPRESSED);
352 ASSERT(!BP_SHOULD_BYTESWAP(bp));
353 ASSERT(!DMU_OT_IS_METADATA(BP_GET_TYPE(bp)));
354 ASSERT3U(BP_GET_COMPRESS(bp), !=, ZIO_COMPRESS_OFF);
355 ASSERT3S(lsize, >=, psize);
356 }
357
358 /* set fields common to compressed and raw sends */
2aa34383
DK
359 drrw->drr_compressiontype = BP_GET_COMPRESS(bp);
360 drrw->drr_compressed_size = psize;
361 payload_size = drrw->drr_compressed_size;
362 } else {
363 payload_size = drrw->drr_logical_size;
364 }
365
b5256303 366 if (bp == NULL || BP_IS_EMBEDDED(bp) || (BP_IS_PROTECTED(bp) && !raw)) {
9b67f605 367 /*
b5256303
TC
368 * There's no pre-computed checksum for partial-block writes,
369 * embedded BP's, or encrypted BP's that are being sent as
370 * plaintext, so (like fletcher4-checkummed blocks) userland
371 * will have to compute a dedup-capable checksum itself.
9b67f605
MA
372 */
373 drrw->drr_checksumtype = ZIO_CHECKSUM_OFF;
374 } else {
375 drrw->drr_checksumtype = BP_GET_CHECKSUM(bp);
3c67d83a
TH
376 if (zio_checksum_table[drrw->drr_checksumtype].ci_flags &
377 ZCHECKSUM_FLAG_DEDUP)
b5256303 378 drrw->drr_flags |= DRR_CHECKSUM_DEDUP;
9b67f605
MA
379 DDK_SET_LSIZE(&drrw->drr_key, BP_GET_LSIZE(bp));
380 DDK_SET_PSIZE(&drrw->drr_key, BP_GET_PSIZE(bp));
381 DDK_SET_COMPRESS(&drrw->drr_key, BP_GET_COMPRESS(bp));
b5256303 382 DDK_SET_CRYPT(&drrw->drr_key, BP_IS_PROTECTED(bp));
9b67f605
MA
383 drrw->drr_key.ddk_cksum = bp->blk_cksum;
384 }
428870ff 385
2aa34383 386 if (dump_record(dsp, data, payload_size) != 0)
2e528b49 387 return (SET_ERROR(EINTR));
428870ff
BB
388 return (0);
389}
390
9b67f605
MA
391static int
392dump_write_embedded(dmu_sendarg_t *dsp, uint64_t object, uint64_t offset,
393 int blksz, const blkptr_t *bp)
394{
395 char buf[BPE_PAYLOAD_SIZE];
396 struct drr_write_embedded *drrw =
397 &(dsp->dsa_drr->drr_u.drr_write_embedded);
398
399 if (dsp->dsa_pending_op != PENDING_NONE) {
37f8a883 400 if (dump_record(dsp, NULL, 0) != 0)
ecb2b7dc 401 return (SET_ERROR(EINTR));
9b67f605
MA
402 dsp->dsa_pending_op = PENDING_NONE;
403 }
404
405 ASSERT(BP_IS_EMBEDDED(bp));
406
407 bzero(dsp->dsa_drr, sizeof (dmu_replay_record_t));
408 dsp->dsa_drr->drr_type = DRR_WRITE_EMBEDDED;
409 drrw->drr_object = object;
410 drrw->drr_offset = offset;
411 drrw->drr_length = blksz;
412 drrw->drr_toguid = dsp->dsa_toguid;
413 drrw->drr_compression = BP_GET_COMPRESS(bp);
414 drrw->drr_etype = BPE_GET_ETYPE(bp);
415 drrw->drr_lsize = BPE_GET_LSIZE(bp);
416 drrw->drr_psize = BPE_GET_PSIZE(bp);
417
418 decode_embedded_bp_compressed(bp, buf);
419
37f8a883 420 if (dump_record(dsp, buf, P2ROUNDUP(drrw->drr_psize, 8)) != 0)
ecb2b7dc 421 return (SET_ERROR(EINTR));
9b67f605
MA
422 return (0);
423}
424
428870ff 425static int
b5256303 426dump_spill(dmu_sendarg_t *dsp, const blkptr_t *bp, uint64_t object, void *data)
428870ff 427{
37abac6d 428 struct drr_spill *drrs = &(dsp->dsa_drr->drr_u.drr_spill);
b5256303 429 uint64_t blksz = BP_GET_LSIZE(bp);
b0ee5946 430 uint64_t payload_size = blksz;
428870ff 431
37abac6d 432 if (dsp->dsa_pending_op != PENDING_NONE) {
37f8a883 433 if (dump_record(dsp, NULL, 0) != 0)
2e528b49 434 return (SET_ERROR(EINTR));
37abac6d 435 dsp->dsa_pending_op = PENDING_NONE;
428870ff
BB
436 }
437
438 /* write a SPILL record */
37abac6d
BP
439 bzero(dsp->dsa_drr, sizeof (dmu_replay_record_t));
440 dsp->dsa_drr->drr_type = DRR_SPILL;
428870ff
BB
441 drrs->drr_object = object;
442 drrs->drr_length = blksz;
37abac6d 443 drrs->drr_toguid = dsp->dsa_toguid;
34dc7c2f 444
b5256303 445 /* handle raw send fields */
9b840763
TC
446 if (dsp->dsa_featureflags & DMU_BACKUP_FEATURE_RAW) {
447 ASSERT(BP_IS_PROTECTED(bp));
448
b5256303
TC
449 if (BP_SHOULD_BYTESWAP(bp))
450 drrs->drr_flags |= DRR_RAW_BYTESWAP;
451 drrs->drr_compressiontype = BP_GET_COMPRESS(bp);
452 drrs->drr_compressed_size = BP_GET_PSIZE(bp);
453 zio_crypt_decode_params_bp(bp, drrs->drr_salt, drrs->drr_iv);
454 zio_crypt_decode_mac_bp(bp, drrs->drr_mac);
b0ee5946 455 payload_size = drrs->drr_compressed_size;
b5256303
TC
456 }
457
b0ee5946 458 if (dump_record(dsp, data, payload_size) != 0)
2e528b49 459 return (SET_ERROR(EINTR));
34dc7c2f
BB
460 return (0);
461}
462
463static int
37abac6d 464dump_freeobjects(dmu_sendarg_t *dsp, uint64_t firstobj, uint64_t numobjs)
34dc7c2f 465{
37abac6d 466 struct drr_freeobjects *drrfo = &(dsp->dsa_drr->drr_u.drr_freeobjects);
829e95c4
FG
467 uint64_t maxobj = DNODES_PER_BLOCK *
468 (DMU_META_DNODE(dsp->dsa_os)->dn_maxblkid + 1);
469
470 /*
471 * ZoL < 0.7 does not handle large FREEOBJECTS records correctly,
472 * leading to zfs recv never completing. to avoid this issue, don't
473 * send FREEOBJECTS records for object IDs which cannot exist on the
474 * receiving side.
475 */
476 if (maxobj > 0) {
477 if (maxobj < firstobj)
478 return (0);
479
480 if (maxobj < firstobj + numobjs)
481 numobjs = maxobj - firstobj;
482 }
428870ff
BB
483
484 /*
485 * If there is a pending op, but it's not PENDING_FREEOBJECTS,
486 * push it out, since free block aggregation can only be done for
487 * blocks of the same type (i.e., DRR_FREE records can only be
488 * aggregated with other DRR_FREE records. DRR_FREEOBJECTS records
489 * can only be aggregated with other DRR_FREEOBJECTS records.
490 */
37abac6d
BP
491 if (dsp->dsa_pending_op != PENDING_NONE &&
492 dsp->dsa_pending_op != PENDING_FREEOBJECTS) {
37f8a883 493 if (dump_record(dsp, NULL, 0) != 0)
2e528b49 494 return (SET_ERROR(EINTR));
37abac6d 495 dsp->dsa_pending_op = PENDING_NONE;
428870ff 496 }
37abac6d 497 if (dsp->dsa_pending_op == PENDING_FREEOBJECTS) {
428870ff
BB
498 /*
499 * See whether this free object array can be aggregated
500 * with pending one
501 */
502 if (drrfo->drr_firstobj + drrfo->drr_numobjs == firstobj) {
503 drrfo->drr_numobjs += numobjs;
504 return (0);
505 } else {
506 /* can't be aggregated. Push out pending record */
37f8a883 507 if (dump_record(dsp, NULL, 0) != 0)
2e528b49 508 return (SET_ERROR(EINTR));
37abac6d 509 dsp->dsa_pending_op = PENDING_NONE;
428870ff
BB
510 }
511 }
512
34dc7c2f 513 /* write a FREEOBJECTS record */
37abac6d
BP
514 bzero(dsp->dsa_drr, sizeof (dmu_replay_record_t));
515 dsp->dsa_drr->drr_type = DRR_FREEOBJECTS;
428870ff
BB
516 drrfo->drr_firstobj = firstobj;
517 drrfo->drr_numobjs = numobjs;
37abac6d 518 drrfo->drr_toguid = dsp->dsa_toguid;
428870ff 519
37abac6d 520 dsp->dsa_pending_op = PENDING_FREEOBJECTS;
34dc7c2f 521
34dc7c2f
BB
522 return (0);
523}
524
525static int
b5256303
TC
526dump_dnode(dmu_sendarg_t *dsp, const blkptr_t *bp, uint64_t object,
527 dnode_phys_t *dnp)
34dc7c2f 528{
37abac6d 529 struct drr_object *drro = &(dsp->dsa_drr->drr_u.drr_object);
4807c0ba 530 int bonuslen;
428870ff 531
47dfff3b
MA
532 if (object < dsp->dsa_resume_object) {
533 /*
534 * Note: when resuming, we will visit all the dnodes in
535 * the block of dnodes that we are resuming from. In
536 * this case it's unnecessary to send the dnodes prior to
537 * the one we are resuming from. We should be at most one
538 * block's worth of dnodes behind the resume point.
539 */
540 ASSERT3U(dsp->dsa_resume_object - object, <,
541 1 << (DNODE_BLOCK_SHIFT - DNODE_SHIFT));
542 return (0);
543 }
544
34dc7c2f 545 if (dnp == NULL || dnp->dn_type == DMU_OT_NONE)
37abac6d 546 return (dump_freeobjects(dsp, object, 1));
34dc7c2f 547
37abac6d 548 if (dsp->dsa_pending_op != PENDING_NONE) {
37f8a883 549 if (dump_record(dsp, NULL, 0) != 0)
2e528b49 550 return (SET_ERROR(EINTR));
37abac6d 551 dsp->dsa_pending_op = PENDING_NONE;
428870ff
BB
552 }
553
34dc7c2f 554 /* write an OBJECT record */
37abac6d
BP
555 bzero(dsp->dsa_drr, sizeof (dmu_replay_record_t));
556 dsp->dsa_drr->drr_type = DRR_OBJECT;
428870ff
BB
557 drro->drr_object = object;
558 drro->drr_type = dnp->dn_type;
559 drro->drr_bonustype = dnp->dn_bonustype;
560 drro->drr_blksz = dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT;
561 drro->drr_bonuslen = dnp->dn_bonuslen;
50c957f7 562 drro->drr_dn_slots = dnp->dn_extra_slots + 1;
428870ff
BB
563 drro->drr_checksumtype = dnp->dn_checksum;
564 drro->drr_compress = dnp->dn_compress;
37abac6d 565 drro->drr_toguid = dsp->dsa_toguid;
428870ff 566
f1512ee6
MA
567 if (!(dsp->dsa_featureflags & DMU_BACKUP_FEATURE_LARGE_BLOCKS) &&
568 drro->drr_blksz > SPA_OLD_MAXBLOCKSIZE)
569 drro->drr_blksz = SPA_OLD_MAXBLOCKSIZE;
570
4807c0ba
TC
571 bonuslen = P2ROUNDUP(dnp->dn_bonuslen, 8);
572
9b840763
TC
573 if ((dsp->dsa_featureflags & DMU_BACKUP_FEATURE_RAW)) {
574 ASSERT(BP_IS_ENCRYPTED(bp));
575
b5256303
TC
576 if (BP_SHOULD_BYTESWAP(bp))
577 drro->drr_flags |= DRR_RAW_BYTESWAP;
578
579 /* needed for reconstructing dnp on recv side */
ae76f45c 580 drro->drr_maxblkid = dnp->dn_maxblkid;
b5256303
TC
581 drro->drr_indblkshift = dnp->dn_indblkshift;
582 drro->drr_nlevels = dnp->dn_nlevels;
583 drro->drr_nblkptr = dnp->dn_nblkptr;
584
585 /*
586 * Since we encrypt the entire bonus area, the (raw) part
4807c0ba 587 * beyond the bonuslen is actually nonzero, so we need
b5256303
TC
588 * to send it.
589 */
590 if (bonuslen != 0) {
591 drro->drr_raw_bonuslen = DN_MAX_BONUS_LEN(dnp);
592 bonuslen = drro->drr_raw_bonuslen;
593 }
37f8a883 594 }
34dc7c2f 595
b5256303
TC
596 if (dump_record(dsp, DN_BONUS(dnp), bonuslen) != 0)
597 return (SET_ERROR(EINTR));
598
ea97f8ce 599 /* Free anything past the end of the file. */
37abac6d 600 if (dump_free(dsp, object, (dnp->dn_maxblkid + 1) *
ee45fbd8 601 (dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT), DMU_OBJECT_END) != 0)
2e528b49 602 return (SET_ERROR(EINTR));
13fe0198 603 if (dsp->dsa_err != 0)
2e528b49 604 return (SET_ERROR(EINTR));
34dc7c2f
BB
605 return (0);
606}
607
b5256303
TC
608static int
609dump_object_range(dmu_sendarg_t *dsp, const blkptr_t *bp, uint64_t firstobj,
610 uint64_t numslots)
611{
612 struct drr_object_range *drror =
613 &(dsp->dsa_drr->drr_u.drr_object_range);
614
615 /* we only use this record type for raw sends */
616 ASSERT(BP_IS_PROTECTED(bp));
617 ASSERT(dsp->dsa_featureflags & DMU_BACKUP_FEATURE_RAW);
618 ASSERT3U(BP_GET_COMPRESS(bp), ==, ZIO_COMPRESS_OFF);
619 ASSERT3U(BP_GET_TYPE(bp), ==, DMU_OT_DNODE);
620 ASSERT0(BP_GET_LEVEL(bp));
621
622 if (dsp->dsa_pending_op != PENDING_NONE) {
623 if (dump_record(dsp, NULL, 0) != 0)
624 return (SET_ERROR(EINTR));
625 dsp->dsa_pending_op = PENDING_NONE;
626 }
627
628 bzero(dsp->dsa_drr, sizeof (dmu_replay_record_t));
629 dsp->dsa_drr->drr_type = DRR_OBJECT_RANGE;
630 drror->drr_firstobj = firstobj;
631 drror->drr_numslots = numslots;
632 drror->drr_toguid = dsp->dsa_toguid;
b5256303
TC
633 if (BP_SHOULD_BYTESWAP(bp))
634 drror->drr_flags |= DRR_RAW_BYTESWAP;
635 zio_crypt_decode_params_bp(bp, drror->drr_salt, drror->drr_iv);
636 zio_crypt_decode_mac_bp(bp, drror->drr_mac);
637
638 if (dump_record(dsp, NULL, 0) != 0)
639 return (SET_ERROR(EINTR));
640 return (0);
641}
642
9b67f605
MA
643static boolean_t
644backup_do_embed(dmu_sendarg_t *dsp, const blkptr_t *bp)
645{
646 if (!BP_IS_EMBEDDED(bp))
647 return (B_FALSE);
648
649 /*
650 * Compression function must be legacy, or explicitly enabled.
651 */
652 if ((BP_GET_COMPRESS(bp) >= ZIO_COMPRESS_LEGACY_FUNCTIONS &&
2aa34383 653 !(dsp->dsa_featureflags & DMU_BACKUP_FEATURE_LZ4)))
9b67f605
MA
654 return (B_FALSE);
655
656 /*
657 * Embed type must be explicitly enabled.
658 */
659 switch (BPE_GET_ETYPE(bp)) {
660 case BP_EMBEDDED_TYPE_DATA:
661 if (dsp->dsa_featureflags & DMU_BACKUP_FEATURE_EMBED_DATA)
662 return (B_TRUE);
663 break;
664 default:
665 return (B_FALSE);
666 }
667 return (B_FALSE);
668}
669
fcff0f35
PD
670/*
671 * This is the callback function to traverse_dataset that acts as the worker
672 * thread for dmu_send_impl.
673 */
674/*ARGSUSED*/
675static int
676send_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
677 const zbookmark_phys_t *zb, const struct dnode_phys *dnp, void *arg)
678{
679 struct send_thread_arg *sta = arg;
680 struct send_block_record *record;
681 uint64_t record_size;
682 int err = 0;
683
47dfff3b
MA
684 ASSERT(zb->zb_object == DMU_META_DNODE_OBJECT ||
685 zb->zb_object >= sta->resume.zb_object);
b5256303 686 ASSERT3P(sta->ds, !=, NULL);
47dfff3b 687
fcff0f35
PD
688 if (sta->cancel)
689 return (SET_ERROR(EINTR));
34dc7c2f 690
fcff0f35
PD
691 if (bp == NULL) {
692 ASSERT3U(zb->zb_level, ==, ZB_DNODE_LEVEL);
693 return (0);
694 } else if (zb->zb_level < 0) {
695 return (0);
696 }
697
698 record = kmem_zalloc(sizeof (struct send_block_record), KM_SLEEP);
699 record->eos_marker = B_FALSE;
700 record->bp = *bp;
701 record->zb = *zb;
702 record->indblkshift = dnp->dn_indblkshift;
703 record->datablkszsec = dnp->dn_datablkszsec;
704 record_size = dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT;
705 bqueue_enqueue(&sta->q, record, record_size);
706
707 return (err);
708}
709
710/*
711 * This function kicks off the traverse_dataset. It also handles setting the
712 * error code of the thread in case something goes wrong, and pushes the End of
713 * Stream record when the traverse_dataset call has finished. If there is no
714 * dataset to traverse, the thread immediately pushes End of Stream marker.
715 */
716static void
717send_traverse_thread(void *arg)
718{
719 struct send_thread_arg *st_arg = arg;
720 int err;
721 struct send_block_record *data;
3e635ac1 722 fstrans_cookie_t cookie = spl_fstrans_mark();
fcff0f35
PD
723
724 if (st_arg->ds != NULL) {
47dfff3b
MA
725 err = traverse_dataset_resume(st_arg->ds,
726 st_arg->fromtxg, &st_arg->resume,
727 st_arg->flags, send_cb, st_arg);
728
fcff0f35
PD
729 if (err != EINTR)
730 st_arg->error_code = err;
731 }
732 data = kmem_zalloc(sizeof (*data), KM_SLEEP);
733 data->eos_marker = B_TRUE;
734 bqueue_enqueue(&st_arg->q, data, 1);
3e635ac1 735 spl_fstrans_unmark(cookie);
34a6b428 736 thread_exit();
fcff0f35
PD
737}
738
739/*
740 * This function actually handles figuring out what kind of record needs to be
741 * dumped, reading the data (which has hopefully been prefetched), and calling
742 * the appropriate helper function.
743 */
34dc7c2f 744static int
fcff0f35 745do_dump(dmu_sendarg_t *dsa, struct send_block_record *data)
34dc7c2f 746{
fcff0f35
PD
747 dsl_dataset_t *ds = dmu_objset_ds(dsa->dsa_os);
748 const blkptr_t *bp = &data->bp;
749 const zbookmark_phys_t *zb = &data->zb;
750 uint8_t indblkshift = data->indblkshift;
751 uint16_t dblkszsec = data->datablkszsec;
752 spa_t *spa = ds->ds_dir->dd_pool->dp_spa;
34dc7c2f 753 dmu_object_type_t type = bp ? BP_GET_TYPE(bp) : DMU_OT_NONE;
34dc7c2f
BB
754 int err = 0;
755
fcff0f35 756 ASSERT3U(zb->zb_level, >=, 0);
34dc7c2f 757
47dfff3b
MA
758 ASSERT(zb->zb_object == DMU_META_DNODE_OBJECT ||
759 zb->zb_object >= dsa->dsa_resume_object);
760
b5256303
TC
761 /*
762 * All bps of an encrypted os should have the encryption bit set.
763 * If this is not true it indicates tampering and we report an error.
764 */
765 if (dsa->dsa_os->os_encrypted &&
766 !BP_IS_HOLE(bp) && !BP_USES_CRYPT(bp)) {
767 spa_log_error(spa, zb);
768 zfs_panic_recover("unencrypted block in encrypted "
769 "object set %llu", ds->ds_object);
770 return (SET_ERROR(EIO));
771 }
772
428870ff
BB
773 if (zb->zb_object != DMU_META_DNODE_OBJECT &&
774 DMU_OBJECT_IS_SPECIAL(zb->zb_object)) {
9babb374 775 return (0);
b0bc7a84
MG
776 } else if (BP_IS_HOLE(bp) &&
777 zb->zb_object == DMU_META_DNODE_OBJECT) {
fcff0f35 778 uint64_t span = BP_SPAN(dblkszsec, indblkshift, zb->zb_level);
b128c09f 779 uint64_t dnobj = (zb->zb_blkid * span) >> DNODE_SHIFT;
fcff0f35 780 err = dump_freeobjects(dsa, dnobj, span >> DNODE_SHIFT);
b0bc7a84 781 } else if (BP_IS_HOLE(bp)) {
fcff0f35
PD
782 uint64_t span = BP_SPAN(dblkszsec, indblkshift, zb->zb_level);
783 uint64_t offset = zb->zb_blkid * span;
ee45fbd8 784 /* Don't dump free records for offsets > DMU_OBJECT_END */
785 if (zb->zb_blkid == 0 || span <= DMU_OBJECT_END / zb->zb_blkid)
786 err = dump_free(dsa, zb->zb_object, offset, span);
b128c09f
BB
787 } else if (zb->zb_level > 0 || type == DMU_OT_OBJSET) {
788 return (0);
789 } else if (type == DMU_OT_DNODE) {
50c957f7 790 int epb = BP_GET_LSIZE(bp) >> DNODE_SHIFT;
2a432414 791 arc_flags_t aflags = ARC_FLAG_WAIT;
b128c09f 792 arc_buf_t *abuf;
b5256303 793 enum zio_flag zioflags = ZIO_FLAG_CANFAIL;
fcff0f35 794
b5256303
TC
795 if (dsa->dsa_featureflags & DMU_BACKUP_FEATURE_RAW) {
796 ASSERT(BP_IS_ENCRYPTED(bp));
797 ASSERT3U(BP_GET_COMPRESS(bp), ==, ZIO_COMPRESS_OFF);
798 zioflags |= ZIO_FLAG_RAW;
799 }
800
fcff0f35 801 ASSERT0(zb->zb_level);
b128c09f 802
294f6806 803 if (arc_read(NULL, spa, bp, arc_getbuf_func, &abuf,
b5256303 804 ZIO_PRIORITY_ASYNC_READ, zioflags, &aflags, zb) != 0)
2e528b49 805 return (SET_ERROR(EIO));
34dc7c2f 806
1c27024e
DB
807 dnode_phys_t *blk = abuf->b_data;
808 uint64_t dnobj = zb->zb_blkid * epb;
b5256303
TC
809
810 /*
811 * Raw sends require sending encryption parameters for the
812 * block of dnodes. Regular sends do not need to send this
813 * info.
814 */
815 if (dsa->dsa_featureflags & DMU_BACKUP_FEATURE_RAW) {
816 ASSERT(arc_is_encrypted(abuf));
817 err = dump_object_range(dsa, bp, dnobj, epb);
818 }
819
820 if (err == 0) {
1c27024e
DB
821 for (int i = 0; i < epb;
822 i += blk[i].dn_extra_slots + 1) {
b5256303
TC
823 err = dump_dnode(dsa, bp, dnobj + i, blk + i);
824 if (err != 0)
825 break;
826 }
34dc7c2f 827 }
d3c2ae1c 828 arc_buf_destroy(abuf, &abuf);
428870ff 829 } else if (type == DMU_OT_SA) {
2a432414 830 arc_flags_t aflags = ARC_FLAG_WAIT;
b128c09f 831 arc_buf_t *abuf;
b5256303
TC
832 enum zio_flag zioflags = ZIO_FLAG_CANFAIL;
833
834 if (dsa->dsa_featureflags & DMU_BACKUP_FEATURE_RAW) {
835 ASSERT(BP_IS_PROTECTED(bp));
836 zioflags |= ZIO_FLAG_RAW;
837 }
b128c09f 838
294f6806 839 if (arc_read(NULL, spa, bp, arc_getbuf_func, &abuf,
b5256303 840 ZIO_PRIORITY_ASYNC_READ, zioflags, &aflags, zb) != 0)
2e528b49 841 return (SET_ERROR(EIO));
b128c09f 842
b5256303 843 err = dump_spill(dsa, bp, zb->zb_object, abuf->b_data);
d3c2ae1c 844 arc_buf_destroy(abuf, &abuf);
fcff0f35 845 } else if (backup_do_embed(dsa, bp)) {
9b67f605 846 /* it's an embedded level-0 block of a regular object */
fcff0f35
PD
847 int blksz = dblkszsec << SPA_MINBLOCKSHIFT;
848 ASSERT0(zb->zb_level);
849 err = dump_write_embedded(dsa, zb->zb_object,
9b67f605 850 zb->zb_blkid * blksz, blksz, bp);
fcff0f35
PD
851 } else {
852 /* it's a level-0 block of a regular object */
2a432414 853 arc_flags_t aflags = ARC_FLAG_WAIT;
428870ff 854 arc_buf_t *abuf;
fcff0f35
PD
855 int blksz = dblkszsec << SPA_MINBLOCKSHIFT;
856 uint64_t offset;
2aa34383
DK
857
858 /*
859 * If we have large blocks stored on disk but the send flags
860 * don't allow us to send large blocks, we split the data from
861 * the arc buf into chunks.
862 */
a7004725 863 boolean_t split_large_blocks = blksz > SPA_OLD_MAXBLOCKSIZE &&
2aa34383 864 !(dsa->dsa_featureflags & DMU_BACKUP_FEATURE_LARGE_BLOCKS);
b5256303
TC
865
866 /*
867 * Raw sends require that we always get raw data as it exists
868 * on disk, so we assert that we are not splitting blocks here.
869 */
870 boolean_t request_raw =
871 (dsa->dsa_featureflags & DMU_BACKUP_FEATURE_RAW) != 0;
872
2aa34383
DK
873 /*
874 * We should only request compressed data from the ARC if all
875 * the following are true:
876 * - stream compression was requested
877 * - we aren't splitting large blocks into smaller chunks
878 * - the data won't need to be byteswapped before sending
879 * - this isn't an embedded block
880 * - this isn't metadata (if receiving on a different endian
881 * system it can be byteswapped more easily)
882 */
883 boolean_t request_compressed =
884 (dsa->dsa_featureflags & DMU_BACKUP_FEATURE_COMPRESSED) &&
885 !split_large_blocks && !BP_SHOULD_BYTESWAP(bp) &&
886 !BP_IS_EMBEDDED(bp) && !DMU_OT_IS_METADATA(BP_GET_TYPE(bp));
428870ff 887
b5256303
TC
888 IMPLY(request_raw, !split_large_blocks);
889 IMPLY(request_raw, BP_IS_PROTECTED(bp));
da536844 890 ASSERT0(zb->zb_level);
47dfff3b
MA
891 ASSERT(zb->zb_object > dsa->dsa_resume_object ||
892 (zb->zb_object == dsa->dsa_resume_object &&
893 zb->zb_blkid * blksz >= dsa->dsa_resume_offset));
894
a7004725
DK
895 ASSERT3U(blksz, ==, BP_GET_LSIZE(bp));
896
897 enum zio_flag zioflags = ZIO_FLAG_CANFAIL;
b5256303 898 if (request_raw)
2aa34383 899 zioflags |= ZIO_FLAG_RAW;
b5256303
TC
900 else if (request_compressed)
901 zioflags |= ZIO_FLAG_RAW_COMPRESS;
2aa34383 902
294f6806 903 if (arc_read(NULL, spa, bp, arc_getbuf_func, &abuf,
a7004725 904 ZIO_PRIORITY_ASYNC_READ, zioflags, &aflags, zb) != 0) {
330d06f9 905 if (zfs_send_corrupt_data) {
330d06f9 906 /* Send a block filled with 0x"zfs badd bloc" */
2aa34383
DK
907 abuf = arc_alloc_buf(spa, &abuf, ARC_BUFC_DATA,
908 blksz);
a7004725 909 uint64_t *ptr;
330d06f9
MA
910 for (ptr = abuf->b_data;
911 (char *)ptr < (char *)abuf->b_data + blksz;
912 ptr++)
dd26aa53 913 *ptr = 0x2f5baddb10cULL;
330d06f9 914 } else {
2e528b49 915 return (SET_ERROR(EIO));
330d06f9
MA
916 }
917 }
428870ff 918
f1512ee6
MA
919 offset = zb->zb_blkid * blksz;
920
2aa34383 921 if (split_large_blocks) {
b5256303 922 ASSERT0(arc_is_encrypted(abuf));
2aa34383
DK
923 ASSERT3U(arc_get_compression(abuf), ==,
924 ZIO_COMPRESS_OFF);
a7004725 925 char *buf = abuf->b_data;
f1512ee6
MA
926 while (blksz > 0 && err == 0) {
927 int n = MIN(blksz, SPA_OLD_MAXBLOCKSIZE);
fcff0f35 928 err = dump_write(dsa, type, zb->zb_object,
2aa34383 929 offset, n, n, NULL, buf);
f1512ee6
MA
930 offset += n;
931 buf += n;
932 blksz -= n;
933 }
934 } else {
2aa34383 935 err = dump_write(dsa, type, zb->zb_object, offset,
b5256303 936 blksz, arc_buf_size(abuf), bp, abuf->b_data);
f1512ee6 937 }
d3c2ae1c 938 arc_buf_destroy(abuf, &abuf);
34dc7c2f
BB
939 }
940
941 ASSERT(err == 0 || err == EINTR);
942 return (err);
943}
944
6f1ffb06 945/*
fcff0f35
PD
946 * Pop the new data off the queue, and free the old data.
947 */
948static struct send_block_record *
949get_next_record(bqueue_t *bq, struct send_block_record *data)
950{
951 struct send_block_record *tmp = bqueue_dequeue(bq);
952 kmem_free(data, sizeof (*data));
953 return (tmp);
954}
955
956/*
957 * Actually do the bulk of the work in a zfs send.
958 *
959 * Note: Releases dp using the specified tag.
6f1ffb06 960 */
13fe0198 961static int
fcff0f35 962dmu_send_impl(void *tag, dsl_pool_t *dp, dsl_dataset_t *to_ds,
2aa34383
DK
963 zfs_bookmark_phys_t *ancestor_zb, boolean_t is_clone,
964 boolean_t embedok, boolean_t large_block_ok, boolean_t compressok,
b5256303 965 boolean_t rawok, int outfd, uint64_t resumeobj, uint64_t resumeoff,
47dfff3b 966 vnode_t *vp, offset_t *off)
34dc7c2f 967{
13fe0198 968 objset_t *os;
34dc7c2f 969 dmu_replay_record_t *drr;
37abac6d 970 dmu_sendarg_t *dsp;
34dc7c2f
BB
971 int err;
972 uint64_t fromtxg = 0;
9b67f605 973 uint64_t featureflags = 0;
fcff0f35 974 struct send_thread_arg to_arg;
47dfff3b
MA
975 void *payload = NULL;
976 size_t payload_len = 0;
fcff0f35 977 struct send_block_record *to_data;
34dc7c2f 978
fcff0f35 979 err = dmu_objset_from_ds(to_ds, &os);
13fe0198 980 if (err != 0) {
13fe0198
MA
981 dsl_pool_rele(dp, tag);
982 return (err);
983 }
34dc7c2f 984
b5256303
TC
985 /*
986 * If this is a non-raw send of an encrypted ds, we can ensure that
987 * the objset_phys_t is authenticated. This is safe because this is
988 * either a snapshot or we have owned the dataset, ensuring that
989 * it can't be modified.
990 */
991 if (!rawok && os->os_encrypted &&
992 arc_is_unauthenticated(os->os_phys_buf)) {
a2c2ed1b
TC
993 zbookmark_phys_t zb;
994
995 SET_BOOKMARK(&zb, to_ds->ds_object, ZB_ROOT_OBJECT,
996 ZB_ROOT_LEVEL, ZB_ROOT_BLKID);
b5256303 997 err = arc_untransform(os->os_phys_buf, os->os_spa,
a2c2ed1b 998 &zb, B_FALSE);
b5256303
TC
999 if (err != 0) {
1000 dsl_pool_rele(dp, tag);
1001 return (err);
1002 }
1003
1004 ASSERT0(arc_is_unauthenticated(os->os_phys_buf));
1005 }
1006
34dc7c2f
BB
1007 drr = kmem_zalloc(sizeof (dmu_replay_record_t), KM_SLEEP);
1008 drr->drr_type = DRR_BEGIN;
1009 drr->drr_u.drr_begin.drr_magic = DMU_BACKUP_MAGIC;
428870ff
BB
1010 DMU_SET_STREAM_HDRTYPE(drr->drr_u.drr_begin.drr_versioninfo,
1011 DMU_SUBSTREAM);
1012
47dfff3b
MA
1013 bzero(&to_arg, sizeof (to_arg));
1014
428870ff 1015#ifdef _KERNEL
13fe0198 1016 if (dmu_objset_type(os) == DMU_OST_ZFS) {
428870ff 1017 uint64_t version;
13fe0198 1018 if (zfs_get_zplprop(os, ZFS_PROP_VERSION, &version) != 0) {
37abac6d 1019 kmem_free(drr, sizeof (dmu_replay_record_t));
13fe0198 1020 dsl_pool_rele(dp, tag);
2e528b49 1021 return (SET_ERROR(EINVAL));
37abac6d 1022 }
13fe0198 1023 if (version >= ZPL_VERSION_SA) {
9b67f605 1024 featureflags |= DMU_BACKUP_FEATURE_SA_SPILL;
428870ff
BB
1025 }
1026 }
1027#endif
1028
b5256303
TC
1029 /* raw sends imply large_block_ok */
1030 if ((large_block_ok || rawok) &&
1031 to_ds->ds_feature_inuse[SPA_FEATURE_LARGE_BLOCKS])
f1512ee6 1032 featureflags |= DMU_BACKUP_FEATURE_LARGE_BLOCKS;
50c957f7
NB
1033 if (to_ds->ds_feature_inuse[SPA_FEATURE_LARGE_DNODE])
1034 featureflags |= DMU_BACKUP_FEATURE_LARGE_DNODE;
b5256303
TC
1035
1036 /* encrypted datasets will not have embedded blocks */
1037 if ((embedok || rawok) && !os->os_encrypted &&
9b67f605
MA
1038 spa_feature_is_active(dp->dp_spa, SPA_FEATURE_EMBEDDED_DATA)) {
1039 featureflags |= DMU_BACKUP_FEATURE_EMBED_DATA;
2aa34383 1040 }
b5256303
TC
1041
1042 /* raw send implies compressok */
1043 if (compressok || rawok)
2aa34383 1044 featureflags |= DMU_BACKUP_FEATURE_COMPRESSED;
b5256303
TC
1045 if (rawok && os->os_encrypted)
1046 featureflags |= DMU_BACKUP_FEATURE_RAW;
1047
2aa34383 1048 if ((featureflags &
b5256303
TC
1049 (DMU_BACKUP_FEATURE_EMBED_DATA | DMU_BACKUP_FEATURE_COMPRESSED |
1050 DMU_BACKUP_FEATURE_RAW)) != 0 &&
1051 spa_feature_is_active(dp->dp_spa, SPA_FEATURE_LZ4_COMPRESS)) {
2aa34383 1052 featureflags |= DMU_BACKUP_FEATURE_LZ4;
9b67f605
MA
1053 }
1054
47dfff3b
MA
1055 if (resumeobj != 0 || resumeoff != 0) {
1056 featureflags |= DMU_BACKUP_FEATURE_RESUMING;
1057 }
1058
9b67f605
MA
1059 DMU_SET_FEATUREFLAGS(drr->drr_u.drr_begin.drr_versioninfo,
1060 featureflags);
1061
34dc7c2f 1062 drr->drr_u.drr_begin.drr_creation_time =
fcff0f35 1063 dsl_dataset_phys(to_ds)->ds_creation_time;
13fe0198 1064 drr->drr_u.drr_begin.drr_type = dmu_objset_type(os);
da536844 1065 if (is_clone)
34dc7c2f 1066 drr->drr_u.drr_begin.drr_flags |= DRR_FLAG_CLONE;
fcff0f35
PD
1067 drr->drr_u.drr_begin.drr_toguid = dsl_dataset_phys(to_ds)->ds_guid;
1068 if (dsl_dataset_phys(to_ds)->ds_flags & DS_FLAG_CI_DATASET)
34dc7c2f 1069 drr->drr_u.drr_begin.drr_flags |= DRR_FLAG_CI_DATA;
b607405f
AS
1070 if (zfs_send_set_freerecords_bit)
1071 drr->drr_u.drr_begin.drr_flags |= DRR_FLAG_FREERECORDS;
34dc7c2f 1072
fcff0f35
PD
1073 if (ancestor_zb != NULL) {
1074 drr->drr_u.drr_begin.drr_fromguid =
1075 ancestor_zb->zbm_guid;
1076 fromtxg = ancestor_zb->zbm_creation_txg;
da536844 1077 }
fcff0f35
PD
1078 dsl_dataset_name(to_ds, drr->drr_u.drr_begin.drr_toname);
1079 if (!to_ds->ds_is_snapshot) {
da536844
MA
1080 (void) strlcat(drr->drr_u.drr_begin.drr_toname, "@--head--",
1081 sizeof (drr->drr_u.drr_begin.drr_toname));
13fe0198 1082 }
34dc7c2f 1083
37abac6d
BP
1084 dsp = kmem_zalloc(sizeof (dmu_sendarg_t), KM_SLEEP);
1085
1086 dsp->dsa_drr = drr;
1087 dsp->dsa_vp = vp;
1088 dsp->dsa_outfd = outfd;
1089 dsp->dsa_proc = curproc;
13fe0198 1090 dsp->dsa_os = os;
37abac6d 1091 dsp->dsa_off = off;
fcff0f35 1092 dsp->dsa_toguid = dsl_dataset_phys(to_ds)->ds_guid;
37abac6d 1093 dsp->dsa_pending_op = PENDING_NONE;
9b67f605 1094 dsp->dsa_featureflags = featureflags;
47dfff3b
MA
1095 dsp->dsa_resume_object = resumeobj;
1096 dsp->dsa_resume_offset = resumeoff;
37abac6d 1097
fcff0f35
PD
1098 mutex_enter(&to_ds->ds_sendstream_lock);
1099 list_insert_head(&to_ds->ds_sendstreams, dsp);
1100 mutex_exit(&to_ds->ds_sendstream_lock);
37abac6d 1101
fcff0f35 1102 dsl_dataset_long_hold(to_ds, FTAG);
7ec09286
MA
1103 dsl_pool_rele(dp, tag);
1104
b5256303
TC
1105 /* handle features that require a DRR_BEGIN payload */
1106 if (featureflags &
1107 (DMU_BACKUP_FEATURE_RESUMING | DMU_BACKUP_FEATURE_RAW)) {
1108 nvlist_t *keynvl = NULL;
1109 nvlist_t *nvl = fnvlist_alloc();
1110
1111 if (featureflags & DMU_BACKUP_FEATURE_RESUMING) {
1112 dmu_object_info_t to_doi;
1113 err = dmu_object_info(os, resumeobj, &to_doi);
1114 if (err != 0) {
1115 fnvlist_free(nvl);
1116 goto out;
1117 }
1118
1119 SET_BOOKMARK(&to_arg.resume, to_ds->ds_object,
1120 resumeobj, 0,
1121 resumeoff / to_doi.doi_data_block_size);
1122
1123 fnvlist_add_uint64(nvl, "resume_object", resumeobj);
1124 fnvlist_add_uint64(nvl, "resume_offset", resumeoff);
1125 }
1126
1127 if (featureflags & DMU_BACKUP_FEATURE_RAW) {
1128 ASSERT(os->os_encrypted);
1129
1130 err = dsl_crypto_populate_key_nvlist(to_ds, &keynvl);
1131 if (err != 0) {
1132 fnvlist_free(nvl);
1133 goto out;
1134 }
1135
1136 fnvlist_add_nvlist(nvl, "crypt_keydata", keynvl);
1137 }
47dfff3b 1138
47dfff3b
MA
1139 payload = fnvlist_pack(nvl, &payload_len);
1140 drr->drr_payloadlen = payload_len;
b5256303 1141 fnvlist_free(keynvl);
47dfff3b
MA
1142 fnvlist_free(nvl);
1143 }
1144
1145 err = dump_record(dsp, payload, payload_len);
1146 fnvlist_pack_free(payload, payload_len);
1147 if (err != 0) {
37abac6d
BP
1148 err = dsp->dsa_err;
1149 goto out;
34dc7c2f
BB
1150 }
1151
3b0d9928
BB
1152 err = bqueue_init(&to_arg.q,
1153 MAX(zfs_send_queue_length, 2 * zfs_max_recordsize),
fcff0f35
PD
1154 offsetof(struct send_block_record, ln));
1155 to_arg.error_code = 0;
1156 to_arg.cancel = B_FALSE;
1157 to_arg.ds = to_ds;
1158 to_arg.fromtxg = fromtxg;
1159 to_arg.flags = TRAVERSE_PRE | TRAVERSE_PREFETCH;
b5256303
TC
1160 if (rawok)
1161 to_arg.flags |= TRAVERSE_NO_DECRYPT;
fcff0f35
PD
1162 (void) thread_create(NULL, 0, send_traverse_thread, &to_arg, 0, curproc,
1163 TS_RUN, minclsyspri);
1164
1165 to_data = bqueue_dequeue(&to_arg.q);
1166
1167 while (!to_data->eos_marker && err == 0) {
1168 err = do_dump(dsp, to_data);
1169 to_data = get_next_record(&to_arg.q, to_data);
1170 if (issig(JUSTLOOKING) && issig(FORREAL))
1171 err = EINTR;
1172 }
1173
1174 if (err != 0) {
1175 to_arg.cancel = B_TRUE;
1176 while (!to_data->eos_marker) {
1177 to_data = get_next_record(&to_arg.q, to_data);
1178 }
1179 }
1180 kmem_free(to_data, sizeof (*to_data));
1181
1182 bqueue_destroy(&to_arg.q);
1183
1184 if (err == 0 && to_arg.error_code != 0)
1185 err = to_arg.error_code;
1186
1187 if (err != 0)
1188 goto out;
34dc7c2f 1189
37abac6d 1190 if (dsp->dsa_pending_op != PENDING_NONE)
37f8a883 1191 if (dump_record(dsp, NULL, 0) != 0)
2e528b49 1192 err = SET_ERROR(EINTR);
428870ff 1193
13fe0198
MA
1194 if (err != 0) {
1195 if (err == EINTR && dsp->dsa_err != 0)
37abac6d
BP
1196 err = dsp->dsa_err;
1197 goto out;
34dc7c2f
BB
1198 }
1199
1200 bzero(drr, sizeof (dmu_replay_record_t));
1201 drr->drr_type = DRR_END;
37abac6d
BP
1202 drr->drr_u.drr_end.drr_checksum = dsp->dsa_zc;
1203 drr->drr_u.drr_end.drr_toguid = dsp->dsa_toguid;
34dc7c2f 1204
fcff0f35 1205 if (dump_record(dsp, NULL, 0) != 0)
37abac6d 1206 err = dsp->dsa_err;
37abac6d 1207out:
fcff0f35
PD
1208 mutex_enter(&to_ds->ds_sendstream_lock);
1209 list_remove(&to_ds->ds_sendstreams, dsp);
1210 mutex_exit(&to_ds->ds_sendstream_lock);
37abac6d 1211
51907a31
K
1212 VERIFY(err != 0 || (dsp->dsa_sent_begin && dsp->dsa_sent_end));
1213
34dc7c2f 1214 kmem_free(drr, sizeof (dmu_replay_record_t));
37abac6d 1215 kmem_free(dsp, sizeof (dmu_sendarg_t));
34dc7c2f 1216
fcff0f35 1217 dsl_dataset_long_rele(to_ds, FTAG);
13fe0198 1218
37abac6d 1219 return (err);
34dc7c2f
BB
1220}
1221
330d06f9 1222int
13fe0198 1223dmu_send_obj(const char *pool, uint64_t tosnap, uint64_t fromsnap,
2aa34383 1224 boolean_t embedok, boolean_t large_block_ok, boolean_t compressok,
b5256303 1225 boolean_t rawok, int outfd, vnode_t *vp, offset_t *off)
13fe0198
MA
1226{
1227 dsl_pool_t *dp;
1228 dsl_dataset_t *ds;
1229 dsl_dataset_t *fromds = NULL;
b5256303 1230 ds_hold_flags_t dsflags = (rawok) ? 0 : DS_HOLD_FLAG_DECRYPT;
13fe0198
MA
1231 int err;
1232
1233 err = dsl_pool_hold(pool, FTAG, &dp);
1234 if (err != 0)
1235 return (err);
1236
b5256303 1237 err = dsl_dataset_hold_obj_flags(dp, tosnap, dsflags, FTAG, &ds);
13fe0198
MA
1238 if (err != 0) {
1239 dsl_pool_rele(dp, FTAG);
1240 return (err);
1241 }
1242
1243 if (fromsnap != 0) {
da536844
MA
1244 zfs_bookmark_phys_t zb;
1245 boolean_t is_clone;
1246
13fe0198
MA
1247 err = dsl_dataset_hold_obj(dp, fromsnap, FTAG, &fromds);
1248 if (err != 0) {
b5256303 1249 dsl_dataset_rele_flags(ds, dsflags, FTAG);
13fe0198
MA
1250 dsl_pool_rele(dp, FTAG);
1251 return (err);
1252 }
da536844
MA
1253 if (!dsl_dataset_is_before(ds, fromds, 0))
1254 err = SET_ERROR(EXDEV);
d683ddbb
JG
1255 zb.zbm_creation_time =
1256 dsl_dataset_phys(fromds)->ds_creation_time;
1257 zb.zbm_creation_txg = dsl_dataset_phys(fromds)->ds_creation_txg;
1258 zb.zbm_guid = dsl_dataset_phys(fromds)->ds_guid;
da536844
MA
1259 is_clone = (fromds->ds_dir != ds->ds_dir);
1260 dsl_dataset_rele(fromds, FTAG);
f1512ee6 1261 err = dmu_send_impl(FTAG, dp, ds, &zb, is_clone,
b5256303
TC
1262 embedok, large_block_ok, compressok, rawok, outfd,
1263 0, 0, vp, off);
da536844 1264 } else {
f1512ee6 1265 err = dmu_send_impl(FTAG, dp, ds, NULL, B_FALSE,
b5256303
TC
1266 embedok, large_block_ok, compressok, rawok, outfd,
1267 0, 0, vp, off);
13fe0198 1268 }
b5256303 1269 dsl_dataset_rele_flags(ds, dsflags, FTAG);
da536844 1270 return (err);
13fe0198
MA
1271}
1272
1273int
47dfff3b 1274dmu_send(const char *tosnap, const char *fromsnap, boolean_t embedok,
b5256303
TC
1275 boolean_t large_block_ok, boolean_t compressok, boolean_t rawok,
1276 int outfd, uint64_t resumeobj, uint64_t resumeoff, vnode_t *vp,
1277 offset_t *off)
13fe0198
MA
1278{
1279 dsl_pool_t *dp;
1280 dsl_dataset_t *ds;
13fe0198 1281 int err;
b5256303 1282 ds_hold_flags_t dsflags = (rawok) ? 0 : DS_HOLD_FLAG_DECRYPT;
da536844 1283 boolean_t owned = B_FALSE;
13fe0198 1284
da536844 1285 if (fromsnap != NULL && strpbrk(fromsnap, "@#") == NULL)
2e528b49 1286 return (SET_ERROR(EINVAL));
13fe0198
MA
1287
1288 err = dsl_pool_hold(tosnap, FTAG, &dp);
1289 if (err != 0)
1290 return (err);
1291
da536844
MA
1292 if (strchr(tosnap, '@') == NULL && spa_writeable(dp->dp_spa)) {
1293 /*
1294 * We are sending a filesystem or volume. Ensure
1295 * that it doesn't change by owning the dataset.
1296 */
b5256303 1297 err = dsl_dataset_own(dp, tosnap, dsflags, FTAG, &ds);
da536844
MA
1298 owned = B_TRUE;
1299 } else {
b5256303 1300 err = dsl_dataset_hold_flags(dp, tosnap, dsflags, FTAG, &ds);
da536844 1301 }
13fe0198
MA
1302 if (err != 0) {
1303 dsl_pool_rele(dp, FTAG);
1304 return (err);
1305 }
1306
1307 if (fromsnap != NULL) {
da536844
MA
1308 zfs_bookmark_phys_t zb;
1309 boolean_t is_clone = B_FALSE;
1310 int fsnamelen = strchr(tosnap, '@') - tosnap;
1311
1312 /*
1313 * If the fromsnap is in a different filesystem, then
1314 * mark the send stream as a clone.
1315 */
1316 if (strncmp(tosnap, fromsnap, fsnamelen) != 0 ||
1317 (fromsnap[fsnamelen] != '@' &&
1318 fromsnap[fsnamelen] != '#')) {
1319 is_clone = B_TRUE;
1320 }
1321
1322 if (strchr(fromsnap, '@')) {
1323 dsl_dataset_t *fromds;
1324 err = dsl_dataset_hold(dp, fromsnap, FTAG, &fromds);
1325 if (err == 0) {
1326 if (!dsl_dataset_is_before(ds, fromds, 0))
1327 err = SET_ERROR(EXDEV);
1328 zb.zbm_creation_time =
d683ddbb 1329 dsl_dataset_phys(fromds)->ds_creation_time;
da536844 1330 zb.zbm_creation_txg =
d683ddbb
JG
1331 dsl_dataset_phys(fromds)->ds_creation_txg;
1332 zb.zbm_guid = dsl_dataset_phys(fromds)->ds_guid;
da536844
MA
1333 is_clone = (ds->ds_dir != fromds->ds_dir);
1334 dsl_dataset_rele(fromds, FTAG);
1335 }
1336 } else {
1337 err = dsl_bookmark_lookup(dp, fromsnap, ds, &zb);
1338 }
13fe0198 1339 if (err != 0) {
b5256303
TC
1340 if (owned)
1341 dsl_dataset_disown(ds, dsflags, FTAG);
1342 else
1343 dsl_dataset_rele_flags(ds, dsflags, FTAG);
1344
13fe0198
MA
1345 dsl_pool_rele(dp, FTAG);
1346 return (err);
1347 }
f1512ee6 1348 err = dmu_send_impl(FTAG, dp, ds, &zb, is_clone,
b5256303 1349 embedok, large_block_ok, compressok, rawok,
47dfff3b 1350 outfd, resumeobj, resumeoff, vp, off);
da536844 1351 } else {
f1512ee6 1352 err = dmu_send_impl(FTAG, dp, ds, NULL, B_FALSE,
b5256303 1353 embedok, large_block_ok, compressok, rawok,
47dfff3b 1354 outfd, resumeobj, resumeoff, vp, off);
13fe0198 1355 }
da536844 1356 if (owned)
b5256303 1357 dsl_dataset_disown(ds, dsflags, FTAG);
da536844 1358 else
b5256303
TC
1359 dsl_dataset_rele_flags(ds, dsflags, FTAG);
1360
da536844 1361 return (err);
13fe0198
MA
1362}
1363
5dc8b736 1364static int
2aa34383
DK
1365dmu_adjust_send_estimate_for_indirects(dsl_dataset_t *ds, uint64_t uncompressed,
1366 uint64_t compressed, boolean_t stream_compressed, uint64_t *sizep)
5dc8b736 1367{
ca0845d5 1368 int err = 0;
2aa34383 1369 uint64_t size;
5dc8b736
MG
1370 /*
1371 * Assume that space (both on-disk and in-stream) is dominated by
1372 * data. We will adjust for indirect blocks and the copies property,
1373 * but ignore per-object space used (eg, dnodes and DRR_OBJECT records).
1374 */
1375
2aa34383
DK
1376 uint64_t recordsize;
1377 uint64_t record_count;
dd429b46
PD
1378 objset_t *os;
1379 VERIFY0(dmu_objset_from_ds(ds, &os));
2aa34383
DK
1380
1381 /* Assume all (uncompressed) blocks are recordsize. */
ca0845d5
PD
1382 if (zfs_override_estimate_recordsize != 0) {
1383 recordsize = zfs_override_estimate_recordsize;
1384 } else if (os->os_phys->os_type == DMU_OST_ZVOL) {
dd429b46
PD
1385 err = dsl_prop_get_int_ds(ds,
1386 zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE), &recordsize);
1387 } else {
1388 err = dsl_prop_get_int_ds(ds,
1389 zfs_prop_to_name(ZFS_PROP_RECORDSIZE), &recordsize);
1390 }
2aa34383
DK
1391 if (err != 0)
1392 return (err);
1393 record_count = uncompressed / recordsize;
1394
1395 /*
1396 * If we're estimating a send size for a compressed stream, use the
1397 * compressed data size to estimate the stream size. Otherwise, use the
1398 * uncompressed data size.
1399 */
1400 size = stream_compressed ? compressed : uncompressed;
1401
5dc8b736
MG
1402 /*
1403 * Subtract out approximate space used by indirect blocks.
1404 * Assume most space is used by data blocks (non-indirect, non-dnode).
2aa34383 1405 * Assume no ditto blocks or internal fragmentation.
5dc8b736
MG
1406 *
1407 * Therefore, space used by indirect blocks is sizeof(blkptr_t) per
2aa34383 1408 * block.
5dc8b736 1409 */
2aa34383 1410 size -= record_count * sizeof (blkptr_t);
5dc8b736
MG
1411
1412 /* Add in the space for the record associated with each block. */
2aa34383 1413 size += record_count * sizeof (dmu_replay_record_t);
5dc8b736
MG
1414
1415 *sizep = size;
1416
1417 return (0);
1418}
1419
13fe0198 1420int
2aa34383
DK
1421dmu_send_estimate(dsl_dataset_t *ds, dsl_dataset_t *fromds,
1422 boolean_t stream_compressed, uint64_t *sizep)
330d06f9 1423{
330d06f9 1424 int err;
2aa34383 1425 uint64_t uncomp, comp;
13fe0198 1426
fd0fd646 1427 ASSERT(dsl_pool_config_held(ds->ds_dir->dd_pool));
330d06f9
MA
1428
1429 /* tosnap must be a snapshot */
0c66c32d 1430 if (!ds->ds_is_snapshot)
2e528b49 1431 return (SET_ERROR(EINVAL));
330d06f9 1432
71e2fe41
AG
1433 /* fromsnap, if provided, must be a snapshot */
1434 if (fromds != NULL && !fromds->ds_is_snapshot)
1435 return (SET_ERROR(EINVAL));
1436
6f1ffb06
MA
1437 /*
1438 * fromsnap must be an earlier snapshot from the same fs as tosnap,
1439 * or the origin's fs.
1440 */
da536844 1441 if (fromds != NULL && !dsl_dataset_is_before(ds, fromds, 0))
2e528b49 1442 return (SET_ERROR(EXDEV));
330d06f9 1443
2aa34383 1444 /* Get compressed and uncompressed size estimates of changed data. */
330d06f9 1445 if (fromds == NULL) {
2aa34383
DK
1446 uncomp = dsl_dataset_phys(ds)->ds_uncompressed_bytes;
1447 comp = dsl_dataset_phys(ds)->ds_compressed_bytes;
330d06f9 1448 } else {
2aa34383 1449 uint64_t used;
330d06f9 1450 err = dsl_dataset_space_written(fromds, ds,
2aa34383 1451 &used, &comp, &uncomp);
13fe0198 1452 if (err != 0)
330d06f9
MA
1453 return (err);
1454 }
1455
2aa34383
DK
1456 err = dmu_adjust_send_estimate_for_indirects(ds, uncomp, comp,
1457 stream_compressed, sizep);
dd429b46
PD
1458 /*
1459 * Add the size of the BEGIN and END records to the estimate.
1460 */
1461 *sizep += 2 * sizeof (dmu_replay_record_t);
5dc8b736
MG
1462 return (err);
1463}
330d06f9 1464
2aa34383
DK
1465struct calculate_send_arg {
1466 uint64_t uncompressed;
1467 uint64_t compressed;
1468};
1469
5dc8b736
MG
1470/*
1471 * Simple callback used to traverse the blocks of a snapshot and sum their
2aa34383 1472 * uncompressed and compressed sizes.
5dc8b736
MG
1473 */
1474/* ARGSUSED */
1475static int
1476dmu_calculate_send_traversal(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
1477 const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
1478{
2aa34383 1479 struct calculate_send_arg *space = arg;
5dc8b736 1480 if (bp != NULL && !BP_IS_HOLE(bp)) {
2aa34383
DK
1481 space->uncompressed += BP_GET_UCSIZE(bp);
1482 space->compressed += BP_GET_PSIZE(bp);
5dc8b736
MG
1483 }
1484 return (0);
1485}
1486
1487/*
1488 * Given a desination snapshot and a TXG, calculate the approximate size of a
1489 * send stream sent from that TXG. from_txg may be zero, indicating that the
1490 * whole snapshot will be sent.
1491 */
1492int
1493dmu_send_estimate_from_txg(dsl_dataset_t *ds, uint64_t from_txg,
2aa34383 1494 boolean_t stream_compressed, uint64_t *sizep)
5dc8b736 1495{
5dc8b736 1496 int err;
2aa34383 1497 struct calculate_send_arg size = { 0 };
5dc8b736 1498
fd0fd646 1499 ASSERT(dsl_pool_config_held(ds->ds_dir->dd_pool));
5dc8b736
MG
1500
1501 /* tosnap must be a snapshot */
1502 if (!dsl_dataset_is_snapshot(ds))
1503 return (SET_ERROR(EINVAL));
1504
1505 /* verify that from_txg is before the provided snapshot was taken */
1506 if (from_txg >= dsl_dataset_phys(ds)->ds_creation_txg) {
1507 return (SET_ERROR(EXDEV));
1508 }
330d06f9 1509 /*
5dc8b736
MG
1510 * traverse the blocks of the snapshot with birth times after
1511 * from_txg, summing their uncompressed size
330d06f9 1512 */
b5256303
TC
1513 err = traverse_dataset(ds, from_txg,
1514 TRAVERSE_POST | TRAVERSE_NO_DECRYPT,
5dc8b736 1515 dmu_calculate_send_traversal, &size);
2aa34383 1516
5dc8b736 1517 if (err)
330d06f9 1518 return (err);
330d06f9 1519
2aa34383
DK
1520 err = dmu_adjust_send_estimate_for_indirects(ds, size.uncompressed,
1521 size.compressed, stream_compressed, sizep);
5dc8b736 1522 return (err);
330d06f9
MA
1523}
1524
13fe0198
MA
1525typedef struct dmu_recv_begin_arg {
1526 const char *drba_origin;
1527 dmu_recv_cookie_t *drba_cookie;
1528 cred_t *drba_cred;
d9c460a0 1529 dsl_crypto_params_t *drba_dcp;
19580676 1530 uint64_t drba_snapobj;
13fe0198 1531} dmu_recv_begin_arg_t;
34dc7c2f 1532
34dc7c2f 1533static int
13fe0198 1534recv_begin_check_existing_impl(dmu_recv_begin_arg_t *drba, dsl_dataset_t *ds,
d9c460a0 1535 uint64_t fromguid, uint64_t featureflags)
34dc7c2f 1536{
34dc7c2f 1537 uint64_t val;
13fe0198
MA
1538 int error;
1539 dsl_pool_t *dp = ds->ds_dir->dd_pool;
4a385862
TC
1540 boolean_t encrypted = ds->ds_dir->dd_crypto_obj != 0;
1541 boolean_t raw = (featureflags & DMU_BACKUP_FEATURE_RAW) != 0;
1fff937a 1542 boolean_t embed = (featureflags & DMU_BACKUP_FEATURE_EMBED_DATA) != 0;
34dc7c2f 1543
13fe0198
MA
1544 /* temporary clone name must not exist */
1545 error = zap_lookup(dp->dp_meta_objset,
d683ddbb 1546 dsl_dir_phys(ds->ds_dir)->dd_child_dir_zapobj, recv_clone_name,
13fe0198
MA
1547 8, 1, &val);
1548 if (error != ENOENT)
1549 return (error == 0 ? EBUSY : error);
1550
572e2857 1551 /* new snapshot name must not exist */
13fe0198 1552 error = zap_lookup(dp->dp_meta_objset,
d683ddbb
JG
1553 dsl_dataset_phys(ds)->ds_snapnames_zapobj,
1554 drba->drba_cookie->drc_tosnap, 8, 1, &val);
13fe0198
MA
1555 if (error != ENOENT)
1556 return (error == 0 ? EEXIST : error);
572e2857 1557
788eb90c
JJ
1558 /*
1559 * Check snapshot limit before receiving. We'll recheck again at the
1560 * end, but might as well abort before receiving if we're already over
1561 * the limit.
1562 *
1563 * Note that we do not check the file system limit with
1564 * dsl_dir_fscount_check because the temporary %clones don't count
1565 * against that limit.
1566 */
1567 error = dsl_fs_ss_limit_check(ds->ds_dir, 1, ZFS_PROP_SNAPSHOT_LIMIT,
1568 NULL, drba->drba_cred);
1569 if (error != 0)
1570 return (error);
1571
13fe0198 1572 if (fromguid != 0) {
19580676 1573 dsl_dataset_t *snap;
d683ddbb 1574 uint64_t obj = dsl_dataset_phys(ds)->ds_prev_snap_obj;
19580676 1575
4a385862
TC
1576 /* Can't perform a raw receive on top of a non-raw receive */
1577 if (!encrypted && raw)
1578 return (SET_ERROR(EINVAL));
1579
1fff937a
TC
1580 /* Encryption is incompatible with embedded data */
1581 if (encrypted && embed)
1582 return (SET_ERROR(EINVAL));
1583
19580676
MA
1584 /* Find snapshot in this dir that matches fromguid. */
1585 while (obj != 0) {
1586 error = dsl_dataset_hold_obj(dp, obj, FTAG,
1587 &snap);
1588 if (error != 0)
1589 return (SET_ERROR(ENODEV));
1590 if (snap->ds_dir != ds->ds_dir) {
1591 dsl_dataset_rele(snap, FTAG);
1592 return (SET_ERROR(ENODEV));
1593 }
d683ddbb 1594 if (dsl_dataset_phys(snap)->ds_guid == fromguid)
19580676 1595 break;
d683ddbb 1596 obj = dsl_dataset_phys(snap)->ds_prev_snap_obj;
19580676
MA
1597 dsl_dataset_rele(snap, FTAG);
1598 }
1599 if (obj == 0)
2e528b49 1600 return (SET_ERROR(ENODEV));
34dc7c2f 1601
19580676
MA
1602 if (drba->drba_cookie->drc_force) {
1603 drba->drba_snapobj = obj;
1604 } else {
1605 /*
1606 * If we are not forcing, there must be no
1607 * changes since fromsnap.
1608 */
1609 if (dsl_dataset_modified_since_snap(ds, snap)) {
428870ff 1610 dsl_dataset_rele(snap, FTAG);
19580676 1611 return (SET_ERROR(ETXTBSY));
428870ff 1612 }
19580676 1613 drba->drba_snapobj = ds->ds_prev->ds_object;
428870ff 1614 }
19580676
MA
1615
1616 dsl_dataset_rele(snap, FTAG);
428870ff 1617 } else {
cf50a2b0
AG
1618 /* if full, then must be forced */
1619 if (!drba->drba_cookie->drc_force)
1620 return (SET_ERROR(EEXIST));
b5256303
TC
1621
1622 /*
1623 * We don't support using zfs recv -F to blow away
1624 * encrypted filesystems. This would require the
1625 * dsl dir to point to the old encryption key and
1626 * the new one at the same time during the receive.
1627 */
4a385862 1628 if ((!encrypted && raw) || encrypted)
b5256303
TC
1629 return (SET_ERROR(EINVAL));
1630
1fff937a
TC
1631 /*
1632 * Perform the same encryption checks we would if
1633 * we were creating a new dataset from scratch.
1634 */
1635 if (!raw) {
1636 boolean_t will_encrypt;
1637
d9c460a0 1638 error = dmu_objset_create_crypt_check(
1fff937a
TC
1639 ds->ds_dir->dd_parent, drba->drba_dcp,
1640 &will_encrypt);
d9c460a0
TC
1641 if (error != 0)
1642 return (error);
1fff937a
TC
1643
1644 if (will_encrypt && embed)
1645 return (SET_ERROR(EINVAL));
d9c460a0
TC
1646 }
1647
b5256303 1648 drba->drba_snapobj = 0;
428870ff 1649 }
34dc7c2f 1650
34dc7c2f 1651 return (0);
13fe0198
MA
1652
1653}
1654
1655static int
1656dmu_recv_begin_check(void *arg, dmu_tx_t *tx)
1657{
1658 dmu_recv_begin_arg_t *drba = arg;
1659 dsl_pool_t *dp = dmu_tx_pool(tx);
1660 struct drr_begin *drrb = drba->drba_cookie->drc_drrb;
1661 uint64_t fromguid = drrb->drr_fromguid;
1662 int flags = drrb->drr_flags;
b5256303 1663 ds_hold_flags_t dsflags = 0;
13fe0198 1664 int error;
9b67f605 1665 uint64_t featureflags = DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo);
13fe0198
MA
1666 dsl_dataset_t *ds;
1667 const char *tofs = drba->drba_cookie->drc_tofs;
1668
1669 /* already checked */
1670 ASSERT3U(drrb->drr_magic, ==, DMU_BACKUP_MAGIC);
47dfff3b 1671 ASSERT(!(featureflags & DMU_BACKUP_FEATURE_RESUMING));
13fe0198
MA
1672
1673 if (DMU_GET_STREAM_HDRTYPE(drrb->drr_versioninfo) ==
1674 DMU_COMPOUNDSTREAM ||
1675 drrb->drr_type >= DMU_OST_NUMTYPES ||
1676 ((flags & DRR_FLAG_CLONE) && drba->drba_origin == NULL))
2e528b49 1677 return (SET_ERROR(EINVAL));
13fe0198
MA
1678
1679 /* Verify pool version supports SA if SA_SPILL feature set */
9b67f605
MA
1680 if ((featureflags & DMU_BACKUP_FEATURE_SA_SPILL) &&
1681 spa_version(dp->dp_spa) < SPA_VERSION_SA)
1682 return (SET_ERROR(ENOTSUP));
1683
47dfff3b
MA
1684 if (drba->drba_cookie->drc_resumable &&
1685 !spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_EXTENSIBLE_DATASET))
1686 return (SET_ERROR(ENOTSUP));
1687
9b67f605
MA
1688 /*
1689 * The receiving code doesn't know how to translate a WRITE_EMBEDDED
2aa34383 1690 * record to a plain WRITE record, so the pool must have the
9b67f605
MA
1691 * EMBEDDED_DATA feature enabled if the stream has WRITE_EMBEDDED
1692 * records. Same with WRITE_EMBEDDED records that use LZ4 compression.
1693 */
1694 if ((featureflags & DMU_BACKUP_FEATURE_EMBED_DATA) &&
1695 !spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_EMBEDDED_DATA))
1696 return (SET_ERROR(ENOTSUP));
2aa34383 1697 if ((featureflags & DMU_BACKUP_FEATURE_LZ4) &&
9b67f605 1698 !spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_LZ4_COMPRESS))
2e528b49 1699 return (SET_ERROR(ENOTSUP));
13fe0198 1700
f1512ee6
MA
1701 /*
1702 * The receiving code doesn't know how to translate large blocks
1703 * to smaller ones, so the pool must have the LARGE_BLOCKS
73aac4aa
NB
1704 * feature enabled if the stream has LARGE_BLOCKS. Same with
1705 * large dnodes.
f1512ee6
MA
1706 */
1707 if ((featureflags & DMU_BACKUP_FEATURE_LARGE_BLOCKS) &&
1708 !spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_LARGE_BLOCKS))
1709 return (SET_ERROR(ENOTSUP));
50c957f7
NB
1710 if ((featureflags & DMU_BACKUP_FEATURE_LARGE_DNODE) &&
1711 !spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_LARGE_DNODE))
1712 return (SET_ERROR(ENOTSUP));
1713
d9c460a0 1714 if (featureflags & DMU_BACKUP_FEATURE_RAW) {
b5256303
TC
1715 /* raw receives require the encryption feature */
1716 if (!spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_ENCRYPTION))
1717 return (SET_ERROR(ENOTSUP));
1fff937a
TC
1718
1719 /* embedded data is incompatible with encryption and raw recv */
1720 if (featureflags & DMU_BACKUP_FEATURE_EMBED_DATA)
1721 return (SET_ERROR(EINVAL));
b5256303
TC
1722 } else {
1723 dsflags |= DS_HOLD_FLAG_DECRYPT;
1724 }
1725
1726 error = dsl_dataset_hold_flags(dp, tofs, dsflags, FTAG, &ds);
13fe0198
MA
1727 if (error == 0) {
1728 /* target fs already exists; recv into temp clone */
1729
1730 /* Can't recv a clone into an existing fs */
e6d3a843 1731 if (flags & DRR_FLAG_CLONE || drba->drba_origin) {
b5256303 1732 dsl_dataset_rele_flags(ds, dsflags, FTAG);
2e528b49 1733 return (SET_ERROR(EINVAL));
13fe0198
MA
1734 }
1735
d9c460a0
TC
1736 error = recv_begin_check_existing_impl(drba, ds, fromguid,
1737 featureflags);
b5256303 1738 dsl_dataset_rele_flags(ds, dsflags, FTAG);
13fe0198
MA
1739 } else if (error == ENOENT) {
1740 /* target fs does not exist; must be a full backup or clone */
eca7b760 1741 char buf[ZFS_MAX_DATASET_NAME_LEN];
13fe0198
MA
1742
1743 /*
1744 * If it's a non-clone incremental, we are missing the
1745 * target fs, so fail the recv.
1746 */
fcff0f35
PD
1747 if (fromguid != 0 && !(flags & DRR_FLAG_CLONE ||
1748 drba->drba_origin))
2e528b49 1749 return (SET_ERROR(ENOENT));
13fe0198 1750
e6d3a843
PD
1751 /*
1752 * If we're receiving a full send as a clone, and it doesn't
1753 * contain all the necessary free records and freeobject
1754 * records, reject it.
1755 */
1756 if (fromguid == 0 && drba->drba_origin &&
1757 !(flags & DRR_FLAG_FREERECORDS))
1758 return (SET_ERROR(EINVAL));
1759
13fe0198 1760 /* Open the parent of tofs */
eca7b760 1761 ASSERT3U(strlen(tofs), <, sizeof (buf));
13fe0198 1762 (void) strlcpy(buf, tofs, strrchr(tofs, '/') - tofs + 1);
b5256303 1763 error = dsl_dataset_hold_flags(dp, buf, dsflags, FTAG, &ds);
13fe0198
MA
1764 if (error != 0)
1765 return (error);
1766
d9c460a0
TC
1767 if ((featureflags & DMU_BACKUP_FEATURE_RAW) == 0 &&
1768 drba->drba_origin == NULL) {
1fff937a
TC
1769 boolean_t will_encrypt;
1770
1771 /*
1772 * Check that we aren't breaking any encryption rules
1773 * and that we have all the parameters we need to
1774 * create an encrypted dataset if necessary. If we are
1775 * making an encrypted dataset the stream can't have
1776 * embedded data.
1777 */
d9c460a0 1778 error = dmu_objset_create_crypt_check(ds->ds_dir,
1fff937a 1779 drba->drba_dcp, &will_encrypt);
d9c460a0
TC
1780 if (error != 0) {
1781 dsl_dataset_rele_flags(ds, dsflags, FTAG);
1782 return (error);
1783 }
1fff937a
TC
1784
1785 if (will_encrypt &&
1786 (featureflags & DMU_BACKUP_FEATURE_EMBED_DATA)) {
1787 dsl_dataset_rele_flags(ds, dsflags, FTAG);
1788 return (SET_ERROR(EINVAL));
1789 }
d9c460a0
TC
1790 }
1791
788eb90c
JJ
1792 /*
1793 * Check filesystem and snapshot limits before receiving. We'll
1794 * recheck snapshot limits again at the end (we create the
1795 * filesystems and increment those counts during begin_sync).
1796 */
1797 error = dsl_fs_ss_limit_check(ds->ds_dir, 1,
1798 ZFS_PROP_FILESYSTEM_LIMIT, NULL, drba->drba_cred);
1799 if (error != 0) {
b5256303 1800 dsl_dataset_rele_flags(ds, dsflags, FTAG);
788eb90c
JJ
1801 return (error);
1802 }
1803
1804 error = dsl_fs_ss_limit_check(ds->ds_dir, 1,
1805 ZFS_PROP_SNAPSHOT_LIMIT, NULL, drba->drba_cred);
1806 if (error != 0) {
b5256303 1807 dsl_dataset_rele_flags(ds, dsflags, FTAG);
788eb90c
JJ
1808 return (error);
1809 }
1810
13fe0198
MA
1811 if (drba->drba_origin != NULL) {
1812 dsl_dataset_t *origin;
b5256303
TC
1813
1814 error = dsl_dataset_hold_flags(dp, drba->drba_origin,
1815 dsflags, FTAG, &origin);
13fe0198 1816 if (error != 0) {
b5256303 1817 dsl_dataset_rele_flags(ds, dsflags, FTAG);
13fe0198
MA
1818 return (error);
1819 }
0c66c32d 1820 if (!origin->ds_is_snapshot) {
9b840763 1821 dsl_dataset_rele_flags(origin, dsflags, FTAG);
b5256303 1822 dsl_dataset_rele_flags(ds, dsflags, FTAG);
2e528b49 1823 return (SET_ERROR(EINVAL));
13fe0198 1824 }
e6d3a843
PD
1825 if (dsl_dataset_phys(origin)->ds_guid != fromguid &&
1826 fromguid != 0) {
9b840763 1827 dsl_dataset_rele_flags(origin, dsflags, FTAG);
b5256303 1828 dsl_dataset_rele_flags(ds, dsflags, FTAG);
2e528b49 1829 return (SET_ERROR(ENODEV));
13fe0198 1830 }
1fff937a
TC
1831 if (origin->ds_dir->dd_crypto_obj != 0 &&
1832 (featureflags & DMU_BACKUP_FEATURE_EMBED_DATA)) {
1833 dsl_dataset_rele_flags(origin, dsflags, FTAG);
1834 dsl_dataset_rele_flags(ds, dsflags, FTAG);
1835 return (SET_ERROR(EINVAL));
1836 }
b5256303
TC
1837 dsl_dataset_rele_flags(origin,
1838 dsflags, FTAG);
13fe0198 1839 }
b5256303 1840 dsl_dataset_rele_flags(ds, dsflags, FTAG);
13fe0198
MA
1841 error = 0;
1842 }
1843 return (error);
34dc7c2f
BB
1844}
1845
34dc7c2f 1846static void
13fe0198 1847dmu_recv_begin_sync(void *arg, dmu_tx_t *tx)
34dc7c2f 1848{
13fe0198
MA
1849 dmu_recv_begin_arg_t *drba = arg;
1850 dsl_pool_t *dp = dmu_tx_pool(tx);
47dfff3b 1851 objset_t *mos = dp->dp_meta_objset;
13fe0198
MA
1852 struct drr_begin *drrb = drba->drba_cookie->drc_drrb;
1853 const char *tofs = drba->drba_cookie->drc_tofs;
b5256303 1854 uint64_t featureflags = DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo);
13fe0198 1855 dsl_dataset_t *ds, *newds;
b5256303 1856 objset_t *os;
34dc7c2f 1857 uint64_t dsobj;
b5256303 1858 ds_hold_flags_t dsflags = 0;
13fe0198 1859 int error;
47dfff3b 1860 uint64_t crflags = 0;
d9c460a0
TC
1861 dsl_crypto_params_t dummy_dcp = { 0 };
1862 dsl_crypto_params_t *dcp = drba->drba_dcp;
13fe0198 1863
47dfff3b
MA
1864 if (drrb->drr_flags & DRR_FLAG_CI_DATA)
1865 crflags |= DS_FLAG_CI_DATASET;
d9c460a0
TC
1866
1867 if ((featureflags & DMU_BACKUP_FEATURE_RAW) == 0)
b5256303 1868 dsflags |= DS_HOLD_FLAG_DECRYPT;
d9c460a0
TC
1869
1870 /*
1871 * Raw, non-incremental recvs always use a dummy dcp with
1872 * the raw cmd set. Raw incremental recvs do not use a dcp
1873 * since the encryption parameters are already set in stone.
1874 */
1875 if (dcp == NULL && drba->drba_snapobj == 0 &&
1876 drba->drba_origin == NULL) {
1877 ASSERT3P(dcp, ==, NULL);
1878 dcp = &dummy_dcp;
1879
1880 if (featureflags & DMU_BACKUP_FEATURE_RAW)
1881 dcp->cp_cmd = DCP_CMD_RAW_RECV;
b5256303 1882 }
34dc7c2f 1883
b5256303 1884 error = dsl_dataset_hold_flags(dp, tofs, dsflags, FTAG, &ds);
13fe0198
MA
1885 if (error == 0) {
1886 /* create temporary clone */
19580676 1887 dsl_dataset_t *snap = NULL;
b5256303 1888
19580676
MA
1889 if (drba->drba_snapobj != 0) {
1890 VERIFY0(dsl_dataset_hold_obj(dp,
1891 drba->drba_snapobj, FTAG, &snap));
d9c460a0 1892 ASSERT3P(dcp, ==, NULL);
19580676 1893 }
b5256303 1894
13fe0198 1895 dsobj = dsl_dataset_create_sync(ds->ds_dir, recv_clone_name,
d9c460a0 1896 snap, crflags, drba->drba_cred, dcp, tx);
6b42ea85
PD
1897 if (drba->drba_snapobj != 0)
1898 dsl_dataset_rele(snap, FTAG);
b5256303 1899 dsl_dataset_rele_flags(ds, dsflags, FTAG);
13fe0198
MA
1900 } else {
1901 dsl_dir_t *dd;
1902 const char *tail;
1903 dsl_dataset_t *origin = NULL;
1904
1905 VERIFY0(dsl_dir_hold(dp, tofs, FTAG, &dd, &tail));
1906
1907 if (drba->drba_origin != NULL) {
1908 VERIFY0(dsl_dataset_hold(dp, drba->drba_origin,
1909 FTAG, &origin));
d9c460a0 1910 ASSERT3P(dcp, ==, NULL);
13fe0198
MA
1911 }
1912
1913 /* Create new dataset. */
b5256303 1914 dsobj = dsl_dataset_create_sync(dd, strrchr(tofs, '/') + 1,
d9c460a0 1915 origin, crflags, drba->drba_cred, dcp, tx);
13fe0198
MA
1916 if (origin != NULL)
1917 dsl_dataset_rele(origin, FTAG);
1918 dsl_dir_rele(dd, FTAG);
1919 drba->drba_cookie->drc_newfs = B_TRUE;
1920 }
d9c460a0 1921
b5256303
TC
1922 VERIFY0(dsl_dataset_own_obj(dp, dsobj, dsflags, dmu_recv_tag, &newds));
1923 VERIFY0(dmu_objset_from_ds(newds, &os));
13fe0198 1924
47dfff3b 1925 if (drba->drba_cookie->drc_resumable) {
47dfff3b
MA
1926 dsl_dataset_zapify(newds, tx);
1927 if (drrb->drr_fromguid != 0) {
1928 VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_FROMGUID,
1929 8, 1, &drrb->drr_fromguid, tx));
1930 }
1931 VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_TOGUID,
1932 8, 1, &drrb->drr_toguid, tx));
1933 VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_TONAME,
1934 1, strlen(drrb->drr_toname) + 1, drrb->drr_toname, tx));
1c27024e
DB
1935 uint64_t one = 1;
1936 uint64_t zero = 0;
47dfff3b
MA
1937 VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_OBJECT,
1938 8, 1, &one, tx));
1939 VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_OFFSET,
1940 8, 1, &zero, tx));
1941 VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_BYTES,
1942 8, 1, &zero, tx));
b5256303 1943 if (featureflags & DMU_BACKUP_FEATURE_LARGE_BLOCKS) {
2aa34383 1944 VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_LARGEBLOCK,
02730c33 1945 8, 1, &one, tx));
2aa34383 1946 }
b5256303 1947 if (featureflags & DMU_BACKUP_FEATURE_EMBED_DATA) {
47dfff3b
MA
1948 VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_EMBEDOK,
1949 8, 1, &one, tx));
1950 }
b5256303 1951 if (featureflags & DMU_BACKUP_FEATURE_COMPRESSED) {
2aa34383
DK
1952 VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_COMPRESSOK,
1953 8, 1, &one, tx));
1954 }
b5256303
TC
1955 if (featureflags & DMU_BACKUP_FEATURE_RAW) {
1956 VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_RAWOK,
1957 8, 1, &one, tx));
1958 }
1959 }
1960
1961 /*
1962 * Usually the os->os_encrypted value is tied to the presence of a
1963 * DSL Crypto Key object in the dd. However, that will not be received
1964 * until dmu_recv_stream(), so we set the value manually for now.
1965 */
1966 if (featureflags & DMU_BACKUP_FEATURE_RAW) {
1967 os->os_encrypted = B_TRUE;
1968 drba->drba_cookie->drc_raw = B_TRUE;
47dfff3b
MA
1969 }
1970
13fe0198 1971 dmu_buf_will_dirty(newds->ds_dbuf, tx);
d683ddbb 1972 dsl_dataset_phys(newds)->ds_flags |= DS_FLAG_INCONSISTENT;
34dc7c2f 1973
428870ff 1974 /*
b5256303
TC
1975 * If we actually created a non-clone, we need to create the objset
1976 * in our new dataset. If this is a raw send we postpone this until
1977 * dmu_recv_stream() so that we can allocate the metadnode with the
1978 * properties from the DRR_BEGIN payload.
428870ff 1979 */
cc9bb3e5 1980 rrw_enter(&newds->ds_bp_rwlock, RW_READER, FTAG);
b5256303
TC
1981 if (BP_IS_HOLE(dsl_dataset_get_blkptr(newds)) &&
1982 (featureflags & DMU_BACKUP_FEATURE_RAW) == 0) {
428870ff 1983 (void) dmu_objset_create_impl(dp->dp_spa,
13fe0198 1984 newds, dsl_dataset_get_blkptr(newds), drrb->drr_type, tx);
428870ff 1985 }
cc9bb3e5 1986 rrw_exit(&newds->ds_bp_rwlock, FTAG);
34dc7c2f 1987
13fe0198 1988 drba->drba_cookie->drc_ds = newds;
428870ff 1989
13fe0198 1990 spa_history_log_internal_ds(newds, "receive", tx, "");
34dc7c2f
BB
1991}
1992
47dfff3b
MA
1993static int
1994dmu_recv_resume_begin_check(void *arg, dmu_tx_t *tx)
1995{
1996 dmu_recv_begin_arg_t *drba = arg;
1997 dsl_pool_t *dp = dmu_tx_pool(tx);
1998 struct drr_begin *drrb = drba->drba_cookie->drc_drrb;
1999 int error;
b5256303 2000 ds_hold_flags_t dsflags = 0;
47dfff3b
MA
2001 uint64_t featureflags = DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo);
2002 dsl_dataset_t *ds;
2003 const char *tofs = drba->drba_cookie->drc_tofs;
eca7b760 2004
47dfff3b
MA
2005 /* already checked */
2006 ASSERT3U(drrb->drr_magic, ==, DMU_BACKUP_MAGIC);
2007 ASSERT(featureflags & DMU_BACKUP_FEATURE_RESUMING);
2008
2009 if (DMU_GET_STREAM_HDRTYPE(drrb->drr_versioninfo) ==
2010 DMU_COMPOUNDSTREAM ||
2011 drrb->drr_type >= DMU_OST_NUMTYPES)
2012 return (SET_ERROR(EINVAL));
2013
2014 /* Verify pool version supports SA if SA_SPILL feature set */
2015 if ((featureflags & DMU_BACKUP_FEATURE_SA_SPILL) &&
2016 spa_version(dp->dp_spa) < SPA_VERSION_SA)
2017 return (SET_ERROR(ENOTSUP));
2018
2019 /*
2020 * The receiving code doesn't know how to translate a WRITE_EMBEDDED
2021 * record to a plain WRITE record, so the pool must have the
2022 * EMBEDDED_DATA feature enabled if the stream has WRITE_EMBEDDED
2023 * records. Same with WRITE_EMBEDDED records that use LZ4 compression.
2024 */
2025 if ((featureflags & DMU_BACKUP_FEATURE_EMBED_DATA) &&
2026 !spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_EMBEDDED_DATA))
2027 return (SET_ERROR(ENOTSUP));
2aa34383 2028 if ((featureflags & DMU_BACKUP_FEATURE_LZ4) &&
47dfff3b
MA
2029 !spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_LZ4_COMPRESS))
2030 return (SET_ERROR(ENOTSUP));
2031
73aac4aa
NB
2032 /*
2033 * The receiving code doesn't know how to translate large blocks
2034 * to smaller ones, so the pool must have the LARGE_BLOCKS
2035 * feature enabled if the stream has LARGE_BLOCKS. Same with
2036 * large dnodes.
2037 */
2038 if ((featureflags & DMU_BACKUP_FEATURE_LARGE_BLOCKS) &&
2039 !spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_LARGE_BLOCKS))
2040 return (SET_ERROR(ENOTSUP));
2041 if ((featureflags & DMU_BACKUP_FEATURE_LARGE_DNODE) &&
2042 !spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_LARGE_DNODE))
2043 return (SET_ERROR(ENOTSUP));
2044
1c27024e
DB
2045 /* 6 extra bytes for /%recv */
2046 char recvname[ZFS_MAX_DATASET_NAME_LEN + 6];
47dfff3b
MA
2047 (void) snprintf(recvname, sizeof (recvname), "%s/%s",
2048 tofs, recv_clone_name);
2049
b5256303
TC
2050 if ((featureflags & DMU_BACKUP_FEATURE_RAW) == 0)
2051 dsflags |= DS_HOLD_FLAG_DECRYPT;
2052
2053 if (dsl_dataset_hold_flags(dp, recvname, dsflags, FTAG, &ds) != 0) {
47dfff3b 2054 /* %recv does not exist; continue in tofs */
b5256303 2055 error = dsl_dataset_hold_flags(dp, tofs, dsflags, FTAG, &ds);
47dfff3b
MA
2056 if (error != 0)
2057 return (error);
2058 }
2059
2060 /* check that ds is marked inconsistent */
2061 if (!DS_IS_INCONSISTENT(ds)) {
b5256303 2062 dsl_dataset_rele_flags(ds, dsflags, FTAG);
47dfff3b
MA
2063 return (SET_ERROR(EINVAL));
2064 }
2065
2066 /* check that there is resuming data, and that the toguid matches */
2067 if (!dsl_dataset_is_zapified(ds)) {
b5256303 2068 dsl_dataset_rele_flags(ds, dsflags, FTAG);
47dfff3b
MA
2069 return (SET_ERROR(EINVAL));
2070 }
1c27024e 2071 uint64_t val;
47dfff3b
MA
2072 error = zap_lookup(dp->dp_meta_objset, ds->ds_object,
2073 DS_FIELD_RESUME_TOGUID, sizeof (val), 1, &val);
2074 if (error != 0 || drrb->drr_toguid != val) {
b5256303 2075 dsl_dataset_rele_flags(ds, dsflags, FTAG);
47dfff3b
MA
2076 return (SET_ERROR(EINVAL));
2077 }
2078
2079 /*
2080 * Check if the receive is still running. If so, it will be owned.
2081 * Note that nothing else can own the dataset (e.g. after the receive
2082 * fails) because it will be marked inconsistent.
2083 */
2084 if (dsl_dataset_has_owner(ds)) {
b5256303 2085 dsl_dataset_rele_flags(ds, dsflags, FTAG);
47dfff3b
MA
2086 return (SET_ERROR(EBUSY));
2087 }
2088
2089 /* There should not be any snapshots of this fs yet. */
2090 if (ds->ds_prev != NULL && ds->ds_prev->ds_dir == ds->ds_dir) {
b5256303 2091 dsl_dataset_rele_flags(ds, dsflags, FTAG);
47dfff3b
MA
2092 return (SET_ERROR(EINVAL));
2093 }
2094
2095 /*
2096 * Note: resume point will be checked when we process the first WRITE
2097 * record.
2098 */
2099
2100 /* check that the origin matches */
2101 val = 0;
2102 (void) zap_lookup(dp->dp_meta_objset, ds->ds_object,
2103 DS_FIELD_RESUME_FROMGUID, sizeof (val), 1, &val);
2104 if (drrb->drr_fromguid != val) {
b5256303 2105 dsl_dataset_rele_flags(ds, dsflags, FTAG);
47dfff3b
MA
2106 return (SET_ERROR(EINVAL));
2107 }
2108
b5256303 2109 dsl_dataset_rele_flags(ds, dsflags, FTAG);
47dfff3b
MA
2110 return (0);
2111}
2112
2113static void
2114dmu_recv_resume_begin_sync(void *arg, dmu_tx_t *tx)
2115{
2116 dmu_recv_begin_arg_t *drba = arg;
2117 dsl_pool_t *dp = dmu_tx_pool(tx);
2118 const char *tofs = drba->drba_cookie->drc_tofs;
b5256303
TC
2119 struct drr_begin *drrb = drba->drba_cookie->drc_drrb;
2120 uint64_t featureflags = DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo);
47dfff3b 2121 dsl_dataset_t *ds;
b5256303
TC
2122 objset_t *os;
2123 ds_hold_flags_t dsflags = 0;
47dfff3b 2124 uint64_t dsobj;
eca7b760
IK
2125 /* 6 extra bytes for /%recv */
2126 char recvname[ZFS_MAX_DATASET_NAME_LEN + 6];
47dfff3b
MA
2127
2128 (void) snprintf(recvname, sizeof (recvname), "%s/%s",
2129 tofs, recv_clone_name);
2130
b5256303
TC
2131 if (featureflags & DMU_BACKUP_FEATURE_RAW) {
2132 drba->drba_cookie->drc_raw = B_TRUE;
2133 } else {
2134 dsflags |= DS_HOLD_FLAG_DECRYPT;
2135 }
2136
2137 if (dsl_dataset_hold_flags(dp, recvname, dsflags, FTAG, &ds) != 0) {
47dfff3b 2138 /* %recv does not exist; continue in tofs */
b5256303 2139 VERIFY0(dsl_dataset_hold_flags(dp, tofs, dsflags, FTAG, &ds));
47dfff3b
MA
2140 drba->drba_cookie->drc_newfs = B_TRUE;
2141 }
2142
2143 /* clear the inconsistent flag so that we can own it */
2144 ASSERT(DS_IS_INCONSISTENT(ds));
2145 dmu_buf_will_dirty(ds->ds_dbuf, tx);
2146 dsl_dataset_phys(ds)->ds_flags &= ~DS_FLAG_INCONSISTENT;
2147 dsobj = ds->ds_object;
b5256303 2148 dsl_dataset_rele_flags(ds, dsflags, FTAG);
47dfff3b 2149
b5256303
TC
2150 VERIFY0(dsl_dataset_own_obj(dp, dsobj, dsflags, dmu_recv_tag, &ds));
2151 VERIFY0(dmu_objset_from_ds(ds, &os));
47dfff3b
MA
2152
2153 dmu_buf_will_dirty(ds->ds_dbuf, tx);
2154 dsl_dataset_phys(ds)->ds_flags |= DS_FLAG_INCONSISTENT;
2155
cc9bb3e5 2156 rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);
2637dda8
TC
2157 ASSERT(!BP_IS_HOLE(dsl_dataset_get_blkptr(ds)) ||
2158 drba->drba_cookie->drc_raw);
cc9bb3e5 2159 rrw_exit(&ds->ds_bp_rwlock, FTAG);
47dfff3b
MA
2160
2161 drba->drba_cookie->drc_ds = ds;
2162
2163 spa_history_log_internal_ds(ds, "resume receive", tx, "");
2164}
2165
34dc7c2f
BB
2166/*
2167 * NB: callers *MUST* call dmu_recv_stream() if dmu_recv_begin()
2168 * succeeds; otherwise we will leak the holds on the datasets.
2169 */
2170int
47dfff3b 2171dmu_recv_begin(char *tofs, char *tosnap, dmu_replay_record_t *drr_begin,
d9c460a0
TC
2172 boolean_t force, boolean_t resumable, nvlist_t *localprops,
2173 nvlist_t *hidden_args, char *origin, dmu_recv_cookie_t *drc)
34dc7c2f 2174{
13fe0198 2175 dmu_recv_begin_arg_t drba = { 0 };
34dc7c2f
BB
2176
2177 bzero(drc, sizeof (dmu_recv_cookie_t));
47dfff3b
MA
2178 drc->drc_drr_begin = drr_begin;
2179 drc->drc_drrb = &drr_begin->drr_u.drr_begin;
34dc7c2f 2180 drc->drc_tosnap = tosnap;
13fe0198 2181 drc->drc_tofs = tofs;
34dc7c2f 2182 drc->drc_force = force;
47dfff3b 2183 drc->drc_resumable = resumable;
788eb90c 2184 drc->drc_cred = CRED();
48fbb9dd 2185 drc->drc_clone = (origin != NULL);
34dc7c2f 2186
47dfff3b 2187 if (drc->drc_drrb->drr_magic == BSWAP_64(DMU_BACKUP_MAGIC)) {
13fe0198 2188 drc->drc_byteswap = B_TRUE;
a6255b7f 2189 (void) fletcher_4_incremental_byteswap(drr_begin,
13fe0198 2190 sizeof (dmu_replay_record_t), &drc->drc_cksum);
47dfff3b
MA
2191 byteswap_record(drr_begin);
2192 } else if (drc->drc_drrb->drr_magic == DMU_BACKUP_MAGIC) {
a6255b7f 2193 (void) fletcher_4_incremental_native(drr_begin,
13fe0198 2194 sizeof (dmu_replay_record_t), &drc->drc_cksum);
47dfff3b
MA
2195 } else {
2196 return (SET_ERROR(EINVAL));
34dc7c2f
BB
2197 }
2198
13fe0198
MA
2199 drba.drba_origin = origin;
2200 drba.drba_cookie = drc;
2201 drba.drba_cred = CRED();
2202
47dfff3b
MA
2203 if (DMU_GET_FEATUREFLAGS(drc->drc_drrb->drr_versioninfo) &
2204 DMU_BACKUP_FEATURE_RESUMING) {
2205 return (dsl_sync_task(tofs,
2206 dmu_recv_resume_begin_check, dmu_recv_resume_begin_sync,
2207 &drba, 5, ZFS_SPACE_CHECK_NORMAL));
2208 } else {
d9c460a0
TC
2209 int err;
2210
2211 /*
2212 * For non-raw, non-incremental, non-resuming receives the
2213 * user can specify encryption parameters on the command line
2214 * with "zfs recv -o". For these receives we create a dcp and
2215 * pass it to the sync task. Creating the dcp will implicitly
2216 * remove the encryption params from the localprops nvlist,
2217 * which avoids errors when trying to set these normally
2218 * read-only properties. Any other kind of receive that
2219 * attempts to set these properties will fail as a result.
2220 */
2221 if ((DMU_GET_FEATUREFLAGS(drc->drc_drrb->drr_versioninfo) &
2222 DMU_BACKUP_FEATURE_RAW) == 0 &&
2223 origin == NULL && drc->drc_drrb->drr_fromguid == 0) {
2224 err = dsl_crypto_params_create_nvlist(DCP_CMD_NONE,
2225 localprops, hidden_args, &drba.drba_dcp);
2226 if (err != 0)
2227 return (err);
2228 }
2229
2230 err = dsl_sync_task(tofs,
47dfff3b 2231 dmu_recv_begin_check, dmu_recv_begin_sync,
d9c460a0
TC
2232 &drba, 5, ZFS_SPACE_CHECK_NORMAL);
2233 dsl_crypto_params_free(drba.drba_dcp, !!err);
2234
2235 return (err);
47dfff3b 2236 }
34dc7c2f
BB
2237}
2238
fcff0f35
PD
2239struct receive_record_arg {
2240 dmu_replay_record_t header;
2241 void *payload; /* Pointer to a buffer containing the payload */
2242 /*
2243 * If the record is a write, pointer to the arc_buf_t containing the
2244 * payload.
2245 */
b5256303 2246 arc_buf_t *arc_buf;
fcff0f35 2247 int payload_size;
47dfff3b 2248 uint64_t bytes_read; /* bytes read from stream when record created */
fcff0f35
PD
2249 boolean_t eos_marker; /* Marks the end of the stream */
2250 bqueue_node_t node;
2251};
2252
2253struct receive_writer_arg {
37f8a883 2254 objset_t *os;
13fe0198 2255 boolean_t byteswap;
fcff0f35 2256 bqueue_t q;
47dfff3b 2257
fcff0f35
PD
2258 /*
2259 * These three args are used to signal to the main thread that we're
2260 * done.
2261 */
2262 kmutex_t mutex;
2263 kcondvar_t cv;
2264 boolean_t done;
47dfff3b 2265
fcff0f35
PD
2266 int err;
2267 /* A map from guid to dataset to help handle dedup'd streams. */
2268 avl_tree_t *guid_to_ds_map;
47dfff3b 2269 boolean_t resumable;
9b840763 2270 boolean_t raw;
48fbb9dd
FG
2271 uint64_t last_object;
2272 uint64_t last_offset;
2273 uint64_t max_object; /* highest object ID referenced in stream */
47dfff3b 2274 uint64_t bytes_read; /* bytes read when current record created */
095495e0
TC
2275
2276 /* Encryption parameters for the last received DRR_OBJECT_RANGE */
0c03d21a 2277 boolean_t or_crypt_params_present;
095495e0
TC
2278 uint64_t or_firstobj;
2279 uint64_t or_numslots;
2280 uint8_t or_salt[ZIO_DATA_SALT_LEN];
2281 uint8_t or_iv[ZIO_DATA_IV_LEN];
2282 uint8_t or_mac[ZIO_DATA_MAC_LEN];
2283 boolean_t or_byteorder;
fcff0f35 2284};
37f8a883 2285
e6d3a843
PD
2286struct objlist {
2287 list_t list; /* List of struct receive_objnode. */
2288 /*
2289 * Last object looked up. Used to assert that objects are being looked
2290 * up in ascending order.
2291 */
2292 uint64_t last_lookup;
2293};
2294
2295struct receive_objnode {
2296 list_node_t node;
2297 uint64_t object;
2298};
2299
fcff0f35
PD
2300struct receive_arg {
2301 objset_t *os;
2302 vnode_t *vp; /* The vnode to read the stream from */
2303 uint64_t voff; /* The current offset in the stream */
47dfff3b 2304 uint64_t bytes_read;
fcff0f35
PD
2305 /*
2306 * A record that has had its payload read in, but hasn't yet been handed
2307 * off to the worker thread.
2308 */
2309 struct receive_record_arg *rrd;
2310 /* A record that has had its header read in, but not its payload. */
2311 struct receive_record_arg *next_rrd;
34dc7c2f 2312 zio_cksum_t cksum;
37f8a883 2313 zio_cksum_t prev_cksum;
fcff0f35
PD
2314 int err;
2315 boolean_t byteswap;
9b840763 2316 boolean_t raw;
b5256303 2317 uint64_t featureflags;
fcff0f35 2318 /* Sorted list of objects not to issue prefetches for. */
e6d3a843 2319 struct objlist ignore_objlist;
34dc7c2f
BB
2320};
2321
428870ff
BB
2322typedef struct guid_map_entry {
2323 uint64_t guid;
b5256303 2324 boolean_t raw;
428870ff
BB
2325 dsl_dataset_t *gme_ds;
2326 avl_node_t avlnode;
2327} guid_map_entry_t;
2328
2329static int
2330guid_compare(const void *arg1, const void *arg2)
2331{
ee36c709
GN
2332 const guid_map_entry_t *gmep1 = (const guid_map_entry_t *)arg1;
2333 const guid_map_entry_t *gmep2 = (const guid_map_entry_t *)arg2;
428870ff 2334
ee36c709 2335 return (AVL_CMP(gmep1->guid, gmep2->guid));
428870ff
BB
2336}
2337
572e2857
BB
2338static void
2339free_guid_map_onexit(void *arg)
2340{
2341 avl_tree_t *ca = arg;
2342 void *cookie = NULL;
2343 guid_map_entry_t *gmep;
2344
2345 while ((gmep = avl_destroy_nodes(ca, &cookie)) != NULL) {
149ce888
TC
2346 ds_hold_flags_t dsflags = DS_HOLD_FLAG_DECRYPT;
2347
2348 if (gmep->raw) {
2349 gmep->gme_ds->ds_objset->os_raw_receive = B_FALSE;
2350 dsflags &= ~DS_HOLD_FLAG_DECRYPT;
2351 }
2352
2353 dsl_dataset_disown(gmep->gme_ds, dsflags, gmep);
572e2857
BB
2354 kmem_free(gmep, sizeof (guid_map_entry_t));
2355 }
2356 avl_destroy(ca);
2357 kmem_free(ca, sizeof (avl_tree_t));
2358}
2359
37f8a883 2360static int
fcff0f35 2361receive_read(struct receive_arg *ra, int len, void *buf)
34dc7c2f 2362{
34dc7c2f
BB
2363 int done = 0;
2364
f8866f8a
ER
2365 /*
2366 * The code doesn't rely on this (lengths being multiples of 8). See
2367 * comment in dump_bytes.
2368 */
b5256303
TC
2369 ASSERT(len % 8 == 0 ||
2370 (ra->featureflags & DMU_BACKUP_FEATURE_RAW) != 0);
34dc7c2f
BB
2371
2372 while (done < len) {
2373 ssize_t resid;
2374
2375 ra->err = vn_rdwr(UIO_READ, ra->vp,
37f8a883 2376 (char *)buf + done, len - done,
34dc7c2f
BB
2377 ra->voff, UIO_SYSSPACE, FAPPEND,
2378 RLIM64_INFINITY, CRED(), &resid);
2379
47dfff3b
MA
2380 if (resid == len - done) {
2381 /*
2382 * Note: ECKSUM indicates that the receive
2383 * was interrupted and can potentially be resumed.
2384 */
2385 ra->err = SET_ERROR(ECKSUM);
2386 }
34dc7c2f
BB
2387 ra->voff += len - done - resid;
2388 done = len - resid;
13fe0198 2389 if (ra->err != 0)
37f8a883 2390 return (ra->err);
34dc7c2f
BB
2391 }
2392
47dfff3b
MA
2393 ra->bytes_read += len;
2394
34dc7c2f 2395 ASSERT3U(done, ==, len);
37f8a883 2396 return (0);
34dc7c2f
BB
2397}
2398
60948de1 2399noinline static void
37f8a883 2400byteswap_record(dmu_replay_record_t *drr)
34dc7c2f
BB
2401{
2402#define DO64(X) (drr->drr_u.X = BSWAP_64(drr->drr_u.X))
2403#define DO32(X) (drr->drr_u.X = BSWAP_32(drr->drr_u.X))
2404 drr->drr_type = BSWAP_32(drr->drr_type);
2405 drr->drr_payloadlen = BSWAP_32(drr->drr_payloadlen);
37f8a883 2406
34dc7c2f
BB
2407 switch (drr->drr_type) {
2408 case DRR_BEGIN:
2409 DO64(drr_begin.drr_magic);
428870ff 2410 DO64(drr_begin.drr_versioninfo);
34dc7c2f
BB
2411 DO64(drr_begin.drr_creation_time);
2412 DO32(drr_begin.drr_type);
2413 DO32(drr_begin.drr_flags);
2414 DO64(drr_begin.drr_toguid);
2415 DO64(drr_begin.drr_fromguid);
2416 break;
2417 case DRR_OBJECT:
2418 DO64(drr_object.drr_object);
34dc7c2f
BB
2419 DO32(drr_object.drr_type);
2420 DO32(drr_object.drr_bonustype);
2421 DO32(drr_object.drr_blksz);
2422 DO32(drr_object.drr_bonuslen);
b5256303 2423 DO32(drr_object.drr_raw_bonuslen);
428870ff 2424 DO64(drr_object.drr_toguid);
ae76f45c 2425 DO64(drr_object.drr_maxblkid);
34dc7c2f
BB
2426 break;
2427 case DRR_FREEOBJECTS:
2428 DO64(drr_freeobjects.drr_firstobj);
2429 DO64(drr_freeobjects.drr_numobjs);
428870ff 2430 DO64(drr_freeobjects.drr_toguid);
34dc7c2f
BB
2431 break;
2432 case DRR_WRITE:
2433 DO64(drr_write.drr_object);
2434 DO32(drr_write.drr_type);
2435 DO64(drr_write.drr_offset);
2aa34383 2436 DO64(drr_write.drr_logical_size);
428870ff 2437 DO64(drr_write.drr_toguid);
37f8a883 2438 ZIO_CHECKSUM_BSWAP(&drr->drr_u.drr_write.drr_key.ddk_cksum);
428870ff 2439 DO64(drr_write.drr_key.ddk_prop);
2aa34383 2440 DO64(drr_write.drr_compressed_size);
428870ff
BB
2441 break;
2442 case DRR_WRITE_BYREF:
2443 DO64(drr_write_byref.drr_object);
2444 DO64(drr_write_byref.drr_offset);
2445 DO64(drr_write_byref.drr_length);
2446 DO64(drr_write_byref.drr_toguid);
2447 DO64(drr_write_byref.drr_refguid);
2448 DO64(drr_write_byref.drr_refobject);
2449 DO64(drr_write_byref.drr_refoffset);
37f8a883
MA
2450 ZIO_CHECKSUM_BSWAP(&drr->drr_u.drr_write_byref.
2451 drr_key.ddk_cksum);
428870ff 2452 DO64(drr_write_byref.drr_key.ddk_prop);
34dc7c2f 2453 break;
9b67f605
MA
2454 case DRR_WRITE_EMBEDDED:
2455 DO64(drr_write_embedded.drr_object);
2456 DO64(drr_write_embedded.drr_offset);
2457 DO64(drr_write_embedded.drr_length);
2458 DO64(drr_write_embedded.drr_toguid);
2459 DO32(drr_write_embedded.drr_lsize);
2460 DO32(drr_write_embedded.drr_psize);
2461 break;
34dc7c2f
BB
2462 case DRR_FREE:
2463 DO64(drr_free.drr_object);
2464 DO64(drr_free.drr_offset);
2465 DO64(drr_free.drr_length);
428870ff
BB
2466 DO64(drr_free.drr_toguid);
2467 break;
2468 case DRR_SPILL:
2469 DO64(drr_spill.drr_object);
2470 DO64(drr_spill.drr_length);
2471 DO64(drr_spill.drr_toguid);
b5256303
TC
2472 DO64(drr_spill.drr_compressed_size);
2473 DO32(drr_spill.drr_type);
2474 break;
2475 case DRR_OBJECT_RANGE:
2476 DO64(drr_object_range.drr_firstobj);
2477 DO64(drr_object_range.drr_numslots);
2478 DO64(drr_object_range.drr_toguid);
34dc7c2f
BB
2479 break;
2480 case DRR_END:
428870ff 2481 DO64(drr_end.drr_toguid);
37f8a883 2482 ZIO_CHECKSUM_BSWAP(&drr->drr_u.drr_end.drr_checksum);
34dc7c2f 2483 break;
e75c13c3
BB
2484 default:
2485 break;
34dc7c2f 2486 }
37f8a883
MA
2487
2488 if (drr->drr_type != DRR_BEGIN) {
2489 ZIO_CHECKSUM_BSWAP(&drr->drr_u.drr_checksum.drr_checksum);
2490 }
2491
34dc7c2f
BB
2492#undef DO64
2493#undef DO32
2494}
2495
6c59307a
MA
2496static inline uint8_t
2497deduce_nblkptr(dmu_object_type_t bonus_type, uint64_t bonus_size)
2498{
2499 if (bonus_type == DMU_OT_SA) {
2500 return (1);
2501 } else {
2502 return (1 +
50c957f7
NB
2503 ((DN_OLD_MAX_BONUSLEN -
2504 MIN(DN_OLD_MAX_BONUSLEN, bonus_size)) >> SPA_BLKPTRSHIFT));
6c59307a
MA
2505 }
2506}
2507
47dfff3b
MA
2508static void
2509save_resume_state(struct receive_writer_arg *rwa,
2510 uint64_t object, uint64_t offset, dmu_tx_t *tx)
2511{
2512 int txgoff = dmu_tx_get_txg(tx) & TXG_MASK;
2513
2514 if (!rwa->resumable)
2515 return;
2516
2517 /*
2518 * We use ds_resume_bytes[] != 0 to indicate that we need to
2519 * update this on disk, so it must not be 0.
2520 */
2521 ASSERT(rwa->bytes_read != 0);
2522
2523 /*
2524 * We only resume from write records, which have a valid
2525 * (non-meta-dnode) object number.
2526 */
2527 ASSERT(object != 0);
2528
2529 /*
2530 * For resuming to work correctly, we must receive records in order,
2531 * sorted by object,offset. This is checked by the callers, but
2532 * assert it here for good measure.
2533 */
2534 ASSERT3U(object, >=, rwa->os->os_dsl_dataset->ds_resume_object[txgoff]);
2535 ASSERT(object != rwa->os->os_dsl_dataset->ds_resume_object[txgoff] ||
2536 offset >= rwa->os->os_dsl_dataset->ds_resume_offset[txgoff]);
2537 ASSERT3U(rwa->bytes_read, >=,
2538 rwa->os->os_dsl_dataset->ds_resume_bytes[txgoff]);
2539
2540 rwa->os->os_dsl_dataset->ds_resume_object[txgoff] = object;
2541 rwa->os->os_dsl_dataset->ds_resume_offset[txgoff] = offset;
2542 rwa->os->os_dsl_dataset->ds_resume_bytes[txgoff] = rwa->bytes_read;
2543}
2544
60948de1 2545noinline static int
fcff0f35 2546receive_object(struct receive_writer_arg *rwa, struct drr_object *drro,
4ea3f864 2547 void *data)
34dc7c2f 2548{
6c59307a 2549 dmu_object_info_t doi;
34dc7c2f 2550 dmu_tx_t *tx;
6c59307a
MA
2551 uint64_t object;
2552 int err;
da2feb42
TC
2553 uint8_t dn_slots = drro->drr_dn_slots != 0 ?
2554 drro->drr_dn_slots : DNODE_MIN_SLOTS;
34dc7c2f 2555
34dc7c2f 2556 if (drro->drr_type == DMU_OT_NONE ||
9ae529ec
CS
2557 !DMU_OT_IS_VALID(drro->drr_type) ||
2558 !DMU_OT_IS_VALID(drro->drr_bonustype) ||
428870ff 2559 drro->drr_checksumtype >= ZIO_CHECKSUM_FUNCTIONS ||
34dc7c2f
BB
2560 drro->drr_compress >= ZIO_COMPRESS_FUNCTIONS ||
2561 P2PHASE(drro->drr_blksz, SPA_MINBLOCKSIZE) ||
2562 drro->drr_blksz < SPA_MINBLOCKSIZE ||
fcff0f35 2563 drro->drr_blksz > spa_maxblocksize(dmu_objset_spa(rwa->os)) ||
50c957f7 2564 drro->drr_bonuslen >
73aac4aa 2565 DN_BONUS_SIZE(spa_maxdnodesize(dmu_objset_spa(rwa->os))) ||
da2feb42 2566 dn_slots >
73aac4aa 2567 (spa_maxdnodesize(dmu_objset_spa(rwa->os)) >> DNODE_SHIFT)) {
2e528b49 2568 return (SET_ERROR(EINVAL));
34dc7c2f
BB
2569 }
2570
9b840763 2571 if (rwa->raw) {
095495e0
TC
2572 /*
2573 * We should have received a DRR_OBJECT_RANGE record
2574 * containing this block and stored it in rwa.
2575 */
2576 if (drro->drr_object < rwa->or_firstobj ||
2577 drro->drr_object >= rwa->or_firstobj + rwa->or_numslots ||
2578 drro->drr_raw_bonuslen < drro->drr_bonuslen ||
b5256303
TC
2579 drro->drr_indblkshift > SPA_MAXBLOCKSHIFT ||
2580 drro->drr_nlevels > DN_MAX_LEVELS ||
2581 drro->drr_nblkptr > DN_MAX_NBLKPTR ||
da2feb42 2582 DN_SLOTS_TO_BONUSLEN(dn_slots) <
b5256303
TC
2583 drro->drr_raw_bonuslen)
2584 return (SET_ERROR(EINVAL));
2585 } else {
2586 if (drro->drr_flags != 0 || drro->drr_raw_bonuslen != 0 ||
2587 drro->drr_indblkshift != 0 || drro->drr_nlevels != 0 ||
2588 drro->drr_nblkptr != 0)
2589 return (SET_ERROR(EINVAL));
2590 }
2591
fcff0f35 2592 err = dmu_object_info(rwa->os, drro->drr_object, &doi);
047116ac 2593 if (err != 0 && err != ENOENT && err != EEXIST)
2e528b49 2594 return (SET_ERROR(EINVAL));
9babb374 2595
48fbb9dd
FG
2596 if (drro->drr_object > rwa->max_object)
2597 rwa->max_object = drro->drr_object;
2598
6c59307a
MA
2599 /*
2600 * If we are losing blkptrs or changing the block size this must
2601 * be a new file instance. We must clear out the previous file
2602 * contents before we can change this type of metadata in the dnode.
b5256303
TC
2603 * Raw receives will also check that the indirect structure of the
2604 * dnode hasn't changed.
6c59307a
MA
2605 */
2606 if (err == 0) {
b5256303
TC
2607 uint32_t indblksz = drro->drr_indblkshift ?
2608 1ULL << drro->drr_indblkshift : 0;
2609 int nblkptr = deduce_nblkptr(drro->drr_bonustype,
6c59307a
MA
2610 drro->drr_bonuslen);
2611
047116ac
TC
2612 object = drro->drr_object;
2613
b5256303 2614 /* nblkptr will be bounded by the bonus size and type */
9b840763 2615 if (rwa->raw && nblkptr != drro->drr_nblkptr)
b5256303
TC
2616 return (SET_ERROR(EINVAL));
2617
0c03d21a 2618 if (drro->drr_blksz != doi.doi_data_block_size ||
b5256303 2619 nblkptr < doi.doi_nblkptr ||
da2feb42 2620 dn_slots != doi.doi_dnodesize >> DNODE_SHIFT ||
0c03d21a
MA
2621 (rwa->raw &&
2622 (indblksz != doi.doi_metadata_block_size ||
2623 drro->drr_nlevels < doi.doi_indirection))) {
2624 err = dmu_free_long_range(rwa->os,
ae76f45c
TC
2625 drro->drr_object, 0, DMU_OBJECT_END);
2626 if (err != 0)
2627 return (SET_ERROR(EINVAL));
34dc7c2f 2628 }
047116ac
TC
2629
2630 /*
2631 * The dmu does not currently support decreasing nlevels
2632 * on an object. For non-raw sends, this does not matter
2633 * and the new object can just use the previous one's nlevels.
2634 * For raw sends, however, the structure of the received dnode
2635 * (including nlevels) must match that of the send side.
2636 * Therefore, instead of using dmu_object_reclaim(), we must
2637 * free the object completely and call dmu_object_claim_dnsize()
2638 * instead.
2639 */
2640 if ((rwa->raw && drro->drr_nlevels < doi.doi_indirection) ||
da2feb42 2641 dn_slots != doi.doi_dnodesize >> DNODE_SHIFT) {
0c03d21a 2642 err = dmu_free_long_object(rwa->os, drro->drr_object);
047116ac
TC
2643 if (err != 0)
2644 return (SET_ERROR(EINVAL));
2645
2646 txg_wait_synced(dmu_objset_pool(rwa->os), 0);
2647 object = DMU_NEW_OBJECT;
2648 }
2649 } else if (err == EEXIST) {
2650 /*
2651 * The object requested is currently an interior slot of a
2652 * multi-slot dnode. This will be resolved when the next txg
2653 * is synced out, since the send stream will have told us
2654 * to free this slot when we freed the associated dnode
2655 * earlier in the stream.
2656 */
2657 txg_wait_synced(dmu_objset_pool(rwa->os), 0);
2658 object = drro->drr_object;
2659 } else {
2660 /* object is free and we are about to allocate a new one */
2661 object = DMU_NEW_OBJECT;
2662 }
2663
2664 /*
2665 * If this is a multi-slot dnode there is a chance that this
2666 * object will expand into a slot that is already used by
2667 * another object from the previous snapshot. We must free
2668 * these objects before we attempt to allocate the new dnode.
2669 */
da2feb42 2670 if (dn_slots > 1) {
5121c4fb
TC
2671 boolean_t need_sync = B_FALSE;
2672
047116ac 2673 for (uint64_t slot = drro->drr_object + 1;
da2feb42 2674 slot < drro->drr_object + dn_slots;
047116ac
TC
2675 slot++) {
2676 dmu_object_info_t slot_doi;
2677
2678 err = dmu_object_info(rwa->os, slot, &slot_doi);
2679 if (err == ENOENT || err == EEXIST)
2680 continue;
2681 else if (err != 0)
2682 return (err);
2683
0c03d21a 2684 err = dmu_free_long_object(rwa->os, slot);
047116ac
TC
2685
2686 if (err != 0)
2687 return (err);
5121c4fb
TC
2688
2689 need_sync = B_TRUE;
047116ac
TC
2690 }
2691
5121c4fb
TC
2692 if (need_sync)
2693 txg_wait_synced(dmu_objset_pool(rwa->os), 0);
6c59307a
MA
2694 }
2695
fcff0f35 2696 tx = dmu_tx_create(rwa->os);
6c59307a 2697 dmu_tx_hold_bonus(tx, object);
b5256303 2698 dmu_tx_hold_write(tx, object, 0, 0);
6c59307a
MA
2699 err = dmu_tx_assign(tx, TXG_WAIT);
2700 if (err != 0) {
2701 dmu_tx_abort(tx);
2702 return (err);
2703 }
2704
2705 if (object == DMU_NEW_OBJECT) {
2706 /* currently free, want to be allocated */
50c957f7 2707 err = dmu_object_claim_dnsize(rwa->os, drro->drr_object,
34dc7c2f 2708 drro->drr_type, drro->drr_blksz,
50c957f7 2709 drro->drr_bonustype, drro->drr_bonuslen,
da2feb42 2710 dn_slots << DNODE_SHIFT, tx);
6c59307a
MA
2711 } else if (drro->drr_type != doi.doi_type ||
2712 drro->drr_blksz != doi.doi_data_block_size ||
2713 drro->drr_bonustype != doi.doi_bonus_type ||
e0dd0a32 2714 drro->drr_bonuslen != doi.doi_bonus_size) {
6c59307a 2715 /* currently allocated, but with different properties */
e14a32b1 2716 err = dmu_object_reclaim_dnsize(rwa->os, drro->drr_object,
34dc7c2f 2717 drro->drr_type, drro->drr_blksz,
e14a32b1 2718 drro->drr_bonustype, drro->drr_bonuslen,
da2feb42 2719 dn_slots << DNODE_SHIFT, tx);
34dc7c2f 2720 }
13fe0198 2721 if (err != 0) {
9b840763 2722 dmu_tx_commit(tx);
2e528b49 2723 return (SET_ERROR(EINVAL));
428870ff 2724 }
9babb374 2725
0c03d21a 2726 if (rwa->or_crypt_params_present) {
095495e0 2727 /*
0c03d21a
MA
2728 * Set the crypt params for the buffer associated with this
2729 * range of dnodes. This causes the blkptr_t to have the
2730 * same crypt params (byteorder, salt, iv, mac) as on the
2731 * sending side.
2732 *
2733 * Since we are committing this tx now, it is possible for
2734 * the dnode block to end up on-disk with the incorrect MAC,
2735 * if subsequent objects in this block are received in a
2736 * different txg. However, since the dataset is marked as
2737 * inconsistent, no code paths will do a non-raw read (or
2738 * decrypt the block / verify the MAC). The receive code and
2739 * scrub code can safely do raw reads and verify the
2740 * checksum. They don't need to verify the MAC.
095495e0 2741 */
0c03d21a
MA
2742 dmu_buf_t *db = NULL;
2743 uint64_t offset = rwa->or_firstobj * DNODE_MIN_SIZE;
2744
2745 err = dmu_buf_hold_by_dnode(DMU_META_DNODE(rwa->os),
2746 offset, FTAG, &db, DMU_READ_PREFETCH | DMU_READ_NO_DECRYPT);
095495e0
TC
2747 if (err != 0) {
2748 dmu_tx_commit(tx);
2749 return (SET_ERROR(EINVAL));
2750 }
0c03d21a
MA
2751
2752 dmu_buf_set_crypt_params(db, rwa->or_byteorder,
2753 rwa->or_salt, rwa->or_iv, rwa->or_mac, tx);
2754
2755 dmu_buf_rele(db, FTAG);
2756
2757 rwa->or_crypt_params_present = B_FALSE;
095495e0 2758 }
9b840763 2759
fcff0f35 2760 dmu_object_set_checksum(rwa->os, drro->drr_object,
37f8a883 2761 drro->drr_checksumtype, tx);
fcff0f35 2762 dmu_object_set_compress(rwa->os, drro->drr_object,
37f8a883 2763 drro->drr_compress, tx);
34dc7c2f 2764
b5256303 2765 /* handle more restrictive dnode structuring for raw recvs */
9b840763 2766 if (rwa->raw) {
b5256303
TC
2767 /*
2768 * Set the indirect block shift and nlevels. This will not fail
2769 * because we ensured all of the blocks were free earlier if
2770 * this is a new object.
2771 */
2772 VERIFY0(dmu_object_set_blocksize(rwa->os, drro->drr_object,
2773 drro->drr_blksz, drro->drr_indblkshift, tx));
2774 VERIFY0(dmu_object_set_nlevels(rwa->os, drro->drr_object,
2775 drro->drr_nlevels, tx));
ae76f45c
TC
2776 VERIFY0(dmu_object_set_maxblkid(rwa->os, drro->drr_object,
2777 drro->drr_maxblkid, tx));
b5256303
TC
2778 }
2779
b128c09f 2780 if (data != NULL) {
34dc7c2f 2781 dmu_buf_t *db;
b5256303 2782 uint32_t flags = DMU_READ_NO_PREFETCH;
b128c09f 2783
9b840763 2784 if (rwa->raw)
b5256303
TC
2785 flags |= DMU_READ_NO_DECRYPT;
2786
2787 VERIFY0(dmu_bonus_hold_impl(rwa->os, drro->drr_object,
2788 FTAG, flags, &db));
34dc7c2f
BB
2789 dmu_buf_will_dirty(db, tx);
2790
2791 ASSERT3U(db->db_size, >=, drro->drr_bonuslen);
b5256303
TC
2792 bcopy(data, db->db_data, DRR_OBJECT_PAYLOAD_SIZE(drro));
2793
2794 /*
2795 * Raw bonus buffers have their byteorder determined by the
2796 * DRR_OBJECT_RANGE record.
2797 */
9b840763 2798 if (rwa->byteswap && !rwa->raw) {
9ae529ec
CS
2799 dmu_object_byteswap_t byteswap =
2800 DMU_OT_BYTESWAP(drro->drr_bonustype);
2801 dmu_ot_byteswap[byteswap].ob_func(db->db_data,
b5256303 2802 DRR_OBJECT_PAYLOAD_SIZE(drro));
34dc7c2f
BB
2803 }
2804 dmu_buf_rele(db, FTAG);
2805 }
2806 dmu_tx_commit(tx);
47dfff3b 2807
34dc7c2f
BB
2808 return (0);
2809}
2810
2811/* ARGSUSED */
60948de1 2812noinline static int
fcff0f35 2813receive_freeobjects(struct receive_writer_arg *rwa,
34dc7c2f
BB
2814 struct drr_freeobjects *drrfo)
2815{
2816 uint64_t obj;
e6d3a843 2817 int next_err = 0;
34dc7c2f
BB
2818
2819 if (drrfo->drr_firstobj + drrfo->drr_numobjs < drrfo->drr_firstobj)
2e528b49 2820 return (SET_ERROR(EINVAL));
34dc7c2f 2821
50c957f7 2822 for (obj = drrfo->drr_firstobj == 0 ? 1 : drrfo->drr_firstobj;
e6d3a843
PD
2823 obj < drrfo->drr_firstobj + drrfo->drr_numobjs && next_err == 0;
2824 next_err = dmu_object_next(rwa->os, &obj, FALSE, 0)) {
50c957f7 2825 dmu_object_info_t doi;
34dc7c2f
BB
2826 int err;
2827
50c957f7 2828 err = dmu_object_info(rwa->os, obj, &doi);
39f56627 2829 if (err == ENOENT)
34dc7c2f 2830 continue;
39f56627 2831 else if (err != 0)
50c957f7 2832 return (err);
34dc7c2f 2833
0c03d21a 2834 err = dmu_free_long_object(rwa->os, obj);
440a3eb9 2835
13fe0198 2836 if (err != 0)
34dc7c2f 2837 return (err);
48fbb9dd
FG
2838
2839 if (obj > rwa->max_object)
2840 rwa->max_object = obj;
34dc7c2f 2841 }
e6d3a843
PD
2842 if (next_err != ESRCH)
2843 return (next_err);
34dc7c2f
BB
2844 return (0);
2845}
2846
60948de1 2847noinline static int
fcff0f35 2848receive_write(struct receive_writer_arg *rwa, struct drr_write *drrw,
4ea3f864 2849 arc_buf_t *abuf)
34dc7c2f 2850{
34dc7c2f 2851 int err;
440a3eb9
TC
2852 dmu_tx_t *tx;
2853 dnode_t *dn;
34dc7c2f 2854
2aa34383 2855 if (drrw->drr_offset + drrw->drr_logical_size < drrw->drr_offset ||
9ae529ec 2856 !DMU_OT_IS_VALID(drrw->drr_type))
2e528b49 2857 return (SET_ERROR(EINVAL));
34dc7c2f 2858
47dfff3b
MA
2859 /*
2860 * For resuming to work, records must be in increasing order
2861 * by (object, offset).
2862 */
2863 if (drrw->drr_object < rwa->last_object ||
2864 (drrw->drr_object == rwa->last_object &&
2865 drrw->drr_offset < rwa->last_offset)) {
2866 return (SET_ERROR(EINVAL));
2867 }
2868 rwa->last_object = drrw->drr_object;
2869 rwa->last_offset = drrw->drr_offset;
2870
48fbb9dd
FG
2871 if (rwa->last_object > rwa->max_object)
2872 rwa->max_object = rwa->last_object;
2873
fcff0f35 2874 if (dmu_object_info(rwa->os, drrw->drr_object, NULL) != 0)
88904bb3
MA
2875 return (SET_ERROR(EINVAL));
2876
fcff0f35 2877 tx = dmu_tx_create(rwa->os);
34dc7c2f 2878 dmu_tx_hold_write(tx, drrw->drr_object,
2aa34383 2879 drrw->drr_offset, drrw->drr_logical_size);
34dc7c2f 2880 err = dmu_tx_assign(tx, TXG_WAIT);
13fe0198 2881 if (err != 0) {
34dc7c2f
BB
2882 dmu_tx_abort(tx);
2883 return (err);
2884 }
9b840763 2885
b5256303
TC
2886 if (rwa->byteswap && !arc_is_encrypted(abuf) &&
2887 arc_get_compression(abuf) == ZIO_COMPRESS_OFF) {
9ae529ec
CS
2888 dmu_object_byteswap_t byteswap =
2889 DMU_OT_BYTESWAP(drrw->drr_type);
37f8a883 2890 dmu_ot_byteswap[byteswap].ob_func(abuf->b_data,
2aa34383 2891 DRR_WRITE_PAYLOAD_SIZE(drrw));
9ae529ec 2892 }
37f8a883 2893
440a3eb9
TC
2894 VERIFY0(dnode_hold(rwa->os, drrw->drr_object, FTAG, &dn));
2895 dmu_assign_arcbuf_by_dnode(dn, drrw->drr_offset, abuf, tx);
2896 dnode_rele(dn, FTAG);
47dfff3b
MA
2897
2898 /*
2899 * Note: If the receive fails, we want the resume stream to start
2900 * with the same record that we last successfully received (as opposed
2901 * to the next record), so that we can verify that we are
2902 * resuming from the correct location.
2903 */
2904 save_resume_state(rwa, drrw->drr_object, drrw->drr_offset, tx);
34dc7c2f 2905 dmu_tx_commit(tx);
47dfff3b 2906
34dc7c2f
BB
2907 return (0);
2908}
2909
428870ff
BB
2910/*
2911 * Handle a DRR_WRITE_BYREF record. This record is used in dedup'ed
2912 * streams to refer to a copy of the data that is already on the
2913 * system because it came in earlier in the stream. This function
2914 * finds the earlier copy of the data, and uses that copy instead of
2915 * data from the stream to fulfill this write.
2916 */
2917static int
fcff0f35
PD
2918receive_write_byref(struct receive_writer_arg *rwa,
2919 struct drr_write_byref *drrwbr)
428870ff
BB
2920{
2921 dmu_tx_t *tx;
2922 int err;
2923 guid_map_entry_t gmesrch;
2924 guid_map_entry_t *gmep;
9b67f605 2925 avl_index_t where;
428870ff 2926 objset_t *ref_os = NULL;
b5256303 2927 int flags = DMU_READ_PREFETCH;
428870ff
BB
2928 dmu_buf_t *dbp;
2929
2930 if (drrwbr->drr_offset + drrwbr->drr_length < drrwbr->drr_offset)
2e528b49 2931 return (SET_ERROR(EINVAL));
428870ff
BB
2932
2933 /*
2934 * If the GUID of the referenced dataset is different from the
2935 * GUID of the target dataset, find the referenced dataset.
2936 */
2937 if (drrwbr->drr_toguid != drrwbr->drr_refguid) {
2938 gmesrch.guid = drrwbr->drr_refguid;
fcff0f35 2939 if ((gmep = avl_find(rwa->guid_to_ds_map, &gmesrch,
428870ff 2940 &where)) == NULL) {
2e528b49 2941 return (SET_ERROR(EINVAL));
428870ff
BB
2942 }
2943 if (dmu_objset_from_ds(gmep->gme_ds, &ref_os))
2e528b49 2944 return (SET_ERROR(EINVAL));
428870ff 2945 } else {
fcff0f35 2946 ref_os = rwa->os;
428870ff
BB
2947 }
2948
48fbb9dd
FG
2949 if (drrwbr->drr_object > rwa->max_object)
2950 rwa->max_object = drrwbr->drr_object;
2951
9b840763 2952 if (rwa->raw)
b5256303 2953 flags |= DMU_READ_NO_DECRYPT;
b5256303
TC
2954
2955 /* may return either a regular db or an encrypted one */
c65aa5b2 2956 err = dmu_buf_hold(ref_os, drrwbr->drr_refobject,
b5256303 2957 drrwbr->drr_refoffset, FTAG, &dbp, flags);
9b67f605 2958 if (err != 0)
428870ff
BB
2959 return (err);
2960
fcff0f35 2961 tx = dmu_tx_create(rwa->os);
428870ff
BB
2962
2963 dmu_tx_hold_write(tx, drrwbr->drr_object,
2964 drrwbr->drr_offset, drrwbr->drr_length);
2965 err = dmu_tx_assign(tx, TXG_WAIT);
13fe0198 2966 if (err != 0) {
428870ff
BB
2967 dmu_tx_abort(tx);
2968 return (err);
2969 }
b5256303 2970
9b840763 2971 if (rwa->raw) {
b5256303
TC
2972 dmu_copy_from_buf(rwa->os, drrwbr->drr_object,
2973 drrwbr->drr_offset, dbp, tx);
2974 } else {
2975 dmu_write(rwa->os, drrwbr->drr_object,
2976 drrwbr->drr_offset, drrwbr->drr_length, dbp->db_data, tx);
2977 }
428870ff 2978 dmu_buf_rele(dbp, FTAG);
47dfff3b
MA
2979
2980 /* See comment in restore_write. */
2981 save_resume_state(rwa, drrwbr->drr_object, drrwbr->drr_offset, tx);
428870ff
BB
2982 dmu_tx_commit(tx);
2983 return (0);
2984}
2985
9b67f605 2986static int
fcff0f35 2987receive_write_embedded(struct receive_writer_arg *rwa,
47dfff3b 2988 struct drr_write_embedded *drrwe, void *data)
9b67f605
MA
2989{
2990 dmu_tx_t *tx;
2991 int err;
9b67f605 2992
47dfff3b 2993 if (drrwe->drr_offset + drrwe->drr_length < drrwe->drr_offset)
ecb2b7dc 2994 return (SET_ERROR(EINVAL));
9b67f605 2995
47dfff3b 2996 if (drrwe->drr_psize > BPE_PAYLOAD_SIZE)
ecb2b7dc 2997 return (SET_ERROR(EINVAL));
9b67f605 2998
47dfff3b 2999 if (drrwe->drr_etype >= NUM_BP_EMBEDDED_TYPES)
ecb2b7dc 3000 return (SET_ERROR(EINVAL));
47dfff3b 3001 if (drrwe->drr_compression >= ZIO_COMPRESS_FUNCTIONS)
ecb2b7dc 3002 return (SET_ERROR(EINVAL));
440a3eb9
TC
3003 if (rwa->raw)
3004 return (SET_ERROR(EINVAL));
9b67f605 3005
48fbb9dd
FG
3006 if (drrwe->drr_object > rwa->max_object)
3007 rwa->max_object = drrwe->drr_object;
3008
fcff0f35 3009 tx = dmu_tx_create(rwa->os);
9b67f605 3010
47dfff3b
MA
3011 dmu_tx_hold_write(tx, drrwe->drr_object,
3012 drrwe->drr_offset, drrwe->drr_length);
9b67f605
MA
3013 err = dmu_tx_assign(tx, TXG_WAIT);
3014 if (err != 0) {
3015 dmu_tx_abort(tx);
3016 return (err);
3017 }
3018
47dfff3b
MA
3019 dmu_write_embedded(rwa->os, drrwe->drr_object,
3020 drrwe->drr_offset, data, drrwe->drr_etype,
3021 drrwe->drr_compression, drrwe->drr_lsize, drrwe->drr_psize,
fcff0f35 3022 rwa->byteswap ^ ZFS_HOST_BYTEORDER, tx);
9b67f605 3023
47dfff3b
MA
3024 /* See comment in restore_write. */
3025 save_resume_state(rwa, drrwe->drr_object, drrwe->drr_offset, tx);
9b67f605
MA
3026 dmu_tx_commit(tx);
3027 return (0);
3028}
3029
428870ff 3030static int
fcff0f35 3031receive_spill(struct receive_writer_arg *rwa, struct drr_spill *drrs,
b5256303 3032 arc_buf_t *abuf)
428870ff
BB
3033{
3034 dmu_tx_t *tx;
428870ff
BB
3035 dmu_buf_t *db, *db_spill;
3036 int err;
e7504d7a 3037 uint32_t flags = 0;
428870ff
BB
3038
3039 if (drrs->drr_length < SPA_MINBLOCKSIZE ||
fcff0f35 3040 drrs->drr_length > spa_maxblocksize(dmu_objset_spa(rwa->os)))
2e528b49 3041 return (SET_ERROR(EINVAL));
428870ff 3042
9b840763 3043 if (rwa->raw) {
b5256303
TC
3044 if (!DMU_OT_IS_VALID(drrs->drr_type) ||
3045 drrs->drr_compressiontype >= ZIO_COMPRESS_FUNCTIONS ||
3046 drrs->drr_compressed_size == 0)
3047 return (SET_ERROR(EINVAL));
e7504d7a
TC
3048
3049 flags |= DMU_READ_NO_DECRYPT;
b5256303
TC
3050 }
3051
fcff0f35 3052 if (dmu_object_info(rwa->os, drrs->drr_object, NULL) != 0)
2e528b49 3053 return (SET_ERROR(EINVAL));
428870ff 3054
48fbb9dd
FG
3055 if (drrs->drr_object > rwa->max_object)
3056 rwa->max_object = drrs->drr_object;
3057
fcff0f35 3058 VERIFY0(dmu_bonus_hold(rwa->os, drrs->drr_object, FTAG, &db));
e7504d7a
TC
3059 if ((err = dmu_spill_hold_by_bonus(db, DMU_READ_NO_DECRYPT, FTAG,
3060 &db_spill)) != 0) {
428870ff
BB
3061 dmu_buf_rele(db, FTAG);
3062 return (err);
3063 }
3064
fcff0f35 3065 tx = dmu_tx_create(rwa->os);
428870ff
BB
3066
3067 dmu_tx_hold_spill(tx, db->db_object);
3068
3069 err = dmu_tx_assign(tx, TXG_WAIT);
13fe0198 3070 if (err != 0) {
428870ff
BB
3071 dmu_buf_rele(db, FTAG);
3072 dmu_buf_rele(db_spill, FTAG);
3073 dmu_tx_abort(tx);
3074 return (err);
3075 }
428870ff
BB
3076
3077 if (db_spill->db_size < drrs->drr_length)
3078 VERIFY(0 == dbuf_spill_set_blksz(db_spill,
3079 drrs->drr_length, tx));
1a234278
PZ
3080
3081 if (rwa->byteswap && !arc_is_encrypted(abuf) &&
3082 arc_get_compression(abuf) == ZIO_COMPRESS_OFF) {
3083 dmu_object_byteswap_t byteswap =
3084 DMU_OT_BYTESWAP(drrs->drr_type);
3085 dmu_ot_byteswap[byteswap].ob_func(abuf->b_data,
3086 DRR_SPILL_PAYLOAD_SIZE(drrs));
3087 }
3088
440a3eb9 3089 dbuf_assign_arcbuf((dmu_buf_impl_t *)db_spill, abuf, tx);
428870ff
BB
3090
3091 dmu_buf_rele(db, FTAG);
3092 dmu_buf_rele(db_spill, FTAG);
3093
3094 dmu_tx_commit(tx);
3095 return (0);
3096}
3097
34dc7c2f 3098/* ARGSUSED */
60948de1 3099noinline static int
fcff0f35 3100receive_free(struct receive_writer_arg *rwa, struct drr_free *drrf)
34dc7c2f 3101{
34dc7c2f
BB
3102 int err;
3103
ee45fbd8 3104 if (drrf->drr_length != DMU_OBJECT_END &&
34dc7c2f 3105 drrf->drr_offset + drrf->drr_length < drrf->drr_offset)
2e528b49 3106 return (SET_ERROR(EINVAL));
34dc7c2f 3107
fcff0f35 3108 if (dmu_object_info(rwa->os, drrf->drr_object, NULL) != 0)
2e528b49 3109 return (SET_ERROR(EINVAL));
34dc7c2f 3110
48fbb9dd
FG
3111 if (drrf->drr_object > rwa->max_object)
3112 rwa->max_object = drrf->drr_object;
3113
0c03d21a
MA
3114 err = dmu_free_long_range(rwa->os, drrf->drr_object,
3115 drrf->drr_offset, drrf->drr_length);
fcff0f35 3116
34dc7c2f
BB
3117 return (err);
3118}
3119
b5256303
TC
3120static int
3121receive_object_range(struct receive_writer_arg *rwa,
3122 struct drr_object_range *drror)
3123{
b5256303
TC
3124 /*
3125 * By default, we assume this block is in our native format
3126 * (ZFS_HOST_BYTEORDER). We then take into account whether
3127 * the send stream is byteswapped (rwa->byteswap). Finally,
3128 * we need to byteswap again if this particular block was
3129 * in non-native format on the send side.
3130 */
3131 boolean_t byteorder = ZFS_HOST_BYTEORDER ^ rwa->byteswap ^
3132 !!DRR_IS_RAW_BYTESWAPPED(drror->drr_flags);
3133
3134 /*
3135 * Since dnode block sizes are constant, we should not need to worry
3136 * about making sure that the dnode block size is the same on the
3137 * sending and receiving sides for the time being. For non-raw sends,
3138 * this does not matter (and in fact we do not send a DRR_OBJECT_RANGE
3139 * record at all). Raw sends require this record type because the
3140 * encryption parameters are used to protect an entire block of bonus
3141 * buffers. If the size of dnode blocks ever becomes variable,
3142 * handling will need to be added to ensure that dnode block sizes
3143 * match on the sending and receiving side.
3144 */
3145 if (drror->drr_numslots != DNODES_PER_BLOCK ||
3146 P2PHASE(drror->drr_firstobj, DNODES_PER_BLOCK) != 0 ||
9b840763 3147 !rwa->raw)
b5256303
TC
3148 return (SET_ERROR(EINVAL));
3149
48fbb9dd
FG
3150 if (drror->drr_firstobj > rwa->max_object)
3151 rwa->max_object = drror->drr_firstobj;
3152
b5256303 3153 /*
095495e0 3154 * The DRR_OBJECT_RANGE handling must be deferred to receive_object()
0c03d21a
MA
3155 * so that the block of dnodes is not written out when it's empty,
3156 * and converted to a HOLE BP.
b5256303 3157 */
0c03d21a 3158 rwa->or_crypt_params_present = B_TRUE;
095495e0
TC
3159 rwa->or_firstobj = drror->drr_firstobj;
3160 rwa->or_numslots = drror->drr_numslots;
3161 bcopy(drror->drr_salt, rwa->or_salt, ZIO_DATA_SALT_LEN);
3162 bcopy(drror->drr_iv, rwa->or_iv, ZIO_DATA_IV_LEN);
3163 bcopy(drror->drr_mac, rwa->or_mac, ZIO_DATA_MAC_LEN);
3164 rwa->or_byteorder = byteorder;
3165
b5256303
TC
3166 return (0);
3167}
3168
13fe0198
MA
3169/* used to destroy the drc_ds on error */
3170static void
3171dmu_recv_cleanup_ds(dmu_recv_cookie_t *drc)
3172{
2637dda8 3173 dsl_dataset_t *ds = drc->drc_ds;
b5256303
TC
3174 ds_hold_flags_t dsflags = (drc->drc_raw) ? 0 : DS_HOLD_FLAG_DECRYPT;
3175
3176 /*
3177 * Wait for the txg sync before cleaning up the receive. For
3178 * resumable receives, this ensures that our resume state has
3179 * been written out to disk. For raw receives, this ensures
3180 * that the user accounting code will not attempt to do anything
3181 * after we stopped receiving the dataset.
3182 */
2637dda8 3183 txg_wait_synced(ds->ds_dir->dd_pool, 0);
0c03d21a 3184 ds->ds_objset->os_raw_receive = B_FALSE;
b5256303 3185
2637dda8
TC
3186 rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);
3187 if (drc->drc_resumable && !BP_IS_HOLE(dsl_dataset_get_blkptr(ds))) {
3188 rrw_exit(&ds->ds_bp_rwlock, FTAG);
3189 dsl_dataset_disown(ds, dsflags, dmu_recv_tag);
47dfff3b 3190 } else {
eca7b760 3191 char name[ZFS_MAX_DATASET_NAME_LEN];
2637dda8
TC
3192 rrw_exit(&ds->ds_bp_rwlock, FTAG);
3193 dsl_dataset_name(ds, name);
3194 dsl_dataset_disown(ds, dsflags, dmu_recv_tag);
47dfff3b
MA
3195 (void) dsl_destroy_head(name);
3196 }
13fe0198
MA
3197}
3198
37f8a883 3199static void
fcff0f35 3200receive_cksum(struct receive_arg *ra, int len, void *buf)
37f8a883
MA
3201{
3202 if (ra->byteswap) {
a6255b7f 3203 (void) fletcher_4_incremental_byteswap(buf, len, &ra->cksum);
37f8a883 3204 } else {
a6255b7f 3205 (void) fletcher_4_incremental_native(buf, len, &ra->cksum);
37f8a883
MA
3206 }
3207}
3208
3209/*
fcff0f35
PD
3210 * Read the payload into a buffer of size len, and update the current record's
3211 * payload field.
3212 * Allocate ra->next_rrd and read the next record's header into
3213 * ra->next_rrd->header.
37f8a883
MA
3214 * Verify checksum of payload and next record.
3215 */
3216static int
fcff0f35 3217receive_read_payload_and_next_header(struct receive_arg *ra, int len, void *buf)
37f8a883
MA
3218{
3219 int err;
3220 zio_cksum_t cksum_orig;
3221 zio_cksum_t *cksump;
3222
3223 if (len != 0) {
fcff0f35 3224 ASSERT3U(len, <=, SPA_MAXBLOCKSIZE);
47dfff3b 3225 err = receive_read(ra, len, buf);
37f8a883
MA
3226 if (err != 0)
3227 return (err);
47dfff3b
MA
3228 receive_cksum(ra, len, buf);
3229
3230 /* note: rrd is NULL when reading the begin record's payload */
3231 if (ra->rrd != NULL) {
3232 ra->rrd->payload = buf;
3233 ra->rrd->payload_size = len;
3234 ra->rrd->bytes_read = ra->bytes_read;
3235 }
37f8a883
MA
3236 }
3237
3238 ra->prev_cksum = ra->cksum;
3239
fcff0f35
PD
3240 ra->next_rrd = kmem_zalloc(sizeof (*ra->next_rrd), KM_SLEEP);
3241 err = receive_read(ra, sizeof (ra->next_rrd->header),
3242 &ra->next_rrd->header);
47dfff3b 3243 ra->next_rrd->bytes_read = ra->bytes_read;
b5256303 3244
fcff0f35
PD
3245 if (err != 0) {
3246 kmem_free(ra->next_rrd, sizeof (*ra->next_rrd));
3247 ra->next_rrd = NULL;
37f8a883 3248 return (err);
fcff0f35
PD
3249 }
3250 if (ra->next_rrd->header.drr_type == DRR_BEGIN) {
3251 kmem_free(ra->next_rrd, sizeof (*ra->next_rrd));
3252 ra->next_rrd = NULL;
37f8a883 3253 return (SET_ERROR(EINVAL));
fcff0f35 3254 }
37f8a883
MA
3255
3256 /*
3257 * Note: checksum is of everything up to but not including the
3258 * checksum itself.
3259 */
3260 ASSERT3U(offsetof(dmu_replay_record_t, drr_u.drr_checksum.drr_checksum),
3261 ==, sizeof (dmu_replay_record_t) - sizeof (zio_cksum_t));
fcff0f35 3262 receive_cksum(ra,
37f8a883 3263 offsetof(dmu_replay_record_t, drr_u.drr_checksum.drr_checksum),
fcff0f35 3264 &ra->next_rrd->header);
37f8a883 3265
fcff0f35
PD
3266 cksum_orig = ra->next_rrd->header.drr_u.drr_checksum.drr_checksum;
3267 cksump = &ra->next_rrd->header.drr_u.drr_checksum.drr_checksum;
37f8a883
MA
3268
3269 if (ra->byteswap)
fcff0f35 3270 byteswap_record(&ra->next_rrd->header);
37f8a883
MA
3271
3272 if ((!ZIO_CHECKSUM_IS_ZERO(cksump)) &&
fcff0f35
PD
3273 !ZIO_CHECKSUM_EQUAL(ra->cksum, *cksump)) {
3274 kmem_free(ra->next_rrd, sizeof (*ra->next_rrd));
3275 ra->next_rrd = NULL;
37f8a883 3276 return (SET_ERROR(ECKSUM));
fcff0f35 3277 }
37f8a883 3278
fcff0f35 3279 receive_cksum(ra, sizeof (cksum_orig), &cksum_orig);
37f8a883
MA
3280
3281 return (0);
3282}
3283
e6d3a843
PD
3284static void
3285objlist_create(struct objlist *list)
3286{
3287 list_create(&list->list, sizeof (struct receive_objnode),
3288 offsetof(struct receive_objnode, node));
3289 list->last_lookup = 0;
3290}
3291
3292static void
3293objlist_destroy(struct objlist *list)
3294{
1c27024e 3295 for (struct receive_objnode *n = list_remove_head(&list->list);
e6d3a843
PD
3296 n != NULL; n = list_remove_head(&list->list)) {
3297 kmem_free(n, sizeof (*n));
3298 }
3299 list_destroy(&list->list);
3300}
3301
3302/*
3303 * This function looks through the objlist to see if the specified object number
3304 * is contained in the objlist. In the process, it will remove all object
3305 * numbers in the list that are smaller than the specified object number. Thus,
3306 * any lookup of an object number smaller than a previously looked up object
3307 * number will always return false; therefore, all lookups should be done in
3308 * ascending order.
3309 */
3310static boolean_t
3311objlist_exists(struct objlist *list, uint64_t object)
3312{
3313 struct receive_objnode *node = list_head(&list->list);
3314 ASSERT3U(object, >=, list->last_lookup);
3315 list->last_lookup = object;
3316 while (node != NULL && node->object < object) {
3317 VERIFY3P(node, ==, list_remove_head(&list->list));
3318 kmem_free(node, sizeof (*node));
3319 node = list_head(&list->list);
3320 }
3321 return (node != NULL && node->object == object);
3322}
3323
3324/*
3325 * The objlist is a list of object numbers stored in ascending order. However,
3326 * the insertion of new object numbers does not seek out the correct location to
3327 * store a new object number; instead, it appends it to the list for simplicity.
3328 * Thus, any users must take care to only insert new object numbers in ascending
3329 * order.
3330 */
3331static void
3332objlist_insert(struct objlist *list, uint64_t object)
3333{
3334 struct receive_objnode *node = kmem_zalloc(sizeof (*node), KM_SLEEP);
3335 node->object = object;
3336#ifdef ZFS_DEBUG
3337 {
3338 struct receive_objnode *last_object = list_tail(&list->list);
3339 uint64_t last_objnum = (last_object != NULL ? last_object->object : 0);
3340 ASSERT3U(node->object, >, last_objnum);
3341 }
3342#endif
3343 list_insert_tail(&list->list, node);
3344}
3345
fcff0f35
PD
3346/*
3347 * Issue the prefetch reads for any necessary indirect blocks.
3348 *
3349 * We use the object ignore list to tell us whether or not to issue prefetches
3350 * for a given object. We do this for both correctness (in case the blocksize
3351 * of an object has changed) and performance (if the object doesn't exist, don't
3352 * needlessly try to issue prefetches). We also trim the list as we go through
3353 * the stream to prevent it from growing to an unbounded size.
3354 *
3355 * The object numbers within will always be in sorted order, and any write
3356 * records we see will also be in sorted order, but they're not sorted with
3357 * respect to each other (i.e. we can get several object records before
3358 * receiving each object's write records). As a result, once we've reached a
3359 * given object number, we can safely remove any reference to lower object
3360 * numbers in the ignore list. In practice, we receive up to 32 object records
3361 * before receiving write records, so the list can have up to 32 nodes in it.
3362 */
3363/* ARGSUSED */
3364static void
3365receive_read_prefetch(struct receive_arg *ra,
3366 uint64_t object, uint64_t offset, uint64_t length)
3367{
e6d3a843 3368 if (!objlist_exists(&ra->ignore_objlist, object)) {
fcff0f35
PD
3369 dmu_prefetch(ra->os, object, 1, offset, length,
3370 ZIO_PRIORITY_SYNC_READ);
3371 }
3372}
3373
3374/*
3375 * Read records off the stream, issuing any necessary prefetches.
3376 */
37f8a883 3377static int
fcff0f35 3378receive_read_record(struct receive_arg *ra)
37f8a883
MA
3379{
3380 int err;
3381
fcff0f35 3382 switch (ra->rrd->header.drr_type) {
37f8a883
MA
3383 case DRR_OBJECT:
3384 {
fcff0f35 3385 struct drr_object *drro = &ra->rrd->header.drr_u.drr_object;
b5256303 3386 uint32_t size = DRR_OBJECT_PAYLOAD_SIZE(drro);
fcff0f35
PD
3387 void *buf = kmem_zalloc(size, KM_SLEEP);
3388 dmu_object_info_t doi;
b5256303 3389
fcff0f35
PD
3390 err = receive_read_payload_and_next_header(ra, size, buf);
3391 if (err != 0) {
3392 kmem_free(buf, size);
37f8a883 3393 return (err);
fcff0f35
PD
3394 }
3395 err = dmu_object_info(ra->os, drro->drr_object, &doi);
3396 /*
3397 * See receive_read_prefetch for an explanation why we're
3398 * storing this object in the ignore_obj_list.
3399 */
047116ac 3400 if (err == ENOENT || err == EEXIST ||
fcff0f35 3401 (err == 0 && doi.doi_data_block_size != drro->drr_blksz)) {
e6d3a843 3402 objlist_insert(&ra->ignore_objlist, drro->drr_object);
fcff0f35
PD
3403 err = 0;
3404 }
3405 return (err);
37f8a883
MA
3406 }
3407 case DRR_FREEOBJECTS:
3408 {
fcff0f35
PD
3409 err = receive_read_payload_and_next_header(ra, 0, NULL);
3410 return (err);
37f8a883
MA
3411 }
3412 case DRR_WRITE:
3413 {
fcff0f35 3414 struct drr_write *drrw = &ra->rrd->header.drr_u.drr_write;
2aa34383
DK
3415 arc_buf_t *abuf;
3416 boolean_t is_meta = DMU_OT_IS_METADATA(drrw->drr_type);
b5256303 3417
9b840763 3418 if (ra->raw) {
b5256303
TC
3419 boolean_t byteorder = ZFS_HOST_BYTEORDER ^
3420 !!DRR_IS_RAW_BYTESWAPPED(drrw->drr_flags) ^
3421 ra->byteswap;
3422
3423 abuf = arc_loan_raw_buf(dmu_objset_spa(ra->os),
3424 drrw->drr_object, byteorder, drrw->drr_salt,
3425 drrw->drr_iv, drrw->drr_mac, drrw->drr_type,
3426 drrw->drr_compressed_size, drrw->drr_logical_size,
3427 drrw->drr_compressiontype);
3428 } else if (DRR_WRITE_COMPRESSED(drrw)) {
2aa34383
DK
3429 ASSERT3U(drrw->drr_compressed_size, >, 0);
3430 ASSERT3U(drrw->drr_logical_size, >=,
3431 drrw->drr_compressed_size);
3432 ASSERT(!is_meta);
3433 abuf = arc_loan_compressed_buf(
3434 dmu_objset_spa(ra->os),
3435 drrw->drr_compressed_size, drrw->drr_logical_size,
3436 drrw->drr_compressiontype);
3437 } else {
3438 abuf = arc_loan_buf(dmu_objset_spa(ra->os),
3439 is_meta, drrw->drr_logical_size);
3440 }
37f8a883 3441
fcff0f35 3442 err = receive_read_payload_and_next_header(ra,
2aa34383 3443 DRR_WRITE_PAYLOAD_SIZE(drrw), abuf->b_data);
fcff0f35 3444 if (err != 0) {
37f8a883 3445 dmu_return_arcbuf(abuf);
fcff0f35
PD
3446 return (err);
3447 }
b5256303 3448 ra->rrd->arc_buf = abuf;
fcff0f35 3449 receive_read_prefetch(ra, drrw->drr_object, drrw->drr_offset,
2aa34383 3450 drrw->drr_logical_size);
37f8a883
MA
3451 return (err);
3452 }
3453 case DRR_WRITE_BYREF:
3454 {
fcff0f35
PD
3455 struct drr_write_byref *drrwb =
3456 &ra->rrd->header.drr_u.drr_write_byref;
3457 err = receive_read_payload_and_next_header(ra, 0, NULL);
3458 receive_read_prefetch(ra, drrwb->drr_object, drrwb->drr_offset,
3459 drrwb->drr_length);
3460 return (err);
37f8a883
MA
3461 }
3462 case DRR_WRITE_EMBEDDED:
3463 {
3464 struct drr_write_embedded *drrwe =
fcff0f35
PD
3465 &ra->rrd->header.drr_u.drr_write_embedded;
3466 uint32_t size = P2ROUNDUP(drrwe->drr_psize, 8);
3467 void *buf = kmem_zalloc(size, KM_SLEEP);
3468
3469 err = receive_read_payload_and_next_header(ra, size, buf);
3470 if (err != 0) {
3471 kmem_free(buf, size);
37f8a883 3472 return (err);
fcff0f35
PD
3473 }
3474
3475 receive_read_prefetch(ra, drrwe->drr_object, drrwe->drr_offset,
3476 drrwe->drr_length);
3477 return (err);
37f8a883
MA
3478 }
3479 case DRR_FREE:
3480 {
fcff0f35
PD
3481 /*
3482 * It might be beneficial to prefetch indirect blocks here, but
3483 * we don't really have the data to decide for sure.
3484 */
3485 err = receive_read_payload_and_next_header(ra, 0, NULL);
3486 return (err);
37f8a883
MA
3487 }
3488 case DRR_END:
3489 {
fcff0f35 3490 struct drr_end *drre = &ra->rrd->header.drr_u.drr_end;
37f8a883 3491 if (!ZIO_CHECKSUM_EQUAL(ra->prev_cksum, drre->drr_checksum))
47dfff3b 3492 return (SET_ERROR(ECKSUM));
37f8a883
MA
3493 return (0);
3494 }
3495 case DRR_SPILL:
3496 {
fcff0f35 3497 struct drr_spill *drrs = &ra->rrd->header.drr_u.drr_spill;
b5256303
TC
3498 arc_buf_t *abuf;
3499 int len = DRR_SPILL_PAYLOAD_SIZE(drrs);
3500
3501 /* DRR_SPILL records are either raw or uncompressed */
9b840763 3502 if (ra->raw) {
b5256303
TC
3503 boolean_t byteorder = ZFS_HOST_BYTEORDER ^
3504 !!DRR_IS_RAW_BYTESWAPPED(drrs->drr_flags) ^
3505 ra->byteswap;
3506
3507 abuf = arc_loan_raw_buf(dmu_objset_spa(ra->os),
b0ee5946 3508 dmu_objset_id(ra->os), byteorder, drrs->drr_salt,
b5256303
TC
3509 drrs->drr_iv, drrs->drr_mac, drrs->drr_type,
3510 drrs->drr_compressed_size, drrs->drr_length,
3511 drrs->drr_compressiontype);
3512 } else {
3513 abuf = arc_loan_buf(dmu_objset_spa(ra->os),
3514 DMU_OT_IS_METADATA(drrs->drr_type),
3515 drrs->drr_length);
3516 }
3517
3518 err = receive_read_payload_and_next_header(ra, len,
3519 abuf->b_data);
3520 if (err != 0) {
3521 dmu_return_arcbuf(abuf);
3522 return (err);
3523 }
3524 ra->rrd->arc_buf = abuf;
3525 return (err);
3526 }
3527 case DRR_OBJECT_RANGE:
3528 {
3529 err = receive_read_payload_and_next_header(ra, 0, NULL);
fcff0f35
PD
3530 return (err);
3531 }
3532 default:
3533 return (SET_ERROR(EINVAL));
3534 }
3535}
3536
6a8ee4f7
NB
3537static void
3538dprintf_drr(struct receive_record_arg *rrd, int err)
3539{
2fd92c3d 3540#ifdef ZFS_DEBUG
6a8ee4f7
NB
3541 switch (rrd->header.drr_type) {
3542 case DRR_OBJECT:
3543 {
3544 struct drr_object *drro = &rrd->header.drr_u.drr_object;
3545 dprintf("drr_type = OBJECT obj = %llu type = %u "
3546 "bonustype = %u blksz = %u bonuslen = %u cksumtype = %u "
3547 "compress = %u dn_slots = %u err = %d\n",
3548 drro->drr_object, drro->drr_type, drro->drr_bonustype,
3549 drro->drr_blksz, drro->drr_bonuslen,
3550 drro->drr_checksumtype, drro->drr_compress,
3551 drro->drr_dn_slots, err);
3552 break;
3553 }
3554 case DRR_FREEOBJECTS:
3555 {
3556 struct drr_freeobjects *drrfo =
3557 &rrd->header.drr_u.drr_freeobjects;
3558 dprintf("drr_type = FREEOBJECTS firstobj = %llu "
3559 "numobjs = %llu err = %d\n",
3560 drrfo->drr_firstobj, drrfo->drr_numobjs, err);
3561 break;
3562 }
3563 case DRR_WRITE:
3564 {
3565 struct drr_write *drrw = &rrd->header.drr_u.drr_write;
3566 dprintf("drr_type = WRITE obj = %llu type = %u offset = %llu "
3567 "lsize = %llu cksumtype = %u cksumflags = %u "
3568 "compress = %u psize = %llu err = %d\n",
3569 drrw->drr_object, drrw->drr_type, drrw->drr_offset,
3570 drrw->drr_logical_size, drrw->drr_checksumtype,
b5256303 3571 drrw->drr_flags, drrw->drr_compressiontype,
6a8ee4f7
NB
3572 drrw->drr_compressed_size, err);
3573 break;
3574 }
3575 case DRR_WRITE_BYREF:
3576 {
3577 struct drr_write_byref *drrwbr =
3578 &rrd->header.drr_u.drr_write_byref;
3579 dprintf("drr_type = WRITE_BYREF obj = %llu offset = %llu "
3580 "length = %llu toguid = %llx refguid = %llx "
3581 "refobject = %llu refoffset = %llu cksumtype = %u "
3582 "cksumflags = %u err = %d\n",
3583 drrwbr->drr_object, drrwbr->drr_offset,
3584 drrwbr->drr_length, drrwbr->drr_toguid,
3585 drrwbr->drr_refguid, drrwbr->drr_refobject,
3586 drrwbr->drr_refoffset, drrwbr->drr_checksumtype,
b5256303 3587 drrwbr->drr_flags, err);
6a8ee4f7
NB
3588 break;
3589 }
3590 case DRR_WRITE_EMBEDDED:
3591 {
3592 struct drr_write_embedded *drrwe =
3593 &rrd->header.drr_u.drr_write_embedded;
3594 dprintf("drr_type = WRITE_EMBEDDED obj = %llu offset = %llu "
3595 "length = %llu compress = %u etype = %u lsize = %u "
3596 "psize = %u err = %d\n",
3597 drrwe->drr_object, drrwe->drr_offset, drrwe->drr_length,
3598 drrwe->drr_compression, drrwe->drr_etype,
3599 drrwe->drr_lsize, drrwe->drr_psize, err);
3600 break;
3601 }
3602 case DRR_FREE:
3603 {
3604 struct drr_free *drrf = &rrd->header.drr_u.drr_free;
3605 dprintf("drr_type = FREE obj = %llu offset = %llu "
3606 "length = %lld err = %d\n",
3607 drrf->drr_object, drrf->drr_offset, drrf->drr_length,
3608 err);
3609 break;
3610 }
3611 case DRR_SPILL:
3612 {
3613 struct drr_spill *drrs = &rrd->header.drr_u.drr_spill;
3614 dprintf("drr_type = SPILL obj = %llu length = %llu "
3615 "err = %d\n", drrs->drr_object, drrs->drr_length, err);
3616 break;
3617 }
3618 default:
3619 return;
3620 }
2fd92c3d 3621#endif
6a8ee4f7
NB
3622}
3623
fcff0f35
PD
3624/*
3625 * Commit the records to the pool.
3626 */
3627static int
3628receive_process_record(struct receive_writer_arg *rwa,
3629 struct receive_record_arg *rrd)
3630{
3631 int err;
3632
47dfff3b
MA
3633 /* Processing in order, therefore bytes_read should be increasing. */
3634 ASSERT3U(rrd->bytes_read, >=, rwa->bytes_read);
3635 rwa->bytes_read = rrd->bytes_read;
3636
fcff0f35
PD
3637 switch (rrd->header.drr_type) {
3638 case DRR_OBJECT:
3639 {
3640 struct drr_object *drro = &rrd->header.drr_u.drr_object;
3641 err = receive_object(rwa, drro, rrd->payload);
3642 kmem_free(rrd->payload, rrd->payload_size);
3643 rrd->payload = NULL;
6a8ee4f7 3644 break;
fcff0f35
PD
3645 }
3646 case DRR_FREEOBJECTS:
3647 {
3648 struct drr_freeobjects *drrfo =
3649 &rrd->header.drr_u.drr_freeobjects;
6a8ee4f7
NB
3650 err = receive_freeobjects(rwa, drrfo);
3651 break;
fcff0f35
PD
3652 }
3653 case DRR_WRITE:
3654 {
3655 struct drr_write *drrw = &rrd->header.drr_u.drr_write;
b5256303 3656 err = receive_write(rwa, drrw, rrd->arc_buf);
fcff0f35
PD
3657 /* if receive_write() is successful, it consumes the arc_buf */
3658 if (err != 0)
b5256303
TC
3659 dmu_return_arcbuf(rrd->arc_buf);
3660 rrd->arc_buf = NULL;
fcff0f35 3661 rrd->payload = NULL;
6a8ee4f7 3662 break;
fcff0f35
PD
3663 }
3664 case DRR_WRITE_BYREF:
3665 {
3666 struct drr_write_byref *drrwbr =
3667 &rrd->header.drr_u.drr_write_byref;
6a8ee4f7
NB
3668 err = receive_write_byref(rwa, drrwbr);
3669 break;
fcff0f35
PD
3670 }
3671 case DRR_WRITE_EMBEDDED:
3672 {
3673 struct drr_write_embedded *drrwe =
3674 &rrd->header.drr_u.drr_write_embedded;
3675 err = receive_write_embedded(rwa, drrwe, rrd->payload);
3676 kmem_free(rrd->payload, rrd->payload_size);
3677 rrd->payload = NULL;
6a8ee4f7 3678 break;
fcff0f35
PD
3679 }
3680 case DRR_FREE:
3681 {
3682 struct drr_free *drrf = &rrd->header.drr_u.drr_free;
6a8ee4f7
NB
3683 err = receive_free(rwa, drrf);
3684 break;
fcff0f35
PD
3685 }
3686 case DRR_SPILL:
3687 {
3688 struct drr_spill *drrs = &rrd->header.drr_u.drr_spill;
b5256303
TC
3689 err = receive_spill(rwa, drrs, rrd->arc_buf);
3690 /* if receive_spill() is successful, it consumes the arc_buf */
3691 if (err != 0)
3692 dmu_return_arcbuf(rrd->arc_buf);
3693 rrd->arc_buf = NULL;
fcff0f35 3694 rrd->payload = NULL;
6a8ee4f7 3695 break;
37f8a883 3696 }
b5256303
TC
3697 case DRR_OBJECT_RANGE:
3698 {
3699 struct drr_object_range *drror =
3700 &rrd->header.drr_u.drr_object_range;
3701 return (receive_object_range(rwa, drror));
3702 }
37f8a883
MA
3703 default:
3704 return (SET_ERROR(EINVAL));
3705 }
6a8ee4f7
NB
3706
3707 if (err != 0)
3708 dprintf_drr(rrd, err);
3709
3710 return (err);
37f8a883
MA
3711}
3712
34dc7c2f 3713/*
fcff0f35
PD
3714 * dmu_recv_stream's worker thread; pull records off the queue, and then call
3715 * receive_process_record When we're done, signal the main thread and exit.
3716 */
3717static void
3718receive_writer_thread(void *arg)
3719{
3720 struct receive_writer_arg *rwa = arg;
3721 struct receive_record_arg *rrd;
3e635ac1
TC
3722 fstrans_cookie_t cookie = spl_fstrans_mark();
3723
fcff0f35
PD
3724 for (rrd = bqueue_dequeue(&rwa->q); !rrd->eos_marker;
3725 rrd = bqueue_dequeue(&rwa->q)) {
3726 /*
3727 * If there's an error, the main thread will stop putting things
3728 * on the queue, but we need to clear everything in it before we
3729 * can exit.
3730 */
3731 if (rwa->err == 0) {
3732 rwa->err = receive_process_record(rwa, rrd);
b5256303
TC
3733 } else if (rrd->arc_buf != NULL) {
3734 dmu_return_arcbuf(rrd->arc_buf);
3735 rrd->arc_buf = NULL;
fcff0f35
PD
3736 rrd->payload = NULL;
3737 } else if (rrd->payload != NULL) {
3738 kmem_free(rrd->payload, rrd->payload_size);
3739 rrd->payload = NULL;
3740 }
3741 kmem_free(rrd, sizeof (*rrd));
3742 }
3743 kmem_free(rrd, sizeof (*rrd));
3744 mutex_enter(&rwa->mutex);
3745 rwa->done = B_TRUE;
3746 cv_signal(&rwa->cv);
3747 mutex_exit(&rwa->mutex);
3e635ac1 3748 spl_fstrans_unmark(cookie);
34a6b428 3749 thread_exit();
fcff0f35
PD
3750}
3751
47dfff3b
MA
3752static int
3753resume_check(struct receive_arg *ra, nvlist_t *begin_nvl)
3754{
3755 uint64_t val;
3756 objset_t *mos = dmu_objset_pool(ra->os)->dp_meta_objset;
3757 uint64_t dsobj = dmu_objset_id(ra->os);
3758 uint64_t resume_obj, resume_off;
3759
3760 if (nvlist_lookup_uint64(begin_nvl,
3761 "resume_object", &resume_obj) != 0 ||
3762 nvlist_lookup_uint64(begin_nvl,
3763 "resume_offset", &resume_off) != 0) {
3764 return (SET_ERROR(EINVAL));
3765 }
3766 VERIFY0(zap_lookup(mos, dsobj,
3767 DS_FIELD_RESUME_OBJECT, sizeof (val), 1, &val));
3768 if (resume_obj != val)
3769 return (SET_ERROR(EINVAL));
3770 VERIFY0(zap_lookup(mos, dsobj,
3771 DS_FIELD_RESUME_OFFSET, sizeof (val), 1, &val));
3772 if (resume_off != val)
3773 return (SET_ERROR(EINVAL));
3774
3775 return (0);
3776}
3777
fcff0f35
PD
3778/*
3779 * Read in the stream's records, one by one, and apply them to the pool. There
3780 * are two threads involved; the thread that calls this function will spin up a
3781 * worker thread, read the records off the stream one by one, and issue
3782 * prefetches for any necessary indirect blocks. It will then push the records
3783 * onto an internal blocking queue. The worker thread will pull the records off
3784 * the queue, and actually write the data into the DMU. This way, the worker
3785 * thread doesn't have to wait for reads to complete, since everything it needs
3786 * (the indirect blocks) will be prefetched.
3787 *
34dc7c2f
BB
3788 * NB: callers *must* call dmu_recv_end() if this succeeds.
3789 */
3790int
572e2857
BB
3791dmu_recv_stream(dmu_recv_cookie_t *drc, vnode_t *vp, offset_t *voffp,
3792 int cleanup_fd, uint64_t *action_handlep)
34dc7c2f 3793{
37f8a883 3794 int err = 0;
04bc4610
NB
3795 struct receive_arg *ra;
3796 struct receive_writer_arg *rwa;
428870ff 3797 int featureflags;
47dfff3b
MA
3798 uint32_t payloadlen;
3799 void *payload;
3800 nvlist_t *begin_nvl = NULL;
34dc7c2f 3801
04bc4610
NB
3802 ra = kmem_zalloc(sizeof (*ra), KM_SLEEP);
3803 rwa = kmem_zalloc(sizeof (*rwa), KM_SLEEP);
3804
3805 ra->byteswap = drc->drc_byteswap;
9b840763 3806 ra->raw = drc->drc_raw;
04bc4610
NB
3807 ra->cksum = drc->drc_cksum;
3808 ra->vp = vp;
3809 ra->voff = *voffp;
47dfff3b
MA
3810
3811 if (dsl_dataset_is_zapified(drc->drc_ds)) {
3812 (void) zap_lookup(drc->drc_ds->ds_dir->dd_pool->dp_meta_objset,
3813 drc->drc_ds->ds_object, DS_FIELD_RESUME_BYTES,
3814 sizeof (ra->bytes_read), 1, &ra->bytes_read);
3815 }
3816
e6d3a843 3817 objlist_create(&ra->ignore_objlist);
34dc7c2f
BB
3818
3819 /* these were verified in dmu_recv_begin */
13fe0198 3820 ASSERT3U(DMU_GET_STREAM_HDRTYPE(drc->drc_drrb->drr_versioninfo), ==,
428870ff 3821 DMU_SUBSTREAM);
13fe0198 3822 ASSERT3U(drc->drc_drrb->drr_type, <, DMU_OST_NUMTYPES);
34dc7c2f
BB
3823
3824 /*
3825 * Open the objset we are modifying.
3826 */
04bc4610 3827 VERIFY0(dmu_objset_from_ds(drc->drc_ds, &ra->os));
34dc7c2f 3828
d683ddbb 3829 ASSERT(dsl_dataset_phys(drc->drc_ds)->ds_flags & DS_FLAG_INCONSISTENT);
34dc7c2f 3830
428870ff 3831 featureflags = DMU_GET_FEATUREFLAGS(drc->drc_drrb->drr_versioninfo);
b5256303 3832 ra->featureflags = featureflags;
428870ff 3833
1fff937a
TC
3834 ASSERT0(ra->os->os_encrypted &&
3835 (featureflags & DMU_BACKUP_FEATURE_EMBED_DATA));
9b840763 3836
428870ff
BB
3837 /* if this stream is dedup'ed, set up the avl tree for guid mapping */
3838 if (featureflags & DMU_BACKUP_FEATURE_DEDUP) {
572e2857
BB
3839 minor_t minor;
3840
3841 if (cleanup_fd == -1) {
9b840763 3842 err = SET_ERROR(EBADF);
572e2857
BB
3843 goto out;
3844 }
9b840763
TC
3845 err = zfs_onexit_fd_hold(cleanup_fd, &minor);
3846 if (err != 0) {
572e2857
BB
3847 cleanup_fd = -1;
3848 goto out;
3849 }
3850
3851 if (*action_handlep == 0) {
04bc4610 3852 rwa->guid_to_ds_map =
572e2857 3853 kmem_alloc(sizeof (avl_tree_t), KM_SLEEP);
04bc4610 3854 avl_create(rwa->guid_to_ds_map, guid_compare,
572e2857
BB
3855 sizeof (guid_map_entry_t),
3856 offsetof(guid_map_entry_t, avlnode));
37f8a883 3857 err = zfs_onexit_add_cb(minor,
04bc4610 3858 free_guid_map_onexit, rwa->guid_to_ds_map,
572e2857 3859 action_handlep);
9b840763 3860 if (err != 0)
572e2857
BB
3861 goto out;
3862 } else {
37f8a883 3863 err = zfs_onexit_cb_data(minor, *action_handlep,
04bc4610 3864 (void **)&rwa->guid_to_ds_map);
9b840763 3865 if (err != 0)
572e2857
BB
3866 goto out;
3867 }
8d35c149 3868
04bc4610 3869 drc->drc_guid_to_ds_map = rwa->guid_to_ds_map;
428870ff
BB
3870 }
3871
47dfff3b
MA
3872 payloadlen = drc->drc_drr_begin->drr_payloadlen;
3873 payload = NULL;
3874 if (payloadlen != 0)
3875 payload = kmem_alloc(payloadlen, KM_SLEEP);
3876
3877 err = receive_read_payload_and_next_header(ra, payloadlen, payload);
3878 if (err != 0) {
3879 if (payloadlen != 0)
3880 kmem_free(payload, payloadlen);
37f8a883 3881 goto out;
47dfff3b
MA
3882 }
3883 if (payloadlen != 0) {
3884 err = nvlist_unpack(payload, payloadlen, &begin_nvl, KM_SLEEP);
3885 kmem_free(payload, payloadlen);
3886 if (err != 0)
3887 goto out;
3888 }
3889
b5256303
TC
3890 /* handle DSL encryption key payload */
3891 if (featureflags & DMU_BACKUP_FEATURE_RAW) {
3892 nvlist_t *keynvl = NULL;
3893
3894 ASSERT(ra->os->os_encrypted);
3895 ASSERT(drc->drc_raw);
3896
3897 err = nvlist_lookup_nvlist(begin_nvl, "crypt_keydata", &keynvl);
3898 if (err != 0)
3899 goto out;
3900
b0918402
TC
3901 /*
3902 * If this is a new dataset we set the key immediately.
3903 * Otherwise we don't want to change the key until we
3904 * are sure the rest of the receive succeeded so we stash
3905 * the keynvl away until then.
3906 */
3907 err = dsl_crypto_recv_raw(spa_name(ra->os->os_spa),
b5256303 3908 drc->drc_ds->ds_object, drc->drc_drrb->drr_type,
b0918402 3909 keynvl, drc->drc_newfs);
b5256303
TC
3910 if (err != 0)
3911 goto out;
b0918402
TC
3912
3913 if (!drc->drc_newfs)
3914 drc->drc_keynvl = fnvlist_dup(keynvl);
b5256303
TC
3915 }
3916
47dfff3b
MA
3917 if (featureflags & DMU_BACKUP_FEATURE_RESUMING) {
3918 err = resume_check(ra, begin_nvl);
3919 if (err != 0)
3920 goto out;
3921 }
37f8a883 3922
3b0d9928
BB
3923 (void) bqueue_init(&rwa->q,
3924 MAX(zfs_recv_queue_length, 2 * zfs_max_recordsize),
fcff0f35 3925 offsetof(struct receive_record_arg, node));
04bc4610
NB
3926 cv_init(&rwa->cv, NULL, CV_DEFAULT, NULL);
3927 mutex_init(&rwa->mutex, NULL, MUTEX_DEFAULT, NULL);
3928 rwa->os = ra->os;
3929 rwa->byteswap = drc->drc_byteswap;
47dfff3b 3930 rwa->resumable = drc->drc_resumable;
9b840763 3931 rwa->raw = drc->drc_raw;
0c03d21a 3932 rwa->os->os_raw_receive = drc->drc_raw;
fcff0f35 3933
04bc4610 3934 (void) thread_create(NULL, 0, receive_writer_thread, rwa, 0, curproc,
fcff0f35
PD
3935 TS_RUN, minclsyspri);
3936 /*
04bc4610 3937 * We're reading rwa->err without locks, which is safe since we are the
fcff0f35
PD
3938 * only reader, and the worker thread is the only writer. It's ok if we
3939 * miss a write for an iteration or two of the loop, since the writer
3940 * thread will keep freeing records we send it until we send it an eos
3941 * marker.
3942 *
04bc4610 3943 * We can leave this loop in 3 ways: First, if rwa->err is
fcff0f35
PD
3944 * non-zero. In that case, the writer thread will free the rrd we just
3945 * pushed. Second, if we're interrupted; in that case, either it's the
47dfff3b 3946 * first loop and ra->rrd was never allocated, or it's later and ra->rrd
fcff0f35
PD
3947 * has been handed off to the writer thread who will free it. Finally,
3948 * if receive_read_record fails or we're at the end of the stream, then
04bc4610 3949 * we free ra->rrd and exit.
fcff0f35 3950 */
04bc4610 3951 while (rwa->err == 0) {
34dc7c2f 3952 if (issig(JUSTLOOKING) && issig(FORREAL)) {
37f8a883
MA
3953 err = SET_ERROR(EINTR);
3954 break;
34dc7c2f
BB
3955 }
3956
04bc4610
NB
3957 ASSERT3P(ra->rrd, ==, NULL);
3958 ra->rrd = ra->next_rrd;
3959 ra->next_rrd = NULL;
3960 /* Allocates and loads header into ra->next_rrd */
3961 err = receive_read_record(ra);
34dc7c2f 3962
04bc4610
NB
3963 if (ra->rrd->header.drr_type == DRR_END || err != 0) {
3964 kmem_free(ra->rrd, sizeof (*ra->rrd));
3965 ra->rrd = NULL;
428870ff 3966 break;
fcff0f35
PD
3967 }
3968
04bc4610
NB
3969 bqueue_enqueue(&rwa->q, ra->rrd,
3970 sizeof (struct receive_record_arg) + ra->rrd->payload_size);
3971 ra->rrd = NULL;
fcff0f35 3972 }
04bc4610
NB
3973 if (ra->next_rrd == NULL)
3974 ra->next_rrd = kmem_zalloc(sizeof (*ra->next_rrd), KM_SLEEP);
3975 ra->next_rrd->eos_marker = B_TRUE;
3976 bqueue_enqueue(&rwa->q, ra->next_rrd, 1);
fcff0f35 3977
04bc4610
NB
3978 mutex_enter(&rwa->mutex);
3979 while (!rwa->done) {
3980 cv_wait(&rwa->cv, &rwa->mutex);
34dc7c2f 3981 }
04bc4610 3982 mutex_exit(&rwa->mutex);
fcff0f35 3983
48fbb9dd
FG
3984 /*
3985 * If we are receiving a full stream as a clone, all object IDs which
3986 * are greater than the maximum ID referenced in the stream are
3987 * by definition unused and must be freed.
3988 */
3989 if (drc->drc_clone && drc->drc_drrb->drr_fromguid == 0) {
3990 uint64_t obj = rwa->max_object + 1;
3991 int free_err = 0;
3992 int next_err = 0;
3993
3994 while (next_err == 0) {
0c03d21a 3995 free_err = dmu_free_long_object(rwa->os, obj);
48fbb9dd
FG
3996 if (free_err != 0 && free_err != ENOENT)
3997 break;
3998
3999 next_err = dmu_object_next(rwa->os, &obj, FALSE, 0);
4000 }
4001
4002 if (err == 0) {
4003 if (free_err != 0 && free_err != ENOENT)
4004 err = free_err;
4005 else if (next_err != ESRCH)
4006 err = next_err;
4007 }
4008 }
4009
04bc4610
NB
4010 cv_destroy(&rwa->cv);
4011 mutex_destroy(&rwa->mutex);
4012 bqueue_destroy(&rwa->q);
fcff0f35 4013 if (err == 0)
04bc4610 4014 err = rwa->err;
34dc7c2f
BB
4015
4016out:
47dfff3b 4017 nvlist_free(begin_nvl);
572e2857
BB
4018 if ((featureflags & DMU_BACKUP_FEATURE_DEDUP) && (cleanup_fd != -1))
4019 zfs_onexit_fd_rele(cleanup_fd);
4020
37f8a883 4021 if (err != 0) {
34dc7c2f 4022 /*
47dfff3b
MA
4023 * Clean up references. If receive is not resumable,
4024 * destroy what we created, so we don't leave it in
4025 * the inconsistent state.
34dc7c2f 4026 */
13fe0198 4027 dmu_recv_cleanup_ds(drc);
b0918402 4028 nvlist_free(drc->drc_keynvl);
34dc7c2f
BB
4029 }
4030
04bc4610 4031 *voffp = ra->voff;
e6d3a843 4032 objlist_destroy(&ra->ignore_objlist);
04bc4610
NB
4033 kmem_free(ra, sizeof (*ra));
4034 kmem_free(rwa, sizeof (*rwa));
37f8a883 4035 return (err);
34dc7c2f
BB
4036}
4037
34dc7c2f 4038static int
13fe0198 4039dmu_recv_end_check(void *arg, dmu_tx_t *tx)
34dc7c2f 4040{
13fe0198
MA
4041 dmu_recv_cookie_t *drc = arg;
4042 dsl_pool_t *dp = dmu_tx_pool(tx);
4043 int error;
4044
4045 ASSERT3P(drc->drc_ds->ds_owner, ==, dmu_recv_tag);
4046
4047 if (!drc->drc_newfs) {
4048 dsl_dataset_t *origin_head;
4049
4050 error = dsl_dataset_hold(dp, drc->drc_tofs, FTAG, &origin_head);
4051 if (error != 0)
4052 return (error);
19580676
MA
4053 if (drc->drc_force) {
4054 /*
4055 * We will destroy any snapshots in tofs (i.e. before
4056 * origin_head) that are after the origin (which is
4057 * the snap before drc_ds, because drc_ds can not
4058 * have any snaps of its own).
4059 */
d683ddbb
JG
4060 uint64_t obj;
4061
4062 obj = dsl_dataset_phys(origin_head)->ds_prev_snap_obj;
4063 while (obj !=
4064 dsl_dataset_phys(drc->drc_ds)->ds_prev_snap_obj) {
19580676
MA
4065 dsl_dataset_t *snap;
4066 error = dsl_dataset_hold_obj(dp, obj, FTAG,
4067 &snap);
4068 if (error != 0)
b6640117 4069 break;
19580676
MA
4070 if (snap->ds_dir != origin_head->ds_dir)
4071 error = SET_ERROR(EINVAL);
4072 if (error == 0) {
4073 error = dsl_destroy_snapshot_check_impl(
4074 snap, B_FALSE);
4075 }
d683ddbb 4076 obj = dsl_dataset_phys(snap)->ds_prev_snap_obj;
19580676
MA
4077 dsl_dataset_rele(snap, FTAG);
4078 if (error != 0)
b6640117
AG
4079 break;
4080 }
4081 if (error != 0) {
4082 dsl_dataset_rele(origin_head, FTAG);
4083 return (error);
19580676
MA
4084 }
4085 }
b0918402
TC
4086 if (drc->drc_keynvl != NULL) {
4087 error = dsl_crypto_recv_raw_key_check(drc->drc_ds,
4088 drc->drc_keynvl, tx);
4089 if (error != 0) {
4090 dsl_dataset_rele(origin_head, FTAG);
4091 return (error);
4092 }
4093 }
4094
13fe0198 4095 error = dsl_dataset_clone_swap_check_impl(drc->drc_ds,
831baf06 4096 origin_head, drc->drc_force, drc->drc_owner, tx);
13fe0198
MA
4097 if (error != 0) {
4098 dsl_dataset_rele(origin_head, FTAG);
4099 return (error);
4100 }
4101 error = dsl_dataset_snapshot_check_impl(origin_head,
788eb90c 4102 drc->drc_tosnap, tx, B_TRUE, 1, drc->drc_cred);
13fe0198
MA
4103 dsl_dataset_rele(origin_head, FTAG);
4104 if (error != 0)
4105 return (error);
34dc7c2f 4106
13fe0198
MA
4107 error = dsl_destroy_head_check_impl(drc->drc_ds, 1);
4108 } else {
4109 error = dsl_dataset_snapshot_check_impl(drc->drc_ds,
788eb90c 4110 drc->drc_tosnap, tx, B_TRUE, 1, drc->drc_cred);
13fe0198
MA
4111 }
4112 return (error);
34dc7c2f
BB
4113}
4114
4115static void
13fe0198 4116dmu_recv_end_sync(void *arg, dmu_tx_t *tx)
34dc7c2f 4117{
13fe0198
MA
4118 dmu_recv_cookie_t *drc = arg;
4119 dsl_pool_t *dp = dmu_tx_pool(tx);
b5256303 4120 boolean_t encrypted = drc->drc_ds->ds_dir->dd_crypto_obj != 0;
13fe0198
MA
4121
4122 spa_history_log_internal_ds(drc->drc_ds, "finish receiving",
4123 tx, "snap=%s", drc->drc_tosnap);
0c03d21a 4124 drc->drc_ds->ds_objset->os_raw_receive = B_FALSE;
13fe0198
MA
4125
4126 if (!drc->drc_newfs) {
4127 dsl_dataset_t *origin_head;
4128
4129 VERIFY0(dsl_dataset_hold(dp, drc->drc_tofs, FTAG,
4130 &origin_head));
19580676
MA
4131
4132 if (drc->drc_force) {
4133 /*
4134 * Destroy any snapshots of drc_tofs (origin_head)
4135 * after the origin (the snap before drc_ds).
4136 */
d683ddbb
JG
4137 uint64_t obj;
4138
4139 obj = dsl_dataset_phys(origin_head)->ds_prev_snap_obj;
4140 while (obj !=
4141 dsl_dataset_phys(drc->drc_ds)->ds_prev_snap_obj) {
19580676
MA
4142 dsl_dataset_t *snap;
4143 VERIFY0(dsl_dataset_hold_obj(dp, obj, FTAG,
4144 &snap));
4145 ASSERT3P(snap->ds_dir, ==, origin_head->ds_dir);
d683ddbb 4146 obj = dsl_dataset_phys(snap)->ds_prev_snap_obj;
19580676
MA
4147 dsl_destroy_snapshot_sync_impl(snap,
4148 B_FALSE, tx);
4149 dsl_dataset_rele(snap, FTAG);
4150 }
4151 }
b0918402
TC
4152 if (drc->drc_keynvl != NULL) {
4153 dsl_crypto_recv_raw_key_sync(drc->drc_ds,
4154 drc->drc_keynvl, tx);
4155 nvlist_free(drc->drc_keynvl);
4156 drc->drc_keynvl = NULL;
4157 }
4158
4159 VERIFY3P(drc->drc_ds->ds_prev, ==, origin_head->ds_prev);
19580676 4160
13fe0198
MA
4161 dsl_dataset_clone_swap_sync_impl(drc->drc_ds,
4162 origin_head, tx);
4163 dsl_dataset_snapshot_sync_impl(origin_head,
4164 drc->drc_tosnap, tx);
4165
4166 /* set snapshot's creation time and guid */
4167 dmu_buf_will_dirty(origin_head->ds_prev->ds_dbuf, tx);
d683ddbb 4168 dsl_dataset_phys(origin_head->ds_prev)->ds_creation_time =
13fe0198 4169 drc->drc_drrb->drr_creation_time;
d683ddbb 4170 dsl_dataset_phys(origin_head->ds_prev)->ds_guid =
13fe0198 4171 drc->drc_drrb->drr_toguid;
d683ddbb 4172 dsl_dataset_phys(origin_head->ds_prev)->ds_flags &=
13fe0198
MA
4173 ~DS_FLAG_INCONSISTENT;
4174
4175 dmu_buf_will_dirty(origin_head->ds_dbuf, tx);
d683ddbb
JG
4176 dsl_dataset_phys(origin_head)->ds_flags &=
4177 ~DS_FLAG_INCONSISTENT;
13fe0198 4178
2e0e443a
GM
4179 drc->drc_newsnapobj =
4180 dsl_dataset_phys(origin_head)->ds_prev_snap_obj;
4181
13fe0198
MA
4182 dsl_dataset_rele(origin_head, FTAG);
4183 dsl_destroy_head_sync_impl(drc->drc_ds, tx);
831baf06
KW
4184
4185 if (drc->drc_owner != NULL)
4186 VERIFY3P(origin_head->ds_owner, ==, drc->drc_owner);
13fe0198
MA
4187 } else {
4188 dsl_dataset_t *ds = drc->drc_ds;
34dc7c2f 4189
13fe0198 4190 dsl_dataset_snapshot_sync_impl(ds, drc->drc_tosnap, tx);
34dc7c2f 4191
13fe0198
MA
4192 /* set snapshot's creation time and guid */
4193 dmu_buf_will_dirty(ds->ds_prev->ds_dbuf, tx);
d683ddbb 4194 dsl_dataset_phys(ds->ds_prev)->ds_creation_time =
13fe0198 4195 drc->drc_drrb->drr_creation_time;
d683ddbb
JG
4196 dsl_dataset_phys(ds->ds_prev)->ds_guid =
4197 drc->drc_drrb->drr_toguid;
4198 dsl_dataset_phys(ds->ds_prev)->ds_flags &=
4199 ~DS_FLAG_INCONSISTENT;
34dc7c2f 4200
13fe0198 4201 dmu_buf_will_dirty(ds->ds_dbuf, tx);
d683ddbb 4202 dsl_dataset_phys(ds)->ds_flags &= ~DS_FLAG_INCONSISTENT;
47dfff3b
MA
4203 if (dsl_dataset_has_resume_receive_state(ds)) {
4204 (void) zap_remove(dp->dp_meta_objset, ds->ds_object,
4205 DS_FIELD_RESUME_FROMGUID, tx);
4206 (void) zap_remove(dp->dp_meta_objset, ds->ds_object,
4207 DS_FIELD_RESUME_OBJECT, tx);
4208 (void) zap_remove(dp->dp_meta_objset, ds->ds_object,
4209 DS_FIELD_RESUME_OFFSET, tx);
4210 (void) zap_remove(dp->dp_meta_objset, ds->ds_object,
4211 DS_FIELD_RESUME_BYTES, tx);
4212 (void) zap_remove(dp->dp_meta_objset, ds->ds_object,
4213 DS_FIELD_RESUME_TOGUID, tx);
4214 (void) zap_remove(dp->dp_meta_objset, ds->ds_object,
4215 DS_FIELD_RESUME_TONAME, tx);
4216 }
2e0e443a
GM
4217 drc->drc_newsnapobj =
4218 dsl_dataset_phys(drc->drc_ds)->ds_prev_snap_obj;
13fe0198 4219 }
a0bd735a 4220 zvol_create_minors(dp->dp_spa, drc->drc_tofs, B_TRUE);
b5256303 4221
13fe0198
MA
4222 /*
4223 * Release the hold from dmu_recv_begin. This must be done before
b5256303
TC
4224 * we return to open context, so that when we free the dataset's dnode
4225 * we can evict its bonus buffer. Since the dataset may be destroyed
4226 * at this point (and therefore won't have a valid pointer to the spa)
4227 * we release the key mapping manually here while we do have a valid
4228 * pointer, if it exists.
13fe0198 4229 */
b5256303
TC
4230 if (!drc->drc_raw && encrypted) {
4231 (void) spa_keystore_remove_mapping(dmu_tx_pool(tx)->dp_spa,
4232 drc->drc_ds->ds_object, drc->drc_ds);
4233 }
4234 dsl_dataset_disown(drc->drc_ds, 0, dmu_recv_tag);
13fe0198 4235 drc->drc_ds = NULL;
34dc7c2f
BB
4236}
4237
8d35c149 4238static int
b5256303
TC
4239add_ds_to_guidmap(const char *name, avl_tree_t *guid_map, uint64_t snapobj,
4240 boolean_t raw)
8d35c149 4241{
13fe0198 4242 dsl_pool_t *dp;
8d35c149
AS
4243 dsl_dataset_t *snapds;
4244 guid_map_entry_t *gmep;
149ce888 4245 objset_t *os;
b5256303 4246 ds_hold_flags_t dsflags = (raw) ? 0 : DS_HOLD_FLAG_DECRYPT;
8d35c149
AS
4247 int err;
4248
4249 ASSERT(guid_map != NULL);
4250
13fe0198
MA
4251 err = dsl_pool_hold(name, FTAG, &dp);
4252 if (err != 0)
4253 return (err);
7ec09286 4254 gmep = kmem_alloc(sizeof (*gmep), KM_SLEEP);
149ce888 4255 err = dsl_dataset_own_obj(dp, snapobj, dsflags, gmep, &snapds);
8d35c149 4256 if (err == 0) {
149ce888
TC
4257 /*
4258 * If this is a deduplicated raw send stream, we need
4259 * to make sure that we can still read raw blocks from
4260 * earlier datasets in the stream, so we set the
4261 * os_raw_receive flag now.
4262 */
4263 if (raw) {
4264 err = dmu_objset_from_ds(snapds, &os);
4265 if (err != 0) {
4266 dsl_dataset_disown(snapds, dsflags, FTAG);
4267 dsl_pool_rele(dp, FTAG);
4268 kmem_free(gmep, sizeof (*gmep));
4269 return (err);
4270 }
4271 os->os_raw_receive = B_TRUE;
4272 }
4273
b5256303 4274 gmep->raw = raw;
149ce888 4275 gmep->guid = dsl_dataset_phys(snapds)->ds_guid;
8d35c149
AS
4276 gmep->gme_ds = snapds;
4277 avl_add(guid_map, gmep);
7ec09286
MA
4278 } else {
4279 kmem_free(gmep, sizeof (*gmep));
8d35c149
AS
4280 }
4281
13fe0198 4282 dsl_pool_rele(dp, FTAG);
8d35c149
AS
4283 return (err);
4284}
4285
13fe0198
MA
4286static int dmu_recv_end_modified_blocks = 3;
4287
428870ff
BB
4288static int
4289dmu_recv_existing_end(dmu_recv_cookie_t *drc)
34dc7c2f 4290{
13fe0198 4291#ifdef _KERNEL
13fe0198
MA
4292 /*
4293 * We will be destroying the ds; make sure its origin is unmounted if
4294 * necessary.
4295 */
eca7b760 4296 char name[ZFS_MAX_DATASET_NAME_LEN];
13fe0198
MA
4297 dsl_dataset_name(drc->drc_ds, name);
4298 zfs_destroy_unmount_origin(name);
13fe0198 4299#endif
34dc7c2f 4300
2e0e443a 4301 return (dsl_sync_task(drc->drc_tofs,
13fe0198 4302 dmu_recv_end_check, dmu_recv_end_sync, drc,
2e0e443a 4303 dmu_recv_end_modified_blocks, ZFS_SPACE_CHECK_NORMAL));
34dc7c2f 4304}
428870ff
BB
4305
4306static int
4307dmu_recv_new_end(dmu_recv_cookie_t *drc)
2e0e443a
GM
4308{
4309 return (dsl_sync_task(drc->drc_tofs,
4310 dmu_recv_end_check, dmu_recv_end_sync, drc,
4311 dmu_recv_end_modified_blocks, ZFS_SPACE_CHECK_NORMAL));
4312}
4313
4314int
4315dmu_recv_end(dmu_recv_cookie_t *drc, void *owner)
428870ff 4316{
13fe0198 4317 int error;
428870ff 4318
2e0e443a
GM
4319 drc->drc_owner = owner;
4320
4321 if (drc->drc_newfs)
4322 error = dmu_recv_new_end(drc);
4323 else
4324 error = dmu_recv_existing_end(drc);
428870ff 4325
13fe0198
MA
4326 if (error != 0) {
4327 dmu_recv_cleanup_ds(drc);
b0918402 4328 nvlist_free(drc->drc_keynvl);
13fe0198 4329 } else if (drc->drc_guid_to_ds_map != NULL) {
b5256303
TC
4330 (void) add_ds_to_guidmap(drc->drc_tofs, drc->drc_guid_to_ds_map,
4331 drc->drc_newsnapobj, drc->drc_raw);
428870ff 4332 }
13fe0198 4333 return (error);
428870ff
BB
4334}
4335
ea97f8ce
MA
4336/*
4337 * Return TRUE if this objset is currently being received into.
4338 */
4339boolean_t
4340dmu_objset_is_receiving(objset_t *os)
4341{
4342 return (os->os_dsl_dataset != NULL &&
4343 os->os_dsl_dataset->ds_owner == dmu_recv_tag);
4344}
fd8febbd
TF
4345
4346#if defined(_KERNEL)
ca0845d5
PD
4347/* BEGIN CSTYLED */
4348module_param(zfs_override_estimate_recordsize, ulong, 0644);
4349MODULE_PARM_DESC(zfs_override_estimate_recordsize,
4350 "Record size calculation override for zfs send estimates");
4351/* END CSTYLED */
4352
fd8febbd
TF
4353module_param(zfs_send_corrupt_data, int, 0644);
4354MODULE_PARM_DESC(zfs_send_corrupt_data, "Allow sending corrupt data");
3b0d9928
BB
4355
4356module_param(zfs_send_queue_length, int, 0644);
4357MODULE_PARM_DESC(zfs_send_queue_length, "Maximum send queue length");
4358
4359module_param(zfs_recv_queue_length, int, 0644);
4360MODULE_PARM_DESC(zfs_recv_queue_length, "Maximum receive queue length");
fd8febbd 4361#endif