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