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