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