]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/cddl/contrib/opensolaris/uts/common/fs/zfs/dmu_send.c
MFC r353176,r353304,r353556,r353559: large_dnode improvements and fixes
[FreeBSD/FreeBSD.git] / sys / cddl / contrib / opensolaris / uts / common / fs / zfs / dmu_send.c
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23  * Copyright 2011 Nexenta Systems, Inc. All rights reserved.
24  * Copyright (c) 2011, 2015 by Delphix. All rights reserved.
25  * Copyright (c) 2014, Joyent, Inc. All rights reserved.
26  * Copyright (c) 2012, Martin Matuska <mm@FreeBSD.org>. All rights reserved.
27  * Copyright 2014 HybridCluster. All rights reserved.
28  * Copyright 2016 RackTop Systems.
29  * Copyright (c) 2014 Integros [integros.com]
30  */
31
32 #include <sys/dmu.h>
33 #include <sys/dmu_impl.h>
34 #include <sys/dmu_tx.h>
35 #include <sys/dbuf.h>
36 #include <sys/dnode.h>
37 #include <sys/zfs_context.h>
38 #include <sys/dmu_objset.h>
39 #include <sys/dmu_traverse.h>
40 #include <sys/dsl_dataset.h>
41 #include <sys/dsl_dir.h>
42 #include <sys/dsl_prop.h>
43 #include <sys/dsl_pool.h>
44 #include <sys/dsl_synctask.h>
45 #include <sys/zfs_ioctl.h>
46 #include <sys/zap.h>
47 #include <sys/zio_checksum.h>
48 #include <sys/zfs_znode.h>
49 #include <zfs_fletcher.h>
50 #include <sys/avl.h>
51 #include <sys/ddt.h>
52 #include <sys/zfs_onexit.h>
53 #include <sys/dmu_send.h>
54 #include <sys/dsl_destroy.h>
55 #include <sys/blkptr.h>
56 #include <sys/dsl_bookmark.h>
57 #include <sys/zfeature.h>
58 #include <sys/bqueue.h>
59
60 #ifdef __FreeBSD__
61 #undef dump_write
62 #define dump_write dmu_dump_write
63 #endif
64
65 /* Set this tunable to TRUE to replace corrupt data with 0x2f5baddb10c */
66 int zfs_send_corrupt_data = B_FALSE;
67 int zfs_send_queue_length = 16 * 1024 * 1024;
68 int zfs_recv_queue_length = 16 * 1024 * 1024;
69 /* Set this tunable to FALSE to disable setting of DRR_FLAG_FREERECORDS */
70 int zfs_send_set_freerecords_bit = B_TRUE;
71
72 #ifdef _KERNEL
73 TUNABLE_INT("vfs.zfs.send_set_freerecords_bit", &zfs_send_set_freerecords_bit);
74 #endif
75
76 static char *dmu_recv_tag = "dmu_recv_tag";
77 const char *recv_clone_name = "%recv";
78
79 /*
80  * Use this to override the recordsize calculation for fast zfs send estimates.
81  */
82 uint64_t zfs_override_estimate_recordsize = 0;
83
84 #define BP_SPAN(datablkszsec, indblkshift, level) \
85         (((uint64_t)datablkszsec) << (SPA_MINBLOCKSHIFT + \
86         (level) * (indblkshift - SPA_BLKPTRSHIFT)))
87
88 static void byteswap_record(dmu_replay_record_t *drr);
89
90 struct send_thread_arg {
91         bqueue_t        q;
92         dsl_dataset_t   *ds;            /* Dataset to traverse */
93         uint64_t        fromtxg;        /* Traverse from this txg */
94         int             flags;          /* flags to pass to traverse_dataset */
95         int             error_code;
96         boolean_t       cancel;
97         zbookmark_phys_t resume;
98 };
99
100 struct send_block_record {
101         boolean_t               eos_marker; /* Marks the end of the stream */
102         blkptr_t                bp;
103         zbookmark_phys_t        zb;
104         uint8_t                 indblkshift;
105         uint16_t                datablkszsec;
106         bqueue_node_t           ln;
107 };
108
109 static int
110 dump_bytes(dmu_sendarg_t *dsp, void *buf, int len)
111 {
112         dsl_dataset_t *ds = dmu_objset_ds(dsp->dsa_os);
113         struct uio auio;
114         struct iovec aiov;
115
116         /*
117          * The code does not rely on this (len being a multiple of 8).  We keep
118          * this assertion because of the corresponding assertion in
119          * receive_read().  Keeping this assertion ensures that we do not
120          * inadvertently break backwards compatibility (causing the assertion
121          * in receive_read() to trigger on old software).
122          *
123          * Removing the assertions could be rolled into a new feature that uses
124          * data that isn't 8-byte aligned; if the assertions were removed, a
125          * feature flag would have to be added.
126          */
127
128         ASSERT0(len % 8);
129
130         aiov.iov_base = buf;
131         aiov.iov_len = len;
132         auio.uio_iov = &aiov;
133         auio.uio_iovcnt = 1;
134         auio.uio_resid = len;
135         auio.uio_segflg = UIO_SYSSPACE;
136         auio.uio_rw = UIO_WRITE;
137         auio.uio_offset = (off_t)-1;
138         auio.uio_td = dsp->dsa_td;
139 #ifdef _KERNEL
140         if (dsp->dsa_fp->f_type == DTYPE_VNODE)
141                 bwillwrite();
142         dsp->dsa_err = fo_write(dsp->dsa_fp, &auio, dsp->dsa_td->td_ucred, 0,
143             dsp->dsa_td);
144 #else
145         fprintf(stderr, "%s: returning EOPNOTSUPP\n", __func__);
146         dsp->dsa_err = EOPNOTSUPP;
147 #endif
148         mutex_enter(&ds->ds_sendstream_lock);
149         *dsp->dsa_off += len;
150         mutex_exit(&ds->ds_sendstream_lock);
151
152         return (dsp->dsa_err);
153 }
154
155 /*
156  * For all record types except BEGIN, fill in the checksum (overlaid in
157  * drr_u.drr_checksum.drr_checksum).  The checksum verifies everything
158  * up to the start of the checksum itself.
159  */
160 static int
161 dump_record(dmu_sendarg_t *dsp, void *payload, int payload_len)
162 {
163         ASSERT3U(offsetof(dmu_replay_record_t, drr_u.drr_checksum.drr_checksum),
164             ==, sizeof (dmu_replay_record_t) - sizeof (zio_cksum_t));
165         (void) fletcher_4_incremental_native(dsp->dsa_drr,
166             offsetof(dmu_replay_record_t, drr_u.drr_checksum.drr_checksum),
167             &dsp->dsa_zc);
168         if (dsp->dsa_drr->drr_type == DRR_BEGIN) {
169                 dsp->dsa_sent_begin = B_TRUE;
170         } else {
171                 ASSERT(ZIO_CHECKSUM_IS_ZERO(&dsp->dsa_drr->drr_u.
172                     drr_checksum.drr_checksum));
173                 dsp->dsa_drr->drr_u.drr_checksum.drr_checksum = dsp->dsa_zc;
174         }
175         if (dsp->dsa_drr->drr_type == DRR_END) {
176                 dsp->dsa_sent_end = B_TRUE;
177         }
178         (void) fletcher_4_incremental_native(&dsp->dsa_drr->
179             drr_u.drr_checksum.drr_checksum,
180             sizeof (zio_cksum_t), &dsp->dsa_zc);
181         if (dump_bytes(dsp, dsp->dsa_drr, sizeof (dmu_replay_record_t)) != 0)
182                 return (SET_ERROR(EINTR));
183         if (payload_len != 0) {
184                 (void) fletcher_4_incremental_native(payload, payload_len,
185                     &dsp->dsa_zc);
186                 if (dump_bytes(dsp, payload, payload_len) != 0)
187                         return (SET_ERROR(EINTR));
188         }
189         return (0);
190 }
191
192 /*
193  * Fill in the drr_free struct, or perform aggregation if the previous record is
194  * also a free record, and the two are adjacent.
195  *
196  * Note that we send free records even for a full send, because we want to be
197  * able to receive a full send as a clone, which requires a list of all the free
198  * and freeobject records that were generated on the source.
199  */
200 static int
201 dump_free(dmu_sendarg_t *dsp, uint64_t object, uint64_t offset,
202     uint64_t length)
203 {
204         struct drr_free *drrf = &(dsp->dsa_drr->drr_u.drr_free);
205
206         /*
207          * When we receive a free record, dbuf_free_range() assumes
208          * that the receiving system doesn't have any dbufs in the range
209          * being freed.  This is always true because there is a one-record
210          * constraint: we only send one WRITE record for any given
211          * object,offset.  We know that the one-record constraint is
212          * true because we always send data in increasing order by
213          * object,offset.
214          *
215          * If the increasing-order constraint ever changes, we should find
216          * another way to assert that the one-record constraint is still
217          * satisfied.
218          */
219         ASSERT(object > dsp->dsa_last_data_object ||
220             (object == dsp->dsa_last_data_object &&
221             offset > dsp->dsa_last_data_offset));
222
223         if (length != -1ULL && offset + length < offset)
224                 length = -1ULL;
225
226         /*
227          * If there is a pending op, but it's not PENDING_FREE, push it out,
228          * since free block aggregation can only be done for blocks of the
229          * same type (i.e., DRR_FREE records can only be aggregated with
230          * other DRR_FREE records.  DRR_FREEOBJECTS records can only be
231          * aggregated with other DRR_FREEOBJECTS records.
232          */
233         if (dsp->dsa_pending_op != PENDING_NONE &&
234             dsp->dsa_pending_op != PENDING_FREE) {
235                 if (dump_record(dsp, NULL, 0) != 0)
236                         return (SET_ERROR(EINTR));
237                 dsp->dsa_pending_op = PENDING_NONE;
238         }
239
240         if (dsp->dsa_pending_op == PENDING_FREE) {
241                 /*
242                  * There should never be a PENDING_FREE if length is -1
243                  * (because dump_dnode is the only place where this
244                  * function is called with a -1, and only after flushing
245                  * any pending record).
246                  */
247                 ASSERT(length != -1ULL);
248                 /*
249                  * Check to see whether this free block can be aggregated
250                  * with pending one.
251                  */
252                 if (drrf->drr_object == object && drrf->drr_offset +
253                     drrf->drr_length == offset) {
254                         drrf->drr_length += length;
255                         return (0);
256                 } else {
257                         /* not a continuation.  Push out pending record */
258                         if (dump_record(dsp, NULL, 0) != 0)
259                                 return (SET_ERROR(EINTR));
260                         dsp->dsa_pending_op = PENDING_NONE;
261                 }
262         }
263         /* create a FREE record and make it pending */
264         bzero(dsp->dsa_drr, sizeof (dmu_replay_record_t));
265         dsp->dsa_drr->drr_type = DRR_FREE;
266         drrf->drr_object = object;
267         drrf->drr_offset = offset;
268         drrf->drr_length = length;
269         drrf->drr_toguid = dsp->dsa_toguid;
270         if (length == -1ULL) {
271                 if (dump_record(dsp, NULL, 0) != 0)
272                         return (SET_ERROR(EINTR));
273         } else {
274                 dsp->dsa_pending_op = PENDING_FREE;
275         }
276
277         return (0);
278 }
279
280 static int
281 dump_write(dmu_sendarg_t *dsp, dmu_object_type_t type,
282     uint64_t object, uint64_t offset, int lsize, int psize, const blkptr_t *bp,
283     void *data)
284 {
285         uint64_t payload_size;
286         struct drr_write *drrw = &(dsp->dsa_drr->drr_u.drr_write);
287
288         /*
289          * We send data in increasing object, offset order.
290          * See comment in dump_free() for details.
291          */
292         ASSERT(object > dsp->dsa_last_data_object ||
293             (object == dsp->dsa_last_data_object &&
294             offset > dsp->dsa_last_data_offset));
295         dsp->dsa_last_data_object = object;
296         dsp->dsa_last_data_offset = offset + lsize - 1;
297
298         /*
299          * If there is any kind of pending aggregation (currently either
300          * a grouping of free objects or free blocks), push it out to
301          * the stream, since aggregation can't be done across operations
302          * of different types.
303          */
304         if (dsp->dsa_pending_op != PENDING_NONE) {
305                 if (dump_record(dsp, NULL, 0) != 0)
306                         return (SET_ERROR(EINTR));
307                 dsp->dsa_pending_op = PENDING_NONE;
308         }
309         /* write a WRITE record */
310         bzero(dsp->dsa_drr, sizeof (dmu_replay_record_t));
311         dsp->dsa_drr->drr_type = DRR_WRITE;
312         drrw->drr_object = object;
313         drrw->drr_type = type;
314         drrw->drr_offset = offset;
315         drrw->drr_toguid = dsp->dsa_toguid;
316         drrw->drr_logical_size = lsize;
317
318         /* only set the compression fields if the buf is compressed */
319         if (lsize != psize) {
320                 ASSERT(dsp->dsa_featureflags & DMU_BACKUP_FEATURE_COMPRESSED);
321                 ASSERT(!BP_IS_EMBEDDED(bp));
322                 ASSERT(!BP_SHOULD_BYTESWAP(bp));
323                 ASSERT(!DMU_OT_IS_METADATA(BP_GET_TYPE(bp)));
324                 ASSERT3U(BP_GET_COMPRESS(bp), !=, ZIO_COMPRESS_OFF);
325                 ASSERT3S(psize, >, 0);
326                 ASSERT3S(lsize, >=, psize);
327
328                 drrw->drr_compressiontype = BP_GET_COMPRESS(bp);
329                 drrw->drr_compressed_size = psize;
330                 payload_size = drrw->drr_compressed_size;
331         } else {
332                 payload_size = drrw->drr_logical_size;
333         }
334
335         if (bp == NULL || BP_IS_EMBEDDED(bp)) {
336                 /*
337                  * There's no pre-computed checksum for partial-block
338                  * writes or embedded BP's, so (like
339                  * fletcher4-checkummed blocks) userland will have to
340                  * compute a dedup-capable checksum itself.
341                  */
342                 drrw->drr_checksumtype = ZIO_CHECKSUM_OFF;
343         } else {
344                 drrw->drr_checksumtype = BP_GET_CHECKSUM(bp);
345                 if (zio_checksum_table[drrw->drr_checksumtype].ci_flags &
346                     ZCHECKSUM_FLAG_DEDUP)
347                         drrw->drr_checksumflags |= DRR_CHECKSUM_DEDUP;
348                 DDK_SET_LSIZE(&drrw->drr_key, BP_GET_LSIZE(bp));
349                 DDK_SET_PSIZE(&drrw->drr_key, BP_GET_PSIZE(bp));
350                 DDK_SET_COMPRESS(&drrw->drr_key, BP_GET_COMPRESS(bp));
351                 drrw->drr_key.ddk_cksum = bp->blk_cksum;
352         }
353
354         if (dump_record(dsp, data, payload_size) != 0)
355                 return (SET_ERROR(EINTR));
356         return (0);
357 }
358
359 static int
360 dump_write_embedded(dmu_sendarg_t *dsp, uint64_t object, uint64_t offset,
361     int blksz, const blkptr_t *bp)
362 {
363         char buf[BPE_PAYLOAD_SIZE];
364         struct drr_write_embedded *drrw =
365             &(dsp->dsa_drr->drr_u.drr_write_embedded);
366
367         if (dsp->dsa_pending_op != PENDING_NONE) {
368                 if (dump_record(dsp, NULL, 0) != 0)
369                         return (EINTR);
370                 dsp->dsa_pending_op = PENDING_NONE;
371         }
372
373         ASSERT(BP_IS_EMBEDDED(bp));
374
375         bzero(dsp->dsa_drr, sizeof (dmu_replay_record_t));
376         dsp->dsa_drr->drr_type = DRR_WRITE_EMBEDDED;
377         drrw->drr_object = object;
378         drrw->drr_offset = offset;
379         drrw->drr_length = blksz;
380         drrw->drr_toguid = dsp->dsa_toguid;
381         drrw->drr_compression = BP_GET_COMPRESS(bp);
382         drrw->drr_etype = BPE_GET_ETYPE(bp);
383         drrw->drr_lsize = BPE_GET_LSIZE(bp);
384         drrw->drr_psize = BPE_GET_PSIZE(bp);
385
386         decode_embedded_bp_compressed(bp, buf);
387
388         if (dump_record(dsp, buf, P2ROUNDUP(drrw->drr_psize, 8)) != 0)
389                 return (EINTR);
390         return (0);
391 }
392
393 static int
394 dump_spill(dmu_sendarg_t *dsp, uint64_t object, int blksz, void *data)
395 {
396         struct drr_spill *drrs = &(dsp->dsa_drr->drr_u.drr_spill);
397
398         if (dsp->dsa_pending_op != PENDING_NONE) {
399                 if (dump_record(dsp, NULL, 0) != 0)
400                         return (SET_ERROR(EINTR));
401                 dsp->dsa_pending_op = PENDING_NONE;
402         }
403
404         /* write a SPILL record */
405         bzero(dsp->dsa_drr, sizeof (dmu_replay_record_t));
406         dsp->dsa_drr->drr_type = DRR_SPILL;
407         drrs->drr_object = object;
408         drrs->drr_length = blksz;
409         drrs->drr_toguid = dsp->dsa_toguid;
410
411         if (dump_record(dsp, data, blksz) != 0)
412                 return (SET_ERROR(EINTR));
413         return (0);
414 }
415
416 static int
417 dump_freeobjects(dmu_sendarg_t *dsp, uint64_t firstobj, uint64_t numobjs)
418 {
419         struct drr_freeobjects *drrfo = &(dsp->dsa_drr->drr_u.drr_freeobjects);
420
421         /*
422          * If there is a pending op, but it's not PENDING_FREEOBJECTS,
423          * push it out, since free block aggregation can only be done for
424          * blocks of the same type (i.e., DRR_FREE records can only be
425          * aggregated with other DRR_FREE records.  DRR_FREEOBJECTS records
426          * can only be aggregated with other DRR_FREEOBJECTS records.
427          */
428         if (dsp->dsa_pending_op != PENDING_NONE &&
429             dsp->dsa_pending_op != PENDING_FREEOBJECTS) {
430                 if (dump_record(dsp, NULL, 0) != 0)
431                         return (SET_ERROR(EINTR));
432                 dsp->dsa_pending_op = PENDING_NONE;
433         }
434         if (dsp->dsa_pending_op == PENDING_FREEOBJECTS) {
435                 /*
436                  * See whether this free object array can be aggregated
437                  * with pending one
438                  */
439                 if (drrfo->drr_firstobj + drrfo->drr_numobjs == firstobj) {
440                         drrfo->drr_numobjs += numobjs;
441                         return (0);
442                 } else {
443                         /* can't be aggregated.  Push out pending record */
444                         if (dump_record(dsp, NULL, 0) != 0)
445                                 return (SET_ERROR(EINTR));
446                         dsp->dsa_pending_op = PENDING_NONE;
447                 }
448         }
449
450         /* write a FREEOBJECTS record */
451         bzero(dsp->dsa_drr, sizeof (dmu_replay_record_t));
452         dsp->dsa_drr->drr_type = DRR_FREEOBJECTS;
453         drrfo->drr_firstobj = firstobj;
454         drrfo->drr_numobjs = numobjs;
455         drrfo->drr_toguid = dsp->dsa_toguid;
456
457         dsp->dsa_pending_op = PENDING_FREEOBJECTS;
458
459         return (0);
460 }
461
462 static int
463 dump_dnode(dmu_sendarg_t *dsp, uint64_t object, dnode_phys_t *dnp)
464 {
465         struct drr_object *drro = &(dsp->dsa_drr->drr_u.drr_object);
466
467         if (object < dsp->dsa_resume_object) {
468                 /*
469                  * Note: when resuming, we will visit all the dnodes in
470                  * the block of dnodes that we are resuming from.  In
471                  * this case it's unnecessary to send the dnodes prior to
472                  * the one we are resuming from.  We should be at most one
473                  * block's worth of dnodes behind the resume point.
474                  */
475                 ASSERT3U(dsp->dsa_resume_object - object, <,
476                     1 << (DNODE_BLOCK_SHIFT - DNODE_SHIFT));
477                 return (0);
478         }
479
480         if (dnp == NULL || dnp->dn_type == DMU_OT_NONE)
481                 return (dump_freeobjects(dsp, object, 1));
482
483         if (dsp->dsa_pending_op != PENDING_NONE) {
484                 if (dump_record(dsp, NULL, 0) != 0)
485                         return (SET_ERROR(EINTR));
486                 dsp->dsa_pending_op = PENDING_NONE;
487         }
488
489         /* write an OBJECT record */
490         bzero(dsp->dsa_drr, sizeof (dmu_replay_record_t));
491         dsp->dsa_drr->drr_type = DRR_OBJECT;
492         drro->drr_object = object;
493         drro->drr_type = dnp->dn_type;
494         drro->drr_bonustype = dnp->dn_bonustype;
495         drro->drr_blksz = dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT;
496         drro->drr_bonuslen = dnp->dn_bonuslen;
497         drro->drr_dn_slots = dnp->dn_extra_slots + 1;
498         drro->drr_checksumtype = dnp->dn_checksum;
499         drro->drr_compress = dnp->dn_compress;
500         drro->drr_toguid = dsp->dsa_toguid;
501
502         if (!(dsp->dsa_featureflags & DMU_BACKUP_FEATURE_LARGE_BLOCKS) &&
503             drro->drr_blksz > SPA_OLD_MAXBLOCKSIZE)
504                 drro->drr_blksz = SPA_OLD_MAXBLOCKSIZE;
505
506         if (dump_record(dsp, DN_BONUS(dnp),
507             P2ROUNDUP(dnp->dn_bonuslen, 8)) != 0) {
508                 return (SET_ERROR(EINTR));
509         }
510
511         /* Free anything past the end of the file. */
512         if (dump_free(dsp, object, (dnp->dn_maxblkid + 1) *
513             (dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT), -1ULL) != 0)
514                 return (SET_ERROR(EINTR));
515         if (dsp->dsa_err != 0)
516                 return (SET_ERROR(EINTR));
517         return (0);
518 }
519
520 static boolean_t
521 backup_do_embed(dmu_sendarg_t *dsp, const blkptr_t *bp)
522 {
523         if (!BP_IS_EMBEDDED(bp))
524                 return (B_FALSE);
525
526         /*
527          * Compression function must be legacy, or explicitly enabled.
528          */
529         if ((BP_GET_COMPRESS(bp) >= ZIO_COMPRESS_LEGACY_FUNCTIONS &&
530             !(dsp->dsa_featureflags & DMU_BACKUP_FEATURE_LZ4)))
531                 return (B_FALSE);
532
533         /*
534          * Embed type must be explicitly enabled.
535          */
536         switch (BPE_GET_ETYPE(bp)) {
537         case BP_EMBEDDED_TYPE_DATA:
538                 if (dsp->dsa_featureflags & DMU_BACKUP_FEATURE_EMBED_DATA)
539                         return (B_TRUE);
540                 break;
541         default:
542                 return (B_FALSE);
543         }
544         return (B_FALSE);
545 }
546
547 /*
548  * This is the callback function to traverse_dataset that acts as the worker
549  * thread for dmu_send_impl.
550  */
551 /*ARGSUSED*/
552 static int
553 send_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
554     const zbookmark_phys_t *zb, const struct dnode_phys *dnp, void *arg)
555 {
556         struct send_thread_arg *sta = arg;
557         struct send_block_record *record;
558         uint64_t record_size;
559         int err = 0;
560
561         ASSERT(zb->zb_object == DMU_META_DNODE_OBJECT ||
562             zb->zb_object >= sta->resume.zb_object);
563
564         if (sta->cancel)
565                 return (SET_ERROR(EINTR));
566
567         if (bp == NULL) {
568                 ASSERT3U(zb->zb_level, ==, ZB_DNODE_LEVEL);
569                 return (0);
570         } else if (zb->zb_level < 0) {
571                 return (0);
572         }
573
574         record = kmem_zalloc(sizeof (struct send_block_record), KM_SLEEP);
575         record->eos_marker = B_FALSE;
576         record->bp = *bp;
577         record->zb = *zb;
578         record->indblkshift = dnp->dn_indblkshift;
579         record->datablkszsec = dnp->dn_datablkszsec;
580         record_size = dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT;
581         bqueue_enqueue(&sta->q, record, record_size);
582
583         return (err);
584 }
585
586 /*
587  * This function kicks off the traverse_dataset.  It also handles setting the
588  * error code of the thread in case something goes wrong, and pushes the End of
589  * Stream record when the traverse_dataset call has finished.  If there is no
590  * dataset to traverse, the thread immediately pushes End of Stream marker.
591  */
592 static void
593 send_traverse_thread(void *arg)
594 {
595         struct send_thread_arg *st_arg = arg;
596         int err;
597         struct send_block_record *data;
598
599         if (st_arg->ds != NULL) {
600                 err = traverse_dataset_resume(st_arg->ds,
601                     st_arg->fromtxg, &st_arg->resume,
602                     st_arg->flags, send_cb, st_arg);
603
604                 if (err != EINTR)
605                         st_arg->error_code = err;
606         }
607         data = kmem_zalloc(sizeof (*data), KM_SLEEP);
608         data->eos_marker = B_TRUE;
609         bqueue_enqueue(&st_arg->q, data, 1);
610         thread_exit();
611 }
612
613 /*
614  * This function actually handles figuring out what kind of record needs to be
615  * dumped, reading the data (which has hopefully been prefetched), and calling
616  * the appropriate helper function.
617  */
618 static int
619 do_dump(dmu_sendarg_t *dsa, struct send_block_record *data)
620 {
621         dsl_dataset_t *ds = dmu_objset_ds(dsa->dsa_os);
622         const blkptr_t *bp = &data->bp;
623         const zbookmark_phys_t *zb = &data->zb;
624         uint8_t indblkshift = data->indblkshift;
625         uint16_t dblkszsec = data->datablkszsec;
626         spa_t *spa = ds->ds_dir->dd_pool->dp_spa;
627         dmu_object_type_t type = bp ? BP_GET_TYPE(bp) : DMU_OT_NONE;
628         int err = 0;
629
630         ASSERT3U(zb->zb_level, >=, 0);
631
632         ASSERT(zb->zb_object == DMU_META_DNODE_OBJECT ||
633             zb->zb_object >= dsa->dsa_resume_object);
634
635         if (zb->zb_object != DMU_META_DNODE_OBJECT &&
636             DMU_OBJECT_IS_SPECIAL(zb->zb_object)) {
637                 return (0);
638         } else if (BP_IS_HOLE(bp) &&
639             zb->zb_object == DMU_META_DNODE_OBJECT) {
640                 uint64_t span = BP_SPAN(dblkszsec, indblkshift, zb->zb_level);
641                 uint64_t dnobj = (zb->zb_blkid * span) >> DNODE_SHIFT;
642                 err = dump_freeobjects(dsa, dnobj, span >> DNODE_SHIFT);
643         } else if (BP_IS_HOLE(bp)) {
644                 uint64_t span = BP_SPAN(dblkszsec, indblkshift, zb->zb_level);
645                 uint64_t offset = zb->zb_blkid * span;
646                 err = dump_free(dsa, zb->zb_object, offset, span);
647         } else if (zb->zb_level > 0 || type == DMU_OT_OBJSET) {
648                 return (0);
649         } else if (type == DMU_OT_DNODE) {
650                 int epb = BP_GET_LSIZE(bp) >> DNODE_SHIFT;
651                 arc_flags_t aflags = ARC_FLAG_WAIT;
652                 arc_buf_t *abuf;
653
654                 ASSERT0(zb->zb_level);
655
656                 if (arc_read(NULL, spa, bp, arc_getbuf_func, &abuf,
657                     ZIO_PRIORITY_ASYNC_READ, ZIO_FLAG_CANFAIL,
658                     &aflags, zb) != 0)
659                         return (SET_ERROR(EIO));
660
661                 dnode_phys_t *blk = abuf->b_data;
662                 uint64_t dnobj = zb->zb_blkid * epb;
663                 for (int i = 0; i < epb; i += blk[i].dn_extra_slots + 1) {
664                         err = dump_dnode(dsa, dnobj + i, blk + i);
665                         if (err != 0)
666                                 break;
667                 }
668                 arc_buf_destroy(abuf, &abuf);
669         } else if (type == DMU_OT_SA) {
670                 arc_flags_t aflags = ARC_FLAG_WAIT;
671                 arc_buf_t *abuf;
672                 int blksz = BP_GET_LSIZE(bp);
673
674                 if (arc_read(NULL, spa, bp, arc_getbuf_func, &abuf,
675                     ZIO_PRIORITY_ASYNC_READ, ZIO_FLAG_CANFAIL,
676                     &aflags, zb) != 0)
677                         return (SET_ERROR(EIO));
678
679                 err = dump_spill(dsa, zb->zb_object, blksz, abuf->b_data);
680                 arc_buf_destroy(abuf, &abuf);
681         } else if (backup_do_embed(dsa, bp)) {
682                 /* it's an embedded level-0 block of a regular object */
683                 int blksz = dblkszsec << SPA_MINBLOCKSHIFT;
684                 ASSERT0(zb->zb_level);
685                 err = dump_write_embedded(dsa, zb->zb_object,
686                     zb->zb_blkid * blksz, blksz, bp);
687         } else {
688                 /* it's a level-0 block of a regular object */
689                 arc_flags_t aflags = ARC_FLAG_WAIT;
690                 arc_buf_t *abuf;
691                 int blksz = dblkszsec << SPA_MINBLOCKSHIFT;
692                 uint64_t offset;
693
694                 /*
695                  * If we have large blocks stored on disk but the send flags
696                  * don't allow us to send large blocks, we split the data from
697                  * the arc buf into chunks.
698                  */
699                 boolean_t split_large_blocks = blksz > SPA_OLD_MAXBLOCKSIZE &&
700                     !(dsa->dsa_featureflags & DMU_BACKUP_FEATURE_LARGE_BLOCKS);
701                 /*
702                  * We should only request compressed data from the ARC if all
703                  * the following are true:
704                  *  - stream compression was requested
705                  *  - we aren't splitting large blocks into smaller chunks
706                  *  - the data won't need to be byteswapped before sending
707                  *  - this isn't an embedded block
708                  *  - this isn't metadata (if receiving on a different endian
709                  *    system it can be byteswapped more easily)
710                  */
711                 boolean_t request_compressed =
712                     (dsa->dsa_featureflags & DMU_BACKUP_FEATURE_COMPRESSED) &&
713                     !split_large_blocks && !BP_SHOULD_BYTESWAP(bp) &&
714                     !BP_IS_EMBEDDED(bp) && !DMU_OT_IS_METADATA(BP_GET_TYPE(bp));
715
716                 ASSERT0(zb->zb_level);
717                 ASSERT(zb->zb_object > dsa->dsa_resume_object ||
718                     (zb->zb_object == dsa->dsa_resume_object &&
719                     zb->zb_blkid * blksz >= dsa->dsa_resume_offset));
720
721                 ASSERT0(zb->zb_level);
722                 ASSERT(zb->zb_object > dsa->dsa_resume_object ||
723                     (zb->zb_object == dsa->dsa_resume_object &&
724                     zb->zb_blkid * blksz >= dsa->dsa_resume_offset));
725
726                 ASSERT3U(blksz, ==, BP_GET_LSIZE(bp));
727
728                 enum zio_flag zioflags = ZIO_FLAG_CANFAIL;
729                 if (request_compressed)
730                         zioflags |= ZIO_FLAG_RAW;
731                 if (arc_read(NULL, spa, bp, arc_getbuf_func, &abuf,
732                     ZIO_PRIORITY_ASYNC_READ, zioflags, &aflags, zb) != 0) {
733                         if (zfs_send_corrupt_data) {
734                                 /* Send a block filled with 0x"zfs badd bloc" */
735                                 abuf = arc_alloc_buf(spa, &abuf, ARC_BUFC_DATA,
736                                     blksz);
737                                 uint64_t *ptr;
738                                 for (ptr = abuf->b_data;
739                                     (char *)ptr < (char *)abuf->b_data + blksz;
740                                     ptr++)
741                                         *ptr = 0x2f5baddb10cULL;
742                         } else {
743                                 return (SET_ERROR(EIO));
744                         }
745                 }
746
747                 offset = zb->zb_blkid * blksz;
748
749                 if (split_large_blocks) {
750                         ASSERT3U(arc_get_compression(abuf), ==,
751                             ZIO_COMPRESS_OFF);
752                         char *buf = abuf->b_data;
753                         while (blksz > 0 && err == 0) {
754                                 int n = MIN(blksz, SPA_OLD_MAXBLOCKSIZE);
755                                 err = dump_write(dsa, type, zb->zb_object,
756                                     offset, n, n, NULL, buf);
757                                 offset += n;
758                                 buf += n;
759                                 blksz -= n;
760                         }
761                 } else {
762                         err = dump_write(dsa, type, zb->zb_object, offset,
763                             blksz, arc_buf_size(abuf), bp, abuf->b_data);
764                 }
765                 arc_buf_destroy(abuf, &abuf);
766         }
767
768         ASSERT(err == 0 || err == EINTR);
769         return (err);
770 }
771
772 /*
773  * Pop the new data off the queue, and free the old data.
774  */
775 static struct send_block_record *
776 get_next_record(bqueue_t *bq, struct send_block_record *data)
777 {
778         struct send_block_record *tmp = bqueue_dequeue(bq);
779         kmem_free(data, sizeof (*data));
780         return (tmp);
781 }
782
783 /*
784  * Actually do the bulk of the work in a zfs send.
785  *
786  * Note: Releases dp using the specified tag.
787  */
788 static int
789 dmu_send_impl(void *tag, dsl_pool_t *dp, dsl_dataset_t *to_ds,
790     zfs_bookmark_phys_t *ancestor_zb, boolean_t is_clone,
791     boolean_t embedok, boolean_t large_block_ok, boolean_t compressok,
792     int outfd, uint64_t resumeobj, uint64_t resumeoff,
793 #ifdef illumos
794     vnode_t *vp, offset_t *off)
795 #else
796     struct file *fp, offset_t *off)
797 #endif
798 {
799         objset_t *os;
800         dmu_replay_record_t *drr;
801         dmu_sendarg_t *dsp;
802         int err;
803         uint64_t fromtxg = 0;
804         uint64_t featureflags = 0;
805         struct send_thread_arg to_arg = { 0 };
806
807         err = dmu_objset_from_ds(to_ds, &os);
808         if (err != 0) {
809                 dsl_pool_rele(dp, tag);
810                 return (err);
811         }
812
813         drr = kmem_zalloc(sizeof (dmu_replay_record_t), KM_SLEEP);
814         drr->drr_type = DRR_BEGIN;
815         drr->drr_u.drr_begin.drr_magic = DMU_BACKUP_MAGIC;
816         DMU_SET_STREAM_HDRTYPE(drr->drr_u.drr_begin.drr_versioninfo,
817             DMU_SUBSTREAM);
818
819 #ifdef _KERNEL
820         if (dmu_objset_type(os) == DMU_OST_ZFS) {
821                 uint64_t version;
822                 if (zfs_get_zplprop(os, ZFS_PROP_VERSION, &version) != 0) {
823                         kmem_free(drr, sizeof (dmu_replay_record_t));
824                         dsl_pool_rele(dp, tag);
825                         return (SET_ERROR(EINVAL));
826                 }
827                 if (version >= ZPL_VERSION_SA) {
828                         featureflags |= DMU_BACKUP_FEATURE_SA_SPILL;
829                 }
830         }
831 #endif
832
833         if (large_block_ok && to_ds->ds_feature_inuse[SPA_FEATURE_LARGE_BLOCKS])
834                 featureflags |= DMU_BACKUP_FEATURE_LARGE_BLOCKS;
835         if (to_ds->ds_feature_inuse[SPA_FEATURE_LARGE_DNODE])
836                 featureflags |= DMU_BACKUP_FEATURE_LARGE_DNODE;
837         if (embedok &&
838             spa_feature_is_active(dp->dp_spa, SPA_FEATURE_EMBEDDED_DATA)) {
839                 featureflags |= DMU_BACKUP_FEATURE_EMBED_DATA;
840                 if (spa_feature_is_active(dp->dp_spa, SPA_FEATURE_LZ4_COMPRESS))
841                         featureflags |= DMU_BACKUP_FEATURE_LZ4;
842         }
843         if (compressok) {
844                 featureflags |= DMU_BACKUP_FEATURE_COMPRESSED;
845         }
846         if ((featureflags &
847             (DMU_BACKUP_FEATURE_EMBED_DATA | DMU_BACKUP_FEATURE_COMPRESSED)) !=
848             0 && spa_feature_is_active(dp->dp_spa, SPA_FEATURE_LZ4_COMPRESS)) {
849                 featureflags |= DMU_BACKUP_FEATURE_LZ4;
850         }
851
852         if (resumeobj != 0 || resumeoff != 0) {
853                 featureflags |= DMU_BACKUP_FEATURE_RESUMING;
854         }
855
856         DMU_SET_FEATUREFLAGS(drr->drr_u.drr_begin.drr_versioninfo,
857             featureflags);
858
859         drr->drr_u.drr_begin.drr_creation_time =
860             dsl_dataset_phys(to_ds)->ds_creation_time;
861         drr->drr_u.drr_begin.drr_type = dmu_objset_type(os);
862         if (is_clone)
863                 drr->drr_u.drr_begin.drr_flags |= DRR_FLAG_CLONE;
864         drr->drr_u.drr_begin.drr_toguid = dsl_dataset_phys(to_ds)->ds_guid;
865         if (dsl_dataset_phys(to_ds)->ds_flags & DS_FLAG_CI_DATASET)
866                 drr->drr_u.drr_begin.drr_flags |= DRR_FLAG_CI_DATA;
867         if (zfs_send_set_freerecords_bit)
868                 drr->drr_u.drr_begin.drr_flags |= DRR_FLAG_FREERECORDS;
869
870         if (ancestor_zb != NULL) {
871                 drr->drr_u.drr_begin.drr_fromguid =
872                     ancestor_zb->zbm_guid;
873                 fromtxg = ancestor_zb->zbm_creation_txg;
874         }
875         dsl_dataset_name(to_ds, drr->drr_u.drr_begin.drr_toname);
876         if (!to_ds->ds_is_snapshot) {
877                 (void) strlcat(drr->drr_u.drr_begin.drr_toname, "@--head--",
878                     sizeof (drr->drr_u.drr_begin.drr_toname));
879         }
880
881         dsp = kmem_zalloc(sizeof (dmu_sendarg_t), KM_SLEEP);
882
883         dsp->dsa_drr = drr;
884         dsp->dsa_outfd = outfd;
885         dsp->dsa_proc = curproc;
886         dsp->dsa_td = curthread;
887         dsp->dsa_fp = fp;
888         dsp->dsa_os = os;
889         dsp->dsa_off = off;
890         dsp->dsa_toguid = dsl_dataset_phys(to_ds)->ds_guid;
891         dsp->dsa_pending_op = PENDING_NONE;
892         dsp->dsa_featureflags = featureflags;
893         dsp->dsa_resume_object = resumeobj;
894         dsp->dsa_resume_offset = resumeoff;
895
896         mutex_enter(&to_ds->ds_sendstream_lock);
897         list_insert_head(&to_ds->ds_sendstreams, dsp);
898         mutex_exit(&to_ds->ds_sendstream_lock);
899
900         dsl_dataset_long_hold(to_ds, FTAG);
901         dsl_pool_rele(dp, tag);
902
903         void *payload = NULL;
904         size_t payload_len = 0;
905         if (resumeobj != 0 || resumeoff != 0) {
906                 dmu_object_info_t to_doi;
907                 err = dmu_object_info(os, resumeobj, &to_doi);
908                 if (err != 0)
909                         goto out;
910                 SET_BOOKMARK(&to_arg.resume, to_ds->ds_object, resumeobj, 0,
911                     resumeoff / to_doi.doi_data_block_size);
912
913                 nvlist_t *nvl = fnvlist_alloc();
914                 fnvlist_add_uint64(nvl, "resume_object", resumeobj);
915                 fnvlist_add_uint64(nvl, "resume_offset", resumeoff);
916                 payload = fnvlist_pack(nvl, &payload_len);
917                 drr->drr_payloadlen = payload_len;
918                 fnvlist_free(nvl);
919         }
920
921         err = dump_record(dsp, payload, payload_len);
922         fnvlist_pack_free(payload, payload_len);
923         if (err != 0) {
924                 err = dsp->dsa_err;
925                 goto out;
926         }
927
928         err = bqueue_init(&to_arg.q, zfs_send_queue_length,
929             offsetof(struct send_block_record, ln));
930         to_arg.error_code = 0;
931         to_arg.cancel = B_FALSE;
932         to_arg.ds = to_ds;
933         to_arg.fromtxg = fromtxg;
934         to_arg.flags = TRAVERSE_PRE | TRAVERSE_PREFETCH;
935         (void) thread_create(NULL, 0, send_traverse_thread, &to_arg, 0, &p0,
936             TS_RUN, minclsyspri);
937
938         struct send_block_record *to_data;
939         to_data = bqueue_dequeue(&to_arg.q);
940
941         while (!to_data->eos_marker && err == 0) {
942                 err = do_dump(dsp, to_data);
943                 to_data = get_next_record(&to_arg.q, to_data);
944                 if (issig(JUSTLOOKING) && issig(FORREAL))
945                         err = EINTR;
946         }
947
948         if (err != 0) {
949                 to_arg.cancel = B_TRUE;
950                 while (!to_data->eos_marker) {
951                         to_data = get_next_record(&to_arg.q, to_data);
952                 }
953         }
954         kmem_free(to_data, sizeof (*to_data));
955
956         bqueue_destroy(&to_arg.q);
957
958         if (err == 0 && to_arg.error_code != 0)
959                 err = to_arg.error_code;
960
961         if (err != 0)
962                 goto out;
963
964         if (dsp->dsa_pending_op != PENDING_NONE)
965                 if (dump_record(dsp, NULL, 0) != 0)
966                         err = SET_ERROR(EINTR);
967
968         if (err != 0) {
969                 if (err == EINTR && dsp->dsa_err != 0)
970                         err = dsp->dsa_err;
971                 goto out;
972         }
973
974         bzero(drr, sizeof (dmu_replay_record_t));
975         drr->drr_type = DRR_END;
976         drr->drr_u.drr_end.drr_checksum = dsp->dsa_zc;
977         drr->drr_u.drr_end.drr_toguid = dsp->dsa_toguid;
978
979         if (dump_record(dsp, NULL, 0) != 0)
980                 err = dsp->dsa_err;
981
982 out:
983         mutex_enter(&to_ds->ds_sendstream_lock);
984         list_remove(&to_ds->ds_sendstreams, dsp);
985         mutex_exit(&to_ds->ds_sendstream_lock);
986
987         VERIFY(err != 0 || (dsp->dsa_sent_begin && dsp->dsa_sent_end));
988
989         kmem_free(drr, sizeof (dmu_replay_record_t));
990         kmem_free(dsp, sizeof (dmu_sendarg_t));
991
992         dsl_dataset_long_rele(to_ds, FTAG);
993
994         return (err);
995 }
996
997 int
998 dmu_send_obj(const char *pool, uint64_t tosnap, uint64_t fromsnap,
999     boolean_t embedok, boolean_t large_block_ok, boolean_t compressok,
1000 #ifdef illumos
1001     int outfd, vnode_t *vp, offset_t *off)
1002 #else
1003     int outfd, struct file *fp, offset_t *off)
1004 #endif
1005 {
1006         dsl_pool_t *dp;
1007         dsl_dataset_t *ds;
1008         dsl_dataset_t *fromds = NULL;
1009         int err;
1010
1011         err = dsl_pool_hold(pool, FTAG, &dp);
1012         if (err != 0)
1013                 return (err);
1014
1015         err = dsl_dataset_hold_obj(dp, tosnap, FTAG, &ds);
1016         if (err != 0) {
1017                 dsl_pool_rele(dp, FTAG);
1018                 return (err);
1019         }
1020
1021         if (fromsnap != 0) {
1022                 zfs_bookmark_phys_t zb;
1023                 boolean_t is_clone;
1024
1025                 err = dsl_dataset_hold_obj(dp, fromsnap, FTAG, &fromds);
1026                 if (err != 0) {
1027                         dsl_dataset_rele(ds, FTAG);
1028                         dsl_pool_rele(dp, FTAG);
1029                         return (err);
1030                 }
1031                 if (!dsl_dataset_is_before(ds, fromds, 0))
1032                         err = SET_ERROR(EXDEV);
1033                 zb.zbm_creation_time =
1034                     dsl_dataset_phys(fromds)->ds_creation_time;
1035                 zb.zbm_creation_txg = dsl_dataset_phys(fromds)->ds_creation_txg;
1036                 zb.zbm_guid = dsl_dataset_phys(fromds)->ds_guid;
1037                 is_clone = (fromds->ds_dir != ds->ds_dir);
1038                 dsl_dataset_rele(fromds, FTAG);
1039                 err = dmu_send_impl(FTAG, dp, ds, &zb, is_clone,
1040                     embedok, large_block_ok, compressok, outfd, 0, 0, fp, off);
1041         } else {
1042                 err = dmu_send_impl(FTAG, dp, ds, NULL, B_FALSE,
1043                     embedok, large_block_ok, compressok, outfd, 0, 0, fp, off);
1044         }
1045         dsl_dataset_rele(ds, FTAG);
1046         return (err);
1047 }
1048
1049 int
1050 dmu_send(const char *tosnap, const char *fromsnap, boolean_t embedok,
1051     boolean_t large_block_ok, boolean_t compressok, int outfd,
1052     uint64_t resumeobj, uint64_t resumeoff,
1053 #ifdef illumos
1054     vnode_t *vp, offset_t *off)
1055 #else
1056     struct file *fp, offset_t *off)
1057 #endif
1058 {
1059         dsl_pool_t *dp;
1060         dsl_dataset_t *ds;
1061         int err;
1062         boolean_t owned = B_FALSE;
1063
1064         if (fromsnap != NULL && strpbrk(fromsnap, "@#") == NULL)
1065                 return (SET_ERROR(EINVAL));
1066
1067         err = dsl_pool_hold(tosnap, FTAG, &dp);
1068         if (err != 0)
1069                 return (err);
1070
1071         if (strchr(tosnap, '@') == NULL && spa_writeable(dp->dp_spa)) {
1072                 /*
1073                  * We are sending a filesystem or volume.  Ensure
1074                  * that it doesn't change by owning the dataset.
1075                  */
1076                 err = dsl_dataset_own(dp, tosnap, FTAG, &ds);
1077                 owned = B_TRUE;
1078         } else {
1079                 err = dsl_dataset_hold(dp, tosnap, FTAG, &ds);
1080         }
1081         if (err != 0) {
1082                 dsl_pool_rele(dp, FTAG);
1083                 return (err);
1084         }
1085
1086         if (fromsnap != NULL) {
1087                 zfs_bookmark_phys_t zb;
1088                 boolean_t is_clone = B_FALSE;
1089                 int fsnamelen = strchr(tosnap, '@') - tosnap;
1090
1091                 /*
1092                  * If the fromsnap is in a different filesystem, then
1093                  * mark the send stream as a clone.
1094                  */
1095                 if (strncmp(tosnap, fromsnap, fsnamelen) != 0 ||
1096                     (fromsnap[fsnamelen] != '@' &&
1097                     fromsnap[fsnamelen] != '#')) {
1098                         is_clone = B_TRUE;
1099                 }
1100
1101                 if (strchr(fromsnap, '@')) {
1102                         dsl_dataset_t *fromds;
1103                         err = dsl_dataset_hold(dp, fromsnap, FTAG, &fromds);
1104                         if (err == 0) {
1105                                 if (!dsl_dataset_is_before(ds, fromds, 0))
1106                                         err = SET_ERROR(EXDEV);
1107                                 zb.zbm_creation_time =
1108                                     dsl_dataset_phys(fromds)->ds_creation_time;
1109                                 zb.zbm_creation_txg =
1110                                     dsl_dataset_phys(fromds)->ds_creation_txg;
1111                                 zb.zbm_guid = dsl_dataset_phys(fromds)->ds_guid;
1112                                 is_clone = (ds->ds_dir != fromds->ds_dir);
1113                                 dsl_dataset_rele(fromds, FTAG);
1114                         }
1115                 } else {
1116                         err = dsl_bookmark_lookup(dp, fromsnap, ds, &zb);
1117                 }
1118                 if (err != 0) {
1119                         dsl_dataset_rele(ds, FTAG);
1120                         dsl_pool_rele(dp, FTAG);
1121                         return (err);
1122                 }
1123                 err = dmu_send_impl(FTAG, dp, ds, &zb, is_clone,
1124                     embedok, large_block_ok, compressok,
1125                     outfd, resumeobj, resumeoff, fp, off);
1126         } else {
1127                 err = dmu_send_impl(FTAG, dp, ds, NULL, B_FALSE,
1128                     embedok, large_block_ok, compressok,
1129                     outfd, resumeobj, resumeoff, fp, off);
1130         }
1131         if (owned)
1132                 dsl_dataset_disown(ds, FTAG);
1133         else
1134                 dsl_dataset_rele(ds, FTAG);
1135         return (err);
1136 }
1137
1138 static int
1139 dmu_adjust_send_estimate_for_indirects(dsl_dataset_t *ds, uint64_t uncompressed,
1140     uint64_t compressed, boolean_t stream_compressed, uint64_t *sizep)
1141 {
1142         int err = 0;
1143         uint64_t size;
1144         /*
1145          * Assume that space (both on-disk and in-stream) is dominated by
1146          * data.  We will adjust for indirect blocks and the copies property,
1147          * but ignore per-object space used (eg, dnodes and DRR_OBJECT records).
1148          */
1149         uint64_t recordsize;
1150         uint64_t record_count;
1151         objset_t *os;
1152         VERIFY0(dmu_objset_from_ds(ds, &os));
1153
1154         /* Assume all (uncompressed) blocks are recordsize. */
1155         if (zfs_override_estimate_recordsize != 0) {
1156                 recordsize = zfs_override_estimate_recordsize;
1157         } else if (os->os_phys->os_type == DMU_OST_ZVOL) {
1158                 err = dsl_prop_get_int_ds(ds,
1159                     zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE), &recordsize);
1160         } else {
1161                 err = dsl_prop_get_int_ds(ds,
1162                     zfs_prop_to_name(ZFS_PROP_RECORDSIZE), &recordsize);
1163         }
1164         if (err != 0)
1165                 return (err);
1166         record_count = uncompressed / recordsize;
1167
1168         /*
1169          * If we're estimating a send size for a compressed stream, use the
1170          * compressed data size to estimate the stream size. Otherwise, use the
1171          * uncompressed data size.
1172          */
1173         size = stream_compressed ? compressed : uncompressed;
1174
1175         /*
1176          * Subtract out approximate space used by indirect blocks.
1177          * Assume most space is used by data blocks (non-indirect, non-dnode).
1178          * Assume no ditto blocks or internal fragmentation.
1179          *
1180          * Therefore, space used by indirect blocks is sizeof(blkptr_t) per
1181          * block.
1182          */
1183         size -= record_count * sizeof (blkptr_t);
1184
1185         /* Add in the space for the record associated with each block. */
1186         size += record_count * sizeof (dmu_replay_record_t);
1187
1188         *sizep = size;
1189
1190         return (0);
1191 }
1192
1193 int
1194 dmu_send_estimate(dsl_dataset_t *ds, dsl_dataset_t *fromds,
1195     boolean_t stream_compressed, uint64_t *sizep)
1196 {
1197         dsl_pool_t *dp = ds->ds_dir->dd_pool;
1198         int err;
1199         uint64_t uncomp, comp;
1200
1201         ASSERT(dsl_pool_config_held(dp));
1202
1203         /* tosnap must be a snapshot */
1204         if (!ds->ds_is_snapshot)
1205                 return (SET_ERROR(EINVAL));
1206
1207         /* fromsnap, if provided, must be a snapshot */
1208         if (fromds != NULL && !fromds->ds_is_snapshot)
1209                 return (SET_ERROR(EINVAL));
1210
1211         /*
1212          * fromsnap must be an earlier snapshot from the same fs as tosnap,
1213          * or the origin's fs.
1214          */
1215         if (fromds != NULL && !dsl_dataset_is_before(ds, fromds, 0))
1216                 return (SET_ERROR(EXDEV));
1217
1218         /* Get compressed and uncompressed size estimates of changed data. */
1219         if (fromds == NULL) {
1220                 uncomp = dsl_dataset_phys(ds)->ds_uncompressed_bytes;
1221                 comp = dsl_dataset_phys(ds)->ds_compressed_bytes;
1222         } else {
1223                 uint64_t used;
1224                 err = dsl_dataset_space_written(fromds, ds,
1225                     &used, &comp, &uncomp);
1226                 if (err != 0)
1227                         return (err);
1228         }
1229
1230         err = dmu_adjust_send_estimate_for_indirects(ds, uncomp, comp,
1231             stream_compressed, sizep);
1232         /*
1233          * Add the size of the BEGIN and END records to the estimate.
1234          */
1235         *sizep += 2 * sizeof (dmu_replay_record_t);
1236         return (err);
1237 }
1238
1239 struct calculate_send_arg {
1240         uint64_t uncompressed;
1241         uint64_t compressed;
1242 };
1243
1244 /*
1245  * Simple callback used to traverse the blocks of a snapshot and sum their
1246  * uncompressed and compressed sizes.
1247  */
1248 /* ARGSUSED */
1249 static int
1250 dmu_calculate_send_traversal(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
1251     const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
1252 {
1253         struct calculate_send_arg *space = arg;
1254         if (bp != NULL && !BP_IS_HOLE(bp)) {
1255                 space->uncompressed += BP_GET_UCSIZE(bp);
1256                 space->compressed += BP_GET_PSIZE(bp);
1257         }
1258         return (0);
1259 }
1260
1261 /*
1262  * Given a desination snapshot and a TXG, calculate the approximate size of a
1263  * send stream sent from that TXG. from_txg may be zero, indicating that the
1264  * whole snapshot will be sent.
1265  */
1266 int
1267 dmu_send_estimate_from_txg(dsl_dataset_t *ds, uint64_t from_txg,
1268     boolean_t stream_compressed, uint64_t *sizep)
1269 {
1270         dsl_pool_t *dp = ds->ds_dir->dd_pool;
1271         int err;
1272         struct calculate_send_arg size = { 0 };
1273
1274         ASSERT(dsl_pool_config_held(dp));
1275
1276         /* tosnap must be a snapshot */
1277         if (!ds->ds_is_snapshot)
1278                 return (SET_ERROR(EINVAL));
1279
1280         /* verify that from_txg is before the provided snapshot was taken */
1281         if (from_txg >= dsl_dataset_phys(ds)->ds_creation_txg) {
1282                 return (SET_ERROR(EXDEV));
1283         }
1284
1285         /*
1286          * traverse the blocks of the snapshot with birth times after
1287          * from_txg, summing their uncompressed size
1288          */
1289         err = traverse_dataset(ds, from_txg, TRAVERSE_POST,
1290             dmu_calculate_send_traversal, &size);
1291         if (err)
1292                 return (err);
1293
1294         err = dmu_adjust_send_estimate_for_indirects(ds, size.uncompressed,
1295             size.compressed, stream_compressed, sizep);
1296         return (err);
1297 }
1298
1299 typedef struct dmu_recv_begin_arg {
1300         const char *drba_origin;
1301         dmu_recv_cookie_t *drba_cookie;
1302         cred_t *drba_cred;
1303         uint64_t drba_snapobj;
1304 } dmu_recv_begin_arg_t;
1305
1306 static int
1307 recv_begin_check_existing_impl(dmu_recv_begin_arg_t *drba, dsl_dataset_t *ds,
1308     uint64_t fromguid)
1309 {
1310         uint64_t val;
1311         int error;
1312         dsl_pool_t *dp = ds->ds_dir->dd_pool;
1313
1314         /* Temporary clone name must not exist. */
1315         error = zap_lookup(dp->dp_meta_objset,
1316             dsl_dir_phys(ds->ds_dir)->dd_child_dir_zapobj, recv_clone_name,
1317             8, 1, &val);
1318         if (error != ENOENT)
1319                 return (error == 0 ? SET_ERROR(EBUSY) : error);
1320
1321         /* Resume state must not be set. */
1322         if (dsl_dataset_has_resume_receive_state(ds))
1323                 return (SET_ERROR(EBUSY));
1324
1325         /* New snapshot name must not exist. */
1326         error = zap_lookup(dp->dp_meta_objset,
1327             dsl_dataset_phys(ds)->ds_snapnames_zapobj,
1328             drba->drba_cookie->drc_tosnap, 8, 1, &val);
1329         if (error != ENOENT)
1330                 return (error == 0 ? SET_ERROR(EEXIST) : error);
1331
1332         /*
1333          * Check snapshot limit before receiving. We'll recheck again at the
1334          * end, but might as well abort before receiving if we're already over
1335          * the limit.
1336          *
1337          * Note that we do not check the file system limit with
1338          * dsl_dir_fscount_check because the temporary %clones don't count
1339          * against that limit.
1340          */
1341         error = dsl_fs_ss_limit_check(ds->ds_dir, 1, ZFS_PROP_SNAPSHOT_LIMIT,
1342             NULL, drba->drba_cred);
1343         if (error != 0)
1344                 return (error);
1345
1346         if (fromguid != 0) {
1347                 dsl_dataset_t *snap;
1348                 uint64_t obj = dsl_dataset_phys(ds)->ds_prev_snap_obj;
1349
1350                 /* Find snapshot in this dir that matches fromguid. */
1351                 while (obj != 0) {
1352                         error = dsl_dataset_hold_obj(dp, obj, FTAG,
1353                             &snap);
1354                         if (error != 0)
1355                                 return (SET_ERROR(ENODEV));
1356                         if (snap->ds_dir != ds->ds_dir) {
1357                                 dsl_dataset_rele(snap, FTAG);
1358                                 return (SET_ERROR(ENODEV));
1359                         }
1360                         if (dsl_dataset_phys(snap)->ds_guid == fromguid)
1361                                 break;
1362                         obj = dsl_dataset_phys(snap)->ds_prev_snap_obj;
1363                         dsl_dataset_rele(snap, FTAG);
1364                 }
1365                 if (obj == 0)
1366                         return (SET_ERROR(ENODEV));
1367
1368                 if (drba->drba_cookie->drc_force) {
1369                         drba->drba_snapobj = obj;
1370                 } else {
1371                         /*
1372                          * If we are not forcing, there must be no
1373                          * changes since fromsnap.
1374                          */
1375                         if (dsl_dataset_modified_since_snap(ds, snap)) {
1376                                 dsl_dataset_rele(snap, FTAG);
1377                                 return (SET_ERROR(ETXTBSY));
1378                         }
1379                         drba->drba_snapobj = ds->ds_prev->ds_object;
1380                 }
1381
1382                 dsl_dataset_rele(snap, FTAG);
1383         } else {
1384                 /* if full, then must be forced */
1385                 if (!drba->drba_cookie->drc_force)
1386                         return (SET_ERROR(EEXIST));
1387                 /* start from $ORIGIN@$ORIGIN, if supported */
1388                 drba->drba_snapobj = dp->dp_origin_snap != NULL ?
1389                     dp->dp_origin_snap->ds_object : 0;
1390         }
1391
1392         return (0);
1393
1394 }
1395
1396 static int
1397 dmu_recv_begin_check(void *arg, dmu_tx_t *tx)
1398 {
1399         dmu_recv_begin_arg_t *drba = arg;
1400         dsl_pool_t *dp = dmu_tx_pool(tx);
1401         struct drr_begin *drrb = drba->drba_cookie->drc_drrb;
1402         uint64_t fromguid = drrb->drr_fromguid;
1403         int flags = drrb->drr_flags;
1404         int error;
1405         uint64_t featureflags = DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo);
1406         dsl_dataset_t *ds;
1407         const char *tofs = drba->drba_cookie->drc_tofs;
1408
1409         /* already checked */
1410         ASSERT3U(drrb->drr_magic, ==, DMU_BACKUP_MAGIC);
1411         ASSERT(!(featureflags & DMU_BACKUP_FEATURE_RESUMING));
1412
1413         if (DMU_GET_STREAM_HDRTYPE(drrb->drr_versioninfo) ==
1414             DMU_COMPOUNDSTREAM ||
1415             drrb->drr_type >= DMU_OST_NUMTYPES ||
1416             ((flags & DRR_FLAG_CLONE) && drba->drba_origin == NULL))
1417                 return (SET_ERROR(EINVAL));
1418
1419         /* Verify pool version supports SA if SA_SPILL feature set */
1420         if ((featureflags & DMU_BACKUP_FEATURE_SA_SPILL) &&
1421             spa_version(dp->dp_spa) < SPA_VERSION_SA)
1422                 return (SET_ERROR(ENOTSUP));
1423
1424         if (drba->drba_cookie->drc_resumable &&
1425             !spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_EXTENSIBLE_DATASET))
1426                 return (SET_ERROR(ENOTSUP));
1427
1428         /*
1429          * The receiving code doesn't know how to translate a WRITE_EMBEDDED
1430          * record to a plain WRITE record, so the pool must have the
1431          * EMBEDDED_DATA feature enabled if the stream has WRITE_EMBEDDED
1432          * records.  Same with WRITE_EMBEDDED records that use LZ4 compression.
1433          */
1434         if ((featureflags & DMU_BACKUP_FEATURE_EMBED_DATA) &&
1435             !spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_EMBEDDED_DATA))
1436                 return (SET_ERROR(ENOTSUP));
1437         if ((featureflags & DMU_BACKUP_FEATURE_LZ4) &&
1438             !spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_LZ4_COMPRESS))
1439                 return (SET_ERROR(ENOTSUP));
1440
1441         /*
1442          * The receiving code doesn't know how to translate large blocks
1443          * to smaller ones, so the pool must have the LARGE_BLOCKS
1444          * feature enabled if the stream has LARGE_BLOCKS. Same with
1445          * large dnodes.
1446          */
1447         if ((featureflags & DMU_BACKUP_FEATURE_LARGE_BLOCKS) &&
1448             !spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_LARGE_BLOCKS))
1449                 return (SET_ERROR(ENOTSUP));
1450         if ((featureflags & DMU_BACKUP_FEATURE_LARGE_DNODE) &&
1451             !spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_LARGE_DNODE))
1452                 return (SET_ERROR(ENOTSUP));
1453
1454         error = dsl_dataset_hold(dp, tofs, FTAG, &ds);
1455         if (error == 0) {
1456                 /* target fs already exists; recv into temp clone */
1457
1458                 /* Can't recv a clone into an existing fs */
1459                 if (flags & DRR_FLAG_CLONE || drba->drba_origin) {
1460                         dsl_dataset_rele(ds, FTAG);
1461                         return (SET_ERROR(EINVAL));
1462                 }
1463
1464                 error = recv_begin_check_existing_impl(drba, ds, fromguid);
1465                 dsl_dataset_rele(ds, FTAG);
1466         } else if (error == ENOENT) {
1467                 /* target fs does not exist; must be a full backup or clone */
1468                 char buf[ZFS_MAX_DATASET_NAME_LEN];
1469
1470                 /*
1471                  * If it's a non-clone incremental, we are missing the
1472                  * target fs, so fail the recv.
1473                  */
1474                 if (fromguid != 0 && !(flags & DRR_FLAG_CLONE ||
1475                     drba->drba_origin))
1476                         return (SET_ERROR(ENOENT));
1477
1478                 /*
1479                  * If we're receiving a full send as a clone, and it doesn't
1480                  * contain all the necessary free records and freeobject
1481                  * records, reject it.
1482                  */
1483                 if (fromguid == 0 && drba->drba_origin &&
1484                     !(flags & DRR_FLAG_FREERECORDS))
1485                         return (SET_ERROR(EINVAL));
1486
1487                 /* Open the parent of tofs */
1488                 ASSERT3U(strlen(tofs), <, sizeof (buf));
1489                 (void) strlcpy(buf, tofs, strrchr(tofs, '/') - tofs + 1);
1490                 error = dsl_dataset_hold(dp, buf, FTAG, &ds);
1491                 if (error != 0)
1492                         return (error);
1493
1494                 /*
1495                  * Check filesystem and snapshot limits before receiving. We'll
1496                  * recheck snapshot limits again at the end (we create the
1497                  * filesystems and increment those counts during begin_sync).
1498                  */
1499                 error = dsl_fs_ss_limit_check(ds->ds_dir, 1,
1500                     ZFS_PROP_FILESYSTEM_LIMIT, NULL, drba->drba_cred);
1501                 if (error != 0) {
1502                         dsl_dataset_rele(ds, FTAG);
1503                         return (error);
1504                 }
1505
1506                 error = dsl_fs_ss_limit_check(ds->ds_dir, 1,
1507                     ZFS_PROP_SNAPSHOT_LIMIT, NULL, drba->drba_cred);
1508                 if (error != 0) {
1509                         dsl_dataset_rele(ds, FTAG);
1510                         return (error);
1511                 }
1512
1513                 if (drba->drba_origin != NULL) {
1514                         dsl_dataset_t *origin;
1515                         error = dsl_dataset_hold(dp, drba->drba_origin,
1516                             FTAG, &origin);
1517                         if (error != 0) {
1518                                 dsl_dataset_rele(ds, FTAG);
1519                                 return (error);
1520                         }
1521                         if (!origin->ds_is_snapshot) {
1522                                 dsl_dataset_rele(origin, FTAG);
1523                                 dsl_dataset_rele(ds, FTAG);
1524                                 return (SET_ERROR(EINVAL));
1525                         }
1526                         if (dsl_dataset_phys(origin)->ds_guid != fromguid &&
1527                             fromguid != 0) {
1528                                 dsl_dataset_rele(origin, FTAG);
1529                                 dsl_dataset_rele(ds, FTAG);
1530                                 return (SET_ERROR(ENODEV));
1531                         }
1532                         dsl_dataset_rele(origin, FTAG);
1533                 }
1534                 dsl_dataset_rele(ds, FTAG);
1535                 error = 0;
1536         }
1537         return (error);
1538 }
1539
1540 static void
1541 dmu_recv_begin_sync(void *arg, dmu_tx_t *tx)
1542 {
1543         dmu_recv_begin_arg_t *drba = arg;
1544         dsl_pool_t *dp = dmu_tx_pool(tx);
1545         objset_t *mos = dp->dp_meta_objset;
1546         struct drr_begin *drrb = drba->drba_cookie->drc_drrb;
1547         const char *tofs = drba->drba_cookie->drc_tofs;
1548         dsl_dataset_t *ds, *newds;
1549         uint64_t dsobj;
1550         int error;
1551         uint64_t crflags = 0;
1552
1553         if (drrb->drr_flags & DRR_FLAG_CI_DATA)
1554                 crflags |= DS_FLAG_CI_DATASET;
1555
1556         error = dsl_dataset_hold(dp, tofs, FTAG, &ds);
1557         if (error == 0) {
1558                 /* create temporary clone */
1559                 dsl_dataset_t *snap = NULL;
1560                 if (drba->drba_snapobj != 0) {
1561                         VERIFY0(dsl_dataset_hold_obj(dp,
1562                             drba->drba_snapobj, FTAG, &snap));
1563                 }
1564                 dsobj = dsl_dataset_create_sync(ds->ds_dir, recv_clone_name,
1565                     snap, crflags, drba->drba_cred, tx);
1566                 if (drba->drba_snapobj != 0)
1567                         dsl_dataset_rele(snap, FTAG);
1568                 dsl_dataset_rele(ds, FTAG);
1569         } else {
1570                 dsl_dir_t *dd;
1571                 const char *tail;
1572                 dsl_dataset_t *origin = NULL;
1573
1574                 VERIFY0(dsl_dir_hold(dp, tofs, FTAG, &dd, &tail));
1575
1576                 if (drba->drba_origin != NULL) {
1577                         VERIFY0(dsl_dataset_hold(dp, drba->drba_origin,
1578                             FTAG, &origin));
1579                 }
1580
1581                 /* Create new dataset. */
1582                 dsobj = dsl_dataset_create_sync(dd,
1583                     strrchr(tofs, '/') + 1,
1584                     origin, crflags, drba->drba_cred, tx);
1585                 if (origin != NULL)
1586                         dsl_dataset_rele(origin, FTAG);
1587                 dsl_dir_rele(dd, FTAG);
1588                 drba->drba_cookie->drc_newfs = B_TRUE;
1589         }
1590         VERIFY0(dsl_dataset_own_obj(dp, dsobj, dmu_recv_tag, &newds));
1591
1592         if (drba->drba_cookie->drc_resumable) {
1593                 dsl_dataset_zapify(newds, tx);
1594                 if (drrb->drr_fromguid != 0) {
1595                         VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_FROMGUID,
1596                             8, 1, &drrb->drr_fromguid, tx));
1597                 }
1598                 VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_TOGUID,
1599                     8, 1, &drrb->drr_toguid, tx));
1600                 VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_TONAME,
1601                     1, strlen(drrb->drr_toname) + 1, drrb->drr_toname, tx));
1602                 uint64_t one = 1;
1603                 uint64_t zero = 0;
1604                 VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_OBJECT,
1605                     8, 1, &one, tx));
1606                 VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_OFFSET,
1607                     8, 1, &zero, tx));
1608                 VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_BYTES,
1609                     8, 1, &zero, tx));
1610                 if (DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo) &
1611                     DMU_BACKUP_FEATURE_LARGE_BLOCKS) {
1612                         VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_LARGEBLOCK,
1613                             8, 1, &one, tx));
1614                 }
1615                 if (DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo) &
1616                     DMU_BACKUP_FEATURE_EMBED_DATA) {
1617                         VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_EMBEDOK,
1618                             8, 1, &one, tx));
1619                 }
1620                 if (DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo) &
1621                     DMU_BACKUP_FEATURE_COMPRESSED) {
1622                         VERIFY0(zap_add(mos, dsobj, DS_FIELD_RESUME_COMPRESSOK,
1623                             8, 1, &one, tx));
1624                 }
1625         }
1626
1627         dmu_buf_will_dirty(newds->ds_dbuf, tx);
1628         dsl_dataset_phys(newds)->ds_flags |= DS_FLAG_INCONSISTENT;
1629
1630         /*
1631          * If we actually created a non-clone, we need to create the
1632          * objset in our new dataset.
1633          */
1634         rrw_enter(&newds->ds_bp_rwlock, RW_READER, FTAG);
1635         if (BP_IS_HOLE(dsl_dataset_get_blkptr(newds))) {
1636                 (void) dmu_objset_create_impl(dp->dp_spa,
1637                     newds, dsl_dataset_get_blkptr(newds), drrb->drr_type, tx);
1638         }
1639         rrw_exit(&newds->ds_bp_rwlock, FTAG);
1640
1641         drba->drba_cookie->drc_ds = newds;
1642
1643         spa_history_log_internal_ds(newds, "receive", tx, "");
1644 }
1645
1646 static int
1647 dmu_recv_resume_begin_check(void *arg, dmu_tx_t *tx)
1648 {
1649         dmu_recv_begin_arg_t *drba = arg;
1650         dsl_pool_t *dp = dmu_tx_pool(tx);
1651         struct drr_begin *drrb = drba->drba_cookie->drc_drrb;
1652         int error;
1653         uint64_t featureflags = DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo);
1654         dsl_dataset_t *ds;
1655         const char *tofs = drba->drba_cookie->drc_tofs;
1656
1657         /* 6 extra bytes for /%recv */
1658         char recvname[ZFS_MAX_DATASET_NAME_LEN + 6];
1659
1660         /* already checked */
1661         ASSERT3U(drrb->drr_magic, ==, DMU_BACKUP_MAGIC);
1662         ASSERT(featureflags & DMU_BACKUP_FEATURE_RESUMING);
1663
1664         if (DMU_GET_STREAM_HDRTYPE(drrb->drr_versioninfo) ==
1665             DMU_COMPOUNDSTREAM ||
1666             drrb->drr_type >= DMU_OST_NUMTYPES)
1667                 return (SET_ERROR(EINVAL));
1668
1669         /* Verify pool version supports SA if SA_SPILL feature set */
1670         if ((featureflags & DMU_BACKUP_FEATURE_SA_SPILL) &&
1671             spa_version(dp->dp_spa) < SPA_VERSION_SA)
1672                 return (SET_ERROR(ENOTSUP));
1673
1674         /*
1675          * The receiving code doesn't know how to translate a WRITE_EMBEDDED
1676          * record to a plain WRITE record, so the pool must have the
1677          * EMBEDDED_DATA feature enabled if the stream has WRITE_EMBEDDED
1678          * records.  Same with WRITE_EMBEDDED records that use LZ4 compression.
1679          */
1680         if ((featureflags & DMU_BACKUP_FEATURE_EMBED_DATA) &&
1681             !spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_EMBEDDED_DATA))
1682                 return (SET_ERROR(ENOTSUP));
1683         if ((featureflags & DMU_BACKUP_FEATURE_LZ4) &&
1684             !spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_LZ4_COMPRESS))
1685                 return (SET_ERROR(ENOTSUP));
1686
1687         /*
1688          * The receiving code doesn't know how to translate large blocks
1689          * to smaller ones, so the pool must have the LARGE_BLOCKS
1690          * feature enabled if the stream has LARGE_BLOCKS. Same with
1691          * large dnodes.
1692          */
1693         if ((featureflags & DMU_BACKUP_FEATURE_LARGE_BLOCKS) &&
1694             !spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_LARGE_BLOCKS))
1695                 return (SET_ERROR(ENOTSUP));
1696         if ((featureflags & DMU_BACKUP_FEATURE_LARGE_DNODE) &&
1697             !spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_LARGE_DNODE))
1698                 return (SET_ERROR(ENOTSUP));
1699
1700         (void) snprintf(recvname, sizeof (recvname), "%s/%s",
1701             tofs, recv_clone_name);
1702
1703         if (dsl_dataset_hold(dp, recvname, FTAG, &ds) != 0) {
1704                 /* %recv does not exist; continue in tofs */
1705                 error = dsl_dataset_hold(dp, tofs, FTAG, &ds);
1706                 if (error != 0)
1707                         return (error);
1708         }
1709
1710         /* check that ds is marked inconsistent */
1711         if (!DS_IS_INCONSISTENT(ds)) {
1712                 dsl_dataset_rele(ds, FTAG);
1713                 return (SET_ERROR(EINVAL));
1714         }
1715
1716         /* check that there is resuming data, and that the toguid matches */
1717         if (!dsl_dataset_is_zapified(ds)) {
1718                 dsl_dataset_rele(ds, FTAG);
1719                 return (SET_ERROR(EINVAL));
1720         }
1721         uint64_t val;
1722         error = zap_lookup(dp->dp_meta_objset, ds->ds_object,
1723             DS_FIELD_RESUME_TOGUID, sizeof (val), 1, &val);
1724         if (error != 0 || drrb->drr_toguid != val) {
1725                 dsl_dataset_rele(ds, FTAG);
1726                 return (SET_ERROR(EINVAL));
1727         }
1728
1729         /*
1730          * Check if the receive is still running.  If so, it will be owned.
1731          * Note that nothing else can own the dataset (e.g. after the receive
1732          * fails) because it will be marked inconsistent.
1733          */
1734         if (dsl_dataset_has_owner(ds)) {
1735                 dsl_dataset_rele(ds, FTAG);
1736                 return (SET_ERROR(EBUSY));
1737         }
1738
1739         /* There should not be any snapshots of this fs yet. */
1740         if (ds->ds_prev != NULL && ds->ds_prev->ds_dir == ds->ds_dir) {
1741                 dsl_dataset_rele(ds, FTAG);
1742                 return (SET_ERROR(EINVAL));
1743         }
1744
1745         /*
1746          * Note: resume point will be checked when we process the first WRITE
1747          * record.
1748          */
1749
1750         /* check that the origin matches */
1751         val = 0;
1752         (void) zap_lookup(dp->dp_meta_objset, ds->ds_object,
1753             DS_FIELD_RESUME_FROMGUID, sizeof (val), 1, &val);
1754         if (drrb->drr_fromguid != val) {
1755                 dsl_dataset_rele(ds, FTAG);
1756                 return (SET_ERROR(EINVAL));
1757         }
1758
1759         dsl_dataset_rele(ds, FTAG);
1760         return (0);
1761 }
1762
1763 static void
1764 dmu_recv_resume_begin_sync(void *arg, dmu_tx_t *tx)
1765 {
1766         dmu_recv_begin_arg_t *drba = arg;
1767         dsl_pool_t *dp = dmu_tx_pool(tx);
1768         const char *tofs = drba->drba_cookie->drc_tofs;
1769         dsl_dataset_t *ds;
1770         uint64_t dsobj;
1771         /* 6 extra bytes for /%recv */
1772         char recvname[ZFS_MAX_DATASET_NAME_LEN + 6];
1773
1774         (void) snprintf(recvname, sizeof (recvname), "%s/%s",
1775             tofs, recv_clone_name);
1776
1777         if (dsl_dataset_hold(dp, recvname, FTAG, &ds) != 0) {
1778                 /* %recv does not exist; continue in tofs */
1779                 VERIFY0(dsl_dataset_hold(dp, tofs, FTAG, &ds));
1780                 drba->drba_cookie->drc_newfs = B_TRUE;
1781         }
1782
1783         /* clear the inconsistent flag so that we can own it */
1784         ASSERT(DS_IS_INCONSISTENT(ds));
1785         dmu_buf_will_dirty(ds->ds_dbuf, tx);
1786         dsl_dataset_phys(ds)->ds_flags &= ~DS_FLAG_INCONSISTENT;
1787         dsobj = ds->ds_object;
1788         dsl_dataset_rele(ds, FTAG);
1789
1790         VERIFY0(dsl_dataset_own_obj(dp, dsobj, dmu_recv_tag, &ds));
1791
1792         dmu_buf_will_dirty(ds->ds_dbuf, tx);
1793         dsl_dataset_phys(ds)->ds_flags |= DS_FLAG_INCONSISTENT;
1794
1795         rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);
1796         ASSERT(!BP_IS_HOLE(dsl_dataset_get_blkptr(ds)));
1797         rrw_exit(&ds->ds_bp_rwlock, FTAG);
1798
1799         drba->drba_cookie->drc_ds = ds;
1800
1801         spa_history_log_internal_ds(ds, "resume receive", tx, "");
1802 }
1803
1804 /*
1805  * NB: callers *MUST* call dmu_recv_stream() if dmu_recv_begin()
1806  * succeeds; otherwise we will leak the holds on the datasets.
1807  */
1808 int
1809 dmu_recv_begin(char *tofs, char *tosnap, dmu_replay_record_t *drr_begin,
1810     boolean_t force, boolean_t resumable, char *origin, dmu_recv_cookie_t *drc)
1811 {
1812         dmu_recv_begin_arg_t drba = { 0 };
1813
1814         bzero(drc, sizeof (dmu_recv_cookie_t));
1815         drc->drc_drr_begin = drr_begin;
1816         drc->drc_drrb = &drr_begin->drr_u.drr_begin;
1817         drc->drc_tosnap = tosnap;
1818         drc->drc_tofs = tofs;
1819         drc->drc_force = force;
1820         drc->drc_resumable = resumable;
1821         drc->drc_cred = CRED();
1822         drc->drc_clone = (origin != NULL);
1823
1824         if (drc->drc_drrb->drr_magic == BSWAP_64(DMU_BACKUP_MAGIC)) {
1825                 drc->drc_byteswap = B_TRUE;
1826                 (void) fletcher_4_incremental_byteswap(drr_begin,
1827                     sizeof (dmu_replay_record_t), &drc->drc_cksum);
1828                 byteswap_record(drr_begin);
1829         } else if (drc->drc_drrb->drr_magic == DMU_BACKUP_MAGIC) {
1830                 (void) fletcher_4_incremental_native(drr_begin,
1831                     sizeof (dmu_replay_record_t), &drc->drc_cksum);
1832         } else {
1833                 return (SET_ERROR(EINVAL));
1834         }
1835
1836         drba.drba_origin = origin;
1837         drba.drba_cookie = drc;
1838         drba.drba_cred = CRED();
1839
1840         if (DMU_GET_FEATUREFLAGS(drc->drc_drrb->drr_versioninfo) &
1841             DMU_BACKUP_FEATURE_RESUMING) {
1842                 return (dsl_sync_task(tofs,
1843                     dmu_recv_resume_begin_check, dmu_recv_resume_begin_sync,
1844                     &drba, 5, ZFS_SPACE_CHECK_NORMAL));
1845         } else  {
1846                 return (dsl_sync_task(tofs,
1847                     dmu_recv_begin_check, dmu_recv_begin_sync,
1848                     &drba, 5, ZFS_SPACE_CHECK_NORMAL));
1849         }
1850 }
1851
1852 struct receive_record_arg {
1853         dmu_replay_record_t header;
1854         void *payload; /* Pointer to a buffer containing the payload */
1855         /*
1856          * If the record is a write, pointer to the arc_buf_t containing the
1857          * payload.
1858          */
1859         arc_buf_t *write_buf;
1860         int payload_size;
1861         uint64_t bytes_read; /* bytes read from stream when record created */
1862         boolean_t eos_marker; /* Marks the end of the stream */
1863         bqueue_node_t node;
1864 };
1865
1866 struct receive_writer_arg {
1867         objset_t *os;
1868         boolean_t byteswap;
1869         bqueue_t q;
1870
1871         /*
1872          * These three args are used to signal to the main thread that we're
1873          * done.
1874          */
1875         kmutex_t mutex;
1876         kcondvar_t cv;
1877         boolean_t done;
1878
1879         int err;
1880         /* A map from guid to dataset to help handle dedup'd streams. */
1881         avl_tree_t *guid_to_ds_map;
1882         boolean_t resumable;
1883         uint64_t last_object;
1884         uint64_t last_offset;
1885         uint64_t max_object; /* highest object ID referenced in stream */
1886         uint64_t bytes_read; /* bytes read when current record created */
1887 };
1888
1889 struct objlist {
1890         list_t list; /* List of struct receive_objnode. */
1891         /*
1892          * Last object looked up. Used to assert that objects are being looked
1893          * up in ascending order.
1894          */
1895         uint64_t last_lookup;
1896 };
1897
1898 struct receive_objnode {
1899         list_node_t node;
1900         uint64_t object;
1901 };
1902
1903 struct receive_arg {
1904         objset_t *os;
1905         kthread_t *td;
1906         struct file *fp;
1907         uint64_t voff; /* The current offset in the stream */
1908         uint64_t bytes_read;
1909         /*
1910          * A record that has had its payload read in, but hasn't yet been handed
1911          * off to the worker thread.
1912          */
1913         struct receive_record_arg *rrd;
1914         /* A record that has had its header read in, but not its payload. */
1915         struct receive_record_arg *next_rrd;
1916         zio_cksum_t cksum;
1917         zio_cksum_t prev_cksum;
1918         int err;
1919         boolean_t byteswap;
1920         /* Sorted list of objects not to issue prefetches for. */
1921         struct objlist ignore_objlist;
1922 };
1923
1924 typedef struct guid_map_entry {
1925         uint64_t        guid;
1926         dsl_dataset_t   *gme_ds;
1927         avl_node_t      avlnode;
1928 } guid_map_entry_t;
1929
1930 static int
1931 guid_compare(const void *arg1, const void *arg2)
1932 {
1933         const guid_map_entry_t *gmep1 = (const guid_map_entry_t *)arg1;
1934         const guid_map_entry_t *gmep2 = (const guid_map_entry_t *)arg2;
1935
1936         return (AVL_CMP(gmep1->guid, gmep2->guid));
1937 }
1938
1939 static void
1940 free_guid_map_onexit(void *arg)
1941 {
1942         avl_tree_t *ca = arg;
1943         void *cookie = NULL;
1944         guid_map_entry_t *gmep;
1945
1946         while ((gmep = avl_destroy_nodes(ca, &cookie)) != NULL) {
1947                 dsl_dataset_long_rele(gmep->gme_ds, gmep);
1948                 dsl_dataset_rele(gmep->gme_ds, gmep);
1949                 kmem_free(gmep, sizeof (guid_map_entry_t));
1950         }
1951         avl_destroy(ca);
1952         kmem_free(ca, sizeof (avl_tree_t));
1953 }
1954
1955 static int
1956 restore_bytes(struct receive_arg *ra, void *buf, int len, off_t off, ssize_t *resid)
1957 {
1958         struct uio auio;
1959         struct iovec aiov;
1960         int error;
1961
1962         aiov.iov_base = buf;
1963         aiov.iov_len = len;
1964         auio.uio_iov = &aiov;
1965         auio.uio_iovcnt = 1;
1966         auio.uio_resid = len;
1967         auio.uio_segflg = UIO_SYSSPACE;
1968         auio.uio_rw = UIO_READ;
1969         auio.uio_offset = off;
1970         auio.uio_td = ra->td;
1971 #ifdef _KERNEL
1972         error = fo_read(ra->fp, &auio, ra->td->td_ucred, FOF_OFFSET, ra->td);
1973 #else
1974         fprintf(stderr, "%s: returning EOPNOTSUPP\n", __func__);
1975         error = EOPNOTSUPP;
1976 #endif
1977         *resid = auio.uio_resid;
1978         return (error);
1979 }
1980
1981 static int
1982 receive_read(struct receive_arg *ra, int len, void *buf)
1983 {
1984         int done = 0;
1985
1986         /*
1987          * The code doesn't rely on this (lengths being multiples of 8).  See
1988          * comment in dump_bytes.
1989          */
1990         ASSERT0(len % 8);
1991
1992         while (done < len) {
1993                 ssize_t resid;
1994
1995                 ra->err = restore_bytes(ra, buf + done,
1996                     len - done, ra->voff, &resid);
1997
1998                 if (resid == len - done) {
1999                         /*
2000                          * Note: ECKSUM indicates that the receive
2001                          * was interrupted and can potentially be resumed.
2002                          */
2003                         ra->err = SET_ERROR(ECKSUM);
2004                 }
2005                 ra->voff += len - done - resid;
2006                 done = len - resid;
2007                 if (ra->err != 0)
2008                         return (ra->err);
2009         }
2010
2011         ra->bytes_read += len;
2012
2013         ASSERT3U(done, ==, len);
2014         return (0);
2015 }
2016
2017 noinline static void
2018 byteswap_record(dmu_replay_record_t *drr)
2019 {
2020 #define DO64(X) (drr->drr_u.X = BSWAP_64(drr->drr_u.X))
2021 #define DO32(X) (drr->drr_u.X = BSWAP_32(drr->drr_u.X))
2022         drr->drr_type = BSWAP_32(drr->drr_type);
2023         drr->drr_payloadlen = BSWAP_32(drr->drr_payloadlen);
2024
2025         switch (drr->drr_type) {
2026         case DRR_BEGIN:
2027                 DO64(drr_begin.drr_magic);
2028                 DO64(drr_begin.drr_versioninfo);
2029                 DO64(drr_begin.drr_creation_time);
2030                 DO32(drr_begin.drr_type);
2031                 DO32(drr_begin.drr_flags);
2032                 DO64(drr_begin.drr_toguid);
2033                 DO64(drr_begin.drr_fromguid);
2034                 break;
2035         case DRR_OBJECT:
2036                 DO64(drr_object.drr_object);
2037                 DO32(drr_object.drr_type);
2038                 DO32(drr_object.drr_bonustype);
2039                 DO32(drr_object.drr_blksz);
2040                 DO32(drr_object.drr_bonuslen);
2041                 DO64(drr_object.drr_toguid);
2042                 break;
2043         case DRR_FREEOBJECTS:
2044                 DO64(drr_freeobjects.drr_firstobj);
2045                 DO64(drr_freeobjects.drr_numobjs);
2046                 DO64(drr_freeobjects.drr_toguid);
2047                 break;
2048         case DRR_WRITE:
2049                 DO64(drr_write.drr_object);
2050                 DO32(drr_write.drr_type);
2051                 DO64(drr_write.drr_offset);
2052                 DO64(drr_write.drr_logical_size);
2053                 DO64(drr_write.drr_toguid);
2054                 ZIO_CHECKSUM_BSWAP(&drr->drr_u.drr_write.drr_key.ddk_cksum);
2055                 DO64(drr_write.drr_key.ddk_prop);
2056                 DO64(drr_write.drr_compressed_size);
2057                 break;
2058         case DRR_WRITE_BYREF:
2059                 DO64(drr_write_byref.drr_object);
2060                 DO64(drr_write_byref.drr_offset);
2061                 DO64(drr_write_byref.drr_length);
2062                 DO64(drr_write_byref.drr_toguid);
2063                 DO64(drr_write_byref.drr_refguid);
2064                 DO64(drr_write_byref.drr_refobject);
2065                 DO64(drr_write_byref.drr_refoffset);
2066                 ZIO_CHECKSUM_BSWAP(&drr->drr_u.drr_write_byref.
2067                     drr_key.ddk_cksum);
2068                 DO64(drr_write_byref.drr_key.ddk_prop);
2069                 break;
2070         case DRR_WRITE_EMBEDDED:
2071                 DO64(drr_write_embedded.drr_object);
2072                 DO64(drr_write_embedded.drr_offset);
2073                 DO64(drr_write_embedded.drr_length);
2074                 DO64(drr_write_embedded.drr_toguid);
2075                 DO32(drr_write_embedded.drr_lsize);
2076                 DO32(drr_write_embedded.drr_psize);
2077                 break;
2078         case DRR_FREE:
2079                 DO64(drr_free.drr_object);
2080                 DO64(drr_free.drr_offset);
2081                 DO64(drr_free.drr_length);
2082                 DO64(drr_free.drr_toguid);
2083                 break;
2084         case DRR_SPILL:
2085                 DO64(drr_spill.drr_object);
2086                 DO64(drr_spill.drr_length);
2087                 DO64(drr_spill.drr_toguid);
2088                 break;
2089         case DRR_END:
2090                 DO64(drr_end.drr_toguid);
2091                 ZIO_CHECKSUM_BSWAP(&drr->drr_u.drr_end.drr_checksum);
2092                 break;
2093         }
2094
2095         if (drr->drr_type != DRR_BEGIN) {
2096                 ZIO_CHECKSUM_BSWAP(&drr->drr_u.drr_checksum.drr_checksum);
2097         }
2098
2099 #undef DO64
2100 #undef DO32
2101 }
2102
2103 static inline uint8_t
2104 deduce_nblkptr(dmu_object_type_t bonus_type, uint64_t bonus_size)
2105 {
2106         if (bonus_type == DMU_OT_SA) {
2107                 return (1);
2108         } else {
2109                 return (1 +
2110                     ((DN_OLD_MAX_BONUSLEN -
2111                     MIN(DN_OLD_MAX_BONUSLEN, bonus_size)) >> SPA_BLKPTRSHIFT));
2112         }
2113 }
2114
2115 static void
2116 save_resume_state(struct receive_writer_arg *rwa,
2117     uint64_t object, uint64_t offset, dmu_tx_t *tx)
2118 {
2119         int txgoff = dmu_tx_get_txg(tx) & TXG_MASK;
2120
2121         if (!rwa->resumable)
2122                 return;
2123
2124         /*
2125          * We use ds_resume_bytes[] != 0 to indicate that we need to
2126          * update this on disk, so it must not be 0.
2127          */
2128         ASSERT(rwa->bytes_read != 0);
2129
2130         /*
2131          * We only resume from write records, which have a valid
2132          * (non-meta-dnode) object number.
2133          */
2134         ASSERT(object != 0);
2135
2136         /*
2137          * For resuming to work correctly, we must receive records in order,
2138          * sorted by object,offset.  This is checked by the callers, but
2139          * assert it here for good measure.
2140          */
2141         ASSERT3U(object, >=, rwa->os->os_dsl_dataset->ds_resume_object[txgoff]);
2142         ASSERT(object != rwa->os->os_dsl_dataset->ds_resume_object[txgoff] ||
2143             offset >= rwa->os->os_dsl_dataset->ds_resume_offset[txgoff]);
2144         ASSERT3U(rwa->bytes_read, >=,
2145             rwa->os->os_dsl_dataset->ds_resume_bytes[txgoff]);
2146
2147         rwa->os->os_dsl_dataset->ds_resume_object[txgoff] = object;
2148         rwa->os->os_dsl_dataset->ds_resume_offset[txgoff] = offset;
2149         rwa->os->os_dsl_dataset->ds_resume_bytes[txgoff] = rwa->bytes_read;
2150 }
2151
2152 noinline static int
2153 receive_object(struct receive_writer_arg *rwa, struct drr_object *drro,
2154     void *data)
2155 {
2156         dmu_object_info_t doi;
2157         dmu_tx_t *tx;
2158         uint64_t object;
2159         int err;
2160         uint8_t dn_slots = drro->drr_dn_slots != 0 ?
2161             drro->drr_dn_slots : DNODE_MIN_SLOTS;
2162
2163         if (drro->drr_type == DMU_OT_NONE ||
2164             !DMU_OT_IS_VALID(drro->drr_type) ||
2165             !DMU_OT_IS_VALID(drro->drr_bonustype) ||
2166             drro->drr_checksumtype >= ZIO_CHECKSUM_FUNCTIONS ||
2167             drro->drr_compress >= ZIO_COMPRESS_FUNCTIONS ||
2168             P2PHASE(drro->drr_blksz, SPA_MINBLOCKSIZE) ||
2169             drro->drr_blksz < SPA_MINBLOCKSIZE ||
2170             drro->drr_blksz > spa_maxblocksize(dmu_objset_spa(rwa->os)) ||
2171             drro->drr_bonuslen >
2172             DN_BONUS_SIZE(spa_maxdnodesize(dmu_objset_spa(rwa->os))) ||
2173             dn_slots >
2174             (spa_maxdnodesize(dmu_objset_spa(rwa->os)) >> DNODE_SHIFT)) {
2175                 return (SET_ERROR(EINVAL));
2176         }
2177
2178         err = dmu_object_info(rwa->os, drro->drr_object, &doi);
2179
2180         if (err != 0 && err != ENOENT && err != EEXIST)
2181                 return (SET_ERROR(EINVAL));
2182
2183         if (drro->drr_object > rwa->max_object)
2184                 rwa->max_object = drro->drr_object;
2185
2186         /*
2187          * If we are losing blkptrs or changing the block size this must
2188          * be a new file instance.  We must clear out the previous file
2189          * contents before we can change this type of metadata in the dnode.
2190          */
2191         if (err == 0) {
2192                 int nblkptr;
2193
2194                 object = drro->drr_object;
2195
2196                 nblkptr = deduce_nblkptr(drro->drr_bonustype,
2197                     drro->drr_bonuslen);
2198
2199                 if (drro->drr_blksz != doi.doi_data_block_size ||
2200                     nblkptr < doi.doi_nblkptr ||
2201                     dn_slots != doi.doi_dnodesize >> DNODE_SHIFT) {
2202                         err = dmu_free_long_range(rwa->os, drro->drr_object,
2203                             0, DMU_OBJECT_END);
2204                         if (err != 0)
2205                                 return (SET_ERROR(EINVAL));
2206                 }
2207         } else if (err == EEXIST) {
2208                 /*
2209                  * The object requested is currently an interior slot of a
2210                  * multi-slot dnode. This will be resolved when the next txg
2211                  * is synced out, since the send stream will have told us
2212                  * to free this slot when we freed the associated dnode
2213                  * earlier in the stream.
2214                  */
2215                 txg_wait_synced(dmu_objset_pool(rwa->os), 0);
2216                 object = drro->drr_object;
2217         } else {
2218                 /* object is free and we are about to allocate a new one */
2219                 object = DMU_NEW_OBJECT;
2220         }
2221
2222         /*
2223          * If this is a multi-slot dnode there is a chance that this
2224          * object will expand into a slot that is already used by
2225          * another object from the previous snapshot. We must free
2226          * these objects before we attempt to allocate the new dnode.
2227          */
2228         if (dn_slots > 1) {
2229                 boolean_t need_sync = B_FALSE;
2230
2231                 for (uint64_t slot = drro->drr_object + 1;
2232                     slot < drro->drr_object + dn_slots;
2233                     slot++) {
2234                         dmu_object_info_t slot_doi;
2235
2236                         err = dmu_object_info(rwa->os, slot, &slot_doi);
2237                         if (err == ENOENT || err == EEXIST)
2238                                 continue;
2239                         else if (err != 0)
2240                                 return (err);
2241
2242                         err = dmu_free_long_object(rwa->os, slot);
2243
2244                         if (err != 0)
2245                                 return (err);
2246
2247                         need_sync = B_TRUE;
2248                 }
2249
2250                 if (need_sync)
2251                         txg_wait_synced(dmu_objset_pool(rwa->os), 0);
2252         }
2253
2254         tx = dmu_tx_create(rwa->os);
2255         dmu_tx_hold_bonus(tx, object);
2256         err = dmu_tx_assign(tx, TXG_WAIT);
2257         if (err != 0) {
2258                 dmu_tx_abort(tx);
2259                 return (err);
2260         }
2261
2262         if (object == DMU_NEW_OBJECT) {
2263                 /* currently free, want to be allocated */
2264                 err = dmu_object_claim_dnsize(rwa->os, drro->drr_object,
2265                     drro->drr_type, drro->drr_blksz,
2266                     drro->drr_bonustype, drro->drr_bonuslen,
2267                     dn_slots << DNODE_SHIFT, tx);
2268         } else if (drro->drr_type != doi.doi_type ||
2269             drro->drr_blksz != doi.doi_data_block_size ||
2270             drro->drr_bonustype != doi.doi_bonus_type ||
2271             drro->drr_bonuslen != doi.doi_bonus_size ||
2272             drro->drr_dn_slots != (doi.doi_dnodesize >> DNODE_SHIFT)) {
2273                 /* currently allocated, but with different properties */
2274                 err = dmu_object_reclaim_dnsize(rwa->os, drro->drr_object,
2275                     drro->drr_type, drro->drr_blksz,
2276                     drro->drr_bonustype, drro->drr_bonuslen,
2277                     drro->drr_dn_slots << DNODE_SHIFT, tx);
2278         }
2279         if (err != 0) {
2280                 dmu_tx_commit(tx);
2281                 return (SET_ERROR(EINVAL));
2282         }
2283
2284         dmu_object_set_checksum(rwa->os, drro->drr_object,
2285             drro->drr_checksumtype, tx);
2286         dmu_object_set_compress(rwa->os, drro->drr_object,
2287             drro->drr_compress, tx);
2288
2289         if (data != NULL) {
2290                 dmu_buf_t *db;
2291
2292                 VERIFY0(dmu_bonus_hold(rwa->os, drro->drr_object, FTAG, &db));
2293                 dmu_buf_will_dirty(db, tx);
2294
2295                 ASSERT3U(db->db_size, >=, drro->drr_bonuslen);
2296                 bcopy(data, db->db_data, drro->drr_bonuslen);
2297                 if (rwa->byteswap) {
2298                         dmu_object_byteswap_t byteswap =
2299                             DMU_OT_BYTESWAP(drro->drr_bonustype);
2300                         dmu_ot_byteswap[byteswap].ob_func(db->db_data,
2301                             drro->drr_bonuslen);
2302                 }
2303                 dmu_buf_rele(db, FTAG);
2304         }
2305         dmu_tx_commit(tx);
2306
2307         return (0);
2308 }
2309
2310 /* ARGSUSED */
2311 noinline static int
2312 receive_freeobjects(struct receive_writer_arg *rwa,
2313     struct drr_freeobjects *drrfo)
2314 {
2315         uint64_t obj;
2316         int next_err = 0;
2317
2318         if (drrfo->drr_firstobj + drrfo->drr_numobjs < drrfo->drr_firstobj)
2319                 return (SET_ERROR(EINVAL));
2320
2321         for (obj = drrfo->drr_firstobj == 0 ? 1 : drrfo->drr_firstobj;
2322             obj < drrfo->drr_firstobj + drrfo->drr_numobjs && next_err == 0;
2323             next_err = dmu_object_next(rwa->os, &obj, FALSE, 0)) {
2324                 dmu_object_info_t doi;
2325                 int err;
2326
2327                 err = dmu_object_info(rwa->os, obj, NULL);
2328                 if (err == ENOENT)
2329                         continue;
2330                 else if (err != 0)
2331                         return (err);
2332
2333                 err = dmu_free_long_object(rwa->os, obj);
2334                 if (err != 0)
2335                         return (err);
2336
2337                 if (obj > rwa->max_object)
2338                         rwa->max_object = obj;
2339         }
2340         if (next_err != ESRCH)
2341                 return (next_err);
2342         return (0);
2343 }
2344
2345 noinline static int
2346 receive_write(struct receive_writer_arg *rwa, struct drr_write *drrw,
2347     arc_buf_t *abuf)
2348 {
2349         dmu_tx_t *tx;
2350         int err;
2351
2352         if (drrw->drr_offset + drrw->drr_logical_size < drrw->drr_offset ||
2353             !DMU_OT_IS_VALID(drrw->drr_type))
2354                 return (SET_ERROR(EINVAL));
2355
2356         /*
2357          * For resuming to work, records must be in increasing order
2358          * by (object, offset).
2359          */
2360         if (drrw->drr_object < rwa->last_object ||
2361             (drrw->drr_object == rwa->last_object &&
2362             drrw->drr_offset < rwa->last_offset)) {
2363                 return (SET_ERROR(EINVAL));
2364         }
2365         rwa->last_object = drrw->drr_object;
2366         rwa->last_offset = drrw->drr_offset;
2367
2368         if (rwa->last_object > rwa->max_object)
2369                 rwa->max_object = rwa->last_object;
2370
2371         if (dmu_object_info(rwa->os, drrw->drr_object, NULL) != 0)
2372                 return (SET_ERROR(EINVAL));
2373
2374         tx = dmu_tx_create(rwa->os);
2375         dmu_tx_hold_write(tx, drrw->drr_object,
2376             drrw->drr_offset, drrw->drr_logical_size);
2377         err = dmu_tx_assign(tx, TXG_WAIT);
2378         if (err != 0) {
2379                 dmu_tx_abort(tx);
2380                 return (err);
2381         }
2382         if (rwa->byteswap) {
2383                 dmu_object_byteswap_t byteswap =
2384                     DMU_OT_BYTESWAP(drrw->drr_type);
2385                 dmu_ot_byteswap[byteswap].ob_func(abuf->b_data,
2386                     DRR_WRITE_PAYLOAD_SIZE(drrw));
2387         }
2388
2389         /* use the bonus buf to look up the dnode in dmu_assign_arcbuf */
2390         dmu_buf_t *bonus;
2391         if (dmu_bonus_hold(rwa->os, drrw->drr_object, FTAG, &bonus) != 0)
2392                 return (SET_ERROR(EINVAL));
2393         dmu_assign_arcbuf(bonus, drrw->drr_offset, abuf, tx);
2394
2395         /*
2396          * Note: If the receive fails, we want the resume stream to start
2397          * with the same record that we last successfully received (as opposed
2398          * to the next record), so that we can verify that we are
2399          * resuming from the correct location.
2400          */
2401         save_resume_state(rwa, drrw->drr_object, drrw->drr_offset, tx);
2402         dmu_tx_commit(tx);
2403         dmu_buf_rele(bonus, FTAG);
2404
2405         return (0);
2406 }
2407
2408 /*
2409  * Handle a DRR_WRITE_BYREF record.  This record is used in dedup'ed
2410  * streams to refer to a copy of the data that is already on the
2411  * system because it came in earlier in the stream.  This function
2412  * finds the earlier copy of the data, and uses that copy instead of
2413  * data from the stream to fulfill this write.
2414  */
2415 static int
2416 receive_write_byref(struct receive_writer_arg *rwa,
2417     struct drr_write_byref *drrwbr)
2418 {
2419         dmu_tx_t *tx;
2420         int err;
2421         guid_map_entry_t gmesrch;
2422         guid_map_entry_t *gmep;
2423         avl_index_t where;
2424         objset_t *ref_os = NULL;
2425         dmu_buf_t *dbp;
2426
2427         if (drrwbr->drr_offset + drrwbr->drr_length < drrwbr->drr_offset)
2428                 return (SET_ERROR(EINVAL));
2429
2430         /*
2431          * If the GUID of the referenced dataset is different from the
2432          * GUID of the target dataset, find the referenced dataset.
2433          */
2434         if (drrwbr->drr_toguid != drrwbr->drr_refguid) {
2435                 gmesrch.guid = drrwbr->drr_refguid;
2436                 if ((gmep = avl_find(rwa->guid_to_ds_map, &gmesrch,
2437                     &where)) == NULL) {
2438                         return (SET_ERROR(EINVAL));
2439                 }
2440                 if (dmu_objset_from_ds(gmep->gme_ds, &ref_os))
2441                         return (SET_ERROR(EINVAL));
2442         } else {
2443                 ref_os = rwa->os;
2444         }
2445
2446         if (drrwbr->drr_object > rwa->max_object)
2447                 rwa->max_object = drrwbr->drr_object;
2448
2449         err = dmu_buf_hold(ref_os, drrwbr->drr_refobject,
2450             drrwbr->drr_refoffset, FTAG, &dbp, DMU_READ_PREFETCH);
2451         if (err != 0)
2452                 return (err);
2453
2454         tx = dmu_tx_create(rwa->os);
2455
2456         dmu_tx_hold_write(tx, drrwbr->drr_object,
2457             drrwbr->drr_offset, drrwbr->drr_length);
2458         err = dmu_tx_assign(tx, TXG_WAIT);
2459         if (err != 0) {
2460                 dmu_tx_abort(tx);
2461                 return (err);
2462         }
2463         dmu_write(rwa->os, drrwbr->drr_object,
2464             drrwbr->drr_offset, drrwbr->drr_length, dbp->db_data, tx);
2465         dmu_buf_rele(dbp, FTAG);
2466
2467         /* See comment in restore_write. */
2468         save_resume_state(rwa, drrwbr->drr_object, drrwbr->drr_offset, tx);
2469         dmu_tx_commit(tx);
2470         return (0);
2471 }
2472
2473 static int
2474 receive_write_embedded(struct receive_writer_arg *rwa,
2475     struct drr_write_embedded *drrwe, void *data)
2476 {
2477         dmu_tx_t *tx;
2478         int err;
2479
2480         if (drrwe->drr_offset + drrwe->drr_length < drrwe->drr_offset)
2481                 return (EINVAL);
2482
2483         if (drrwe->drr_psize > BPE_PAYLOAD_SIZE)
2484                 return (EINVAL);
2485
2486         if (drrwe->drr_etype >= NUM_BP_EMBEDDED_TYPES)
2487                 return (EINVAL);
2488         if (drrwe->drr_compression >= ZIO_COMPRESS_FUNCTIONS)
2489                 return (EINVAL);
2490
2491         if (drrwe->drr_object > rwa->max_object)
2492                 rwa->max_object = drrwe->drr_object;
2493
2494         tx = dmu_tx_create(rwa->os);
2495
2496         dmu_tx_hold_write(tx, drrwe->drr_object,
2497             drrwe->drr_offset, drrwe->drr_length);
2498         err = dmu_tx_assign(tx, TXG_WAIT);
2499         if (err != 0) {
2500                 dmu_tx_abort(tx);
2501                 return (err);
2502         }
2503
2504         dmu_write_embedded(rwa->os, drrwe->drr_object,
2505             drrwe->drr_offset, data, drrwe->drr_etype,
2506             drrwe->drr_compression, drrwe->drr_lsize, drrwe->drr_psize,
2507             rwa->byteswap ^ ZFS_HOST_BYTEORDER, tx);
2508
2509         /* See comment in restore_write. */
2510         save_resume_state(rwa, drrwe->drr_object, drrwe->drr_offset, tx);
2511         dmu_tx_commit(tx);
2512         return (0);
2513 }
2514
2515 static int
2516 receive_spill(struct receive_writer_arg *rwa, struct drr_spill *drrs,
2517     void *data)
2518 {
2519         dmu_tx_t *tx;
2520         dmu_buf_t *db, *db_spill;
2521         int err;
2522
2523         if (drrs->drr_length < SPA_MINBLOCKSIZE ||
2524             drrs->drr_length > spa_maxblocksize(dmu_objset_spa(rwa->os)))
2525                 return (SET_ERROR(EINVAL));
2526
2527         if (dmu_object_info(rwa->os, drrs->drr_object, NULL) != 0)
2528                 return (SET_ERROR(EINVAL));
2529
2530         if (drrs->drr_object > rwa->max_object)
2531                 rwa->max_object = drrs->drr_object;
2532
2533         VERIFY0(dmu_bonus_hold(rwa->os, drrs->drr_object, FTAG, &db));
2534         if ((err = dmu_spill_hold_by_bonus(db, FTAG, &db_spill)) != 0) {
2535                 dmu_buf_rele(db, FTAG);
2536                 return (err);
2537         }
2538
2539         tx = dmu_tx_create(rwa->os);
2540
2541         dmu_tx_hold_spill(tx, db->db_object);
2542
2543         err = dmu_tx_assign(tx, TXG_WAIT);
2544         if (err != 0) {
2545                 dmu_buf_rele(db, FTAG);
2546                 dmu_buf_rele(db_spill, FTAG);
2547                 dmu_tx_abort(tx);
2548                 return (err);
2549         }
2550         dmu_buf_will_dirty(db_spill, tx);
2551
2552         if (db_spill->db_size < drrs->drr_length)
2553                 VERIFY(0 == dbuf_spill_set_blksz(db_spill,
2554                     drrs->drr_length, tx));
2555         bcopy(data, db_spill->db_data, drrs->drr_length);
2556
2557         dmu_buf_rele(db, FTAG);
2558         dmu_buf_rele(db_spill, FTAG);
2559
2560         dmu_tx_commit(tx);
2561         return (0);
2562 }
2563
2564 /* ARGSUSED */
2565 noinline static int
2566 receive_free(struct receive_writer_arg *rwa, struct drr_free *drrf)
2567 {
2568         int err;
2569
2570         if (drrf->drr_length != -1ULL &&
2571             drrf->drr_offset + drrf->drr_length < drrf->drr_offset)
2572                 return (SET_ERROR(EINVAL));
2573
2574         if (dmu_object_info(rwa->os, drrf->drr_object, NULL) != 0)
2575                 return (SET_ERROR(EINVAL));
2576
2577         if (drrf->drr_object > rwa->max_object)
2578                 rwa->max_object = drrf->drr_object;
2579
2580         err = dmu_free_long_range(rwa->os, drrf->drr_object,
2581             drrf->drr_offset, drrf->drr_length);
2582
2583         return (err);
2584 }
2585
2586 /* used to destroy the drc_ds on error */
2587 static void
2588 dmu_recv_cleanup_ds(dmu_recv_cookie_t *drc)
2589 {
2590         if (drc->drc_resumable) {
2591                 /* wait for our resume state to be written to disk */
2592                 txg_wait_synced(drc->drc_ds->ds_dir->dd_pool, 0);
2593                 dsl_dataset_disown(drc->drc_ds, dmu_recv_tag);
2594         } else {
2595                 char name[ZFS_MAX_DATASET_NAME_LEN];
2596                 dsl_dataset_name(drc->drc_ds, name);
2597                 dsl_dataset_disown(drc->drc_ds, dmu_recv_tag);
2598                 (void) dsl_destroy_head(name);
2599         }
2600 }
2601
2602 static void
2603 receive_cksum(struct receive_arg *ra, int len, void *buf)
2604 {
2605         if (ra->byteswap) {
2606                 (void) fletcher_4_incremental_byteswap(buf, len, &ra->cksum);
2607         } else {
2608                 (void) fletcher_4_incremental_native(buf, len, &ra->cksum);
2609         }
2610 }
2611
2612 /*
2613  * Read the payload into a buffer of size len, and update the current record's
2614  * payload field.
2615  * Allocate ra->next_rrd and read the next record's header into
2616  * ra->next_rrd->header.
2617  * Verify checksum of payload and next record.
2618  */
2619 static int
2620 receive_read_payload_and_next_header(struct receive_arg *ra, int len, void *buf)
2621 {
2622         int err;
2623
2624         if (len != 0) {
2625                 ASSERT3U(len, <=, SPA_MAXBLOCKSIZE);
2626                 err = receive_read(ra, len, buf);
2627                 if (err != 0)
2628                         return (err);
2629                 receive_cksum(ra, len, buf);
2630
2631                 /* note: rrd is NULL when reading the begin record's payload */
2632                 if (ra->rrd != NULL) {
2633                         ra->rrd->payload = buf;
2634                         ra->rrd->payload_size = len;
2635                         ra->rrd->bytes_read = ra->bytes_read;
2636                 }
2637         }
2638
2639         ra->prev_cksum = ra->cksum;
2640
2641         ra->next_rrd = kmem_zalloc(sizeof (*ra->next_rrd), KM_SLEEP);
2642         err = receive_read(ra, sizeof (ra->next_rrd->header),
2643             &ra->next_rrd->header);
2644         ra->next_rrd->bytes_read = ra->bytes_read;
2645         if (err != 0) {
2646                 kmem_free(ra->next_rrd, sizeof (*ra->next_rrd));
2647                 ra->next_rrd = NULL;
2648                 return (err);
2649         }
2650         if (ra->next_rrd->header.drr_type == DRR_BEGIN) {
2651                 kmem_free(ra->next_rrd, sizeof (*ra->next_rrd));
2652                 ra->next_rrd = NULL;
2653                 return (SET_ERROR(EINVAL));
2654         }
2655
2656         /*
2657          * Note: checksum is of everything up to but not including the
2658          * checksum itself.
2659          */
2660         ASSERT3U(offsetof(dmu_replay_record_t, drr_u.drr_checksum.drr_checksum),
2661             ==, sizeof (dmu_replay_record_t) - sizeof (zio_cksum_t));
2662         receive_cksum(ra,
2663             offsetof(dmu_replay_record_t, drr_u.drr_checksum.drr_checksum),
2664             &ra->next_rrd->header);
2665
2666         zio_cksum_t cksum_orig =
2667             ra->next_rrd->header.drr_u.drr_checksum.drr_checksum;
2668         zio_cksum_t *cksump =
2669             &ra->next_rrd->header.drr_u.drr_checksum.drr_checksum;
2670
2671         if (ra->byteswap)
2672                 byteswap_record(&ra->next_rrd->header);
2673
2674         if ((!ZIO_CHECKSUM_IS_ZERO(cksump)) &&
2675             !ZIO_CHECKSUM_EQUAL(ra->cksum, *cksump)) {
2676                 kmem_free(ra->next_rrd, sizeof (*ra->next_rrd));
2677                 ra->next_rrd = NULL;
2678                 return (SET_ERROR(ECKSUM));
2679         }
2680
2681         receive_cksum(ra, sizeof (cksum_orig), &cksum_orig);
2682
2683         return (0);
2684 }
2685
2686 static void
2687 objlist_create(struct objlist *list)
2688 {
2689         list_create(&list->list, sizeof (struct receive_objnode),
2690             offsetof(struct receive_objnode, node));
2691         list->last_lookup = 0;
2692 }
2693
2694 static void
2695 objlist_destroy(struct objlist *list)
2696 {
2697         for (struct receive_objnode *n = list_remove_head(&list->list);
2698             n != NULL; n = list_remove_head(&list->list)) {
2699                 kmem_free(n, sizeof (*n));
2700         }
2701         list_destroy(&list->list);
2702 }
2703
2704 /*
2705  * This function looks through the objlist to see if the specified object number
2706  * is contained in the objlist.  In the process, it will remove all object
2707  * numbers in the list that are smaller than the specified object number.  Thus,
2708  * any lookup of an object number smaller than a previously looked up object
2709  * number will always return false; therefore, all lookups should be done in
2710  * ascending order.
2711  */
2712 static boolean_t
2713 objlist_exists(struct objlist *list, uint64_t object)
2714 {
2715         struct receive_objnode *node = list_head(&list->list);
2716         ASSERT3U(object, >=, list->last_lookup);
2717         list->last_lookup = object;
2718         while (node != NULL && node->object < object) {
2719                 VERIFY3P(node, ==, list_remove_head(&list->list));
2720                 kmem_free(node, sizeof (*node));
2721                 node = list_head(&list->list);
2722         }
2723         return (node != NULL && node->object == object);
2724 }
2725
2726 /*
2727  * The objlist is a list of object numbers stored in ascending order.  However,
2728  * the insertion of new object numbers does not seek out the correct location to
2729  * store a new object number; instead, it appends it to the list for simplicity.
2730  * Thus, any users must take care to only insert new object numbers in ascending
2731  * order.
2732  */
2733 static void
2734 objlist_insert(struct objlist *list, uint64_t object)
2735 {
2736         struct receive_objnode *node = kmem_zalloc(sizeof (*node), KM_SLEEP);
2737         node->object = object;
2738 #ifdef ZFS_DEBUG
2739         struct receive_objnode *last_object = list_tail(&list->list);
2740         uint64_t last_objnum = (last_object != NULL ? last_object->object : 0);
2741         ASSERT3U(node->object, >, last_objnum);
2742 #endif
2743         list_insert_tail(&list->list, node);
2744 }
2745
2746 /*
2747  * Issue the prefetch reads for any necessary indirect blocks.
2748  *
2749  * We use the object ignore list to tell us whether or not to issue prefetches
2750  * for a given object.  We do this for both correctness (in case the blocksize
2751  * of an object has changed) and performance (if the object doesn't exist, don't
2752  * needlessly try to issue prefetches).  We also trim the list as we go through
2753  * the stream to prevent it from growing to an unbounded size.
2754  *
2755  * The object numbers within will always be in sorted order, and any write
2756  * records we see will also be in sorted order, but they're not sorted with
2757  * respect to each other (i.e. we can get several object records before
2758  * receiving each object's write records).  As a result, once we've reached a
2759  * given object number, we can safely remove any reference to lower object
2760  * numbers in the ignore list. In practice, we receive up to 32 object records
2761  * before receiving write records, so the list can have up to 32 nodes in it.
2762  */
2763 /* ARGSUSED */
2764 static void
2765 receive_read_prefetch(struct receive_arg *ra,
2766     uint64_t object, uint64_t offset, uint64_t length)
2767 {
2768         if (!objlist_exists(&ra->ignore_objlist, object)) {
2769                 dmu_prefetch(ra->os, object, 1, offset, length,
2770                     ZIO_PRIORITY_SYNC_READ);
2771         }
2772 }
2773
2774 /*
2775  * Read records off the stream, issuing any necessary prefetches.
2776  */
2777 static int
2778 receive_read_record(struct receive_arg *ra)
2779 {
2780         int err;
2781
2782         switch (ra->rrd->header.drr_type) {
2783         case DRR_OBJECT:
2784         {
2785                 struct drr_object *drro = &ra->rrd->header.drr_u.drr_object;
2786                 uint32_t size = P2ROUNDUP(drro->drr_bonuslen, 8);
2787                 void *buf = kmem_zalloc(size, KM_SLEEP);
2788                 dmu_object_info_t doi;
2789                 err = receive_read_payload_and_next_header(ra, size, buf);
2790                 if (err != 0) {
2791                         kmem_free(buf, size);
2792                         return (err);
2793                 }
2794                 err = dmu_object_info(ra->os, drro->drr_object, &doi);
2795                 /*
2796                  * See receive_read_prefetch for an explanation why we're
2797                  * storing this object in the ignore_obj_list.
2798                  */
2799                 if (err == ENOENT ||
2800                     (err == 0 && doi.doi_data_block_size != drro->drr_blksz)) {
2801                         objlist_insert(&ra->ignore_objlist, drro->drr_object);
2802                         err = 0;
2803                 }
2804                 return (err);
2805         }
2806         case DRR_FREEOBJECTS:
2807         {
2808                 err = receive_read_payload_and_next_header(ra, 0, NULL);
2809                 return (err);
2810         }
2811         case DRR_WRITE:
2812         {
2813                 struct drr_write *drrw = &ra->rrd->header.drr_u.drr_write;
2814                 arc_buf_t *abuf;
2815                 boolean_t is_meta = DMU_OT_IS_METADATA(drrw->drr_type);
2816                 if (DRR_WRITE_COMPRESSED(drrw)) {
2817                         ASSERT3U(drrw->drr_compressed_size, >, 0);
2818                         ASSERT3U(drrw->drr_logical_size, >=,
2819                             drrw->drr_compressed_size);
2820                         ASSERT(!is_meta);
2821                         abuf = arc_loan_compressed_buf(
2822                             dmu_objset_spa(ra->os),
2823                             drrw->drr_compressed_size, drrw->drr_logical_size,
2824                             drrw->drr_compressiontype);
2825                 } else {
2826                         abuf = arc_loan_buf(dmu_objset_spa(ra->os),
2827                             is_meta, drrw->drr_logical_size);
2828                 }
2829
2830                 err = receive_read_payload_and_next_header(ra,
2831                     DRR_WRITE_PAYLOAD_SIZE(drrw), abuf->b_data);
2832                 if (err != 0) {
2833                         dmu_return_arcbuf(abuf);
2834                         return (err);
2835                 }
2836                 ra->rrd->write_buf = abuf;
2837                 receive_read_prefetch(ra, drrw->drr_object, drrw->drr_offset,
2838                     drrw->drr_logical_size);
2839                 return (err);
2840         }
2841         case DRR_WRITE_BYREF:
2842         {
2843                 struct drr_write_byref *drrwb =
2844                     &ra->rrd->header.drr_u.drr_write_byref;
2845                 err = receive_read_payload_and_next_header(ra, 0, NULL);
2846                 receive_read_prefetch(ra, drrwb->drr_object, drrwb->drr_offset,
2847                     drrwb->drr_length);
2848                 return (err);
2849         }
2850         case DRR_WRITE_EMBEDDED:
2851         {
2852                 struct drr_write_embedded *drrwe =
2853                     &ra->rrd->header.drr_u.drr_write_embedded;
2854                 uint32_t size = P2ROUNDUP(drrwe->drr_psize, 8);
2855                 void *buf = kmem_zalloc(size, KM_SLEEP);
2856
2857                 err = receive_read_payload_and_next_header(ra, size, buf);
2858                 if (err != 0) {
2859                         kmem_free(buf, size);
2860                         return (err);
2861                 }
2862
2863                 receive_read_prefetch(ra, drrwe->drr_object, drrwe->drr_offset,
2864                     drrwe->drr_length);
2865                 return (err);
2866         }
2867         case DRR_FREE:
2868         {
2869                 /*
2870                  * It might be beneficial to prefetch indirect blocks here, but
2871                  * we don't really have the data to decide for sure.
2872                  */
2873                 err = receive_read_payload_and_next_header(ra, 0, NULL);
2874                 return (err);
2875         }
2876         case DRR_END:
2877         {
2878                 struct drr_end *drre = &ra->rrd->header.drr_u.drr_end;
2879                 if (!ZIO_CHECKSUM_EQUAL(ra->prev_cksum, drre->drr_checksum))
2880                         return (SET_ERROR(ECKSUM));
2881                 return (0);
2882         }
2883         case DRR_SPILL:
2884         {
2885                 struct drr_spill *drrs = &ra->rrd->header.drr_u.drr_spill;
2886                 void *buf = kmem_zalloc(drrs->drr_length, KM_SLEEP);
2887                 err = receive_read_payload_and_next_header(ra, drrs->drr_length,
2888                     buf);
2889                 if (err != 0)
2890                         kmem_free(buf, drrs->drr_length);
2891                 return (err);
2892         }
2893         default:
2894                 return (SET_ERROR(EINVAL));
2895         }
2896 }
2897
2898 /*
2899  * Commit the records to the pool.
2900  */
2901 static int
2902 receive_process_record(struct receive_writer_arg *rwa,
2903     struct receive_record_arg *rrd)
2904 {
2905         int err;
2906
2907         /* Processing in order, therefore bytes_read should be increasing. */
2908         ASSERT3U(rrd->bytes_read, >=, rwa->bytes_read);
2909         rwa->bytes_read = rrd->bytes_read;
2910
2911         switch (rrd->header.drr_type) {
2912         case DRR_OBJECT:
2913         {
2914                 struct drr_object *drro = &rrd->header.drr_u.drr_object;
2915                 err = receive_object(rwa, drro, rrd->payload);
2916                 kmem_free(rrd->payload, rrd->payload_size);
2917                 rrd->payload = NULL;
2918                 return (err);
2919         }
2920         case DRR_FREEOBJECTS:
2921         {
2922                 struct drr_freeobjects *drrfo =
2923                     &rrd->header.drr_u.drr_freeobjects;
2924                 return (receive_freeobjects(rwa, drrfo));
2925         }
2926         case DRR_WRITE:
2927         {
2928                 struct drr_write *drrw = &rrd->header.drr_u.drr_write;
2929                 err = receive_write(rwa, drrw, rrd->write_buf);
2930                 /* if receive_write() is successful, it consumes the arc_buf */
2931                 if (err != 0)
2932                         dmu_return_arcbuf(rrd->write_buf);
2933                 rrd->write_buf = NULL;
2934                 rrd->payload = NULL;
2935                 return (err);
2936         }
2937         case DRR_WRITE_BYREF:
2938         {
2939                 struct drr_write_byref *drrwbr =
2940                     &rrd->header.drr_u.drr_write_byref;
2941                 return (receive_write_byref(rwa, drrwbr));
2942         }
2943         case DRR_WRITE_EMBEDDED:
2944         {
2945                 struct drr_write_embedded *drrwe =
2946                     &rrd->header.drr_u.drr_write_embedded;
2947                 err = receive_write_embedded(rwa, drrwe, rrd->payload);
2948                 kmem_free(rrd->payload, rrd->payload_size);
2949                 rrd->payload = NULL;
2950                 return (err);
2951         }
2952         case DRR_FREE:
2953         {
2954                 struct drr_free *drrf = &rrd->header.drr_u.drr_free;
2955                 return (receive_free(rwa, drrf));
2956         }
2957         case DRR_SPILL:
2958         {
2959                 struct drr_spill *drrs = &rrd->header.drr_u.drr_spill;
2960                 err = receive_spill(rwa, drrs, rrd->payload);
2961                 kmem_free(rrd->payload, rrd->payload_size);
2962                 rrd->payload = NULL;
2963                 return (err);
2964         }
2965         default:
2966                 return (SET_ERROR(EINVAL));
2967         }
2968 }
2969
2970 /*
2971  * dmu_recv_stream's worker thread; pull records off the queue, and then call
2972  * receive_process_record  When we're done, signal the main thread and exit.
2973  */
2974 static void
2975 receive_writer_thread(void *arg)
2976 {
2977         struct receive_writer_arg *rwa = arg;
2978         struct receive_record_arg *rrd;
2979         for (rrd = bqueue_dequeue(&rwa->q); !rrd->eos_marker;
2980             rrd = bqueue_dequeue(&rwa->q)) {
2981                 /*
2982                  * If there's an error, the main thread will stop putting things
2983                  * on the queue, but we need to clear everything in it before we
2984                  * can exit.
2985                  */
2986                 if (rwa->err == 0) {
2987                         rwa->err = receive_process_record(rwa, rrd);
2988                 } else if (rrd->write_buf != NULL) {
2989                         dmu_return_arcbuf(rrd->write_buf);
2990                         rrd->write_buf = NULL;
2991                         rrd->payload = NULL;
2992                 } else if (rrd->payload != NULL) {
2993                         kmem_free(rrd->payload, rrd->payload_size);
2994                         rrd->payload = NULL;
2995                 }
2996                 kmem_free(rrd, sizeof (*rrd));
2997         }
2998         kmem_free(rrd, sizeof (*rrd));
2999         mutex_enter(&rwa->mutex);
3000         rwa->done = B_TRUE;
3001         cv_signal(&rwa->cv);
3002         mutex_exit(&rwa->mutex);
3003         thread_exit();
3004 }
3005
3006 static int
3007 resume_check(struct receive_arg *ra, nvlist_t *begin_nvl)
3008 {
3009         uint64_t val;
3010         objset_t *mos = dmu_objset_pool(ra->os)->dp_meta_objset;
3011         uint64_t dsobj = dmu_objset_id(ra->os);
3012         uint64_t resume_obj, resume_off;
3013
3014         if (nvlist_lookup_uint64(begin_nvl,
3015             "resume_object", &resume_obj) != 0 ||
3016             nvlist_lookup_uint64(begin_nvl,
3017             "resume_offset", &resume_off) != 0) {
3018                 return (SET_ERROR(EINVAL));
3019         }
3020         VERIFY0(zap_lookup(mos, dsobj,
3021             DS_FIELD_RESUME_OBJECT, sizeof (val), 1, &val));
3022         if (resume_obj != val)
3023                 return (SET_ERROR(EINVAL));
3024         VERIFY0(zap_lookup(mos, dsobj,
3025             DS_FIELD_RESUME_OFFSET, sizeof (val), 1, &val));
3026         if (resume_off != val)
3027                 return (SET_ERROR(EINVAL));
3028
3029         return (0);
3030 }
3031
3032 /*
3033  * Read in the stream's records, one by one, and apply them to the pool.  There
3034  * are two threads involved; the thread that calls this function will spin up a
3035  * worker thread, read the records off the stream one by one, and issue
3036  * prefetches for any necessary indirect blocks.  It will then push the records
3037  * onto an internal blocking queue.  The worker thread will pull the records off
3038  * the queue, and actually write the data into the DMU.  This way, the worker
3039  * thread doesn't have to wait for reads to complete, since everything it needs
3040  * (the indirect blocks) will be prefetched.
3041  *
3042  * NB: callers *must* call dmu_recv_end() if this succeeds.
3043  */
3044 int
3045 dmu_recv_stream(dmu_recv_cookie_t *drc, struct file *fp, offset_t *voffp,
3046     int cleanup_fd, uint64_t *action_handlep)
3047 {
3048         int err = 0;
3049         struct receive_arg ra = { 0 };
3050         struct receive_writer_arg rwa = { 0 };
3051         int featureflags;
3052         nvlist_t *begin_nvl = NULL;
3053
3054         ra.byteswap = drc->drc_byteswap;
3055         ra.cksum = drc->drc_cksum;
3056         ra.td = curthread;
3057         ra.fp = fp;
3058         ra.voff = *voffp;
3059
3060         if (dsl_dataset_is_zapified(drc->drc_ds)) {
3061                 (void) zap_lookup(drc->drc_ds->ds_dir->dd_pool->dp_meta_objset,
3062                     drc->drc_ds->ds_object, DS_FIELD_RESUME_BYTES,
3063                     sizeof (ra.bytes_read), 1, &ra.bytes_read);
3064         }
3065
3066         objlist_create(&ra.ignore_objlist);
3067
3068         /* these were verified in dmu_recv_begin */
3069         ASSERT3U(DMU_GET_STREAM_HDRTYPE(drc->drc_drrb->drr_versioninfo), ==,
3070             DMU_SUBSTREAM);
3071         ASSERT3U(drc->drc_drrb->drr_type, <, DMU_OST_NUMTYPES);
3072
3073         /*
3074          * Open the objset we are modifying.
3075          */
3076         VERIFY0(dmu_objset_from_ds(drc->drc_ds, &ra.os));
3077
3078         ASSERT(dsl_dataset_phys(drc->drc_ds)->ds_flags & DS_FLAG_INCONSISTENT);
3079
3080         featureflags = DMU_GET_FEATUREFLAGS(drc->drc_drrb->drr_versioninfo);
3081
3082         /* if this stream is dedup'ed, set up the avl tree for guid mapping */
3083         if (featureflags & DMU_BACKUP_FEATURE_DEDUP) {
3084                 minor_t minor;
3085
3086                 if (cleanup_fd == -1) {
3087                         ra.err = SET_ERROR(EBADF);
3088                         goto out;
3089                 }
3090                 ra.err = zfs_onexit_fd_hold(cleanup_fd, &minor);
3091                 if (ra.err != 0) {
3092                         cleanup_fd = -1;
3093                         goto out;
3094                 }
3095
3096                 if (*action_handlep == 0) {
3097                         rwa.guid_to_ds_map =
3098                             kmem_alloc(sizeof (avl_tree_t), KM_SLEEP);
3099                         avl_create(rwa.guid_to_ds_map, guid_compare,
3100                             sizeof (guid_map_entry_t),
3101                             offsetof(guid_map_entry_t, avlnode));
3102                         err = zfs_onexit_add_cb(minor,
3103                             free_guid_map_onexit, rwa.guid_to_ds_map,
3104                             action_handlep);
3105                         if (ra.err != 0)
3106                                 goto out;
3107                 } else {
3108                         err = zfs_onexit_cb_data(minor, *action_handlep,
3109                             (void **)&rwa.guid_to_ds_map);
3110                         if (ra.err != 0)
3111                                 goto out;
3112                 }
3113
3114                 drc->drc_guid_to_ds_map = rwa.guid_to_ds_map;
3115         }
3116
3117         uint32_t payloadlen = drc->drc_drr_begin->drr_payloadlen;
3118         void *payload = NULL;
3119         if (payloadlen != 0)
3120                 payload = kmem_alloc(payloadlen, KM_SLEEP);
3121
3122         err = receive_read_payload_and_next_header(&ra, payloadlen, payload);
3123         if (err != 0) {
3124                 if (payloadlen != 0)
3125                         kmem_free(payload, payloadlen);
3126                 goto out;
3127         }
3128         if (payloadlen != 0) {
3129                 err = nvlist_unpack(payload, payloadlen, &begin_nvl, KM_SLEEP);
3130                 kmem_free(payload, payloadlen);
3131                 if (err != 0)
3132                         goto out;
3133         }
3134
3135         if (featureflags & DMU_BACKUP_FEATURE_RESUMING) {
3136                 err = resume_check(&ra, begin_nvl);
3137                 if (err != 0)
3138                         goto out;
3139         }
3140
3141         (void) bqueue_init(&rwa.q, zfs_recv_queue_length,
3142             offsetof(struct receive_record_arg, node));
3143         cv_init(&rwa.cv, NULL, CV_DEFAULT, NULL);
3144         mutex_init(&rwa.mutex, NULL, MUTEX_DEFAULT, NULL);
3145         rwa.os = ra.os;
3146         rwa.byteswap = drc->drc_byteswap;
3147         rwa.resumable = drc->drc_resumable;
3148
3149         (void) thread_create(NULL, 0, receive_writer_thread, &rwa, 0, &p0,
3150             TS_RUN, minclsyspri);
3151         /*
3152          * We're reading rwa.err without locks, which is safe since we are the
3153          * only reader, and the worker thread is the only writer.  It's ok if we
3154          * miss a write for an iteration or two of the loop, since the writer
3155          * thread will keep freeing records we send it until we send it an eos
3156          * marker.
3157          *
3158          * We can leave this loop in 3 ways:  First, if rwa.err is
3159          * non-zero.  In that case, the writer thread will free the rrd we just
3160          * pushed.  Second, if  we're interrupted; in that case, either it's the
3161          * first loop and ra.rrd was never allocated, or it's later, and ra.rrd
3162          * has been handed off to the writer thread who will free it.  Finally,
3163          * if receive_read_record fails or we're at the end of the stream, then
3164          * we free ra.rrd and exit.
3165          */
3166         while (rwa.err == 0) {
3167                 if (issig(JUSTLOOKING) && issig(FORREAL)) {
3168                         err = SET_ERROR(EINTR);
3169                         break;
3170                 }
3171
3172                 ASSERT3P(ra.rrd, ==, NULL);
3173                 ra.rrd = ra.next_rrd;
3174                 ra.next_rrd = NULL;
3175                 /* Allocates and loads header into ra.next_rrd */
3176                 err = receive_read_record(&ra);
3177
3178                 if (ra.rrd->header.drr_type == DRR_END || err != 0) {
3179                         kmem_free(ra.rrd, sizeof (*ra.rrd));
3180                         ra.rrd = NULL;
3181                         break;
3182                 }
3183
3184                 bqueue_enqueue(&rwa.q, ra.rrd,
3185                     sizeof (struct receive_record_arg) + ra.rrd->payload_size);
3186                 ra.rrd = NULL;
3187         }
3188         if (ra.next_rrd == NULL)
3189                 ra.next_rrd = kmem_zalloc(sizeof (*ra.next_rrd), KM_SLEEP);
3190         ra.next_rrd->eos_marker = B_TRUE;
3191         bqueue_enqueue(&rwa.q, ra.next_rrd, 1);
3192
3193         mutex_enter(&rwa.mutex);
3194         while (!rwa.done) {
3195                 cv_wait(&rwa.cv, &rwa.mutex);
3196         }
3197         mutex_exit(&rwa.mutex);
3198
3199         /*
3200          * If we are receiving a full stream as a clone, all object IDs which
3201          * are greater than the maximum ID referenced in the stream are
3202          * by definition unused and must be freed. Note that it's possible that
3203          * we've resumed this send and the first record we received was the END
3204          * record. In that case, max_object would be 0, but we shouldn't start
3205          * freeing all objects from there; instead we should start from the
3206          * resumeobj.
3207          */
3208         if (drc->drc_clone && drc->drc_drrb->drr_fromguid == 0) {
3209                 uint64_t obj;
3210                 if (nvlist_lookup_uint64(begin_nvl, "resume_object", &obj) != 0)
3211                         obj = 0;
3212                 if (rwa.max_object > obj)
3213                         obj = rwa.max_object;
3214                 obj++;
3215                 int free_err = 0;
3216                 int next_err = 0;
3217
3218                 while (next_err == 0) {
3219                         free_err = dmu_free_long_object(rwa.os, obj);
3220                         if (free_err != 0 && free_err != ENOENT)
3221                                 break;
3222
3223                         next_err = dmu_object_next(rwa.os, &obj, FALSE, 0);
3224                 }
3225
3226                 if (err == 0) {
3227                         if (free_err != 0 && free_err != ENOENT)
3228                                 err = free_err;
3229                         else if (next_err != ESRCH)
3230                                 err = next_err;
3231                 }
3232         }
3233
3234         cv_destroy(&rwa.cv);
3235         mutex_destroy(&rwa.mutex);
3236         bqueue_destroy(&rwa.q);
3237         if (err == 0)
3238                 err = rwa.err;
3239
3240 out:
3241         nvlist_free(begin_nvl);
3242         if ((featureflags & DMU_BACKUP_FEATURE_DEDUP) && (cleanup_fd != -1))
3243                 zfs_onexit_fd_rele(cleanup_fd);
3244
3245         if (err != 0) {
3246                 /*
3247                  * Clean up references. If receive is not resumable,
3248                  * destroy what we created, so we don't leave it in
3249                  * the inconsistent state.
3250                  */
3251                 dmu_recv_cleanup_ds(drc);
3252         }
3253
3254         *voffp = ra.voff;
3255         objlist_destroy(&ra.ignore_objlist);
3256         return (err);
3257 }
3258
3259 static int
3260 dmu_recv_end_check(void *arg, dmu_tx_t *tx)
3261 {
3262         dmu_recv_cookie_t *drc = arg;
3263         dsl_pool_t *dp = dmu_tx_pool(tx);
3264         int error;
3265
3266         ASSERT3P(drc->drc_ds->ds_owner, ==, dmu_recv_tag);
3267
3268         if (!drc->drc_newfs) {
3269                 dsl_dataset_t *origin_head;
3270
3271                 error = dsl_dataset_hold(dp, drc->drc_tofs, FTAG, &origin_head);
3272                 if (error != 0)
3273                         return (error);
3274                 if (drc->drc_force) {
3275                         /*
3276                          * We will destroy any snapshots in tofs (i.e. before
3277                          * origin_head) that are after the origin (which is
3278                          * the snap before drc_ds, because drc_ds can not
3279                          * have any snaps of its own).
3280                          */
3281                         uint64_t obj;
3282
3283                         obj = dsl_dataset_phys(origin_head)->ds_prev_snap_obj;
3284                         while (obj !=
3285                             dsl_dataset_phys(drc->drc_ds)->ds_prev_snap_obj) {
3286                                 dsl_dataset_t *snap;
3287                                 error = dsl_dataset_hold_obj(dp, obj, FTAG,
3288                                     &snap);
3289                                 if (error != 0)
3290                                         break;
3291                                 if (snap->ds_dir != origin_head->ds_dir)
3292                                         error = SET_ERROR(EINVAL);
3293                                 if (error == 0)  {
3294                                         error = dsl_destroy_snapshot_check_impl(
3295                                             snap, B_FALSE);
3296                                 }
3297                                 obj = dsl_dataset_phys(snap)->ds_prev_snap_obj;
3298                                 dsl_dataset_rele(snap, FTAG);
3299                                 if (error != 0)
3300                                         break;
3301                         }
3302                         if (error != 0) {
3303                                 dsl_dataset_rele(origin_head, FTAG);
3304                                 return (error);
3305                         }
3306                 }
3307                 error = dsl_dataset_clone_swap_check_impl(drc->drc_ds,
3308                     origin_head, drc->drc_force, drc->drc_owner, tx);
3309                 if (error != 0) {
3310                         dsl_dataset_rele(origin_head, FTAG);
3311                         return (error);
3312                 }
3313                 error = dsl_dataset_snapshot_check_impl(origin_head,
3314                     drc->drc_tosnap, tx, B_TRUE, 1, drc->drc_cred);
3315                 dsl_dataset_rele(origin_head, FTAG);
3316                 if (error != 0)
3317                         return (error);
3318
3319                 error = dsl_destroy_head_check_impl(drc->drc_ds, 1);
3320         } else {
3321                 error = dsl_dataset_snapshot_check_impl(drc->drc_ds,
3322                     drc->drc_tosnap, tx, B_TRUE, 1, drc->drc_cred);
3323         }
3324         return (error);
3325 }
3326
3327 static void
3328 dmu_recv_end_sync(void *arg, dmu_tx_t *tx)
3329 {
3330         dmu_recv_cookie_t *drc = arg;
3331         dsl_pool_t *dp = dmu_tx_pool(tx);
3332
3333         spa_history_log_internal_ds(drc->drc_ds, "finish receiving",
3334             tx, "snap=%s", drc->drc_tosnap);
3335
3336         if (!drc->drc_newfs) {
3337                 dsl_dataset_t *origin_head;
3338
3339                 VERIFY0(dsl_dataset_hold(dp, drc->drc_tofs, FTAG,
3340                     &origin_head));
3341
3342                 if (drc->drc_force) {
3343                         /*
3344                          * Destroy any snapshots of drc_tofs (origin_head)
3345                          * after the origin (the snap before drc_ds).
3346                          */
3347                         uint64_t obj;
3348
3349                         obj = dsl_dataset_phys(origin_head)->ds_prev_snap_obj;
3350                         while (obj !=
3351                             dsl_dataset_phys(drc->drc_ds)->ds_prev_snap_obj) {
3352                                 dsl_dataset_t *snap;
3353                                 VERIFY0(dsl_dataset_hold_obj(dp, obj, FTAG,
3354                                     &snap));
3355                                 ASSERT3P(snap->ds_dir, ==, origin_head->ds_dir);
3356                                 obj = dsl_dataset_phys(snap)->ds_prev_snap_obj;
3357                                 dsl_destroy_snapshot_sync_impl(snap,
3358                                     B_FALSE, tx);
3359                                 dsl_dataset_rele(snap, FTAG);
3360                         }
3361                 }
3362                 VERIFY3P(drc->drc_ds->ds_prev, ==,
3363                     origin_head->ds_prev);
3364
3365                 dsl_dataset_clone_swap_sync_impl(drc->drc_ds,
3366                     origin_head, tx);
3367                 dsl_dataset_snapshot_sync_impl(origin_head,
3368                     drc->drc_tosnap, tx);
3369
3370                 /* set snapshot's creation time and guid */
3371                 dmu_buf_will_dirty(origin_head->ds_prev->ds_dbuf, tx);
3372                 dsl_dataset_phys(origin_head->ds_prev)->ds_creation_time =
3373                     drc->drc_drrb->drr_creation_time;
3374                 dsl_dataset_phys(origin_head->ds_prev)->ds_guid =
3375                     drc->drc_drrb->drr_toguid;
3376                 dsl_dataset_phys(origin_head->ds_prev)->ds_flags &=
3377                     ~DS_FLAG_INCONSISTENT;
3378
3379                 dmu_buf_will_dirty(origin_head->ds_dbuf, tx);
3380                 dsl_dataset_phys(origin_head)->ds_flags &=
3381                     ~DS_FLAG_INCONSISTENT;
3382
3383                 drc->drc_newsnapobj =
3384                     dsl_dataset_phys(origin_head)->ds_prev_snap_obj;
3385
3386                 dsl_dataset_rele(origin_head, FTAG);
3387                 dsl_destroy_head_sync_impl(drc->drc_ds, tx);
3388
3389                 if (drc->drc_owner != NULL)
3390                         VERIFY3P(origin_head->ds_owner, ==, drc->drc_owner);
3391         } else {
3392                 dsl_dataset_t *ds = drc->drc_ds;
3393
3394                 dsl_dataset_snapshot_sync_impl(ds, drc->drc_tosnap, tx);
3395
3396                 /* set snapshot's creation time and guid */
3397                 dmu_buf_will_dirty(ds->ds_prev->ds_dbuf, tx);
3398                 dsl_dataset_phys(ds->ds_prev)->ds_creation_time =
3399                     drc->drc_drrb->drr_creation_time;
3400                 dsl_dataset_phys(ds->ds_prev)->ds_guid =
3401                     drc->drc_drrb->drr_toguid;
3402                 dsl_dataset_phys(ds->ds_prev)->ds_flags &=
3403                     ~DS_FLAG_INCONSISTENT;
3404
3405                 dmu_buf_will_dirty(ds->ds_dbuf, tx);
3406                 dsl_dataset_phys(ds)->ds_flags &= ~DS_FLAG_INCONSISTENT;
3407                 if (dsl_dataset_has_resume_receive_state(ds)) {
3408                         (void) zap_remove(dp->dp_meta_objset, ds->ds_object,
3409                             DS_FIELD_RESUME_FROMGUID, tx);
3410                         (void) zap_remove(dp->dp_meta_objset, ds->ds_object,
3411                             DS_FIELD_RESUME_OBJECT, tx);
3412                         (void) zap_remove(dp->dp_meta_objset, ds->ds_object,
3413                             DS_FIELD_RESUME_OFFSET, tx);
3414                         (void) zap_remove(dp->dp_meta_objset, ds->ds_object,
3415                             DS_FIELD_RESUME_BYTES, tx);
3416                         (void) zap_remove(dp->dp_meta_objset, ds->ds_object,
3417                             DS_FIELD_RESUME_TOGUID, tx);
3418                         (void) zap_remove(dp->dp_meta_objset, ds->ds_object,
3419                             DS_FIELD_RESUME_TONAME, tx);
3420                 }
3421                 drc->drc_newsnapobj =
3422                     dsl_dataset_phys(drc->drc_ds)->ds_prev_snap_obj;
3423         }
3424         /*
3425          * Release the hold from dmu_recv_begin.  This must be done before
3426          * we return to open context, so that when we free the dataset's dnode,
3427          * we can evict its bonus buffer.
3428          */
3429         dsl_dataset_disown(drc->drc_ds, dmu_recv_tag);
3430         drc->drc_ds = NULL;
3431 }
3432
3433 static int
3434 add_ds_to_guidmap(const char *name, avl_tree_t *guid_map, uint64_t snapobj)
3435 {
3436         dsl_pool_t *dp;
3437         dsl_dataset_t *snapds;
3438         guid_map_entry_t *gmep;
3439         int err;
3440
3441         ASSERT(guid_map != NULL);
3442
3443         err = dsl_pool_hold(name, FTAG, &dp);
3444         if (err != 0)
3445                 return (err);
3446         gmep = kmem_alloc(sizeof (*gmep), KM_SLEEP);
3447         err = dsl_dataset_hold_obj(dp, snapobj, gmep, &snapds);
3448         if (err == 0) {
3449                 gmep->guid = dsl_dataset_phys(snapds)->ds_guid;
3450                 gmep->gme_ds = snapds;
3451                 avl_add(guid_map, gmep);
3452                 dsl_dataset_long_hold(snapds, gmep);
3453         } else
3454                 kmem_free(gmep, sizeof (*gmep));
3455
3456         dsl_pool_rele(dp, FTAG);
3457         return (err);
3458 }
3459
3460 static int dmu_recv_end_modified_blocks = 3;
3461
3462 static int
3463 dmu_recv_existing_end(dmu_recv_cookie_t *drc)
3464 {
3465 #ifdef _KERNEL
3466         /*
3467          * We will be destroying the ds; make sure its origin is unmounted if
3468          * necessary.
3469          */
3470         char name[ZFS_MAX_DATASET_NAME_LEN];
3471         dsl_dataset_name(drc->drc_ds, name);
3472         zfs_destroy_unmount_origin(name);
3473 #endif
3474
3475         return (dsl_sync_task(drc->drc_tofs,
3476             dmu_recv_end_check, dmu_recv_end_sync, drc,
3477             dmu_recv_end_modified_blocks, ZFS_SPACE_CHECK_NORMAL));
3478 }
3479
3480 static int
3481 dmu_recv_new_end(dmu_recv_cookie_t *drc)
3482 {
3483         return (dsl_sync_task(drc->drc_tofs,
3484             dmu_recv_end_check, dmu_recv_end_sync, drc,
3485             dmu_recv_end_modified_blocks, ZFS_SPACE_CHECK_NORMAL));
3486 }
3487
3488 int
3489 dmu_recv_end(dmu_recv_cookie_t *drc, void *owner)
3490 {
3491         int error;
3492
3493         drc->drc_owner = owner;
3494
3495         if (drc->drc_newfs)
3496                 error = dmu_recv_new_end(drc);
3497         else
3498                 error = dmu_recv_existing_end(drc);
3499
3500         if (error != 0) {
3501                 dmu_recv_cleanup_ds(drc);
3502         } else if (drc->drc_guid_to_ds_map != NULL) {
3503                 (void) add_ds_to_guidmap(drc->drc_tofs,
3504                     drc->drc_guid_to_ds_map,
3505                     drc->drc_newsnapobj);
3506         }
3507         return (error);
3508 }
3509
3510 /*
3511  * Return TRUE if this objset is currently being received into.
3512  */
3513 boolean_t
3514 dmu_objset_is_receiving(objset_t *os)
3515 {
3516         return (os->os_dsl_dataset != NULL &&
3517             os->os_dsl_dataset->ds_owner == dmu_recv_tag);
3518 }