<commit_before>/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#include <sys/dmu.h>
#include <sys/dmu_impl.h>
#include <sys/dmu_tx.h>
#include <sys/dbuf.h>
#include <sys/dnode.h>
#include <sys/zfs_context.h>
#include <sys/dmu_objset.h>
#include <sys/dmu_traverse.h>
#include <sys/dsl_dataset.h>
#include <sys/dsl_dir.h>
#include <sys/dsl_pool.h>
#include <sys/dsl_synctask.h>
#include <sys/zfs_ioctl.h>
#include <sys/zap.h>
#include <sys/zio_checksum.h>

static char *dmu_recv_tag = "dmu_recv_tag";

struct backuparg {
	dmu_replay_record_t *drr;
	kthread_t *td;
	struct file *fp;
	offset_t *off;
	objset_t *os;
	zio_cksum_t zc;
	int err;
};

static int
dump_bytes(struct backuparg *ba, void *buf, int len)
{
	struct uio auio;
	struct iovec aiov;

	ASSERT3U(len % 8, ==, 0);

	fletcher_4_incremental_native(buf, len, &ba->zc);

	aiov.iov_base = buf;
	aiov.iov_len = len;
	auio.uio_iov = &aiov;
	auio.uio_iovcnt = 1;
	auio.uio_resid = len;
	auio.uio_segflg = UIO_SYSSPACE;
	auio.uio_rw = UIO_WRITE;
	auio.uio_offset = (off_t)-1;
	auio.uio_td = ba->td;
#ifdef _KERNEL
	if (ba->fp->f_type == DTYPE_VNODE)
		bwillwrite();
	ba->err = fo_write(ba->fp, &auio, ba->td->td_ucred, 0, ba->td);
#else
	fprintf(stderr, "%s: returning EOPNOTSUPP\n", __func__);
	ba->err = EOPNOTSUPP;
#endif
	*ba->off += len;

	return (ba->err);
}

static int
dump_free(struct backuparg *ba, uint64_t object, uint64_t offset,
    uint64_t length)
{
	/* write a FREE record */
	bzero(ba->drr, sizeof (dmu_replay_record_t));
	ba->drr->drr_type = DRR_FREE;
	ba->drr->drr_u.drr_free.drr_object = object;
	ba->drr->drr_u.drr_free.drr_offset = offset;
	ba->drr->drr_u.drr_free.drr_length = length;

	if (dump_bytes(ba, ba->drr, sizeof (dmu_replay_record_t)))
		return (EINTR);
	return (0);
}

static int
dump_data(struct backuparg *ba, dmu_object_type_t type,
    uint64_t object, uint64_t offset, int blksz, void *data)
{
	/* write a DATA record */
	bzero(ba->drr, sizeof (dmu_replay_record_t));
	ba->drr->drr_type = DRR_WRITE;
	ba->drr->drr_u.drr_write.drr_object = object;
	ba->drr->drr_u.drr_write.drr_type = type;
	ba->drr->drr_u.drr_write.drr_offset = offset;
	ba->drr->drr_u.drr_write.drr_length = blksz;

	if (dump_bytes(ba, ba->drr, sizeof (dmu_replay_record_t)))
		return (EINTR);
	if (dump_bytes(ba, data, blksz))
		return (EINTR);
	return (0);
}

static int
dump_freeobjects(struct backuparg *ba, uint64_t firstobj, uint64_t numobjs)
{
	/* write a FREEOBJECTS record */
	bzero(ba->drr, sizeof (dmu_replay_record_t));
	ba->drr->drr_type = DRR_FREEOBJECTS;
	ba->drr->drr_u.drr_freeobjects.drr_firstobj = firstobj;
	ba->drr->drr_u.drr_freeobjects.drr_numobjs = numobjs;

	if (dump_bytes(ba, ba->drr, sizeof (dmu_replay_record_t)))
		return (EINTR);
	return (0);
}

static int
dump_dnode(struct backuparg *ba, uint64_t object, dnode_phys_t *dnp)
{
	if (dnp == NULL || dnp->dn_type == DMU_OT_NONE)
		return (dump_freeobjects(ba, object, 1));

	/* write an OBJECT record */
	bzero(ba->drr, sizeof (dmu_replay_record_t));
	ba->drr->drr_type = DRR_OBJECT;
	ba->drr->drr_u.drr_object.drr_object = object;
	ba->drr->drr_u.drr_object.drr_type = dnp->dn_type;
	ba->drr->drr_u.drr_object.drr_bonustype = dnp->dn_bonustype;
	ba->drr->drr_u.drr_object.drr_blksz =
	    dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT;
	ba->drr->drr_u.drr_object.drr_bonuslen = dnp->dn_bonuslen;
	ba->drr->drr_u.drr_object.drr_checksum = dnp->dn_checksum;
	ba->drr->drr_u.drr_object.drr_compress = dnp->dn_compress;

	if (dump_bytes(ba, ba->drr, sizeof (dmu_replay_record_t)))
		return (EINTR);

	if (dump_bytes(ba, DN_BONUS(dnp), P2ROUNDUP(dnp->dn_bonuslen, 8)))
		return (EINTR);

	/* free anything past the end of the file */
	if (dump_free(ba, object, (dnp->dn_maxblkid + 1) *
	    (dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT), -1ULL))
		return (EINTR);
	if (ba->err)
		return (EINTR);
	return (0);
}

#define	BP_SPAN(dnp, level) \
	(((uint64_t)dnp->dn_datablkszsec) << (SPA_MINBLOCKSHIFT + \
	(level) * (dnp->dn_indblkshift - SPA_BLKPTRSHIFT)))

static int
backup_cb(traverse_blk_cache_t *bc, spa_t *spa, void *arg)
{
	struct backuparg *ba = arg;
	uint64_t object = bc->bc_bookmark.zb_object;
	int level = bc->bc_bookmark.zb_level;
	uint64_t blkid = bc->bc_bookmark.zb_blkid;
	blkptr_t *bp = bc->bc_blkptr.blk_birth ? &bc->bc_blkptr : NULL;
	dmu_object_type_t type = bp ? BP_GET_TYPE(bp) : DMU_OT_NONE;
	void *data = bc->bc_data;
	int err = 0;

	if (issig(JUSTLOOKING) && issig(FORREAL))
		return (EINTR);

	ASSERT(data || bp == NULL);

	if (bp == NULL && object == 0) {
		uint64_t span = BP_SPAN(bc->bc_dnode, level);
		uint64_t dnobj = (blkid * span) >> DNODE_SHIFT;
		err = dump_freeobjects(ba, dnobj, span >> DNODE_SHIFT);
	} else if (bp == NULL) {
		uint64_t span = BP_SPAN(bc->bc_dnode, level);
		err = dump_free(ba, object, blkid * span, span);
	} else if (data && level == 0 && type == DMU_OT_DNODE) {
		dnode_phys_t *blk = data;
		int i;
		int blksz = BP_GET_LSIZE(bp);

		for (i = 0; i < blksz >> DNODE_SHIFT; i++) {
			uint64_t dnobj =
			    (blkid << (DNODE_BLOCK_SHIFT - DNODE_SHIFT)) + i;
			err = dump_dnode(ba, dnobj, blk+i);
			if (err)
				break;
		}
	} else if (level == 0 &&
	    type != DMU_OT_DNODE && type != DMU_OT_OBJSET) {
		int blksz = BP_GET_LSIZE(bp);
		if (data == NULL) {
			uint32_t aflags = ARC_WAIT;
			arc_buf_t *abuf;
			zbookmark_t zb;

			zb.zb_objset = ba->os->os->os_dsl_dataset->ds_object;
			zb.zb_object = object;
			zb.zb_level = level;
			zb.zb_blkid = blkid;
			(void) arc_read_nolock(NULL, spa, bp,
			    arc_getbuf_func, &abuf, ZIO_PRIORITY_ASYNC_READ,
			    ZIO_FLAG_MUSTSUCCEED, &aflags, &zb);

			if (abuf) {
				err = dump_data(ba, type, object, blkid * blksz,
				    blksz, abuf->b_data);
				(void) arc_buf_remove_ref(abuf, &abuf);
			}
		} else {
			err = dump_data(ba, type, object, blkid * blksz,
			    blksz, data);
		}
	}

	ASSERT(err == 0 || err == EINTR);
	return (err);
}

int
dmu_sendbackup(objset_t *tosnap, objset_t *fromsnap, boolean_t fromorigin,
    struct file *fp, offset_t *off)
{
	dsl_dataset_t *ds = tosnap->os->os_dsl_dataset;
	dsl_dataset_t *fromds = fromsnap ? fromsnap->os->os_dsl_dataset : NULL;
	dmu_replay_record_t *drr;
	struct backuparg ba;
	int err;
	uint64_t fromtxg = 0;

	/* tosnap must be a snapshot */
	if (ds->ds_phys->ds_next_snap_obj == 0)
		return (EINVAL);

	/* fromsnap must be an earlier snapshot from the same fs as tosnap */
	if (fromds && (ds->ds_dir != fromds->ds_dir ||
	    fromds->ds_phys->ds_creation_txg >= ds->ds_phys->ds_creation_txg))
		return (EXDEV);

	if (fromorigin) {
		dsl_pool_t *dp = ds->ds_dir->dd_pool;

		if (fromsnap)
			return (EINVAL);

		if (dsl_dir_is_clone(ds->ds_dir)) {
			rw_enter(&dp->dp_config_rwlock, RW_READER);
			err = dsl_dataset_hold_obj(dp,
			    ds->ds_dir->dd_phys->dd_origin_obj, FTAG, &fromds);
			rw_exit(&dp->dp_config_rwlock);
			if (err)
				return (err);
		} else {
			fromorigin = B_FALSE;
		}
	}


	drr = kmem_zalloc(sizeof (dmu_replay_record_t), KM_SLEEP);
	drr->drr_type = DRR_BEGIN;
	drr->drr_u.drr_begin.drr_magic = DMU_BACKUP_MAGIC;
	drr->drr_u.drr_begin.drr_version = DMU_BACKUP_STREAM_VERSION;
	drr->drr_u.drr_begin.drr_creation_time =
	    ds->ds_phys->ds_creation_time;
	drr->drr_u.drr_begin.drr_type = tosnap->os->os_phys->os_type;
	if (fromorigin)
		drr->drr_u.drr_begin.drr_flags |= DRR_FLAG_CLONE;
	drr->drr_u.drr_begin.drr_toguid = ds->ds_phys->ds_guid;
	if (ds->ds_phys->ds_flags & DS_FLAG_CI_DATASET)
		drr->drr_u.drr_begin.drr_flags |= DRR_FLAG_CI_DATA;

	if (fromds)
		drr->drr_u.drr_begin.drr_fromguid = fromds->ds_phys->ds_guid;
	dsl_dataset_name(ds, drr->drr_u.drr_begin.drr_toname);

	if (fromds)
		fromtxg = fromds->ds_phys->ds_creation_txg;
	if (fromorigin)
		dsl_dataset_rele(fromds, FTAG);

	ba.drr = drr;
	ba.td = curthread;
	ba.fp = fp;
	ba.os = tosnap;
	ba.off = off;
	ZIO_SET_CHECKSUM(&ba.zc, 0, 0, 0, 0);

	if (dump_bytes(&ba, drr, sizeof (dmu_replay_record_t))) {
		kmem_free(drr, sizeof (dmu_replay_record_t));
		return (ba.err);
	}

	err = traverse_dsl_dataset(ds, fromtxg,
	    ADVANCE_PRE | ADVANCE_HOLES | ADVANCE_DATA | ADVANCE_NOLOCK,
	    backup_cb, &ba);

	if (err) {
		if (err == EINTR && ba.err)
			err = ba.err;
		kmem_free(drr, sizeof (dmu_replay_record_t));
		return (err);
	}

	bzero(drr, sizeof (dmu_replay_record_t));
	drr->drr_type = DRR_END;
	drr->drr_u.drr_end.drr_checksum = ba.zc;

	if (dump_bytes(&ba, drr, sizeof (dmu_replay_record_t))) {
		kmem_free(drr, sizeof (dmu_replay_record_t));
		return (ba.err);
	}

	kmem_free(drr, sizeof (dmu_replay_record_t));

	return (0);
}

struct recvbeginsyncarg {
	const char *tofs;
	const char *tosnap;
	dsl_dataset_t *origin;
	uint64_t fromguid;
	dmu_objset_type_t type;
	void *tag;
	boolean_t force;
	uint64_t dsflags;
	char clonelastname[MAXNAMELEN];
	dsl_dataset_t *ds; /* the ds to recv into; returned from the syncfunc */
};

static dsl_dataset_t *
recv_full_sync_impl(dsl_pool_t *dp, uint64_t dsobj, dmu_objset_type_t type,
    cred_t *cr, dmu_tx_t *tx)
{
	dsl_dataset_t *ds;

	/* This should always work, since we just created it */
	/* XXX - create should return an owned ds */
	VERIFY(0 == dsl_dataset_own_obj(dp, dsobj,
	    DS_MODE_INCONSISTENT, dmu_recv_tag, &ds));

	if (type != DMU_OST_NONE) {
		(void) dmu_objset_create_impl(dp->dp_spa,
		    ds, &ds->ds_phys->ds_bp, type, tx);
	}

	spa_history_internal_log(LOG_DS_REPLAY_FULL_SYNC,
	    dp->dp_spa, tx, cr, "dataset = %lld", dsobj);

	return (ds);
}

/* ARGSUSED */
static int
recv_full_check(void *arg1, void *arg2, dmu_tx_t *tx)
{
	dsl_dir_t *dd = arg1;
	struct recvbeginsyncarg *rbsa = arg2;
	objset_t *mos = dd->dd_pool->dp_meta_objset;
	uint64_t val;
	int err;

	err = zap_lookup(mos, dd->dd_phys->dd_child_dir_zapobj,
	    strrchr(rbsa->tofs, '/') + 1, sizeof (uint64_t), 1, &val);

	if (err != ENOENT)
		return (err ? err : EEXIST);

	if (rbsa->origin) {
		/* make sure it's a snap in the same pool */
		if (rbsa->origin->ds_dir->dd_pool != dd->dd_pool)
			return (EXDEV);
		if (rbsa->origin->ds_phys->ds_num_children == 0)
			return (EINVAL);
		if (rbsa->origin->ds_phys->ds_guid != rbsa->fromguid)
			return (ENODEV);
	}

	return (0);
}

static void
recv_full_sync(void *arg1, void *arg2, cred_t *cr, dmu_tx_t *tx)
{
	dsl_dir_t *dd = arg1;
	struct recvbeginsyncarg *rbsa = arg2;
	uint64_t flags = DS_FLAG_INCONSISTENT | rbsa->dsflags;
	uint64_t dsobj;

	dsobj = dsl_dataset_create_sync(dd, strrchr(rbsa->tofs, '/') + 1,
	    rbsa->origin, flags, cr, tx);

	rbsa->ds = recv_full_sync_impl(dd->dd_pool, dsobj,
	    rbsa->origin ? DMU_OST_NONE : rbsa->type, cr, tx);
}

static int
recv_full_existing_check(void *arg1, void *arg2, dmu_tx_t *tx)
{
	dsl_dataset_t *ds = arg1;
	struct recvbeginsyncarg *rbsa = arg2;
	int err;

	/* must be a head ds */
	if (ds->ds_phys->ds_next_snap_obj != 0)
		return (EINVAL);

	/* must not be a clone ds */
	if (dsl_dir_is_clone(ds->ds_dir))
		return (EINVAL);

	err = dsl_dataset_destroy_check(ds, rbsa->tag, tx);
	if (err)
		return (err);

	if (rbsa->origin) {
		/* make sure it's a snap in the same pool */
		if (rbsa->origin->ds_dir->dd_pool != ds->ds_dir->dd_pool)
			return (EXDEV);
		if (rbsa->origin->ds_phys->ds_num_children == 0)
			return (EINVAL);
		if (rbsa->origin->ds_phys->ds_guid != rbsa->fromguid)
			return (ENODEV);
	}

	return (0);
}

static void
recv_full_existing_sync(void *arg1, void *arg2, cred_t *cr, dmu_tx_t *tx)
{
	dsl_dataset_t *ds = arg1;
	struct recvbeginsyncarg *rbsa = arg2;
	dsl_dir_t *dd = ds->ds_dir;
	uint64_t flags = DS_FLAG_INCONSISTENT | rbsa->dsflags;
	uint64_t dsobj;

	/*
	 * NB: caller must provide an extra hold on the dsl_dir_t, so it
	 * won't go away when dsl_dataset_destroy_sync() closes the
	 * dataset.
	 */
	dsl_dataset_destroy_sync(ds, rbsa->tag, cr, tx);

	dsobj = dsl_dataset_create_sync_dd(dd, rbsa->origin, flags, tx);

	rbsa->ds = recv_full_sync_impl(dd->dd_pool, dsobj,
	    rbsa->origin ? DMU_OST_NONE : rbsa->type, cr, tx);
}

/* ARGSUSED */
static int
recv_incremental_check(void *arg1, void *arg2, dmu_tx_t *tx)
{
	dsl_dataset_t *ds = arg1;
	struct recvbeginsyncarg *rbsa = arg2;
	int err;
	uint64_t val;

	/* must not have any changes since most recent snapshot */
	if (!rbsa->force && dsl_dataset_modified_since_lastsnap(ds))
		return (ETXTBSY);

	/* must already be a snapshot of this fs */
	if (ds->ds_phys->ds_prev_snap_obj == 0)
		return (ENODEV);

	/* most recent snapshot must match fromguid */
	if (ds->ds_prev->ds_phys->ds_guid != rbsa->fromguid)
		return (ENODEV);

	/* temporary clone name must not exist */
	err = zap_lookup(ds->ds_dir->dd_pool->dp_meta_objset,
	    ds->ds_dir->dd_phys->dd_child_dir_zapobj,
	    rbsa->clonelastname, 8, 1, &val);
	if (err == 0)
		return (EEXIST);
	if (err != ENOENT)
		return (err);

	/* new snapshot name must not exist */
	err = zap_lookup(ds->ds_dir->dd_pool->dp_meta_objset,
	    ds->ds_phys->ds_snapnames_zapobj, rbsa->tosnap, 8, 1, &val);
	if (err == 0)
		return (EEXIST);
	if (err != ENOENT)
		return (err);
	return (0);
}

/* ARGSUSED */
static void
recv_online_incremental_sync(void *arg1, void *arg2, cred_t *cr, dmu_tx_t *tx)
{
	dsl_dataset_t *ohds = arg1;
	struct recvbeginsyncarg *rbsa = arg2;
	dsl_pool_t *dp = ohds->ds_dir->dd_pool;
	dsl_dataset_t *ods, *cds;
	uint64_t flags = DS_FLAG_INCONSISTENT | rbsa->dsflags;
	uint64_t dsobj;

	/* create the temporary clone */
	VERIFY(0 == dsl_dataset_hold_obj(dp, ohds->ds_phys->ds_prev_snap_obj,
	    FTAG, &ods));
	dsobj = dsl_dataset_create_sync(ohds->ds_dir,
	    rbsa->clonelastname, ods, flags, cr, tx);
	dsl_dataset_rele(ods, FTAG);

	/* open the temporary clone */
	VERIFY(0 == dsl_dataset_own_obj(dp, dsobj,
	    DS_MODE_INCONSISTENT, dmu_recv_tag, &cds));

	/* copy the refquota from the target fs to the clone */
	if (ohds->ds_quota > 0)
		dsl_dataset_set_quota_sync(cds, &ohds->ds_quota, cr, tx);

	rbsa->ds = cds;

	spa_history_internal_log(LOG_DS_REPLAY_INC_SYNC,
	    dp->dp_spa, tx, cr, "dataset = %lld", dsobj);
}

/* ARGSUSED */
static void
recv_offline_incremental_sync(void *arg1, void *arg2, cred_t *cr, dmu_tx_t *tx)
{
	dsl_dataset_t *ds = arg1;

	dmu_buf_will_dirty(ds->ds_dbuf, tx);
	ds->ds_phys->ds_flags |= DS_FLAG_INCONSISTENT;

	spa_history_internal_log(LOG_DS_REPLAY_INC_SYNC,
	    ds->ds_dir->dd_pool->dp_spa, tx, cr, "dataset = %lld",
	    ds->ds_object);
}

/*
 * NB: callers *MUST* call dmu_recv_stream() if dmu_recv_begin()
 * succeeds; otherwise we will leak the holds on the datasets.
 */
int
dmu_recv_begin(char *tofs, char *tosnap, struct drr_begin *drrb,
    boolean_t force, objset_t *origin, boolean_t online, dmu_recv_cookie_t *drc)
{
	int err = 0;
	boolean_t byteswap;
	struct recvbeginsyncarg rbsa;
	uint64_t version;
	int flags;
	dsl_dataset_t *ds;

	if (drrb->drr_magic == DMU_BACKUP_MAGIC)
		byteswap = FALSE;
	else if (drrb->drr_magic == BSWAP_64(DMU_BACKUP_MAGIC))
		byteswap = TRUE;
	else
		return (EINVAL);

	rbsa.tofs = tofs;
	rbsa.tosnap = tosnap;
	rbsa.origin = origin ? origin->os->os_dsl_dataset : NULL;
	rbsa.fromguid = drrb->drr_fromguid;
	rbsa.type = drrb->drr_type;
	rbsa.tag = FTAG;
	rbsa.dsflags = 0;
	version = drrb->drr_version;
	flags = drrb->drr_flags;

	if (byteswap) {
		rbsa.type = BSWAP_32(rbsa.type);
		rbsa.fromguid = BSWAP_64(rbsa.fromguid);
		version = BSWAP_64(version);
		flags = BSWAP_32(flags);
	}

	if (version != DMU_BACKUP_STREAM_VERSION ||
	    rbsa.type >= DMU_OST_NUMTYPES ||
	    ((flags & DRR_FLAG_CLONE) && origin == NULL))
		return (EINVAL);

	if (flags & DRR_FLAG_CI_DATA)
		rbsa.dsflags = DS_FLAG_CI_DATASET;

	bzero(drc, sizeof (dmu_recv_cookie_t));
	drc->drc_drrb = drrb;
	drc->drc_tosnap = tosnap;
	drc->drc_force = force;

	/*
	 * Process the begin in syncing context.
	 */
	if (rbsa.fromguid && !(flags & DRR_FLAG_CLONE) && !online) {
		/* offline incremental receive */
		err = dsl_dataset_own(tofs, 0, dmu_recv_tag, &ds);
		if (err)
			return (err);

		/*
		 * Only do the rollback if the most recent snapshot
		 * matches the incremental source
		 */
		if (force) {
			if (ds->ds_prev == NULL ||
			    ds->ds_prev->ds_phys->ds_guid !=
			    rbsa.fromguid) {
				dsl_dataset_disown(ds, dmu_recv_tag);
				return (ENODEV);
			}
			(void) dsl_dataset_rollback(ds, DMU_OST_NONE);
		}
		rbsa.force = B_FALSE;
		err = dsl_sync_task_do(ds->ds_dir->dd_pool,
		    recv_incremental_check,
		    recv_offline_incremental_sync, ds, &rbsa, 1);
		if (err) {
			dsl_dataset_disown(ds, dmu_recv_tag);
			return (err);
		}
		drc->drc_logical_ds = drc->drc_real_ds = ds;
	} else if (rbsa.fromguid && !(flags & DRR_FLAG_CLONE)) {
		/* online incremental receive */

		/* tmp clone name is: tofs/%tosnap" */
		(void) snprintf(rbsa.clonelastname, sizeof (rbsa.clonelastname),
		    "%%%s", tosnap);

		/* open the dataset we are logically receiving into */
		err = dsl_dataset_hold(tofs, dmu_recv_tag, &ds);
		if (err)
			return (err);

		rbsa.force = force;
		err = dsl_sync_task_do(ds->ds_dir->dd_pool,
		    recv_incremental_check,
		    recv_online_incremental_sync, ds, &rbsa, 5);
		if (err) {
			dsl_dataset_rele(ds, dmu_recv_tag);
			return (err);
		}
		drc->drc_logical_ds = ds;
		drc->drc_real_ds = rbsa.ds;
	} else {
		/* create new fs -- full backup or clone */
		dsl_dir_t *dd = NULL;
		const char *tail;

		err = dsl_dir_open(tofs, FTAG, &dd, &tail);
		if (err)
			return (err);
		if (tail == NULL) {
			if (!force) {
				dsl_dir_close(dd, FTAG);
				return (EEXIST);
			}

			rw_enter(&dd->dd_pool->dp_config_rwlock, RW_READER);
			err = dsl_dataset_own_obj(dd->dd_pool,
			    dd->dd_phys->dd_head_dataset_obj,
			    DS_MODE_INCONSISTENT, FTAG, &ds);
			rw_exit(&dd->dd_pool->dp_config_rwlock);
			if (err) {
				dsl_dir_close(dd, FTAG);
				return (err);
			}

			dsl_dataset_make_exclusive(ds, FTAG);
			err = dsl_sync_task_do(dd->dd_pool,
			    recv_full_existing_check,
			    recv_full_existing_sync, ds, &rbsa, 5);
			dsl_dataset_disown(ds, FTAG);
		} else {
			err = dsl_sync_task_do(dd->dd_pool, recv_full_check,
			    recv_full_sync, dd, &rbsa, 5);
		}
		dsl_dir_close(dd, FTAG);
		if (err)
			return (err);
		drc->drc_logical_ds = drc->drc_real_ds = rbsa.ds;
		drc->drc_newfs = B_TRUE;
	}

	return (0);
}

struct restorearg {
	int err;
	int byteswap;
	kthread_t *td;
	struct file *fp;
	char *buf;
	uint64_t voff;
	int bufsize; /* amount of memory allocated for buf */
	zio_cksum_t cksum;
};

static int
restore_bytes(struct restorearg *ra, void *buf, int len, off_t off, int *resid)
{
	struct uio auio;
	struct iovec aiov;
	int error;

	aiov.iov_base = buf;
	aiov.iov_len = len;
	auio.uio_iov = &aiov;
	auio.uio_iovcnt = 1;
	auio.uio_resid = len;
	auio.uio_segflg = UIO_SYSSPACE;
	auio.uio_rw = UIO_READ;
	auio.uio_offset = off;
	auio.uio_td = ra->td;
#ifdef _KERNEL
	error = fo_read(ra->fp, &auio, ra->td->td_ucred, FOF_OFFSET, ra->td);
#else
	fprintf(stderr, "%s: returning EOPNOTSUPP\n", __func__);
	error = EOPNOTSUPP;
#endif
	*resid = auio.uio_resid;
	return (error);
}

static void *
restore_read(struct restorearg *ra, int len)
{
	void *rv;
	int done = 0;

	/* some things will require 8-byte alignment, so everything must */
	ASSERT3U(len % 8, ==, 0);

	while (done < len) {
		int resid;

		ra->err = restore_bytes(ra, (caddr_t)ra->buf + done,
		    len - done, ra->voff, &resid);

		if (resid == len - done)
			ra->err = EINVAL;
		ra->voff += len - done - resid;
		done = len - resid;
		if (ra->err)
			return (NULL);
	}

	ASSERT3U(done, ==, len);
	rv = ra->buf;
	if (ra->byteswap)
		fletcher_4_incremental_byteswap(rv, len, &ra->cksum);
	else
		fletcher_4_incremental_native(rv, len, &ra->cksum);
	return (rv);
}

static void
backup_byteswap(dmu_replay_record_t *drr)
{
#define	DO64(X) (drr->drr_u.X = BSWAP_64(drr->drr_u.X))
#define	DO32(X) (drr->drr_u.X = BSWAP_32(drr->drr_u.X))
	drr->drr_type = BSWAP_32(drr->drr_type);
	drr->drr_payloadlen = BSWAP_32(drr->drr_payloadlen);
	switch (drr->drr_type) {
	case DRR_BEGIN:
		DO64(drr_begin.drr_magic);
		DO64(drr_begin.drr_version);
		DO64(drr_begin.drr_creation_time);
		DO32(drr_begin.drr_type);
		DO32(drr_begin.drr_flags);
		DO64(drr_begin.drr_toguid);
		DO64(drr_begin.drr_fromguid);
		break;
	case DRR_OBJECT:
		DO64(drr_object.drr_object);
		/* DO64(drr_object.drr_allocation_txg); */
		DO32(drr_object.drr_type);
		DO32(drr_object.drr_bonustype);
		DO32(drr_object.drr_blksz);
		DO32(drr_object.drr_bonuslen);
		break;
	case DRR_FREEOBJECTS:
		DO64(drr_freeobjects.drr_firstobj);
		DO64(drr_freeobjects.drr_numobjs);
		break;
	case DRR_WRITE:
		DO64(drr_write.drr_object);
		DO32(drr_write.drr_type);
		DO64(drr_write.drr_offset);
		DO64(drr_write.drr_length);
		break;
	case DRR_FREE:
		DO64(drr_free.drr_object);
		DO64(drr_free.drr_offset);
		DO64(drr_free.drr_length);
		break;
	case DRR_END:
		DO64(drr_end.drr_checksum.zc_word[0]);
		DO64(drr_end.drr_checksum.zc_word[1]);
		DO64(drr_end.drr_checksum.zc_word[2]);
		DO64(drr_end.drr_checksum.zc_word[3]);
		break;
	}
#undef DO64
#undef DO32
}

static int
restore_object(struct restorearg *ra, objset_t *os, struct drr_object *drro)
{
	int err;
	dmu_tx_t *tx;

	if (drro->drr_type == DMU_OT_NONE ||
	    drro->drr_type >= DMU_OT_NUMTYPES ||
	    drro->drr_bonustype >= DMU_OT_NUMTYPES ||
	    drro->drr_checksum >= ZIO_CHECKSUM_FUNCTIONS ||
	    drro->drr_compress >= ZIO_COMPRESS_FUNCTIONS ||
	    P2PHASE(drro->drr_blksz, SPA_MINBLOCKSIZE) ||
	    drro->drr_blksz < SPA_MINBLOCKSIZE ||
	    drro->drr_blksz > SPA_MAXBLOCKSIZE ||
	    drro->drr_bonuslen > DN_MAX_BONUSLEN) {
		return (EINVAL);
	}

	err = dmu_object_info(os, drro->drr_object, NULL);

	if (err != 0 && err != ENOENT)
		return (EINVAL);

	if (err == ENOENT) {
		/* currently free, want to be allocated */
		tx = dmu_tx_create(os);
		dmu_tx_hold_bonus(tx, DMU_NEW_OBJECT);
		err = dmu_tx_assign(tx, TXG_WAIT);
		if (err) {
			dmu_tx_abort(tx);
			return (err);
		}
		err = dmu_object_claim(os, drro->drr_object,
		    drro->drr_type, drro->drr_blksz,
		    drro->drr_bonustype, drro->drr_bonuslen, tx);
		dmu_tx_commit(tx);
	} else {
		/* currently allocated, want to be allocated */

		err = dmu_object_reclaim(os, drro->drr_object,
		    drro->drr_type, drro->drr_blksz,
		    drro->drr_bonustype, drro->drr_bonuslen);
	}
	if (err)
		return (EINVAL);

	tx = dmu_tx_create(os);
	dmu_tx_hold_bonus(tx, drro->drr_object);
	err = dmu_tx_assign(tx, TXG_WAIT);
	if (err) {
		dmu_tx_abort(tx);
		return (err);
	}

	dmu_object_set_checksum(os, drro->drr_object, drro->drr_checksum, tx);
	dmu_object_set_compress(os, drro->drr_object, drro->drr_compress, tx);

	if (drro->drr_bonuslen) {
		dmu_buf_t *db;
		void *data;
		VERIFY(0 == dmu_bonus_hold(os, drro->drr_object, FTAG, &db));
		dmu_buf_will_dirty(db, tx);

		ASSERT3U(db->db_size, >=, drro->drr_bonuslen);
		data = restore_read(ra, P2ROUNDUP(drro->drr_bonuslen, 8));
		if (data == NULL) {
			dmu_tx_commit(tx);
			return (ra->err);
		}
		bcopy(data, db->db_data, drro->drr_bonuslen);
		if (ra->byteswap) {
			dmu_ot[drro->drr_bonustype].ot_byteswap(db->db_data,
			    drro->drr_bonuslen);<commit_msg>MFC r200727:<commit_after>/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#include <sys/dmu.h>
#include <sys/dmu_impl.h>
#include <sys/dmu_tx.h>
#include <sys/dbuf.h>
#include <sys/dnode.h>
#include <sys/zfs_context.h>
#include <sys/dmu_objset.h>
#include <sys/dmu_traverse.h>
#include <sys/dsl_dataset.h>
#include <sys/dsl_dir.h>
#include <sys/dsl_pool.h>
#include <sys/dsl_synctask.h>
#include <sys/zfs_ioctl.h>
#include <sys/zap.h>
#include <sys/zio_checksum.h>

static char *dmu_recv_tag = "dmu_recv_tag";

struct backuparg {
	dmu_replay_record_t *drr;
	kthread_t *td;
	struct file *fp;
	offset_t *off;
	objset_t *os;
	zio_cksum_t zc;
	int err;
};

static int
dump_bytes(struct backuparg *ba, void *buf, int len)
{
	struct uio auio;
	struct iovec aiov;

	ASSERT3U(len % 8, ==, 0);

	fletcher_4_incremental_native(buf, len, &ba->zc);

	aiov.iov_base = buf;
	aiov.iov_len = len;
	auio.uio_iov = &aiov;
	auio.uio_iovcnt = 1;
	auio.uio_resid = len;
	auio.uio_segflg = UIO_SYSSPACE;
	auio.uio_rw = UIO_WRITE;
	auio.uio_offset = (off_t)-1;
	auio.uio_td = ba->td;
#ifdef _KERNEL
	if (ba->fp->f_type == DTYPE_VNODE)
		bwillwrite();
	ba->err = fo_write(ba->fp, &auio, ba->td->td_ucred, 0, ba->td);
#else
	fprintf(stderr, "%s: returning EOPNOTSUPP\n", __func__);
	ba->err = EOPNOTSUPP;
#endif
	*ba->off += len;

	return (ba->err);
}

static int
dump_free(struct backuparg *ba, uint64_t object, uint64_t offset,
    uint64_t length)
{
	/* write a FREE record */
	bzero(ba->drr, sizeof (dmu_replay_record_t));
	ba->drr->drr_type = DRR_FREE;
	ba->drr->drr_u.drr_free.drr_object = object;
	ba->drr->drr_u.drr_free.drr_offset = offset;
	ba->drr->drr_u.drr_free.drr_length = length;

	if (dump_bytes(ba, ba->drr, sizeof (dmu_replay_record_t)))
		return (EINTR);
	return (0);
}

static int
dump_data(struct backuparg *ba, dmu_object_type_t type,
    uint64_t object, uint64_t offset, int blksz, void *data)
{
	/* write a DATA record */
	bzero(ba->drr, sizeof (dmu_replay_record_t));
	ba->drr->drr_type = DRR_WRITE;
	ba->drr->drr_u.drr_write.drr_object = object;
	ba->drr->drr_u.drr_write.drr_type = type;
	ba->drr->drr_u.drr_write.drr_offset = offset;
	ba->drr->drr_u.drr_write.drr_length = blksz;

	if (dump_bytes(ba, ba->drr, sizeof (dmu_replay_record_t)))
		return (EINTR);
	if (dump_bytes(ba, data, blksz))
		return (EINTR);
	return (0);
}

static int
dump_freeobjects(struct backuparg *ba, uint64_t firstobj, uint64_t numobjs)
{
	/* write a FREEOBJECTS record */
	bzero(ba->drr, sizeof (dmu_replay_record_t));
	ba->drr->drr_type = DRR_FREEOBJECTS;
	ba->drr->drr_u.drr_freeobjects.drr_firstobj = firstobj;
	ba->drr->drr_u.drr_freeobjects.drr_numobjs = numobjs;

	if (dump_bytes(ba, ba->drr, sizeof (dmu_replay_record_t)))
		return (EINTR);
	return (0);
}

static int
dump_dnode(struct backuparg *ba, uint64_t object, dnode_phys_t *dnp)
{
	if (dnp == NULL || dnp->dn_type == DMU_OT_NONE)
		return (dump_freeobjects(ba, object, 1));

	/* write an OBJECT record */
	bzero(ba->drr, sizeof (dmu_replay_record_t));
	ba->drr->drr_type = DRR_OBJECT;
	ba->drr->drr_u.drr_object.drr_object = object;
	ba->drr->drr_u.drr_object.drr_type = dnp->dn_type;
	ba->drr->drr_u.drr_object.drr_bonustype = dnp->dn_bonustype;
	ba->drr->drr_u.drr_object.drr_blksz =
	    dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT;
	ba->drr->drr_u.drr_object.drr_bonuslen = dnp->dn_bonuslen;
	ba->drr->drr_u.drr_object.drr_checksum = dnp->dn_checksum;
	ba->drr->drr_u.drr_object.drr_compress = dnp->dn_compress;

	if (dump_bytes(ba, ba->drr, sizeof (dmu_replay_record_t)))
		return (EINTR);

	if (dump_bytes(ba, DN_BONUS(dnp), P2ROUNDUP(dnp->dn_bonuslen, 8)))
		return (EINTR);

	/* free anything past the end of the file */
	if (dump_free(ba, object, (dnp->dn_maxblkid + 1) *
	    (dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT), -1ULL))
		return (EINTR);
	if (ba->err)
		return (EINTR);
	return (0);
}

#define	BP_SPAN(dnp, level) \
	(((uint64_t)dnp->dn_datablkszsec) << (SPA_MINBLOCKSHIFT + \
	(level) * (dnp->dn_indblkshift - SPA_BLKPTRSHIFT)))

static int
backup_cb(traverse_blk_cache_t *bc, spa_t *spa, void *arg)
{
	struct backuparg *ba = arg;
	uint64_t object = bc->bc_bookmark.zb_object;
	int level = bc->bc_bookmark.zb_level;
	uint64_t blkid = bc->bc_bookmark.zb_blkid;
	blkptr_t *bp = bc->bc_blkptr.blk_birth ? &bc->bc_blkptr : NULL;
	dmu_object_type_t type = bp ? BP_GET_TYPE(bp) : DMU_OT_NONE;
	void *data = bc->bc_data;
	int err = 0;

	if (issig(JUSTLOOKING) && issig(FORREAL))
		return (EINTR);

	ASSERT(data || bp == NULL);

	if (bp == NULL && object == 0) {
		uint64_t span = BP_SPAN(bc->bc_dnode, level);
		uint64_t dnobj = (blkid * span) >> DNODE_SHIFT;
		err = dump_freeobjects(ba, dnobj, span >> DNODE_SHIFT);
	} else if (bp == NULL) {
		uint64_t span = BP_SPAN(bc->bc_dnode, level);
		err = dump_free(ba, object, blkid * span, span);
	} else if (data && level == 0 && type == DMU_OT_DNODE) {
		dnode_phys_t *blk = data;
		int i;
		int blksz = BP_GET_LSIZE(bp);

		for (i = 0; i < blksz >> DNODE_SHIFT; i++) {
			uint64_t dnobj =
			    (blkid << (DNODE_BLOCK_SHIFT - DNODE_SHIFT)) + i;
			err = dump_dnode(ba, dnobj, blk+i);
			if (err)
				break;
		}
	} else if (level == 0 &&
	    type != DMU_OT_DNODE && type != DMU_OT_OBJSET) {
		int blksz = BP_GET_LSIZE(bp);
		if (data == NULL) {
			uint32_t aflags = ARC_WAIT;
			arc_buf_t *abuf;
			zbookmark_t zb;

			zb.zb_objset = ba->os->os->os_dsl_dataset->ds_object;
			zb.zb_object = object;
			zb.zb_level = level;
			zb.zb_blkid = blkid;
			(void) arc_read_nolock(NULL, spa, bp,
			    arc_getbuf_func, &abuf, ZIO_PRIORITY_ASYNC_READ,
			    ZIO_FLAG_MUSTSUCCEED, &aflags, &zb);

			if (abuf) {
				err = dump_data(ba, type, object, blkid * blksz,
				    blksz, abuf->b_data);
				(void) arc_buf_remove_ref(abuf, &abuf);
			}
		} else {
			err = dump_data(ba, type, object, blkid * blksz,
			    blksz, data);
		}
	}

	ASSERT(err == 0 || err == EINTR);
	return (err);
}

int
dmu_sendbackup(objset_t *tosnap, objset_t *fromsnap, boolean_t fromorigin,
    struct file *fp, offset_t *off)
{
	dsl_dataset_t *ds = tosnap->os->os_dsl_dataset;
	dsl_dataset_t *fromds = fromsnap ? fromsnap->os->os_dsl_dataset : NULL;
	dmu_replay_record_t *drr;
	struct backuparg ba;
	int err;
	uint64_t fromtxg = 0;

	/* tosnap must be a snapshot */
	if (ds->ds_phys->ds_next_snap_obj == 0)
		return (EINVAL);

	/* fromsnap must be an earlier snapshot from the same fs as tosnap */
	if (fromds && (ds->ds_dir != fromds->ds_dir ||
	    fromds->ds_phys->ds_creation_txg >= ds->ds_phys->ds_creation_txg))
		return (EXDEV);

	if (fromorigin) {
		dsl_pool_t *dp = ds->ds_dir->dd_pool;

		if (fromsnap)
			return (EINVAL);

		if (dsl_dir_is_clone(ds->ds_dir)) {
			rw_enter(&dp->dp_config_rwlock, RW_READER);
			err = dsl_dataset_hold_obj(dp,
			    ds->ds_dir->dd_phys->dd_origin_obj, FTAG, &fromds);
			rw_exit(&dp->dp_config_rwlock);
			if (err)
				return (err);
		} else {
			fromorigin = B_FALSE;
		}
	}


	drr = kmem_zalloc(sizeof (dmu_replay_record_t), KM_SLEEP);
	drr->drr_type = DRR_BEGIN;
	drr->drr_u.drr_begin.drr_magic = DMU_BACKUP_MAGIC;
	drr->drr_u.drr_begin.drr_version = DMU_BACKUP_STREAM_VERSION;
	drr->drr_u.drr_begin.drr_creation_time =
	    ds->ds_phys->ds_creation_time;
	drr->drr_u.drr_begin.drr_type = tosnap->os->os_phys->os_type;
	if (fromorigin)
		drr->drr_u.drr_begin.drr_flags |= DRR_FLAG_CLONE;
	drr->drr_u.drr_begin.drr_toguid = ds->ds_phys->ds_guid;
	if (ds->ds_phys->ds_flags & DS_FLAG_CI_DATASET)
		drr->drr_u.drr_begin.drr_flags |= DRR_FLAG_CI_DATA;

	if (fromds)
		drr->drr_u.drr_begin.drr_fromguid = fromds->ds_phys->ds_guid;
	dsl_dataset_name(ds, drr->drr_u.drr_begin.drr_toname);

	if (fromds)
		fromtxg = fromds->ds_phys->ds_creation_txg;
	if (fromorigin)
		dsl_dataset_rele(fromds, FTAG);

	ba.drr = drr;
	ba.td = curthread;
	ba.fp = fp;
	ba.os = tosnap;
	ba.off = off;
	ZIO_SET_CHECKSUM(&ba.zc, 0, 0, 0, 0);

	if (dump_bytes(&ba, drr, sizeof (dmu_replay_record_t))) {
		kmem_free(drr, sizeof (dmu_replay_record_t));
		return (ba.err);
	}

	err = traverse_dsl_dataset(ds, fromtxg,
	    ADVANCE_PRE | ADVANCE_HOLES | ADVANCE_DATA | ADVANCE_NOLOCK,
	    backup_cb, &ba);

	if (err) {
		if (err == EINTR && ba.err)
			err = ba.err;
		kmem_free(drr, sizeof (dmu_replay_record_t));
		return (err);
	}

	bzero(drr, sizeof (dmu_replay_record_t));
	drr->drr_type = DRR_END;
	drr->drr_u.drr_end.drr_checksum = ba.zc;

	if (dump_bytes(&ba, drr, sizeof (dmu_replay_record_t))) {
		kmem_free(drr, sizeof (dmu_replay_record_t));
		return (ba.err);
	}

	kmem_free(drr, sizeof (dmu_replay_record_t));

	return (0);
}

struct recvbeginsyncarg {
	const char *tofs;
	const char *tosnap;
	dsl_dataset_t *origin;
	uint64_t fromguid;
	dmu_objset_type_t type;
	void *tag;
	boolean_t force;
	uint64_t dsflags;
	char clonelastname[MAXNAMELEN];
	dsl_dataset_t *ds; /* the ds to recv into; returned from the syncfunc */
};

static dsl_dataset_t *
recv_full_sync_impl(dsl_pool_t *dp, uint64_t dsobj, dmu_objset_type_t type,
    cred_t *cr, dmu_tx_t *tx)
{
	dsl_dataset_t *ds;

	/* This should always work, since we just created it */
	/* XXX - create should return an owned ds */
	VERIFY(0 == dsl_dataset_own_obj(dp, dsobj,
	    DS_MODE_INCONSISTENT, dmu_recv_tag, &ds));

	if (type != DMU_OST_NONE) {
		(void) dmu_objset_create_impl(dp->dp_spa,
		    ds, &ds->ds_phys->ds_bp, type, tx);
	}

	spa_history_internal_log(LOG_DS_REPLAY_FULL_SYNC,
	    dp->dp_spa, tx, cr, "dataset = %lld", dsobj);

	return (ds);
}

/* ARGSUSED */
static int
recv_full_check(void *arg1, void *arg2, dmu_tx_t *tx)
{
	dsl_dir_t *dd = arg1;
	struct recvbeginsyncarg *rbsa = arg2;
	objset_t *mos = dd->dd_pool->dp_meta_objset;
	uint64_t val;
	int err;

	err = zap_lookup(mos, dd->dd_phys->dd_child_dir_zapobj,
	    strrchr(rbsa->tofs, '/') + 1, sizeof (uint64_t), 1, &val);

	if (err != ENOENT)
		return (err ? err : EEXIST);

	if (rbsa->origin) {
		/* make sure it's a snap in the same pool */
		if (rbsa->origin->ds_dir->dd_pool != dd->dd_pool)
			return (EXDEV);
		if (rbsa->origin->ds_phys->ds_num_children == 0)
			return (EINVAL);
		if (rbsa->origin->ds_phys->ds_guid != rbsa->fromguid)
			return (ENODEV);
	}

	return (0);
}

static void
recv_full_sync(void *arg1, void *arg2, cred_t *cr, dmu_tx_t *tx)
{
	dsl_dir_t *dd = arg1;
	struct recvbeginsyncarg *rbsa = arg2;
	uint64_t flags = DS_FLAG_INCONSISTENT | rbsa->dsflags;
	uint64_t dsobj;

	dsobj = dsl_dataset_create_sync(dd, strrchr(rbsa->tofs, '/') + 1,
	    rbsa->origin, flags, cr, tx);

	rbsa->ds = recv_full_sync_impl(dd->dd_pool, dsobj,
	    rbsa->origin ? DMU_OST_NONE : rbsa->type, cr, tx);
}

static int
recv_full_existing_check(void *arg1, void *arg2, dmu_tx_t *tx)
{
	dsl_dataset_t *ds = arg1;
	struct recvbeginsyncarg *rbsa = arg2;
	int err;

	/* must be a head ds */
	if (ds->ds_phys->ds_next_snap_obj != 0)
		return (EINVAL);

	/* must not be a clone ds */
	if (dsl_dir_is_clone(ds->ds_dir))
		return (EINVAL);

	err = dsl_dataset_destroy_check(ds, rbsa->tag, tx);
	if (err)
		return (err);

	if (rbsa->origin) {
		/* make sure it's a snap in the same pool */
		if (rbsa->origin->ds_dir->dd_pool != ds->ds_dir->dd_pool)
			return (EXDEV);
		if (rbsa->origin->ds_phys->ds_num_children == 0)
			return (EINVAL);
		if (rbsa->origin->ds_phys->ds_guid != rbsa->fromguid)
			return (ENODEV);
	}

	return (0);
}

static void
recv_full_existing_sync(void *arg1, void *arg2, cred_t *cr, dmu_tx_t *tx)
{
	dsl_dataset_t *ds = arg1;
	struct recvbeginsyncarg *rbsa = arg2;
	dsl_dir_t *dd = ds->ds_dir;
	uint64_t flags = DS_FLAG_INCONSISTENT | rbsa->dsflags;
	uint64_t dsobj;

	/*
	 * NB: caller must provide an extra hold on the dsl_dir_t, so it
	 * won't go away when dsl_dataset_destroy_sync() closes the
	 * dataset.
	 */
	dsl_dataset_destroy_sync(ds, rbsa->tag, cr, tx);

	dsobj = dsl_dataset_create_sync_dd(dd, rbsa->origin, flags, tx);

	rbsa->ds = recv_full_sync_impl(dd->dd_pool, dsobj,
	    rbsa->origin ? DMU_OST_NONE : rbsa->type, cr, tx);
}

/* ARGSUSED */
static int
recv_incremental_check(void *arg1, void *arg2, dmu_tx_t *tx)
{
	dsl_dataset_t *ds = arg1;
	struct recvbeginsyncarg *rbsa = arg2;
	int err;
	uint64_t val;

	/* must not have any changes since most recent snapshot */
	if (!rbsa->force && dsl_dataset_modified_since_lastsnap(ds))
		return (ETXTBSY);

	/* must already be a snapshot of this fs */
	if (ds->ds_phys->ds_prev_snap_obj == 0)
		return (ENODEV);

	/* most recent snapshot must match fromguid */
	if (ds->ds_prev->ds_phys->ds_guid != rbsa->fromguid)
		return (ENODEV);

	/* temporary clone name must not exist */
	err = zap_lookup(ds->ds_dir->dd_pool->dp_meta_objset,
	    ds->ds_dir->dd_phys->dd_child_dir_zapobj,
	    rbsa->clonelastname, 8, 1, &val);
	if (err == 0)
		return (EEXIST);
	if (err != ENOENT)
		return (err);

	/* new snapshot name must not exist */
	err = zap_lookup(ds->ds_dir->dd_pool->dp_meta_objset,
	    ds->ds_phys->ds_snapnames_zapobj, rbsa->tosnap, 8, 1, &val);
	if (err == 0)
		return (EEXIST);
	if (err != ENOENT)
		return (err);
	return (0);
}

/* ARGSUSED */
static void
recv_online_incremental_sync(void *arg1, void *arg2, cred_t *cr, dmu_tx_t *tx)
{
	dsl_dataset_t *ohds = arg1;
	struct recvbeginsyncarg *rbsa = arg2;
	dsl_pool_t *dp = ohds->ds_dir->dd_pool;
	dsl_dataset_t *ods, *cds;
	uint64_t flags = DS_FLAG_INCONSISTENT | rbsa->dsflags;
	uint64_t dsobj;

	/* create the temporary clone */
	VERIFY(0 == dsl_dataset_hold_obj(dp, ohds->ds_phys->ds_prev_snap_obj,
	    FTAG, &ods));
	dsobj = dsl_dataset_create_sync(ohds->ds_dir,
	    rbsa->clonelastname, ods, flags, cr, tx);
	dsl_dataset_rele(ods, FTAG);

	/* open the temporary clone */
	VERIFY(0 == dsl_dataset_own_obj(dp, dsobj,
	    DS_MODE_INCONSISTENT, dmu_recv_tag, &cds));

	/* copy the refquota from the target fs to the clone */
	if (ohds->ds_quota > 0)
		dsl_dataset_set_quota_sync(cds, &ohds->ds_quota, cr, tx);

	rbsa->ds = cds;

	spa_history_internal_log(LOG_DS_REPLAY_INC_SYNC,
	    dp->dp_spa, tx, cr, "dataset = %lld", dsobj);
}

/* ARGSUSED */
static void
recv_offline_incremental_sync(void *arg1, void *arg2, cred_t *cr, dmu_tx_t *tx)
{
	dsl_dataset_t *ds = arg1;

	dmu_buf_will_dirty(ds->ds_dbuf, tx);
	ds->ds_phys->ds_flags |= DS_FLAG_INCONSISTENT;

	spa_history_internal_log(LOG_DS_REPLAY_INC_SYNC,
	    ds->ds_dir->dd_pool->dp_spa, tx, cr, "dataset = %lld",
	    ds->ds_object);
}

/*
 * NB: callers *MUST* call dmu_recv_stream() if dmu_recv_begin()
 * succeeds; otherwise we will leak the holds on the datasets.
 */
int
dmu_recv_begin(char *tofs, char *tosnap, struct drr_begin *drrb,
    boolean_t force, objset_t *origin, boolean_t online, dmu_recv_cookie_t *drc)
{
	int err = 0;
	boolean_t byteswap;
	struct recvbeginsyncarg rbsa;
	uint64_t version;
	int flags;
	dsl_dataset_t *ds;

	if (drrb->drr_magic == DMU_BACKUP_MAGIC)
		byteswap = FALSE;
	else if (drrb->drr_magic == BSWAP_64(DMU_BACKUP_MAGIC))
		byteswap = TRUE;
	else
		return (EINVAL);

	rbsa.tofs = tofs;
	rbsa.tosnap = tosnap;
	rbsa.origin = origin ? origin->os->os_dsl_dataset : NULL;
	rbsa.fromguid = drrb->drr_fromguid;
	rbsa.type = drrb->drr_type;
	rbsa.tag = FTAG;
	rbsa.dsflags = 0;
	version = drrb->drr_version;
	flags = drrb->drr_flags;

	if (byteswap) {
		rbsa.type = BSWAP_32(rbsa.type);
		rbsa.fromguid = BSWAP_64(rbsa.fromguid);
		version = BSWAP_64(version);
		flags = BSWAP_32(flags);
	}

	if (version != DMU_BACKUP_STREAM_VERSION ||
	    rbsa.type >= DMU_OST_NUMTYPES ||
	    ((flags & DRR_FLAG_CLONE) && origin == NULL))
		return (EINVAL);

	if (flags & DRR_FLAG_CI_DATA)
		rbsa.dsflags = DS_FLAG_CI_DATASET;

	bzero(drc, sizeof (dmu_recv_cookie_t));
	drc->drc_drrb = drrb;
	drc->drc_tosnap = tosnap;
	drc->drc_force = force;

	/*
	 * Process the begin in syncing context.
	 */
	if (rbsa.fromguid && !(flags & DRR_FLAG_CLONE) && !online) {
		/* offline incremental receive */
		err = dsl_dataset_own(tofs, 0, dmu_recv_tag, &ds);
		if (err)
			return (err);

		/*
		 * Only do the rollback if the most recent snapshot
		 * matches the incremental source
		 */
		if (force) {
			if (ds->ds_prev == NULL ||
			    ds->ds_prev->ds_phys->ds_guid !=
			    rbsa.fromguid) {
				dsl_dataset_disown(ds, dmu_recv_tag);
				return (ENODEV);
			}
			(void) dsl_dataset_rollback(ds, DMU_OST_NONE);
		}
		rbsa.force = B_FALSE;
		err = dsl_sync_task_do(ds->ds_dir->dd_pool,
		    recv_incremental_check,
		    recv_offline_incremental_sync, ds, &rbsa, 1);
		if (err) {
			dsl_dataset_disown(ds, dmu_recv_tag);
			return (err);
		}
		drc->drc_logical_ds = drc->drc_real_ds = ds;
	} else if (rbsa.fromguid && !(flags & DRR_FLAG_CLONE)) {
		/* online incremental receive */

		/* tmp clone name is: tofs/%tosnap" */
		(void) snprintf(rbsa.clonelastname, sizeof (rbsa.clonelastname),
		    "%%%s", tosnap);

		/* open the dataset we are logically receiving into */
		err = dsl_dataset_hold(tofs, dmu_recv_tag, &ds);
		if (err)
			return (err);

		rbsa.force = force;
		err = dsl_sync_task_do(ds->ds_dir->dd_pool,
		    recv_incremental_check,
		    recv_online_incremental_sync, ds, &rbsa, 5);
		if (err) {
			dsl_dataset_rele(ds, dmu_recv_tag);
			return (err);
		}
		drc->drc_logical_ds = ds;
		drc->drc_real_ds = rbsa.ds;
	} else {
		/* create new fs -- full backup or clone */
		dsl_dir_t *dd = NULL;
		const char *tail;

		err = dsl_dir_open(tofs, FTAG, &dd, &tail);
		if (err)
			return (err);
		if (tail == NULL) {
			if (!force) {
				dsl_dir_close(dd, FTAG);
				return (EEXIST);
			}

			rw_enter(&dd->dd_pool->dp_config_rwlock, RW_READER);
			err = dsl_dataset_own_obj(dd->dd_pool,
			    dd->dd_phys->dd_head_dataset_obj,
			    DS_MODE_INCONSISTENT, FTAG, &ds);
			rw_exit(&dd->dd_pool->dp_config_rwlock);
			if (err) {
				dsl_dir_close(dd, FTAG);
				return (err);
			}

			dsl_dataset_make_exclusive(ds, FTAG);
			err = dsl_sync_task_do(dd->dd_pool,
			    recv_full_existing_check,
			    recv_full_existing_sync, ds, &rbsa, 5);
			dsl_dataset_disown(ds, FTAG);
		} else {
			err = dsl_sync_task_do(dd->dd_pool, recv_full_check,
			    recv_full_sync, dd, &rbsa, 5);
		}
		dsl_dir_close(dd, FTAG);
		if (err)
			return (err);
		drc->drc_logical_ds = drc->drc_real_ds = rbsa.ds;
		drc->drc_newfs = B_TRUE;
	}

	return (0);
}

struct restorearg {
	int err;
	int byteswap;
	kthread_t *td;
	struct file *fp;
	char *buf;
	uint64_t voff;
	int bufsize; /* amount of memory allocated for buf */
	zio_cksum_t cksum;
};

static int
restore_bytes(struct restorearg *ra, void *buf, int len, off_t off, int *resid)
{
	struct uio auio;
	struct iovec aiov;
	int error;

	aiov.iov_base = buf;
	aiov.iov_len = len;
	auio.uio_iov = &aiov;
	auio.uio_iovcnt = 1;
	auio.uio_resid = len;
	auio.uio_segflg = UIO_SYSSPACE;
	auio.uio_rw = UIO_READ;
	auio.uio_offset = off;
	auio.uio_td = ra->td;
#ifdef _KERNEL
	error = fo_read(ra->fp, &auio, ra->td->td_ucred, FOF_OFFSET, ra->td);
#else
	fprintf(stderr, "%s: returning EOPNOTSUPP\n", __func__);
	error = EOPNOTSUPP;
#endif
	*resid = auio.uio_resid;
	return (error);
}

static void *
restore_read(struct restorearg *ra, int len)
{
	void *rv;
	int done = 0;

	/* some things will require 8-byte alignment, so everything must */
	ASSERT3U(len % 8, ==, 0);

	while (done < len) {
		int resid;

		ra->err = restore_bytes(ra, (caddr_t)ra->buf + done,
		    len - done, ra->voff, &resid);

		if (resid == len - done)
			ra->err = EINVAL;
		ra->voff += len - done - resid;
		done = len - resid;
		if (ra->err)
			return (NULL);
	}

	ASSERT3U(done, ==, len);
	rv = ra->buf;
	if (ra->byteswap)
		fletcher_4_incremental_byteswap(rv, len, &ra->cksum);
	else
		fletcher_4_incremental_native(rv, len, &ra->cksum);
	return (rv);
}

static void
backup_byteswap(dmu_replay_record_t *drr)
{
#define	DO64(X) (drr->drr_u.X = BSWAP_64(drr->drr_u.X))
#define	DO32(X) (drr->drr_u.X = BSWAP_32(drr->drr_u.X))
	drr->drr_type = BSWAP_32(drr->drr_type);
	drr->drr_payloadlen = BSWAP_32(drr->drr_payloadlen);
	switch (drr->drr_type) {
	case DRR_BEGIN:
		DO64(drr_begin.drr_magic);
		DO64(drr_begin.drr_version);
		DO64(drr_begin.drr_creation_time);
		DO32(drr_begin.drr_type);
		DO32(drr_begin.drr_flags);
		DO64(drr_begin.drr_toguid);
		DO64(drr_begin.drr_fromguid);
		break;
	case DRR_OBJECT:
		DO64(drr_object.drr_object);
		/* DO64(drr_object.drr_allocation_txg); */
		DO32(drr_object.drr_type);
		DO32(drr_object.drr_bonustype);
		DO32(drr_object.drr_blksz);
		DO32(drr_object.drr_bonuslen);
		break;
	case DRR_FREEOBJECTS:
		DO64(drr_freeobjects.drr_firstobj);
		DO64(drr_freeobjects.drr_numobjs);
		break;
	case DRR_WRITE:
		DO64(drr_write.drr_object);
		DO32(drr_write.drr_type);
		DO64(drr_write.drr_offset);
		DO64(drr_write.drr_length);
		break;
	case DRR_FREE:
		DO64(drr_free.drr_object);
		DO64(drr_free.drr_offset);
		DO64(drr_free.drr_length);
		break;
	case DRR_END:
		DO64(drr_end.drr_checksum.zc_word[0]);
		DO64(drr_end.drr_checksum.zc_word[1]);
		DO64(drr_end.drr_checksum.zc_word[2]);
		DO64(drr_end.drr_checksum.zc_word[3]);
		break;
	}
#undef DO64
#undef DO32
}

static int
restore_object(struct restorearg *ra, objset_t *os, struct drr_object *drro)
{
	int err;
	dmu_tx_t *tx;
	void *data = NULL;

	if (drro->drr_type == DMU_OT_NONE ||
	    drro->drr_type >= DMU_OT_NUMTYPES ||
	    drro->drr_bonustype >= DMU_OT_NUMTYPES ||
	    drro->drr_checksum >= ZIO_CHECKSUM_FUNCTIONS ||
	    drro->drr_compress >= ZIO_COMPRESS_FUNCTIONS ||
	    P2PHASE(drro->drr_blksz, SPA_MINBLOCKSIZE) ||
	    drro->drr_blksz < SPA_MINBLOCKSIZE ||
	    drro->drr_blksz > SPA_MAXBLOCKSIZE ||
	    drro->drr_bonuslen > DN_MAX_BONUSLEN) {
		return (EINVAL);
	}

	err = dmu_object_info(os, drro->drr_object, NULL);

	if (err != 0 && err != ENOENT)
		return (EINVAL);

	if (err == ENOENT) {
		/* currently free, want to be allocated */
		tx = dmu_tx_create(os);
		dmu_tx_hold_bonus(tx, DMU_NEW_OBJECT);
		err = dmu_tx_assign(tx, TXG_WAIT);
		if (err) {
			dmu_tx_abort(tx);
			return (err);
		}
		err = dmu_object_claim(os, drro->drr_object,
		    drro->drr_type, drro->drr_blksz,
		    drro->drr_bonustype, drro->drr_bonuslen, tx);
		dmu_tx_commit(tx);
	} else {
		/* currently allocated, want to be allocated */

		err = dmu_object_reclaim(os, drro->drr_object,
		    drro->drr_type, drro->drr_blksz,
		    drro->drr_bonustype, drro->drr_bonuslen);
	}
	if (err)
		return (EINVAL);

	if (drro->drr_bonuslen) {
		data = restore_read(ra, P2ROUNDUP(drro->drr_bonuslen, 8));
		if (ra->err)
			return (ra->err);
	}

	tx = dmu_tx_create(os);
	dmu_tx_hold_bonus(tx, drro->drr_object);
	err = dmu_tx_assign(tx, TXG_WAIT);
	if (err) {
		dmu_tx_abort(tx);
		return (err);
	}

	dmu_object_set_checksum(os, drro->drr_object, drro->drr_checksum, tx);
	dmu_object_set_compress(os, drro->drr_object, drro->drr_compress, tx);

	if (data != NULL) {
		dmu_buf_t *db;

		VERIFY(0 == dmu_bonus_hold(os, drro->drr_object, FTAG, &db));
		dmu_buf_will_dirty(db, tx);

		ASSERT3U(db->db_size, >=, drro->drr_bonuslen);
		bcopy(data, db->db_data, drro->drr_bonuslen);
		if (ra->byteswap) {
			dmu_ot[drro->drr_bonustype].ot_byteswap(db->db_data,
			    drro->drr_bonuslen);
{'fraction_non_alphanumeric': 0.14308803156878386, 'fraction_numerical': 0.010494941438226775, 'mean_word_length': 4.139482200647249, 'pattern_counts': {'":': 0, '<': 55, '<?xml version=': 0, '>': 702, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7246953', 'n_tokens_mistral': 22583, 'n_tokens_neox': 21118, 'n_words': 4096}