Path: blob/main/sys/contrib/openzfs/module/zfs/dmu_recv.c
48383 views
// SPDX-License-Identifier: CDDL-1.01/*2* CDDL HEADER START3*4* The contents of this file are subject to the terms of the5* 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.LICENSE9* or https://opensource.org/licenses/CDDL-1.0.10* See the License for the specific language governing permissions11* and limitations under the License.12*13* When distributing Covered Code, include this CDDL HEADER in each14* file and include the License file at usr/src/OPENSOLARIS.LICENSE.15* If applicable, add the following below this CDDL HEADER, with the16* fields enclosed by brackets "[]" replaced with your own identifying17* information: Portions Copyright [yyyy] [name of copyright owner]18*19* CDDL HEADER END20*/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 <[email protected]>. All rights reserved.28* Copyright (c) 2019, 2024, Klara, Inc.29* Copyright (c) 2019, Allan Jude30* Copyright (c) 2019 Datto Inc.31* Copyright (c) 2022 Axcient.32* Copyright (c) 2025, Rob Norris <[email protected]>33*/3435#include <sys/arc.h>36#include <sys/spa_impl.h>37#include <sys/dmu.h>38#include <sys/dmu_impl.h>39#include <sys/dmu_send.h>40#include <sys/dmu_recv.h>41#include <sys/dmu_tx.h>42#include <sys/dbuf.h>43#include <sys/dnode.h>44#include <sys/zfs_context.h>45#include <sys/dmu_objset.h>46#include <sys/dmu_traverse.h>47#include <sys/dsl_dataset.h>48#include <sys/dsl_dir.h>49#include <sys/dsl_prop.h>50#include <sys/dsl_pool.h>51#include <sys/dsl_synctask.h>52#include <sys/zfs_ioctl.h>53#include <sys/zap.h>54#include <sys/zvol.h>55#include <sys/zio_checksum.h>56#include <sys/zfs_znode.h>57#include <zfs_fletcher.h>58#include <sys/avl.h>59#include <sys/ddt.h>60#include <sys/zfs_onexit.h>61#include <sys/dsl_destroy.h>62#include <sys/blkptr.h>63#include <sys/dsl_bookmark.h>64#include <sys/zfeature.h>65#include <sys/bqueue.h>66#include <sys/objlist.h>67#ifdef _KERNEL68#include <sys/zfs_vfsops.h>69#endif70#include <sys/zfs_file.h>71#include <sys/cred.h>7273static uint_t zfs_recv_queue_length = SPA_MAXBLOCKSIZE;74static uint_t zfs_recv_queue_ff = 20;75static uint_t zfs_recv_write_batch_size = 1024 * 1024;76static int zfs_recv_best_effort_corrective = 0;7778static const void *const dmu_recv_tag = "dmu_recv_tag";79const char *const recv_clone_name = "%recv";8081typedef enum {82ORNS_NO,83ORNS_YES,84ORNS_MAYBE85} or_need_sync_t;8687static int receive_read_payload_and_next_header(dmu_recv_cookie_t *ra, int len,88void *buf);8990struct receive_record_arg {91dmu_replay_record_t header;92void *payload; /* Pointer to a buffer containing the payload */93/*94* If the record is a WRITE or SPILL, pointer to the abd containing the95* payload.96*/97abd_t *abd;98int payload_size;99uint64_t bytes_read; /* bytes read from stream when record created */100boolean_t eos_marker; /* Marks the end of the stream */101bqueue_node_t node;102};103104struct receive_writer_arg {105objset_t *os;106boolean_t byteswap;107bqueue_t q;108109/*110* These three members are used to signal to the main thread when111* we're done.112*/113kmutex_t mutex;114kcondvar_t cv;115boolean_t done;116117int err;118const char *tofs;119boolean_t heal;120boolean_t resumable;121boolean_t raw; /* DMU_BACKUP_FEATURE_RAW set */122boolean_t spill; /* DRR_FLAG_SPILL_BLOCK set */123boolean_t full; /* this is a full send stream */124uint64_t last_object;125uint64_t last_offset;126uint64_t max_object; /* highest object ID referenced in stream */127uint64_t bytes_read; /* bytes read when current record created */128129list_t write_batch;130131/* Encryption parameters for the last received DRR_OBJECT_RANGE */132boolean_t or_crypt_params_present;133uint64_t or_firstobj;134uint64_t or_numslots;135uint8_t or_salt[ZIO_DATA_SALT_LEN];136uint8_t or_iv[ZIO_DATA_IV_LEN];137uint8_t or_mac[ZIO_DATA_MAC_LEN];138boolean_t or_byteorder;139zio_t *heal_pio;140141/* Keep track of DRR_FREEOBJECTS right after DRR_OBJECT_RANGE */142or_need_sync_t or_need_sync;143};144145typedef struct dmu_recv_begin_arg {146const char *drba_origin;147dmu_recv_cookie_t *drba_cookie;148cred_t *drba_cred;149dsl_crypto_params_t *drba_dcp;150} dmu_recv_begin_arg_t;151152static void153byteswap_record(dmu_replay_record_t *drr)154{155#define DO64(X) (drr->drr_u.X = BSWAP_64(drr->drr_u.X))156#define DO32(X) (drr->drr_u.X = BSWAP_32(drr->drr_u.X))157drr->drr_type = BSWAP_32(drr->drr_type);158drr->drr_payloadlen = BSWAP_32(drr->drr_payloadlen);159160switch (drr->drr_type) {161case DRR_BEGIN:162DO64(drr_begin.drr_magic);163DO64(drr_begin.drr_versioninfo);164DO64(drr_begin.drr_creation_time);165DO32(drr_begin.drr_type);166DO32(drr_begin.drr_flags);167DO64(drr_begin.drr_toguid);168DO64(drr_begin.drr_fromguid);169break;170case DRR_OBJECT:171DO64(drr_object.drr_object);172DO32(drr_object.drr_type);173DO32(drr_object.drr_bonustype);174DO32(drr_object.drr_blksz);175DO32(drr_object.drr_bonuslen);176DO32(drr_object.drr_raw_bonuslen);177DO64(drr_object.drr_toguid);178DO64(drr_object.drr_maxblkid);179break;180case DRR_FREEOBJECTS:181DO64(drr_freeobjects.drr_firstobj);182DO64(drr_freeobjects.drr_numobjs);183DO64(drr_freeobjects.drr_toguid);184break;185case DRR_WRITE:186DO64(drr_write.drr_object);187DO32(drr_write.drr_type);188DO64(drr_write.drr_offset);189DO64(drr_write.drr_logical_size);190DO64(drr_write.drr_toguid);191ZIO_CHECKSUM_BSWAP(&drr->drr_u.drr_write.drr_key.ddk_cksum);192DO64(drr_write.drr_key.ddk_prop);193DO64(drr_write.drr_compressed_size);194break;195case DRR_WRITE_EMBEDDED:196DO64(drr_write_embedded.drr_object);197DO64(drr_write_embedded.drr_offset);198DO64(drr_write_embedded.drr_length);199DO64(drr_write_embedded.drr_toguid);200DO32(drr_write_embedded.drr_lsize);201DO32(drr_write_embedded.drr_psize);202break;203case DRR_FREE:204DO64(drr_free.drr_object);205DO64(drr_free.drr_offset);206DO64(drr_free.drr_length);207DO64(drr_free.drr_toguid);208break;209case DRR_SPILL:210DO64(drr_spill.drr_object);211DO64(drr_spill.drr_length);212DO64(drr_spill.drr_toguid);213DO64(drr_spill.drr_compressed_size);214DO32(drr_spill.drr_type);215break;216case DRR_OBJECT_RANGE:217DO64(drr_object_range.drr_firstobj);218DO64(drr_object_range.drr_numslots);219DO64(drr_object_range.drr_toguid);220break;221case DRR_REDACT:222DO64(drr_redact.drr_object);223DO64(drr_redact.drr_offset);224DO64(drr_redact.drr_length);225DO64(drr_redact.drr_toguid);226break;227case DRR_END:228DO64(drr_end.drr_toguid);229ZIO_CHECKSUM_BSWAP(&drr->drr_u.drr_end.drr_checksum);230break;231default:232break;233}234235if (drr->drr_type != DRR_BEGIN) {236ZIO_CHECKSUM_BSWAP(&drr->drr_u.drr_checksum.drr_checksum);237}238239#undef DO64240#undef DO32241}242243static boolean_t244redact_snaps_contains(uint64_t *snaps, uint64_t num_snaps, uint64_t guid)245{246for (int i = 0; i < num_snaps; i++) {247if (snaps[i] == guid)248return (B_TRUE);249}250return (B_FALSE);251}252253/*254* Check that the new stream we're trying to receive is redacted with respect to255* a subset of the snapshots that the origin was redacted with respect to. For256* the reasons behind this, see the man page on redacted zfs sends and receives.257*/258static boolean_t259compatible_redact_snaps(uint64_t *origin_snaps, uint64_t origin_num_snaps,260uint64_t *redact_snaps, uint64_t num_redact_snaps)261{262/*263* Short circuit the comparison; if we are redacted with respect to264* more snapshots than the origin, we can't be redacted with respect265* to a subset.266*/267if (num_redact_snaps > origin_num_snaps) {268return (B_FALSE);269}270271for (int i = 0; i < num_redact_snaps; i++) {272if (!redact_snaps_contains(origin_snaps, origin_num_snaps,273redact_snaps[i])) {274return (B_FALSE);275}276}277return (B_TRUE);278}279280static boolean_t281redact_check(dmu_recv_begin_arg_t *drba, dsl_dataset_t *origin)282{283uint64_t *origin_snaps;284uint64_t origin_num_snaps;285dmu_recv_cookie_t *drc = drba->drba_cookie;286struct drr_begin *drrb = drc->drc_drrb;287int featureflags = DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo);288int err = 0;289boolean_t ret = B_TRUE;290uint64_t *redact_snaps;291uint_t numredactsnaps;292293/*294* If this is a full send stream, we're safe no matter what.295*/296if (drrb->drr_fromguid == 0)297return (ret);298299VERIFY(dsl_dataset_get_uint64_array_feature(origin,300SPA_FEATURE_REDACTED_DATASETS, &origin_num_snaps, &origin_snaps));301302if (nvlist_lookup_uint64_array(drc->drc_begin_nvl,303BEGINNV_REDACT_FROM_SNAPS, &redact_snaps, &numredactsnaps) ==3040) {305/*306* If the send stream was sent from the redaction bookmark or307* the redacted version of the dataset, then we're safe. Verify308* that this is from the a compatible redaction bookmark or309* redacted dataset.310*/311if (!compatible_redact_snaps(origin_snaps, origin_num_snaps,312redact_snaps, numredactsnaps)) {313err = EINVAL;314}315} else if (featureflags & DMU_BACKUP_FEATURE_REDACTED) {316/*317* If the stream is redacted, it must be redacted with respect318* to a subset of what the origin is redacted with respect to.319* See case number 2 in the zfs man page section on redacted zfs320* send.321*/322err = nvlist_lookup_uint64_array(drc->drc_begin_nvl,323BEGINNV_REDACT_SNAPS, &redact_snaps, &numredactsnaps);324325if (err != 0 || !compatible_redact_snaps(origin_snaps,326origin_num_snaps, redact_snaps, numredactsnaps)) {327err = EINVAL;328}329} else if (!redact_snaps_contains(origin_snaps, origin_num_snaps,330drrb->drr_toguid)) {331/*332* If the stream isn't redacted but the origin is, this must be333* one of the snapshots the origin is redacted with respect to.334* See case number 1 in the zfs man page section on redacted zfs335* send.336*/337err = EINVAL;338}339340if (err != 0)341ret = B_FALSE;342return (ret);343}344345/*346* If we previously received a stream with --large-block, we don't support347* receiving an incremental on top of it without --large-block. This avoids348* forcing a read-modify-write or trying to re-aggregate a string of WRITE349* records.350*/351static int352recv_check_large_blocks(dsl_dataset_t *ds, uint64_t featureflags)353{354if (dsl_dataset_feature_is_active(ds, SPA_FEATURE_LARGE_BLOCKS) &&355!(featureflags & DMU_BACKUP_FEATURE_LARGE_BLOCKS))356return (SET_ERROR(ZFS_ERR_STREAM_LARGE_BLOCK_MISMATCH));357return (0);358}359360static int361recv_begin_check_existing_impl(dmu_recv_begin_arg_t *drba, dsl_dataset_t *ds,362uint64_t fromguid, uint64_t featureflags)363{364uint64_t obj;365uint64_t children;366int error;367dsl_dataset_t *snap;368dsl_pool_t *dp = ds->ds_dir->dd_pool;369boolean_t encrypted = ds->ds_dir->dd_crypto_obj != 0;370boolean_t raw = (featureflags & DMU_BACKUP_FEATURE_RAW) != 0;371boolean_t embed = (featureflags & DMU_BACKUP_FEATURE_EMBED_DATA) != 0;372373/* Temporary clone name must not exist. */374error = zap_lookup(dp->dp_meta_objset,375dsl_dir_phys(ds->ds_dir)->dd_child_dir_zapobj, recv_clone_name,3768, 1, &obj);377if (error != ENOENT)378return (error == 0 ? SET_ERROR(EBUSY) : error);379380/* Resume state must not be set. */381if (dsl_dataset_has_resume_receive_state(ds))382return (SET_ERROR(EBUSY));383384/* New snapshot name must not exist if we're not healing it. */385error = zap_lookup(dp->dp_meta_objset,386dsl_dataset_phys(ds)->ds_snapnames_zapobj,387drba->drba_cookie->drc_tosnap, 8, 1, &obj);388if (drba->drba_cookie->drc_heal) {389if (error != 0)390return (error);391} else if (error != ENOENT) {392return (error == 0 ? SET_ERROR(EEXIST) : error);393}394395/* Must not have children if receiving a ZVOL. */396error = zap_count(dp->dp_meta_objset,397dsl_dir_phys(ds->ds_dir)->dd_child_dir_zapobj, &children);398if (error != 0)399return (error);400if (drba->drba_cookie->drc_drrb->drr_type != DMU_OST_ZFS &&401children > 0)402return (SET_ERROR(ZFS_ERR_WRONG_PARENT));403404/*405* Check snapshot limit before receiving. We'll recheck again at the406* end, but might as well abort before receiving if we're already over407* the limit.408*409* Note that we do not check the file system limit with410* dsl_dir_fscount_check because the temporary %clones don't count411* against that limit.412*/413error = dsl_fs_ss_limit_check(ds->ds_dir, 1, ZFS_PROP_SNAPSHOT_LIMIT,414NULL, drba->drba_cred);415if (error != 0)416return (error);417418if (drba->drba_cookie->drc_heal) {419/* Encryption is incompatible with embedded data. */420if (encrypted && embed)421return (SET_ERROR(EINVAL));422423/* Healing is not supported when in 'force' mode. */424if (drba->drba_cookie->drc_force)425return (SET_ERROR(EINVAL));426427/* Must have keys loaded if doing encrypted non-raw recv. */428if (encrypted && !raw) {429if (spa_keystore_lookup_key(dp->dp_spa, ds->ds_object,430NULL, NULL) != 0)431return (SET_ERROR(EACCES));432}433434error = dsl_dataset_hold_obj(dp, obj, FTAG, &snap);435if (error != 0)436return (error);437438/*439* When not doing best effort corrective recv healing can only440* be done if the send stream is for the same snapshot as the441* one we are trying to heal.442*/443if (zfs_recv_best_effort_corrective == 0 &&444drba->drba_cookie->drc_drrb->drr_toguid !=445dsl_dataset_phys(snap)->ds_guid) {446dsl_dataset_rele(snap, FTAG);447return (SET_ERROR(ENOTSUP));448}449dsl_dataset_rele(snap, FTAG);450} else if (fromguid != 0) {451/* Sanity check the incremental recv */452uint64_t obj = dsl_dataset_phys(ds)->ds_prev_snap_obj;453454/* Can't perform a raw receive on top of a non-raw receive */455if (!encrypted && raw)456return (SET_ERROR(EINVAL));457458/* Encryption is incompatible with embedded data */459if (encrypted && embed)460return (SET_ERROR(EINVAL));461462/* Find snapshot in this dir that matches fromguid. */463while (obj != 0) {464error = dsl_dataset_hold_obj(dp, obj, FTAG,465&snap);466if (error != 0)467return (SET_ERROR(ENODEV));468if (snap->ds_dir != ds->ds_dir) {469dsl_dataset_rele(snap, FTAG);470return (SET_ERROR(ENODEV));471}472if (dsl_dataset_phys(snap)->ds_guid == fromguid)473break;474obj = dsl_dataset_phys(snap)->ds_prev_snap_obj;475dsl_dataset_rele(snap, FTAG);476}477if (obj == 0)478return (SET_ERROR(ENODEV));479480if (drba->drba_cookie->drc_force) {481drba->drba_cookie->drc_fromsnapobj = obj;482} else {483/*484* If we are not forcing, there must be no485* changes since fromsnap. Raw sends have an486* additional constraint that requires that487* no "noop" snapshots exist between fromsnap488* and tosnap for the IVset checking code to489* work properly.490*/491if (dsl_dataset_modified_since_snap(ds, snap) ||492(raw &&493dsl_dataset_phys(ds)->ds_prev_snap_obj !=494snap->ds_object)) {495dsl_dataset_rele(snap, FTAG);496return (SET_ERROR(ETXTBSY));497}498drba->drba_cookie->drc_fromsnapobj =499ds->ds_prev->ds_object;500}501502if (dsl_dataset_feature_is_active(snap,503SPA_FEATURE_REDACTED_DATASETS) && !redact_check(drba,504snap)) {505dsl_dataset_rele(snap, FTAG);506return (SET_ERROR(EINVAL));507}508509error = recv_check_large_blocks(snap, featureflags);510if (error != 0) {511dsl_dataset_rele(snap, FTAG);512return (error);513}514515dsl_dataset_rele(snap, FTAG);516} else {517/* If full and not healing then must be forced. */518if (!drba->drba_cookie->drc_force)519return (SET_ERROR(EEXIST));520521/*522* We don't support using zfs recv -F to blow away523* encrypted filesystems. This would require the524* dsl dir to point to the old encryption key and525* the new one at the same time during the receive.526*/527if ((!encrypted && raw) || encrypted)528return (SET_ERROR(EINVAL));529530/*531* Perform the same encryption checks we would if532* we were creating a new dataset from scratch.533*/534if (!raw) {535boolean_t will_encrypt;536537error = dmu_objset_create_crypt_check(538ds->ds_dir->dd_parent, drba->drba_dcp,539&will_encrypt);540if (error != 0)541return (error);542543if (will_encrypt && embed)544return (SET_ERROR(EINVAL));545}546}547548return (0);549}550551/*552* Check that any feature flags used in the data stream we're receiving are553* supported by the pool we are receiving into.554*555* Note that some of the features we explicitly check here have additional556* (implicit) features they depend on, but those dependencies are enforced557* through the zfeature_register() calls declaring the features that we558* explicitly check.559*/560static int561recv_begin_check_feature_flags_impl(uint64_t featureflags, spa_t *spa)562{563/*564* Check if there are any unsupported feature flags.565*/566if (!DMU_STREAM_SUPPORTED(featureflags)) {567return (SET_ERROR(ZFS_ERR_UNKNOWN_SEND_STREAM_FEATURE));568}569570/* Verify pool version supports SA if SA_SPILL feature set */571if ((featureflags & DMU_BACKUP_FEATURE_SA_SPILL) &&572spa_version(spa) < SPA_VERSION_SA)573return (SET_ERROR(ENOTSUP));574575/*576* LZ4 compressed, ZSTD compressed, embedded, mooched, large blocks,577* and large_dnodes in the stream can only be used if those pool578* features are enabled because we don't attempt to decompress /579* un-embed / un-mooch / split up the blocks / dnodes during the580* receive process.581*/582if ((featureflags & DMU_BACKUP_FEATURE_LZ4) &&583!spa_feature_is_enabled(spa, SPA_FEATURE_LZ4_COMPRESS))584return (SET_ERROR(ENOTSUP));585if ((featureflags & DMU_BACKUP_FEATURE_ZSTD) &&586!spa_feature_is_enabled(spa, SPA_FEATURE_ZSTD_COMPRESS))587return (SET_ERROR(ENOTSUP));588if ((featureflags & DMU_BACKUP_FEATURE_EMBED_DATA) &&589!spa_feature_is_enabled(spa, SPA_FEATURE_EMBEDDED_DATA))590return (SET_ERROR(ENOTSUP));591if ((featureflags & DMU_BACKUP_FEATURE_LARGE_BLOCKS) &&592!spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_BLOCKS))593return (SET_ERROR(ENOTSUP));594if ((featureflags & DMU_BACKUP_FEATURE_LARGE_DNODE) &&595!spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_DNODE))596return (SET_ERROR(ENOTSUP));597if ((featureflags & DMU_BACKUP_FEATURE_LARGE_MICROZAP) &&598!spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_MICROZAP))599return (SET_ERROR(ENOTSUP));600601/*602* Receiving redacted streams requires that redacted datasets are603* enabled.604*/605if ((featureflags & DMU_BACKUP_FEATURE_REDACTED) &&606!spa_feature_is_enabled(spa, SPA_FEATURE_REDACTED_DATASETS))607return (SET_ERROR(ENOTSUP));608609/*610* If the LONGNAME is not enabled on the target, fail that request.611*/612if ((featureflags & DMU_BACKUP_FEATURE_LONGNAME) &&613!spa_feature_is_enabled(spa, SPA_FEATURE_LONGNAME))614return (SET_ERROR(ENOTSUP));615616return (0);617}618619static int620dmu_recv_begin_check(void *arg, dmu_tx_t *tx)621{622dmu_recv_begin_arg_t *drba = arg;623dsl_pool_t *dp = dmu_tx_pool(tx);624struct drr_begin *drrb = drba->drba_cookie->drc_drrb;625uint64_t fromguid = drrb->drr_fromguid;626int flags = drrb->drr_flags;627ds_hold_flags_t dsflags = DS_HOLD_FLAG_NONE;628int error;629uint64_t featureflags = drba->drba_cookie->drc_featureflags;630dsl_dataset_t *ds;631const char *tofs = drba->drba_cookie->drc_tofs;632633/* already checked */634ASSERT3U(drrb->drr_magic, ==, DMU_BACKUP_MAGIC);635ASSERT(!(featureflags & DMU_BACKUP_FEATURE_RESUMING));636637if (DMU_GET_STREAM_HDRTYPE(drrb->drr_versioninfo) ==638DMU_COMPOUNDSTREAM ||639drrb->drr_type >= DMU_OST_NUMTYPES ||640((flags & DRR_FLAG_CLONE) && drba->drba_origin == NULL))641return (SET_ERROR(EINVAL));642643error = recv_begin_check_feature_flags_impl(featureflags, dp->dp_spa);644if (error != 0)645return (error);646647/* Resumable receives require extensible datasets */648if (drba->drba_cookie->drc_resumable &&649!spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_EXTENSIBLE_DATASET))650return (SET_ERROR(ENOTSUP));651652if (featureflags & DMU_BACKUP_FEATURE_RAW) {653/* raw receives require the encryption feature */654if (!spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_ENCRYPTION))655return (SET_ERROR(ENOTSUP));656657/* embedded data is incompatible with encryption and raw recv */658if (featureflags & DMU_BACKUP_FEATURE_EMBED_DATA)659return (SET_ERROR(EINVAL));660661/* raw receives require spill block allocation flag */662if (!(flags & DRR_FLAG_SPILL_BLOCK))663return (SET_ERROR(ZFS_ERR_SPILL_BLOCK_FLAG_MISSING));664} else {665/*666* We support unencrypted datasets below encrypted ones now,667* so add the DS_HOLD_FLAG_DECRYPT flag only if we are dealing668* with a dataset we may encrypt.669*/670if (drba->drba_dcp == NULL ||671drba->drba_dcp->cp_crypt != ZIO_CRYPT_OFF) {672dsflags |= DS_HOLD_FLAG_DECRYPT;673}674}675676error = dsl_dataset_hold_flags(dp, tofs, dsflags, FTAG, &ds);677if (error == 0) {678/* target fs already exists; recv into temp clone */679680/* Can't recv a clone into an existing fs */681if (flags & DRR_FLAG_CLONE || drba->drba_origin) {682dsl_dataset_rele_flags(ds, dsflags, FTAG);683return (SET_ERROR(EINVAL));684}685686error = recv_begin_check_existing_impl(drba, ds, fromguid,687featureflags);688dsl_dataset_rele_flags(ds, dsflags, FTAG);689} else if (error == ENOENT) {690/* target fs does not exist; must be a full backup or clone */691char buf[ZFS_MAX_DATASET_NAME_LEN];692objset_t *os;693694/* healing recv must be done "into" an existing snapshot */695if (drba->drba_cookie->drc_heal == B_TRUE)696return (SET_ERROR(ENOTSUP));697698/*699* If it's a non-clone incremental, we are missing the700* target fs, so fail the recv.701*/702if (fromguid != 0 && !((flags & DRR_FLAG_CLONE) ||703drba->drba_origin))704return (SET_ERROR(ENOENT));705706/*707* If we're receiving a full send as a clone, and it doesn't708* contain all the necessary free records and freeobject709* records, reject it.710*/711if (fromguid == 0 && drba->drba_origin != NULL &&712!(flags & DRR_FLAG_FREERECORDS))713return (SET_ERROR(EINVAL));714715/* Open the parent of tofs */716ASSERT3U(strlen(tofs), <, sizeof (buf));717(void) strlcpy(buf, tofs, strrchr(tofs, '/') - tofs + 1);718error = dsl_dataset_hold(dp, buf, FTAG, &ds);719if (error != 0)720return (error);721722if ((featureflags & DMU_BACKUP_FEATURE_RAW) == 0 &&723drba->drba_origin == NULL) {724boolean_t will_encrypt;725726/*727* Check that we aren't breaking any encryption rules728* and that we have all the parameters we need to729* create an encrypted dataset if necessary. If we are730* making an encrypted dataset the stream can't have731* embedded data.732*/733error = dmu_objset_create_crypt_check(ds->ds_dir,734drba->drba_dcp, &will_encrypt);735if (error != 0) {736dsl_dataset_rele(ds, FTAG);737return (error);738}739740if (will_encrypt &&741(featureflags & DMU_BACKUP_FEATURE_EMBED_DATA)) {742dsl_dataset_rele(ds, FTAG);743return (SET_ERROR(EINVAL));744}745}746747/*748* Check filesystem and snapshot limits before receiving. We'll749* recheck snapshot limits again at the end (we create the750* filesystems and increment those counts during begin_sync).751*/752error = dsl_fs_ss_limit_check(ds->ds_dir, 1,753ZFS_PROP_FILESYSTEM_LIMIT, NULL, drba->drba_cred);754if (error != 0) {755dsl_dataset_rele(ds, FTAG);756return (error);757}758759error = dsl_fs_ss_limit_check(ds->ds_dir, 1,760ZFS_PROP_SNAPSHOT_LIMIT, NULL, drba->drba_cred);761if (error != 0) {762dsl_dataset_rele(ds, FTAG);763return (error);764}765766/* can't recv below anything but filesystems (eg. no ZVOLs) */767error = dmu_objset_from_ds(ds, &os);768if (error != 0) {769dsl_dataset_rele(ds, FTAG);770return (error);771}772if (dmu_objset_type(os) != DMU_OST_ZFS) {773dsl_dataset_rele(ds, FTAG);774return (SET_ERROR(ZFS_ERR_WRONG_PARENT));775}776777if (drba->drba_origin != NULL) {778dsl_dataset_t *origin;779error = dsl_dataset_hold_flags(dp, drba->drba_origin,780dsflags, FTAG, &origin);781if (error != 0) {782dsl_dataset_rele(ds, FTAG);783return (error);784}785if (!origin->ds_is_snapshot) {786dsl_dataset_rele_flags(origin, dsflags, FTAG);787dsl_dataset_rele(ds, FTAG);788return (SET_ERROR(EINVAL));789}790if (dsl_dataset_phys(origin)->ds_guid != fromguid &&791fromguid != 0) {792dsl_dataset_rele_flags(origin, dsflags, FTAG);793dsl_dataset_rele(ds, FTAG);794return (SET_ERROR(ENODEV));795}796797if (origin->ds_dir->dd_crypto_obj != 0 &&798(featureflags & DMU_BACKUP_FEATURE_EMBED_DATA)) {799dsl_dataset_rele_flags(origin, dsflags, FTAG);800dsl_dataset_rele(ds, FTAG);801return (SET_ERROR(EINVAL));802}803804/*805* If the origin is redacted we need to verify that this806* send stream can safely be received on top of the807* origin.808*/809if (dsl_dataset_feature_is_active(origin,810SPA_FEATURE_REDACTED_DATASETS)) {811if (!redact_check(drba, origin)) {812dsl_dataset_rele_flags(origin, dsflags,813FTAG);814dsl_dataset_rele_flags(ds, dsflags,815FTAG);816return (SET_ERROR(EINVAL));817}818}819820error = recv_check_large_blocks(ds, featureflags);821if (error != 0) {822dsl_dataset_rele_flags(origin, dsflags, FTAG);823dsl_dataset_rele_flags(ds, dsflags, FTAG);824return (error);825}826827dsl_dataset_rele_flags(origin, dsflags, FTAG);828}829830dsl_dataset_rele(ds, FTAG);831error = 0;832}833return (error);834}835836static void837dmu_recv_begin_sync(void *arg, dmu_tx_t *tx)838{839dmu_recv_begin_arg_t *drba = arg;840dsl_pool_t *dp = dmu_tx_pool(tx);841objset_t *mos = dp->dp_meta_objset;842dmu_recv_cookie_t *drc = drba->drba_cookie;843struct drr_begin *drrb = drc->drc_drrb;844const char *tofs = drc->drc_tofs;845uint64_t featureflags = drc->drc_featureflags;846dsl_dataset_t *ds, *newds;847objset_t *os;848uint64_t dsobj;849ds_hold_flags_t dsflags = DS_HOLD_FLAG_NONE;850int error;851uint64_t crflags = 0;852dsl_crypto_params_t dummy_dcp = { 0 };853dsl_crypto_params_t *dcp = drba->drba_dcp;854855if (drrb->drr_flags & DRR_FLAG_CI_DATA)856crflags |= DS_FLAG_CI_DATASET;857858if ((featureflags & DMU_BACKUP_FEATURE_RAW) == 0)859dsflags |= DS_HOLD_FLAG_DECRYPT;860861/*862* Raw, non-incremental recvs always use a dummy dcp with863* the raw cmd set. Raw incremental recvs do not use a dcp864* since the encryption parameters are already set in stone.865*/866if (dcp == NULL && drrb->drr_fromguid == 0 &&867drba->drba_origin == NULL) {868ASSERT0P(dcp);869dcp = &dummy_dcp;870871if (featureflags & DMU_BACKUP_FEATURE_RAW)872dcp->cp_cmd = DCP_CMD_RAW_RECV;873}874875error = dsl_dataset_hold_flags(dp, tofs, dsflags, FTAG, &ds);876if (error == 0) {877/* Create temporary clone unless we're doing corrective recv */878dsl_dataset_t *snap = NULL;879880if (drba->drba_cookie->drc_fromsnapobj != 0) {881VERIFY0(dsl_dataset_hold_obj(dp,882drba->drba_cookie->drc_fromsnapobj, FTAG, &snap));883ASSERT0P(dcp);884}885if (drc->drc_heal) {886/* When healing we want to use the provided snapshot */887VERIFY0(dsl_dataset_snap_lookup(ds, drc->drc_tosnap,888&dsobj));889} else {890dsobj = dsl_dataset_create_sync(ds->ds_dir,891recv_clone_name, snap, crflags, drba->drba_cred,892dcp, tx);893}894if (drba->drba_cookie->drc_fromsnapobj != 0)895dsl_dataset_rele(snap, FTAG);896dsl_dataset_rele_flags(ds, dsflags, FTAG);897} else {898dsl_dir_t *dd;899const char *tail;900dsl_dataset_t *origin = NULL;901902VERIFY0(dsl_dir_hold(dp, tofs, FTAG, &dd, &tail));903904if (drba->drba_origin != NULL) {905VERIFY0(dsl_dataset_hold(dp, drba->drba_origin,906FTAG, &origin));907ASSERT0P(dcp);908}909910/* Create new dataset. */911dsobj = dsl_dataset_create_sync(dd, strrchr(tofs, '/') + 1,912origin, crflags, drba->drba_cred, dcp, tx);913if (origin != NULL)914dsl_dataset_rele(origin, FTAG);915dsl_dir_rele(dd, FTAG);916drc->drc_newfs = B_TRUE;917}918VERIFY0(dsl_dataset_own_obj_force(dp, dsobj, dsflags, dmu_recv_tag,919&newds));920if (dsl_dataset_feature_is_active(newds,921SPA_FEATURE_REDACTED_DATASETS)) {922/*923* If the origin dataset is redacted, the child will be redacted924* when we create it. We clear the new dataset's925* redaction info; if it should be redacted, we'll fill926* in its information later.927*/928dsl_dataset_deactivate_feature(newds,929SPA_FEATURE_REDACTED_DATASETS, tx);930}931VERIFY0(dmu_objset_from_ds(newds, &os));932933if (drc->drc_resumable) {934dsl_dataset_zapify(newds, tx);935if (drrb->drr_fromguid != 0) {936VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_FROMGUID,9378, 1, &drrb->drr_fromguid, tx));938}939VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_TOGUID,9408, 1, &drrb->drr_toguid, tx));941VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_TONAME,9421, strlen(drrb->drr_toname) + 1, drrb->drr_toname, tx));943uint64_t one = 1;944uint64_t zero = 0;945VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_OBJECT,9468, 1, &one, tx));947VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_OFFSET,9488, 1, &zero, tx));949VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_BYTES,9508, 1, &zero, tx));951if (featureflags & DMU_BACKUP_FEATURE_LARGE_BLOCKS) {952VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_LARGEBLOCK,9538, 1, &one, tx));954}955if (featureflags & DMU_BACKUP_FEATURE_EMBED_DATA) {956VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_EMBEDOK,9578, 1, &one, tx));958}959if (featureflags & DMU_BACKUP_FEATURE_COMPRESSED) {960VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_COMPRESSOK,9618, 1, &one, tx));962}963if (featureflags & DMU_BACKUP_FEATURE_RAW) {964VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_RAWOK,9658, 1, &one, tx));966}967968uint64_t *redact_snaps;969uint_t numredactsnaps;970if (nvlist_lookup_uint64_array(drc->drc_begin_nvl,971BEGINNV_REDACT_FROM_SNAPS, &redact_snaps,972&numredactsnaps) == 0) {973VERIFY0(zap_add(mos, dsobj,974DS_FIELD_RESUME_REDACT_BOOKMARK_SNAPS,975sizeof (*redact_snaps), numredactsnaps,976redact_snaps, tx));977}978}979980/*981* Usually the os->os_encrypted value is tied to the presence of a982* DSL Crypto Key object in the dd. However, that will not be received983* until dmu_recv_stream(), so we set the value manually for now.984*/985if (featureflags & DMU_BACKUP_FEATURE_RAW) {986os->os_encrypted = B_TRUE;987drba->drba_cookie->drc_raw = B_TRUE;988}989990if (featureflags & DMU_BACKUP_FEATURE_REDACTED) {991uint64_t *redact_snaps;992uint_t numredactsnaps;993VERIFY0(nvlist_lookup_uint64_array(drc->drc_begin_nvl,994BEGINNV_REDACT_SNAPS, &redact_snaps, &numredactsnaps));995dsl_dataset_activate_redaction(newds, redact_snaps,996numredactsnaps, tx);997}998999if (featureflags & DMU_BACKUP_FEATURE_LARGE_MICROZAP) {1000/*1001* The source has seen a large microzap at least once in its1002* life, so we activate the feature here to match. It's not1003* strictly necessary since a large microzap is usable without1004* the feature active, but if that object is sent on from here,1005* we need this info to know to add the stream feature.1006*1007* There may be no large microzap in the incoming stream, or1008* ever again, but this is a very niche feature and its very1009* difficult to spot a large microzap in the stream, so its1010* not worth the effort of trying harder to activate the1011* feature at first use.1012*/1013dsl_dataset_activate_feature(dsobj, SPA_FEATURE_LARGE_MICROZAP,1014(void *)B_TRUE, tx);1015}10161017dmu_buf_will_dirty(newds->ds_dbuf, tx);1018dsl_dataset_phys(newds)->ds_flags |= DS_FLAG_INCONSISTENT;10191020/*1021* Activate longname feature if received1022*/1023if (featureflags & DMU_BACKUP_FEATURE_LONGNAME &&1024!dsl_dataset_feature_is_active(newds, SPA_FEATURE_LONGNAME)) {1025dsl_dataset_activate_feature(newds->ds_object,1026SPA_FEATURE_LONGNAME, (void *)B_TRUE, tx);1027newds->ds_feature[SPA_FEATURE_LONGNAME] = (void *)B_TRUE;1028}10291030/*1031* If we actually created a non-clone, we need to create the objset1032* in our new dataset. If this is a raw send we postpone this until1033* dmu_recv_stream() so that we can allocate the metadnode with the1034* properties from the DRR_BEGIN payload.1035*/1036rrw_enter(&newds->ds_bp_rwlock, RW_READER, FTAG);1037if (BP_IS_HOLE(dsl_dataset_get_blkptr(newds)) &&1038(featureflags & DMU_BACKUP_FEATURE_RAW) == 0 &&1039!drc->drc_heal) {1040(void) dmu_objset_create_impl(dp->dp_spa,1041newds, dsl_dataset_get_blkptr(newds), drrb->drr_type, tx);1042}1043rrw_exit(&newds->ds_bp_rwlock, FTAG);10441045drba->drba_cookie->drc_ds = newds;1046drba->drba_cookie->drc_os = os;10471048spa_history_log_internal_ds(newds, "receive", tx, " ");1049}10501051static int1052dmu_recv_resume_begin_check(void *arg, dmu_tx_t *tx)1053{1054dmu_recv_begin_arg_t *drba = arg;1055dmu_recv_cookie_t *drc = drba->drba_cookie;1056dsl_pool_t *dp = dmu_tx_pool(tx);1057struct drr_begin *drrb = drc->drc_drrb;1058int error;1059ds_hold_flags_t dsflags = DS_HOLD_FLAG_NONE;1060dsl_dataset_t *ds;1061const char *tofs = drc->drc_tofs;10621063/* already checked */1064ASSERT3U(drrb->drr_magic, ==, DMU_BACKUP_MAGIC);1065ASSERT(drc->drc_featureflags & DMU_BACKUP_FEATURE_RESUMING);10661067if (DMU_GET_STREAM_HDRTYPE(drrb->drr_versioninfo) ==1068DMU_COMPOUNDSTREAM ||1069drrb->drr_type >= DMU_OST_NUMTYPES)1070return (SET_ERROR(EINVAL));10711072/*1073* This is mostly a sanity check since we should have already done these1074* checks during a previous attempt to receive the data.1075*/1076error = recv_begin_check_feature_flags_impl(drc->drc_featureflags,1077dp->dp_spa);1078if (error != 0)1079return (error);10801081/* 6 extra bytes for /%recv */1082char recvname[ZFS_MAX_DATASET_NAME_LEN + 6];10831084(void) snprintf(recvname, sizeof (recvname), "%s/%s",1085tofs, recv_clone_name);10861087if (drc->drc_featureflags & DMU_BACKUP_FEATURE_RAW) {1088/* raw receives require spill block allocation flag */1089if (!(drrb->drr_flags & DRR_FLAG_SPILL_BLOCK))1090return (SET_ERROR(ZFS_ERR_SPILL_BLOCK_FLAG_MISSING));1091} else {1092dsflags |= DS_HOLD_FLAG_DECRYPT;1093}10941095boolean_t recvexist = B_TRUE;1096if (dsl_dataset_hold_flags(dp, recvname, dsflags, FTAG, &ds) != 0) {1097/* %recv does not exist; continue in tofs */1098recvexist = B_FALSE;1099error = dsl_dataset_hold_flags(dp, tofs, dsflags, FTAG, &ds);1100if (error != 0)1101return (error);1102}11031104/*1105* Resume of full/newfs recv on existing dataset should be done with1106* force flag1107*/1108if (recvexist && drrb->drr_fromguid == 0 && !drc->drc_force) {1109dsl_dataset_rele_flags(ds, dsflags, FTAG);1110return (SET_ERROR(ZFS_ERR_RESUME_EXISTS));1111}11121113/* check that ds is marked inconsistent */1114if (!DS_IS_INCONSISTENT(ds)) {1115dsl_dataset_rele_flags(ds, dsflags, FTAG);1116return (SET_ERROR(EINVAL));1117}11181119/* check that there is resuming data, and that the toguid matches */1120if (!dsl_dataset_is_zapified(ds)) {1121dsl_dataset_rele_flags(ds, dsflags, FTAG);1122return (SET_ERROR(EINVAL));1123}1124uint64_t val;1125error = zap_lookup(dp->dp_meta_objset, ds->ds_object,1126DS_FIELD_RESUME_TOGUID, sizeof (val), 1, &val);1127if (error != 0 || drrb->drr_toguid != val) {1128dsl_dataset_rele_flags(ds, dsflags, FTAG);1129return (SET_ERROR(EINVAL));1130}11311132/*1133* Check if the receive is still running. If so, it will be owned.1134* Note that nothing else can own the dataset (e.g. after the receive1135* fails) because it will be marked inconsistent.1136*/1137if (dsl_dataset_has_owner(ds)) {1138dsl_dataset_rele_flags(ds, dsflags, FTAG);1139return (SET_ERROR(EBUSY));1140}11411142/* There should not be any snapshots of this fs yet. */1143if (ds->ds_prev != NULL && ds->ds_prev->ds_dir == ds->ds_dir) {1144dsl_dataset_rele_flags(ds, dsflags, FTAG);1145return (SET_ERROR(EINVAL));1146}11471148/*1149* Note: resume point will be checked when we process the first WRITE1150* record.1151*/11521153/* check that the origin matches */1154val = 0;1155(void) zap_lookup(dp->dp_meta_objset, ds->ds_object,1156DS_FIELD_RESUME_FROMGUID, sizeof (val), 1, &val);1157if (drrb->drr_fromguid != val) {1158dsl_dataset_rele_flags(ds, dsflags, FTAG);1159return (SET_ERROR(EINVAL));1160}11611162if (ds->ds_prev != NULL && drrb->drr_fromguid != 0)1163drc->drc_fromsnapobj = ds->ds_prev->ds_object;11641165/*1166* If we're resuming, and the send is redacted, then the original send1167* must have been redacted, and must have been redacted with respect to1168* the same snapshots.1169*/1170if (drc->drc_featureflags & DMU_BACKUP_FEATURE_REDACTED) {1171uint64_t num_ds_redact_snaps;1172uint64_t *ds_redact_snaps;11731174uint_t num_stream_redact_snaps;1175uint64_t *stream_redact_snaps;11761177if (nvlist_lookup_uint64_array(drc->drc_begin_nvl,1178BEGINNV_REDACT_SNAPS, &stream_redact_snaps,1179&num_stream_redact_snaps) != 0) {1180dsl_dataset_rele_flags(ds, dsflags, FTAG);1181return (SET_ERROR(EINVAL));1182}11831184if (!dsl_dataset_get_uint64_array_feature(ds,1185SPA_FEATURE_REDACTED_DATASETS, &num_ds_redact_snaps,1186&ds_redact_snaps)) {1187dsl_dataset_rele_flags(ds, dsflags, FTAG);1188return (SET_ERROR(EINVAL));1189}11901191for (int i = 0; i < num_ds_redact_snaps; i++) {1192if (!redact_snaps_contains(ds_redact_snaps,1193num_ds_redact_snaps, stream_redact_snaps[i])) {1194dsl_dataset_rele_flags(ds, dsflags, FTAG);1195return (SET_ERROR(EINVAL));1196}1197}1198}11991200error = recv_check_large_blocks(ds, drc->drc_featureflags);1201if (error != 0) {1202dsl_dataset_rele_flags(ds, dsflags, FTAG);1203return (error);1204}12051206dsl_dataset_rele_flags(ds, dsflags, FTAG);1207return (0);1208}12091210static void1211dmu_recv_resume_begin_sync(void *arg, dmu_tx_t *tx)1212{1213dmu_recv_begin_arg_t *drba = arg;1214dsl_pool_t *dp = dmu_tx_pool(tx);1215const char *tofs = drba->drba_cookie->drc_tofs;1216uint64_t featureflags = drba->drba_cookie->drc_featureflags;1217dsl_dataset_t *ds;1218ds_hold_flags_t dsflags = DS_HOLD_FLAG_NONE;1219/* 6 extra bytes for /%recv */1220char recvname[ZFS_MAX_DATASET_NAME_LEN + 6];12211222(void) snprintf(recvname, sizeof (recvname), "%s/%s", tofs,1223recv_clone_name);12241225if (featureflags & DMU_BACKUP_FEATURE_RAW) {1226drba->drba_cookie->drc_raw = B_TRUE;1227} else {1228dsflags |= DS_HOLD_FLAG_DECRYPT;1229}12301231if (dsl_dataset_own_force(dp, recvname, dsflags, dmu_recv_tag, &ds)1232!= 0) {1233/* %recv does not exist; continue in tofs */1234VERIFY0(dsl_dataset_own_force(dp, tofs, dsflags, dmu_recv_tag,1235&ds));1236drba->drba_cookie->drc_newfs = B_TRUE;1237}12381239ASSERT(DS_IS_INCONSISTENT(ds));1240rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);1241ASSERT(!BP_IS_HOLE(dsl_dataset_get_blkptr(ds)) ||1242drba->drba_cookie->drc_raw);1243rrw_exit(&ds->ds_bp_rwlock, FTAG);12441245drba->drba_cookie->drc_ds = ds;1246VERIFY0(dmu_objset_from_ds(ds, &drba->drba_cookie->drc_os));1247drba->drba_cookie->drc_should_save = B_TRUE;12481249spa_history_log_internal_ds(ds, "resume receive", tx, " ");1250}12511252/*1253* NB: callers *MUST* call dmu_recv_stream() if dmu_recv_begin()1254* succeeds; otherwise we will leak the holds on the datasets.1255*/1256int1257dmu_recv_begin(const char *tofs, const char *tosnap,1258dmu_replay_record_t *drr_begin, boolean_t force, boolean_t heal,1259boolean_t resumable, nvlist_t *localprops, nvlist_t *hidden_args,1260const char *origin, dmu_recv_cookie_t *drc, zfs_file_t *fp,1261offset_t *voffp)1262{1263dmu_recv_begin_arg_t drba = { 0 };1264int err = 0;12651266cred_t *cr = CRED();1267crhold(cr);12681269memset(drc, 0, sizeof (dmu_recv_cookie_t));1270drc->drc_drr_begin = drr_begin;1271drc->drc_drrb = &drr_begin->drr_u.drr_begin;1272drc->drc_tosnap = tosnap;1273drc->drc_tofs = tofs;1274drc->drc_force = force;1275drc->drc_heal = heal;1276drc->drc_resumable = resumable;1277drc->drc_cred = cr;1278drc->drc_clone = (origin != NULL);12791280if (drc->drc_drrb->drr_magic == BSWAP_64(DMU_BACKUP_MAGIC)) {1281drc->drc_byteswap = B_TRUE;1282(void) fletcher_4_incremental_byteswap(drr_begin,1283sizeof (dmu_replay_record_t), &drc->drc_cksum);1284byteswap_record(drr_begin);1285} else if (drc->drc_drrb->drr_magic == DMU_BACKUP_MAGIC) {1286(void) fletcher_4_incremental_native(drr_begin,1287sizeof (dmu_replay_record_t), &drc->drc_cksum);1288} else {1289crfree(cr);1290drc->drc_cred = NULL;1291return (SET_ERROR(EINVAL));1292}12931294drc->drc_fp = fp;1295drc->drc_voff = *voffp;1296drc->drc_featureflags =1297DMU_GET_FEATUREFLAGS(drc->drc_drrb->drr_versioninfo);12981299uint32_t payloadlen = drc->drc_drr_begin->drr_payloadlen;13001301/*1302* Since OpenZFS 2.0.0, we have enforced a 64MB limit in userspace1303* configurable via ZFS_SENDRECV_MAX_NVLIST. We enforce 256MB as a hard1304* upper limit. Systems with less than 1GB of RAM will see a lower1305* limit from `arc_all_memory() / 4`.1306*/1307if (payloadlen > (MIN((1U << 28), arc_all_memory() / 4))) {1308crfree(cr);1309drc->drc_cred = NULL;1310return (SET_ERROR(E2BIG));1311}13121313if (payloadlen != 0) {1314void *payload = vmem_alloc(payloadlen, KM_SLEEP);1315/*1316* For compatibility with recursive send streams, we don't do1317* this here if the stream could be part of a package. Instead,1318* we'll do it in dmu_recv_stream. If we pull the next header1319* too early, and it's the END record, we break the `recv_skip`1320* logic.1321*/13221323err = receive_read_payload_and_next_header(drc, payloadlen,1324payload);1325if (err != 0) {1326vmem_free(payload, payloadlen);1327crfree(cr);1328drc->drc_cred = NULL;1329return (err);1330}1331err = nvlist_unpack(payload, payloadlen, &drc->drc_begin_nvl,1332KM_SLEEP);1333vmem_free(payload, payloadlen);1334if (err != 0) {1335kmem_free(drc->drc_next_rrd,1336sizeof (*drc->drc_next_rrd));1337crfree(cr);1338drc->drc_cred = NULL;1339return (err);1340}1341}13421343if (drc->drc_drrb->drr_flags & DRR_FLAG_SPILL_BLOCK)1344drc->drc_spill = B_TRUE;13451346drba.drba_origin = origin;1347drba.drba_cookie = drc;1348drba.drba_cred = drc->drc_cred;13491350if (drc->drc_featureflags & DMU_BACKUP_FEATURE_RESUMING) {1351err = dsl_sync_task(tofs,1352dmu_recv_resume_begin_check, dmu_recv_resume_begin_sync,1353&drba, 5, ZFS_SPACE_CHECK_NORMAL);1354} else {1355/*1356* For non-raw, non-incremental, non-resuming receives the1357* user can specify encryption parameters on the command line1358* with "zfs recv -o". For these receives we create a dcp and1359* pass it to the sync task. Creating the dcp will implicitly1360* remove the encryption params from the localprops nvlist,1361* which avoids errors when trying to set these normally1362* read-only properties. Any other kind of receive that1363* attempts to set these properties will fail as a result.1364*/1365if ((DMU_GET_FEATUREFLAGS(drc->drc_drrb->drr_versioninfo) &1366DMU_BACKUP_FEATURE_RAW) == 0 &&1367origin == NULL && drc->drc_drrb->drr_fromguid == 0) {1368err = dsl_crypto_params_create_nvlist(DCP_CMD_NONE,1369localprops, hidden_args, &drba.drba_dcp);1370}13711372if (err == 0) {1373err = dsl_sync_task(tofs,1374dmu_recv_begin_check, dmu_recv_begin_sync,1375&drba, 5, ZFS_SPACE_CHECK_NORMAL);1376dsl_crypto_params_free(drba.drba_dcp, !!err);1377}1378}13791380if (err != 0) {1381kmem_free(drc->drc_next_rrd, sizeof (*drc->drc_next_rrd));1382nvlist_free(drc->drc_begin_nvl);1383crfree(cr);1384drc->drc_cred = NULL;1385}1386return (err);1387}13881389/*1390* Holds data need for corrective recv callback1391*/1392typedef struct cr_cb_data {1393uint64_t size;1394zbookmark_phys_t zb;1395spa_t *spa;1396} cr_cb_data_t;13971398static void1399corrective_read_done(zio_t *zio)1400{1401cr_cb_data_t *data = zio->io_private;1402/* Corruption corrected; update error log if needed */1403if (zio->io_error == 0) {1404spa_remove_error(data->spa, &data->zb,1405BP_GET_PHYSICAL_BIRTH(zio->io_bp));1406}1407kmem_free(data, sizeof (cr_cb_data_t));1408abd_free(zio->io_abd);1409}14101411/*1412* zio_rewrite the data pointed to by bp with the data from the rrd's abd.1413*/1414static int1415do_corrective_recv(struct receive_writer_arg *rwa, struct drr_write *drrw,1416struct receive_record_arg *rrd, blkptr_t *bp)1417{1418int err;1419zio_t *io;1420zbookmark_phys_t zb;1421dnode_t *dn;1422abd_t *abd = rrd->abd;1423zio_cksum_t bp_cksum = bp->blk_cksum;1424zio_flag_t flags = ZIO_FLAG_SPECULATIVE | ZIO_FLAG_DONT_RETRY |1425ZIO_FLAG_CANFAIL;14261427if (rwa->raw)1428flags |= ZIO_FLAG_RAW;14291430err = dnode_hold(rwa->os, drrw->drr_object, FTAG, &dn);1431if (err != 0)1432return (err);1433SET_BOOKMARK(&zb, dmu_objset_id(rwa->os), drrw->drr_object, 0,1434dbuf_whichblock(dn, 0, drrw->drr_offset));1435dnode_rele(dn, FTAG);14361437if (!rwa->raw && DRR_WRITE_COMPRESSED(drrw)) {1438/* Decompress the stream data */1439abd_t *dabd = abd_alloc_linear(1440drrw->drr_logical_size, B_FALSE);1441err = zio_decompress_data(drrw->drr_compressiontype,1442abd, dabd, abd_get_size(abd),1443abd_get_size(dabd), NULL);14441445if (err != 0) {1446abd_free(dabd);1447return (err);1448}1449/* Swap in the newly decompressed data into the abd */1450abd_free(abd);1451abd = dabd;1452}14531454if (!rwa->raw && BP_GET_COMPRESS(bp) != ZIO_COMPRESS_OFF) {1455/* Recompress the data */1456abd_t *cabd = abd_alloc_linear(BP_GET_PSIZE(bp),1457B_FALSE);1458uint64_t csize = zio_compress_data(BP_GET_COMPRESS(bp),1459abd, &cabd, abd_get_size(abd), BP_GET_PSIZE(bp),1460rwa->os->os_complevel);1461abd_zero_off(cabd, csize, BP_GET_PSIZE(bp) - csize);1462/* Swap in newly compressed data into the abd */1463abd_free(abd);1464abd = cabd;1465flags |= ZIO_FLAG_RAW_COMPRESS;1466}14671468/*1469* The stream is not encrypted but the data on-disk is.1470* We need to re-encrypt the buf using the same1471* encryption type, salt, iv, and mac that was used to encrypt1472* the block previosly.1473*/1474if (!rwa->raw && BP_USES_CRYPT(bp)) {1475dsl_dataset_t *ds;1476dsl_crypto_key_t *dck = NULL;1477uint8_t salt[ZIO_DATA_SALT_LEN];1478uint8_t iv[ZIO_DATA_IV_LEN];1479uint8_t mac[ZIO_DATA_MAC_LEN];1480boolean_t no_crypt = B_FALSE;1481dsl_pool_t *dp = dmu_objset_pool(rwa->os);1482abd_t *eabd = abd_alloc_linear(BP_GET_PSIZE(bp), B_FALSE);14831484zio_crypt_decode_params_bp(bp, salt, iv);1485zio_crypt_decode_mac_bp(bp, mac);14861487dsl_pool_config_enter(dp, FTAG);1488err = dsl_dataset_hold_flags(dp, rwa->tofs,1489DS_HOLD_FLAG_DECRYPT, FTAG, &ds);1490if (err != 0) {1491dsl_pool_config_exit(dp, FTAG);1492abd_free(eabd);1493return (SET_ERROR(EACCES));1494}14951496/* Look up the key from the spa's keystore */1497err = spa_keystore_lookup_key(rwa->os->os_spa,1498zb.zb_objset, FTAG, &dck);1499if (err != 0) {1500dsl_dataset_rele_flags(ds, DS_HOLD_FLAG_DECRYPT,1501FTAG);1502dsl_pool_config_exit(dp, FTAG);1503abd_free(eabd);1504return (SET_ERROR(EACCES));1505}15061507err = zio_do_crypt_abd(B_TRUE, &dck->dck_key,1508BP_GET_TYPE(bp), BP_SHOULD_BYTESWAP(bp), salt, iv,1509mac, abd_get_size(abd), abd, eabd, &no_crypt);15101511spa_keystore_dsl_key_rele(rwa->os->os_spa, dck, FTAG);1512dsl_dataset_rele_flags(ds, DS_HOLD_FLAG_DECRYPT, FTAG);1513dsl_pool_config_exit(dp, FTAG);15141515ASSERT0(no_crypt);1516if (err != 0) {1517abd_free(eabd);1518return (err);1519}1520/* Swap in the newly encrypted data into the abd */1521abd_free(abd);1522abd = eabd;15231524/*1525* We want to prevent zio_rewrite() from trying to1526* encrypt the data again1527*/1528flags |= ZIO_FLAG_RAW_ENCRYPT;1529}1530rrd->abd = abd;15311532io = zio_rewrite(NULL, rwa->os->os_spa, BP_GET_BIRTH(bp), bp,1533abd, BP_GET_PSIZE(bp), NULL, NULL, ZIO_PRIORITY_SYNC_WRITE, flags,1534&zb);15351536ASSERT(abd_get_size(abd) == BP_GET_LSIZE(bp) ||1537abd_get_size(abd) == BP_GET_PSIZE(bp));15381539/* compute new bp checksum value and make sure it matches the old one */1540zio_checksum_compute(io, BP_GET_CHECKSUM(bp), abd, abd_get_size(abd));1541if (!ZIO_CHECKSUM_EQUAL(bp_cksum, io->io_bp->blk_cksum)) {1542zio_destroy(io);1543if (zfs_recv_best_effort_corrective != 0)1544return (0);1545return (SET_ERROR(ECKSUM));1546}15471548/* Correct the corruption in place */1549err = zio_wait(io);1550if (err == 0) {1551cr_cb_data_t *cb_data =1552kmem_alloc(sizeof (cr_cb_data_t), KM_SLEEP);1553cb_data->spa = rwa->os->os_spa;1554cb_data->size = drrw->drr_logical_size;1555cb_data->zb = zb;1556/* Test if healing worked by re-reading the bp */1557err = zio_wait(zio_read(rwa->heal_pio, rwa->os->os_spa, bp,1558abd_alloc_for_io(drrw->drr_logical_size, B_FALSE),1559drrw->drr_logical_size, corrective_read_done,1560cb_data, ZIO_PRIORITY_ASYNC_READ, flags, NULL));1561}1562if (err != 0 && zfs_recv_best_effort_corrective != 0)1563err = 0;15641565return (err);1566}15671568static int1569receive_read(dmu_recv_cookie_t *drc, int len, void *buf)1570{1571int done = 0;15721573/*1574* The code doesn't rely on this (lengths being multiples of 8). See1575* comment in dump_bytes.1576*/1577ASSERT(len % 8 == 0 ||1578(drc->drc_featureflags & DMU_BACKUP_FEATURE_RAW) != 0);15791580while (done < len) {1581ssize_t resid = len - done;1582zfs_file_t *fp = drc->drc_fp;1583int err = zfs_file_read(fp, (char *)buf + done,1584len - done, &resid);1585if (err == 0 && resid == len - done) {1586/*1587* Note: ECKSUM or ZFS_ERR_STREAM_TRUNCATED indicates1588* that the receive was interrupted and can1589* potentially be resumed.1590*/1591err = SET_ERROR(ZFS_ERR_STREAM_TRUNCATED);1592}1593drc->drc_voff += len - done - resid;1594done = len - resid;1595if (err != 0)1596return (err);1597}15981599drc->drc_bytes_read += len;16001601ASSERT3U(done, ==, len);1602return (0);1603}16041605static inline uint8_t1606deduce_nblkptr(dmu_object_type_t bonus_type, uint64_t bonus_size)1607{1608if (bonus_type == DMU_OT_SA) {1609return (1);1610} else {1611return (1 +1612((DN_OLD_MAX_BONUSLEN -1613MIN(DN_OLD_MAX_BONUSLEN, bonus_size)) >> SPA_BLKPTRSHIFT));1614}1615}16161617static void1618save_resume_state(struct receive_writer_arg *rwa,1619uint64_t object, uint64_t offset, dmu_tx_t *tx)1620{1621int txgoff = dmu_tx_get_txg(tx) & TXG_MASK;16221623if (!rwa->resumable)1624return;16251626/*1627* We use ds_resume_bytes[] != 0 to indicate that we need to1628* update this on disk, so it must not be 0.1629*/1630ASSERT(rwa->bytes_read != 0);16311632/*1633* We only resume from write records, which have a valid1634* (non-meta-dnode) object number.1635*/1636ASSERT(object != 0);16371638/*1639* For resuming to work correctly, we must receive records in order,1640* sorted by object,offset. This is checked by the callers, but1641* assert it here for good measure.1642*/1643ASSERT3U(object, >=, rwa->os->os_dsl_dataset->ds_resume_object[txgoff]);1644ASSERT(object != rwa->os->os_dsl_dataset->ds_resume_object[txgoff] ||1645offset >= rwa->os->os_dsl_dataset->ds_resume_offset[txgoff]);1646ASSERT3U(rwa->bytes_read, >=,1647rwa->os->os_dsl_dataset->ds_resume_bytes[txgoff]);16481649rwa->os->os_dsl_dataset->ds_resume_object[txgoff] = object;1650rwa->os->os_dsl_dataset->ds_resume_offset[txgoff] = offset;1651rwa->os->os_dsl_dataset->ds_resume_bytes[txgoff] = rwa->bytes_read;1652}16531654static int1655receive_object_is_same_generation(objset_t *os, uint64_t object,1656dmu_object_type_t old_bonus_type, dmu_object_type_t new_bonus_type,1657const void *new_bonus, boolean_t *samegenp)1658{1659zfs_file_info_t zoi;1660int err;16611662dmu_buf_t *old_bonus_dbuf;1663err = dmu_bonus_hold(os, object, FTAG, &old_bonus_dbuf);1664if (err != 0)1665return (err);1666err = dmu_get_file_info(os, old_bonus_type, old_bonus_dbuf->db_data,1667&zoi);1668dmu_buf_rele(old_bonus_dbuf, FTAG);1669if (err != 0)1670return (err);1671uint64_t old_gen = zoi.zfi_generation;16721673err = dmu_get_file_info(os, new_bonus_type, new_bonus, &zoi);1674if (err != 0)1675return (err);1676uint64_t new_gen = zoi.zfi_generation;16771678*samegenp = (old_gen == new_gen);1679return (0);1680}16811682static int1683receive_handle_existing_object(const struct receive_writer_arg *rwa,1684const struct drr_object *drro, const dmu_object_info_t *doi,1685const void *bonus_data,1686uint64_t *object_to_hold, uint32_t *new_blksz)1687{1688uint32_t indblksz = drro->drr_indblkshift ?16891ULL << drro->drr_indblkshift : 0;1690int nblkptr = deduce_nblkptr(drro->drr_bonustype,1691drro->drr_bonuslen);1692uint8_t dn_slots = drro->drr_dn_slots != 0 ?1693drro->drr_dn_slots : DNODE_MIN_SLOTS;1694boolean_t do_free_range = B_FALSE;1695int err;16961697*object_to_hold = drro->drr_object;16981699/* nblkptr should be bounded by the bonus size and type */1700if (rwa->raw && nblkptr != drro->drr_nblkptr)1701return (SET_ERROR(EINVAL));17021703/*1704* After the previous send stream, the sending system may1705* have freed this object, and then happened to re-allocate1706* this object number in a later txg. In this case, we are1707* receiving a different logical file, and the block size may1708* appear to be different. i.e. we may have a different1709* block size for this object than what the send stream says.1710* In this case we need to remove the object's contents,1711* so that its structure can be changed and then its contents1712* entirely replaced by subsequent WRITE records.1713*1714* If this is a -L (--large-block) incremental stream, and1715* the previous stream was not -L, the block size may appear1716* to increase. i.e. we may have a smaller block size for1717* this object than what the send stream says. In this case1718* we need to keep the object's contents and block size1719* intact, so that we don't lose parts of the object's1720* contents that are not changed by this incremental send1721* stream.1722*1723* We can distinguish between the two above cases by using1724* the ZPL's generation number (see1725* receive_object_is_same_generation()). However, we only1726* want to rely on the generation number when absolutely1727* necessary, because with raw receives, the generation is1728* encrypted. We also want to minimize dependence on the1729* ZPL, so that other types of datasets can also be received1730* (e.g. ZVOLs, although note that ZVOLS currently do not1731* reallocate their objects or change their structure).1732* Therefore, we check a number of different cases where we1733* know it is safe to discard the object's contents, before1734* using the ZPL's generation number to make the above1735* distinction.1736*/1737if (drro->drr_blksz != doi->doi_data_block_size) {1738if (rwa->raw) {1739/*1740* RAW streams always have large blocks, so1741* we are sure that the data is not needed1742* due to changing --large-block to be on.1743* Which is fortunate since the bonus buffer1744* (which contains the ZPL generation) is1745* encrypted, and the key might not be1746* loaded.1747*/1748do_free_range = B_TRUE;1749} else if (rwa->full) {1750/*1751* This is a full send stream, so it always1752* replaces what we have. Even if the1753* generation numbers happen to match, this1754* can not actually be the same logical file.1755* This is relevant when receiving a full1756* send as a clone.1757*/1758do_free_range = B_TRUE;1759} else if (drro->drr_type !=1760DMU_OT_PLAIN_FILE_CONTENTS ||1761doi->doi_type != DMU_OT_PLAIN_FILE_CONTENTS) {1762/*1763* PLAIN_FILE_CONTENTS are the only type of1764* objects that have ever been stored with1765* large blocks, so we don't need the special1766* logic below. ZAP blocks can shrink (when1767* there's only one block), so we don't want1768* to hit the error below about block size1769* only increasing.1770*/1771do_free_range = B_TRUE;1772} else if (doi->doi_max_offset <=1773doi->doi_data_block_size) {1774/*1775* There is only one block. We can free it,1776* because its contents will be replaced by a1777* WRITE record. This can not be the no-L ->1778* -L case, because the no-L case would have1779* resulted in multiple blocks. If we1780* supported -L -> no-L, it would not be safe1781* to free the file's contents. Fortunately,1782* that is not allowed (see1783* recv_check_large_blocks()).1784*/1785do_free_range = B_TRUE;1786} else {1787boolean_t is_same_gen;1788err = receive_object_is_same_generation(rwa->os,1789drro->drr_object, doi->doi_bonus_type,1790drro->drr_bonustype, bonus_data, &is_same_gen);1791if (err != 0)1792return (SET_ERROR(EINVAL));17931794if (is_same_gen) {1795/*1796* This is the same logical file, and1797* the block size must be increasing.1798* It could only decrease if1799* --large-block was changed to be1800* off, which is checked in1801* recv_check_large_blocks().1802*/1803if (drro->drr_blksz <=1804doi->doi_data_block_size)1805return (SET_ERROR(EINVAL));1806/*1807* We keep the existing blocksize and1808* contents.1809*/1810*new_blksz =1811doi->doi_data_block_size;1812} else {1813do_free_range = B_TRUE;1814}1815}1816}18171818/* nblkptr can only decrease if the object was reallocated */1819if (nblkptr < doi->doi_nblkptr)1820do_free_range = B_TRUE;18211822/* number of slots can only change on reallocation */1823if (dn_slots != doi->doi_dnodesize >> DNODE_SHIFT)1824do_free_range = B_TRUE;18251826/*1827* For raw sends we also check a few other fields to1828* ensure we are preserving the objset structure exactly1829* as it was on the receive side:1830* - A changed indirect block size1831* - A smaller nlevels1832*/1833if (rwa->raw) {1834if (indblksz != doi->doi_metadata_block_size)1835do_free_range = B_TRUE;1836if (drro->drr_nlevels < doi->doi_indirection)1837do_free_range = B_TRUE;1838}18391840if (do_free_range) {1841err = dmu_free_long_range(rwa->os, drro->drr_object,18420, DMU_OBJECT_END);1843if (err != 0)1844return (SET_ERROR(EINVAL));1845}18461847/*1848* The dmu does not currently support decreasing nlevels or changing1849* indirect block size if there is already one, same as changing the1850* number of of dnode slots on an object. For non-raw sends this1851* does not matter and the new object can just use the previous one's1852* parameters. For raw sends, however, the structure of the received1853* dnode (including indirects and dnode slots) must match that of the1854* send side. Therefore, instead of using dmu_object_reclaim(), we1855* must free the object completely and call dmu_object_claim_dnsize()1856* instead.1857*/1858if ((rwa->raw && ((doi->doi_indirection > 1 &&1859indblksz != doi->doi_metadata_block_size) ||1860drro->drr_nlevels < doi->doi_indirection)) ||1861dn_slots != doi->doi_dnodesize >> DNODE_SHIFT) {1862err = dmu_free_long_object(rwa->os, drro->drr_object);1863if (err != 0)1864return (SET_ERROR(EINVAL));18651866txg_wait_synced(dmu_objset_pool(rwa->os), 0);1867*object_to_hold = DMU_NEW_OBJECT;1868}18691870/*1871* For raw receives, free everything beyond the new incoming1872* maxblkid. Normally this would be done with a DRR_FREE1873* record that would come after this DRR_OBJECT record is1874* processed. However, for raw receives we manually set the1875* maxblkid from the drr_maxblkid and so we must first free1876* everything above that blkid to ensure the DMU is always1877* consistent with itself. We will never free the first block1878* of the object here because a maxblkid of 0 could indicate1879* an object with a single block or one with no blocks. This1880* free may be skipped when dmu_free_long_range() was called1881* above since it covers the entire object's contents.1882*/1883if (rwa->raw && *object_to_hold != DMU_NEW_OBJECT && !do_free_range) {1884err = dmu_free_long_range(rwa->os, drro->drr_object,1885(drro->drr_maxblkid + 1) * doi->doi_data_block_size,1886DMU_OBJECT_END);1887if (err != 0)1888return (SET_ERROR(EINVAL));1889}1890return (0);1891}18921893noinline static int1894receive_object(struct receive_writer_arg *rwa, struct drr_object *drro,1895void *data)1896{1897dmu_object_info_t doi;1898dmu_tx_t *tx;1899int err;1900uint32_t new_blksz = drro->drr_blksz;1901uint8_t dn_slots = drro->drr_dn_slots != 0 ?1902drro->drr_dn_slots : DNODE_MIN_SLOTS;19031904if (drro->drr_type == DMU_OT_NONE ||1905!DMU_OT_IS_VALID(drro->drr_type) ||1906!DMU_OT_IS_VALID(drro->drr_bonustype) ||1907drro->drr_checksumtype >= ZIO_CHECKSUM_FUNCTIONS ||1908drro->drr_compress >= ZIO_COMPRESS_FUNCTIONS ||1909P2PHASE(drro->drr_blksz, SPA_MINBLOCKSIZE) ||1910drro->drr_blksz < SPA_MINBLOCKSIZE ||1911drro->drr_blksz > spa_maxblocksize(dmu_objset_spa(rwa->os)) ||1912drro->drr_bonuslen >1913DN_BONUS_SIZE(spa_maxdnodesize(dmu_objset_spa(rwa->os))) ||1914dn_slots >1915(spa_maxdnodesize(dmu_objset_spa(rwa->os)) >> DNODE_SHIFT)) {1916return (SET_ERROR(EINVAL));1917}19181919if (rwa->raw) {1920/*1921* We should have received a DRR_OBJECT_RANGE record1922* containing this block and stored it in rwa.1923*/1924if (drro->drr_object < rwa->or_firstobj ||1925drro->drr_object >= rwa->or_firstobj + rwa->or_numslots ||1926drro->drr_raw_bonuslen < drro->drr_bonuslen ||1927drro->drr_indblkshift > SPA_MAXBLOCKSHIFT ||1928drro->drr_nlevels > DN_MAX_LEVELS ||1929drro->drr_nblkptr > DN_MAX_NBLKPTR ||1930DN_SLOTS_TO_BONUSLEN(dn_slots) <1931drro->drr_raw_bonuslen)1932return (SET_ERROR(EINVAL));1933} else {1934/*1935* The DRR_OBJECT_SPILL flag is valid when the DRR_BEGIN1936* record indicates this by setting DRR_FLAG_SPILL_BLOCK.1937*/1938if (((drro->drr_flags & ~(DRR_OBJECT_SPILL))) ||1939(!rwa->spill && DRR_OBJECT_HAS_SPILL(drro->drr_flags))) {1940return (SET_ERROR(EINVAL));1941}19421943if (drro->drr_raw_bonuslen != 0 || drro->drr_nblkptr != 0 ||1944drro->drr_indblkshift != 0 || drro->drr_nlevels != 0) {1945return (SET_ERROR(EINVAL));1946}1947}19481949err = dmu_object_info(rwa->os, drro->drr_object, &doi);19501951if (err != 0 && err != ENOENT && err != EEXIST)1952return (SET_ERROR(EINVAL));19531954if (drro->drr_object > rwa->max_object)1955rwa->max_object = drro->drr_object;19561957/*1958* If we are losing blkptrs or changing the block size this must1959* be a new file instance. We must clear out the previous file1960* contents before we can change this type of metadata in the dnode.1961* Raw receives will also check that the indirect structure of the1962* dnode hasn't changed.1963*/1964uint64_t object_to_hold;1965if (err == 0) {1966err = receive_handle_existing_object(rwa, drro, &doi, data,1967&object_to_hold, &new_blksz);1968if (err != 0)1969return (err);1970} else if (err == EEXIST) {1971/*1972* The object requested is currently an interior slot of a1973* multi-slot dnode. This will be resolved when the next txg1974* is synced out, since the send stream will have told us1975* to free this slot when we freed the associated dnode1976* earlier in the stream.1977*/1978txg_wait_synced(dmu_objset_pool(rwa->os), 0);19791980if (dmu_object_info(rwa->os, drro->drr_object, NULL) != ENOENT)1981return (SET_ERROR(EINVAL));19821983/* object was freed and we are about to allocate a new one */1984object_to_hold = DMU_NEW_OBJECT;1985} else {1986/*1987* If the only record in this range so far was DRR_FREEOBJECTS1988* with at least one actually freed object, it's possible that1989* the block will now be converted to a hole. We need to wait1990* for the txg to sync to prevent races.1991*/1992if (rwa->or_need_sync == ORNS_YES)1993txg_wait_synced(dmu_objset_pool(rwa->os), 0);19941995/* object is free and we are about to allocate a new one */1996object_to_hold = DMU_NEW_OBJECT;1997}19981999/* Only relevant for the first object in the range */2000rwa->or_need_sync = ORNS_NO;20012002/*2003* If this is a multi-slot dnode there is a chance that this2004* object will expand into a slot that is already used by2005* another object from the previous snapshot. We must free2006* these objects before we attempt to allocate the new dnode.2007*/2008if (dn_slots > 1) {2009boolean_t need_sync = B_FALSE;20102011for (uint64_t slot = drro->drr_object + 1;2012slot < drro->drr_object + dn_slots;2013slot++) {2014dmu_object_info_t slot_doi;20152016err = dmu_object_info(rwa->os, slot, &slot_doi);2017if (err == ENOENT || err == EEXIST)2018continue;2019else if (err != 0)2020return (err);20212022err = dmu_free_long_object(rwa->os, slot);2023if (err != 0)2024return (err);20252026need_sync = B_TRUE;2027}20282029if (need_sync)2030txg_wait_synced(dmu_objset_pool(rwa->os), 0);2031}20322033tx = dmu_tx_create(rwa->os);2034dmu_tx_hold_bonus(tx, object_to_hold);2035dmu_tx_hold_write(tx, object_to_hold, 0, 0);2036err = dmu_tx_assign(tx, DMU_TX_WAIT);2037if (err != 0) {2038dmu_tx_abort(tx);2039return (err);2040}20412042if (object_to_hold == DMU_NEW_OBJECT) {2043/* Currently free, wants to be allocated */2044err = dmu_object_claim_dnsize(rwa->os, drro->drr_object,2045drro->drr_type, new_blksz,2046drro->drr_bonustype, drro->drr_bonuslen,2047dn_slots << DNODE_SHIFT, tx);2048} else if (drro->drr_type != doi.doi_type ||2049new_blksz != doi.doi_data_block_size ||2050drro->drr_bonustype != doi.doi_bonus_type ||2051drro->drr_bonuslen != doi.doi_bonus_size) {2052/* Currently allocated, but with different properties */2053err = dmu_object_reclaim_dnsize(rwa->os, drro->drr_object,2054drro->drr_type, new_blksz,2055drro->drr_bonustype, drro->drr_bonuslen,2056dn_slots << DNODE_SHIFT, rwa->spill ?2057DRR_OBJECT_HAS_SPILL(drro->drr_flags) : B_FALSE, tx);2058} else if (rwa->spill && !DRR_OBJECT_HAS_SPILL(drro->drr_flags)) {2059/*2060* Currently allocated, the existing version of this object2061* may reference a spill block that is no longer allocated2062* at the source and needs to be freed.2063*/2064err = dmu_object_rm_spill(rwa->os, drro->drr_object, tx);2065}20662067if (err != 0) {2068dmu_tx_commit(tx);2069return (SET_ERROR(EINVAL));2070}20712072if (rwa->or_crypt_params_present) {2073/*2074* Set the crypt params for the buffer associated with this2075* range of dnodes. This causes the blkptr_t to have the2076* same crypt params (byteorder, salt, iv, mac) as on the2077* sending side.2078*2079* Since we are committing this tx now, it is possible for2080* the dnode block to end up on-disk with the incorrect MAC,2081* if subsequent objects in this block are received in a2082* different txg. However, since the dataset is marked as2083* inconsistent, no code paths will do a non-raw read (or2084* decrypt the block / verify the MAC). The receive code and2085* scrub code can safely do raw reads and verify the2086* checksum. They don't need to verify the MAC.2087*/2088dmu_buf_t *db = NULL;2089uint64_t offset = rwa->or_firstobj * DNODE_MIN_SIZE;20902091err = dmu_buf_hold_by_dnode(DMU_META_DNODE(rwa->os),2092offset, FTAG, &db, DMU_READ_PREFETCH | DMU_READ_NO_DECRYPT);2093if (err != 0) {2094dmu_tx_commit(tx);2095return (SET_ERROR(EINVAL));2096}20972098dmu_buf_set_crypt_params(db, rwa->or_byteorder,2099rwa->or_salt, rwa->or_iv, rwa->or_mac, tx);21002101dmu_buf_rele(db, FTAG);21022103rwa->or_crypt_params_present = B_FALSE;2104}21052106dmu_object_set_checksum(rwa->os, drro->drr_object,2107drro->drr_checksumtype, tx);2108dmu_object_set_compress(rwa->os, drro->drr_object,2109drro->drr_compress, tx);21102111/* handle more restrictive dnode structuring for raw recvs */2112if (rwa->raw) {2113/*2114* Set the indirect block size, block shift, nlevels.2115* This will not fail because we ensured all of the2116* blocks were freed earlier if this is a new object.2117* For non-new objects block size and indirect block2118* shift cannot change and nlevels can only increase.2119*/2120ASSERT3U(new_blksz, ==, drro->drr_blksz);2121VERIFY0(dmu_object_set_blocksize(rwa->os, drro->drr_object,2122drro->drr_blksz, drro->drr_indblkshift, tx));2123VERIFY0(dmu_object_set_nlevels(rwa->os, drro->drr_object,2124drro->drr_nlevels, tx));21252126/*2127* Set the maxblkid. This will always succeed because2128* we freed all blocks beyond the new maxblkid above.2129*/2130VERIFY0(dmu_object_set_maxblkid(rwa->os, drro->drr_object,2131drro->drr_maxblkid, tx));2132}21332134if (data != NULL) {2135dmu_buf_t *db;2136dnode_t *dn;2137dmu_flags_t flags = DMU_READ_NO_PREFETCH;21382139if (rwa->raw)2140flags |= DMU_READ_NO_DECRYPT;21412142VERIFY0(dnode_hold(rwa->os, drro->drr_object, FTAG, &dn));2143VERIFY0(dmu_bonus_hold_by_dnode(dn, FTAG, &db, flags));21442145dmu_buf_will_dirty(db, tx);21462147ASSERT3U(db->db_size, >=, drro->drr_bonuslen);2148memcpy(db->db_data, data, DRR_OBJECT_PAYLOAD_SIZE(drro));21492150/*2151* Raw bonus buffers have their byteorder determined by the2152* DRR_OBJECT_RANGE record.2153*/2154if (rwa->byteswap && !rwa->raw) {2155dmu_object_byteswap_t byteswap =2156DMU_OT_BYTESWAP(drro->drr_bonustype);2157dmu_ot_byteswap[byteswap].ob_func(db->db_data,2158DRR_OBJECT_PAYLOAD_SIZE(drro));2159}2160dmu_buf_rele(db, FTAG);2161dnode_rele(dn, FTAG);2162}21632164/*2165* If the receive fails, we want the resume stream to start with the2166* same record that we last successfully received. There is no way to2167* request resume from the object record, but we can benefit from the2168* fact that sender always sends object record before anything else,2169* after which it will "resend" data at offset 0 and resume normally.2170*/2171save_resume_state(rwa, drro->drr_object, 0, tx);21722173dmu_tx_commit(tx);21742175return (0);2176}21772178noinline static int2179receive_freeobjects(struct receive_writer_arg *rwa,2180struct drr_freeobjects *drrfo)2181{2182uint64_t obj;2183int next_err = 0;21842185if (drrfo->drr_firstobj + drrfo->drr_numobjs < drrfo->drr_firstobj)2186return (SET_ERROR(EINVAL));21872188for (obj = drrfo->drr_firstobj == 0 ? 1 : drrfo->drr_firstobj;2189obj < drrfo->drr_firstobj + drrfo->drr_numobjs &&2190obj < DN_MAX_OBJECT && next_err == 0;2191next_err = dmu_object_next(rwa->os, &obj, FALSE, 0)) {2192dmu_object_info_t doi;2193int err;21942195err = dmu_object_info(rwa->os, obj, &doi);2196if (err == ENOENT)2197continue;2198else if (err != 0)2199return (err);22002201err = dmu_free_long_object(rwa->os, obj);22022203if (err != 0)2204return (err);22052206if (rwa->or_need_sync == ORNS_MAYBE)2207rwa->or_need_sync = ORNS_YES;2208}2209if (next_err != ESRCH)2210return (next_err);2211return (0);2212}22132214/*2215* Note: if this fails, the caller will clean up any records left on the2216* rwa->write_batch list.2217*/2218static int2219flush_write_batch_impl(struct receive_writer_arg *rwa)2220{2221dnode_t *dn;2222int err;22232224if (dnode_hold(rwa->os, rwa->last_object, FTAG, &dn) != 0)2225return (SET_ERROR(EINVAL));22262227struct receive_record_arg *last_rrd = list_tail(&rwa->write_batch);2228struct drr_write *last_drrw = &last_rrd->header.drr_u.drr_write;22292230struct receive_record_arg *first_rrd = list_head(&rwa->write_batch);2231struct drr_write *first_drrw = &first_rrd->header.drr_u.drr_write;22322233ASSERT3U(rwa->last_object, ==, last_drrw->drr_object);2234ASSERT3U(rwa->last_offset, ==, last_drrw->drr_offset);22352236dmu_tx_t *tx = dmu_tx_create(rwa->os);2237dmu_tx_hold_write_by_dnode(tx, dn, first_drrw->drr_offset,2238last_drrw->drr_offset - first_drrw->drr_offset +2239last_drrw->drr_logical_size);2240err = dmu_tx_assign(tx, DMU_TX_WAIT);2241if (err != 0) {2242dmu_tx_abort(tx);2243dnode_rele(dn, FTAG);2244return (err);2245}22462247struct receive_record_arg *rrd;2248while ((rrd = list_head(&rwa->write_batch)) != NULL) {2249struct drr_write *drrw = &rrd->header.drr_u.drr_write;2250abd_t *abd = rrd->abd;22512252ASSERT3U(drrw->drr_object, ==, rwa->last_object);22532254if (drrw->drr_logical_size != dn->dn_datablksz) {2255/*2256* The WRITE record is larger than the object's block2257* size. We must be receiving an incremental2258* large-block stream into a dataset that previously did2259* a non-large-block receive. Lightweight writes must2260* be exactly one block, so we need to decompress the2261* data (if compressed) and do a normal dmu_write().2262*/2263ASSERT3U(drrw->drr_logical_size, >, dn->dn_datablksz);2264if (DRR_WRITE_COMPRESSED(drrw)) {2265abd_t *decomp_abd =2266abd_alloc_linear(drrw->drr_logical_size,2267B_FALSE);22682269err = zio_decompress_data(2270drrw->drr_compressiontype,2271abd, decomp_abd,2272abd_get_size(abd),2273abd_get_size(decomp_abd), NULL);22742275if (err == 0) {2276dmu_write_by_dnode(dn,2277drrw->drr_offset,2278drrw->drr_logical_size,2279abd_to_buf(decomp_abd), tx,2280DMU_READ_NO_PREFETCH |2281DMU_UNCACHEDIO);2282}2283abd_free(decomp_abd);2284} else {2285dmu_write_by_dnode(dn,2286drrw->drr_offset,2287drrw->drr_logical_size,2288abd_to_buf(abd), tx,2289DMU_READ_NO_PREFETCH |2290DMU_UNCACHEDIO);2291}2292if (err == 0)2293abd_free(abd);2294} else {2295zio_prop_t zp = {0};2296dmu_write_policy(rwa->os, dn, 0, 0, &zp);22972298zio_flag_t zio_flags = 0;22992300if (rwa->raw) {2301zp.zp_encrypt = B_TRUE;2302zp.zp_compress = drrw->drr_compressiontype;2303zp.zp_byteorder = ZFS_HOST_BYTEORDER ^2304!!DRR_IS_RAW_BYTESWAPPED(drrw->drr_flags) ^2305rwa->byteswap;2306memcpy(zp.zp_salt, drrw->drr_salt,2307ZIO_DATA_SALT_LEN);2308memcpy(zp.zp_iv, drrw->drr_iv,2309ZIO_DATA_IV_LEN);2310memcpy(zp.zp_mac, drrw->drr_mac,2311ZIO_DATA_MAC_LEN);2312if (DMU_OT_IS_ENCRYPTED(zp.zp_type)) {2313zp.zp_nopwrite = B_FALSE;2314zp.zp_copies = MIN(zp.zp_copies,2315SPA_DVAS_PER_BP - 1);2316zp.zp_gang_copies =2317MIN(zp.zp_gang_copies,2318SPA_DVAS_PER_BP - 1);2319}2320zio_flags |= ZIO_FLAG_RAW;2321} else if (DRR_WRITE_COMPRESSED(drrw)) {2322ASSERT3U(drrw->drr_compressed_size, >, 0);2323ASSERT3U(drrw->drr_logical_size, >=,2324drrw->drr_compressed_size);2325zp.zp_compress = drrw->drr_compressiontype;2326zio_flags |= ZIO_FLAG_RAW_COMPRESS;2327} else if (rwa->byteswap) {2328/*2329* Note: compressed blocks never need to be2330* byteswapped, because WRITE records for2331* metadata blocks are never compressed. The2332* exception is raw streams, which are written2333* in the original byteorder, and the byteorder2334* bit is preserved in the BP by setting2335* zp_byteorder above.2336*/2337dmu_object_byteswap_t byteswap =2338DMU_OT_BYTESWAP(drrw->drr_type);2339dmu_ot_byteswap[byteswap].ob_func(2340abd_to_buf(abd),2341DRR_WRITE_PAYLOAD_SIZE(drrw));2342}23432344/*2345* Since this data can't be read until the receive2346* completes, we can do a "lightweight" write for2347* improved performance.2348*/2349err = dmu_lightweight_write_by_dnode(dn,2350drrw->drr_offset, abd, &zp, zio_flags, tx);2351}23522353if (err != 0) {2354/*2355* This rrd is left on the list, so the caller will2356* free it (and the abd).2357*/2358break;2359}23602361/*2362* Note: If the receive fails, we want the resume stream to2363* start with the same record that we last successfully2364* received (as opposed to the next record), so that we can2365* verify that we are resuming from the correct location.2366*/2367save_resume_state(rwa, drrw->drr_object, drrw->drr_offset, tx);23682369list_remove(&rwa->write_batch, rrd);2370kmem_free(rrd, sizeof (*rrd));2371}23722373dmu_tx_commit(tx);2374dnode_rele(dn, FTAG);2375return (err);2376}23772378noinline static int2379flush_write_batch(struct receive_writer_arg *rwa)2380{2381if (list_is_empty(&rwa->write_batch))2382return (0);2383int err = rwa->err;2384if (err == 0)2385err = flush_write_batch_impl(rwa);2386if (err != 0) {2387struct receive_record_arg *rrd;2388while ((rrd = list_remove_head(&rwa->write_batch)) != NULL) {2389abd_free(rrd->abd);2390kmem_free(rrd, sizeof (*rrd));2391}2392}2393ASSERT(list_is_empty(&rwa->write_batch));2394return (err);2395}23962397noinline static int2398receive_process_write_record(struct receive_writer_arg *rwa,2399struct receive_record_arg *rrd)2400{2401int err = 0;24022403ASSERT3U(rrd->header.drr_type, ==, DRR_WRITE);2404struct drr_write *drrw = &rrd->header.drr_u.drr_write;24052406if (drrw->drr_offset + drrw->drr_logical_size < drrw->drr_offset ||2407!DMU_OT_IS_VALID(drrw->drr_type))2408return (SET_ERROR(EINVAL));24092410if (rwa->heal) {2411blkptr_t *bp;2412dmu_buf_t *dbp;2413dmu_flags_t flags = DB_RF_CANFAIL;24142415if (rwa->raw)2416flags |= DMU_READ_NO_DECRYPT;24172418if (rwa->byteswap) {2419dmu_object_byteswap_t byteswap =2420DMU_OT_BYTESWAP(drrw->drr_type);2421dmu_ot_byteswap[byteswap].ob_func(abd_to_buf(rrd->abd),2422DRR_WRITE_PAYLOAD_SIZE(drrw));2423}24242425err = dmu_buf_hold_noread(rwa->os, drrw->drr_object,2426drrw->drr_offset, FTAG, &dbp);2427if (err != 0)2428return (err);24292430/* Try to read the object to see if it needs healing */2431err = dbuf_read((dmu_buf_impl_t *)dbp, NULL, flags);2432/*2433* We only try to heal when dbuf_read() returns a ECKSUMs.2434* Other errors (even EIO) get returned to caller.2435* EIO indicates that the device is not present/accessible,2436* so writing to it will likely fail.2437* If the block is healthy, we don't want to overwrite it2438* unnecessarily.2439*/2440if (err != ECKSUM) {2441dmu_buf_rele(dbp, FTAG);2442return (err);2443}2444/* Make sure the on-disk block and recv record sizes match */2445if (drrw->drr_logical_size != dbp->db_size) {2446err = ENOTSUP;2447dmu_buf_rele(dbp, FTAG);2448return (err);2449}2450/* Get the block pointer for the corrupted block */2451bp = dmu_buf_get_blkptr(dbp);2452err = do_corrective_recv(rwa, drrw, rrd, bp);2453dmu_buf_rele(dbp, FTAG);2454return (err);2455}24562457/*2458* For resuming to work, records must be in increasing order2459* by (object, offset).2460*/2461if (drrw->drr_object < rwa->last_object ||2462(drrw->drr_object == rwa->last_object &&2463drrw->drr_offset < rwa->last_offset)) {2464return (SET_ERROR(EINVAL));2465}24662467struct receive_record_arg *first_rrd = list_head(&rwa->write_batch);2468struct drr_write *first_drrw = &first_rrd->header.drr_u.drr_write;2469uint64_t batch_size =2470MIN(zfs_recv_write_batch_size, DMU_MAX_ACCESS / 2);2471if (first_rrd != NULL &&2472(drrw->drr_object != first_drrw->drr_object ||2473drrw->drr_offset >= first_drrw->drr_offset + batch_size)) {2474err = flush_write_batch(rwa);2475if (err != 0)2476return (err);2477}24782479rwa->last_object = drrw->drr_object;2480rwa->last_offset = drrw->drr_offset;24812482if (rwa->last_object > rwa->max_object)2483rwa->max_object = rwa->last_object;24842485list_insert_tail(&rwa->write_batch, rrd);2486/*2487* Return EAGAIN to indicate that we will use this rrd again,2488* so the caller should not free it2489*/2490return (EAGAIN);2491}24922493static int2494receive_write_embedded(struct receive_writer_arg *rwa,2495struct drr_write_embedded *drrwe, void *data)2496{2497dmu_tx_t *tx;2498int err;24992500if (drrwe->drr_offset + drrwe->drr_length < drrwe->drr_offset)2501return (SET_ERROR(EINVAL));25022503if (drrwe->drr_psize > BPE_PAYLOAD_SIZE)2504return (SET_ERROR(EINVAL));25052506if (drrwe->drr_etype >= NUM_BP_EMBEDDED_TYPES)2507return (SET_ERROR(EINVAL));2508if (drrwe->drr_compression >= ZIO_COMPRESS_FUNCTIONS)2509return (SET_ERROR(EINVAL));2510if (rwa->raw)2511return (SET_ERROR(EINVAL));25122513if (drrwe->drr_object > rwa->max_object)2514rwa->max_object = drrwe->drr_object;25152516tx = dmu_tx_create(rwa->os);25172518dmu_tx_hold_write(tx, drrwe->drr_object,2519drrwe->drr_offset, drrwe->drr_length);2520err = dmu_tx_assign(tx, DMU_TX_WAIT);2521if (err != 0) {2522dmu_tx_abort(tx);2523return (err);2524}25252526dmu_write_embedded(rwa->os, drrwe->drr_object,2527drrwe->drr_offset, data, drrwe->drr_etype,2528drrwe->drr_compression, drrwe->drr_lsize, drrwe->drr_psize,2529rwa->byteswap ^ ZFS_HOST_BYTEORDER, tx);25302531/* See comment in restore_write. */2532save_resume_state(rwa, drrwe->drr_object, drrwe->drr_offset, tx);2533dmu_tx_commit(tx);2534return (0);2535}25362537static int2538receive_spill(struct receive_writer_arg *rwa, struct drr_spill *drrs,2539abd_t *abd)2540{2541dmu_buf_t *db, *db_spill;2542int err;25432544if (drrs->drr_length < SPA_MINBLOCKSIZE ||2545drrs->drr_length > spa_maxblocksize(dmu_objset_spa(rwa->os)))2546return (SET_ERROR(EINVAL));25472548/*2549* This is an unmodified spill block which was added to the stream2550* to resolve an issue with incorrectly removing spill blocks. It2551* should be ignored by current versions of the code which support2552* the DRR_FLAG_SPILL_BLOCK flag.2553*/2554if (rwa->spill && DRR_SPILL_IS_UNMODIFIED(drrs->drr_flags)) {2555abd_free(abd);2556return (0);2557}25582559if (rwa->raw) {2560if (!DMU_OT_IS_VALID(drrs->drr_type) ||2561drrs->drr_compressiontype >= ZIO_COMPRESS_FUNCTIONS ||2562drrs->drr_compressed_size == 0)2563return (SET_ERROR(EINVAL));2564}25652566if (dmu_object_info(rwa->os, drrs->drr_object, NULL) != 0)2567return (SET_ERROR(EINVAL));25682569if (drrs->drr_object > rwa->max_object)2570rwa->max_object = drrs->drr_object;25712572VERIFY0(dmu_bonus_hold(rwa->os, drrs->drr_object, FTAG, &db));2573if ((err = dmu_spill_hold_by_bonus(db, DMU_READ_NO_DECRYPT |2574DB_RF_CANFAIL, FTAG, &db_spill)) != 0) {2575dmu_buf_rele(db, FTAG);2576return (err);2577}25782579dmu_tx_t *tx = dmu_tx_create(rwa->os);25802581dmu_tx_hold_spill(tx, db->db_object);25822583err = dmu_tx_assign(tx, DMU_TX_WAIT);2584if (err != 0) {2585dmu_buf_rele(db, FTAG);2586dmu_buf_rele(db_spill, FTAG);2587dmu_tx_abort(tx);2588return (err);2589}25902591/*2592* Spill blocks may both grow and shrink. When a change in size2593* occurs any existing dbuf must be updated to match the logical2594* size of the provided arc_buf_t.2595*/2596if (db_spill->db_size != drrs->drr_length) {2597dmu_buf_will_fill(db_spill, tx, B_FALSE);2598VERIFY0(dbuf_spill_set_blksz(db_spill,2599drrs->drr_length, tx));2600}26012602arc_buf_t *abuf;2603if (rwa->raw) {2604boolean_t byteorder = ZFS_HOST_BYTEORDER ^2605!!DRR_IS_RAW_BYTESWAPPED(drrs->drr_flags) ^2606rwa->byteswap;26072608abuf = arc_loan_raw_buf(dmu_objset_spa(rwa->os),2609drrs->drr_object, byteorder, drrs->drr_salt,2610drrs->drr_iv, drrs->drr_mac, drrs->drr_type,2611drrs->drr_compressed_size, drrs->drr_length,2612drrs->drr_compressiontype, 0);2613} else {2614abuf = arc_loan_buf(dmu_objset_spa(rwa->os),2615DMU_OT_IS_METADATA(drrs->drr_type),2616drrs->drr_length);2617if (rwa->byteswap) {2618dmu_object_byteswap_t byteswap =2619DMU_OT_BYTESWAP(drrs->drr_type);2620dmu_ot_byteswap[byteswap].ob_func(abd_to_buf(abd),2621DRR_SPILL_PAYLOAD_SIZE(drrs));2622}2623}26242625memcpy(abuf->b_data, abd_to_buf(abd), DRR_SPILL_PAYLOAD_SIZE(drrs));2626abd_free(abd);2627dbuf_assign_arcbuf((dmu_buf_impl_t *)db_spill, abuf, tx,2628DMU_UNCACHEDIO);26292630dmu_buf_rele(db, FTAG);2631dmu_buf_rele(db_spill, FTAG);26322633dmu_tx_commit(tx);2634return (0);2635}26362637noinline static int2638receive_free(struct receive_writer_arg *rwa, struct drr_free *drrf)2639{2640int err;26412642if (drrf->drr_length != -1ULL &&2643drrf->drr_offset + drrf->drr_length < drrf->drr_offset)2644return (SET_ERROR(EINVAL));26452646if (dmu_object_info(rwa->os, drrf->drr_object, NULL) != 0)2647return (SET_ERROR(EINVAL));26482649if (drrf->drr_object > rwa->max_object)2650rwa->max_object = drrf->drr_object;26512652err = dmu_free_long_range(rwa->os, drrf->drr_object,2653drrf->drr_offset, drrf->drr_length);26542655return (err);2656}26572658static int2659receive_object_range(struct receive_writer_arg *rwa,2660struct drr_object_range *drror)2661{2662/*2663* By default, we assume this block is in our native format2664* (ZFS_HOST_BYTEORDER). We then take into account whether2665* the send stream is byteswapped (rwa->byteswap). Finally,2666* we need to byteswap again if this particular block was2667* in non-native format on the send side.2668*/2669boolean_t byteorder = ZFS_HOST_BYTEORDER ^ rwa->byteswap ^2670!!DRR_IS_RAW_BYTESWAPPED(drror->drr_flags);26712672/*2673* Since dnode block sizes are constant, we should not need to worry2674* about making sure that the dnode block size is the same on the2675* sending and receiving sides for the time being. For non-raw sends,2676* this does not matter (and in fact we do not send a DRR_OBJECT_RANGE2677* record at all). Raw sends require this record type because the2678* encryption parameters are used to protect an entire block of bonus2679* buffers. If the size of dnode blocks ever becomes variable,2680* handling will need to be added to ensure that dnode block sizes2681* match on the sending and receiving side.2682*/2683if (drror->drr_numslots != DNODES_PER_BLOCK ||2684P2PHASE(drror->drr_firstobj, DNODES_PER_BLOCK) != 0 ||2685!rwa->raw)2686return (SET_ERROR(EINVAL));26872688if (drror->drr_firstobj > rwa->max_object)2689rwa->max_object = drror->drr_firstobj;26902691/*2692* The DRR_OBJECT_RANGE handling must be deferred to receive_object()2693* so that the block of dnodes is not written out when it's empty,2694* and converted to a HOLE BP.2695*/2696rwa->or_crypt_params_present = B_TRUE;2697rwa->or_firstobj = drror->drr_firstobj;2698rwa->or_numslots = drror->drr_numslots;2699memcpy(rwa->or_salt, drror->drr_salt, ZIO_DATA_SALT_LEN);2700memcpy(rwa->or_iv, drror->drr_iv, ZIO_DATA_IV_LEN);2701memcpy(rwa->or_mac, drror->drr_mac, ZIO_DATA_MAC_LEN);2702rwa->or_byteorder = byteorder;27032704rwa->or_need_sync = ORNS_MAYBE;27052706return (0);2707}27082709/*2710* Until we have the ability to redact large ranges of data efficiently, we2711* process these records as frees.2712*/2713noinline static int2714receive_redact(struct receive_writer_arg *rwa, struct drr_redact *drrr)2715{2716struct drr_free drrf = {0};2717drrf.drr_length = drrr->drr_length;2718drrf.drr_object = drrr->drr_object;2719drrf.drr_offset = drrr->drr_offset;2720drrf.drr_toguid = drrr->drr_toguid;2721return (receive_free(rwa, &drrf));2722}27232724/* used to destroy the drc_ds on error */2725static void2726dmu_recv_cleanup_ds(dmu_recv_cookie_t *drc)2727{2728dsl_dataset_t *ds = drc->drc_ds;2729ds_hold_flags_t dsflags;27302731dsflags = (drc->drc_raw) ? DS_HOLD_FLAG_NONE : DS_HOLD_FLAG_DECRYPT;2732/*2733* Wait for the txg sync before cleaning up the receive. For2734* resumable receives, this ensures that our resume state has2735* been written out to disk. For raw receives, this ensures2736* that the user accounting code will not attempt to do anything2737* after we stopped receiving the dataset.2738*/2739txg_wait_synced(ds->ds_dir->dd_pool, 0);2740ds->ds_objset->os_raw_receive = B_FALSE;27412742rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);2743if (drc->drc_resumable && drc->drc_should_save &&2744!BP_IS_HOLE(dsl_dataset_get_blkptr(ds))) {2745rrw_exit(&ds->ds_bp_rwlock, FTAG);2746dsl_dataset_disown(ds, dsflags, dmu_recv_tag);2747} else {2748char name[ZFS_MAX_DATASET_NAME_LEN];2749rrw_exit(&ds->ds_bp_rwlock, FTAG);2750dsl_dataset_name(ds, name);2751dsl_dataset_disown(ds, dsflags, dmu_recv_tag);2752if (!drc->drc_heal)2753(void) dsl_destroy_head(name);2754}2755}27562757static void2758receive_cksum(dmu_recv_cookie_t *drc, int len, void *buf)2759{2760if (drc->drc_byteswap) {2761(void) fletcher_4_incremental_byteswap(buf, len,2762&drc->drc_cksum);2763} else {2764(void) fletcher_4_incremental_native(buf, len, &drc->drc_cksum);2765}2766}27672768/*2769* Read the payload into a buffer of size len, and update the current record's2770* payload field.2771* Allocate drc->drc_next_rrd and read the next record's header into2772* drc->drc_next_rrd->header.2773* Verify checksum of payload and next record.2774*/2775static int2776receive_read_payload_and_next_header(dmu_recv_cookie_t *drc, int len, void *buf)2777{2778int err;27792780if (len != 0) {2781ASSERT3U(len, <=, SPA_MAXBLOCKSIZE);2782err = receive_read(drc, len, buf);2783if (err != 0)2784return (err);2785receive_cksum(drc, len, buf);27862787/* note: rrd is NULL when reading the begin record's payload */2788if (drc->drc_rrd != NULL) {2789drc->drc_rrd->payload = buf;2790drc->drc_rrd->payload_size = len;2791drc->drc_rrd->bytes_read = drc->drc_bytes_read;2792}2793} else {2794ASSERT0P(buf);2795}27962797drc->drc_prev_cksum = drc->drc_cksum;27982799drc->drc_next_rrd = kmem_zalloc(sizeof (*drc->drc_next_rrd), KM_SLEEP);2800err = receive_read(drc, sizeof (drc->drc_next_rrd->header),2801&drc->drc_next_rrd->header);2802drc->drc_next_rrd->bytes_read = drc->drc_bytes_read;28032804if (err != 0) {2805kmem_free(drc->drc_next_rrd, sizeof (*drc->drc_next_rrd));2806drc->drc_next_rrd = NULL;2807return (err);2808}2809if (drc->drc_next_rrd->header.drr_type == DRR_BEGIN) {2810kmem_free(drc->drc_next_rrd, sizeof (*drc->drc_next_rrd));2811drc->drc_next_rrd = NULL;2812return (SET_ERROR(EINVAL));2813}28142815/*2816* Note: checksum is of everything up to but not including the2817* checksum itself.2818*/2819ASSERT3U(offsetof(dmu_replay_record_t, drr_u.drr_checksum.drr_checksum),2820==, sizeof (dmu_replay_record_t) - sizeof (zio_cksum_t));2821receive_cksum(drc,2822offsetof(dmu_replay_record_t, drr_u.drr_checksum.drr_checksum),2823&drc->drc_next_rrd->header);28242825zio_cksum_t cksum_orig =2826drc->drc_next_rrd->header.drr_u.drr_checksum.drr_checksum;2827zio_cksum_t *cksump =2828&drc->drc_next_rrd->header.drr_u.drr_checksum.drr_checksum;28292830if (drc->drc_byteswap)2831byteswap_record(&drc->drc_next_rrd->header);28322833if ((!ZIO_CHECKSUM_IS_ZERO(cksump)) &&2834!ZIO_CHECKSUM_EQUAL(drc->drc_cksum, *cksump)) {2835kmem_free(drc->drc_next_rrd, sizeof (*drc->drc_next_rrd));2836drc->drc_next_rrd = NULL;2837return (SET_ERROR(ECKSUM));2838}28392840receive_cksum(drc, sizeof (cksum_orig), &cksum_orig);28412842return (0);2843}28442845/*2846* Issue the prefetch reads for any necessary indirect blocks.2847*2848* We use the object ignore list to tell us whether or not to issue prefetches2849* for a given object. We do this for both correctness (in case the blocksize2850* of an object has changed) and performance (if the object doesn't exist, don't2851* needlessly try to issue prefetches). We also trim the list as we go through2852* the stream to prevent it from growing to an unbounded size.2853*2854* The object numbers within will always be in sorted order, and any write2855* records we see will also be in sorted order, but they're not sorted with2856* respect to each other (i.e. we can get several object records before2857* receiving each object's write records). As a result, once we've reached a2858* given object number, we can safely remove any reference to lower object2859* numbers in the ignore list. In practice, we receive up to 32 object records2860* before receiving write records, so the list can have up to 32 nodes in it.2861*/2862static void2863receive_read_prefetch(dmu_recv_cookie_t *drc, uint64_t object, uint64_t offset,2864uint64_t length)2865{2866if (!objlist_exists(drc->drc_ignore_objlist, object)) {2867dmu_prefetch(drc->drc_os, object, 1, offset, length,2868ZIO_PRIORITY_SYNC_READ);2869}2870}28712872/*2873* Read records off the stream, issuing any necessary prefetches.2874*/2875static int2876receive_read_record(dmu_recv_cookie_t *drc)2877{2878int err;28792880switch (drc->drc_rrd->header.drr_type) {2881case DRR_OBJECT:2882{2883struct drr_object *drro =2884&drc->drc_rrd->header.drr_u.drr_object;2885uint32_t size = DRR_OBJECT_PAYLOAD_SIZE(drro);2886void *buf = NULL;2887dmu_object_info_t doi;28882889if (size != 0)2890buf = kmem_zalloc(size, KM_SLEEP);28912892err = receive_read_payload_and_next_header(drc, size, buf);2893if (err != 0) {2894kmem_free(buf, size);2895return (err);2896}2897err = dmu_object_info(drc->drc_os, drro->drr_object, &doi);2898/*2899* See receive_read_prefetch for an explanation why we're2900* storing this object in the ignore_obj_list.2901*/2902if (err == ENOENT || err == EEXIST ||2903(err == 0 && doi.doi_data_block_size != drro->drr_blksz)) {2904objlist_insert(drc->drc_ignore_objlist,2905drro->drr_object);2906err = 0;2907}2908return (err);2909}2910case DRR_FREEOBJECTS:2911{2912err = receive_read_payload_and_next_header(drc, 0, NULL);2913return (err);2914}2915case DRR_WRITE:2916{2917struct drr_write *drrw = &drc->drc_rrd->header.drr_u.drr_write;2918int size = DRR_WRITE_PAYLOAD_SIZE(drrw);2919abd_t *abd = abd_alloc_linear(size, B_FALSE);2920err = receive_read_payload_and_next_header(drc, size,2921abd_to_buf(abd));2922if (err != 0) {2923abd_free(abd);2924return (err);2925}2926drc->drc_rrd->abd = abd;2927receive_read_prefetch(drc, drrw->drr_object, drrw->drr_offset,2928drrw->drr_logical_size);2929return (err);2930}2931case DRR_WRITE_EMBEDDED:2932{2933struct drr_write_embedded *drrwe =2934&drc->drc_rrd->header.drr_u.drr_write_embedded;2935uint32_t size = P2ROUNDUP(drrwe->drr_psize, 8);2936void *buf = kmem_zalloc(size, KM_SLEEP);29372938err = receive_read_payload_and_next_header(drc, size, buf);2939if (err != 0) {2940kmem_free(buf, size);2941return (err);2942}29432944receive_read_prefetch(drc, drrwe->drr_object, drrwe->drr_offset,2945drrwe->drr_length);2946return (err);2947}2948case DRR_FREE:2949case DRR_REDACT:2950{2951/*2952* It might be beneficial to prefetch indirect blocks here, but2953* we don't really have the data to decide for sure.2954*/2955err = receive_read_payload_and_next_header(drc, 0, NULL);2956return (err);2957}2958case DRR_END:2959{2960struct drr_end *drre = &drc->drc_rrd->header.drr_u.drr_end;2961if (!ZIO_CHECKSUM_EQUAL(drc->drc_prev_cksum,2962drre->drr_checksum))2963return (SET_ERROR(ECKSUM));2964return (0);2965}2966case DRR_SPILL:2967{2968struct drr_spill *drrs = &drc->drc_rrd->header.drr_u.drr_spill;2969int size = DRR_SPILL_PAYLOAD_SIZE(drrs);2970abd_t *abd = abd_alloc_linear(size, B_FALSE);2971err = receive_read_payload_and_next_header(drc, size,2972abd_to_buf(abd));2973if (err != 0)2974abd_free(abd);2975else2976drc->drc_rrd->abd = abd;2977return (err);2978}2979case DRR_OBJECT_RANGE:2980{2981err = receive_read_payload_and_next_header(drc, 0, NULL);2982return (err);29832984}2985default:2986return (SET_ERROR(EINVAL));2987}2988}2989299029912992static void2993dprintf_drr(struct receive_record_arg *rrd, int err)2994{2995#ifdef ZFS_DEBUG2996switch (rrd->header.drr_type) {2997case DRR_OBJECT:2998{2999struct drr_object *drro = &rrd->header.drr_u.drr_object;3000dprintf("drr_type = OBJECT obj = %llu type = %u "3001"bonustype = %u blksz = %u bonuslen = %u cksumtype = %u "3002"compress = %u dn_slots = %u err = %d\n",3003(u_longlong_t)drro->drr_object, drro->drr_type,3004drro->drr_bonustype, drro->drr_blksz, drro->drr_bonuslen,3005drro->drr_checksumtype, drro->drr_compress,3006drro->drr_dn_slots, err);3007break;3008}3009case DRR_FREEOBJECTS:3010{3011struct drr_freeobjects *drrfo =3012&rrd->header.drr_u.drr_freeobjects;3013dprintf("drr_type = FREEOBJECTS firstobj = %llu "3014"numobjs = %llu err = %d\n",3015(u_longlong_t)drrfo->drr_firstobj,3016(u_longlong_t)drrfo->drr_numobjs, err);3017break;3018}3019case DRR_WRITE:3020{3021struct drr_write *drrw = &rrd->header.drr_u.drr_write;3022dprintf("drr_type = WRITE obj = %llu type = %u offset = %llu "3023"lsize = %llu cksumtype = %u flags = %u "3024"compress = %u psize = %llu err = %d\n",3025(u_longlong_t)drrw->drr_object, drrw->drr_type,3026(u_longlong_t)drrw->drr_offset,3027(u_longlong_t)drrw->drr_logical_size,3028drrw->drr_checksumtype, drrw->drr_flags,3029drrw->drr_compressiontype,3030(u_longlong_t)drrw->drr_compressed_size, err);3031break;3032}3033case DRR_WRITE_BYREF:3034{3035struct drr_write_byref *drrwbr =3036&rrd->header.drr_u.drr_write_byref;3037dprintf("drr_type = WRITE_BYREF obj = %llu offset = %llu "3038"length = %llu toguid = %llx refguid = %llx "3039"refobject = %llu refoffset = %llu cksumtype = %u "3040"flags = %u err = %d\n",3041(u_longlong_t)drrwbr->drr_object,3042(u_longlong_t)drrwbr->drr_offset,3043(u_longlong_t)drrwbr->drr_length,3044(u_longlong_t)drrwbr->drr_toguid,3045(u_longlong_t)drrwbr->drr_refguid,3046(u_longlong_t)drrwbr->drr_refobject,3047(u_longlong_t)drrwbr->drr_refoffset,3048drrwbr->drr_checksumtype, drrwbr->drr_flags, err);3049break;3050}3051case DRR_WRITE_EMBEDDED:3052{3053struct drr_write_embedded *drrwe =3054&rrd->header.drr_u.drr_write_embedded;3055dprintf("drr_type = WRITE_EMBEDDED obj = %llu offset = %llu "3056"length = %llu compress = %u etype = %u lsize = %u "3057"psize = %u err = %d\n",3058(u_longlong_t)drrwe->drr_object,3059(u_longlong_t)drrwe->drr_offset,3060(u_longlong_t)drrwe->drr_length,3061drrwe->drr_compression, drrwe->drr_etype,3062drrwe->drr_lsize, drrwe->drr_psize, err);3063break;3064}3065case DRR_FREE:3066{3067struct drr_free *drrf = &rrd->header.drr_u.drr_free;3068dprintf("drr_type = FREE obj = %llu offset = %llu "3069"length = %lld err = %d\n",3070(u_longlong_t)drrf->drr_object,3071(u_longlong_t)drrf->drr_offset,3072(longlong_t)drrf->drr_length,3073err);3074break;3075}3076case DRR_SPILL:3077{3078struct drr_spill *drrs = &rrd->header.drr_u.drr_spill;3079dprintf("drr_type = SPILL obj = %llu length = %llu "3080"err = %d\n", (u_longlong_t)drrs->drr_object,3081(u_longlong_t)drrs->drr_length, err);3082break;3083}3084case DRR_OBJECT_RANGE:3085{3086struct drr_object_range *drror =3087&rrd->header.drr_u.drr_object_range;3088dprintf("drr_type = OBJECT_RANGE firstobj = %llu "3089"numslots = %llu flags = %u err = %d\n",3090(u_longlong_t)drror->drr_firstobj,3091(u_longlong_t)drror->drr_numslots,3092drror->drr_flags, err);3093break;3094}3095default:3096return;3097}3098#endif3099}31003101/*3102* Commit the records to the pool.3103*/3104static int3105receive_process_record(struct receive_writer_arg *rwa,3106struct receive_record_arg *rrd)3107{3108int err;31093110/* Processing in order, therefore bytes_read should be increasing. */3111ASSERT3U(rrd->bytes_read, >=, rwa->bytes_read);3112rwa->bytes_read = rrd->bytes_read;31133114/* We can only heal write records; other ones get ignored */3115if (rwa->heal && rrd->header.drr_type != DRR_WRITE) {3116if (rrd->abd != NULL) {3117abd_free(rrd->abd);3118rrd->abd = NULL;3119} else if (rrd->payload != NULL) {3120kmem_free(rrd->payload, rrd->payload_size);3121rrd->payload = NULL;3122}3123return (0);3124}31253126if (!rwa->heal && rrd->header.drr_type != DRR_WRITE) {3127err = flush_write_batch(rwa);3128if (err != 0) {3129if (rrd->abd != NULL) {3130abd_free(rrd->abd);3131rrd->abd = NULL;3132rrd->payload = NULL;3133} else if (rrd->payload != NULL) {3134kmem_free(rrd->payload, rrd->payload_size);3135rrd->payload = NULL;3136}31373138return (err);3139}3140}31413142switch (rrd->header.drr_type) {3143case DRR_OBJECT:3144{3145struct drr_object *drro = &rrd->header.drr_u.drr_object;3146err = receive_object(rwa, drro, rrd->payload);3147kmem_free(rrd->payload, rrd->payload_size);3148rrd->payload = NULL;3149break;3150}3151case DRR_FREEOBJECTS:3152{3153struct drr_freeobjects *drrfo =3154&rrd->header.drr_u.drr_freeobjects;3155err = receive_freeobjects(rwa, drrfo);3156break;3157}3158case DRR_WRITE:3159{3160err = receive_process_write_record(rwa, rrd);3161if (rwa->heal) {3162/*3163* If healing - always free the abd after processing3164*/3165abd_free(rrd->abd);3166rrd->abd = NULL;3167} else if (err != EAGAIN) {3168/*3169* On success, a non-healing3170* receive_process_write_record() returns3171* EAGAIN to indicate that we do not want to free3172* the rrd or arc_buf.3173*/3174ASSERT(err != 0);3175abd_free(rrd->abd);3176rrd->abd = NULL;3177}3178break;3179}3180case DRR_WRITE_EMBEDDED:3181{3182struct drr_write_embedded *drrwe =3183&rrd->header.drr_u.drr_write_embedded;3184err = receive_write_embedded(rwa, drrwe, rrd->payload);3185kmem_free(rrd->payload, rrd->payload_size);3186rrd->payload = NULL;3187break;3188}3189case DRR_FREE:3190{3191struct drr_free *drrf = &rrd->header.drr_u.drr_free;3192err = receive_free(rwa, drrf);3193break;3194}3195case DRR_SPILL:3196{3197struct drr_spill *drrs = &rrd->header.drr_u.drr_spill;3198err = receive_spill(rwa, drrs, rrd->abd);3199if (err != 0)3200abd_free(rrd->abd);3201rrd->abd = NULL;3202rrd->payload = NULL;3203break;3204}3205case DRR_OBJECT_RANGE:3206{3207struct drr_object_range *drror =3208&rrd->header.drr_u.drr_object_range;3209err = receive_object_range(rwa, drror);3210break;3211}3212case DRR_REDACT:3213{3214struct drr_redact *drrr = &rrd->header.drr_u.drr_redact;3215err = receive_redact(rwa, drrr);3216break;3217}3218default:3219err = (SET_ERROR(EINVAL));3220}32213222if (err != 0)3223dprintf_drr(rrd, err);32243225return (err);3226}32273228/*3229* dmu_recv_stream's worker thread; pull records off the queue, and then call3230* receive_process_record When we're done, signal the main thread and exit.3231*/3232static __attribute__((noreturn)) void3233receive_writer_thread(void *arg)3234{3235struct receive_writer_arg *rwa = arg;3236struct receive_record_arg *rrd;3237fstrans_cookie_t cookie = spl_fstrans_mark();32383239for (rrd = bqueue_dequeue(&rwa->q); !rrd->eos_marker;3240rrd = bqueue_dequeue(&rwa->q)) {3241/*3242* If there's an error, the main thread will stop putting things3243* on the queue, but we need to clear everything in it before we3244* can exit.3245*/3246int err = 0;3247if (rwa->err == 0) {3248err = receive_process_record(rwa, rrd);3249} else if (rrd->abd != NULL) {3250abd_free(rrd->abd);3251rrd->abd = NULL;3252rrd->payload = NULL;3253} else if (rrd->payload != NULL) {3254kmem_free(rrd->payload, rrd->payload_size);3255rrd->payload = NULL;3256}3257/*3258* EAGAIN indicates that this record has been saved (on3259* raw->write_batch), and will be used again, so we don't3260* free it.3261* When healing data we always need to free the record.3262*/3263if (err != EAGAIN || rwa->heal) {3264if (rwa->err == 0)3265rwa->err = err;3266kmem_free(rrd, sizeof (*rrd));3267}3268}3269kmem_free(rrd, sizeof (*rrd));32703271if (rwa->heal) {3272zio_wait(rwa->heal_pio);3273} else {3274int err = flush_write_batch(rwa);3275if (rwa->err == 0)3276rwa->err = err;3277}3278mutex_enter(&rwa->mutex);3279rwa->done = B_TRUE;3280cv_signal(&rwa->cv);3281mutex_exit(&rwa->mutex);3282spl_fstrans_unmark(cookie);3283thread_exit();3284}32853286static int3287resume_check(dmu_recv_cookie_t *drc, nvlist_t *begin_nvl)3288{3289uint64_t val;3290objset_t *mos = dmu_objset_pool(drc->drc_os)->dp_meta_objset;3291uint64_t dsobj = dmu_objset_id(drc->drc_os);3292uint64_t resume_obj, resume_off;32933294if (nvlist_lookup_uint64(begin_nvl,3295"resume_object", &resume_obj) != 0 ||3296nvlist_lookup_uint64(begin_nvl,3297"resume_offset", &resume_off) != 0) {3298return (SET_ERROR(EINVAL));3299}3300VERIFY0(zap_lookup(mos, dsobj,3301DS_FIELD_RESUME_OBJECT, sizeof (val), 1, &val));3302if (resume_obj != val)3303return (SET_ERROR(EINVAL));3304VERIFY0(zap_lookup(mos, dsobj,3305DS_FIELD_RESUME_OFFSET, sizeof (val), 1, &val));3306if (resume_off != val)3307return (SET_ERROR(EINVAL));33083309return (0);3310}33113312/*3313* Read in the stream's records, one by one, and apply them to the pool. There3314* are two threads involved; the thread that calls this function will spin up a3315* worker thread, read the records off the stream one by one, and issue3316* prefetches for any necessary indirect blocks. It will then push the records3317* onto an internal blocking queue. The worker thread will pull the records off3318* the queue, and actually write the data into the DMU. This way, the worker3319* thread doesn't have to wait for reads to complete, since everything it needs3320* (the indirect blocks) will be prefetched.3321*3322* NB: callers *must* call dmu_recv_end() if this succeeds.3323*/3324int3325dmu_recv_stream(dmu_recv_cookie_t *drc, offset_t *voffp)3326{3327int err = 0;3328struct receive_writer_arg *rwa = kmem_zalloc(sizeof (*rwa), KM_SLEEP);33293330if (dsl_dataset_has_resume_receive_state(drc->drc_ds)) {3331uint64_t bytes = 0;3332(void) zap_lookup(drc->drc_ds->ds_dir->dd_pool->dp_meta_objset,3333drc->drc_ds->ds_object, DS_FIELD_RESUME_BYTES,3334sizeof (bytes), 1, &bytes);3335drc->drc_bytes_read += bytes;3336}33373338drc->drc_ignore_objlist = objlist_create();33393340/* these were verified in dmu_recv_begin */3341ASSERT3U(DMU_GET_STREAM_HDRTYPE(drc->drc_drrb->drr_versioninfo), ==,3342DMU_SUBSTREAM);3343ASSERT3U(drc->drc_drrb->drr_type, <, DMU_OST_NUMTYPES);33443345ASSERT(dsl_dataset_phys(drc->drc_ds)->ds_flags & DS_FLAG_INCONSISTENT);3346ASSERT0(drc->drc_os->os_encrypted &&3347(drc->drc_featureflags & DMU_BACKUP_FEATURE_EMBED_DATA));33483349/* handle DSL encryption key payload */3350if (drc->drc_featureflags & DMU_BACKUP_FEATURE_RAW) {3351nvlist_t *keynvl = NULL;33523353ASSERT(drc->drc_os->os_encrypted);3354ASSERT(drc->drc_raw);33553356err = nvlist_lookup_nvlist(drc->drc_begin_nvl, "crypt_keydata",3357&keynvl);3358if (err != 0)3359goto out;33603361if (!drc->drc_heal) {3362/*3363* If this is a new dataset we set the key immediately.3364* Otherwise we don't want to change the key until we3365* are sure the rest of the receive succeeded so we3366* stash the keynvl away until then.3367*/3368err = dsl_crypto_recv_raw(spa_name(drc->drc_os->os_spa),3369drc->drc_ds->ds_object, drc->drc_fromsnapobj,3370drc->drc_drrb->drr_type, keynvl, drc->drc_newfs);3371if (err != 0)3372goto out;3373}33743375/* see comment in dmu_recv_end_sync() */3376drc->drc_ivset_guid = 0;3377(void) nvlist_lookup_uint64(keynvl, "to_ivset_guid",3378&drc->drc_ivset_guid);33793380if (!drc->drc_newfs)3381drc->drc_keynvl = fnvlist_dup(keynvl);3382}33833384if (drc->drc_featureflags & DMU_BACKUP_FEATURE_RESUMING) {3385err = resume_check(drc, drc->drc_begin_nvl);3386if (err != 0)3387goto out;3388}33893390/*3391* For compatibility with recursive send streams, we do this here,3392* rather than in dmu_recv_begin. If we pull the next header too3393* early, and it's the END record, we break the `recv_skip` logic.3394*/3395if (drc->drc_drr_begin->drr_payloadlen == 0) {3396err = receive_read_payload_and_next_header(drc, 0, NULL);3397if (err != 0)3398goto out;3399}34003401/*3402* If we failed before this point we will clean up any new resume3403* state that was created. Now that we've gotten past the initial3404* checks we are ok to retain that resume state.3405*/3406drc->drc_should_save = B_TRUE;34073408(void) bqueue_init(&rwa->q, zfs_recv_queue_ff,3409MAX(zfs_recv_queue_length, 2 * zfs_max_recordsize),3410offsetof(struct receive_record_arg, node));3411cv_init(&rwa->cv, NULL, CV_DEFAULT, NULL);3412mutex_init(&rwa->mutex, NULL, MUTEX_DEFAULT, NULL);3413rwa->os = drc->drc_os;3414rwa->byteswap = drc->drc_byteswap;3415rwa->heal = drc->drc_heal;3416rwa->tofs = drc->drc_tofs;3417rwa->resumable = drc->drc_resumable;3418rwa->raw = drc->drc_raw;3419rwa->spill = drc->drc_spill;3420rwa->full = (drc->drc_drr_begin->drr_u.drr_begin.drr_fromguid == 0);3421rwa->os->os_raw_receive = drc->drc_raw;3422if (drc->drc_heal) {3423rwa->heal_pio = zio_root(drc->drc_os->os_spa, NULL, NULL,3424ZIO_FLAG_GODFATHER);3425}3426list_create(&rwa->write_batch, sizeof (struct receive_record_arg),3427offsetof(struct receive_record_arg, node.bqn_node));34283429(void) thread_create(NULL, 0, receive_writer_thread, rwa, 0, curproc,3430TS_RUN, minclsyspri);3431/*3432* We're reading rwa->err without locks, which is safe since we are the3433* only reader, and the worker thread is the only writer. It's ok if we3434* miss a write for an iteration or two of the loop, since the writer3435* thread will keep freeing records we send it until we send it an eos3436* marker.3437*3438* We can leave this loop in 3 ways: First, if rwa->err is3439* non-zero. In that case, the writer thread will free the rrd we just3440* pushed. Second, if we're interrupted; in that case, either it's the3441* first loop and drc->drc_rrd was never allocated, or it's later, and3442* drc->drc_rrd has been handed off to the writer thread who will free3443* it. Finally, if receive_read_record fails or we're at the end of the3444* stream, then we free drc->drc_rrd and exit.3445*/3446while (rwa->err == 0) {3447if (issig()) {3448err = SET_ERROR(EINTR);3449break;3450}34513452ASSERT0P(drc->drc_rrd);3453drc->drc_rrd = drc->drc_next_rrd;3454drc->drc_next_rrd = NULL;3455/* Allocates and loads header into drc->drc_next_rrd */3456err = receive_read_record(drc);34573458if (drc->drc_rrd->header.drr_type == DRR_END || err != 0) {3459kmem_free(drc->drc_rrd, sizeof (*drc->drc_rrd));3460drc->drc_rrd = NULL;3461break;3462}34633464bqueue_enqueue(&rwa->q, drc->drc_rrd,3465sizeof (struct receive_record_arg) +3466drc->drc_rrd->payload_size);3467drc->drc_rrd = NULL;3468}34693470ASSERT0P(drc->drc_rrd);3471drc->drc_rrd = kmem_zalloc(sizeof (*drc->drc_rrd), KM_SLEEP);3472drc->drc_rrd->eos_marker = B_TRUE;3473bqueue_enqueue_flush(&rwa->q, drc->drc_rrd, 1);34743475mutex_enter(&rwa->mutex);3476while (!rwa->done) {3477/*3478* We need to use cv_wait_sig() so that any process that may3479* be sleeping here can still fork.3480*/3481(void) cv_wait_sig(&rwa->cv, &rwa->mutex);3482}3483mutex_exit(&rwa->mutex);34843485/*3486* If we are receiving a full stream as a clone, all object IDs which3487* are greater than the maximum ID referenced in the stream are3488* by definition unused and must be freed.3489*/3490if (drc->drc_clone && drc->drc_drrb->drr_fromguid == 0) {3491uint64_t obj = rwa->max_object + 1;3492int free_err = 0;3493int next_err = 0;34943495while (next_err == 0) {3496free_err = dmu_free_long_object(rwa->os, obj);3497if (free_err != 0 && free_err != ENOENT)3498break;34993500next_err = dmu_object_next(rwa->os, &obj, FALSE, 0);3501}35023503if (err == 0) {3504if (free_err != 0 && free_err != ENOENT)3505err = free_err;3506else if (next_err != ESRCH)3507err = next_err;3508}3509}35103511cv_destroy(&rwa->cv);3512mutex_destroy(&rwa->mutex);3513bqueue_destroy(&rwa->q);3514list_destroy(&rwa->write_batch);3515if (err == 0)3516err = rwa->err;35173518out:3519/*3520* If we hit an error before we started the receive_writer_thread3521* we need to clean up the next_rrd we create by processing the3522* DRR_BEGIN record.3523*/3524if (drc->drc_next_rrd != NULL)3525kmem_free(drc->drc_next_rrd, sizeof (*drc->drc_next_rrd));35263527/*3528* The objset will be invalidated by dmu_recv_end() when we do3529* dsl_dataset_clone_swap_sync_impl().3530*/3531drc->drc_os = NULL;35323533kmem_free(rwa, sizeof (*rwa));3534nvlist_free(drc->drc_begin_nvl);35353536if (err != 0) {3537/*3538* Clean up references. If receive is not resumable,3539* destroy what we created, so we don't leave it in3540* the inconsistent state.3541*/3542dmu_recv_cleanup_ds(drc);3543nvlist_free(drc->drc_keynvl);3544crfree(drc->drc_cred);3545drc->drc_cred = NULL;3546}35473548objlist_destroy(drc->drc_ignore_objlist);3549drc->drc_ignore_objlist = NULL;3550*voffp = drc->drc_voff;3551return (err);3552}35533554static int3555dmu_recv_end_check(void *arg, dmu_tx_t *tx)3556{3557dmu_recv_cookie_t *drc = arg;3558dsl_pool_t *dp = dmu_tx_pool(tx);3559int error;35603561ASSERT3P(drc->drc_ds->ds_owner, ==, dmu_recv_tag);35623563if (drc->drc_heal) {3564error = 0;3565} else if (!drc->drc_newfs) {3566dsl_dataset_t *origin_head;35673568error = dsl_dataset_hold(dp, drc->drc_tofs, FTAG, &origin_head);3569if (error != 0)3570return (error);3571if (drc->drc_force) {3572/*3573* We will destroy any snapshots in tofs (i.e. before3574* origin_head) that are after the origin (which is3575* the snap before drc_ds, because drc_ds can not3576* have any snaps of its own).3577*/3578uint64_t obj;35793580obj = dsl_dataset_phys(origin_head)->ds_prev_snap_obj;3581while (obj !=3582dsl_dataset_phys(drc->drc_ds)->ds_prev_snap_obj) {3583dsl_dataset_t *snap;3584error = dsl_dataset_hold_obj(dp, obj, FTAG,3585&snap);3586if (error != 0)3587break;3588if (snap->ds_dir != origin_head->ds_dir)3589error = SET_ERROR(EINVAL);3590if (error == 0) {3591error = dsl_destroy_snapshot_check_impl(3592snap, B_FALSE);3593}3594obj = dsl_dataset_phys(snap)->ds_prev_snap_obj;3595dsl_dataset_rele(snap, FTAG);3596if (error != 0)3597break;3598}3599if (error != 0) {3600dsl_dataset_rele(origin_head, FTAG);3601return (error);3602}3603}3604if (drc->drc_keynvl != NULL) {3605error = dsl_crypto_recv_raw_key_check(drc->drc_ds,3606drc->drc_keynvl, tx);3607if (error != 0) {3608dsl_dataset_rele(origin_head, FTAG);3609return (error);3610}3611}36123613error = dsl_dataset_clone_swap_check_impl(drc->drc_ds,3614origin_head, drc->drc_force, drc->drc_owner, tx);3615if (error != 0) {3616dsl_dataset_rele(origin_head, FTAG);3617return (error);3618}3619error = dsl_dataset_snapshot_check_impl(origin_head,3620drc->drc_tosnap, tx, B_TRUE, 1, drc->drc_cred);3621dsl_dataset_rele(origin_head, FTAG);3622if (error != 0)3623return (error);36243625error = dsl_destroy_head_check_impl(drc->drc_ds, 1);3626} else {3627error = dsl_dataset_snapshot_check_impl(drc->drc_ds,3628drc->drc_tosnap, tx, B_TRUE, 1, drc->drc_cred);3629}3630return (error);3631}36323633static void3634dmu_recv_end_sync(void *arg, dmu_tx_t *tx)3635{3636dmu_recv_cookie_t *drc = arg;3637dsl_pool_t *dp = dmu_tx_pool(tx);3638boolean_t encrypted = drc->drc_ds->ds_dir->dd_crypto_obj != 0;3639uint64_t newsnapobj = 0;36403641spa_history_log_internal_ds(drc->drc_ds, "finish receiving",3642tx, "snap=%s", drc->drc_tosnap);3643drc->drc_ds->ds_objset->os_raw_receive = B_FALSE;36443645if (drc->drc_heal) {3646if (drc->drc_keynvl != NULL) {3647nvlist_free(drc->drc_keynvl);3648drc->drc_keynvl = NULL;3649}3650} else if (!drc->drc_newfs) {3651dsl_dataset_t *origin_head;36523653VERIFY0(dsl_dataset_hold(dp, drc->drc_tofs, FTAG,3654&origin_head));36553656if (drc->drc_force) {3657/*3658* Destroy any snapshots of drc_tofs (origin_head)3659* after the origin (the snap before drc_ds).3660*/3661uint64_t obj;36623663obj = dsl_dataset_phys(origin_head)->ds_prev_snap_obj;3664while (obj !=3665dsl_dataset_phys(drc->drc_ds)->ds_prev_snap_obj) {3666dsl_dataset_t *snap;3667VERIFY0(dsl_dataset_hold_obj(dp, obj, FTAG,3668&snap));3669ASSERT3P(snap->ds_dir, ==, origin_head->ds_dir);3670obj = dsl_dataset_phys(snap)->ds_prev_snap_obj;3671dsl_destroy_snapshot_sync_impl(snap,3672B_FALSE, tx);3673dsl_dataset_rele(snap, FTAG);3674}3675}3676if (drc->drc_keynvl != NULL) {3677dsl_crypto_recv_raw_key_sync(drc->drc_ds,3678drc->drc_keynvl, tx);3679nvlist_free(drc->drc_keynvl);3680drc->drc_keynvl = NULL;3681}36823683VERIFY3P(drc->drc_ds->ds_prev, ==,3684origin_head->ds_prev);36853686dsl_dataset_clone_swap_sync_impl(drc->drc_ds,3687origin_head, tx);3688/*3689* The objset was evicted by dsl_dataset_clone_swap_sync_impl,3690* so drc_os is no longer valid.3691*/3692drc->drc_os = NULL;36933694dsl_dataset_snapshot_sync_impl(origin_head,3695drc->drc_tosnap, tx);36963697/* set snapshot's creation time and guid */3698dmu_buf_will_dirty(origin_head->ds_prev->ds_dbuf, tx);3699dsl_dataset_phys(origin_head->ds_prev)->ds_creation_time =3700drc->drc_drrb->drr_creation_time;3701dsl_dataset_phys(origin_head->ds_prev)->ds_guid =3702drc->drc_drrb->drr_toguid;3703dsl_dataset_phys(origin_head->ds_prev)->ds_flags &=3704~DS_FLAG_INCONSISTENT;37053706dmu_buf_will_dirty(origin_head->ds_dbuf, tx);3707dsl_dataset_phys(origin_head)->ds_flags &=3708~DS_FLAG_INCONSISTENT;37093710newsnapobj =3711dsl_dataset_phys(origin_head)->ds_prev_snap_obj;37123713dsl_dataset_rele(origin_head, FTAG);3714dsl_destroy_head_sync_impl(drc->drc_ds, tx);37153716if (drc->drc_owner != NULL)3717VERIFY3P(origin_head->ds_owner, ==, drc->drc_owner);3718} else {3719dsl_dataset_t *ds = drc->drc_ds;37203721dsl_dataset_snapshot_sync_impl(ds, drc->drc_tosnap, tx);37223723/* set snapshot's creation time and guid */3724dmu_buf_will_dirty(ds->ds_prev->ds_dbuf, tx);3725dsl_dataset_phys(ds->ds_prev)->ds_creation_time =3726drc->drc_drrb->drr_creation_time;3727dsl_dataset_phys(ds->ds_prev)->ds_guid =3728drc->drc_drrb->drr_toguid;3729dsl_dataset_phys(ds->ds_prev)->ds_flags &=3730~DS_FLAG_INCONSISTENT;37313732dmu_buf_will_dirty(ds->ds_dbuf, tx);3733dsl_dataset_phys(ds)->ds_flags &= ~DS_FLAG_INCONSISTENT;3734if (dsl_dataset_has_resume_receive_state(ds)) {3735(void) zap_remove(dp->dp_meta_objset, ds->ds_object,3736DS_FIELD_RESUME_FROMGUID, tx);3737(void) zap_remove(dp->dp_meta_objset, ds->ds_object,3738DS_FIELD_RESUME_OBJECT, tx);3739(void) zap_remove(dp->dp_meta_objset, ds->ds_object,3740DS_FIELD_RESUME_OFFSET, tx);3741(void) zap_remove(dp->dp_meta_objset, ds->ds_object,3742DS_FIELD_RESUME_BYTES, tx);3743(void) zap_remove(dp->dp_meta_objset, ds->ds_object,3744DS_FIELD_RESUME_TOGUID, tx);3745(void) zap_remove(dp->dp_meta_objset, ds->ds_object,3746DS_FIELD_RESUME_TONAME, tx);3747(void) zap_remove(dp->dp_meta_objset, ds->ds_object,3748DS_FIELD_RESUME_REDACT_BOOKMARK_SNAPS, tx);3749}3750newsnapobj =3751dsl_dataset_phys(drc->drc_ds)->ds_prev_snap_obj;3752}37533754/*3755* If this is a raw receive, the crypt_keydata nvlist will include3756* a to_ivset_guid for us to set on the new snapshot. This value3757* will override the value generated by the snapshot code. However,3758* this value may not be present, because older implementations of3759* the raw send code did not include this value, and we are still3760* allowed to receive them if the zfs_disable_ivset_guid_check3761* tunable is set, in which case we will leave the newly-generated3762* value.3763*/3764if (!drc->drc_heal && drc->drc_raw && drc->drc_ivset_guid != 0) {3765dmu_object_zapify(dp->dp_meta_objset, newsnapobj,3766DMU_OT_DSL_DATASET, tx);3767VERIFY0(zap_update(dp->dp_meta_objset, newsnapobj,3768DS_FIELD_IVSET_GUID, sizeof (uint64_t), 1,3769&drc->drc_ivset_guid, tx));3770}37713772/*3773* Release the hold from dmu_recv_begin. This must be done before3774* we return to open context, so that when we free the dataset's dnode3775* we can evict its bonus buffer. Since the dataset may be destroyed3776* at this point (and therefore won't have a valid pointer to the spa)3777* we release the key mapping manually here while we do have a valid3778* pointer, if it exists.3779*/3780if (!drc->drc_raw && encrypted) {3781(void) spa_keystore_remove_mapping(dmu_tx_pool(tx)->dp_spa,3782drc->drc_ds->ds_object, drc->drc_ds);3783}3784dsl_dataset_disown(drc->drc_ds, 0, dmu_recv_tag);3785drc->drc_ds = NULL;3786}37873788static int dmu_recv_end_modified_blocks = 3;37893790static int3791dmu_recv_existing_end(dmu_recv_cookie_t *drc)3792{3793#ifdef _KERNEL3794/*3795* We will be destroying the ds; make sure its origin is unmounted if3796* necessary.3797*/3798char name[ZFS_MAX_DATASET_NAME_LEN];3799dsl_dataset_name(drc->drc_ds, name);3800zfs_destroy_unmount_origin(name);3801#endif38023803return (dsl_sync_task(drc->drc_tofs,3804dmu_recv_end_check, dmu_recv_end_sync, drc,3805dmu_recv_end_modified_blocks, ZFS_SPACE_CHECK_NORMAL));3806}38073808static int3809dmu_recv_new_end(dmu_recv_cookie_t *drc)3810{3811return (dsl_sync_task(drc->drc_tofs,3812dmu_recv_end_check, dmu_recv_end_sync, drc,3813dmu_recv_end_modified_blocks, ZFS_SPACE_CHECK_NORMAL));3814}38153816int3817dmu_recv_end(dmu_recv_cookie_t *drc, void *owner)3818{3819int error;38203821drc->drc_owner = owner;38223823if (drc->drc_newfs)3824error = dmu_recv_new_end(drc);3825else3826error = dmu_recv_existing_end(drc);38273828if (error != 0) {3829dmu_recv_cleanup_ds(drc);3830nvlist_free(drc->drc_keynvl);3831} else if (!drc->drc_heal) {3832if (drc->drc_newfs) {3833zvol_create_minors(drc->drc_tofs);3834}3835char *snapname = kmem_asprintf("%s@%s",3836drc->drc_tofs, drc->drc_tosnap);3837zvol_create_minors(snapname);3838kmem_strfree(snapname);3839}38403841crfree(drc->drc_cred);3842drc->drc_cred = NULL;38433844return (error);3845}38463847/*3848* Return TRUE if this objset is currently being received into.3849*/3850boolean_t3851dmu_objset_is_receiving(objset_t *os)3852{3853return (os->os_dsl_dataset != NULL &&3854os->os_dsl_dataset->ds_owner == dmu_recv_tag);3855}38563857ZFS_MODULE_PARAM(zfs_recv, zfs_recv_, queue_length, UINT, ZMOD_RW,3858"Maximum receive queue length");38593860ZFS_MODULE_PARAM(zfs_recv, zfs_recv_, queue_ff, UINT, ZMOD_RW,3861"Receive queue fill fraction");38623863ZFS_MODULE_PARAM(zfs_recv, zfs_recv_, write_batch_size, UINT, ZMOD_RW,3864"Maximum amount of writes to batch into one transaction");38653866ZFS_MODULE_PARAM(zfs_recv, zfs_recv_, best_effort_corrective, INT, ZMOD_RW,3867"Ignore errors during corrective receive");386838693870