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