1 // SPDX-License-Identifier: CDDL-1.0
2 /*
3 * CDDL HEADER START
4 *
5 * The contents of this file are subject to the terms of the
6 * Common Development and Distribution License (the "License").
7 * You may not use this file except in compliance with the License.
8 *
9 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10 * or https://opensource.org/licenses/CDDL-1.0.
11 * See the License for the specific language governing permissions
12 * and limitations under the License.
13 *
14 * When distributing Covered Code, include this CDDL HEADER in each
15 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16 * If applicable, add the following below this CDDL HEADER, with the
17 * fields enclosed by brackets "[]" replaced with your own identifying
18 * information: Portions Copyright [yyyy] [name of copyright owner]
19 *
20 * CDDL HEADER END
21 */
22 /*
23 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24 * Copyright 2011 Nexenta Systems, Inc. All rights reserved.
25 * Copyright (c) 2011, 2020 by Delphix. All rights reserved.
26 * Copyright (c) 2014, Joyent, Inc. All rights reserved.
27 * Copyright 2014 HybridCluster. All rights reserved.
28 * Copyright (c) 2018, loli10K <ezomori.nozomu@gmail.com>. All rights reserved.
29 * Copyright (c) 2019, 2024, Klara, Inc.
30 * Copyright (c) 2019, Allan Jude
31 * Copyright (c) 2019 Datto Inc.
32 * Copyright (c) 2022 Axcient.
33 */
34
35 #include <sys/arc.h>
36 #include <sys/spa_impl.h>
37 #include <sys/dmu.h>
38 #include <sys/dmu_impl.h>
39 #include <sys/dmu_send.h>
40 #include <sys/dmu_recv.h>
41 #include <sys/dmu_tx.h>
42 #include <sys/dbuf.h>
43 #include <sys/dnode.h>
44 #include <sys/zfs_context.h>
45 #include <sys/dmu_objset.h>
46 #include <sys/dmu_traverse.h>
47 #include <sys/dsl_dataset.h>
48 #include <sys/dsl_dir.h>
49 #include <sys/dsl_prop.h>
50 #include <sys/dsl_pool.h>
51 #include <sys/dsl_synctask.h>
52 #include <sys/zfs_ioctl.h>
53 #include <sys/zap.h>
54 #include <sys/zvol.h>
55 #include <sys/zio_checksum.h>
56 #include <sys/zfs_znode.h>
57 #include <zfs_fletcher.h>
58 #include <sys/avl.h>
59 #include <sys/ddt.h>
60 #include <sys/zfs_onexit.h>
61 #include <sys/dsl_destroy.h>
62 #include <sys/blkptr.h>
63 #include <sys/dsl_bookmark.h>
64 #include <sys/zfeature.h>
65 #include <sys/bqueue.h>
66 #include <sys/objlist.h>
67 #ifdef _KERNEL
68 #include <sys/zfs_vfsops.h>
69 #endif
70 #include <sys/zfs_file.h>
71
72 static uint_t zfs_recv_queue_length = SPA_MAXBLOCKSIZE;
73 static uint_t zfs_recv_queue_ff = 20;
74 static uint_t zfs_recv_write_batch_size = 1024 * 1024;
75 static int zfs_recv_best_effort_corrective = 0;
76
77 static const void *const dmu_recv_tag = "dmu_recv_tag";
78 const char *const recv_clone_name = "%recv";
79
80 typedef enum {
81 ORNS_NO,
82 ORNS_YES,
83 ORNS_MAYBE
84 } or_need_sync_t;
85
86 static int receive_read_payload_and_next_header(dmu_recv_cookie_t *ra, int len,
87 void *buf);
88
89 struct receive_record_arg {
90 dmu_replay_record_t header;
91 void *payload; /* Pointer to a buffer containing the payload */
92 /*
93 * If the record is a WRITE or SPILL, pointer to the abd containing the
94 * payload.
95 */
96 abd_t *abd;
97 int payload_size;
98 uint64_t bytes_read; /* bytes read from stream when record created */
99 boolean_t eos_marker; /* Marks the end of the stream */
100 bqueue_node_t node;
101 };
102
103 struct receive_writer_arg {
104 objset_t *os;
105 boolean_t byteswap;
106 bqueue_t q;
107
108 /*
109 * These three members are used to signal to the main thread when
110 * we're done.
111 */
112 kmutex_t mutex;
113 kcondvar_t cv;
114 boolean_t done;
115
116 int err;
117 const char *tofs;
118 boolean_t heal;
119 boolean_t resumable;
120 boolean_t raw; /* DMU_BACKUP_FEATURE_RAW set */
121 boolean_t spill; /* DRR_FLAG_SPILL_BLOCK set */
122 boolean_t full; /* this is a full send stream */
123 uint64_t last_object;
124 uint64_t last_offset;
125 uint64_t max_object; /* highest object ID referenced in stream */
126 uint64_t bytes_read; /* bytes read when current record created */
127
128 list_t write_batch;
129
130 /* Encryption parameters for the last received DRR_OBJECT_RANGE */
131 boolean_t or_crypt_params_present;
132 uint64_t or_firstobj;
133 uint64_t or_numslots;
134 uint8_t or_salt[ZIO_DATA_SALT_LEN];
135 uint8_t or_iv[ZIO_DATA_IV_LEN];
136 uint8_t or_mac[ZIO_DATA_MAC_LEN];
137 boolean_t or_byteorder;
138 zio_t *heal_pio;
139
140 /* Keep track of DRR_FREEOBJECTS right after DRR_OBJECT_RANGE */
141 or_need_sync_t or_need_sync;
142 };
143
144 typedef struct dmu_recv_begin_arg {
145 const char *drba_origin;
146 dmu_recv_cookie_t *drba_cookie;
147 cred_t *drba_cred;
148 proc_t *drba_proc;
149 dsl_crypto_params_t *drba_dcp;
150 } dmu_recv_begin_arg_t;
151
152 static void
byteswap_record(dmu_replay_record_t * drr)153 byteswap_record(dmu_replay_record_t *drr)
154 {
155 #define DO64(X) (drr->drr_u.X = BSWAP_64(drr->drr_u.X))
156 #define DO32(X) (drr->drr_u.X = BSWAP_32(drr->drr_u.X))
157 drr->drr_type = BSWAP_32(drr->drr_type);
158 drr->drr_payloadlen = BSWAP_32(drr->drr_payloadlen);
159
160 switch (drr->drr_type) {
161 case DRR_BEGIN:
162 DO64(drr_begin.drr_magic);
163 DO64(drr_begin.drr_versioninfo);
164 DO64(drr_begin.drr_creation_time);
165 DO32(drr_begin.drr_type);
166 DO32(drr_begin.drr_flags);
167 DO64(drr_begin.drr_toguid);
168 DO64(drr_begin.drr_fromguid);
169 break;
170 case DRR_OBJECT:
171 DO64(drr_object.drr_object);
172 DO32(drr_object.drr_type);
173 DO32(drr_object.drr_bonustype);
174 DO32(drr_object.drr_blksz);
175 DO32(drr_object.drr_bonuslen);
176 DO32(drr_object.drr_raw_bonuslen);
177 DO64(drr_object.drr_toguid);
178 DO64(drr_object.drr_maxblkid);
179 break;
180 case DRR_FREEOBJECTS:
181 DO64(drr_freeobjects.drr_firstobj);
182 DO64(drr_freeobjects.drr_numobjs);
183 DO64(drr_freeobjects.drr_toguid);
184 break;
185 case DRR_WRITE:
186 DO64(drr_write.drr_object);
187 DO32(drr_write.drr_type);
188 DO64(drr_write.drr_offset);
189 DO64(drr_write.drr_logical_size);
190 DO64(drr_write.drr_toguid);
191 ZIO_CHECKSUM_BSWAP(&drr->drr_u.drr_write.drr_key.ddk_cksum);
192 DO64(drr_write.drr_key.ddk_prop);
193 DO64(drr_write.drr_compressed_size);
194 break;
195 case DRR_WRITE_EMBEDDED:
196 DO64(drr_write_embedded.drr_object);
197 DO64(drr_write_embedded.drr_offset);
198 DO64(drr_write_embedded.drr_length);
199 DO64(drr_write_embedded.drr_toguid);
200 DO32(drr_write_embedded.drr_lsize);
201 DO32(drr_write_embedded.drr_psize);
202 break;
203 case DRR_FREE:
204 DO64(drr_free.drr_object);
205 DO64(drr_free.drr_offset);
206 DO64(drr_free.drr_length);
207 DO64(drr_free.drr_toguid);
208 break;
209 case DRR_SPILL:
210 DO64(drr_spill.drr_object);
211 DO64(drr_spill.drr_length);
212 DO64(drr_spill.drr_toguid);
213 DO64(drr_spill.drr_compressed_size);
214 DO32(drr_spill.drr_type);
215 break;
216 case DRR_OBJECT_RANGE:
217 DO64(drr_object_range.drr_firstobj);
218 DO64(drr_object_range.drr_numslots);
219 DO64(drr_object_range.drr_toguid);
220 break;
221 case DRR_REDACT:
222 DO64(drr_redact.drr_object);
223 DO64(drr_redact.drr_offset);
224 DO64(drr_redact.drr_length);
225 DO64(drr_redact.drr_toguid);
226 break;
227 case DRR_END:
228 DO64(drr_end.drr_toguid);
229 ZIO_CHECKSUM_BSWAP(&drr->drr_u.drr_end.drr_checksum);
230 break;
231 default:
232 break;
233 }
234
235 if (drr->drr_type != DRR_BEGIN) {
236 ZIO_CHECKSUM_BSWAP(&drr->drr_u.drr_checksum.drr_checksum);
237 }
238
239 #undef DO64
240 #undef DO32
241 }
242
243 static boolean_t
redact_snaps_contains(uint64_t * snaps,uint64_t num_snaps,uint64_t guid)244 redact_snaps_contains(uint64_t *snaps, uint64_t num_snaps, uint64_t guid)
245 {
246 for (int i = 0; i < num_snaps; i++) {
247 if (snaps[i] == guid)
248 return (B_TRUE);
249 }
250 return (B_FALSE);
251 }
252
253 /*
254 * Check that the new stream we're trying to receive is redacted with respect to
255 * a subset of the snapshots that the origin was redacted with respect to. For
256 * the reasons behind this, see the man page on redacted zfs sends and receives.
257 */
258 static boolean_t
compatible_redact_snaps(uint64_t * origin_snaps,uint64_t origin_num_snaps,uint64_t * redact_snaps,uint64_t num_redact_snaps)259 compatible_redact_snaps(uint64_t *origin_snaps, uint64_t origin_num_snaps,
260 uint64_t *redact_snaps, uint64_t num_redact_snaps)
261 {
262 /*
263 * Short circuit the comparison; if we are redacted with respect to
264 * more snapshots than the origin, we can't be redacted with respect
265 * to a subset.
266 */
267 if (num_redact_snaps > origin_num_snaps) {
268 return (B_FALSE);
269 }
270
271 for (int i = 0; i < num_redact_snaps; i++) {
272 if (!redact_snaps_contains(origin_snaps, origin_num_snaps,
273 redact_snaps[i])) {
274 return (B_FALSE);
275 }
276 }
277 return (B_TRUE);
278 }
279
280 static boolean_t
redact_check(dmu_recv_begin_arg_t * drba,dsl_dataset_t * origin)281 redact_check(dmu_recv_begin_arg_t *drba, dsl_dataset_t *origin)
282 {
283 uint64_t *origin_snaps;
284 uint64_t origin_num_snaps;
285 dmu_recv_cookie_t *drc = drba->drba_cookie;
286 struct drr_begin *drrb = drc->drc_drrb;
287 int featureflags = DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo);
288 int err = 0;
289 boolean_t ret = B_TRUE;
290 uint64_t *redact_snaps;
291 uint_t numredactsnaps;
292
293 /*
294 * If this is a full send stream, we're safe no matter what.
295 */
296 if (drrb->drr_fromguid == 0)
297 return (ret);
298
299 VERIFY(dsl_dataset_get_uint64_array_feature(origin,
300 SPA_FEATURE_REDACTED_DATASETS, &origin_num_snaps, &origin_snaps));
301
302 if (nvlist_lookup_uint64_array(drc->drc_begin_nvl,
303 BEGINNV_REDACT_FROM_SNAPS, &redact_snaps, &numredactsnaps) ==
304 0) {
305 /*
306 * If the send stream was sent from the redaction bookmark or
307 * the redacted version of the dataset, then we're safe. Verify
308 * that this is from the a compatible redaction bookmark or
309 * redacted dataset.
310 */
311 if (!compatible_redact_snaps(origin_snaps, origin_num_snaps,
312 redact_snaps, numredactsnaps)) {
313 err = EINVAL;
314 }
315 } else if (featureflags & DMU_BACKUP_FEATURE_REDACTED) {
316 /*
317 * If the stream is redacted, it must be redacted with respect
318 * to a subset of what the origin is redacted with respect to.
319 * See case number 2 in the zfs man page section on redacted zfs
320 * send.
321 */
322 err = nvlist_lookup_uint64_array(drc->drc_begin_nvl,
323 BEGINNV_REDACT_SNAPS, &redact_snaps, &numredactsnaps);
324
325 if (err != 0 || !compatible_redact_snaps(origin_snaps,
326 origin_num_snaps, redact_snaps, numredactsnaps)) {
327 err = EINVAL;
328 }
329 } else if (!redact_snaps_contains(origin_snaps, origin_num_snaps,
330 drrb->drr_toguid)) {
331 /*
332 * If the stream isn't redacted but the origin is, this must be
333 * one of the snapshots the origin is redacted with respect to.
334 * See case number 1 in the zfs man page section on redacted zfs
335 * send.
336 */
337 err = EINVAL;
338 }
339
340 if (err != 0)
341 ret = B_FALSE;
342 return (ret);
343 }
344
345 /*
346 * If we previously received a stream with --large-block, we don't support
347 * receiving an incremental on top of it without --large-block. This avoids
348 * forcing a read-modify-write or trying to re-aggregate a string of WRITE
349 * records.
350 */
351 static int
recv_check_large_blocks(dsl_dataset_t * ds,uint64_t featureflags)352 recv_check_large_blocks(dsl_dataset_t *ds, uint64_t featureflags)
353 {
354 if (dsl_dataset_feature_is_active(ds, SPA_FEATURE_LARGE_BLOCKS) &&
355 !(featureflags & DMU_BACKUP_FEATURE_LARGE_BLOCKS))
356 return (SET_ERROR(ZFS_ERR_STREAM_LARGE_BLOCK_MISMATCH));
357 return (0);
358 }
359
360 static int
recv_begin_check_existing_impl(dmu_recv_begin_arg_t * drba,dsl_dataset_t * ds,uint64_t fromguid,uint64_t featureflags)361 recv_begin_check_existing_impl(dmu_recv_begin_arg_t *drba, dsl_dataset_t *ds,
362 uint64_t fromguid, uint64_t featureflags)
363 {
364 uint64_t obj;
365 uint64_t children;
366 int error;
367 dsl_dataset_t *snap;
368 dsl_pool_t *dp = ds->ds_dir->dd_pool;
369 boolean_t encrypted = ds->ds_dir->dd_crypto_obj != 0;
370 boolean_t raw = (featureflags & DMU_BACKUP_FEATURE_RAW) != 0;
371 boolean_t embed = (featureflags & DMU_BACKUP_FEATURE_EMBED_DATA) != 0;
372
373 /* Temporary clone name must not exist. */
374 error = zap_lookup(dp->dp_meta_objset,
375 dsl_dir_phys(ds->ds_dir)->dd_child_dir_zapobj, recv_clone_name,
376 8, 1, &obj);
377 if (error != ENOENT)
378 return (error == 0 ? SET_ERROR(EBUSY) : error);
379
380 /* Resume state must not be set. */
381 if (dsl_dataset_has_resume_receive_state(ds))
382 return (SET_ERROR(EBUSY));
383
384 /* New snapshot name must not exist if we're not healing it. */
385 error = zap_lookup(dp->dp_meta_objset,
386 dsl_dataset_phys(ds)->ds_snapnames_zapobj,
387 drba->drba_cookie->drc_tosnap, 8, 1, &obj);
388 if (drba->drba_cookie->drc_heal) {
389 if (error != 0)
390 return (error);
391 } else if (error != ENOENT) {
392 return (error == 0 ? SET_ERROR(EEXIST) : error);
393 }
394
395 /* Must not have children if receiving a ZVOL. */
396 error = zap_count(dp->dp_meta_objset,
397 dsl_dir_phys(ds->ds_dir)->dd_child_dir_zapobj, &children);
398 if (error != 0)
399 return (error);
400 if (drba->drba_cookie->drc_drrb->drr_type != DMU_OST_ZFS &&
401 children > 0)
402 return (SET_ERROR(ZFS_ERR_WRONG_PARENT));
403
404 /*
405 * Check snapshot limit before receiving. We'll recheck again at the
406 * end, but might as well abort before receiving if we're already over
407 * the limit.
408 *
409 * Note that we do not check the file system limit with
410 * dsl_dir_fscount_check because the temporary %clones don't count
411 * against that limit.
412 */
413 error = dsl_fs_ss_limit_check(ds->ds_dir, 1, ZFS_PROP_SNAPSHOT_LIMIT,
414 NULL, drba->drba_cred, drba->drba_proc);
415 if (error != 0)
416 return (error);
417
418 if (drba->drba_cookie->drc_heal) {
419 /* Encryption is incompatible with embedded data. */
420 if (encrypted && embed)
421 return (SET_ERROR(EINVAL));
422
423 /* Healing is not supported when in 'force' mode. */
424 if (drba->drba_cookie->drc_force)
425 return (SET_ERROR(EINVAL));
426
427 /* Must have keys loaded if doing encrypted non-raw recv. */
428 if (encrypted && !raw) {
429 if (spa_keystore_lookup_key(dp->dp_spa, ds->ds_object,
430 NULL, NULL) != 0)
431 return (SET_ERROR(EACCES));
432 }
433
434 error = dsl_dataset_hold_obj(dp, obj, FTAG, &snap);
435 if (error != 0)
436 return (error);
437
438 /*
439 * When not doing best effort corrective recv healing can only
440 * be done if the send stream is for the same snapshot as the
441 * one we are trying to heal.
442 */
443 if (zfs_recv_best_effort_corrective == 0 &&
444 drba->drba_cookie->drc_drrb->drr_toguid !=
445 dsl_dataset_phys(snap)->ds_guid) {
446 dsl_dataset_rele(snap, FTAG);
447 return (SET_ERROR(ENOTSUP));
448 }
449 dsl_dataset_rele(snap, FTAG);
450 } else if (fromguid != 0) {
451 /* Sanity check the incremental recv */
452 uint64_t obj = dsl_dataset_phys(ds)->ds_prev_snap_obj;
453
454 /* Can't perform a raw receive on top of a non-raw receive */
455 if (!encrypted && raw)
456 return (SET_ERROR(EINVAL));
457
458 /* Encryption is incompatible with embedded data */
459 if (encrypted && embed)
460 return (SET_ERROR(EINVAL));
461
462 /* Find snapshot in this dir that matches fromguid. */
463 while (obj != 0) {
464 error = dsl_dataset_hold_obj(dp, obj, FTAG,
465 &snap);
466 if (error != 0)
467 return (SET_ERROR(ENODEV));
468 if (snap->ds_dir != ds->ds_dir) {
469 dsl_dataset_rele(snap, FTAG);
470 return (SET_ERROR(ENODEV));
471 }
472 if (dsl_dataset_phys(snap)->ds_guid == fromguid)
473 break;
474 obj = dsl_dataset_phys(snap)->ds_prev_snap_obj;
475 dsl_dataset_rele(snap, FTAG);
476 }
477 if (obj == 0)
478 return (SET_ERROR(ENODEV));
479
480 if (drba->drba_cookie->drc_force) {
481 drba->drba_cookie->drc_fromsnapobj = obj;
482 } else {
483 /*
484 * If we are not forcing, there must be no
485 * changes since fromsnap. Raw sends have an
486 * additional constraint that requires that
487 * no "noop" snapshots exist between fromsnap
488 * and tosnap for the IVset checking code to
489 * work properly.
490 */
491 if (dsl_dataset_modified_since_snap(ds, snap) ||
492 (raw &&
493 dsl_dataset_phys(ds)->ds_prev_snap_obj !=
494 snap->ds_object)) {
495 dsl_dataset_rele(snap, FTAG);
496 return (SET_ERROR(ETXTBSY));
497 }
498 drba->drba_cookie->drc_fromsnapobj =
499 ds->ds_prev->ds_object;
500 }
501
502 if (dsl_dataset_feature_is_active(snap,
503 SPA_FEATURE_REDACTED_DATASETS) && !redact_check(drba,
504 snap)) {
505 dsl_dataset_rele(snap, FTAG);
506 return (SET_ERROR(EINVAL));
507 }
508
509 error = recv_check_large_blocks(snap, featureflags);
510 if (error != 0) {
511 dsl_dataset_rele(snap, FTAG);
512 return (error);
513 }
514
515 dsl_dataset_rele(snap, FTAG);
516 } else {
517 /* If full and not healing then must be forced. */
518 if (!drba->drba_cookie->drc_force)
519 return (SET_ERROR(EEXIST));
520
521 /*
522 * We don't support using zfs recv -F to blow away
523 * encrypted filesystems. This would require the
524 * dsl dir to point to the old encryption key and
525 * the new one at the same time during the receive.
526 */
527 if ((!encrypted && raw) || encrypted)
528 return (SET_ERROR(EINVAL));
529
530 /*
531 * Perform the same encryption checks we would if
532 * we were creating a new dataset from scratch.
533 */
534 if (!raw) {
535 boolean_t will_encrypt;
536
537 error = dmu_objset_create_crypt_check(
538 ds->ds_dir->dd_parent, drba->drba_dcp,
539 &will_encrypt);
540 if (error != 0)
541 return (error);
542
543 if (will_encrypt && embed)
544 return (SET_ERROR(EINVAL));
545 }
546 }
547
548 return (0);
549 }
550
551 /*
552 * Check that any feature flags used in the data stream we're receiving are
553 * supported by the pool we are receiving into.
554 *
555 * Note that some of the features we explicitly check here have additional
556 * (implicit) features they depend on, but those dependencies are enforced
557 * through the zfeature_register() calls declaring the features that we
558 * explicitly check.
559 */
560 static int
recv_begin_check_feature_flags_impl(uint64_t featureflags,spa_t * spa)561 recv_begin_check_feature_flags_impl(uint64_t featureflags, spa_t *spa)
562 {
563 /*
564 * Check if there are any unsupported feature flags.
565 */
566 if (!DMU_STREAM_SUPPORTED(featureflags)) {
567 return (SET_ERROR(ZFS_ERR_UNKNOWN_SEND_STREAM_FEATURE));
568 }
569
570 /* Verify pool version supports SA if SA_SPILL feature set */
571 if ((featureflags & DMU_BACKUP_FEATURE_SA_SPILL) &&
572 spa_version(spa) < SPA_VERSION_SA)
573 return (SET_ERROR(ENOTSUP));
574
575 /*
576 * LZ4 compressed, ZSTD compressed, embedded, mooched, large blocks,
577 * and large_dnodes in the stream can only be used if those pool
578 * features are enabled because we don't attempt to decompress /
579 * un-embed / un-mooch / split up the blocks / dnodes during the
580 * receive process.
581 */
582 if ((featureflags & DMU_BACKUP_FEATURE_LZ4) &&
583 !spa_feature_is_enabled(spa, SPA_FEATURE_LZ4_COMPRESS))
584 return (SET_ERROR(ENOTSUP));
585 if ((featureflags & DMU_BACKUP_FEATURE_ZSTD) &&
586 !spa_feature_is_enabled(spa, SPA_FEATURE_ZSTD_COMPRESS))
587 return (SET_ERROR(ENOTSUP));
588 if ((featureflags & DMU_BACKUP_FEATURE_EMBED_DATA) &&
589 !spa_feature_is_enabled(spa, SPA_FEATURE_EMBEDDED_DATA))
590 return (SET_ERROR(ENOTSUP));
591 if ((featureflags & DMU_BACKUP_FEATURE_LARGE_BLOCKS) &&
592 !spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_BLOCKS))
593 return (SET_ERROR(ENOTSUP));
594 if ((featureflags & DMU_BACKUP_FEATURE_LARGE_DNODE) &&
595 !spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_DNODE))
596 return (SET_ERROR(ENOTSUP));
597 if ((featureflags & DMU_BACKUP_FEATURE_LARGE_MICROZAP) &&
598 !spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_MICROZAP))
599 return (SET_ERROR(ENOTSUP));
600
601 /*
602 * Receiving redacted streams requires that redacted datasets are
603 * enabled.
604 */
605 if ((featureflags & DMU_BACKUP_FEATURE_REDACTED) &&
606 !spa_feature_is_enabled(spa, SPA_FEATURE_REDACTED_DATASETS))
607 return (SET_ERROR(ENOTSUP));
608
609 /*
610 * If the LONGNAME is not enabled on the target, fail that request.
611 */
612 if ((featureflags & DMU_BACKUP_FEATURE_LONGNAME) &&
613 !spa_feature_is_enabled(spa, SPA_FEATURE_LONGNAME))
614 return (SET_ERROR(ENOTSUP));
615
616 return (0);
617 }
618
619 static int
dmu_recv_begin_check(void * arg,dmu_tx_t * tx)620 dmu_recv_begin_check(void *arg, dmu_tx_t *tx)
621 {
622 dmu_recv_begin_arg_t *drba = arg;
623 dsl_pool_t *dp = dmu_tx_pool(tx);
624 struct drr_begin *drrb = drba->drba_cookie->drc_drrb;
625 uint64_t fromguid = drrb->drr_fromguid;
626 int flags = drrb->drr_flags;
627 ds_hold_flags_t dsflags = DS_HOLD_FLAG_NONE;
628 int error;
629 uint64_t featureflags = drba->drba_cookie->drc_featureflags;
630 dsl_dataset_t *ds;
631 const char *tofs = drba->drba_cookie->drc_tofs;
632
633 /* already checked */
634 ASSERT3U(drrb->drr_magic, ==, DMU_BACKUP_MAGIC);
635 ASSERT(!(featureflags & DMU_BACKUP_FEATURE_RESUMING));
636
637 if (DMU_GET_STREAM_HDRTYPE(drrb->drr_versioninfo) ==
638 DMU_COMPOUNDSTREAM ||
639 drrb->drr_type >= DMU_OST_NUMTYPES ||
640 ((flags & DRR_FLAG_CLONE) && drba->drba_origin == NULL))
641 return (SET_ERROR(EINVAL));
642
643 error = recv_begin_check_feature_flags_impl(featureflags, dp->dp_spa);
644 if (error != 0)
645 return (error);
646
647 /* Resumable receives require extensible datasets */
648 if (drba->drba_cookie->drc_resumable &&
649 !spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_EXTENSIBLE_DATASET))
650 return (SET_ERROR(ENOTSUP));
651
652 if (featureflags & DMU_BACKUP_FEATURE_RAW) {
653 /* raw receives require the encryption feature */
654 if (!spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_ENCRYPTION))
655 return (SET_ERROR(ENOTSUP));
656
657 /* embedded data is incompatible with encryption and raw recv */
658 if (featureflags & DMU_BACKUP_FEATURE_EMBED_DATA)
659 return (SET_ERROR(EINVAL));
660
661 /* raw receives require spill block allocation flag */
662 if (!(flags & DRR_FLAG_SPILL_BLOCK))
663 return (SET_ERROR(ZFS_ERR_SPILL_BLOCK_FLAG_MISSING));
664 } else {
665 /*
666 * We support unencrypted datasets below encrypted ones now,
667 * so add the DS_HOLD_FLAG_DECRYPT flag only if we are dealing
668 * with a dataset we may encrypt.
669 */
670 if (drba->drba_dcp == NULL ||
671 drba->drba_dcp->cp_crypt != ZIO_CRYPT_OFF) {
672 dsflags |= DS_HOLD_FLAG_DECRYPT;
673 }
674 }
675
676 error = dsl_dataset_hold_flags(dp, tofs, dsflags, FTAG, &ds);
677 if (error == 0) {
678 /* target fs already exists; recv into temp clone */
679
680 /* Can't recv a clone into an existing fs */
681 if (flags & DRR_FLAG_CLONE || drba->drba_origin) {
682 dsl_dataset_rele_flags(ds, dsflags, FTAG);
683 return (SET_ERROR(EINVAL));
684 }
685
686 error = recv_begin_check_existing_impl(drba, ds, fromguid,
687 featureflags);
688 dsl_dataset_rele_flags(ds, dsflags, FTAG);
689 } else if (error == ENOENT) {
690 /* target fs does not exist; must be a full backup or clone */
691 char buf[ZFS_MAX_DATASET_NAME_LEN];
692 objset_t *os;
693
694 /* healing recv must be done "into" an existing snapshot */
695 if (drba->drba_cookie->drc_heal == B_TRUE)
696 return (SET_ERROR(ENOTSUP));
697
698 /*
699 * If it's a non-clone incremental, we are missing the
700 * target fs, so fail the recv.
701 */
702 if (fromguid != 0 && !((flags & DRR_FLAG_CLONE) ||
703 drba->drba_origin))
704 return (SET_ERROR(ENOENT));
705
706 /*
707 * If we're receiving a full send as a clone, and it doesn't
708 * contain all the necessary free records and freeobject
709 * records, reject it.
710 */
711 if (fromguid == 0 && drba->drba_origin != NULL &&
712 !(flags & DRR_FLAG_FREERECORDS))
713 return (SET_ERROR(EINVAL));
714
715 /* Open the parent of tofs */
716 ASSERT3U(strlen(tofs), <, sizeof (buf));
717 (void) strlcpy(buf, tofs, strrchr(tofs, '/') - tofs + 1);
718 error = dsl_dataset_hold(dp, buf, FTAG, &ds);
719 if (error != 0)
720 return (error);
721
722 if ((featureflags & DMU_BACKUP_FEATURE_RAW) == 0 &&
723 drba->drba_origin == NULL) {
724 boolean_t will_encrypt;
725
726 /*
727 * Check that we aren't breaking any encryption rules
728 * and that we have all the parameters we need to
729 * create an encrypted dataset if necessary. If we are
730 * making an encrypted dataset the stream can't have
731 * embedded data.
732 */
733 error = dmu_objset_create_crypt_check(ds->ds_dir,
734 drba->drba_dcp, &will_encrypt);
735 if (error != 0) {
736 dsl_dataset_rele(ds, FTAG);
737 return (error);
738 }
739
740 if (will_encrypt &&
741 (featureflags & DMU_BACKUP_FEATURE_EMBED_DATA)) {
742 dsl_dataset_rele(ds, FTAG);
743 return (SET_ERROR(EINVAL));
744 }
745 }
746
747 /*
748 * Check filesystem and snapshot limits before receiving. We'll
749 * recheck snapshot limits again at the end (we create the
750 * filesystems and increment those counts during begin_sync).
751 */
752 error = dsl_fs_ss_limit_check(ds->ds_dir, 1,
753 ZFS_PROP_FILESYSTEM_LIMIT, NULL,
754 drba->drba_cred, drba->drba_proc);
755 if (error != 0) {
756 dsl_dataset_rele(ds, FTAG);
757 return (error);
758 }
759
760 error = dsl_fs_ss_limit_check(ds->ds_dir, 1,
761 ZFS_PROP_SNAPSHOT_LIMIT, NULL,
762 drba->drba_cred, drba->drba_proc);
763 if (error != 0) {
764 dsl_dataset_rele(ds, FTAG);
765 return (error);
766 }
767
768 /* can't recv below anything but filesystems (eg. no ZVOLs) */
769 error = dmu_objset_from_ds(ds, &os);
770 if (error != 0) {
771 dsl_dataset_rele(ds, FTAG);
772 return (error);
773 }
774 if (dmu_objset_type(os) != DMU_OST_ZFS) {
775 dsl_dataset_rele(ds, FTAG);
776 return (SET_ERROR(ZFS_ERR_WRONG_PARENT));
777 }
778
779 if (drba->drba_origin != NULL) {
780 dsl_dataset_t *origin;
781 error = dsl_dataset_hold_flags(dp, drba->drba_origin,
782 dsflags, FTAG, &origin);
783 if (error != 0) {
784 dsl_dataset_rele(ds, FTAG);
785 return (error);
786 }
787 if (!origin->ds_is_snapshot) {
788 dsl_dataset_rele_flags(origin, dsflags, FTAG);
789 dsl_dataset_rele(ds, FTAG);
790 return (SET_ERROR(EINVAL));
791 }
792 if (dsl_dataset_phys(origin)->ds_guid != fromguid &&
793 fromguid != 0) {
794 dsl_dataset_rele_flags(origin, dsflags, FTAG);
795 dsl_dataset_rele(ds, FTAG);
796 return (SET_ERROR(ENODEV));
797 }
798
799 if (origin->ds_dir->dd_crypto_obj != 0 &&
800 (featureflags & DMU_BACKUP_FEATURE_EMBED_DATA)) {
801 dsl_dataset_rele_flags(origin, dsflags, FTAG);
802 dsl_dataset_rele(ds, FTAG);
803 return (SET_ERROR(EINVAL));
804 }
805
806 /*
807 * If the origin is redacted we need to verify that this
808 * send stream can safely be received on top of the
809 * origin.
810 */
811 if (dsl_dataset_feature_is_active(origin,
812 SPA_FEATURE_REDACTED_DATASETS)) {
813 if (!redact_check(drba, origin)) {
814 dsl_dataset_rele_flags(origin, dsflags,
815 FTAG);
816 dsl_dataset_rele_flags(ds, dsflags,
817 FTAG);
818 return (SET_ERROR(EINVAL));
819 }
820 }
821
822 error = recv_check_large_blocks(ds, featureflags);
823 if (error != 0) {
824 dsl_dataset_rele_flags(origin, dsflags, FTAG);
825 dsl_dataset_rele_flags(ds, dsflags, FTAG);
826 return (error);
827 }
828
829 dsl_dataset_rele_flags(origin, dsflags, FTAG);
830 }
831
832 dsl_dataset_rele(ds, FTAG);
833 error = 0;
834 }
835 return (error);
836 }
837
838 static void
dmu_recv_begin_sync(void * arg,dmu_tx_t * tx)839 dmu_recv_begin_sync(void *arg, dmu_tx_t *tx)
840 {
841 dmu_recv_begin_arg_t *drba = arg;
842 dsl_pool_t *dp = dmu_tx_pool(tx);
843 objset_t *mos = dp->dp_meta_objset;
844 dmu_recv_cookie_t *drc = drba->drba_cookie;
845 struct drr_begin *drrb = drc->drc_drrb;
846 const char *tofs = drc->drc_tofs;
847 uint64_t featureflags = drc->drc_featureflags;
848 dsl_dataset_t *ds, *newds;
849 objset_t *os;
850 uint64_t dsobj;
851 ds_hold_flags_t dsflags = DS_HOLD_FLAG_NONE;
852 int error;
853 uint64_t crflags = 0;
854 dsl_crypto_params_t dummy_dcp = { 0 };
855 dsl_crypto_params_t *dcp = drba->drba_dcp;
856
857 if (drrb->drr_flags & DRR_FLAG_CI_DATA)
858 crflags |= DS_FLAG_CI_DATASET;
859
860 if ((featureflags & DMU_BACKUP_FEATURE_RAW) == 0)
861 dsflags |= DS_HOLD_FLAG_DECRYPT;
862
863 /*
864 * Raw, non-incremental recvs always use a dummy dcp with
865 * the raw cmd set. Raw incremental recvs do not use a dcp
866 * since the encryption parameters are already set in stone.
867 */
868 if (dcp == NULL && drrb->drr_fromguid == 0 &&
869 drba->drba_origin == NULL) {
870 ASSERT3P(dcp, ==, NULL);
871 dcp = &dummy_dcp;
872
873 if (featureflags & DMU_BACKUP_FEATURE_RAW)
874 dcp->cp_cmd = DCP_CMD_RAW_RECV;
875 }
876
877 error = dsl_dataset_hold_flags(dp, tofs, dsflags, FTAG, &ds);
878 if (error == 0) {
879 /* Create temporary clone unless we're doing corrective recv */
880 dsl_dataset_t *snap = NULL;
881
882 if (drba->drba_cookie->drc_fromsnapobj != 0) {
883 VERIFY0(dsl_dataset_hold_obj(dp,
884 drba->drba_cookie->drc_fromsnapobj, FTAG, &snap));
885 ASSERT3P(dcp, ==, NULL);
886 }
887 if (drc->drc_heal) {
888 /* When healing we want to use the provided snapshot */
889 VERIFY0(dsl_dataset_snap_lookup(ds, drc->drc_tosnap,
890 &dsobj));
891 } else {
892 dsobj = dsl_dataset_create_sync(ds->ds_dir,
893 recv_clone_name, snap, crflags, drba->drba_cred,
894 dcp, tx);
895 }
896 if (drba->drba_cookie->drc_fromsnapobj != 0)
897 dsl_dataset_rele(snap, FTAG);
898 dsl_dataset_rele_flags(ds, dsflags, FTAG);
899 } else {
900 dsl_dir_t *dd;
901 const char *tail;
902 dsl_dataset_t *origin = NULL;
903
904 VERIFY0(dsl_dir_hold(dp, tofs, FTAG, &dd, &tail));
905
906 if (drba->drba_origin != NULL) {
907 VERIFY0(dsl_dataset_hold(dp, drba->drba_origin,
908 FTAG, &origin));
909 ASSERT3P(dcp, ==, NULL);
910 }
911
912 /* Create new dataset. */
913 dsobj = dsl_dataset_create_sync(dd, strrchr(tofs, '/') + 1,
914 origin, crflags, drba->drba_cred, dcp, tx);
915 if (origin != NULL)
916 dsl_dataset_rele(origin, FTAG);
917 dsl_dir_rele(dd, FTAG);
918 drc->drc_newfs = B_TRUE;
919 }
920 VERIFY0(dsl_dataset_own_obj_force(dp, dsobj, dsflags, dmu_recv_tag,
921 &newds));
922 if (dsl_dataset_feature_is_active(newds,
923 SPA_FEATURE_REDACTED_DATASETS)) {
924 /*
925 * If the origin dataset is redacted, the child will be redacted
926 * when we create it. We clear the new dataset's
927 * redaction info; if it should be redacted, we'll fill
928 * in its information later.
929 */
930 dsl_dataset_deactivate_feature(newds,
931 SPA_FEATURE_REDACTED_DATASETS, tx);
932 }
933 VERIFY0(dmu_objset_from_ds(newds, &os));
934
935 if (drc->drc_resumable) {
936 dsl_dataset_zapify(newds, tx);
937 if (drrb->drr_fromguid != 0) {
938 VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_FROMGUID,
939 8, 1, &drrb->drr_fromguid, tx));
940 }
941 VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_TOGUID,
942 8, 1, &drrb->drr_toguid, tx));
943 VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_TONAME,
944 1, strlen(drrb->drr_toname) + 1, drrb->drr_toname, tx));
945 uint64_t one = 1;
946 uint64_t zero = 0;
947 VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_OBJECT,
948 8, 1, &one, tx));
949 VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_OFFSET,
950 8, 1, &zero, tx));
951 VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_BYTES,
952 8, 1, &zero, tx));
953 if (featureflags & DMU_BACKUP_FEATURE_LARGE_BLOCKS) {
954 VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_LARGEBLOCK,
955 8, 1, &one, tx));
956 }
957 if (featureflags & DMU_BACKUP_FEATURE_EMBED_DATA) {
958 VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_EMBEDOK,
959 8, 1, &one, tx));
960 }
961 if (featureflags & DMU_BACKUP_FEATURE_COMPRESSED) {
962 VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_COMPRESSOK,
963 8, 1, &one, tx));
964 }
965 if (featureflags & DMU_BACKUP_FEATURE_RAW) {
966 VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_RAWOK,
967 8, 1, &one, tx));
968 }
969
970 uint64_t *redact_snaps;
971 uint_t numredactsnaps;
972 if (nvlist_lookup_uint64_array(drc->drc_begin_nvl,
973 BEGINNV_REDACT_FROM_SNAPS, &redact_snaps,
974 &numredactsnaps) == 0) {
975 VERIFY0(zap_add(mos, dsobj,
976 DS_FIELD_RESUME_REDACT_BOOKMARK_SNAPS,
977 sizeof (*redact_snaps), numredactsnaps,
978 redact_snaps, tx));
979 }
980 }
981
982 /*
983 * Usually the os->os_encrypted value is tied to the presence of a
984 * DSL Crypto Key object in the dd. However, that will not be received
985 * until dmu_recv_stream(), so we set the value manually for now.
986 */
987 if (featureflags & DMU_BACKUP_FEATURE_RAW) {
988 os->os_encrypted = B_TRUE;
989 drba->drba_cookie->drc_raw = B_TRUE;
990 }
991
992 if (featureflags & DMU_BACKUP_FEATURE_REDACTED) {
993 uint64_t *redact_snaps;
994 uint_t numredactsnaps;
995 VERIFY0(nvlist_lookup_uint64_array(drc->drc_begin_nvl,
996 BEGINNV_REDACT_SNAPS, &redact_snaps, &numredactsnaps));
997 dsl_dataset_activate_redaction(newds, redact_snaps,
998 numredactsnaps, tx);
999 }
1000
1001 if (featureflags & DMU_BACKUP_FEATURE_LARGE_MICROZAP) {
1002 /*
1003 * The source has seen a large microzap at least once in its
1004 * life, so we activate the feature here to match. It's not
1005 * strictly necessary since a large microzap is usable without
1006 * the feature active, but if that object is sent on from here,
1007 * we need this info to know to add the stream feature.
1008 *
1009 * There may be no large microzap in the incoming stream, or
1010 * ever again, but this is a very niche feature and its very
1011 * difficult to spot a large microzap in the stream, so its
1012 * not worth the effort of trying harder to activate the
1013 * feature at first use.
1014 */
1015 dsl_dataset_activate_feature(dsobj, SPA_FEATURE_LARGE_MICROZAP,
1016 (void *)B_TRUE, tx);
1017 }
1018
1019 dmu_buf_will_dirty(newds->ds_dbuf, tx);
1020 dsl_dataset_phys(newds)->ds_flags |= DS_FLAG_INCONSISTENT;
1021
1022 /*
1023 * Activate longname feature if received
1024 */
1025 if (featureflags & DMU_BACKUP_FEATURE_LONGNAME &&
1026 !dsl_dataset_feature_is_active(newds, SPA_FEATURE_LONGNAME)) {
1027 dsl_dataset_activate_feature(newds->ds_object,
1028 SPA_FEATURE_LONGNAME, (void *)B_TRUE, tx);
1029 newds->ds_feature[SPA_FEATURE_LONGNAME] = (void *)B_TRUE;
1030 }
1031
1032 /*
1033 * If we actually created a non-clone, we need to create the objset
1034 * in our new dataset. If this is a raw send we postpone this until
1035 * dmu_recv_stream() so that we can allocate the metadnode with the
1036 * properties from the DRR_BEGIN payload.
1037 */
1038 rrw_enter(&newds->ds_bp_rwlock, RW_READER, FTAG);
1039 if (BP_IS_HOLE(dsl_dataset_get_blkptr(newds)) &&
1040 (featureflags & DMU_BACKUP_FEATURE_RAW) == 0 &&
1041 !drc->drc_heal) {
1042 (void) dmu_objset_create_impl(dp->dp_spa,
1043 newds, dsl_dataset_get_blkptr(newds), drrb->drr_type, tx);
1044 }
1045 rrw_exit(&newds->ds_bp_rwlock, FTAG);
1046
1047 drba->drba_cookie->drc_ds = newds;
1048 drba->drba_cookie->drc_os = os;
1049
1050 spa_history_log_internal_ds(newds, "receive", tx, " ");
1051 }
1052
1053 static int
dmu_recv_resume_begin_check(void * arg,dmu_tx_t * tx)1054 dmu_recv_resume_begin_check(void *arg, dmu_tx_t *tx)
1055 {
1056 dmu_recv_begin_arg_t *drba = arg;
1057 dmu_recv_cookie_t *drc = drba->drba_cookie;
1058 dsl_pool_t *dp = dmu_tx_pool(tx);
1059 struct drr_begin *drrb = drc->drc_drrb;
1060 int error;
1061 ds_hold_flags_t dsflags = DS_HOLD_FLAG_NONE;
1062 dsl_dataset_t *ds;
1063 const char *tofs = drc->drc_tofs;
1064
1065 /* already checked */
1066 ASSERT3U(drrb->drr_magic, ==, DMU_BACKUP_MAGIC);
1067 ASSERT(drc->drc_featureflags & DMU_BACKUP_FEATURE_RESUMING);
1068
1069 if (DMU_GET_STREAM_HDRTYPE(drrb->drr_versioninfo) ==
1070 DMU_COMPOUNDSTREAM ||
1071 drrb->drr_type >= DMU_OST_NUMTYPES)
1072 return (SET_ERROR(EINVAL));
1073
1074 /*
1075 * This is mostly a sanity check since we should have already done these
1076 * checks during a previous attempt to receive the data.
1077 */
1078 error = recv_begin_check_feature_flags_impl(drc->drc_featureflags,
1079 dp->dp_spa);
1080 if (error != 0)
1081 return (error);
1082
1083 /* 6 extra bytes for /%recv */
1084 char recvname[ZFS_MAX_DATASET_NAME_LEN + 6];
1085
1086 (void) snprintf(recvname, sizeof (recvname), "%s/%s",
1087 tofs, recv_clone_name);
1088
1089 if (drc->drc_featureflags & DMU_BACKUP_FEATURE_RAW) {
1090 /* raw receives require spill block allocation flag */
1091 if (!(drrb->drr_flags & DRR_FLAG_SPILL_BLOCK))
1092 return (SET_ERROR(ZFS_ERR_SPILL_BLOCK_FLAG_MISSING));
1093 } else {
1094 dsflags |= DS_HOLD_FLAG_DECRYPT;
1095 }
1096
1097 boolean_t recvexist = B_TRUE;
1098 if (dsl_dataset_hold_flags(dp, recvname, dsflags, FTAG, &ds) != 0) {
1099 /* %recv does not exist; continue in tofs */
1100 recvexist = B_FALSE;
1101 error = dsl_dataset_hold_flags(dp, tofs, dsflags, FTAG, &ds);
1102 if (error != 0)
1103 return (error);
1104 }
1105
1106 /*
1107 * Resume of full/newfs recv on existing dataset should be done with
1108 * force flag
1109 */
1110 if (recvexist && drrb->drr_fromguid == 0 && !drc->drc_force) {
1111 dsl_dataset_rele_flags(ds, dsflags, FTAG);
1112 return (SET_ERROR(ZFS_ERR_RESUME_EXISTS));
1113 }
1114
1115 /* check that ds is marked inconsistent */
1116 if (!DS_IS_INCONSISTENT(ds)) {
1117 dsl_dataset_rele_flags(ds, dsflags, FTAG);
1118 return (SET_ERROR(EINVAL));
1119 }
1120
1121 /* check that there is resuming data, and that the toguid matches */
1122 if (!dsl_dataset_is_zapified(ds)) {
1123 dsl_dataset_rele_flags(ds, dsflags, FTAG);
1124 return (SET_ERROR(EINVAL));
1125 }
1126 uint64_t val;
1127 error = zap_lookup(dp->dp_meta_objset, ds->ds_object,
1128 DS_FIELD_RESUME_TOGUID, sizeof (val), 1, &val);
1129 if (error != 0 || drrb->drr_toguid != val) {
1130 dsl_dataset_rele_flags(ds, dsflags, FTAG);
1131 return (SET_ERROR(EINVAL));
1132 }
1133
1134 /*
1135 * Check if the receive is still running. If so, it will be owned.
1136 * Note that nothing else can own the dataset (e.g. after the receive
1137 * fails) because it will be marked inconsistent.
1138 */
1139 if (dsl_dataset_has_owner(ds)) {
1140 dsl_dataset_rele_flags(ds, dsflags, FTAG);
1141 return (SET_ERROR(EBUSY));
1142 }
1143
1144 /* There should not be any snapshots of this fs yet. */
1145 if (ds->ds_prev != NULL && ds->ds_prev->ds_dir == ds->ds_dir) {
1146 dsl_dataset_rele_flags(ds, dsflags, FTAG);
1147 return (SET_ERROR(EINVAL));
1148 }
1149
1150 /*
1151 * Note: resume point will be checked when we process the first WRITE
1152 * record.
1153 */
1154
1155 /* check that the origin matches */
1156 val = 0;
1157 (void) zap_lookup(dp->dp_meta_objset, ds->ds_object,
1158 DS_FIELD_RESUME_FROMGUID, sizeof (val), 1, &val);
1159 if (drrb->drr_fromguid != val) {
1160 dsl_dataset_rele_flags(ds, dsflags, FTAG);
1161 return (SET_ERROR(EINVAL));
1162 }
1163
1164 if (ds->ds_prev != NULL && drrb->drr_fromguid != 0)
1165 drc->drc_fromsnapobj = ds->ds_prev->ds_object;
1166
1167 /*
1168 * If we're resuming, and the send is redacted, then the original send
1169 * must have been redacted, and must have been redacted with respect to
1170 * the same snapshots.
1171 */
1172 if (drc->drc_featureflags & DMU_BACKUP_FEATURE_REDACTED) {
1173 uint64_t num_ds_redact_snaps;
1174 uint64_t *ds_redact_snaps;
1175
1176 uint_t num_stream_redact_snaps;
1177 uint64_t *stream_redact_snaps;
1178
1179 if (nvlist_lookup_uint64_array(drc->drc_begin_nvl,
1180 BEGINNV_REDACT_SNAPS, &stream_redact_snaps,
1181 &num_stream_redact_snaps) != 0) {
1182 dsl_dataset_rele_flags(ds, dsflags, FTAG);
1183 return (SET_ERROR(EINVAL));
1184 }
1185
1186 if (!dsl_dataset_get_uint64_array_feature(ds,
1187 SPA_FEATURE_REDACTED_DATASETS, &num_ds_redact_snaps,
1188 &ds_redact_snaps)) {
1189 dsl_dataset_rele_flags(ds, dsflags, FTAG);
1190 return (SET_ERROR(EINVAL));
1191 }
1192
1193 for (int i = 0; i < num_ds_redact_snaps; i++) {
1194 if (!redact_snaps_contains(ds_redact_snaps,
1195 num_ds_redact_snaps, stream_redact_snaps[i])) {
1196 dsl_dataset_rele_flags(ds, dsflags, FTAG);
1197 return (SET_ERROR(EINVAL));
1198 }
1199 }
1200 }
1201
1202 error = recv_check_large_blocks(ds, drc->drc_featureflags);
1203 if (error != 0) {
1204 dsl_dataset_rele_flags(ds, dsflags, FTAG);
1205 return (error);
1206 }
1207
1208 dsl_dataset_rele_flags(ds, dsflags, FTAG);
1209 return (0);
1210 }
1211
1212 static void
dmu_recv_resume_begin_sync(void * arg,dmu_tx_t * tx)1213 dmu_recv_resume_begin_sync(void *arg, dmu_tx_t *tx)
1214 {
1215 dmu_recv_begin_arg_t *drba = arg;
1216 dsl_pool_t *dp = dmu_tx_pool(tx);
1217 const char *tofs = drba->drba_cookie->drc_tofs;
1218 uint64_t featureflags = drba->drba_cookie->drc_featureflags;
1219 dsl_dataset_t *ds;
1220 ds_hold_flags_t dsflags = DS_HOLD_FLAG_NONE;
1221 /* 6 extra bytes for /%recv */
1222 char recvname[ZFS_MAX_DATASET_NAME_LEN + 6];
1223
1224 (void) snprintf(recvname, sizeof (recvname), "%s/%s", tofs,
1225 recv_clone_name);
1226
1227 if (featureflags & DMU_BACKUP_FEATURE_RAW) {
1228 drba->drba_cookie->drc_raw = B_TRUE;
1229 } else {
1230 dsflags |= DS_HOLD_FLAG_DECRYPT;
1231 }
1232
1233 if (dsl_dataset_own_force(dp, recvname, dsflags, dmu_recv_tag, &ds)
1234 != 0) {
1235 /* %recv does not exist; continue in tofs */
1236 VERIFY0(dsl_dataset_own_force(dp, tofs, dsflags, dmu_recv_tag,
1237 &ds));
1238 drba->drba_cookie->drc_newfs = B_TRUE;
1239 }
1240
1241 ASSERT(DS_IS_INCONSISTENT(ds));
1242 rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);
1243 ASSERT(!BP_IS_HOLE(dsl_dataset_get_blkptr(ds)) ||
1244 drba->drba_cookie->drc_raw);
1245 rrw_exit(&ds->ds_bp_rwlock, FTAG);
1246
1247 drba->drba_cookie->drc_ds = ds;
1248 VERIFY0(dmu_objset_from_ds(ds, &drba->drba_cookie->drc_os));
1249 drba->drba_cookie->drc_should_save = B_TRUE;
1250
1251 spa_history_log_internal_ds(ds, "resume receive", tx, " ");
1252 }
1253
1254 /*
1255 * NB: callers *MUST* call dmu_recv_stream() if dmu_recv_begin()
1256 * succeeds; otherwise we will leak the holds on the datasets.
1257 */
1258 int
dmu_recv_begin(const char * tofs,const char * tosnap,dmu_replay_record_t * drr_begin,boolean_t force,boolean_t heal,boolean_t resumable,nvlist_t * localprops,nvlist_t * hidden_args,const char * origin,dmu_recv_cookie_t * drc,zfs_file_t * fp,offset_t * voffp)1259 dmu_recv_begin(const char *tofs, const char *tosnap,
1260 dmu_replay_record_t *drr_begin, boolean_t force, boolean_t heal,
1261 boolean_t resumable, nvlist_t *localprops, nvlist_t *hidden_args,
1262 const char *origin, dmu_recv_cookie_t *drc, zfs_file_t *fp,
1263 offset_t *voffp)
1264 {
1265 dmu_recv_begin_arg_t drba = { 0 };
1266 int err = 0;
1267
1268 memset(drc, 0, sizeof (dmu_recv_cookie_t));
1269 drc->drc_drr_begin = drr_begin;
1270 drc->drc_drrb = &drr_begin->drr_u.drr_begin;
1271 drc->drc_tosnap = tosnap;
1272 drc->drc_tofs = tofs;
1273 drc->drc_force = force;
1274 drc->drc_heal = heal;
1275 drc->drc_resumable = resumable;
1276 drc->drc_cred = CRED();
1277 drc->drc_proc = curproc;
1278 drc->drc_clone = (origin != NULL);
1279
1280 if (drc->drc_drrb->drr_magic == BSWAP_64(DMU_BACKUP_MAGIC)) {
1281 drc->drc_byteswap = B_TRUE;
1282 (void) fletcher_4_incremental_byteswap(drr_begin,
1283 sizeof (dmu_replay_record_t), &drc->drc_cksum);
1284 byteswap_record(drr_begin);
1285 } else if (drc->drc_drrb->drr_magic == DMU_BACKUP_MAGIC) {
1286 (void) fletcher_4_incremental_native(drr_begin,
1287 sizeof (dmu_replay_record_t), &drc->drc_cksum);
1288 } else {
1289 return (SET_ERROR(EINVAL));
1290 }
1291
1292 drc->drc_fp = fp;
1293 drc->drc_voff = *voffp;
1294 drc->drc_featureflags =
1295 DMU_GET_FEATUREFLAGS(drc->drc_drrb->drr_versioninfo);
1296
1297 uint32_t payloadlen = drc->drc_drr_begin->drr_payloadlen;
1298
1299 /*
1300 * Since OpenZFS 2.0.0, we have enforced a 64MB limit in userspace
1301 * configurable via ZFS_SENDRECV_MAX_NVLIST. We enforce 256MB as a hard
1302 * upper limit. Systems with less than 1GB of RAM will see a lower
1303 * limit from `arc_all_memory() / 4`.
1304 */
1305 if (payloadlen > (MIN((1U << 28), arc_all_memory() / 4)))
1306 return (E2BIG);
1307
1308
1309 if (payloadlen != 0) {
1310 void *payload = vmem_alloc(payloadlen, KM_SLEEP);
1311 /*
1312 * For compatibility with recursive send streams, we don't do
1313 * this here if the stream could be part of a package. Instead,
1314 * we'll do it in dmu_recv_stream. If we pull the next header
1315 * too early, and it's the END record, we break the `recv_skip`
1316 * logic.
1317 */
1318
1319 err = receive_read_payload_and_next_header(drc, payloadlen,
1320 payload);
1321 if (err != 0) {
1322 vmem_free(payload, payloadlen);
1323 return (err);
1324 }
1325 err = nvlist_unpack(payload, payloadlen, &drc->drc_begin_nvl,
1326 KM_SLEEP);
1327 vmem_free(payload, payloadlen);
1328 if (err != 0) {
1329 kmem_free(drc->drc_next_rrd,
1330 sizeof (*drc->drc_next_rrd));
1331 return (err);
1332 }
1333 }
1334
1335 if (drc->drc_drrb->drr_flags & DRR_FLAG_SPILL_BLOCK)
1336 drc->drc_spill = B_TRUE;
1337
1338 drba.drba_origin = origin;
1339 drba.drba_cookie = drc;
1340 drba.drba_cred = CRED();
1341 drba.drba_proc = curproc;
1342
1343 if (drc->drc_featureflags & DMU_BACKUP_FEATURE_RESUMING) {
1344 err = dsl_sync_task(tofs,
1345 dmu_recv_resume_begin_check, dmu_recv_resume_begin_sync,
1346 &drba, 5, ZFS_SPACE_CHECK_NORMAL);
1347 } else {
1348 /*
1349 * For non-raw, non-incremental, non-resuming receives the
1350 * user can specify encryption parameters on the command line
1351 * with "zfs recv -o". For these receives we create a dcp and
1352 * pass it to the sync task. Creating the dcp will implicitly
1353 * remove the encryption params from the localprops nvlist,
1354 * which avoids errors when trying to set these normally
1355 * read-only properties. Any other kind of receive that
1356 * attempts to set these properties will fail as a result.
1357 */
1358 if ((DMU_GET_FEATUREFLAGS(drc->drc_drrb->drr_versioninfo) &
1359 DMU_BACKUP_FEATURE_RAW) == 0 &&
1360 origin == NULL && drc->drc_drrb->drr_fromguid == 0) {
1361 err = dsl_crypto_params_create_nvlist(DCP_CMD_NONE,
1362 localprops, hidden_args, &drba.drba_dcp);
1363 }
1364
1365 if (err == 0) {
1366 err = dsl_sync_task(tofs,
1367 dmu_recv_begin_check, dmu_recv_begin_sync,
1368 &drba, 5, ZFS_SPACE_CHECK_NORMAL);
1369 dsl_crypto_params_free(drba.drba_dcp, !!err);
1370 }
1371 }
1372
1373 if (err != 0) {
1374 kmem_free(drc->drc_next_rrd, sizeof (*drc->drc_next_rrd));
1375 nvlist_free(drc->drc_begin_nvl);
1376 }
1377 return (err);
1378 }
1379
1380 /*
1381 * Holds data need for corrective recv callback
1382 */
1383 typedef struct cr_cb_data {
1384 uint64_t size;
1385 zbookmark_phys_t zb;
1386 spa_t *spa;
1387 } cr_cb_data_t;
1388
1389 static void
corrective_read_done(zio_t * zio)1390 corrective_read_done(zio_t *zio)
1391 {
1392 cr_cb_data_t *data = zio->io_private;
1393 /* Corruption corrected; update error log if needed */
1394 if (zio->io_error == 0) {
1395 spa_remove_error(data->spa, &data->zb,
1396 BP_GET_LOGICAL_BIRTH(zio->io_bp));
1397 }
1398 kmem_free(data, sizeof (cr_cb_data_t));
1399 abd_free(zio->io_abd);
1400 }
1401
1402 /*
1403 * zio_rewrite the data pointed to by bp with the data from the rrd's abd.
1404 */
1405 static int
do_corrective_recv(struct receive_writer_arg * rwa,struct drr_write * drrw,struct receive_record_arg * rrd,blkptr_t * bp)1406 do_corrective_recv(struct receive_writer_arg *rwa, struct drr_write *drrw,
1407 struct receive_record_arg *rrd, blkptr_t *bp)
1408 {
1409 int err;
1410 zio_t *io;
1411 zbookmark_phys_t zb;
1412 dnode_t *dn;
1413 abd_t *abd = rrd->abd;
1414 zio_cksum_t bp_cksum = bp->blk_cksum;
1415 zio_flag_t flags = ZIO_FLAG_SPECULATIVE | ZIO_FLAG_DONT_RETRY |
1416 ZIO_FLAG_CANFAIL;
1417
1418 if (rwa->raw)
1419 flags |= ZIO_FLAG_RAW;
1420
1421 err = dnode_hold(rwa->os, drrw->drr_object, FTAG, &dn);
1422 if (err != 0)
1423 return (err);
1424 SET_BOOKMARK(&zb, dmu_objset_id(rwa->os), drrw->drr_object, 0,
1425 dbuf_whichblock(dn, 0, drrw->drr_offset));
1426 dnode_rele(dn, FTAG);
1427
1428 if (!rwa->raw && DRR_WRITE_COMPRESSED(drrw)) {
1429 /* Decompress the stream data */
1430 abd_t *dabd = abd_alloc_linear(
1431 drrw->drr_logical_size, B_FALSE);
1432 err = zio_decompress_data(drrw->drr_compressiontype,
1433 abd, dabd, abd_get_size(abd),
1434 abd_get_size(dabd), NULL);
1435
1436 if (err != 0) {
1437 abd_free(dabd);
1438 return (err);
1439 }
1440 /* Swap in the newly decompressed data into the abd */
1441 abd_free(abd);
1442 abd = dabd;
1443 }
1444
1445 if (!rwa->raw && BP_GET_COMPRESS(bp) != ZIO_COMPRESS_OFF) {
1446 /* Recompress the data */
1447 abd_t *cabd = abd_alloc_linear(BP_GET_PSIZE(bp),
1448 B_FALSE);
1449 uint64_t csize = zio_compress_data(BP_GET_COMPRESS(bp),
1450 abd, &cabd, abd_get_size(abd), BP_GET_PSIZE(bp),
1451 rwa->os->os_complevel);
1452 abd_zero_off(cabd, csize, BP_GET_PSIZE(bp) - csize);
1453 /* Swap in newly compressed data into the abd */
1454 abd_free(abd);
1455 abd = cabd;
1456 flags |= ZIO_FLAG_RAW_COMPRESS;
1457 }
1458
1459 /*
1460 * The stream is not encrypted but the data on-disk is.
1461 * We need to re-encrypt the buf using the same
1462 * encryption type, salt, iv, and mac that was used to encrypt
1463 * the block previosly.
1464 */
1465 if (!rwa->raw && BP_USES_CRYPT(bp)) {
1466 dsl_dataset_t *ds;
1467 dsl_crypto_key_t *dck = NULL;
1468 uint8_t salt[ZIO_DATA_SALT_LEN];
1469 uint8_t iv[ZIO_DATA_IV_LEN];
1470 uint8_t mac[ZIO_DATA_MAC_LEN];
1471 boolean_t no_crypt = B_FALSE;
1472 dsl_pool_t *dp = dmu_objset_pool(rwa->os);
1473 abd_t *eabd = abd_alloc_linear(BP_GET_PSIZE(bp), B_FALSE);
1474
1475 zio_crypt_decode_params_bp(bp, salt, iv);
1476 zio_crypt_decode_mac_bp(bp, mac);
1477
1478 dsl_pool_config_enter(dp, FTAG);
1479 err = dsl_dataset_hold_flags(dp, rwa->tofs,
1480 DS_HOLD_FLAG_DECRYPT, FTAG, &ds);
1481 if (err != 0) {
1482 dsl_pool_config_exit(dp, FTAG);
1483 abd_free(eabd);
1484 return (SET_ERROR(EACCES));
1485 }
1486
1487 /* Look up the key from the spa's keystore */
1488 err = spa_keystore_lookup_key(rwa->os->os_spa,
1489 zb.zb_objset, FTAG, &dck);
1490 if (err != 0) {
1491 dsl_dataset_rele_flags(ds, DS_HOLD_FLAG_DECRYPT,
1492 FTAG);
1493 dsl_pool_config_exit(dp, FTAG);
1494 abd_free(eabd);
1495 return (SET_ERROR(EACCES));
1496 }
1497
1498 err = zio_do_crypt_abd(B_TRUE, &dck->dck_key,
1499 BP_GET_TYPE(bp), BP_SHOULD_BYTESWAP(bp), salt, iv,
1500 mac, abd_get_size(abd), abd, eabd, &no_crypt);
1501
1502 spa_keystore_dsl_key_rele(rwa->os->os_spa, dck, FTAG);
1503 dsl_dataset_rele_flags(ds, DS_HOLD_FLAG_DECRYPT, FTAG);
1504 dsl_pool_config_exit(dp, FTAG);
1505
1506 ASSERT0(no_crypt);
1507 if (err != 0) {
1508 abd_free(eabd);
1509 return (err);
1510 }
1511 /* Swap in the newly encrypted data into the abd */
1512 abd_free(abd);
1513 abd = eabd;
1514
1515 /*
1516 * We want to prevent zio_rewrite() from trying to
1517 * encrypt the data again
1518 */
1519 flags |= ZIO_FLAG_RAW_ENCRYPT;
1520 }
1521 rrd->abd = abd;
1522
1523 io = zio_rewrite(NULL, rwa->os->os_spa, BP_GET_LOGICAL_BIRTH(bp), bp,
1524 abd, BP_GET_PSIZE(bp), NULL, NULL, ZIO_PRIORITY_SYNC_WRITE, flags,
1525 &zb);
1526
1527 ASSERT(abd_get_size(abd) == BP_GET_LSIZE(bp) ||
1528 abd_get_size(abd) == BP_GET_PSIZE(bp));
1529
1530 /* compute new bp checksum value and make sure it matches the old one */
1531 zio_checksum_compute(io, BP_GET_CHECKSUM(bp), abd, abd_get_size(abd));
1532 if (!ZIO_CHECKSUM_EQUAL(bp_cksum, io->io_bp->blk_cksum)) {
1533 zio_destroy(io);
1534 if (zfs_recv_best_effort_corrective != 0)
1535 return (0);
1536 return (SET_ERROR(ECKSUM));
1537 }
1538
1539 /* Correct the corruption in place */
1540 err = zio_wait(io);
1541 if (err == 0) {
1542 cr_cb_data_t *cb_data =
1543 kmem_alloc(sizeof (cr_cb_data_t), KM_SLEEP);
1544 cb_data->spa = rwa->os->os_spa;
1545 cb_data->size = drrw->drr_logical_size;
1546 cb_data->zb = zb;
1547 /* Test if healing worked by re-reading the bp */
1548 err = zio_wait(zio_read(rwa->heal_pio, rwa->os->os_spa, bp,
1549 abd_alloc_for_io(drrw->drr_logical_size, B_FALSE),
1550 drrw->drr_logical_size, corrective_read_done,
1551 cb_data, ZIO_PRIORITY_ASYNC_READ, flags, NULL));
1552 }
1553 if (err != 0 && zfs_recv_best_effort_corrective != 0)
1554 err = 0;
1555
1556 return (err);
1557 }
1558
1559 static int
receive_read(dmu_recv_cookie_t * drc,int len,void * buf)1560 receive_read(dmu_recv_cookie_t *drc, int len, void *buf)
1561 {
1562 int done = 0;
1563
1564 /*
1565 * The code doesn't rely on this (lengths being multiples of 8). See
1566 * comment in dump_bytes.
1567 */
1568 ASSERT(len % 8 == 0 ||
1569 (drc->drc_featureflags & DMU_BACKUP_FEATURE_RAW) != 0);
1570
1571 while (done < len) {
1572 ssize_t resid = len - done;
1573 zfs_file_t *fp = drc->drc_fp;
1574 int err = zfs_file_read(fp, (char *)buf + done,
1575 len - done, &resid);
1576 if (err == 0 && resid == len - done) {
1577 /*
1578 * Note: ECKSUM or ZFS_ERR_STREAM_TRUNCATED indicates
1579 * that the receive was interrupted and can
1580 * potentially be resumed.
1581 */
1582 err = SET_ERROR(ZFS_ERR_STREAM_TRUNCATED);
1583 }
1584 drc->drc_voff += len - done - resid;
1585 done = len - resid;
1586 if (err != 0)
1587 return (err);
1588 }
1589
1590 drc->drc_bytes_read += len;
1591
1592 ASSERT3U(done, ==, len);
1593 return (0);
1594 }
1595
1596 static inline uint8_t
deduce_nblkptr(dmu_object_type_t bonus_type,uint64_t bonus_size)1597 deduce_nblkptr(dmu_object_type_t bonus_type, uint64_t bonus_size)
1598 {
1599 if (bonus_type == DMU_OT_SA) {
1600 return (1);
1601 } else {
1602 return (1 +
1603 ((DN_OLD_MAX_BONUSLEN -
1604 MIN(DN_OLD_MAX_BONUSLEN, bonus_size)) >> SPA_BLKPTRSHIFT));
1605 }
1606 }
1607
1608 static void
save_resume_state(struct receive_writer_arg * rwa,uint64_t object,uint64_t offset,dmu_tx_t * tx)1609 save_resume_state(struct receive_writer_arg *rwa,
1610 uint64_t object, uint64_t offset, dmu_tx_t *tx)
1611 {
1612 int txgoff = dmu_tx_get_txg(tx) & TXG_MASK;
1613
1614 if (!rwa->resumable)
1615 return;
1616
1617 /*
1618 * We use ds_resume_bytes[] != 0 to indicate that we need to
1619 * update this on disk, so it must not be 0.
1620 */
1621 ASSERT(rwa->bytes_read != 0);
1622
1623 /*
1624 * We only resume from write records, which have a valid
1625 * (non-meta-dnode) object number.
1626 */
1627 ASSERT(object != 0);
1628
1629 /*
1630 * For resuming to work correctly, we must receive records in order,
1631 * sorted by object,offset. This is checked by the callers, but
1632 * assert it here for good measure.
1633 */
1634 ASSERT3U(object, >=, rwa->os->os_dsl_dataset->ds_resume_object[txgoff]);
1635 ASSERT(object != rwa->os->os_dsl_dataset->ds_resume_object[txgoff] ||
1636 offset >= rwa->os->os_dsl_dataset->ds_resume_offset[txgoff]);
1637 ASSERT3U(rwa->bytes_read, >=,
1638 rwa->os->os_dsl_dataset->ds_resume_bytes[txgoff]);
1639
1640 rwa->os->os_dsl_dataset->ds_resume_object[txgoff] = object;
1641 rwa->os->os_dsl_dataset->ds_resume_offset[txgoff] = offset;
1642 rwa->os->os_dsl_dataset->ds_resume_bytes[txgoff] = rwa->bytes_read;
1643 }
1644
1645 static int
receive_object_is_same_generation(objset_t * os,uint64_t object,dmu_object_type_t old_bonus_type,dmu_object_type_t new_bonus_type,const void * new_bonus,boolean_t * samegenp)1646 receive_object_is_same_generation(objset_t *os, uint64_t object,
1647 dmu_object_type_t old_bonus_type, dmu_object_type_t new_bonus_type,
1648 const void *new_bonus, boolean_t *samegenp)
1649 {
1650 zfs_file_info_t zoi;
1651 int err;
1652
1653 dmu_buf_t *old_bonus_dbuf;
1654 err = dmu_bonus_hold(os, object, FTAG, &old_bonus_dbuf);
1655 if (err != 0)
1656 return (err);
1657 err = dmu_get_file_info(os, old_bonus_type, old_bonus_dbuf->db_data,
1658 &zoi);
1659 dmu_buf_rele(old_bonus_dbuf, FTAG);
1660 if (err != 0)
1661 return (err);
1662 uint64_t old_gen = zoi.zfi_generation;
1663
1664 err = dmu_get_file_info(os, new_bonus_type, new_bonus, &zoi);
1665 if (err != 0)
1666 return (err);
1667 uint64_t new_gen = zoi.zfi_generation;
1668
1669 *samegenp = (old_gen == new_gen);
1670 return (0);
1671 }
1672
1673 static int
receive_handle_existing_object(const struct receive_writer_arg * rwa,const struct drr_object * drro,const dmu_object_info_t * doi,const void * bonus_data,uint64_t * object_to_hold,uint32_t * new_blksz)1674 receive_handle_existing_object(const struct receive_writer_arg *rwa,
1675 const struct drr_object *drro, const dmu_object_info_t *doi,
1676 const void *bonus_data,
1677 uint64_t *object_to_hold, uint32_t *new_blksz)
1678 {
1679 uint32_t indblksz = drro->drr_indblkshift ?
1680 1ULL << drro->drr_indblkshift : 0;
1681 int nblkptr = deduce_nblkptr(drro->drr_bonustype,
1682 drro->drr_bonuslen);
1683 uint8_t dn_slots = drro->drr_dn_slots != 0 ?
1684 drro->drr_dn_slots : DNODE_MIN_SLOTS;
1685 boolean_t do_free_range = B_FALSE;
1686 int err;
1687
1688 *object_to_hold = drro->drr_object;
1689
1690 /* nblkptr should be bounded by the bonus size and type */
1691 if (rwa->raw && nblkptr != drro->drr_nblkptr)
1692 return (SET_ERROR(EINVAL));
1693
1694 /*
1695 * After the previous send stream, the sending system may
1696 * have freed this object, and then happened to re-allocate
1697 * this object number in a later txg. In this case, we are
1698 * receiving a different logical file, and the block size may
1699 * appear to be different. i.e. we may have a different
1700 * block size for this object than what the send stream says.
1701 * In this case we need to remove the object's contents,
1702 * so that its structure can be changed and then its contents
1703 * entirely replaced by subsequent WRITE records.
1704 *
1705 * If this is a -L (--large-block) incremental stream, and
1706 * the previous stream was not -L, the block size may appear
1707 * to increase. i.e. we may have a smaller block size for
1708 * this object than what the send stream says. In this case
1709 * we need to keep the object's contents and block size
1710 * intact, so that we don't lose parts of the object's
1711 * contents that are not changed by this incremental send
1712 * stream.
1713 *
1714 * We can distinguish between the two above cases by using
1715 * the ZPL's generation number (see
1716 * receive_object_is_same_generation()). However, we only
1717 * want to rely on the generation number when absolutely
1718 * necessary, because with raw receives, the generation is
1719 * encrypted. We also want to minimize dependence on the
1720 * ZPL, so that other types of datasets can also be received
1721 * (e.g. ZVOLs, although note that ZVOLS currently do not
1722 * reallocate their objects or change their structure).
1723 * Therefore, we check a number of different cases where we
1724 * know it is safe to discard the object's contents, before
1725 * using the ZPL's generation number to make the above
1726 * distinction.
1727 */
1728 if (drro->drr_blksz != doi->doi_data_block_size) {
1729 if (rwa->raw) {
1730 /*
1731 * RAW streams always have large blocks, so
1732 * we are sure that the data is not needed
1733 * due to changing --large-block to be on.
1734 * Which is fortunate since the bonus buffer
1735 * (which contains the ZPL generation) is
1736 * encrypted, and the key might not be
1737 * loaded.
1738 */
1739 do_free_range = B_TRUE;
1740 } else if (rwa->full) {
1741 /*
1742 * This is a full send stream, so it always
1743 * replaces what we have. Even if the
1744 * generation numbers happen to match, this
1745 * can not actually be the same logical file.
1746 * This is relevant when receiving a full
1747 * send as a clone.
1748 */
1749 do_free_range = B_TRUE;
1750 } else if (drro->drr_type !=
1751 DMU_OT_PLAIN_FILE_CONTENTS ||
1752 doi->doi_type != DMU_OT_PLAIN_FILE_CONTENTS) {
1753 /*
1754 * PLAIN_FILE_CONTENTS are the only type of
1755 * objects that have ever been stored with
1756 * large blocks, so we don't need the special
1757 * logic below. ZAP blocks can shrink (when
1758 * there's only one block), so we don't want
1759 * to hit the error below about block size
1760 * only increasing.
1761 */
1762 do_free_range = B_TRUE;
1763 } else if (doi->doi_max_offset <=
1764 doi->doi_data_block_size) {
1765 /*
1766 * There is only one block. We can free it,
1767 * because its contents will be replaced by a
1768 * WRITE record. This can not be the no-L ->
1769 * -L case, because the no-L case would have
1770 * resulted in multiple blocks. If we
1771 * supported -L -> no-L, it would not be safe
1772 * to free the file's contents. Fortunately,
1773 * that is not allowed (see
1774 * recv_check_large_blocks()).
1775 */
1776 do_free_range = B_TRUE;
1777 } else {
1778 boolean_t is_same_gen;
1779 err = receive_object_is_same_generation(rwa->os,
1780 drro->drr_object, doi->doi_bonus_type,
1781 drro->drr_bonustype, bonus_data, &is_same_gen);
1782 if (err != 0)
1783 return (SET_ERROR(EINVAL));
1784
1785 if (is_same_gen) {
1786 /*
1787 * This is the same logical file, and
1788 * the block size must be increasing.
1789 * It could only decrease if
1790 * --large-block was changed to be
1791 * off, which is checked in
1792 * recv_check_large_blocks().
1793 */
1794 if (drro->drr_blksz <=
1795 doi->doi_data_block_size)
1796 return (SET_ERROR(EINVAL));
1797 /*
1798 * We keep the existing blocksize and
1799 * contents.
1800 */
1801 *new_blksz =
1802 doi->doi_data_block_size;
1803 } else {
1804 do_free_range = B_TRUE;
1805 }
1806 }
1807 }
1808
1809 /* nblkptr can only decrease if the object was reallocated */
1810 if (nblkptr < doi->doi_nblkptr)
1811 do_free_range = B_TRUE;
1812
1813 /* number of slots can only change on reallocation */
1814 if (dn_slots != doi->doi_dnodesize >> DNODE_SHIFT)
1815 do_free_range = B_TRUE;
1816
1817 /*
1818 * For raw sends we also check a few other fields to
1819 * ensure we are preserving the objset structure exactly
1820 * as it was on the receive side:
1821 * - A changed indirect block size
1822 * - A smaller nlevels
1823 */
1824 if (rwa->raw) {
1825 if (indblksz != doi->doi_metadata_block_size)
1826 do_free_range = B_TRUE;
1827 if (drro->drr_nlevels < doi->doi_indirection)
1828 do_free_range = B_TRUE;
1829 }
1830
1831 if (do_free_range) {
1832 err = dmu_free_long_range(rwa->os, drro->drr_object,
1833 0, DMU_OBJECT_END);
1834 if (err != 0)
1835 return (SET_ERROR(EINVAL));
1836 }
1837
1838 /*
1839 * The dmu does not currently support decreasing nlevels or changing
1840 * indirect block size if there is already one, same as changing the
1841 * number of of dnode slots on an object. For non-raw sends this
1842 * does not matter and the new object can just use the previous one's
1843 * parameters. For raw sends, however, the structure of the received
1844 * dnode (including indirects and dnode slots) must match that of the
1845 * send side. Therefore, instead of using dmu_object_reclaim(), we
1846 * must free the object completely and call dmu_object_claim_dnsize()
1847 * instead.
1848 */
1849 if ((rwa->raw && ((doi->doi_indirection > 1 &&
1850 indblksz != doi->doi_metadata_block_size) ||
1851 drro->drr_nlevels < doi->doi_indirection)) ||
1852 dn_slots != doi->doi_dnodesize >> DNODE_SHIFT) {
1853 err = dmu_free_long_object(rwa->os, drro->drr_object);
1854 if (err != 0)
1855 return (SET_ERROR(EINVAL));
1856
1857 txg_wait_synced(dmu_objset_pool(rwa->os), 0);
1858 *object_to_hold = DMU_NEW_OBJECT;
1859 }
1860
1861 /*
1862 * For raw receives, free everything beyond the new incoming
1863 * maxblkid. Normally this would be done with a DRR_FREE
1864 * record that would come after this DRR_OBJECT record is
1865 * processed. However, for raw receives we manually set the
1866 * maxblkid from the drr_maxblkid and so we must first free
1867 * everything above that blkid to ensure the DMU is always
1868 * consistent with itself. We will never free the first block
1869 * of the object here because a maxblkid of 0 could indicate
1870 * an object with a single block or one with no blocks. This
1871 * free may be skipped when dmu_free_long_range() was called
1872 * above since it covers the entire object's contents.
1873 */
1874 if (rwa->raw && *object_to_hold != DMU_NEW_OBJECT && !do_free_range) {
1875 err = dmu_free_long_range(rwa->os, drro->drr_object,
1876 (drro->drr_maxblkid + 1) * doi->doi_data_block_size,
1877 DMU_OBJECT_END);
1878 if (err != 0)
1879 return (SET_ERROR(EINVAL));
1880 }
1881 return (0);
1882 }
1883
1884 noinline static int
receive_object(struct receive_writer_arg * rwa,struct drr_object * drro,void * data)1885 receive_object(struct receive_writer_arg *rwa, struct drr_object *drro,
1886 void *data)
1887 {
1888 dmu_object_info_t doi;
1889 dmu_tx_t *tx;
1890 int err;
1891 uint32_t new_blksz = drro->drr_blksz;
1892 uint8_t dn_slots = drro->drr_dn_slots != 0 ?
1893 drro->drr_dn_slots : DNODE_MIN_SLOTS;
1894
1895 if (drro->drr_type == DMU_OT_NONE ||
1896 !DMU_OT_IS_VALID(drro->drr_type) ||
1897 !DMU_OT_IS_VALID(drro->drr_bonustype) ||
1898 drro->drr_checksumtype >= ZIO_CHECKSUM_FUNCTIONS ||
1899 drro->drr_compress >= ZIO_COMPRESS_FUNCTIONS ||
1900 P2PHASE(drro->drr_blksz, SPA_MINBLOCKSIZE) ||
1901 drro->drr_blksz < SPA_MINBLOCKSIZE ||
1902 drro->drr_blksz > spa_maxblocksize(dmu_objset_spa(rwa->os)) ||
1903 drro->drr_bonuslen >
1904 DN_BONUS_SIZE(spa_maxdnodesize(dmu_objset_spa(rwa->os))) ||
1905 dn_slots >
1906 (spa_maxdnodesize(dmu_objset_spa(rwa->os)) >> DNODE_SHIFT)) {
1907 return (SET_ERROR(EINVAL));
1908 }
1909
1910 if (rwa->raw) {
1911 /*
1912 * We should have received a DRR_OBJECT_RANGE record
1913 * containing this block and stored it in rwa.
1914 */
1915 if (drro->drr_object < rwa->or_firstobj ||
1916 drro->drr_object >= rwa->or_firstobj + rwa->or_numslots ||
1917 drro->drr_raw_bonuslen < drro->drr_bonuslen ||
1918 drro->drr_indblkshift > SPA_MAXBLOCKSHIFT ||
1919 drro->drr_nlevels > DN_MAX_LEVELS ||
1920 drro->drr_nblkptr > DN_MAX_NBLKPTR ||
1921 DN_SLOTS_TO_BONUSLEN(dn_slots) <
1922 drro->drr_raw_bonuslen)
1923 return (SET_ERROR(EINVAL));
1924 } else {
1925 /*
1926 * The DRR_OBJECT_SPILL flag is valid when the DRR_BEGIN
1927 * record indicates this by setting DRR_FLAG_SPILL_BLOCK.
1928 */
1929 if (((drro->drr_flags & ~(DRR_OBJECT_SPILL))) ||
1930 (!rwa->spill && DRR_OBJECT_HAS_SPILL(drro->drr_flags))) {
1931 return (SET_ERROR(EINVAL));
1932 }
1933
1934 if (drro->drr_raw_bonuslen != 0 || drro->drr_nblkptr != 0 ||
1935 drro->drr_indblkshift != 0 || drro->drr_nlevels != 0) {
1936 return (SET_ERROR(EINVAL));
1937 }
1938 }
1939
1940 err = dmu_object_info(rwa->os, drro->drr_object, &doi);
1941
1942 if (err != 0 && err != ENOENT && err != EEXIST)
1943 return (SET_ERROR(EINVAL));
1944
1945 if (drro->drr_object > rwa->max_object)
1946 rwa->max_object = drro->drr_object;
1947
1948 /*
1949 * If we are losing blkptrs or changing the block size this must
1950 * be a new file instance. We must clear out the previous file
1951 * contents before we can change this type of metadata in the dnode.
1952 * Raw receives will also check that the indirect structure of the
1953 * dnode hasn't changed.
1954 */
1955 uint64_t object_to_hold;
1956 if (err == 0) {
1957 err = receive_handle_existing_object(rwa, drro, &doi, data,
1958 &object_to_hold, &new_blksz);
1959 if (err != 0)
1960 return (err);
1961 } else if (err == EEXIST) {
1962 /*
1963 * The object requested is currently an interior slot of a
1964 * multi-slot dnode. This will be resolved when the next txg
1965 * is synced out, since the send stream will have told us
1966 * to free this slot when we freed the associated dnode
1967 * earlier in the stream.
1968 */
1969 txg_wait_synced(dmu_objset_pool(rwa->os), 0);
1970
1971 if (dmu_object_info(rwa->os, drro->drr_object, NULL) != ENOENT)
1972 return (SET_ERROR(EINVAL));
1973
1974 /* object was freed and we are about to allocate a new one */
1975 object_to_hold = DMU_NEW_OBJECT;
1976 } else {
1977 /*
1978 * If the only record in this range so far was DRR_FREEOBJECTS
1979 * with at least one actually freed object, it's possible that
1980 * the block will now be converted to a hole. We need to wait
1981 * for the txg to sync to prevent races.
1982 */
1983 if (rwa->or_need_sync == ORNS_YES)
1984 txg_wait_synced(dmu_objset_pool(rwa->os), 0);
1985
1986 /* object is free and we are about to allocate a new one */
1987 object_to_hold = DMU_NEW_OBJECT;
1988 }
1989
1990 /* Only relevant for the first object in the range */
1991 rwa->or_need_sync = ORNS_NO;
1992
1993 /*
1994 * If this is a multi-slot dnode there is a chance that this
1995 * object will expand into a slot that is already used by
1996 * another object from the previous snapshot. We must free
1997 * these objects before we attempt to allocate the new dnode.
1998 */
1999 if (dn_slots > 1) {
2000 boolean_t need_sync = B_FALSE;
2001
2002 for (uint64_t slot = drro->drr_object + 1;
2003 slot < drro->drr_object + dn_slots;
2004 slot++) {
2005 dmu_object_info_t slot_doi;
2006
2007 err = dmu_object_info(rwa->os, slot, &slot_doi);
2008 if (err == ENOENT || err == EEXIST)
2009 continue;
2010 else if (err != 0)
2011 return (err);
2012
2013 err = dmu_free_long_object(rwa->os, slot);
2014 if (err != 0)
2015 return (err);
2016
2017 need_sync = B_TRUE;
2018 }
2019
2020 if (need_sync)
2021 txg_wait_synced(dmu_objset_pool(rwa->os), 0);
2022 }
2023
2024 tx = dmu_tx_create(rwa->os);
2025 dmu_tx_hold_bonus(tx, object_to_hold);
2026 dmu_tx_hold_write(tx, object_to_hold, 0, 0);
2027 err = dmu_tx_assign(tx, DMU_TX_WAIT);
2028 if (err != 0) {
2029 dmu_tx_abort(tx);
2030 return (err);
2031 }
2032
2033 if (object_to_hold == DMU_NEW_OBJECT) {
2034 /* Currently free, wants to be allocated */
2035 err = dmu_object_claim_dnsize(rwa->os, drro->drr_object,
2036 drro->drr_type, new_blksz,
2037 drro->drr_bonustype, drro->drr_bonuslen,
2038 dn_slots << DNODE_SHIFT, tx);
2039 } else if (drro->drr_type != doi.doi_type ||
2040 new_blksz != doi.doi_data_block_size ||
2041 drro->drr_bonustype != doi.doi_bonus_type ||
2042 drro->drr_bonuslen != doi.doi_bonus_size) {
2043 /* Currently allocated, but with different properties */
2044 err = dmu_object_reclaim_dnsize(rwa->os, drro->drr_object,
2045 drro->drr_type, new_blksz,
2046 drro->drr_bonustype, drro->drr_bonuslen,
2047 dn_slots << DNODE_SHIFT, rwa->spill ?
2048 DRR_OBJECT_HAS_SPILL(drro->drr_flags) : B_FALSE, tx);
2049 } else if (rwa->spill && !DRR_OBJECT_HAS_SPILL(drro->drr_flags)) {
2050 /*
2051 * Currently allocated, the existing version of this object
2052 * may reference a spill block that is no longer allocated
2053 * at the source and needs to be freed.
2054 */
2055 err = dmu_object_rm_spill(rwa->os, drro->drr_object, tx);
2056 }
2057
2058 if (err != 0) {
2059 dmu_tx_commit(tx);
2060 return (SET_ERROR(EINVAL));
2061 }
2062
2063 if (rwa->or_crypt_params_present) {
2064 /*
2065 * Set the crypt params for the buffer associated with this
2066 * range of dnodes. This causes the blkptr_t to have the
2067 * same crypt params (byteorder, salt, iv, mac) as on the
2068 * sending side.
2069 *
2070 * Since we are committing this tx now, it is possible for
2071 * the dnode block to end up on-disk with the incorrect MAC,
2072 * if subsequent objects in this block are received in a
2073 * different txg. However, since the dataset is marked as
2074 * inconsistent, no code paths will do a non-raw read (or
2075 * decrypt the block / verify the MAC). The receive code and
2076 * scrub code can safely do raw reads and verify the
2077 * checksum. They don't need to verify the MAC.
2078 */
2079 dmu_buf_t *db = NULL;
2080 uint64_t offset = rwa->or_firstobj * DNODE_MIN_SIZE;
2081
2082 err = dmu_buf_hold_by_dnode(DMU_META_DNODE(rwa->os),
2083 offset, FTAG, &db, DMU_READ_PREFETCH | DMU_READ_NO_DECRYPT);
2084 if (err != 0) {
2085 dmu_tx_commit(tx);
2086 return (SET_ERROR(EINVAL));
2087 }
2088
2089 dmu_buf_set_crypt_params(db, rwa->or_byteorder,
2090 rwa->or_salt, rwa->or_iv, rwa->or_mac, tx);
2091
2092 dmu_buf_rele(db, FTAG);
2093
2094 rwa->or_crypt_params_present = B_FALSE;
2095 }
2096
2097 dmu_object_set_checksum(rwa->os, drro->drr_object,
2098 drro->drr_checksumtype, tx);
2099 dmu_object_set_compress(rwa->os, drro->drr_object,
2100 drro->drr_compress, tx);
2101
2102 /* handle more restrictive dnode structuring for raw recvs */
2103 if (rwa->raw) {
2104 /*
2105 * Set the indirect block size, block shift, nlevels.
2106 * This will not fail because we ensured all of the
2107 * blocks were freed earlier if this is a new object.
2108 * For non-new objects block size and indirect block
2109 * shift cannot change and nlevels can only increase.
2110 */
2111 ASSERT3U(new_blksz, ==, drro->drr_blksz);
2112 VERIFY0(dmu_object_set_blocksize(rwa->os, drro->drr_object,
2113 drro->drr_blksz, drro->drr_indblkshift, tx));
2114 VERIFY0(dmu_object_set_nlevels(rwa->os, drro->drr_object,
2115 drro->drr_nlevels, tx));
2116
2117 /*
2118 * Set the maxblkid. This will always succeed because
2119 * we freed all blocks beyond the new maxblkid above.
2120 */
2121 VERIFY0(dmu_object_set_maxblkid(rwa->os, drro->drr_object,
2122 drro->drr_maxblkid, tx));
2123 }
2124
2125 if (data != NULL) {
2126 dmu_buf_t *db;
2127 dnode_t *dn;
2128 uint32_t flags = DMU_READ_NO_PREFETCH;
2129
2130 if (rwa->raw)
2131 flags |= DMU_READ_NO_DECRYPT;
2132
2133 VERIFY0(dnode_hold(rwa->os, drro->drr_object, FTAG, &dn));
2134 VERIFY0(dmu_bonus_hold_by_dnode(dn, FTAG, &db, flags));
2135
2136 dmu_buf_will_dirty(db, tx);
2137
2138 ASSERT3U(db->db_size, >=, drro->drr_bonuslen);
2139 memcpy(db->db_data, data, DRR_OBJECT_PAYLOAD_SIZE(drro));
2140
2141 /*
2142 * Raw bonus buffers have their byteorder determined by the
2143 * DRR_OBJECT_RANGE record.
2144 */
2145 if (rwa->byteswap && !rwa->raw) {
2146 dmu_object_byteswap_t byteswap =
2147 DMU_OT_BYTESWAP(drro->drr_bonustype);
2148 dmu_ot_byteswap[byteswap].ob_func(db->db_data,
2149 DRR_OBJECT_PAYLOAD_SIZE(drro));
2150 }
2151 dmu_buf_rele(db, FTAG);
2152 dnode_rele(dn, FTAG);
2153 }
2154
2155 /*
2156 * If the receive fails, we want the resume stream to start with the
2157 * same record that we last successfully received. There is no way to
2158 * request resume from the object record, but we can benefit from the
2159 * fact that sender always sends object record before anything else,
2160 * after which it will "resend" data at offset 0 and resume normally.
2161 */
2162 save_resume_state(rwa, drro->drr_object, 0, tx);
2163
2164 dmu_tx_commit(tx);
2165
2166 return (0);
2167 }
2168
2169 noinline static int
receive_freeobjects(struct receive_writer_arg * rwa,struct drr_freeobjects * drrfo)2170 receive_freeobjects(struct receive_writer_arg *rwa,
2171 struct drr_freeobjects *drrfo)
2172 {
2173 uint64_t obj;
2174 int next_err = 0;
2175
2176 if (drrfo->drr_firstobj + drrfo->drr_numobjs < drrfo->drr_firstobj)
2177 return (SET_ERROR(EINVAL));
2178
2179 for (obj = drrfo->drr_firstobj == 0 ? 1 : drrfo->drr_firstobj;
2180 obj < drrfo->drr_firstobj + drrfo->drr_numobjs &&
2181 obj < DN_MAX_OBJECT && next_err == 0;
2182 next_err = dmu_object_next(rwa->os, &obj, FALSE, 0)) {
2183 dmu_object_info_t doi;
2184 int err;
2185
2186 err = dmu_object_info(rwa->os, obj, &doi);
2187 if (err == ENOENT)
2188 continue;
2189 else if (err != 0)
2190 return (err);
2191
2192 err = dmu_free_long_object(rwa->os, obj);
2193
2194 if (err != 0)
2195 return (err);
2196
2197 if (rwa->or_need_sync == ORNS_MAYBE)
2198 rwa->or_need_sync = ORNS_YES;
2199 }
2200 if (next_err != ESRCH)
2201 return (next_err);
2202 return (0);
2203 }
2204
2205 /*
2206 * Note: if this fails, the caller will clean up any records left on the
2207 * rwa->write_batch list.
2208 */
2209 static int
flush_write_batch_impl(struct receive_writer_arg * rwa)2210 flush_write_batch_impl(struct receive_writer_arg *rwa)
2211 {
2212 dnode_t *dn;
2213 int err;
2214
2215 if (dnode_hold(rwa->os, rwa->last_object, FTAG, &dn) != 0)
2216 return (SET_ERROR(EINVAL));
2217
2218 struct receive_record_arg *last_rrd = list_tail(&rwa->write_batch);
2219 struct drr_write *last_drrw = &last_rrd->header.drr_u.drr_write;
2220
2221 struct receive_record_arg *first_rrd = list_head(&rwa->write_batch);
2222 struct drr_write *first_drrw = &first_rrd->header.drr_u.drr_write;
2223
2224 ASSERT3U(rwa->last_object, ==, last_drrw->drr_object);
2225 ASSERT3U(rwa->last_offset, ==, last_drrw->drr_offset);
2226
2227 dmu_tx_t *tx = dmu_tx_create(rwa->os);
2228 dmu_tx_hold_write_by_dnode(tx, dn, first_drrw->drr_offset,
2229 last_drrw->drr_offset - first_drrw->drr_offset +
2230 last_drrw->drr_logical_size);
2231 err = dmu_tx_assign(tx, DMU_TX_WAIT);
2232 if (err != 0) {
2233 dmu_tx_abort(tx);
2234 dnode_rele(dn, FTAG);
2235 return (err);
2236 }
2237
2238 struct receive_record_arg *rrd;
2239 while ((rrd = list_head(&rwa->write_batch)) != NULL) {
2240 struct drr_write *drrw = &rrd->header.drr_u.drr_write;
2241 abd_t *abd = rrd->abd;
2242
2243 ASSERT3U(drrw->drr_object, ==, rwa->last_object);
2244
2245 if (drrw->drr_logical_size != dn->dn_datablksz) {
2246 /*
2247 * The WRITE record is larger than the object's block
2248 * size. We must be receiving an incremental
2249 * large-block stream into a dataset that previously did
2250 * a non-large-block receive. Lightweight writes must
2251 * be exactly one block, so we need to decompress the
2252 * data (if compressed) and do a normal dmu_write().
2253 */
2254 ASSERT3U(drrw->drr_logical_size, >, dn->dn_datablksz);
2255 if (DRR_WRITE_COMPRESSED(drrw)) {
2256 abd_t *decomp_abd =
2257 abd_alloc_linear(drrw->drr_logical_size,
2258 B_FALSE);
2259
2260 err = zio_decompress_data(
2261 drrw->drr_compressiontype,
2262 abd, decomp_abd,
2263 abd_get_size(abd),
2264 abd_get_size(decomp_abd), NULL);
2265
2266 if (err == 0) {
2267 dmu_write_by_dnode(dn,
2268 drrw->drr_offset,
2269 drrw->drr_logical_size,
2270 abd_to_buf(decomp_abd), tx);
2271 }
2272 abd_free(decomp_abd);
2273 } else {
2274 dmu_write_by_dnode(dn,
2275 drrw->drr_offset,
2276 drrw->drr_logical_size,
2277 abd_to_buf(abd), tx);
2278 }
2279 if (err == 0)
2280 abd_free(abd);
2281 } else {
2282 zio_prop_t zp = {0};
2283 dmu_write_policy(rwa->os, dn, 0, 0, &zp);
2284
2285 zio_flag_t zio_flags = 0;
2286
2287 if (rwa->raw) {
2288 zp.zp_encrypt = B_TRUE;
2289 zp.zp_compress = drrw->drr_compressiontype;
2290 zp.zp_byteorder = ZFS_HOST_BYTEORDER ^
2291 !!DRR_IS_RAW_BYTESWAPPED(drrw->drr_flags) ^
2292 rwa->byteswap;
2293 memcpy(zp.zp_salt, drrw->drr_salt,
2294 ZIO_DATA_SALT_LEN);
2295 memcpy(zp.zp_iv, drrw->drr_iv,
2296 ZIO_DATA_IV_LEN);
2297 memcpy(zp.zp_mac, drrw->drr_mac,
2298 ZIO_DATA_MAC_LEN);
2299 if (DMU_OT_IS_ENCRYPTED(zp.zp_type)) {
2300 zp.zp_nopwrite = B_FALSE;
2301 zp.zp_copies = MIN(zp.zp_copies,
2302 SPA_DVAS_PER_BP - 1);
2303 zp.zp_gang_copies =
2304 MIN(zp.zp_gang_copies,
2305 SPA_DVAS_PER_BP - 1);
2306 }
2307 zio_flags |= ZIO_FLAG_RAW;
2308 } else if (DRR_WRITE_COMPRESSED(drrw)) {
2309 ASSERT3U(drrw->drr_compressed_size, >, 0);
2310 ASSERT3U(drrw->drr_logical_size, >=,
2311 drrw->drr_compressed_size);
2312 zp.zp_compress = drrw->drr_compressiontype;
2313 zio_flags |= ZIO_FLAG_RAW_COMPRESS;
2314 } else if (rwa->byteswap) {
2315 /*
2316 * Note: compressed blocks never need to be
2317 * byteswapped, because WRITE records for
2318 * metadata blocks are never compressed. The
2319 * exception is raw streams, which are written
2320 * in the original byteorder, and the byteorder
2321 * bit is preserved in the BP by setting
2322 * zp_byteorder above.
2323 */
2324 dmu_object_byteswap_t byteswap =
2325 DMU_OT_BYTESWAP(drrw->drr_type);
2326 dmu_ot_byteswap[byteswap].ob_func(
2327 abd_to_buf(abd),
2328 DRR_WRITE_PAYLOAD_SIZE(drrw));
2329 }
2330
2331 /*
2332 * Since this data can't be read until the receive
2333 * completes, we can do a "lightweight" write for
2334 * improved performance.
2335 */
2336 err = dmu_lightweight_write_by_dnode(dn,
2337 drrw->drr_offset, abd, &zp, zio_flags, tx);
2338 }
2339
2340 if (err != 0) {
2341 /*
2342 * This rrd is left on the list, so the caller will
2343 * free it (and the abd).
2344 */
2345 break;
2346 }
2347
2348 /*
2349 * Note: If the receive fails, we want the resume stream to
2350 * start with the same record that we last successfully
2351 * received (as opposed to the next record), so that we can
2352 * verify that we are resuming from the correct location.
2353 */
2354 save_resume_state(rwa, drrw->drr_object, drrw->drr_offset, tx);
2355
2356 list_remove(&rwa->write_batch, rrd);
2357 kmem_free(rrd, sizeof (*rrd));
2358 }
2359
2360 dmu_tx_commit(tx);
2361 dnode_rele(dn, FTAG);
2362 return (err);
2363 }
2364
2365 noinline static int
flush_write_batch(struct receive_writer_arg * rwa)2366 flush_write_batch(struct receive_writer_arg *rwa)
2367 {
2368 if (list_is_empty(&rwa->write_batch))
2369 return (0);
2370 int err = rwa->err;
2371 if (err == 0)
2372 err = flush_write_batch_impl(rwa);
2373 if (err != 0) {
2374 struct receive_record_arg *rrd;
2375 while ((rrd = list_remove_head(&rwa->write_batch)) != NULL) {
2376 abd_free(rrd->abd);
2377 kmem_free(rrd, sizeof (*rrd));
2378 }
2379 }
2380 ASSERT(list_is_empty(&rwa->write_batch));
2381 return (err);
2382 }
2383
2384 noinline static int
receive_process_write_record(struct receive_writer_arg * rwa,struct receive_record_arg * rrd)2385 receive_process_write_record(struct receive_writer_arg *rwa,
2386 struct receive_record_arg *rrd)
2387 {
2388 int err = 0;
2389
2390 ASSERT3U(rrd->header.drr_type, ==, DRR_WRITE);
2391 struct drr_write *drrw = &rrd->header.drr_u.drr_write;
2392
2393 if (drrw->drr_offset + drrw->drr_logical_size < drrw->drr_offset ||
2394 !DMU_OT_IS_VALID(drrw->drr_type))
2395 return (SET_ERROR(EINVAL));
2396
2397 if (rwa->heal) {
2398 blkptr_t *bp;
2399 dmu_buf_t *dbp;
2400 int flags = DB_RF_CANFAIL;
2401
2402 if (rwa->raw)
2403 flags |= DB_RF_NO_DECRYPT;
2404
2405 if (rwa->byteswap) {
2406 dmu_object_byteswap_t byteswap =
2407 DMU_OT_BYTESWAP(drrw->drr_type);
2408 dmu_ot_byteswap[byteswap].ob_func(abd_to_buf(rrd->abd),
2409 DRR_WRITE_PAYLOAD_SIZE(drrw));
2410 }
2411
2412 err = dmu_buf_hold_noread(rwa->os, drrw->drr_object,
2413 drrw->drr_offset, FTAG, &dbp);
2414 if (err != 0)
2415 return (err);
2416
2417 /* Try to read the object to see if it needs healing */
2418 err = dbuf_read((dmu_buf_impl_t *)dbp, NULL, flags);
2419 /*
2420 * We only try to heal when dbuf_read() returns a ECKSUMs.
2421 * Other errors (even EIO) get returned to caller.
2422 * EIO indicates that the device is not present/accessible,
2423 * so writing to it will likely fail.
2424 * If the block is healthy, we don't want to overwrite it
2425 * unnecessarily.
2426 */
2427 if (err != ECKSUM) {
2428 dmu_buf_rele(dbp, FTAG);
2429 return (err);
2430 }
2431 /* Make sure the on-disk block and recv record sizes match */
2432 if (drrw->drr_logical_size != dbp->db_size) {
2433 err = ENOTSUP;
2434 dmu_buf_rele(dbp, FTAG);
2435 return (err);
2436 }
2437 /* Get the block pointer for the corrupted block */
2438 bp = dmu_buf_get_blkptr(dbp);
2439 err = do_corrective_recv(rwa, drrw, rrd, bp);
2440 dmu_buf_rele(dbp, FTAG);
2441 return (err);
2442 }
2443
2444 /*
2445 * For resuming to work, records must be in increasing order
2446 * by (object, offset).
2447 */
2448 if (drrw->drr_object < rwa->last_object ||
2449 (drrw->drr_object == rwa->last_object &&
2450 drrw->drr_offset < rwa->last_offset)) {
2451 return (SET_ERROR(EINVAL));
2452 }
2453
2454 struct receive_record_arg *first_rrd = list_head(&rwa->write_batch);
2455 struct drr_write *first_drrw = &first_rrd->header.drr_u.drr_write;
2456 uint64_t batch_size =
2457 MIN(zfs_recv_write_batch_size, DMU_MAX_ACCESS / 2);
2458 if (first_rrd != NULL &&
2459 (drrw->drr_object != first_drrw->drr_object ||
2460 drrw->drr_offset >= first_drrw->drr_offset + batch_size)) {
2461 err = flush_write_batch(rwa);
2462 if (err != 0)
2463 return (err);
2464 }
2465
2466 rwa->last_object = drrw->drr_object;
2467 rwa->last_offset = drrw->drr_offset;
2468
2469 if (rwa->last_object > rwa->max_object)
2470 rwa->max_object = rwa->last_object;
2471
2472 list_insert_tail(&rwa->write_batch, rrd);
2473 /*
2474 * Return EAGAIN to indicate that we will use this rrd again,
2475 * so the caller should not free it
2476 */
2477 return (EAGAIN);
2478 }
2479
2480 static int
receive_write_embedded(struct receive_writer_arg * rwa,struct drr_write_embedded * drrwe,void * data)2481 receive_write_embedded(struct receive_writer_arg *rwa,
2482 struct drr_write_embedded *drrwe, void *data)
2483 {
2484 dmu_tx_t *tx;
2485 int err;
2486
2487 if (drrwe->drr_offset + drrwe->drr_length < drrwe->drr_offset)
2488 return (SET_ERROR(EINVAL));
2489
2490 if (drrwe->drr_psize > BPE_PAYLOAD_SIZE)
2491 return (SET_ERROR(EINVAL));
2492
2493 if (drrwe->drr_etype >= NUM_BP_EMBEDDED_TYPES)
2494 return (SET_ERROR(EINVAL));
2495 if (drrwe->drr_compression >= ZIO_COMPRESS_FUNCTIONS)
2496 return (SET_ERROR(EINVAL));
2497 if (rwa->raw)
2498 return (SET_ERROR(EINVAL));
2499
2500 if (drrwe->drr_object > rwa->max_object)
2501 rwa->max_object = drrwe->drr_object;
2502
2503 tx = dmu_tx_create(rwa->os);
2504
2505 dmu_tx_hold_write(tx, drrwe->drr_object,
2506 drrwe->drr_offset, drrwe->drr_length);
2507 err = dmu_tx_assign(tx, DMU_TX_WAIT);
2508 if (err != 0) {
2509 dmu_tx_abort(tx);
2510 return (err);
2511 }
2512
2513 dmu_write_embedded(rwa->os, drrwe->drr_object,
2514 drrwe->drr_offset, data, drrwe->drr_etype,
2515 drrwe->drr_compression, drrwe->drr_lsize, drrwe->drr_psize,
2516 rwa->byteswap ^ ZFS_HOST_BYTEORDER, tx);
2517
2518 /* See comment in restore_write. */
2519 save_resume_state(rwa, drrwe->drr_object, drrwe->drr_offset, tx);
2520 dmu_tx_commit(tx);
2521 return (0);
2522 }
2523
2524 static int
receive_spill(struct receive_writer_arg * rwa,struct drr_spill * drrs,abd_t * abd)2525 receive_spill(struct receive_writer_arg *rwa, struct drr_spill *drrs,
2526 abd_t *abd)
2527 {
2528 dmu_buf_t *db, *db_spill;
2529 int err;
2530
2531 if (drrs->drr_length < SPA_MINBLOCKSIZE ||
2532 drrs->drr_length > spa_maxblocksize(dmu_objset_spa(rwa->os)))
2533 return (SET_ERROR(EINVAL));
2534
2535 /*
2536 * This is an unmodified spill block which was added to the stream
2537 * to resolve an issue with incorrectly removing spill blocks. It
2538 * should be ignored by current versions of the code which support
2539 * the DRR_FLAG_SPILL_BLOCK flag.
2540 */
2541 if (rwa->spill && DRR_SPILL_IS_UNMODIFIED(drrs->drr_flags)) {
2542 abd_free(abd);
2543 return (0);
2544 }
2545
2546 if (rwa->raw) {
2547 if (!DMU_OT_IS_VALID(drrs->drr_type) ||
2548 drrs->drr_compressiontype >= ZIO_COMPRESS_FUNCTIONS ||
2549 drrs->drr_compressed_size == 0)
2550 return (SET_ERROR(EINVAL));
2551 }
2552
2553 if (dmu_object_info(rwa->os, drrs->drr_object, NULL) != 0)
2554 return (SET_ERROR(EINVAL));
2555
2556 if (drrs->drr_object > rwa->max_object)
2557 rwa->max_object = drrs->drr_object;
2558
2559 VERIFY0(dmu_bonus_hold(rwa->os, drrs->drr_object, FTAG, &db));
2560 if ((err = dmu_spill_hold_by_bonus(db, DMU_READ_NO_DECRYPT, FTAG,
2561 &db_spill)) != 0) {
2562 dmu_buf_rele(db, FTAG);
2563 return (err);
2564 }
2565
2566 dmu_tx_t *tx = dmu_tx_create(rwa->os);
2567
2568 dmu_tx_hold_spill(tx, db->db_object);
2569
2570 err = dmu_tx_assign(tx, DMU_TX_WAIT);
2571 if (err != 0) {
2572 dmu_buf_rele(db, FTAG);
2573 dmu_buf_rele(db_spill, FTAG);
2574 dmu_tx_abort(tx);
2575 return (err);
2576 }
2577
2578 /*
2579 * Spill blocks may both grow and shrink. When a change in size
2580 * occurs any existing dbuf must be updated to match the logical
2581 * size of the provided arc_buf_t.
2582 */
2583 if (db_spill->db_size != drrs->drr_length) {
2584 dmu_buf_will_fill(db_spill, tx, B_FALSE);
2585 VERIFY0(dbuf_spill_set_blksz(db_spill,
2586 drrs->drr_length, tx));
2587 }
2588
2589 arc_buf_t *abuf;
2590 if (rwa->raw) {
2591 boolean_t byteorder = ZFS_HOST_BYTEORDER ^
2592 !!DRR_IS_RAW_BYTESWAPPED(drrs->drr_flags) ^
2593 rwa->byteswap;
2594
2595 abuf = arc_loan_raw_buf(dmu_objset_spa(rwa->os),
2596 drrs->drr_object, byteorder, drrs->drr_salt,
2597 drrs->drr_iv, drrs->drr_mac, drrs->drr_type,
2598 drrs->drr_compressed_size, drrs->drr_length,
2599 drrs->drr_compressiontype, 0);
2600 } else {
2601 abuf = arc_loan_buf(dmu_objset_spa(rwa->os),
2602 DMU_OT_IS_METADATA(drrs->drr_type),
2603 drrs->drr_length);
2604 if (rwa->byteswap) {
2605 dmu_object_byteswap_t byteswap =
2606 DMU_OT_BYTESWAP(drrs->drr_type);
2607 dmu_ot_byteswap[byteswap].ob_func(abd_to_buf(abd),
2608 DRR_SPILL_PAYLOAD_SIZE(drrs));
2609 }
2610 }
2611
2612 memcpy(abuf->b_data, abd_to_buf(abd), DRR_SPILL_PAYLOAD_SIZE(drrs));
2613 abd_free(abd);
2614 dbuf_assign_arcbuf((dmu_buf_impl_t *)db_spill, abuf, tx);
2615
2616 dmu_buf_rele(db, FTAG);
2617 dmu_buf_rele(db_spill, FTAG);
2618
2619 dmu_tx_commit(tx);
2620 return (0);
2621 }
2622
2623 noinline static int
receive_free(struct receive_writer_arg * rwa,struct drr_free * drrf)2624 receive_free(struct receive_writer_arg *rwa, struct drr_free *drrf)
2625 {
2626 int err;
2627
2628 if (drrf->drr_length != -1ULL &&
2629 drrf->drr_offset + drrf->drr_length < drrf->drr_offset)
2630 return (SET_ERROR(EINVAL));
2631
2632 if (dmu_object_info(rwa->os, drrf->drr_object, NULL) != 0)
2633 return (SET_ERROR(EINVAL));
2634
2635 if (drrf->drr_object > rwa->max_object)
2636 rwa->max_object = drrf->drr_object;
2637
2638 err = dmu_free_long_range(rwa->os, drrf->drr_object,
2639 drrf->drr_offset, drrf->drr_length);
2640
2641 return (err);
2642 }
2643
2644 static int
receive_object_range(struct receive_writer_arg * rwa,struct drr_object_range * drror)2645 receive_object_range(struct receive_writer_arg *rwa,
2646 struct drr_object_range *drror)
2647 {
2648 /*
2649 * By default, we assume this block is in our native format
2650 * (ZFS_HOST_BYTEORDER). We then take into account whether
2651 * the send stream is byteswapped (rwa->byteswap). Finally,
2652 * we need to byteswap again if this particular block was
2653 * in non-native format on the send side.
2654 */
2655 boolean_t byteorder = ZFS_HOST_BYTEORDER ^ rwa->byteswap ^
2656 !!DRR_IS_RAW_BYTESWAPPED(drror->drr_flags);
2657
2658 /*
2659 * Since dnode block sizes are constant, we should not need to worry
2660 * about making sure that the dnode block size is the same on the
2661 * sending and receiving sides for the time being. For non-raw sends,
2662 * this does not matter (and in fact we do not send a DRR_OBJECT_RANGE
2663 * record at all). Raw sends require this record type because the
2664 * encryption parameters are used to protect an entire block of bonus
2665 * buffers. If the size of dnode blocks ever becomes variable,
2666 * handling will need to be added to ensure that dnode block sizes
2667 * match on the sending and receiving side.
2668 */
2669 if (drror->drr_numslots != DNODES_PER_BLOCK ||
2670 P2PHASE(drror->drr_firstobj, DNODES_PER_BLOCK) != 0 ||
2671 !rwa->raw)
2672 return (SET_ERROR(EINVAL));
2673
2674 if (drror->drr_firstobj > rwa->max_object)
2675 rwa->max_object = drror->drr_firstobj;
2676
2677 /*
2678 * The DRR_OBJECT_RANGE handling must be deferred to receive_object()
2679 * so that the block of dnodes is not written out when it's empty,
2680 * and converted to a HOLE BP.
2681 */
2682 rwa->or_crypt_params_present = B_TRUE;
2683 rwa->or_firstobj = drror->drr_firstobj;
2684 rwa->or_numslots = drror->drr_numslots;
2685 memcpy(rwa->or_salt, drror->drr_salt, ZIO_DATA_SALT_LEN);
2686 memcpy(rwa->or_iv, drror->drr_iv, ZIO_DATA_IV_LEN);
2687 memcpy(rwa->or_mac, drror->drr_mac, ZIO_DATA_MAC_LEN);
2688 rwa->or_byteorder = byteorder;
2689
2690 rwa->or_need_sync = ORNS_MAYBE;
2691
2692 return (0);
2693 }
2694
2695 /*
2696 * Until we have the ability to redact large ranges of data efficiently, we
2697 * process these records as frees.
2698 */
2699 noinline static int
receive_redact(struct receive_writer_arg * rwa,struct drr_redact * drrr)2700 receive_redact(struct receive_writer_arg *rwa, struct drr_redact *drrr)
2701 {
2702 struct drr_free drrf = {0};
2703 drrf.drr_length = drrr->drr_length;
2704 drrf.drr_object = drrr->drr_object;
2705 drrf.drr_offset = drrr->drr_offset;
2706 drrf.drr_toguid = drrr->drr_toguid;
2707 return (receive_free(rwa, &drrf));
2708 }
2709
2710 /* used to destroy the drc_ds on error */
2711 static void
dmu_recv_cleanup_ds(dmu_recv_cookie_t * drc)2712 dmu_recv_cleanup_ds(dmu_recv_cookie_t *drc)
2713 {
2714 dsl_dataset_t *ds = drc->drc_ds;
2715 ds_hold_flags_t dsflags;
2716
2717 dsflags = (drc->drc_raw) ? DS_HOLD_FLAG_NONE : DS_HOLD_FLAG_DECRYPT;
2718 /*
2719 * Wait for the txg sync before cleaning up the receive. For
2720 * resumable receives, this ensures that our resume state has
2721 * been written out to disk. For raw receives, this ensures
2722 * that the user accounting code will not attempt to do anything
2723 * after we stopped receiving the dataset.
2724 */
2725 txg_wait_synced(ds->ds_dir->dd_pool, 0);
2726 ds->ds_objset->os_raw_receive = B_FALSE;
2727
2728 rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);
2729 if (drc->drc_resumable && drc->drc_should_save &&
2730 !BP_IS_HOLE(dsl_dataset_get_blkptr(ds))) {
2731 rrw_exit(&ds->ds_bp_rwlock, FTAG);
2732 dsl_dataset_disown(ds, dsflags, dmu_recv_tag);
2733 } else {
2734 char name[ZFS_MAX_DATASET_NAME_LEN];
2735 rrw_exit(&ds->ds_bp_rwlock, FTAG);
2736 dsl_dataset_name(ds, name);
2737 dsl_dataset_disown(ds, dsflags, dmu_recv_tag);
2738 if (!drc->drc_heal)
2739 (void) dsl_destroy_head(name);
2740 }
2741 }
2742
2743 static void
receive_cksum(dmu_recv_cookie_t * drc,int len,void * buf)2744 receive_cksum(dmu_recv_cookie_t *drc, int len, void *buf)
2745 {
2746 if (drc->drc_byteswap) {
2747 (void) fletcher_4_incremental_byteswap(buf, len,
2748 &drc->drc_cksum);
2749 } else {
2750 (void) fletcher_4_incremental_native(buf, len, &drc->drc_cksum);
2751 }
2752 }
2753
2754 /*
2755 * Read the payload into a buffer of size len, and update the current record's
2756 * payload field.
2757 * Allocate drc->drc_next_rrd and read the next record's header into
2758 * drc->drc_next_rrd->header.
2759 * Verify checksum of payload and next record.
2760 */
2761 static int
receive_read_payload_and_next_header(dmu_recv_cookie_t * drc,int len,void * buf)2762 receive_read_payload_and_next_header(dmu_recv_cookie_t *drc, int len, void *buf)
2763 {
2764 int err;
2765
2766 if (len != 0) {
2767 ASSERT3U(len, <=, SPA_MAXBLOCKSIZE);
2768 err = receive_read(drc, len, buf);
2769 if (err != 0)
2770 return (err);
2771 receive_cksum(drc, len, buf);
2772
2773 /* note: rrd is NULL when reading the begin record's payload */
2774 if (drc->drc_rrd != NULL) {
2775 drc->drc_rrd->payload = buf;
2776 drc->drc_rrd->payload_size = len;
2777 drc->drc_rrd->bytes_read = drc->drc_bytes_read;
2778 }
2779 } else {
2780 ASSERT3P(buf, ==, NULL);
2781 }
2782
2783 drc->drc_prev_cksum = drc->drc_cksum;
2784
2785 drc->drc_next_rrd = kmem_zalloc(sizeof (*drc->drc_next_rrd), KM_SLEEP);
2786 err = receive_read(drc, sizeof (drc->drc_next_rrd->header),
2787 &drc->drc_next_rrd->header);
2788 drc->drc_next_rrd->bytes_read = drc->drc_bytes_read;
2789
2790 if (err != 0) {
2791 kmem_free(drc->drc_next_rrd, sizeof (*drc->drc_next_rrd));
2792 drc->drc_next_rrd = NULL;
2793 return (err);
2794 }
2795 if (drc->drc_next_rrd->header.drr_type == DRR_BEGIN) {
2796 kmem_free(drc->drc_next_rrd, sizeof (*drc->drc_next_rrd));
2797 drc->drc_next_rrd = NULL;
2798 return (SET_ERROR(EINVAL));
2799 }
2800
2801 /*
2802 * Note: checksum is of everything up to but not including the
2803 * checksum itself.
2804 */
2805 ASSERT3U(offsetof(dmu_replay_record_t, drr_u.drr_checksum.drr_checksum),
2806 ==, sizeof (dmu_replay_record_t) - sizeof (zio_cksum_t));
2807 receive_cksum(drc,
2808 offsetof(dmu_replay_record_t, drr_u.drr_checksum.drr_checksum),
2809 &drc->drc_next_rrd->header);
2810
2811 zio_cksum_t cksum_orig =
2812 drc->drc_next_rrd->header.drr_u.drr_checksum.drr_checksum;
2813 zio_cksum_t *cksump =
2814 &drc->drc_next_rrd->header.drr_u.drr_checksum.drr_checksum;
2815
2816 if (drc->drc_byteswap)
2817 byteswap_record(&drc->drc_next_rrd->header);
2818
2819 if ((!ZIO_CHECKSUM_IS_ZERO(cksump)) &&
2820 !ZIO_CHECKSUM_EQUAL(drc->drc_cksum, *cksump)) {
2821 kmem_free(drc->drc_next_rrd, sizeof (*drc->drc_next_rrd));
2822 drc->drc_next_rrd = NULL;
2823 return (SET_ERROR(ECKSUM));
2824 }
2825
2826 receive_cksum(drc, sizeof (cksum_orig), &cksum_orig);
2827
2828 return (0);
2829 }
2830
2831 /*
2832 * Issue the prefetch reads for any necessary indirect blocks.
2833 *
2834 * We use the object ignore list to tell us whether or not to issue prefetches
2835 * for a given object. We do this for both correctness (in case the blocksize
2836 * of an object has changed) and performance (if the object doesn't exist, don't
2837 * needlessly try to issue prefetches). We also trim the list as we go through
2838 * the stream to prevent it from growing to an unbounded size.
2839 *
2840 * The object numbers within will always be in sorted order, and any write
2841 * records we see will also be in sorted order, but they're not sorted with
2842 * respect to each other (i.e. we can get several object records before
2843 * receiving each object's write records). As a result, once we've reached a
2844 * given object number, we can safely remove any reference to lower object
2845 * numbers in the ignore list. In practice, we receive up to 32 object records
2846 * before receiving write records, so the list can have up to 32 nodes in it.
2847 */
2848 static void
receive_read_prefetch(dmu_recv_cookie_t * drc,uint64_t object,uint64_t offset,uint64_t length)2849 receive_read_prefetch(dmu_recv_cookie_t *drc, uint64_t object, uint64_t offset,
2850 uint64_t length)
2851 {
2852 if (!objlist_exists(drc->drc_ignore_objlist, object)) {
2853 dmu_prefetch(drc->drc_os, object, 1, offset, length,
2854 ZIO_PRIORITY_SYNC_READ);
2855 }
2856 }
2857
2858 /*
2859 * Read records off the stream, issuing any necessary prefetches.
2860 */
2861 static int
receive_read_record(dmu_recv_cookie_t * drc)2862 receive_read_record(dmu_recv_cookie_t *drc)
2863 {
2864 int err;
2865
2866 switch (drc->drc_rrd->header.drr_type) {
2867 case DRR_OBJECT:
2868 {
2869 struct drr_object *drro =
2870 &drc->drc_rrd->header.drr_u.drr_object;
2871 uint32_t size = DRR_OBJECT_PAYLOAD_SIZE(drro);
2872 void *buf = NULL;
2873 dmu_object_info_t doi;
2874
2875 if (size != 0)
2876 buf = kmem_zalloc(size, KM_SLEEP);
2877
2878 err = receive_read_payload_and_next_header(drc, size, buf);
2879 if (err != 0) {
2880 kmem_free(buf, size);
2881 return (err);
2882 }
2883 err = dmu_object_info(drc->drc_os, drro->drr_object, &doi);
2884 /*
2885 * See receive_read_prefetch for an explanation why we're
2886 * storing this object in the ignore_obj_list.
2887 */
2888 if (err == ENOENT || err == EEXIST ||
2889 (err == 0 && doi.doi_data_block_size != drro->drr_blksz)) {
2890 objlist_insert(drc->drc_ignore_objlist,
2891 drro->drr_object);
2892 err = 0;
2893 }
2894 return (err);
2895 }
2896 case DRR_FREEOBJECTS:
2897 {
2898 err = receive_read_payload_and_next_header(drc, 0, NULL);
2899 return (err);
2900 }
2901 case DRR_WRITE:
2902 {
2903 struct drr_write *drrw = &drc->drc_rrd->header.drr_u.drr_write;
2904 int size = DRR_WRITE_PAYLOAD_SIZE(drrw);
2905 abd_t *abd = abd_alloc_linear(size, B_FALSE);
2906 err = receive_read_payload_and_next_header(drc, size,
2907 abd_to_buf(abd));
2908 if (err != 0) {
2909 abd_free(abd);
2910 return (err);
2911 }
2912 drc->drc_rrd->abd = abd;
2913 receive_read_prefetch(drc, drrw->drr_object, drrw->drr_offset,
2914 drrw->drr_logical_size);
2915 return (err);
2916 }
2917 case DRR_WRITE_EMBEDDED:
2918 {
2919 struct drr_write_embedded *drrwe =
2920 &drc->drc_rrd->header.drr_u.drr_write_embedded;
2921 uint32_t size = P2ROUNDUP(drrwe->drr_psize, 8);
2922 void *buf = kmem_zalloc(size, KM_SLEEP);
2923
2924 err = receive_read_payload_and_next_header(drc, size, buf);
2925 if (err != 0) {
2926 kmem_free(buf, size);
2927 return (err);
2928 }
2929
2930 receive_read_prefetch(drc, drrwe->drr_object, drrwe->drr_offset,
2931 drrwe->drr_length);
2932 return (err);
2933 }
2934 case DRR_FREE:
2935 case DRR_REDACT:
2936 {
2937 /*
2938 * It might be beneficial to prefetch indirect blocks here, but
2939 * we don't really have the data to decide for sure.
2940 */
2941 err = receive_read_payload_and_next_header(drc, 0, NULL);
2942 return (err);
2943 }
2944 case DRR_END:
2945 {
2946 struct drr_end *drre = &drc->drc_rrd->header.drr_u.drr_end;
2947 if (!ZIO_CHECKSUM_EQUAL(drc->drc_prev_cksum,
2948 drre->drr_checksum))
2949 return (SET_ERROR(ECKSUM));
2950 return (0);
2951 }
2952 case DRR_SPILL:
2953 {
2954 struct drr_spill *drrs = &drc->drc_rrd->header.drr_u.drr_spill;
2955 int size = DRR_SPILL_PAYLOAD_SIZE(drrs);
2956 abd_t *abd = abd_alloc_linear(size, B_FALSE);
2957 err = receive_read_payload_and_next_header(drc, size,
2958 abd_to_buf(abd));
2959 if (err != 0)
2960 abd_free(abd);
2961 else
2962 drc->drc_rrd->abd = abd;
2963 return (err);
2964 }
2965 case DRR_OBJECT_RANGE:
2966 {
2967 err = receive_read_payload_and_next_header(drc, 0, NULL);
2968 return (err);
2969
2970 }
2971 default:
2972 return (SET_ERROR(EINVAL));
2973 }
2974 }
2975
2976
2977
2978 static void
dprintf_drr(struct receive_record_arg * rrd,int err)2979 dprintf_drr(struct receive_record_arg *rrd, int err)
2980 {
2981 #ifdef ZFS_DEBUG
2982 switch (rrd->header.drr_type) {
2983 case DRR_OBJECT:
2984 {
2985 struct drr_object *drro = &rrd->header.drr_u.drr_object;
2986 dprintf("drr_type = OBJECT obj = %llu type = %u "
2987 "bonustype = %u blksz = %u bonuslen = %u cksumtype = %u "
2988 "compress = %u dn_slots = %u err = %d\n",
2989 (u_longlong_t)drro->drr_object, drro->drr_type,
2990 drro->drr_bonustype, drro->drr_blksz, drro->drr_bonuslen,
2991 drro->drr_checksumtype, drro->drr_compress,
2992 drro->drr_dn_slots, err);
2993 break;
2994 }
2995 case DRR_FREEOBJECTS:
2996 {
2997 struct drr_freeobjects *drrfo =
2998 &rrd->header.drr_u.drr_freeobjects;
2999 dprintf("drr_type = FREEOBJECTS firstobj = %llu "
3000 "numobjs = %llu err = %d\n",
3001 (u_longlong_t)drrfo->drr_firstobj,
3002 (u_longlong_t)drrfo->drr_numobjs, err);
3003 break;
3004 }
3005 case DRR_WRITE:
3006 {
3007 struct drr_write *drrw = &rrd->header.drr_u.drr_write;
3008 dprintf("drr_type = WRITE obj = %llu type = %u offset = %llu "
3009 "lsize = %llu cksumtype = %u flags = %u "
3010 "compress = %u psize = %llu err = %d\n",
3011 (u_longlong_t)drrw->drr_object, drrw->drr_type,
3012 (u_longlong_t)drrw->drr_offset,
3013 (u_longlong_t)drrw->drr_logical_size,
3014 drrw->drr_checksumtype, drrw->drr_flags,
3015 drrw->drr_compressiontype,
3016 (u_longlong_t)drrw->drr_compressed_size, err);
3017 break;
3018 }
3019 case DRR_WRITE_BYREF:
3020 {
3021 struct drr_write_byref *drrwbr =
3022 &rrd->header.drr_u.drr_write_byref;
3023 dprintf("drr_type = WRITE_BYREF obj = %llu offset = %llu "
3024 "length = %llu toguid = %llx refguid = %llx "
3025 "refobject = %llu refoffset = %llu cksumtype = %u "
3026 "flags = %u err = %d\n",
3027 (u_longlong_t)drrwbr->drr_object,
3028 (u_longlong_t)drrwbr->drr_offset,
3029 (u_longlong_t)drrwbr->drr_length,
3030 (u_longlong_t)drrwbr->drr_toguid,
3031 (u_longlong_t)drrwbr->drr_refguid,
3032 (u_longlong_t)drrwbr->drr_refobject,
3033 (u_longlong_t)drrwbr->drr_refoffset,
3034 drrwbr->drr_checksumtype, drrwbr->drr_flags, err);
3035 break;
3036 }
3037 case DRR_WRITE_EMBEDDED:
3038 {
3039 struct drr_write_embedded *drrwe =
3040 &rrd->header.drr_u.drr_write_embedded;
3041 dprintf("drr_type = WRITE_EMBEDDED obj = %llu offset = %llu "
3042 "length = %llu compress = %u etype = %u lsize = %u "
3043 "psize = %u err = %d\n",
3044 (u_longlong_t)drrwe->drr_object,
3045 (u_longlong_t)drrwe->drr_offset,
3046 (u_longlong_t)drrwe->drr_length,
3047 drrwe->drr_compression, drrwe->drr_etype,
3048 drrwe->drr_lsize, drrwe->drr_psize, err);
3049 break;
3050 }
3051 case DRR_FREE:
3052 {
3053 struct drr_free *drrf = &rrd->header.drr_u.drr_free;
3054 dprintf("drr_type = FREE obj = %llu offset = %llu "
3055 "length = %lld err = %d\n",
3056 (u_longlong_t)drrf->drr_object,
3057 (u_longlong_t)drrf->drr_offset,
3058 (longlong_t)drrf->drr_length,
3059 err);
3060 break;
3061 }
3062 case DRR_SPILL:
3063 {
3064 struct drr_spill *drrs = &rrd->header.drr_u.drr_spill;
3065 dprintf("drr_type = SPILL obj = %llu length = %llu "
3066 "err = %d\n", (u_longlong_t)drrs->drr_object,
3067 (u_longlong_t)drrs->drr_length, err);
3068 break;
3069 }
3070 case DRR_OBJECT_RANGE:
3071 {
3072 struct drr_object_range *drror =
3073 &rrd->header.drr_u.drr_object_range;
3074 dprintf("drr_type = OBJECT_RANGE firstobj = %llu "
3075 "numslots = %llu flags = %u err = %d\n",
3076 (u_longlong_t)drror->drr_firstobj,
3077 (u_longlong_t)drror->drr_numslots,
3078 drror->drr_flags, err);
3079 break;
3080 }
3081 default:
3082 return;
3083 }
3084 #endif
3085 }
3086
3087 /*
3088 * Commit the records to the pool.
3089 */
3090 static int
receive_process_record(struct receive_writer_arg * rwa,struct receive_record_arg * rrd)3091 receive_process_record(struct receive_writer_arg *rwa,
3092 struct receive_record_arg *rrd)
3093 {
3094 int err;
3095
3096 /* Processing in order, therefore bytes_read should be increasing. */
3097 ASSERT3U(rrd->bytes_read, >=, rwa->bytes_read);
3098 rwa->bytes_read = rrd->bytes_read;
3099
3100 /* We can only heal write records; other ones get ignored */
3101 if (rwa->heal && rrd->header.drr_type != DRR_WRITE) {
3102 if (rrd->abd != NULL) {
3103 abd_free(rrd->abd);
3104 rrd->abd = NULL;
3105 } else if (rrd->payload != NULL) {
3106 kmem_free(rrd->payload, rrd->payload_size);
3107 rrd->payload = NULL;
3108 }
3109 return (0);
3110 }
3111
3112 if (!rwa->heal && rrd->header.drr_type != DRR_WRITE) {
3113 err = flush_write_batch(rwa);
3114 if (err != 0) {
3115 if (rrd->abd != NULL) {
3116 abd_free(rrd->abd);
3117 rrd->abd = NULL;
3118 rrd->payload = NULL;
3119 } else if (rrd->payload != NULL) {
3120 kmem_free(rrd->payload, rrd->payload_size);
3121 rrd->payload = NULL;
3122 }
3123
3124 return (err);
3125 }
3126 }
3127
3128 switch (rrd->header.drr_type) {
3129 case DRR_OBJECT:
3130 {
3131 struct drr_object *drro = &rrd->header.drr_u.drr_object;
3132 err = receive_object(rwa, drro, rrd->payload);
3133 kmem_free(rrd->payload, rrd->payload_size);
3134 rrd->payload = NULL;
3135 break;
3136 }
3137 case DRR_FREEOBJECTS:
3138 {
3139 struct drr_freeobjects *drrfo =
3140 &rrd->header.drr_u.drr_freeobjects;
3141 err = receive_freeobjects(rwa, drrfo);
3142 break;
3143 }
3144 case DRR_WRITE:
3145 {
3146 err = receive_process_write_record(rwa, rrd);
3147 if (rwa->heal) {
3148 /*
3149 * If healing - always free the abd after processing
3150 */
3151 abd_free(rrd->abd);
3152 rrd->abd = NULL;
3153 } else if (err != EAGAIN) {
3154 /*
3155 * On success, a non-healing
3156 * receive_process_write_record() returns
3157 * EAGAIN to indicate that we do not want to free
3158 * the rrd or arc_buf.
3159 */
3160 ASSERT(err != 0);
3161 abd_free(rrd->abd);
3162 rrd->abd = NULL;
3163 }
3164 break;
3165 }
3166 case DRR_WRITE_EMBEDDED:
3167 {
3168 struct drr_write_embedded *drrwe =
3169 &rrd->header.drr_u.drr_write_embedded;
3170 err = receive_write_embedded(rwa, drrwe, rrd->payload);
3171 kmem_free(rrd->payload, rrd->payload_size);
3172 rrd->payload = NULL;
3173 break;
3174 }
3175 case DRR_FREE:
3176 {
3177 struct drr_free *drrf = &rrd->header.drr_u.drr_free;
3178 err = receive_free(rwa, drrf);
3179 break;
3180 }
3181 case DRR_SPILL:
3182 {
3183 struct drr_spill *drrs = &rrd->header.drr_u.drr_spill;
3184 err = receive_spill(rwa, drrs, rrd->abd);
3185 if (err != 0)
3186 abd_free(rrd->abd);
3187 rrd->abd = NULL;
3188 rrd->payload = NULL;
3189 break;
3190 }
3191 case DRR_OBJECT_RANGE:
3192 {
3193 struct drr_object_range *drror =
3194 &rrd->header.drr_u.drr_object_range;
3195 err = receive_object_range(rwa, drror);
3196 break;
3197 }
3198 case DRR_REDACT:
3199 {
3200 struct drr_redact *drrr = &rrd->header.drr_u.drr_redact;
3201 err = receive_redact(rwa, drrr);
3202 break;
3203 }
3204 default:
3205 err = (SET_ERROR(EINVAL));
3206 }
3207
3208 if (err != 0)
3209 dprintf_drr(rrd, err);
3210
3211 return (err);
3212 }
3213
3214 /*
3215 * dmu_recv_stream's worker thread; pull records off the queue, and then call
3216 * receive_process_record When we're done, signal the main thread and exit.
3217 */
3218 static __attribute__((noreturn)) void
receive_writer_thread(void * arg)3219 receive_writer_thread(void *arg)
3220 {
3221 struct receive_writer_arg *rwa = arg;
3222 struct receive_record_arg *rrd;
3223 fstrans_cookie_t cookie = spl_fstrans_mark();
3224
3225 for (rrd = bqueue_dequeue(&rwa->q); !rrd->eos_marker;
3226 rrd = bqueue_dequeue(&rwa->q)) {
3227 /*
3228 * If there's an error, the main thread will stop putting things
3229 * on the queue, but we need to clear everything in it before we
3230 * can exit.
3231 */
3232 int err = 0;
3233 if (rwa->err == 0) {
3234 err = receive_process_record(rwa, rrd);
3235 } else if (rrd->abd != NULL) {
3236 abd_free(rrd->abd);
3237 rrd->abd = NULL;
3238 rrd->payload = NULL;
3239 } else if (rrd->payload != NULL) {
3240 kmem_free(rrd->payload, rrd->payload_size);
3241 rrd->payload = NULL;
3242 }
3243 /*
3244 * EAGAIN indicates that this record has been saved (on
3245 * raw->write_batch), and will be used again, so we don't
3246 * free it.
3247 * When healing data we always need to free the record.
3248 */
3249 if (err != EAGAIN || rwa->heal) {
3250 if (rwa->err == 0)
3251 rwa->err = err;
3252 kmem_free(rrd, sizeof (*rrd));
3253 }
3254 }
3255 kmem_free(rrd, sizeof (*rrd));
3256
3257 if (rwa->heal) {
3258 zio_wait(rwa->heal_pio);
3259 } else {
3260 int err = flush_write_batch(rwa);
3261 if (rwa->err == 0)
3262 rwa->err = err;
3263 }
3264 mutex_enter(&rwa->mutex);
3265 rwa->done = B_TRUE;
3266 cv_signal(&rwa->cv);
3267 mutex_exit(&rwa->mutex);
3268 spl_fstrans_unmark(cookie);
3269 thread_exit();
3270 }
3271
3272 static int
resume_check(dmu_recv_cookie_t * drc,nvlist_t * begin_nvl)3273 resume_check(dmu_recv_cookie_t *drc, nvlist_t *begin_nvl)
3274 {
3275 uint64_t val;
3276 objset_t *mos = dmu_objset_pool(drc->drc_os)->dp_meta_objset;
3277 uint64_t dsobj = dmu_objset_id(drc->drc_os);
3278 uint64_t resume_obj, resume_off;
3279
3280 if (nvlist_lookup_uint64(begin_nvl,
3281 "resume_object", &resume_obj) != 0 ||
3282 nvlist_lookup_uint64(begin_nvl,
3283 "resume_offset", &resume_off) != 0) {
3284 return (SET_ERROR(EINVAL));
3285 }
3286 VERIFY0(zap_lookup(mos, dsobj,
3287 DS_FIELD_RESUME_OBJECT, sizeof (val), 1, &val));
3288 if (resume_obj != val)
3289 return (SET_ERROR(EINVAL));
3290 VERIFY0(zap_lookup(mos, dsobj,
3291 DS_FIELD_RESUME_OFFSET, sizeof (val), 1, &val));
3292 if (resume_off != val)
3293 return (SET_ERROR(EINVAL));
3294
3295 return (0);
3296 }
3297
3298 /*
3299 * Read in the stream's records, one by one, and apply them to the pool. There
3300 * are two threads involved; the thread that calls this function will spin up a
3301 * worker thread, read the records off the stream one by one, and issue
3302 * prefetches for any necessary indirect blocks. It will then push the records
3303 * onto an internal blocking queue. The worker thread will pull the records off
3304 * the queue, and actually write the data into the DMU. This way, the worker
3305 * thread doesn't have to wait for reads to complete, since everything it needs
3306 * (the indirect blocks) will be prefetched.
3307 *
3308 * NB: callers *must* call dmu_recv_end() if this succeeds.
3309 */
3310 int
dmu_recv_stream(dmu_recv_cookie_t * drc,offset_t * voffp)3311 dmu_recv_stream(dmu_recv_cookie_t *drc, offset_t *voffp)
3312 {
3313 int err = 0;
3314 struct receive_writer_arg *rwa = kmem_zalloc(sizeof (*rwa), KM_SLEEP);
3315
3316 if (dsl_dataset_has_resume_receive_state(drc->drc_ds)) {
3317 uint64_t bytes = 0;
3318 (void) zap_lookup(drc->drc_ds->ds_dir->dd_pool->dp_meta_objset,
3319 drc->drc_ds->ds_object, DS_FIELD_RESUME_BYTES,
3320 sizeof (bytes), 1, &bytes);
3321 drc->drc_bytes_read += bytes;
3322 }
3323
3324 drc->drc_ignore_objlist = objlist_create();
3325
3326 /* these were verified in dmu_recv_begin */
3327 ASSERT3U(DMU_GET_STREAM_HDRTYPE(drc->drc_drrb->drr_versioninfo), ==,
3328 DMU_SUBSTREAM);
3329 ASSERT3U(drc->drc_drrb->drr_type, <, DMU_OST_NUMTYPES);
3330
3331 ASSERT(dsl_dataset_phys(drc->drc_ds)->ds_flags & DS_FLAG_INCONSISTENT);
3332 ASSERT0(drc->drc_os->os_encrypted &&
3333 (drc->drc_featureflags & DMU_BACKUP_FEATURE_EMBED_DATA));
3334
3335 /* handle DSL encryption key payload */
3336 if (drc->drc_featureflags & DMU_BACKUP_FEATURE_RAW) {
3337 nvlist_t *keynvl = NULL;
3338
3339 ASSERT(drc->drc_os->os_encrypted);
3340 ASSERT(drc->drc_raw);
3341
3342 err = nvlist_lookup_nvlist(drc->drc_begin_nvl, "crypt_keydata",
3343 &keynvl);
3344 if (err != 0)
3345 goto out;
3346
3347 if (!drc->drc_heal) {
3348 /*
3349 * If this is a new dataset we set the key immediately.
3350 * Otherwise we don't want to change the key until we
3351 * are sure the rest of the receive succeeded so we
3352 * stash the keynvl away until then.
3353 */
3354 err = dsl_crypto_recv_raw(spa_name(drc->drc_os->os_spa),
3355 drc->drc_ds->ds_object, drc->drc_fromsnapobj,
3356 drc->drc_drrb->drr_type, keynvl, drc->drc_newfs);
3357 if (err != 0)
3358 goto out;
3359 }
3360
3361 /* see comment in dmu_recv_end_sync() */
3362 drc->drc_ivset_guid = 0;
3363 (void) nvlist_lookup_uint64(keynvl, "to_ivset_guid",
3364 &drc->drc_ivset_guid);
3365
3366 if (!drc->drc_newfs)
3367 drc->drc_keynvl = fnvlist_dup(keynvl);
3368 }
3369
3370 if (drc->drc_featureflags & DMU_BACKUP_FEATURE_RESUMING) {
3371 err = resume_check(drc, drc->drc_begin_nvl);
3372 if (err != 0)
3373 goto out;
3374 }
3375
3376 /*
3377 * For compatibility with recursive send streams, we do this here,
3378 * rather than in dmu_recv_begin. If we pull the next header too
3379 * early, and it's the END record, we break the `recv_skip` logic.
3380 */
3381 if (drc->drc_drr_begin->drr_payloadlen == 0) {
3382 err = receive_read_payload_and_next_header(drc, 0, NULL);
3383 if (err != 0)
3384 goto out;
3385 }
3386
3387 /*
3388 * If we failed before this point we will clean up any new resume
3389 * state that was created. Now that we've gotten past the initial
3390 * checks we are ok to retain that resume state.
3391 */
3392 drc->drc_should_save = B_TRUE;
3393
3394 (void) bqueue_init(&rwa->q, zfs_recv_queue_ff,
3395 MAX(zfs_recv_queue_length, 2 * zfs_max_recordsize),
3396 offsetof(struct receive_record_arg, node));
3397 cv_init(&rwa->cv, NULL, CV_DEFAULT, NULL);
3398 mutex_init(&rwa->mutex, NULL, MUTEX_DEFAULT, NULL);
3399 rwa->os = drc->drc_os;
3400 rwa->byteswap = drc->drc_byteswap;
3401 rwa->heal = drc->drc_heal;
3402 rwa->tofs = drc->drc_tofs;
3403 rwa->resumable = drc->drc_resumable;
3404 rwa->raw = drc->drc_raw;
3405 rwa->spill = drc->drc_spill;
3406 rwa->full = (drc->drc_drr_begin->drr_u.drr_begin.drr_fromguid == 0);
3407 rwa->os->os_raw_receive = drc->drc_raw;
3408 if (drc->drc_heal) {
3409 rwa->heal_pio = zio_root(drc->drc_os->os_spa, NULL, NULL,
3410 ZIO_FLAG_GODFATHER);
3411 }
3412 list_create(&rwa->write_batch, sizeof (struct receive_record_arg),
3413 offsetof(struct receive_record_arg, node.bqn_node));
3414
3415 (void) thread_create(NULL, 0, receive_writer_thread, rwa, 0, curproc,
3416 TS_RUN, minclsyspri);
3417 /*
3418 * We're reading rwa->err without locks, which is safe since we are the
3419 * only reader, and the worker thread is the only writer. It's ok if we
3420 * miss a write for an iteration or two of the loop, since the writer
3421 * thread will keep freeing records we send it until we send it an eos
3422 * marker.
3423 *
3424 * We can leave this loop in 3 ways: First, if rwa->err is
3425 * non-zero. In that case, the writer thread will free the rrd we just
3426 * pushed. Second, if we're interrupted; in that case, either it's the
3427 * first loop and drc->drc_rrd was never allocated, or it's later, and
3428 * drc->drc_rrd has been handed off to the writer thread who will free
3429 * it. Finally, if receive_read_record fails or we're at the end of the
3430 * stream, then we free drc->drc_rrd and exit.
3431 */
3432 while (rwa->err == 0) {
3433 if (issig()) {
3434 err = SET_ERROR(EINTR);
3435 break;
3436 }
3437
3438 ASSERT3P(drc->drc_rrd, ==, NULL);
3439 drc->drc_rrd = drc->drc_next_rrd;
3440 drc->drc_next_rrd = NULL;
3441 /* Allocates and loads header into drc->drc_next_rrd */
3442 err = receive_read_record(drc);
3443
3444 if (drc->drc_rrd->header.drr_type == DRR_END || err != 0) {
3445 kmem_free(drc->drc_rrd, sizeof (*drc->drc_rrd));
3446 drc->drc_rrd = NULL;
3447 break;
3448 }
3449
3450 bqueue_enqueue(&rwa->q, drc->drc_rrd,
3451 sizeof (struct receive_record_arg) +
3452 drc->drc_rrd->payload_size);
3453 drc->drc_rrd = NULL;
3454 }
3455
3456 ASSERT3P(drc->drc_rrd, ==, NULL);
3457 drc->drc_rrd = kmem_zalloc(sizeof (*drc->drc_rrd), KM_SLEEP);
3458 drc->drc_rrd->eos_marker = B_TRUE;
3459 bqueue_enqueue_flush(&rwa->q, drc->drc_rrd, 1);
3460
3461 mutex_enter(&rwa->mutex);
3462 while (!rwa->done) {
3463 /*
3464 * We need to use cv_wait_sig() so that any process that may
3465 * be sleeping here can still fork.
3466 */
3467 (void) cv_wait_sig(&rwa->cv, &rwa->mutex);
3468 }
3469 mutex_exit(&rwa->mutex);
3470
3471 /*
3472 * If we are receiving a full stream as a clone, all object IDs which
3473 * are greater than the maximum ID referenced in the stream are
3474 * by definition unused and must be freed.
3475 */
3476 if (drc->drc_clone && drc->drc_drrb->drr_fromguid == 0) {
3477 uint64_t obj = rwa->max_object + 1;
3478 int free_err = 0;
3479 int next_err = 0;
3480
3481 while (next_err == 0) {
3482 free_err = dmu_free_long_object(rwa->os, obj);
3483 if (free_err != 0 && free_err != ENOENT)
3484 break;
3485
3486 next_err = dmu_object_next(rwa->os, &obj, FALSE, 0);
3487 }
3488
3489 if (err == 0) {
3490 if (free_err != 0 && free_err != ENOENT)
3491 err = free_err;
3492 else if (next_err != ESRCH)
3493 err = next_err;
3494 }
3495 }
3496
3497 cv_destroy(&rwa->cv);
3498 mutex_destroy(&rwa->mutex);
3499 bqueue_destroy(&rwa->q);
3500 list_destroy(&rwa->write_batch);
3501 if (err == 0)
3502 err = rwa->err;
3503
3504 out:
3505 /*
3506 * If we hit an error before we started the receive_writer_thread
3507 * we need to clean up the next_rrd we create by processing the
3508 * DRR_BEGIN record.
3509 */
3510 if (drc->drc_next_rrd != NULL)
3511 kmem_free(drc->drc_next_rrd, sizeof (*drc->drc_next_rrd));
3512
3513 /*
3514 * The objset will be invalidated by dmu_recv_end() when we do
3515 * dsl_dataset_clone_swap_sync_impl().
3516 */
3517 drc->drc_os = NULL;
3518
3519 kmem_free(rwa, sizeof (*rwa));
3520 nvlist_free(drc->drc_begin_nvl);
3521
3522 if (err != 0) {
3523 /*
3524 * Clean up references. If receive is not resumable,
3525 * destroy what we created, so we don't leave it in
3526 * the inconsistent state.
3527 */
3528 dmu_recv_cleanup_ds(drc);
3529 nvlist_free(drc->drc_keynvl);
3530 }
3531
3532 objlist_destroy(drc->drc_ignore_objlist);
3533 drc->drc_ignore_objlist = NULL;
3534 *voffp = drc->drc_voff;
3535 return (err);
3536 }
3537
3538 static int
dmu_recv_end_check(void * arg,dmu_tx_t * tx)3539 dmu_recv_end_check(void *arg, dmu_tx_t *tx)
3540 {
3541 dmu_recv_cookie_t *drc = arg;
3542 dsl_pool_t *dp = dmu_tx_pool(tx);
3543 int error;
3544
3545 ASSERT3P(drc->drc_ds->ds_owner, ==, dmu_recv_tag);
3546
3547 if (drc->drc_heal) {
3548 error = 0;
3549 } else if (!drc->drc_newfs) {
3550 dsl_dataset_t *origin_head;
3551
3552 error = dsl_dataset_hold(dp, drc->drc_tofs, FTAG, &origin_head);
3553 if (error != 0)
3554 return (error);
3555 if (drc->drc_force) {
3556 /*
3557 * We will destroy any snapshots in tofs (i.e. before
3558 * origin_head) that are after the origin (which is
3559 * the snap before drc_ds, because drc_ds can not
3560 * have any snaps of its own).
3561 */
3562 uint64_t obj;
3563
3564 obj = dsl_dataset_phys(origin_head)->ds_prev_snap_obj;
3565 while (obj !=
3566 dsl_dataset_phys(drc->drc_ds)->ds_prev_snap_obj) {
3567 dsl_dataset_t *snap;
3568 error = dsl_dataset_hold_obj(dp, obj, FTAG,
3569 &snap);
3570 if (error != 0)
3571 break;
3572 if (snap->ds_dir != origin_head->ds_dir)
3573 error = SET_ERROR(EINVAL);
3574 if (error == 0) {
3575 error = dsl_destroy_snapshot_check_impl(
3576 snap, B_FALSE);
3577 }
3578 obj = dsl_dataset_phys(snap)->ds_prev_snap_obj;
3579 dsl_dataset_rele(snap, FTAG);
3580 if (error != 0)
3581 break;
3582 }
3583 if (error != 0) {
3584 dsl_dataset_rele(origin_head, FTAG);
3585 return (error);
3586 }
3587 }
3588 if (drc->drc_keynvl != NULL) {
3589 error = dsl_crypto_recv_raw_key_check(drc->drc_ds,
3590 drc->drc_keynvl, tx);
3591 if (error != 0) {
3592 dsl_dataset_rele(origin_head, FTAG);
3593 return (error);
3594 }
3595 }
3596
3597 error = dsl_dataset_clone_swap_check_impl(drc->drc_ds,
3598 origin_head, drc->drc_force, drc->drc_owner, tx);
3599 if (error != 0) {
3600 dsl_dataset_rele(origin_head, FTAG);
3601 return (error);
3602 }
3603 error = dsl_dataset_snapshot_check_impl(origin_head,
3604 drc->drc_tosnap, tx, B_TRUE, 1,
3605 drc->drc_cred, drc->drc_proc);
3606 dsl_dataset_rele(origin_head, FTAG);
3607 if (error != 0)
3608 return (error);
3609
3610 error = dsl_destroy_head_check_impl(drc->drc_ds, 1);
3611 } else {
3612 error = dsl_dataset_snapshot_check_impl(drc->drc_ds,
3613 drc->drc_tosnap, tx, B_TRUE, 1,
3614 drc->drc_cred, drc->drc_proc);
3615 }
3616 return (error);
3617 }
3618
3619 static void
dmu_recv_end_sync(void * arg,dmu_tx_t * tx)3620 dmu_recv_end_sync(void *arg, dmu_tx_t *tx)
3621 {
3622 dmu_recv_cookie_t *drc = arg;
3623 dsl_pool_t *dp = dmu_tx_pool(tx);
3624 boolean_t encrypted = drc->drc_ds->ds_dir->dd_crypto_obj != 0;
3625 uint64_t newsnapobj = 0;
3626
3627 spa_history_log_internal_ds(drc->drc_ds, "finish receiving",
3628 tx, "snap=%s", drc->drc_tosnap);
3629 drc->drc_ds->ds_objset->os_raw_receive = B_FALSE;
3630
3631 if (drc->drc_heal) {
3632 if (drc->drc_keynvl != NULL) {
3633 nvlist_free(drc->drc_keynvl);
3634 drc->drc_keynvl = NULL;
3635 }
3636 } else if (!drc->drc_newfs) {
3637 dsl_dataset_t *origin_head;
3638
3639 VERIFY0(dsl_dataset_hold(dp, drc->drc_tofs, FTAG,
3640 &origin_head));
3641
3642 if (drc->drc_force) {
3643 /*
3644 * Destroy any snapshots of drc_tofs (origin_head)
3645 * after the origin (the snap before drc_ds).
3646 */
3647 uint64_t obj;
3648
3649 obj = dsl_dataset_phys(origin_head)->ds_prev_snap_obj;
3650 while (obj !=
3651 dsl_dataset_phys(drc->drc_ds)->ds_prev_snap_obj) {
3652 dsl_dataset_t *snap;
3653 VERIFY0(dsl_dataset_hold_obj(dp, obj, FTAG,
3654 &snap));
3655 ASSERT3P(snap->ds_dir, ==, origin_head->ds_dir);
3656 obj = dsl_dataset_phys(snap)->ds_prev_snap_obj;
3657 dsl_destroy_snapshot_sync_impl(snap,
3658 B_FALSE, tx);
3659 dsl_dataset_rele(snap, FTAG);
3660 }
3661 }
3662 if (drc->drc_keynvl != NULL) {
3663 dsl_crypto_recv_raw_key_sync(drc->drc_ds,
3664 drc->drc_keynvl, tx);
3665 nvlist_free(drc->drc_keynvl);
3666 drc->drc_keynvl = NULL;
3667 }
3668
3669 VERIFY3P(drc->drc_ds->ds_prev, ==,
3670 origin_head->ds_prev);
3671
3672 dsl_dataset_clone_swap_sync_impl(drc->drc_ds,
3673 origin_head, tx);
3674 /*
3675 * The objset was evicted by dsl_dataset_clone_swap_sync_impl,
3676 * so drc_os is no longer valid.
3677 */
3678 drc->drc_os = NULL;
3679
3680 dsl_dataset_snapshot_sync_impl(origin_head,
3681 drc->drc_tosnap, tx);
3682
3683 /* set snapshot's creation time and guid */
3684 dmu_buf_will_dirty(origin_head->ds_prev->ds_dbuf, tx);
3685 dsl_dataset_phys(origin_head->ds_prev)->ds_creation_time =
3686 drc->drc_drrb->drr_creation_time;
3687 dsl_dataset_phys(origin_head->ds_prev)->ds_guid =
3688 drc->drc_drrb->drr_toguid;
3689 dsl_dataset_phys(origin_head->ds_prev)->ds_flags &=
3690 ~DS_FLAG_INCONSISTENT;
3691
3692 dmu_buf_will_dirty(origin_head->ds_dbuf, tx);
3693 dsl_dataset_phys(origin_head)->ds_flags &=
3694 ~DS_FLAG_INCONSISTENT;
3695
3696 newsnapobj =
3697 dsl_dataset_phys(origin_head)->ds_prev_snap_obj;
3698
3699 dsl_dataset_rele(origin_head, FTAG);
3700 dsl_destroy_head_sync_impl(drc->drc_ds, tx);
3701
3702 if (drc->drc_owner != NULL)
3703 VERIFY3P(origin_head->ds_owner, ==, drc->drc_owner);
3704 } else {
3705 dsl_dataset_t *ds = drc->drc_ds;
3706
3707 dsl_dataset_snapshot_sync_impl(ds, drc->drc_tosnap, tx);
3708
3709 /* set snapshot's creation time and guid */
3710 dmu_buf_will_dirty(ds->ds_prev->ds_dbuf, tx);
3711 dsl_dataset_phys(ds->ds_prev)->ds_creation_time =
3712 drc->drc_drrb->drr_creation_time;
3713 dsl_dataset_phys(ds->ds_prev)->ds_guid =
3714 drc->drc_drrb->drr_toguid;
3715 dsl_dataset_phys(ds->ds_prev)->ds_flags &=
3716 ~DS_FLAG_INCONSISTENT;
3717
3718 dmu_buf_will_dirty(ds->ds_dbuf, tx);
3719 dsl_dataset_phys(ds)->ds_flags &= ~DS_FLAG_INCONSISTENT;
3720 if (dsl_dataset_has_resume_receive_state(ds)) {
3721 (void) zap_remove(dp->dp_meta_objset, ds->ds_object,
3722 DS_FIELD_RESUME_FROMGUID, tx);
3723 (void) zap_remove(dp->dp_meta_objset, ds->ds_object,
3724 DS_FIELD_RESUME_OBJECT, tx);
3725 (void) zap_remove(dp->dp_meta_objset, ds->ds_object,
3726 DS_FIELD_RESUME_OFFSET, tx);
3727 (void) zap_remove(dp->dp_meta_objset, ds->ds_object,
3728 DS_FIELD_RESUME_BYTES, tx);
3729 (void) zap_remove(dp->dp_meta_objset, ds->ds_object,
3730 DS_FIELD_RESUME_TOGUID, tx);
3731 (void) zap_remove(dp->dp_meta_objset, ds->ds_object,
3732 DS_FIELD_RESUME_TONAME, tx);
3733 (void) zap_remove(dp->dp_meta_objset, ds->ds_object,
3734 DS_FIELD_RESUME_REDACT_BOOKMARK_SNAPS, tx);
3735 }
3736 newsnapobj =
3737 dsl_dataset_phys(drc->drc_ds)->ds_prev_snap_obj;
3738 }
3739
3740 /*
3741 * If this is a raw receive, the crypt_keydata nvlist will include
3742 * a to_ivset_guid for us to set on the new snapshot. This value
3743 * will override the value generated by the snapshot code. However,
3744 * this value may not be present, because older implementations of
3745 * the raw send code did not include this value, and we are still
3746 * allowed to receive them if the zfs_disable_ivset_guid_check
3747 * tunable is set, in which case we will leave the newly-generated
3748 * value.
3749 */
3750 if (!drc->drc_heal && drc->drc_raw && drc->drc_ivset_guid != 0) {
3751 dmu_object_zapify(dp->dp_meta_objset, newsnapobj,
3752 DMU_OT_DSL_DATASET, tx);
3753 VERIFY0(zap_update(dp->dp_meta_objset, newsnapobj,
3754 DS_FIELD_IVSET_GUID, sizeof (uint64_t), 1,
3755 &drc->drc_ivset_guid, tx));
3756 }
3757
3758 /*
3759 * Release the hold from dmu_recv_begin. This must be done before
3760 * we return to open context, so that when we free the dataset's dnode
3761 * we can evict its bonus buffer. Since the dataset may be destroyed
3762 * at this point (and therefore won't have a valid pointer to the spa)
3763 * we release the key mapping manually here while we do have a valid
3764 * pointer, if it exists.
3765 */
3766 if (!drc->drc_raw && encrypted) {
3767 (void) spa_keystore_remove_mapping(dmu_tx_pool(tx)->dp_spa,
3768 drc->drc_ds->ds_object, drc->drc_ds);
3769 }
3770 dsl_dataset_disown(drc->drc_ds, 0, dmu_recv_tag);
3771 drc->drc_ds = NULL;
3772 }
3773
3774 static int dmu_recv_end_modified_blocks = 3;
3775
3776 static int
dmu_recv_existing_end(dmu_recv_cookie_t * drc)3777 dmu_recv_existing_end(dmu_recv_cookie_t *drc)
3778 {
3779 #ifdef _KERNEL
3780 /*
3781 * We will be destroying the ds; make sure its origin is unmounted if
3782 * necessary.
3783 */
3784 char name[ZFS_MAX_DATASET_NAME_LEN];
3785 dsl_dataset_name(drc->drc_ds, name);
3786 zfs_destroy_unmount_origin(name);
3787 #endif
3788
3789 return (dsl_sync_task(drc->drc_tofs,
3790 dmu_recv_end_check, dmu_recv_end_sync, drc,
3791 dmu_recv_end_modified_blocks, ZFS_SPACE_CHECK_NORMAL));
3792 }
3793
3794 static int
dmu_recv_new_end(dmu_recv_cookie_t * drc)3795 dmu_recv_new_end(dmu_recv_cookie_t *drc)
3796 {
3797 return (dsl_sync_task(drc->drc_tofs,
3798 dmu_recv_end_check, dmu_recv_end_sync, drc,
3799 dmu_recv_end_modified_blocks, ZFS_SPACE_CHECK_NORMAL));
3800 }
3801
3802 int
dmu_recv_end(dmu_recv_cookie_t * drc,void * owner)3803 dmu_recv_end(dmu_recv_cookie_t *drc, void *owner)
3804 {
3805 int error;
3806
3807 drc->drc_owner = owner;
3808
3809 if (drc->drc_newfs)
3810 error = dmu_recv_new_end(drc);
3811 else
3812 error = dmu_recv_existing_end(drc);
3813
3814 if (error != 0) {
3815 dmu_recv_cleanup_ds(drc);
3816 nvlist_free(drc->drc_keynvl);
3817 } else if (!drc->drc_heal) {
3818 if (drc->drc_newfs) {
3819 zvol_create_minor(drc->drc_tofs);
3820 }
3821 char *snapname = kmem_asprintf("%s@%s",
3822 drc->drc_tofs, drc->drc_tosnap);
3823 zvol_create_minor(snapname);
3824 kmem_strfree(snapname);
3825 }
3826 return (error);
3827 }
3828
3829 /*
3830 * Return TRUE if this objset is currently being received into.
3831 */
3832 boolean_t
dmu_objset_is_receiving(objset_t * os)3833 dmu_objset_is_receiving(objset_t *os)
3834 {
3835 return (os->os_dsl_dataset != NULL &&
3836 os->os_dsl_dataset->ds_owner == dmu_recv_tag);
3837 }
3838
3839 ZFS_MODULE_PARAM(zfs_recv, zfs_recv_, queue_length, UINT, ZMOD_RW,
3840 "Maximum receive queue length");
3841
3842 ZFS_MODULE_PARAM(zfs_recv, zfs_recv_, queue_ff, UINT, ZMOD_RW,
3843 "Receive queue fill fraction");
3844
3845 ZFS_MODULE_PARAM(zfs_recv, zfs_recv_, write_batch_size, UINT, ZMOD_RW,
3846 "Maximum amount of writes to batch into one transaction");
3847
3848 ZFS_MODULE_PARAM(zfs_recv, zfs_recv_, best_effort_corrective, INT, ZMOD_RW,
3849 "Ignore errors during corrective receive");
3850