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