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