xref: /freebsd/sys/contrib/openzfs/module/zfs/dmu_objset.c (revision 1db64f89363c97858961c4df0b7d02f3223723cf)
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 https://opensource.org/licenses/CDDL-1.0.
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 /*
23  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright (c) 2012, 2020 by Delphix. All rights reserved.
25  * Copyright (c) 2013 by Saso Kiselkov. All rights reserved.
26  * Copyright (c) 2013, Joyent, Inc. All rights reserved.
27  * Copyright (c) 2014 Spectra Logic Corporation, All rights reserved.
28  * Copyright (c) 2015, STRATO AG, Inc. All rights reserved.
29  * Copyright (c) 2016 Actifio, Inc. All rights reserved.
30  * Copyright 2017 Nexenta Systems, Inc.
31  * Copyright (c) 2017 Open-E, Inc. All Rights Reserved.
32  * Copyright (c) 2018, loli10K <ezomori.nozomu@gmail.com>. All rights reserved.
33  * Copyright (c) 2019, Klara Inc.
34  * Copyright (c) 2019, Allan Jude
35  * Copyright (c) 2022 Hewlett Packard Enterprise Development LP.
36  */
37 
38 /* Portions Copyright 2010 Robert Milkowski */
39 
40 #include <sys/cred.h>
41 #include <sys/zfs_context.h>
42 #include <sys/dmu_objset.h>
43 #include <sys/dsl_dir.h>
44 #include <sys/dsl_dataset.h>
45 #include <sys/dsl_prop.h>
46 #include <sys/dsl_pool.h>
47 #include <sys/dsl_synctask.h>
48 #include <sys/dsl_deleg.h>
49 #include <sys/dnode.h>
50 #include <sys/dbuf.h>
51 #include <sys/zvol.h>
52 #include <sys/dmu_tx.h>
53 #include <sys/zap.h>
54 #include <sys/zil.h>
55 #include <sys/dmu_impl.h>
56 #include <sys/zfs_ioctl.h>
57 #include <sys/sa.h>
58 #include <sys/zfs_onexit.h>
59 #include <sys/dsl_destroy.h>
60 #include <sys/vdev.h>
61 #include <sys/zfeature.h>
62 #include <sys/policy.h>
63 #include <sys/spa_impl.h>
64 #include <sys/dmu_recv.h>
65 #include <sys/zfs_project.h>
66 #include "zfs_namecheck.h"
67 #include <sys/vdev_impl.h>
68 #include <sys/arc.h>
69 
70 /*
71  * Needed to close a window in dnode_move() that allows the objset to be freed
72  * before it can be safely accessed.
73  */
74 krwlock_t os_lock;
75 
76 /*
77  * Tunable to overwrite the maximum number of threads for the parallelization
78  * of dmu_objset_find_dp, needed to speed up the import of pools with many
79  * datasets.
80  * Default is 4 times the number of leaf vdevs.
81  */
82 static const int dmu_find_threads = 0;
83 
84 /*
85  * Backfill lower metadnode objects after this many have been freed.
86  * Backfilling negatively impacts object creation rates, so only do it
87  * if there are enough holes to fill.
88  */
89 static const int dmu_rescan_dnode_threshold = 1 << DN_MAX_INDBLKSHIFT;
90 
91 static const char *upgrade_tag = "upgrade_tag";
92 
93 static void dmu_objset_find_dp_cb(void *arg);
94 
95 static void dmu_objset_upgrade(objset_t *os, dmu_objset_upgrade_cb_t cb);
96 static void dmu_objset_upgrade_stop(objset_t *os);
97 
98 void
99 dmu_objset_init(void)
100 {
101 	rw_init(&os_lock, NULL, RW_DEFAULT, NULL);
102 }
103 
104 void
105 dmu_objset_fini(void)
106 {
107 	rw_destroy(&os_lock);
108 }
109 
110 spa_t *
111 dmu_objset_spa(objset_t *os)
112 {
113 	return (os->os_spa);
114 }
115 
116 zilog_t *
117 dmu_objset_zil(objset_t *os)
118 {
119 	return (os->os_zil);
120 }
121 
122 dsl_pool_t *
123 dmu_objset_pool(objset_t *os)
124 {
125 	dsl_dataset_t *ds;
126 
127 	if ((ds = os->os_dsl_dataset) != NULL && ds->ds_dir)
128 		return (ds->ds_dir->dd_pool);
129 	else
130 		return (spa_get_dsl(os->os_spa));
131 }
132 
133 dsl_dataset_t *
134 dmu_objset_ds(objset_t *os)
135 {
136 	return (os->os_dsl_dataset);
137 }
138 
139 dmu_objset_type_t
140 dmu_objset_type(objset_t *os)
141 {
142 	return (os->os_phys->os_type);
143 }
144 
145 void
146 dmu_objset_name(objset_t *os, char *buf)
147 {
148 	dsl_dataset_name(os->os_dsl_dataset, buf);
149 }
150 
151 uint64_t
152 dmu_objset_id(objset_t *os)
153 {
154 	dsl_dataset_t *ds = os->os_dsl_dataset;
155 
156 	return (ds ? ds->ds_object : 0);
157 }
158 
159 uint64_t
160 dmu_objset_dnodesize(objset_t *os)
161 {
162 	return (os->os_dnodesize);
163 }
164 
165 zfs_sync_type_t
166 dmu_objset_syncprop(objset_t *os)
167 {
168 	return (os->os_sync);
169 }
170 
171 zfs_logbias_op_t
172 dmu_objset_logbias(objset_t *os)
173 {
174 	return (os->os_logbias);
175 }
176 
177 static void
178 checksum_changed_cb(void *arg, uint64_t newval)
179 {
180 	objset_t *os = arg;
181 
182 	/*
183 	 * Inheritance should have been done by now.
184 	 */
185 	ASSERT(newval != ZIO_CHECKSUM_INHERIT);
186 
187 	os->os_checksum = zio_checksum_select(newval, ZIO_CHECKSUM_ON_VALUE);
188 }
189 
190 static void
191 compression_changed_cb(void *arg, uint64_t newval)
192 {
193 	objset_t *os = arg;
194 
195 	/*
196 	 * Inheritance and range checking should have been done by now.
197 	 */
198 	ASSERT(newval != ZIO_COMPRESS_INHERIT);
199 
200 	os->os_compress = zio_compress_select(os->os_spa,
201 	    ZIO_COMPRESS_ALGO(newval), ZIO_COMPRESS_ON);
202 	os->os_complevel = zio_complevel_select(os->os_spa, os->os_compress,
203 	    ZIO_COMPRESS_LEVEL(newval), ZIO_COMPLEVEL_DEFAULT);
204 }
205 
206 static void
207 copies_changed_cb(void *arg, uint64_t newval)
208 {
209 	objset_t *os = arg;
210 
211 	/*
212 	 * Inheritance and range checking should have been done by now.
213 	 */
214 	ASSERT(newval > 0);
215 	ASSERT(newval <= spa_max_replication(os->os_spa));
216 
217 	os->os_copies = newval;
218 }
219 
220 static void
221 dedup_changed_cb(void *arg, uint64_t newval)
222 {
223 	objset_t *os = arg;
224 	spa_t *spa = os->os_spa;
225 	enum zio_checksum checksum;
226 
227 	/*
228 	 * Inheritance should have been done by now.
229 	 */
230 	ASSERT(newval != ZIO_CHECKSUM_INHERIT);
231 
232 	checksum = zio_checksum_dedup_select(spa, newval, ZIO_CHECKSUM_OFF);
233 
234 	os->os_dedup_checksum = checksum & ZIO_CHECKSUM_MASK;
235 	os->os_dedup_verify = !!(checksum & ZIO_CHECKSUM_VERIFY);
236 }
237 
238 static void
239 primary_cache_changed_cb(void *arg, uint64_t newval)
240 {
241 	objset_t *os = arg;
242 
243 	/*
244 	 * Inheritance and range checking should have been done by now.
245 	 */
246 	ASSERT(newval == ZFS_CACHE_ALL || newval == ZFS_CACHE_NONE ||
247 	    newval == ZFS_CACHE_METADATA);
248 
249 	os->os_primary_cache = newval;
250 }
251 
252 static void
253 secondary_cache_changed_cb(void *arg, uint64_t newval)
254 {
255 	objset_t *os = arg;
256 
257 	/*
258 	 * Inheritance and range checking should have been done by now.
259 	 */
260 	ASSERT(newval == ZFS_CACHE_ALL || newval == ZFS_CACHE_NONE ||
261 	    newval == ZFS_CACHE_METADATA);
262 
263 	os->os_secondary_cache = newval;
264 }
265 
266 static void
267 prefetch_changed_cb(void *arg, uint64_t newval)
268 {
269 	objset_t *os = arg;
270 
271 	/*
272 	 * Inheritance should have been done by now.
273 	 */
274 	ASSERT(newval == ZFS_PREFETCH_ALL || newval == ZFS_PREFETCH_NONE ||
275 	    newval == ZFS_PREFETCH_METADATA);
276 	os->os_prefetch = newval;
277 }
278 
279 static void
280 sync_changed_cb(void *arg, uint64_t newval)
281 {
282 	objset_t *os = arg;
283 
284 	/*
285 	 * Inheritance and range checking should have been done by now.
286 	 */
287 	ASSERT(newval == ZFS_SYNC_STANDARD || newval == ZFS_SYNC_ALWAYS ||
288 	    newval == ZFS_SYNC_DISABLED);
289 
290 	os->os_sync = newval;
291 	if (os->os_zil)
292 		zil_set_sync(os->os_zil, newval);
293 }
294 
295 static void
296 redundant_metadata_changed_cb(void *arg, uint64_t newval)
297 {
298 	objset_t *os = arg;
299 
300 	/*
301 	 * Inheritance and range checking should have been done by now.
302 	 */
303 	ASSERT(newval == ZFS_REDUNDANT_METADATA_ALL ||
304 	    newval == ZFS_REDUNDANT_METADATA_MOST ||
305 	    newval == ZFS_REDUNDANT_METADATA_SOME ||
306 	    newval == ZFS_REDUNDANT_METADATA_NONE);
307 
308 	os->os_redundant_metadata = newval;
309 }
310 
311 static void
312 dnodesize_changed_cb(void *arg, uint64_t newval)
313 {
314 	objset_t *os = arg;
315 
316 	switch (newval) {
317 	case ZFS_DNSIZE_LEGACY:
318 		os->os_dnodesize = DNODE_MIN_SIZE;
319 		break;
320 	case ZFS_DNSIZE_AUTO:
321 		/*
322 		 * Choose a dnode size that will work well for most
323 		 * workloads if the user specified "auto". Future code
324 		 * improvements could dynamically select a dnode size
325 		 * based on observed workload patterns.
326 		 */
327 		os->os_dnodesize = DNODE_MIN_SIZE * 2;
328 		break;
329 	case ZFS_DNSIZE_1K:
330 	case ZFS_DNSIZE_2K:
331 	case ZFS_DNSIZE_4K:
332 	case ZFS_DNSIZE_8K:
333 	case ZFS_DNSIZE_16K:
334 		os->os_dnodesize = newval;
335 		break;
336 	}
337 }
338 
339 static void
340 smallblk_changed_cb(void *arg, uint64_t newval)
341 {
342 	objset_t *os = arg;
343 
344 	/*
345 	 * Inheritance and range checking should have been done by now.
346 	 */
347 	ASSERT(newval <= SPA_MAXBLOCKSIZE);
348 	ASSERT(ISP2(newval));
349 
350 	os->os_zpl_special_smallblock = newval;
351 }
352 
353 static void
354 logbias_changed_cb(void *arg, uint64_t newval)
355 {
356 	objset_t *os = arg;
357 
358 	ASSERT(newval == ZFS_LOGBIAS_LATENCY ||
359 	    newval == ZFS_LOGBIAS_THROUGHPUT);
360 	os->os_logbias = newval;
361 	if (os->os_zil)
362 		zil_set_logbias(os->os_zil, newval);
363 }
364 
365 static void
366 recordsize_changed_cb(void *arg, uint64_t newval)
367 {
368 	objset_t *os = arg;
369 
370 	os->os_recordsize = newval;
371 }
372 
373 void
374 dmu_objset_byteswap(void *buf, size_t size)
375 {
376 	objset_phys_t *osp = buf;
377 
378 	ASSERT(size == OBJSET_PHYS_SIZE_V1 || size == OBJSET_PHYS_SIZE_V2 ||
379 	    size == sizeof (objset_phys_t));
380 	dnode_byteswap(&osp->os_meta_dnode);
381 	byteswap_uint64_array(&osp->os_zil_header, sizeof (zil_header_t));
382 	osp->os_type = BSWAP_64(osp->os_type);
383 	osp->os_flags = BSWAP_64(osp->os_flags);
384 	if (size >= OBJSET_PHYS_SIZE_V2) {
385 		dnode_byteswap(&osp->os_userused_dnode);
386 		dnode_byteswap(&osp->os_groupused_dnode);
387 		if (size >= sizeof (objset_phys_t))
388 			dnode_byteswap(&osp->os_projectused_dnode);
389 	}
390 }
391 
392 /*
393  * The hash is a CRC-based hash of the objset_t pointer and the object number.
394  */
395 static uint64_t
396 dnode_hash(const objset_t *os, uint64_t obj)
397 {
398 	uintptr_t osv = (uintptr_t)os;
399 	uint64_t crc = -1ULL;
400 
401 	ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
402 	/*
403 	 * The low 6 bits of the pointer don't have much entropy, because
404 	 * the objset_t is larger than 2^6 bytes long.
405 	 */
406 	crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (osv >> 6)) & 0xFF];
407 	crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (obj >> 0)) & 0xFF];
408 	crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (obj >> 8)) & 0xFF];
409 	crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (obj >> 16)) & 0xFF];
410 
411 	crc ^= (osv>>14) ^ (obj>>24);
412 
413 	return (crc);
414 }
415 
416 static unsigned int
417 dnode_multilist_index_func(multilist_t *ml, void *obj)
418 {
419 	dnode_t *dn = obj;
420 
421 	/*
422 	 * The low order bits of the hash value are thought to be
423 	 * distributed evenly. Otherwise, in the case that the multilist
424 	 * has a power of two number of sublists, each sublists' usage
425 	 * would not be evenly distributed. In this context full 64bit
426 	 * division would be a waste of time, so limit it to 32 bits.
427 	 */
428 	return ((unsigned int)dnode_hash(dn->dn_objset, dn->dn_object) %
429 	    multilist_get_num_sublists(ml));
430 }
431 
432 static inline boolean_t
433 dmu_os_is_l2cacheable(objset_t *os)
434 {
435 	if (os->os_secondary_cache == ZFS_CACHE_ALL ||
436 	    os->os_secondary_cache == ZFS_CACHE_METADATA) {
437 		if (l2arc_exclude_special == 0)
438 			return (B_TRUE);
439 
440 		blkptr_t *bp = os->os_rootbp;
441 		if (bp == NULL || BP_IS_HOLE(bp))
442 			return (B_FALSE);
443 		uint64_t vdev = DVA_GET_VDEV(bp->blk_dva);
444 		vdev_t *rvd = os->os_spa->spa_root_vdev;
445 		vdev_t *vd = NULL;
446 
447 		if (vdev < rvd->vdev_children)
448 			vd = rvd->vdev_child[vdev];
449 
450 		if (vd == NULL)
451 			return (B_TRUE);
452 
453 		if (vd->vdev_alloc_bias != VDEV_BIAS_SPECIAL &&
454 		    vd->vdev_alloc_bias != VDEV_BIAS_DEDUP)
455 			return (B_TRUE);
456 	}
457 	return (B_FALSE);
458 }
459 
460 /*
461  * Instantiates the objset_t in-memory structure corresponding to the
462  * objset_phys_t that's pointed to by the specified blkptr_t.
463  */
464 int
465 dmu_objset_open_impl(spa_t *spa, dsl_dataset_t *ds, blkptr_t *bp,
466     objset_t **osp)
467 {
468 	objset_t *os;
469 	int i, err;
470 
471 	ASSERT(ds == NULL || MUTEX_HELD(&ds->ds_opening_lock));
472 	ASSERT(!BP_IS_REDACTED(bp));
473 
474 	/*
475 	 * We need the pool config lock to get properties.
476 	 */
477 	ASSERT(ds == NULL || dsl_pool_config_held(ds->ds_dir->dd_pool));
478 
479 	/*
480 	 * The $ORIGIN dataset (if it exists) doesn't have an associated
481 	 * objset, so there's no reason to open it. The $ORIGIN dataset
482 	 * will not exist on pools older than SPA_VERSION_ORIGIN.
483 	 */
484 	if (ds != NULL && spa_get_dsl(spa) != NULL &&
485 	    spa_get_dsl(spa)->dp_origin_snap != NULL) {
486 		ASSERT3P(ds->ds_dir, !=,
487 		    spa_get_dsl(spa)->dp_origin_snap->ds_dir);
488 	}
489 
490 	os = kmem_zalloc(sizeof (objset_t), KM_SLEEP);
491 	os->os_dsl_dataset = ds;
492 	os->os_spa = spa;
493 	os->os_rootbp = bp;
494 	if (!BP_IS_HOLE(os->os_rootbp)) {
495 		arc_flags_t aflags = ARC_FLAG_WAIT;
496 		zbookmark_phys_t zb;
497 		int size;
498 		zio_flag_t zio_flags = ZIO_FLAG_CANFAIL;
499 		SET_BOOKMARK(&zb, ds ? ds->ds_object : DMU_META_OBJSET,
500 		    ZB_ROOT_OBJECT, ZB_ROOT_LEVEL, ZB_ROOT_BLKID);
501 
502 		if (dmu_os_is_l2cacheable(os))
503 			aflags |= ARC_FLAG_L2CACHE;
504 
505 		if (ds != NULL && ds->ds_dir->dd_crypto_obj != 0) {
506 			ASSERT3U(BP_GET_COMPRESS(bp), ==, ZIO_COMPRESS_OFF);
507 			ASSERT(BP_IS_AUTHENTICATED(bp));
508 			zio_flags |= ZIO_FLAG_RAW;
509 		}
510 
511 		dprintf_bp(os->os_rootbp, "reading %s", "");
512 		err = arc_read(NULL, spa, os->os_rootbp,
513 		    arc_getbuf_func, &os->os_phys_buf,
514 		    ZIO_PRIORITY_SYNC_READ, zio_flags, &aflags, &zb);
515 		if (err != 0) {
516 			kmem_free(os, sizeof (objset_t));
517 			/* convert checksum errors into IO errors */
518 			if (err == ECKSUM)
519 				err = SET_ERROR(EIO);
520 			return (err);
521 		}
522 
523 		if (spa_version(spa) < SPA_VERSION_USERSPACE)
524 			size = OBJSET_PHYS_SIZE_V1;
525 		else if (!spa_feature_is_enabled(spa,
526 		    SPA_FEATURE_PROJECT_QUOTA))
527 			size = OBJSET_PHYS_SIZE_V2;
528 		else
529 			size = sizeof (objset_phys_t);
530 
531 		/* Increase the blocksize if we are permitted. */
532 		if (arc_buf_size(os->os_phys_buf) < size) {
533 			arc_buf_t *buf = arc_alloc_buf(spa, &os->os_phys_buf,
534 			    ARC_BUFC_METADATA, size);
535 			memset(buf->b_data, 0, size);
536 			memcpy(buf->b_data, os->os_phys_buf->b_data,
537 			    arc_buf_size(os->os_phys_buf));
538 			arc_buf_destroy(os->os_phys_buf, &os->os_phys_buf);
539 			os->os_phys_buf = buf;
540 		}
541 
542 		os->os_phys = os->os_phys_buf->b_data;
543 		os->os_flags = os->os_phys->os_flags;
544 	} else {
545 		int size = spa_version(spa) >= SPA_VERSION_USERSPACE ?
546 		    sizeof (objset_phys_t) : OBJSET_PHYS_SIZE_V1;
547 		os->os_phys_buf = arc_alloc_buf(spa, &os->os_phys_buf,
548 		    ARC_BUFC_METADATA, size);
549 		os->os_phys = os->os_phys_buf->b_data;
550 		memset(os->os_phys, 0, size);
551 	}
552 	/*
553 	 * These properties will be filled in by the logic in zfs_get_zplprop()
554 	 * when they are queried for the first time.
555 	 */
556 	os->os_version = OBJSET_PROP_UNINITIALIZED;
557 	os->os_normalization = OBJSET_PROP_UNINITIALIZED;
558 	os->os_utf8only = OBJSET_PROP_UNINITIALIZED;
559 	os->os_casesensitivity = OBJSET_PROP_UNINITIALIZED;
560 
561 	/*
562 	 * Note: the changed_cb will be called once before the register
563 	 * func returns, thus changing the checksum/compression from the
564 	 * default (fletcher2/off).  Snapshots don't need to know about
565 	 * checksum/compression/copies.
566 	 */
567 	if (ds != NULL) {
568 		os->os_encrypted = (ds->ds_dir->dd_crypto_obj != 0);
569 
570 		err = dsl_prop_register(ds,
571 		    zfs_prop_to_name(ZFS_PROP_PRIMARYCACHE),
572 		    primary_cache_changed_cb, os);
573 		if (err == 0) {
574 			err = dsl_prop_register(ds,
575 			    zfs_prop_to_name(ZFS_PROP_SECONDARYCACHE),
576 			    secondary_cache_changed_cb, os);
577 		}
578 		if (err == 0) {
579 			err = dsl_prop_register(ds,
580 			    zfs_prop_to_name(ZFS_PROP_PREFETCH),
581 			    prefetch_changed_cb, os);
582 		}
583 		if (!ds->ds_is_snapshot) {
584 			if (err == 0) {
585 				err = dsl_prop_register(ds,
586 				    zfs_prop_to_name(ZFS_PROP_CHECKSUM),
587 				    checksum_changed_cb, os);
588 			}
589 			if (err == 0) {
590 				err = dsl_prop_register(ds,
591 				    zfs_prop_to_name(ZFS_PROP_COMPRESSION),
592 				    compression_changed_cb, os);
593 			}
594 			if (err == 0) {
595 				err = dsl_prop_register(ds,
596 				    zfs_prop_to_name(ZFS_PROP_COPIES),
597 				    copies_changed_cb, os);
598 			}
599 			if (err == 0) {
600 				err = dsl_prop_register(ds,
601 				    zfs_prop_to_name(ZFS_PROP_DEDUP),
602 				    dedup_changed_cb, os);
603 			}
604 			if (err == 0) {
605 				err = dsl_prop_register(ds,
606 				    zfs_prop_to_name(ZFS_PROP_LOGBIAS),
607 				    logbias_changed_cb, os);
608 			}
609 			if (err == 0) {
610 				err = dsl_prop_register(ds,
611 				    zfs_prop_to_name(ZFS_PROP_SYNC),
612 				    sync_changed_cb, os);
613 			}
614 			if (err == 0) {
615 				err = dsl_prop_register(ds,
616 				    zfs_prop_to_name(
617 				    ZFS_PROP_REDUNDANT_METADATA),
618 				    redundant_metadata_changed_cb, os);
619 			}
620 			if (err == 0) {
621 				err = dsl_prop_register(ds,
622 				    zfs_prop_to_name(ZFS_PROP_RECORDSIZE),
623 				    recordsize_changed_cb, os);
624 			}
625 			if (err == 0) {
626 				err = dsl_prop_register(ds,
627 				    zfs_prop_to_name(ZFS_PROP_DNODESIZE),
628 				    dnodesize_changed_cb, os);
629 			}
630 			if (err == 0) {
631 				err = dsl_prop_register(ds,
632 				    zfs_prop_to_name(
633 				    ZFS_PROP_SPECIAL_SMALL_BLOCKS),
634 				    smallblk_changed_cb, os);
635 			}
636 		}
637 		if (err != 0) {
638 			arc_buf_destroy(os->os_phys_buf, &os->os_phys_buf);
639 			kmem_free(os, sizeof (objset_t));
640 			return (err);
641 		}
642 	} else {
643 		/* It's the meta-objset. */
644 		os->os_checksum = ZIO_CHECKSUM_FLETCHER_4;
645 		os->os_compress = ZIO_COMPRESS_ON;
646 		os->os_complevel = ZIO_COMPLEVEL_DEFAULT;
647 		os->os_encrypted = B_FALSE;
648 		os->os_copies = spa_max_replication(spa);
649 		os->os_dedup_checksum = ZIO_CHECKSUM_OFF;
650 		os->os_dedup_verify = B_FALSE;
651 		os->os_logbias = ZFS_LOGBIAS_LATENCY;
652 		os->os_sync = ZFS_SYNC_STANDARD;
653 		os->os_primary_cache = ZFS_CACHE_ALL;
654 		os->os_secondary_cache = ZFS_CACHE_ALL;
655 		os->os_dnodesize = DNODE_MIN_SIZE;
656 		os->os_prefetch = ZFS_PREFETCH_ALL;
657 	}
658 
659 	if (ds == NULL || !ds->ds_is_snapshot)
660 		os->os_zil_header = os->os_phys->os_zil_header;
661 	os->os_zil = zil_alloc(os, &os->os_zil_header);
662 
663 	for (i = 0; i < TXG_SIZE; i++) {
664 		multilist_create(&os->os_dirty_dnodes[i], sizeof (dnode_t),
665 		    offsetof(dnode_t, dn_dirty_link[i]),
666 		    dnode_multilist_index_func);
667 	}
668 	list_create(&os->os_dnodes, sizeof (dnode_t),
669 	    offsetof(dnode_t, dn_link));
670 	list_create(&os->os_downgraded_dbufs, sizeof (dmu_buf_impl_t),
671 	    offsetof(dmu_buf_impl_t, db_link));
672 
673 	list_link_init(&os->os_evicting_node);
674 
675 	mutex_init(&os->os_lock, NULL, MUTEX_DEFAULT, NULL);
676 	mutex_init(&os->os_userused_lock, NULL, MUTEX_DEFAULT, NULL);
677 	mutex_init(&os->os_obj_lock, NULL, MUTEX_DEFAULT, NULL);
678 	mutex_init(&os->os_user_ptr_lock, NULL, MUTEX_DEFAULT, NULL);
679 	os->os_obj_next_percpu_len = boot_ncpus;
680 	os->os_obj_next_percpu = kmem_zalloc(os->os_obj_next_percpu_len *
681 	    sizeof (os->os_obj_next_percpu[0]), KM_SLEEP);
682 
683 	dnode_special_open(os, &os->os_phys->os_meta_dnode,
684 	    DMU_META_DNODE_OBJECT, &os->os_meta_dnode);
685 	if (OBJSET_BUF_HAS_USERUSED(os->os_phys_buf)) {
686 		dnode_special_open(os, &os->os_phys->os_userused_dnode,
687 		    DMU_USERUSED_OBJECT, &os->os_userused_dnode);
688 		dnode_special_open(os, &os->os_phys->os_groupused_dnode,
689 		    DMU_GROUPUSED_OBJECT, &os->os_groupused_dnode);
690 		if (OBJSET_BUF_HAS_PROJECTUSED(os->os_phys_buf))
691 			dnode_special_open(os,
692 			    &os->os_phys->os_projectused_dnode,
693 			    DMU_PROJECTUSED_OBJECT, &os->os_projectused_dnode);
694 	}
695 
696 	mutex_init(&os->os_upgrade_lock, NULL, MUTEX_DEFAULT, NULL);
697 
698 	*osp = os;
699 	return (0);
700 }
701 
702 int
703 dmu_objset_from_ds(dsl_dataset_t *ds, objset_t **osp)
704 {
705 	int err = 0;
706 
707 	/*
708 	 * We need the pool_config lock to manipulate the dsl_dataset_t.
709 	 * Even if the dataset is long-held, we need the pool_config lock
710 	 * to open the objset, as it needs to get properties.
711 	 */
712 	ASSERT(dsl_pool_config_held(ds->ds_dir->dd_pool));
713 
714 	mutex_enter(&ds->ds_opening_lock);
715 	if (ds->ds_objset == NULL) {
716 		objset_t *os;
717 		rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);
718 		err = dmu_objset_open_impl(dsl_dataset_get_spa(ds),
719 		    ds, dsl_dataset_get_blkptr(ds), &os);
720 		rrw_exit(&ds->ds_bp_rwlock, FTAG);
721 
722 		if (err == 0) {
723 			mutex_enter(&ds->ds_lock);
724 			ASSERT(ds->ds_objset == NULL);
725 			ds->ds_objset = os;
726 			mutex_exit(&ds->ds_lock);
727 		}
728 	}
729 	*osp = ds->ds_objset;
730 	mutex_exit(&ds->ds_opening_lock);
731 	return (err);
732 }
733 
734 /*
735  * Holds the pool while the objset is held.  Therefore only one objset
736  * can be held at a time.
737  */
738 int
739 dmu_objset_hold_flags(const char *name, boolean_t decrypt, const void *tag,
740     objset_t **osp)
741 {
742 	dsl_pool_t *dp;
743 	dsl_dataset_t *ds;
744 	int err;
745 	ds_hold_flags_t flags;
746 
747 	flags = (decrypt) ? DS_HOLD_FLAG_DECRYPT : DS_HOLD_FLAG_NONE;
748 	err = dsl_pool_hold(name, tag, &dp);
749 	if (err != 0)
750 		return (err);
751 	err = dsl_dataset_hold_flags(dp, name, flags, tag, &ds);
752 	if (err != 0) {
753 		dsl_pool_rele(dp, tag);
754 		return (err);
755 	}
756 
757 	err = dmu_objset_from_ds(ds, osp);
758 	if (err != 0) {
759 		dsl_dataset_rele(ds, tag);
760 		dsl_pool_rele(dp, tag);
761 	}
762 
763 	return (err);
764 }
765 
766 int
767 dmu_objset_hold(const char *name, const void *tag, objset_t **osp)
768 {
769 	return (dmu_objset_hold_flags(name, B_FALSE, tag, osp));
770 }
771 
772 static int
773 dmu_objset_own_impl(dsl_dataset_t *ds, dmu_objset_type_t type,
774     boolean_t readonly, boolean_t decrypt, const void *tag, objset_t **osp)
775 {
776 	(void) tag;
777 
778 	int err = dmu_objset_from_ds(ds, osp);
779 	if (err != 0) {
780 		return (err);
781 	} else if (type != DMU_OST_ANY && type != (*osp)->os_phys->os_type) {
782 		return (SET_ERROR(EINVAL));
783 	} else if (!readonly && dsl_dataset_is_snapshot(ds)) {
784 		return (SET_ERROR(EROFS));
785 	} else if (!readonly && decrypt &&
786 	    dsl_dir_incompatible_encryption_version(ds->ds_dir)) {
787 		return (SET_ERROR(EROFS));
788 	}
789 
790 	/* if we are decrypting, we can now check MACs in os->os_phys_buf */
791 	if (decrypt && arc_is_unauthenticated((*osp)->os_phys_buf)) {
792 		zbookmark_phys_t zb;
793 
794 		SET_BOOKMARK(&zb, ds->ds_object, ZB_ROOT_OBJECT,
795 		    ZB_ROOT_LEVEL, ZB_ROOT_BLKID);
796 		err = arc_untransform((*osp)->os_phys_buf, (*osp)->os_spa,
797 		    &zb, B_FALSE);
798 		if (err != 0)
799 			return (err);
800 
801 		ASSERT0(arc_is_unauthenticated((*osp)->os_phys_buf));
802 	}
803 
804 	return (0);
805 }
806 
807 /*
808  * dsl_pool must not be held when this is called.
809  * Upon successful return, there will be a longhold on the dataset,
810  * and the dsl_pool will not be held.
811  */
812 int
813 dmu_objset_own(const char *name, dmu_objset_type_t type,
814     boolean_t readonly, boolean_t decrypt, const void *tag, objset_t **osp)
815 {
816 	dsl_pool_t *dp;
817 	dsl_dataset_t *ds;
818 	int err;
819 	ds_hold_flags_t flags;
820 
821 	flags = (decrypt) ? DS_HOLD_FLAG_DECRYPT : DS_HOLD_FLAG_NONE;
822 	err = dsl_pool_hold(name, FTAG, &dp);
823 	if (err != 0)
824 		return (err);
825 	err = dsl_dataset_own(dp, name, flags, tag, &ds);
826 	if (err != 0) {
827 		dsl_pool_rele(dp, FTAG);
828 		return (err);
829 	}
830 	err = dmu_objset_own_impl(ds, type, readonly, decrypt, tag, osp);
831 	if (err != 0) {
832 		dsl_dataset_disown(ds, flags, tag);
833 		dsl_pool_rele(dp, FTAG);
834 		return (err);
835 	}
836 
837 	/*
838 	 * User accounting requires the dataset to be decrypted and rw.
839 	 * We also don't begin user accounting during claiming to help
840 	 * speed up pool import times and to keep this txg reserved
841 	 * completely for recovery work.
842 	 */
843 	if (!readonly && !dp->dp_spa->spa_claiming &&
844 	    (ds->ds_dir->dd_crypto_obj == 0 || decrypt)) {
845 		if (dmu_objset_userobjspace_upgradable(*osp) ||
846 		    dmu_objset_projectquota_upgradable(*osp)) {
847 			dmu_objset_id_quota_upgrade(*osp);
848 		} else if (dmu_objset_userused_enabled(*osp)) {
849 			dmu_objset_userspace_upgrade(*osp);
850 		}
851 	}
852 
853 	dsl_pool_rele(dp, FTAG);
854 	return (0);
855 }
856 
857 int
858 dmu_objset_own_obj(dsl_pool_t *dp, uint64_t obj, dmu_objset_type_t type,
859     boolean_t readonly, boolean_t decrypt, const void *tag, objset_t **osp)
860 {
861 	dsl_dataset_t *ds;
862 	int err;
863 	ds_hold_flags_t flags;
864 
865 	flags = (decrypt) ? DS_HOLD_FLAG_DECRYPT : DS_HOLD_FLAG_NONE;
866 	err = dsl_dataset_own_obj(dp, obj, flags, tag, &ds);
867 	if (err != 0)
868 		return (err);
869 
870 	err = dmu_objset_own_impl(ds, type, readonly, decrypt, tag, osp);
871 	if (err != 0) {
872 		dsl_dataset_disown(ds, flags, tag);
873 		return (err);
874 	}
875 
876 	return (0);
877 }
878 
879 void
880 dmu_objset_rele_flags(objset_t *os, boolean_t decrypt, const void *tag)
881 {
882 	ds_hold_flags_t flags;
883 	dsl_pool_t *dp = dmu_objset_pool(os);
884 
885 	flags = (decrypt) ? DS_HOLD_FLAG_DECRYPT : DS_HOLD_FLAG_NONE;
886 	dsl_dataset_rele_flags(os->os_dsl_dataset, flags, tag);
887 	dsl_pool_rele(dp, tag);
888 }
889 
890 void
891 dmu_objset_rele(objset_t *os, const void *tag)
892 {
893 	dmu_objset_rele_flags(os, B_FALSE, tag);
894 }
895 
896 /*
897  * When we are called, os MUST refer to an objset associated with a dataset
898  * that is owned by 'tag'; that is, is held and long held by 'tag' and ds_owner
899  * == tag.  We will then release and reacquire ownership of the dataset while
900  * holding the pool config_rwlock to avoid intervening namespace or ownership
901  * changes may occur.
902  *
903  * This exists solely to accommodate zfs_ioc_userspace_upgrade()'s desire to
904  * release the hold on its dataset and acquire a new one on the dataset of the
905  * same name so that it can be partially torn down and reconstructed.
906  */
907 void
908 dmu_objset_refresh_ownership(dsl_dataset_t *ds, dsl_dataset_t **newds,
909     boolean_t decrypt, const void *tag)
910 {
911 	dsl_pool_t *dp;
912 	char name[ZFS_MAX_DATASET_NAME_LEN];
913 	ds_hold_flags_t flags;
914 
915 	flags = (decrypt) ? DS_HOLD_FLAG_DECRYPT : DS_HOLD_FLAG_NONE;
916 	VERIFY3P(ds, !=, NULL);
917 	VERIFY3P(ds->ds_owner, ==, tag);
918 	VERIFY(dsl_dataset_long_held(ds));
919 
920 	dsl_dataset_name(ds, name);
921 	dp = ds->ds_dir->dd_pool;
922 	dsl_pool_config_enter(dp, FTAG);
923 	dsl_dataset_disown(ds, flags, tag);
924 	VERIFY0(dsl_dataset_own(dp, name, flags, tag, newds));
925 	dsl_pool_config_exit(dp, FTAG);
926 }
927 
928 void
929 dmu_objset_disown(objset_t *os, boolean_t decrypt, const void *tag)
930 {
931 	ds_hold_flags_t flags;
932 
933 	flags = (decrypt) ? DS_HOLD_FLAG_DECRYPT : DS_HOLD_FLAG_NONE;
934 	/*
935 	 * Stop upgrading thread
936 	 */
937 	dmu_objset_upgrade_stop(os);
938 	dsl_dataset_disown(os->os_dsl_dataset, flags, tag);
939 }
940 
941 void
942 dmu_objset_evict_dbufs(objset_t *os)
943 {
944 	dnode_t *dn_marker;
945 	dnode_t *dn;
946 
947 	dn_marker = kmem_alloc(sizeof (dnode_t), KM_SLEEP);
948 
949 	mutex_enter(&os->os_lock);
950 	dn = list_head(&os->os_dnodes);
951 	while (dn != NULL) {
952 		/*
953 		 * Skip dnodes without holds.  We have to do this dance
954 		 * because dnode_add_ref() only works if there is already a
955 		 * hold.  If the dnode has no holds, then it has no dbufs.
956 		 */
957 		if (dnode_add_ref(dn, FTAG)) {
958 			list_insert_after(&os->os_dnodes, dn, dn_marker);
959 			mutex_exit(&os->os_lock);
960 
961 			dnode_evict_dbufs(dn);
962 			dnode_rele(dn, FTAG);
963 
964 			mutex_enter(&os->os_lock);
965 			dn = list_next(&os->os_dnodes, dn_marker);
966 			list_remove(&os->os_dnodes, dn_marker);
967 		} else {
968 			dn = list_next(&os->os_dnodes, dn);
969 		}
970 	}
971 	mutex_exit(&os->os_lock);
972 
973 	kmem_free(dn_marker, sizeof (dnode_t));
974 
975 	if (DMU_USERUSED_DNODE(os) != NULL) {
976 		if (DMU_PROJECTUSED_DNODE(os) != NULL)
977 			dnode_evict_dbufs(DMU_PROJECTUSED_DNODE(os));
978 		dnode_evict_dbufs(DMU_GROUPUSED_DNODE(os));
979 		dnode_evict_dbufs(DMU_USERUSED_DNODE(os));
980 	}
981 	dnode_evict_dbufs(DMU_META_DNODE(os));
982 }
983 
984 /*
985  * Objset eviction processing is split into into two pieces.
986  * The first marks the objset as evicting, evicts any dbufs that
987  * have a refcount of zero, and then queues up the objset for the
988  * second phase of eviction.  Once os->os_dnodes has been cleared by
989  * dnode_buf_pageout()->dnode_destroy(), the second phase is executed.
990  * The second phase closes the special dnodes, dequeues the objset from
991  * the list of those undergoing eviction, and finally frees the objset.
992  *
993  * NOTE: Due to asynchronous eviction processing (invocation of
994  *       dnode_buf_pageout()), it is possible for the meta dnode for the
995  *       objset to have no holds even though os->os_dnodes is not empty.
996  */
997 void
998 dmu_objset_evict(objset_t *os)
999 {
1000 	dsl_dataset_t *ds = os->os_dsl_dataset;
1001 
1002 	for (int t = 0; t < TXG_SIZE; t++)
1003 		ASSERT(!dmu_objset_is_dirty(os, t));
1004 
1005 	if (ds)
1006 		dsl_prop_unregister_all(ds, os);
1007 
1008 	if (os->os_sa)
1009 		sa_tear_down(os);
1010 
1011 	dmu_objset_evict_dbufs(os);
1012 
1013 	mutex_enter(&os->os_lock);
1014 	spa_evicting_os_register(os->os_spa, os);
1015 	if (list_is_empty(&os->os_dnodes)) {
1016 		mutex_exit(&os->os_lock);
1017 		dmu_objset_evict_done(os);
1018 	} else {
1019 		mutex_exit(&os->os_lock);
1020 	}
1021 
1022 
1023 }
1024 
1025 void
1026 dmu_objset_evict_done(objset_t *os)
1027 {
1028 	ASSERT3P(list_head(&os->os_dnodes), ==, NULL);
1029 
1030 	dnode_special_close(&os->os_meta_dnode);
1031 	if (DMU_USERUSED_DNODE(os)) {
1032 		if (DMU_PROJECTUSED_DNODE(os))
1033 			dnode_special_close(&os->os_projectused_dnode);
1034 		dnode_special_close(&os->os_userused_dnode);
1035 		dnode_special_close(&os->os_groupused_dnode);
1036 	}
1037 	zil_free(os->os_zil);
1038 
1039 	arc_buf_destroy(os->os_phys_buf, &os->os_phys_buf);
1040 
1041 	/*
1042 	 * This is a barrier to prevent the objset from going away in
1043 	 * dnode_move() until we can safely ensure that the objset is still in
1044 	 * use. We consider the objset valid before the barrier and invalid
1045 	 * after the barrier.
1046 	 */
1047 	rw_enter(&os_lock, RW_READER);
1048 	rw_exit(&os_lock);
1049 
1050 	kmem_free(os->os_obj_next_percpu,
1051 	    os->os_obj_next_percpu_len * sizeof (os->os_obj_next_percpu[0]));
1052 
1053 	mutex_destroy(&os->os_lock);
1054 	mutex_destroy(&os->os_userused_lock);
1055 	mutex_destroy(&os->os_obj_lock);
1056 	mutex_destroy(&os->os_user_ptr_lock);
1057 	mutex_destroy(&os->os_upgrade_lock);
1058 	for (int i = 0; i < TXG_SIZE; i++)
1059 		multilist_destroy(&os->os_dirty_dnodes[i]);
1060 	spa_evicting_os_deregister(os->os_spa, os);
1061 	kmem_free(os, sizeof (objset_t));
1062 }
1063 
1064 inode_timespec_t
1065 dmu_objset_snap_cmtime(objset_t *os)
1066 {
1067 	return (dsl_dir_snap_cmtime(os->os_dsl_dataset->ds_dir));
1068 }
1069 
1070 objset_t *
1071 dmu_objset_create_impl_dnstats(spa_t *spa, dsl_dataset_t *ds, blkptr_t *bp,
1072     dmu_objset_type_t type, int levels, int blksz, int ibs, dmu_tx_t *tx)
1073 {
1074 	objset_t *os;
1075 	dnode_t *mdn;
1076 
1077 	ASSERT(dmu_tx_is_syncing(tx));
1078 
1079 	if (blksz == 0)
1080 		blksz = DNODE_BLOCK_SIZE;
1081 	if (ibs == 0)
1082 		ibs = DN_MAX_INDBLKSHIFT;
1083 
1084 	if (ds != NULL)
1085 		VERIFY0(dmu_objset_from_ds(ds, &os));
1086 	else
1087 		VERIFY0(dmu_objset_open_impl(spa, NULL, bp, &os));
1088 
1089 	mdn = DMU_META_DNODE(os);
1090 
1091 	dnode_allocate(mdn, DMU_OT_DNODE, blksz, ibs, DMU_OT_NONE, 0,
1092 	    DNODE_MIN_SLOTS, tx);
1093 
1094 	/*
1095 	 * We don't want to have to increase the meta-dnode's nlevels
1096 	 * later, because then we could do it in quiescing context while
1097 	 * we are also accessing it in open context.
1098 	 *
1099 	 * This precaution is not necessary for the MOS (ds == NULL),
1100 	 * because the MOS is only updated in syncing context.
1101 	 * This is most fortunate: the MOS is the only objset that
1102 	 * needs to be synced multiple times as spa_sync() iterates
1103 	 * to convergence, so minimizing its dn_nlevels matters.
1104 	 */
1105 	if (ds != NULL) {
1106 		if (levels == 0) {
1107 			levels = 1;
1108 
1109 			/*
1110 			 * Determine the number of levels necessary for the
1111 			 * meta-dnode to contain DN_MAX_OBJECT dnodes.  Note
1112 			 * that in order to ensure that we do not overflow
1113 			 * 64 bits, there has to be a nlevels that gives us a
1114 			 * number of blocks > DN_MAX_OBJECT but < 2^64.
1115 			 * Therefore, (mdn->dn_indblkshift - SPA_BLKPTRSHIFT)
1116 			 * (10) must be less than (64 - log2(DN_MAX_OBJECT))
1117 			 * (16).
1118 			 */
1119 			while ((uint64_t)mdn->dn_nblkptr <<
1120 			    (mdn->dn_datablkshift - DNODE_SHIFT + (levels - 1) *
1121 			    (mdn->dn_indblkshift - SPA_BLKPTRSHIFT)) <
1122 			    DN_MAX_OBJECT)
1123 				levels++;
1124 		}
1125 
1126 		mdn->dn_next_nlevels[tx->tx_txg & TXG_MASK] =
1127 		    mdn->dn_nlevels = levels;
1128 	}
1129 
1130 	ASSERT(type != DMU_OST_NONE);
1131 	ASSERT(type != DMU_OST_ANY);
1132 	ASSERT(type < DMU_OST_NUMTYPES);
1133 	os->os_phys->os_type = type;
1134 
1135 	/*
1136 	 * Enable user accounting if it is enabled and this is not an
1137 	 * encrypted receive.
1138 	 */
1139 	if (dmu_objset_userused_enabled(os) &&
1140 	    (!os->os_encrypted || !dmu_objset_is_receiving(os))) {
1141 		os->os_phys->os_flags |= OBJSET_FLAG_USERACCOUNTING_COMPLETE;
1142 		if (dmu_objset_userobjused_enabled(os)) {
1143 			ASSERT3P(ds, !=, NULL);
1144 			ds->ds_feature_activation[
1145 			    SPA_FEATURE_USEROBJ_ACCOUNTING] = (void *)B_TRUE;
1146 			os->os_phys->os_flags |=
1147 			    OBJSET_FLAG_USEROBJACCOUNTING_COMPLETE;
1148 		}
1149 		if (dmu_objset_projectquota_enabled(os)) {
1150 			ASSERT3P(ds, !=, NULL);
1151 			ds->ds_feature_activation[
1152 			    SPA_FEATURE_PROJECT_QUOTA] = (void *)B_TRUE;
1153 			os->os_phys->os_flags |=
1154 			    OBJSET_FLAG_PROJECTQUOTA_COMPLETE;
1155 		}
1156 		os->os_flags = os->os_phys->os_flags;
1157 	}
1158 
1159 	dsl_dataset_dirty(ds, tx);
1160 
1161 	return (os);
1162 }
1163 
1164 /* called from dsl for meta-objset */
1165 objset_t *
1166 dmu_objset_create_impl(spa_t *spa, dsl_dataset_t *ds, blkptr_t *bp,
1167     dmu_objset_type_t type, dmu_tx_t *tx)
1168 {
1169 	return (dmu_objset_create_impl_dnstats(spa, ds, bp, type, 0, 0, 0, tx));
1170 }
1171 
1172 typedef struct dmu_objset_create_arg {
1173 	const char *doca_name;
1174 	cred_t *doca_cred;
1175 	proc_t *doca_proc;
1176 	void (*doca_userfunc)(objset_t *os, void *arg,
1177 	    cred_t *cr, dmu_tx_t *tx);
1178 	void *doca_userarg;
1179 	dmu_objset_type_t doca_type;
1180 	uint64_t doca_flags;
1181 	dsl_crypto_params_t *doca_dcp;
1182 } dmu_objset_create_arg_t;
1183 
1184 static int
1185 dmu_objset_create_check(void *arg, dmu_tx_t *tx)
1186 {
1187 	dmu_objset_create_arg_t *doca = arg;
1188 	dsl_pool_t *dp = dmu_tx_pool(tx);
1189 	dsl_dir_t *pdd;
1190 	dsl_dataset_t *parentds;
1191 	objset_t *parentos;
1192 	const char *tail;
1193 	int error;
1194 
1195 	if (strchr(doca->doca_name, '@') != NULL)
1196 		return (SET_ERROR(EINVAL));
1197 
1198 	if (strlen(doca->doca_name) >= ZFS_MAX_DATASET_NAME_LEN)
1199 		return (SET_ERROR(ENAMETOOLONG));
1200 
1201 	if (dataset_nestcheck(doca->doca_name) != 0)
1202 		return (SET_ERROR(ENAMETOOLONG));
1203 
1204 	error = dsl_dir_hold(dp, doca->doca_name, FTAG, &pdd, &tail);
1205 	if (error != 0)
1206 		return (error);
1207 	if (tail == NULL) {
1208 		dsl_dir_rele(pdd, FTAG);
1209 		return (SET_ERROR(EEXIST));
1210 	}
1211 
1212 	error = dmu_objset_create_crypt_check(pdd, doca->doca_dcp, NULL);
1213 	if (error != 0) {
1214 		dsl_dir_rele(pdd, FTAG);
1215 		return (error);
1216 	}
1217 
1218 	error = dsl_fs_ss_limit_check(pdd, 1, ZFS_PROP_FILESYSTEM_LIMIT, NULL,
1219 	    doca->doca_cred, doca->doca_proc);
1220 	if (error != 0) {
1221 		dsl_dir_rele(pdd, FTAG);
1222 		return (error);
1223 	}
1224 
1225 	/* can't create below anything but filesystems (eg. no ZVOLs) */
1226 	error = dsl_dataset_hold_obj(pdd->dd_pool,
1227 	    dsl_dir_phys(pdd)->dd_head_dataset_obj, FTAG, &parentds);
1228 	if (error != 0) {
1229 		dsl_dir_rele(pdd, FTAG);
1230 		return (error);
1231 	}
1232 	error = dmu_objset_from_ds(parentds, &parentos);
1233 	if (error != 0) {
1234 		dsl_dataset_rele(parentds, FTAG);
1235 		dsl_dir_rele(pdd, FTAG);
1236 		return (error);
1237 	}
1238 	if (dmu_objset_type(parentos) != DMU_OST_ZFS) {
1239 		dsl_dataset_rele(parentds, FTAG);
1240 		dsl_dir_rele(pdd, FTAG);
1241 		return (SET_ERROR(ZFS_ERR_WRONG_PARENT));
1242 	}
1243 	dsl_dataset_rele(parentds, FTAG);
1244 	dsl_dir_rele(pdd, FTAG);
1245 
1246 	return (error);
1247 }
1248 
1249 static void
1250 dmu_objset_create_sync(void *arg, dmu_tx_t *tx)
1251 {
1252 	dmu_objset_create_arg_t *doca = arg;
1253 	dsl_pool_t *dp = dmu_tx_pool(tx);
1254 	spa_t *spa = dp->dp_spa;
1255 	dsl_dir_t *pdd;
1256 	const char *tail;
1257 	dsl_dataset_t *ds;
1258 	uint64_t obj;
1259 	blkptr_t *bp;
1260 	objset_t *os;
1261 	zio_t *rzio;
1262 
1263 	VERIFY0(dsl_dir_hold(dp, doca->doca_name, FTAG, &pdd, &tail));
1264 
1265 	obj = dsl_dataset_create_sync(pdd, tail, NULL, doca->doca_flags,
1266 	    doca->doca_cred, doca->doca_dcp, tx);
1267 
1268 	VERIFY0(dsl_dataset_hold_obj_flags(pdd->dd_pool, obj,
1269 	    DS_HOLD_FLAG_DECRYPT, FTAG, &ds));
1270 	rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);
1271 	bp = dsl_dataset_get_blkptr(ds);
1272 	os = dmu_objset_create_impl(spa, ds, bp, doca->doca_type, tx);
1273 	rrw_exit(&ds->ds_bp_rwlock, FTAG);
1274 
1275 	if (doca->doca_userfunc != NULL) {
1276 		doca->doca_userfunc(os, doca->doca_userarg,
1277 		    doca->doca_cred, tx);
1278 	}
1279 
1280 	/*
1281 	 * The doca_userfunc() may write out some data that needs to be
1282 	 * encrypted if the dataset is encrypted (specifically the root
1283 	 * directory).  This data must be written out before the encryption
1284 	 * key mapping is removed by dsl_dataset_rele_flags().  Force the
1285 	 * I/O to occur immediately by invoking the relevant sections of
1286 	 * dsl_pool_sync().
1287 	 */
1288 	if (os->os_encrypted) {
1289 		dsl_dataset_t *tmpds = NULL;
1290 		boolean_t need_sync_done = B_FALSE;
1291 
1292 		mutex_enter(&ds->ds_lock);
1293 		ds->ds_owner = FTAG;
1294 		mutex_exit(&ds->ds_lock);
1295 
1296 		rzio = zio_root(spa, NULL, NULL, ZIO_FLAG_MUSTSUCCEED);
1297 		tmpds = txg_list_remove_this(&dp->dp_dirty_datasets, ds,
1298 		    tx->tx_txg);
1299 		if (tmpds != NULL) {
1300 			dsl_dataset_sync(ds, rzio, tx);
1301 			need_sync_done = B_TRUE;
1302 		}
1303 		VERIFY0(zio_wait(rzio));
1304 
1305 		dmu_objset_sync_done(os, tx);
1306 		taskq_wait(dp->dp_sync_taskq);
1307 		if (txg_list_member(&dp->dp_dirty_datasets, ds, tx->tx_txg)) {
1308 			ASSERT3P(ds->ds_key_mapping, !=, NULL);
1309 			key_mapping_rele(spa, ds->ds_key_mapping, ds);
1310 		}
1311 
1312 		rzio = zio_root(spa, NULL, NULL, ZIO_FLAG_MUSTSUCCEED);
1313 		tmpds = txg_list_remove_this(&dp->dp_dirty_datasets, ds,
1314 		    tx->tx_txg);
1315 		if (tmpds != NULL) {
1316 			dmu_buf_rele(ds->ds_dbuf, ds);
1317 			dsl_dataset_sync(ds, rzio, tx);
1318 		}
1319 		VERIFY0(zio_wait(rzio));
1320 
1321 		if (need_sync_done) {
1322 			ASSERT3P(ds->ds_key_mapping, !=, NULL);
1323 			key_mapping_rele(spa, ds->ds_key_mapping, ds);
1324 			dsl_dataset_sync_done(ds, tx);
1325 			dmu_buf_rele(ds->ds_dbuf, ds);
1326 		}
1327 
1328 		mutex_enter(&ds->ds_lock);
1329 		ds->ds_owner = NULL;
1330 		mutex_exit(&ds->ds_lock);
1331 	}
1332 
1333 	spa_history_log_internal_ds(ds, "create", tx, " ");
1334 
1335 	dsl_dataset_rele_flags(ds, DS_HOLD_FLAG_DECRYPT, FTAG);
1336 	dsl_dir_rele(pdd, FTAG);
1337 }
1338 
1339 int
1340 dmu_objset_create(const char *name, dmu_objset_type_t type, uint64_t flags,
1341     dsl_crypto_params_t *dcp, dmu_objset_create_sync_func_t func, void *arg)
1342 {
1343 	dmu_objset_create_arg_t doca;
1344 	dsl_crypto_params_t tmp_dcp = { 0 };
1345 
1346 	doca.doca_name = name;
1347 	doca.doca_cred = CRED();
1348 	doca.doca_proc = curproc;
1349 	doca.doca_flags = flags;
1350 	doca.doca_userfunc = func;
1351 	doca.doca_userarg = arg;
1352 	doca.doca_type = type;
1353 
1354 	/*
1355 	 * Some callers (mostly for testing) do not provide a dcp on their
1356 	 * own but various code inside the sync task will require it to be
1357 	 * allocated. Rather than adding NULL checks throughout this code
1358 	 * or adding dummy dcp's to all of the callers we simply create a
1359 	 * dummy one here and use that. This zero dcp will have the same
1360 	 * effect as asking for inheritance of all encryption params.
1361 	 */
1362 	doca.doca_dcp = (dcp != NULL) ? dcp : &tmp_dcp;
1363 
1364 	int rv = dsl_sync_task(name,
1365 	    dmu_objset_create_check, dmu_objset_create_sync, &doca,
1366 	    6, ZFS_SPACE_CHECK_NORMAL);
1367 
1368 	if (rv == 0)
1369 		zvol_create_minor(name);
1370 	return (rv);
1371 }
1372 
1373 typedef struct dmu_objset_clone_arg {
1374 	const char *doca_clone;
1375 	const char *doca_origin;
1376 	cred_t *doca_cred;
1377 	proc_t *doca_proc;
1378 } dmu_objset_clone_arg_t;
1379 
1380 static int
1381 dmu_objset_clone_check(void *arg, dmu_tx_t *tx)
1382 {
1383 	dmu_objset_clone_arg_t *doca = arg;
1384 	dsl_dir_t *pdd;
1385 	const char *tail;
1386 	int error;
1387 	dsl_dataset_t *origin;
1388 	dsl_pool_t *dp = dmu_tx_pool(tx);
1389 
1390 	if (strchr(doca->doca_clone, '@') != NULL)
1391 		return (SET_ERROR(EINVAL));
1392 
1393 	if (strlen(doca->doca_clone) >= ZFS_MAX_DATASET_NAME_LEN)
1394 		return (SET_ERROR(ENAMETOOLONG));
1395 
1396 	error = dsl_dir_hold(dp, doca->doca_clone, FTAG, &pdd, &tail);
1397 	if (error != 0)
1398 		return (error);
1399 	if (tail == NULL) {
1400 		dsl_dir_rele(pdd, FTAG);
1401 		return (SET_ERROR(EEXIST));
1402 	}
1403 
1404 	error = dsl_fs_ss_limit_check(pdd, 1, ZFS_PROP_FILESYSTEM_LIMIT, NULL,
1405 	    doca->doca_cred, doca->doca_proc);
1406 	if (error != 0) {
1407 		dsl_dir_rele(pdd, FTAG);
1408 		return (SET_ERROR(EDQUOT));
1409 	}
1410 
1411 	error = dsl_dataset_hold(dp, doca->doca_origin, FTAG, &origin);
1412 	if (error != 0) {
1413 		dsl_dir_rele(pdd, FTAG);
1414 		return (error);
1415 	}
1416 
1417 	/* You can only clone snapshots, not the head datasets. */
1418 	if (!origin->ds_is_snapshot) {
1419 		dsl_dataset_rele(origin, FTAG);
1420 		dsl_dir_rele(pdd, FTAG);
1421 		return (SET_ERROR(EINVAL));
1422 	}
1423 
1424 	dsl_dataset_rele(origin, FTAG);
1425 	dsl_dir_rele(pdd, FTAG);
1426 
1427 	return (0);
1428 }
1429 
1430 static void
1431 dmu_objset_clone_sync(void *arg, dmu_tx_t *tx)
1432 {
1433 	dmu_objset_clone_arg_t *doca = arg;
1434 	dsl_pool_t *dp = dmu_tx_pool(tx);
1435 	dsl_dir_t *pdd;
1436 	const char *tail;
1437 	dsl_dataset_t *origin, *ds;
1438 	uint64_t obj;
1439 	char namebuf[ZFS_MAX_DATASET_NAME_LEN];
1440 
1441 	VERIFY0(dsl_dir_hold(dp, doca->doca_clone, FTAG, &pdd, &tail));
1442 	VERIFY0(dsl_dataset_hold(dp, doca->doca_origin, FTAG, &origin));
1443 
1444 	obj = dsl_dataset_create_sync(pdd, tail, origin, 0,
1445 	    doca->doca_cred, NULL, tx);
1446 
1447 	VERIFY0(dsl_dataset_hold_obj(pdd->dd_pool, obj, FTAG, &ds));
1448 	dsl_dataset_name(origin, namebuf);
1449 	spa_history_log_internal_ds(ds, "clone", tx,
1450 	    "origin=%s (%llu)", namebuf, (u_longlong_t)origin->ds_object);
1451 	dsl_dataset_rele(ds, FTAG);
1452 	dsl_dataset_rele(origin, FTAG);
1453 	dsl_dir_rele(pdd, FTAG);
1454 }
1455 
1456 int
1457 dmu_objset_clone(const char *clone, const char *origin)
1458 {
1459 	dmu_objset_clone_arg_t doca;
1460 
1461 	doca.doca_clone = clone;
1462 	doca.doca_origin = origin;
1463 	doca.doca_cred = CRED();
1464 	doca.doca_proc = curproc;
1465 
1466 	int rv = dsl_sync_task(clone,
1467 	    dmu_objset_clone_check, dmu_objset_clone_sync, &doca,
1468 	    6, ZFS_SPACE_CHECK_NORMAL);
1469 
1470 	if (rv == 0)
1471 		zvol_create_minor(clone);
1472 
1473 	return (rv);
1474 }
1475 
1476 int
1477 dmu_objset_snapshot_one(const char *fsname, const char *snapname)
1478 {
1479 	int err;
1480 	char *longsnap = kmem_asprintf("%s@%s", fsname, snapname);
1481 	nvlist_t *snaps = fnvlist_alloc();
1482 
1483 	fnvlist_add_boolean(snaps, longsnap);
1484 	kmem_strfree(longsnap);
1485 	err = dsl_dataset_snapshot(snaps, NULL, NULL);
1486 	fnvlist_free(snaps);
1487 	return (err);
1488 }
1489 
1490 static void
1491 dmu_objset_upgrade_task_cb(void *data)
1492 {
1493 	objset_t *os = data;
1494 
1495 	mutex_enter(&os->os_upgrade_lock);
1496 	os->os_upgrade_status = EINTR;
1497 	if (!os->os_upgrade_exit) {
1498 		int status;
1499 
1500 		mutex_exit(&os->os_upgrade_lock);
1501 
1502 		status = os->os_upgrade_cb(os);
1503 
1504 		mutex_enter(&os->os_upgrade_lock);
1505 
1506 		os->os_upgrade_status = status;
1507 	}
1508 	os->os_upgrade_exit = B_TRUE;
1509 	os->os_upgrade_id = 0;
1510 	mutex_exit(&os->os_upgrade_lock);
1511 	dsl_dataset_long_rele(dmu_objset_ds(os), upgrade_tag);
1512 }
1513 
1514 static void
1515 dmu_objset_upgrade(objset_t *os, dmu_objset_upgrade_cb_t cb)
1516 {
1517 	if (os->os_upgrade_id != 0)
1518 		return;
1519 
1520 	ASSERT(dsl_pool_config_held(dmu_objset_pool(os)));
1521 	dsl_dataset_long_hold(dmu_objset_ds(os), upgrade_tag);
1522 
1523 	mutex_enter(&os->os_upgrade_lock);
1524 	if (os->os_upgrade_id == 0 && os->os_upgrade_status == 0) {
1525 		os->os_upgrade_exit = B_FALSE;
1526 		os->os_upgrade_cb = cb;
1527 		os->os_upgrade_id = taskq_dispatch(
1528 		    os->os_spa->spa_upgrade_taskq,
1529 		    dmu_objset_upgrade_task_cb, os, TQ_SLEEP);
1530 		if (os->os_upgrade_id == TASKQID_INVALID) {
1531 			dsl_dataset_long_rele(dmu_objset_ds(os), upgrade_tag);
1532 			os->os_upgrade_status = ENOMEM;
1533 		}
1534 	} else {
1535 		dsl_dataset_long_rele(dmu_objset_ds(os), upgrade_tag);
1536 	}
1537 	mutex_exit(&os->os_upgrade_lock);
1538 }
1539 
1540 static void
1541 dmu_objset_upgrade_stop(objset_t *os)
1542 {
1543 	mutex_enter(&os->os_upgrade_lock);
1544 	os->os_upgrade_exit = B_TRUE;
1545 	if (os->os_upgrade_id != 0) {
1546 		taskqid_t id = os->os_upgrade_id;
1547 
1548 		os->os_upgrade_id = 0;
1549 		mutex_exit(&os->os_upgrade_lock);
1550 
1551 		if ((taskq_cancel_id(os->os_spa->spa_upgrade_taskq, id)) == 0) {
1552 			dsl_dataset_long_rele(dmu_objset_ds(os), upgrade_tag);
1553 		}
1554 		txg_wait_synced(os->os_spa->spa_dsl_pool, 0);
1555 	} else {
1556 		mutex_exit(&os->os_upgrade_lock);
1557 	}
1558 }
1559 
1560 static void
1561 dmu_objset_sync_dnodes(multilist_sublist_t *list, dmu_tx_t *tx)
1562 {
1563 	dnode_t *dn;
1564 
1565 	while ((dn = multilist_sublist_head(list)) != NULL) {
1566 		ASSERT(dn->dn_object != DMU_META_DNODE_OBJECT);
1567 		ASSERT(dn->dn_dbuf->db_data_pending);
1568 		/*
1569 		 * Initialize dn_zio outside dnode_sync() because the
1570 		 * meta-dnode needs to set it outside dnode_sync().
1571 		 */
1572 		dn->dn_zio = dn->dn_dbuf->db_data_pending->dr_zio;
1573 		ASSERT(dn->dn_zio);
1574 
1575 		ASSERT3U(dn->dn_nlevels, <=, DN_MAX_LEVELS);
1576 		multilist_sublist_remove(list, dn);
1577 
1578 		/*
1579 		 * See the comment above dnode_rele_task() for an explanation
1580 		 * of why this dnode hold is always needed (even when not
1581 		 * doing user accounting).
1582 		 */
1583 		multilist_t *newlist = &dn->dn_objset->os_synced_dnodes;
1584 		(void) dnode_add_ref(dn, newlist);
1585 		multilist_insert(newlist, dn);
1586 
1587 		dnode_sync(dn, tx);
1588 	}
1589 }
1590 
1591 static void
1592 dmu_objset_write_ready(zio_t *zio, arc_buf_t *abuf, void *arg)
1593 {
1594 	(void) abuf;
1595 	blkptr_t *bp = zio->io_bp;
1596 	objset_t *os = arg;
1597 	dnode_phys_t *dnp = &os->os_phys->os_meta_dnode;
1598 	uint64_t fill = 0;
1599 
1600 	ASSERT(!BP_IS_EMBEDDED(bp));
1601 	ASSERT3U(BP_GET_TYPE(bp), ==, DMU_OT_OBJSET);
1602 	ASSERT0(BP_GET_LEVEL(bp));
1603 
1604 	/*
1605 	 * Update rootbp fill count: it should be the number of objects
1606 	 * allocated in the object set (not counting the "special"
1607 	 * objects that are stored in the objset_phys_t -- the meta
1608 	 * dnode and user/group/project accounting objects).
1609 	 */
1610 	for (int i = 0; i < dnp->dn_nblkptr; i++)
1611 		fill += BP_GET_FILL(&dnp->dn_blkptr[i]);
1612 
1613 	BP_SET_FILL(bp, fill);
1614 
1615 	if (os->os_dsl_dataset != NULL)
1616 		rrw_enter(&os->os_dsl_dataset->ds_bp_rwlock, RW_WRITER, FTAG);
1617 	*os->os_rootbp = *bp;
1618 	if (os->os_dsl_dataset != NULL)
1619 		rrw_exit(&os->os_dsl_dataset->ds_bp_rwlock, FTAG);
1620 }
1621 
1622 static void
1623 dmu_objset_write_done(zio_t *zio, arc_buf_t *abuf, void *arg)
1624 {
1625 	(void) abuf;
1626 	blkptr_t *bp = zio->io_bp;
1627 	blkptr_t *bp_orig = &zio->io_bp_orig;
1628 	objset_t *os = arg;
1629 
1630 	if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
1631 		ASSERT(BP_EQUAL(bp, bp_orig));
1632 	} else {
1633 		dsl_dataset_t *ds = os->os_dsl_dataset;
1634 		dmu_tx_t *tx = os->os_synctx;
1635 
1636 		(void) dsl_dataset_block_kill(ds, bp_orig, tx, B_TRUE);
1637 		dsl_dataset_block_born(ds, bp, tx);
1638 	}
1639 	kmem_free(bp, sizeof (*bp));
1640 }
1641 
1642 typedef struct sync_objset_arg {
1643 	zio_t		*soa_zio;
1644 	objset_t	*soa_os;
1645 	dmu_tx_t	*soa_tx;
1646 	kmutex_t	soa_mutex;
1647 	int		soa_count;
1648 	taskq_ent_t	soa_tq_ent;
1649 } sync_objset_arg_t;
1650 
1651 typedef struct sync_dnodes_arg {
1652 	multilist_t	*sda_list;
1653 	int		sda_sublist_idx;
1654 	multilist_t	*sda_newlist;
1655 	sync_objset_arg_t *sda_soa;
1656 } sync_dnodes_arg_t;
1657 
1658 static void sync_meta_dnode_task(void *arg);
1659 
1660 static void
1661 sync_dnodes_task(void *arg)
1662 {
1663 	sync_dnodes_arg_t *sda = arg;
1664 	sync_objset_arg_t *soa = sda->sda_soa;
1665 	objset_t *os = soa->soa_os;
1666 
1667 	multilist_sublist_t *ms =
1668 	    multilist_sublist_lock(sda->sda_list, sda->sda_sublist_idx);
1669 
1670 	dmu_objset_sync_dnodes(ms, soa->soa_tx);
1671 
1672 	multilist_sublist_unlock(ms);
1673 
1674 	kmem_free(sda, sizeof (*sda));
1675 
1676 	mutex_enter(&soa->soa_mutex);
1677 	ASSERT(soa->soa_count != 0);
1678 	if (--soa->soa_count != 0) {
1679 		mutex_exit(&soa->soa_mutex);
1680 		return;
1681 	}
1682 	mutex_exit(&soa->soa_mutex);
1683 
1684 	taskq_dispatch_ent(dmu_objset_pool(os)->dp_sync_taskq,
1685 	    sync_meta_dnode_task, soa, TQ_FRONT, &soa->soa_tq_ent);
1686 }
1687 
1688 /*
1689  * Issue the zio_nowait() for all dirty record zios on the meta dnode,
1690  * then trigger the callback for the zil_sync. This runs once for each
1691  * objset, only after any/all sublists in the objset have been synced.
1692  */
1693 static void
1694 sync_meta_dnode_task(void *arg)
1695 {
1696 	sync_objset_arg_t *soa = arg;
1697 	objset_t *os = soa->soa_os;
1698 	dmu_tx_t *tx = soa->soa_tx;
1699 	int txgoff = tx->tx_txg & TXG_MASK;
1700 	dbuf_dirty_record_t *dr;
1701 
1702 	ASSERT0(soa->soa_count);
1703 
1704 	list_t *list = &DMU_META_DNODE(os)->dn_dirty_records[txgoff];
1705 	while ((dr = list_remove_head(list)) != NULL) {
1706 		ASSERT0(dr->dr_dbuf->db_level);
1707 		zio_nowait(dr->dr_zio);
1708 	}
1709 
1710 	/* Enable dnode backfill if enough objects have been freed. */
1711 	if (os->os_freed_dnodes >= dmu_rescan_dnode_threshold) {
1712 		os->os_rescan_dnodes = B_TRUE;
1713 		os->os_freed_dnodes = 0;
1714 	}
1715 
1716 	/*
1717 	 * Free intent log blocks up to this tx.
1718 	 */
1719 	zil_sync(os->os_zil, tx);
1720 	os->os_phys->os_zil_header = os->os_zil_header;
1721 	zio_nowait(soa->soa_zio);
1722 
1723 	mutex_destroy(&soa->soa_mutex);
1724 	kmem_free(soa, sizeof (*soa));
1725 }
1726 
1727 /* called from dsl */
1728 void
1729 dmu_objset_sync(objset_t *os, zio_t *pio, dmu_tx_t *tx)
1730 {
1731 	int txgoff;
1732 	zbookmark_phys_t zb;
1733 	zio_prop_t zp;
1734 	zio_t *zio;
1735 	int num_sublists;
1736 	multilist_t *ml;
1737 	blkptr_t *blkptr_copy = kmem_alloc(sizeof (*os->os_rootbp), KM_SLEEP);
1738 	*blkptr_copy = *os->os_rootbp;
1739 
1740 	dprintf_ds(os->os_dsl_dataset, "txg=%llu\n", (u_longlong_t)tx->tx_txg);
1741 
1742 	ASSERT(dmu_tx_is_syncing(tx));
1743 	/* XXX the write_done callback should really give us the tx... */
1744 	os->os_synctx = tx;
1745 
1746 	if (os->os_dsl_dataset == NULL) {
1747 		/*
1748 		 * This is the MOS.  If we have upgraded,
1749 		 * spa_max_replication() could change, so reset
1750 		 * os_copies here.
1751 		 */
1752 		os->os_copies = spa_max_replication(os->os_spa);
1753 	}
1754 
1755 	/*
1756 	 * Create the root block IO
1757 	 */
1758 	SET_BOOKMARK(&zb, os->os_dsl_dataset ?
1759 	    os->os_dsl_dataset->ds_object : DMU_META_OBJSET,
1760 	    ZB_ROOT_OBJECT, ZB_ROOT_LEVEL, ZB_ROOT_BLKID);
1761 	arc_release(os->os_phys_buf, &os->os_phys_buf);
1762 
1763 	dmu_write_policy(os, NULL, 0, 0, &zp);
1764 
1765 	/*
1766 	 * If we are either claiming the ZIL or doing a raw receive, write
1767 	 * out the os_phys_buf raw. Neither of these actions will effect the
1768 	 * MAC at this point.
1769 	 */
1770 	if (os->os_raw_receive ||
1771 	    os->os_next_write_raw[tx->tx_txg & TXG_MASK]) {
1772 		ASSERT(os->os_encrypted);
1773 		arc_convert_to_raw(os->os_phys_buf,
1774 		    os->os_dsl_dataset->ds_object, ZFS_HOST_BYTEORDER,
1775 		    DMU_OT_OBJSET, NULL, NULL, NULL);
1776 	}
1777 
1778 	zio = arc_write(pio, os->os_spa, tx->tx_txg,
1779 	    blkptr_copy, os->os_phys_buf, B_FALSE, dmu_os_is_l2cacheable(os),
1780 	    &zp, dmu_objset_write_ready, NULL, dmu_objset_write_done,
1781 	    os, ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_MUSTSUCCEED, &zb);
1782 
1783 	/*
1784 	 * Sync special dnodes - the parent IO for the sync is the root block
1785 	 */
1786 	DMU_META_DNODE(os)->dn_zio = zio;
1787 	dnode_sync(DMU_META_DNODE(os), tx);
1788 
1789 	os->os_phys->os_flags = os->os_flags;
1790 
1791 	if (DMU_USERUSED_DNODE(os) &&
1792 	    DMU_USERUSED_DNODE(os)->dn_type != DMU_OT_NONE) {
1793 		DMU_USERUSED_DNODE(os)->dn_zio = zio;
1794 		dnode_sync(DMU_USERUSED_DNODE(os), tx);
1795 		DMU_GROUPUSED_DNODE(os)->dn_zio = zio;
1796 		dnode_sync(DMU_GROUPUSED_DNODE(os), tx);
1797 	}
1798 
1799 	if (DMU_PROJECTUSED_DNODE(os) &&
1800 	    DMU_PROJECTUSED_DNODE(os)->dn_type != DMU_OT_NONE) {
1801 		DMU_PROJECTUSED_DNODE(os)->dn_zio = zio;
1802 		dnode_sync(DMU_PROJECTUSED_DNODE(os), tx);
1803 	}
1804 
1805 	txgoff = tx->tx_txg & TXG_MASK;
1806 
1807 	/*
1808 	 * We must create the list here because it uses the
1809 	 * dn_dirty_link[] of this txg.  But it may already
1810 	 * exist because we call dsl_dataset_sync() twice per txg.
1811 	 */
1812 	if (os->os_synced_dnodes.ml_sublists == NULL) {
1813 		multilist_create(&os->os_synced_dnodes, sizeof (dnode_t),
1814 		    offsetof(dnode_t, dn_dirty_link[txgoff]),
1815 		    dnode_multilist_index_func);
1816 	} else {
1817 		ASSERT3U(os->os_synced_dnodes.ml_offset, ==,
1818 		    offsetof(dnode_t, dn_dirty_link[txgoff]));
1819 	}
1820 
1821 	/*
1822 	 * zio_nowait(zio) is done after any/all sublist and meta dnode
1823 	 * zios have been nowaited, and the zil_sync() has been performed.
1824 	 * The soa is freed at the end of sync_meta_dnode_task.
1825 	 */
1826 	sync_objset_arg_t *soa = kmem_alloc(sizeof (*soa), KM_SLEEP);
1827 	soa->soa_zio = zio;
1828 	soa->soa_os = os;
1829 	soa->soa_tx = tx;
1830 	taskq_init_ent(&soa->soa_tq_ent);
1831 	mutex_init(&soa->soa_mutex, NULL, MUTEX_DEFAULT, NULL);
1832 
1833 	ml = &os->os_dirty_dnodes[txgoff];
1834 	soa->soa_count = num_sublists = multilist_get_num_sublists(ml);
1835 
1836 	for (int i = 0; i < num_sublists; i++) {
1837 		if (multilist_sublist_is_empty_idx(ml, i))
1838 			soa->soa_count--;
1839 	}
1840 
1841 	if (soa->soa_count == 0) {
1842 		taskq_dispatch_ent(dmu_objset_pool(os)->dp_sync_taskq,
1843 		    sync_meta_dnode_task, soa, TQ_FRONT, &soa->soa_tq_ent);
1844 	} else {
1845 		/*
1846 		 * Sync sublists in parallel. The last to finish
1847 		 * (i.e., when soa->soa_count reaches zero) must
1848 		 *  dispatch sync_meta_dnode_task.
1849 		 */
1850 		for (int i = 0; i < num_sublists; i++) {
1851 			if (multilist_sublist_is_empty_idx(ml, i))
1852 				continue;
1853 			sync_dnodes_arg_t *sda =
1854 			    kmem_alloc(sizeof (*sda), KM_SLEEP);
1855 			sda->sda_list = ml;
1856 			sda->sda_sublist_idx = i;
1857 			sda->sda_soa = soa;
1858 			(void) taskq_dispatch(
1859 			    dmu_objset_pool(os)->dp_sync_taskq,
1860 			    sync_dnodes_task, sda, 0);
1861 			/* sync_dnodes_task frees sda */
1862 		}
1863 	}
1864 }
1865 
1866 boolean_t
1867 dmu_objset_is_dirty(objset_t *os, uint64_t txg)
1868 {
1869 	return (!multilist_is_empty(&os->os_dirty_dnodes[txg & TXG_MASK]));
1870 }
1871 
1872 static file_info_cb_t *file_cbs[DMU_OST_NUMTYPES];
1873 
1874 void
1875 dmu_objset_register_type(dmu_objset_type_t ost, file_info_cb_t *cb)
1876 {
1877 	file_cbs[ost] = cb;
1878 }
1879 
1880 int
1881 dmu_get_file_info(objset_t *os, dmu_object_type_t bonustype, const void *data,
1882     zfs_file_info_t *zfi)
1883 {
1884 	file_info_cb_t *cb = file_cbs[os->os_phys->os_type];
1885 	if (cb == NULL)
1886 		return (EINVAL);
1887 	return (cb(bonustype, data, zfi));
1888 }
1889 
1890 boolean_t
1891 dmu_objset_userused_enabled(objset_t *os)
1892 {
1893 	return (spa_version(os->os_spa) >= SPA_VERSION_USERSPACE &&
1894 	    file_cbs[os->os_phys->os_type] != NULL &&
1895 	    DMU_USERUSED_DNODE(os) != NULL);
1896 }
1897 
1898 boolean_t
1899 dmu_objset_userobjused_enabled(objset_t *os)
1900 {
1901 	return (dmu_objset_userused_enabled(os) &&
1902 	    spa_feature_is_enabled(os->os_spa, SPA_FEATURE_USEROBJ_ACCOUNTING));
1903 }
1904 
1905 boolean_t
1906 dmu_objset_projectquota_enabled(objset_t *os)
1907 {
1908 	return (file_cbs[os->os_phys->os_type] != NULL &&
1909 	    DMU_PROJECTUSED_DNODE(os) != NULL &&
1910 	    spa_feature_is_enabled(os->os_spa, SPA_FEATURE_PROJECT_QUOTA));
1911 }
1912 
1913 typedef struct userquota_node {
1914 	/* must be in the first filed, see userquota_update_cache() */
1915 	char		uqn_id[20 + DMU_OBJACCT_PREFIX_LEN];
1916 	int64_t		uqn_delta;
1917 	avl_node_t	uqn_node;
1918 } userquota_node_t;
1919 
1920 typedef struct userquota_cache {
1921 	avl_tree_t uqc_user_deltas;
1922 	avl_tree_t uqc_group_deltas;
1923 	avl_tree_t uqc_project_deltas;
1924 } userquota_cache_t;
1925 
1926 static int
1927 userquota_compare(const void *l, const void *r)
1928 {
1929 	const userquota_node_t *luqn = l;
1930 	const userquota_node_t *ruqn = r;
1931 	int rv;
1932 
1933 	/*
1934 	 * NB: can only access uqn_id because userquota_update_cache() doesn't
1935 	 * pass in an entire userquota_node_t.
1936 	 */
1937 	rv = strcmp(luqn->uqn_id, ruqn->uqn_id);
1938 
1939 	return (TREE_ISIGN(rv));
1940 }
1941 
1942 static void
1943 do_userquota_cacheflush(objset_t *os, userquota_cache_t *cache, dmu_tx_t *tx)
1944 {
1945 	void *cookie;
1946 	userquota_node_t *uqn;
1947 
1948 	ASSERT(dmu_tx_is_syncing(tx));
1949 
1950 	cookie = NULL;
1951 	while ((uqn = avl_destroy_nodes(&cache->uqc_user_deltas,
1952 	    &cookie)) != NULL) {
1953 		/*
1954 		 * os_userused_lock protects against concurrent calls to
1955 		 * zap_increment_int().  It's needed because zap_increment_int()
1956 		 * is not thread-safe (i.e. not atomic).
1957 		 */
1958 		mutex_enter(&os->os_userused_lock);
1959 		VERIFY0(zap_increment(os, DMU_USERUSED_OBJECT,
1960 		    uqn->uqn_id, uqn->uqn_delta, tx));
1961 		mutex_exit(&os->os_userused_lock);
1962 		kmem_free(uqn, sizeof (*uqn));
1963 	}
1964 	avl_destroy(&cache->uqc_user_deltas);
1965 
1966 	cookie = NULL;
1967 	while ((uqn = avl_destroy_nodes(&cache->uqc_group_deltas,
1968 	    &cookie)) != NULL) {
1969 		mutex_enter(&os->os_userused_lock);
1970 		VERIFY0(zap_increment(os, DMU_GROUPUSED_OBJECT,
1971 		    uqn->uqn_id, uqn->uqn_delta, tx));
1972 		mutex_exit(&os->os_userused_lock);
1973 		kmem_free(uqn, sizeof (*uqn));
1974 	}
1975 	avl_destroy(&cache->uqc_group_deltas);
1976 
1977 	if (dmu_objset_projectquota_enabled(os)) {
1978 		cookie = NULL;
1979 		while ((uqn = avl_destroy_nodes(&cache->uqc_project_deltas,
1980 		    &cookie)) != NULL) {
1981 			mutex_enter(&os->os_userused_lock);
1982 			VERIFY0(zap_increment(os, DMU_PROJECTUSED_OBJECT,
1983 			    uqn->uqn_id, uqn->uqn_delta, tx));
1984 			mutex_exit(&os->os_userused_lock);
1985 			kmem_free(uqn, sizeof (*uqn));
1986 		}
1987 		avl_destroy(&cache->uqc_project_deltas);
1988 	}
1989 }
1990 
1991 static void
1992 userquota_update_cache(avl_tree_t *avl, const char *id, int64_t delta)
1993 {
1994 	userquota_node_t *uqn;
1995 	avl_index_t idx;
1996 
1997 	ASSERT(strlen(id) < sizeof (uqn->uqn_id));
1998 	/*
1999 	 * Use id directly for searching because uqn_id is the first field of
2000 	 * userquota_node_t and fields after uqn_id won't be accessed in
2001 	 * avl_find().
2002 	 */
2003 	uqn = avl_find(avl, (const void *)id, &idx);
2004 	if (uqn == NULL) {
2005 		uqn = kmem_zalloc(sizeof (*uqn), KM_SLEEP);
2006 		strlcpy(uqn->uqn_id, id, sizeof (uqn->uqn_id));
2007 		avl_insert(avl, uqn, idx);
2008 	}
2009 	uqn->uqn_delta += delta;
2010 }
2011 
2012 static void
2013 do_userquota_update(objset_t *os, userquota_cache_t *cache, uint64_t used,
2014     uint64_t flags, uint64_t user, uint64_t group, uint64_t project,
2015     boolean_t subtract)
2016 {
2017 	if (flags & DNODE_FLAG_USERUSED_ACCOUNTED) {
2018 		int64_t delta = DNODE_MIN_SIZE + used;
2019 		char name[20];
2020 
2021 		if (subtract)
2022 			delta = -delta;
2023 
2024 		(void) snprintf(name, sizeof (name), "%llx", (longlong_t)user);
2025 		userquota_update_cache(&cache->uqc_user_deltas, name, delta);
2026 
2027 		(void) snprintf(name, sizeof (name), "%llx", (longlong_t)group);
2028 		userquota_update_cache(&cache->uqc_group_deltas, name, delta);
2029 
2030 		if (dmu_objset_projectquota_enabled(os)) {
2031 			(void) snprintf(name, sizeof (name), "%llx",
2032 			    (longlong_t)project);
2033 			userquota_update_cache(&cache->uqc_project_deltas,
2034 			    name, delta);
2035 		}
2036 	}
2037 }
2038 
2039 static void
2040 do_userobjquota_update(objset_t *os, userquota_cache_t *cache, uint64_t flags,
2041     uint64_t user, uint64_t group, uint64_t project, boolean_t subtract)
2042 {
2043 	if (flags & DNODE_FLAG_USEROBJUSED_ACCOUNTED) {
2044 		char name[20 + DMU_OBJACCT_PREFIX_LEN];
2045 		int delta = subtract ? -1 : 1;
2046 
2047 		(void) snprintf(name, sizeof (name), DMU_OBJACCT_PREFIX "%llx",
2048 		    (longlong_t)user);
2049 		userquota_update_cache(&cache->uqc_user_deltas, name, delta);
2050 
2051 		(void) snprintf(name, sizeof (name), DMU_OBJACCT_PREFIX "%llx",
2052 		    (longlong_t)group);
2053 		userquota_update_cache(&cache->uqc_group_deltas, name, delta);
2054 
2055 		if (dmu_objset_projectquota_enabled(os)) {
2056 			(void) snprintf(name, sizeof (name),
2057 			    DMU_OBJACCT_PREFIX "%llx", (longlong_t)project);
2058 			userquota_update_cache(&cache->uqc_project_deltas,
2059 			    name, delta);
2060 		}
2061 	}
2062 }
2063 
2064 typedef struct userquota_updates_arg {
2065 	objset_t *uua_os;
2066 	int uua_sublist_idx;
2067 	dmu_tx_t *uua_tx;
2068 } userquota_updates_arg_t;
2069 
2070 static void
2071 userquota_updates_task(void *arg)
2072 {
2073 	userquota_updates_arg_t *uua = arg;
2074 	objset_t *os = uua->uua_os;
2075 	dmu_tx_t *tx = uua->uua_tx;
2076 	dnode_t *dn;
2077 	userquota_cache_t cache = { { 0 } };
2078 
2079 	multilist_sublist_t *list =
2080 	    multilist_sublist_lock(&os->os_synced_dnodes, uua->uua_sublist_idx);
2081 
2082 	ASSERT(multilist_sublist_head(list) == NULL ||
2083 	    dmu_objset_userused_enabled(os));
2084 	avl_create(&cache.uqc_user_deltas, userquota_compare,
2085 	    sizeof (userquota_node_t), offsetof(userquota_node_t, uqn_node));
2086 	avl_create(&cache.uqc_group_deltas, userquota_compare,
2087 	    sizeof (userquota_node_t), offsetof(userquota_node_t, uqn_node));
2088 	if (dmu_objset_projectquota_enabled(os))
2089 		avl_create(&cache.uqc_project_deltas, userquota_compare,
2090 		    sizeof (userquota_node_t), offsetof(userquota_node_t,
2091 		    uqn_node));
2092 
2093 	while ((dn = multilist_sublist_head(list)) != NULL) {
2094 		int flags;
2095 		ASSERT(!DMU_OBJECT_IS_SPECIAL(dn->dn_object));
2096 		ASSERT(dn->dn_phys->dn_type == DMU_OT_NONE ||
2097 		    dn->dn_phys->dn_flags &
2098 		    DNODE_FLAG_USERUSED_ACCOUNTED);
2099 
2100 		flags = dn->dn_id_flags;
2101 		ASSERT(flags);
2102 		if (flags & DN_ID_OLD_EXIST)  {
2103 			do_userquota_update(os, &cache, dn->dn_oldused,
2104 			    dn->dn_oldflags, dn->dn_olduid, dn->dn_oldgid,
2105 			    dn->dn_oldprojid, B_TRUE);
2106 			do_userobjquota_update(os, &cache, dn->dn_oldflags,
2107 			    dn->dn_olduid, dn->dn_oldgid,
2108 			    dn->dn_oldprojid, B_TRUE);
2109 		}
2110 		if (flags & DN_ID_NEW_EXIST) {
2111 			do_userquota_update(os, &cache,
2112 			    DN_USED_BYTES(dn->dn_phys), dn->dn_phys->dn_flags,
2113 			    dn->dn_newuid, dn->dn_newgid,
2114 			    dn->dn_newprojid, B_FALSE);
2115 			do_userobjquota_update(os, &cache,
2116 			    dn->dn_phys->dn_flags, dn->dn_newuid, dn->dn_newgid,
2117 			    dn->dn_newprojid, B_FALSE);
2118 		}
2119 
2120 		mutex_enter(&dn->dn_mtx);
2121 		dn->dn_oldused = 0;
2122 		dn->dn_oldflags = 0;
2123 		if (dn->dn_id_flags & DN_ID_NEW_EXIST) {
2124 			dn->dn_olduid = dn->dn_newuid;
2125 			dn->dn_oldgid = dn->dn_newgid;
2126 			dn->dn_oldprojid = dn->dn_newprojid;
2127 			dn->dn_id_flags |= DN_ID_OLD_EXIST;
2128 			if (dn->dn_bonuslen == 0)
2129 				dn->dn_id_flags |= DN_ID_CHKED_SPILL;
2130 			else
2131 				dn->dn_id_flags |= DN_ID_CHKED_BONUS;
2132 		}
2133 		dn->dn_id_flags &= ~(DN_ID_NEW_EXIST);
2134 		mutex_exit(&dn->dn_mtx);
2135 
2136 		multilist_sublist_remove(list, dn);
2137 		dnode_rele(dn, &os->os_synced_dnodes);
2138 	}
2139 	do_userquota_cacheflush(os, &cache, tx);
2140 	multilist_sublist_unlock(list);
2141 	kmem_free(uua, sizeof (*uua));
2142 }
2143 
2144 /*
2145  * Release dnode holds from dmu_objset_sync_dnodes().  When the dnode is being
2146  * synced (i.e. we have issued the zio's for blocks in the dnode), it can't be
2147  * evicted because the block containing the dnode can't be evicted until it is
2148  * written out.  However, this hold is necessary to prevent the dnode_t from
2149  * being moved (via dnode_move()) while it's still referenced by
2150  * dbuf_dirty_record_t:dr_dnode.  And dr_dnode is needed for
2151  * dirty_lightweight_leaf-type dirty records.
2152  *
2153  * If we are doing user-object accounting, the dnode_rele() happens from
2154  * userquota_updates_task() instead.
2155  */
2156 static void
2157 dnode_rele_task(void *arg)
2158 {
2159 	userquota_updates_arg_t *uua = arg;
2160 	objset_t *os = uua->uua_os;
2161 
2162 	multilist_sublist_t *list =
2163 	    multilist_sublist_lock(&os->os_synced_dnodes, uua->uua_sublist_idx);
2164 
2165 	dnode_t *dn;
2166 	while ((dn = multilist_sublist_head(list)) != NULL) {
2167 		multilist_sublist_remove(list, dn);
2168 		dnode_rele(dn, &os->os_synced_dnodes);
2169 	}
2170 	multilist_sublist_unlock(list);
2171 	kmem_free(uua, sizeof (*uua));
2172 }
2173 
2174 /*
2175  * Return TRUE if userquota updates are needed.
2176  */
2177 static boolean_t
2178 dmu_objset_do_userquota_updates_prep(objset_t *os, dmu_tx_t *tx)
2179 {
2180 	if (!dmu_objset_userused_enabled(os))
2181 		return (B_FALSE);
2182 
2183 	/*
2184 	 * If this is a raw receive just return and handle accounting
2185 	 * later when we have the keys loaded. We also don't do user
2186 	 * accounting during claiming since the datasets are not owned
2187 	 * for the duration of claiming and this txg should only be
2188 	 * used for recovery.
2189 	 */
2190 	if (os->os_encrypted && dmu_objset_is_receiving(os))
2191 		return (B_FALSE);
2192 
2193 	if (tx->tx_txg <= os->os_spa->spa_claim_max_txg)
2194 		return (B_FALSE);
2195 
2196 	/* Allocate the user/group/project used objects if necessary. */
2197 	if (DMU_USERUSED_DNODE(os)->dn_type == DMU_OT_NONE) {
2198 		VERIFY0(zap_create_claim(os,
2199 		    DMU_USERUSED_OBJECT,
2200 		    DMU_OT_USERGROUP_USED, DMU_OT_NONE, 0, tx));
2201 		VERIFY0(zap_create_claim(os,
2202 		    DMU_GROUPUSED_OBJECT,
2203 		    DMU_OT_USERGROUP_USED, DMU_OT_NONE, 0, tx));
2204 	}
2205 
2206 	if (dmu_objset_projectquota_enabled(os) &&
2207 	    DMU_PROJECTUSED_DNODE(os)->dn_type == DMU_OT_NONE) {
2208 		VERIFY0(zap_create_claim(os, DMU_PROJECTUSED_OBJECT,
2209 		    DMU_OT_USERGROUP_USED, DMU_OT_NONE, 0, tx));
2210 	}
2211 	return (B_TRUE);
2212 }
2213 
2214 /*
2215  * Dispatch taskq tasks to dp_sync_taskq to update the user accounting, and
2216  * also release the holds on the dnodes from dmu_objset_sync_dnodes().
2217  * The caller must taskq_wait(dp_sync_taskq).
2218  */
2219 void
2220 dmu_objset_sync_done(objset_t *os, dmu_tx_t *tx)
2221 {
2222 	boolean_t need_userquota = dmu_objset_do_userquota_updates_prep(os, tx);
2223 
2224 	int num_sublists = multilist_get_num_sublists(&os->os_synced_dnodes);
2225 	for (int i = 0; i < num_sublists; i++) {
2226 		userquota_updates_arg_t *uua =
2227 		    kmem_alloc(sizeof (*uua), KM_SLEEP);
2228 		uua->uua_os = os;
2229 		uua->uua_sublist_idx = i;
2230 		uua->uua_tx = tx;
2231 
2232 		/*
2233 		 * If we don't need to update userquotas, use
2234 		 * dnode_rele_task() to call dnode_rele()
2235 		 */
2236 		(void) taskq_dispatch(dmu_objset_pool(os)->dp_sync_taskq,
2237 		    need_userquota ? userquota_updates_task : dnode_rele_task,
2238 		    uua, 0);
2239 		/* callback frees uua */
2240 	}
2241 }
2242 
2243 
2244 /*
2245  * Returns a pointer to data to find uid/gid from
2246  *
2247  * If a dirty record for transaction group that is syncing can't
2248  * be found then NULL is returned.  In the NULL case it is assumed
2249  * the uid/gid aren't changing.
2250  */
2251 static void *
2252 dmu_objset_userquota_find_data(dmu_buf_impl_t *db, dmu_tx_t *tx)
2253 {
2254 	dbuf_dirty_record_t *dr;
2255 	void *data;
2256 
2257 	if (db->db_dirtycnt == 0)
2258 		return (db->db.db_data);  /* Nothing is changing */
2259 
2260 	dr = dbuf_find_dirty_eq(db, tx->tx_txg);
2261 
2262 	if (dr == NULL) {
2263 		data = NULL;
2264 	} else {
2265 		if (dr->dr_dnode->dn_bonuslen == 0 &&
2266 		    dr->dr_dbuf->db_blkid == DMU_SPILL_BLKID)
2267 			data = dr->dt.dl.dr_data->b_data;
2268 		else
2269 			data = dr->dt.dl.dr_data;
2270 	}
2271 
2272 	return (data);
2273 }
2274 
2275 void
2276 dmu_objset_userquota_get_ids(dnode_t *dn, boolean_t before, dmu_tx_t *tx)
2277 {
2278 	objset_t *os = dn->dn_objset;
2279 	void *data = NULL;
2280 	dmu_buf_impl_t *db = NULL;
2281 	int flags = dn->dn_id_flags;
2282 	int error;
2283 	boolean_t have_spill = B_FALSE;
2284 
2285 	if (!dmu_objset_userused_enabled(dn->dn_objset))
2286 		return;
2287 
2288 	/*
2289 	 * Raw receives introduce a problem with user accounting. Raw
2290 	 * receives cannot update the user accounting info because the
2291 	 * user ids and the sizes are encrypted. To guarantee that we
2292 	 * never end up with bad user accounting, we simply disable it
2293 	 * during raw receives. We also disable this for normal receives
2294 	 * so that an incremental raw receive may be done on top of an
2295 	 * existing non-raw receive.
2296 	 */
2297 	if (os->os_encrypted && dmu_objset_is_receiving(os))
2298 		return;
2299 
2300 	if (before && (flags & (DN_ID_CHKED_BONUS|DN_ID_OLD_EXIST|
2301 	    DN_ID_CHKED_SPILL)))
2302 		return;
2303 
2304 	if (before && dn->dn_bonuslen != 0)
2305 		data = DN_BONUS(dn->dn_phys);
2306 	else if (!before && dn->dn_bonuslen != 0) {
2307 		if (dn->dn_bonus) {
2308 			db = dn->dn_bonus;
2309 			mutex_enter(&db->db_mtx);
2310 			data = dmu_objset_userquota_find_data(db, tx);
2311 		} else {
2312 			data = DN_BONUS(dn->dn_phys);
2313 		}
2314 	} else if (dn->dn_bonuslen == 0 && dn->dn_bonustype == DMU_OT_SA) {
2315 			int rf = 0;
2316 
2317 			if (RW_WRITE_HELD(&dn->dn_struct_rwlock))
2318 				rf |= DB_RF_HAVESTRUCT;
2319 			error = dmu_spill_hold_by_dnode(dn,
2320 			    rf | DB_RF_MUST_SUCCEED,
2321 			    FTAG, (dmu_buf_t **)&db);
2322 			ASSERT(error == 0);
2323 			mutex_enter(&db->db_mtx);
2324 			data = (before) ? db->db.db_data :
2325 			    dmu_objset_userquota_find_data(db, tx);
2326 			have_spill = B_TRUE;
2327 	} else {
2328 		mutex_enter(&dn->dn_mtx);
2329 		dn->dn_id_flags |= DN_ID_CHKED_BONUS;
2330 		mutex_exit(&dn->dn_mtx);
2331 		return;
2332 	}
2333 
2334 	/*
2335 	 * Must always call the callback in case the object
2336 	 * type has changed and that type isn't an object type to track
2337 	 */
2338 	zfs_file_info_t zfi;
2339 	error = file_cbs[os->os_phys->os_type](dn->dn_bonustype, data, &zfi);
2340 
2341 	if (before) {
2342 		ASSERT(data);
2343 		dn->dn_olduid = zfi.zfi_user;
2344 		dn->dn_oldgid = zfi.zfi_group;
2345 		dn->dn_oldprojid = zfi.zfi_project;
2346 	} else if (data) {
2347 		dn->dn_newuid = zfi.zfi_user;
2348 		dn->dn_newgid = zfi.zfi_group;
2349 		dn->dn_newprojid = zfi.zfi_project;
2350 	}
2351 
2352 	/*
2353 	 * Preserve existing uid/gid when the callback can't determine
2354 	 * what the new uid/gid are and the callback returned EEXIST.
2355 	 * The EEXIST error tells us to just use the existing uid/gid.
2356 	 * If we don't know what the old values are then just assign
2357 	 * them to 0, since that is a new file  being created.
2358 	 */
2359 	if (!before && data == NULL && error == EEXIST) {
2360 		if (flags & DN_ID_OLD_EXIST) {
2361 			dn->dn_newuid = dn->dn_olduid;
2362 			dn->dn_newgid = dn->dn_oldgid;
2363 			dn->dn_newprojid = dn->dn_oldprojid;
2364 		} else {
2365 			dn->dn_newuid = 0;
2366 			dn->dn_newgid = 0;
2367 			dn->dn_newprojid = ZFS_DEFAULT_PROJID;
2368 		}
2369 		error = 0;
2370 	}
2371 
2372 	if (db)
2373 		mutex_exit(&db->db_mtx);
2374 
2375 	mutex_enter(&dn->dn_mtx);
2376 	if (error == 0 && before)
2377 		dn->dn_id_flags |= DN_ID_OLD_EXIST;
2378 	if (error == 0 && !before)
2379 		dn->dn_id_flags |= DN_ID_NEW_EXIST;
2380 
2381 	if (have_spill) {
2382 		dn->dn_id_flags |= DN_ID_CHKED_SPILL;
2383 	} else {
2384 		dn->dn_id_flags |= DN_ID_CHKED_BONUS;
2385 	}
2386 	mutex_exit(&dn->dn_mtx);
2387 	if (have_spill)
2388 		dmu_buf_rele((dmu_buf_t *)db, FTAG);
2389 }
2390 
2391 boolean_t
2392 dmu_objset_userspace_present(objset_t *os)
2393 {
2394 	return (os->os_phys->os_flags &
2395 	    OBJSET_FLAG_USERACCOUNTING_COMPLETE);
2396 }
2397 
2398 boolean_t
2399 dmu_objset_userobjspace_present(objset_t *os)
2400 {
2401 	return (os->os_phys->os_flags &
2402 	    OBJSET_FLAG_USEROBJACCOUNTING_COMPLETE);
2403 }
2404 
2405 boolean_t
2406 dmu_objset_projectquota_present(objset_t *os)
2407 {
2408 	return (os->os_phys->os_flags &
2409 	    OBJSET_FLAG_PROJECTQUOTA_COMPLETE);
2410 }
2411 
2412 static int
2413 dmu_objset_space_upgrade(objset_t *os)
2414 {
2415 	uint64_t obj;
2416 	int err = 0;
2417 
2418 	/*
2419 	 * We simply need to mark every object dirty, so that it will be
2420 	 * synced out and now accounted.  If this is called
2421 	 * concurrently, or if we already did some work before crashing,
2422 	 * that's fine, since we track each object's accounted state
2423 	 * independently.
2424 	 */
2425 
2426 	for (obj = 0; err == 0; err = dmu_object_next(os, &obj, FALSE, 0)) {
2427 		dmu_tx_t *tx;
2428 		dmu_buf_t *db;
2429 		int objerr;
2430 
2431 		mutex_enter(&os->os_upgrade_lock);
2432 		if (os->os_upgrade_exit)
2433 			err = SET_ERROR(EINTR);
2434 		mutex_exit(&os->os_upgrade_lock);
2435 		if (err != 0)
2436 			return (err);
2437 
2438 		if (issig(JUSTLOOKING) && issig(FORREAL))
2439 			return (SET_ERROR(EINTR));
2440 
2441 		objerr = dmu_bonus_hold(os, obj, FTAG, &db);
2442 		if (objerr != 0)
2443 			continue;
2444 		tx = dmu_tx_create(os);
2445 		dmu_tx_hold_bonus(tx, obj);
2446 		objerr = dmu_tx_assign(tx, TXG_WAIT);
2447 		if (objerr != 0) {
2448 			dmu_buf_rele(db, FTAG);
2449 			dmu_tx_abort(tx);
2450 			continue;
2451 		}
2452 		dmu_buf_will_dirty(db, tx);
2453 		dmu_buf_rele(db, FTAG);
2454 		dmu_tx_commit(tx);
2455 	}
2456 	return (0);
2457 }
2458 
2459 static int
2460 dmu_objset_userspace_upgrade_cb(objset_t *os)
2461 {
2462 	int err = 0;
2463 
2464 	if (dmu_objset_userspace_present(os))
2465 		return (0);
2466 	if (dmu_objset_is_snapshot(os))
2467 		return (SET_ERROR(EINVAL));
2468 	if (!dmu_objset_userused_enabled(os))
2469 		return (SET_ERROR(ENOTSUP));
2470 
2471 	err = dmu_objset_space_upgrade(os);
2472 	if (err)
2473 		return (err);
2474 
2475 	os->os_flags |= OBJSET_FLAG_USERACCOUNTING_COMPLETE;
2476 	txg_wait_synced(dmu_objset_pool(os), 0);
2477 	return (0);
2478 }
2479 
2480 void
2481 dmu_objset_userspace_upgrade(objset_t *os)
2482 {
2483 	dmu_objset_upgrade(os, dmu_objset_userspace_upgrade_cb);
2484 }
2485 
2486 static int
2487 dmu_objset_id_quota_upgrade_cb(objset_t *os)
2488 {
2489 	int err = 0;
2490 
2491 	if (dmu_objset_userobjspace_present(os) &&
2492 	    dmu_objset_projectquota_present(os))
2493 		return (0);
2494 	if (dmu_objset_is_snapshot(os))
2495 		return (SET_ERROR(EINVAL));
2496 	if (!dmu_objset_userused_enabled(os))
2497 		return (SET_ERROR(ENOTSUP));
2498 	if (!dmu_objset_projectquota_enabled(os) &&
2499 	    dmu_objset_userobjspace_present(os))
2500 		return (SET_ERROR(ENOTSUP));
2501 
2502 	if (dmu_objset_userobjused_enabled(os))
2503 		dmu_objset_ds(os)->ds_feature_activation[
2504 		    SPA_FEATURE_USEROBJ_ACCOUNTING] = (void *)B_TRUE;
2505 	if (dmu_objset_projectquota_enabled(os))
2506 		dmu_objset_ds(os)->ds_feature_activation[
2507 		    SPA_FEATURE_PROJECT_QUOTA] = (void *)B_TRUE;
2508 
2509 	err = dmu_objset_space_upgrade(os);
2510 	if (err)
2511 		return (err);
2512 
2513 	os->os_flags |= OBJSET_FLAG_USERACCOUNTING_COMPLETE;
2514 	if (dmu_objset_userobjused_enabled(os))
2515 		os->os_flags |= OBJSET_FLAG_USEROBJACCOUNTING_COMPLETE;
2516 	if (dmu_objset_projectquota_enabled(os))
2517 		os->os_flags |= OBJSET_FLAG_PROJECTQUOTA_COMPLETE;
2518 
2519 	txg_wait_synced(dmu_objset_pool(os), 0);
2520 	return (0);
2521 }
2522 
2523 void
2524 dmu_objset_id_quota_upgrade(objset_t *os)
2525 {
2526 	dmu_objset_upgrade(os, dmu_objset_id_quota_upgrade_cb);
2527 }
2528 
2529 boolean_t
2530 dmu_objset_userobjspace_upgradable(objset_t *os)
2531 {
2532 	return (dmu_objset_type(os) == DMU_OST_ZFS &&
2533 	    !dmu_objset_is_snapshot(os) &&
2534 	    dmu_objset_userobjused_enabled(os) &&
2535 	    !dmu_objset_userobjspace_present(os) &&
2536 	    spa_writeable(dmu_objset_spa(os)));
2537 }
2538 
2539 boolean_t
2540 dmu_objset_projectquota_upgradable(objset_t *os)
2541 {
2542 	return (dmu_objset_type(os) == DMU_OST_ZFS &&
2543 	    !dmu_objset_is_snapshot(os) &&
2544 	    dmu_objset_projectquota_enabled(os) &&
2545 	    !dmu_objset_projectquota_present(os) &&
2546 	    spa_writeable(dmu_objset_spa(os)));
2547 }
2548 
2549 void
2550 dmu_objset_space(objset_t *os, uint64_t *refdbytesp, uint64_t *availbytesp,
2551     uint64_t *usedobjsp, uint64_t *availobjsp)
2552 {
2553 	dsl_dataset_space(os->os_dsl_dataset, refdbytesp, availbytesp,
2554 	    usedobjsp, availobjsp);
2555 }
2556 
2557 uint64_t
2558 dmu_objset_fsid_guid(objset_t *os)
2559 {
2560 	return (dsl_dataset_fsid_guid(os->os_dsl_dataset));
2561 }
2562 
2563 void
2564 dmu_objset_fast_stat(objset_t *os, dmu_objset_stats_t *stat)
2565 {
2566 	stat->dds_type = os->os_phys->os_type;
2567 	if (os->os_dsl_dataset)
2568 		dsl_dataset_fast_stat(os->os_dsl_dataset, stat);
2569 }
2570 
2571 void
2572 dmu_objset_stats(objset_t *os, nvlist_t *nv)
2573 {
2574 	ASSERT(os->os_dsl_dataset ||
2575 	    os->os_phys->os_type == DMU_OST_META);
2576 
2577 	if (os->os_dsl_dataset != NULL)
2578 		dsl_dataset_stats(os->os_dsl_dataset, nv);
2579 
2580 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_TYPE,
2581 	    os->os_phys->os_type);
2582 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USERACCOUNTING,
2583 	    dmu_objset_userspace_present(os));
2584 }
2585 
2586 int
2587 dmu_objset_is_snapshot(objset_t *os)
2588 {
2589 	if (os->os_dsl_dataset != NULL)
2590 		return (os->os_dsl_dataset->ds_is_snapshot);
2591 	else
2592 		return (B_FALSE);
2593 }
2594 
2595 int
2596 dmu_snapshot_realname(objset_t *os, const char *name, char *real, int maxlen,
2597     boolean_t *conflict)
2598 {
2599 	dsl_dataset_t *ds = os->os_dsl_dataset;
2600 	uint64_t ignored;
2601 
2602 	if (dsl_dataset_phys(ds)->ds_snapnames_zapobj == 0)
2603 		return (SET_ERROR(ENOENT));
2604 
2605 	return (zap_lookup_norm(ds->ds_dir->dd_pool->dp_meta_objset,
2606 	    dsl_dataset_phys(ds)->ds_snapnames_zapobj, name, 8, 1, &ignored,
2607 	    MT_NORMALIZE, real, maxlen, conflict));
2608 }
2609 
2610 int
2611 dmu_snapshot_list_next(objset_t *os, int namelen, char *name,
2612     uint64_t *idp, uint64_t *offp, boolean_t *case_conflict)
2613 {
2614 	dsl_dataset_t *ds = os->os_dsl_dataset;
2615 	zap_cursor_t cursor;
2616 	zap_attribute_t attr;
2617 
2618 	ASSERT(dsl_pool_config_held(dmu_objset_pool(os)));
2619 
2620 	if (dsl_dataset_phys(ds)->ds_snapnames_zapobj == 0)
2621 		return (SET_ERROR(ENOENT));
2622 
2623 	zap_cursor_init_serialized(&cursor,
2624 	    ds->ds_dir->dd_pool->dp_meta_objset,
2625 	    dsl_dataset_phys(ds)->ds_snapnames_zapobj, *offp);
2626 
2627 	if (zap_cursor_retrieve(&cursor, &attr) != 0) {
2628 		zap_cursor_fini(&cursor);
2629 		return (SET_ERROR(ENOENT));
2630 	}
2631 
2632 	if (strlen(attr.za_name) + 1 > namelen) {
2633 		zap_cursor_fini(&cursor);
2634 		return (SET_ERROR(ENAMETOOLONG));
2635 	}
2636 
2637 	(void) strlcpy(name, attr.za_name, namelen);
2638 	if (idp)
2639 		*idp = attr.za_first_integer;
2640 	if (case_conflict)
2641 		*case_conflict = attr.za_normalization_conflict;
2642 	zap_cursor_advance(&cursor);
2643 	*offp = zap_cursor_serialize(&cursor);
2644 	zap_cursor_fini(&cursor);
2645 
2646 	return (0);
2647 }
2648 
2649 int
2650 dmu_snapshot_lookup(objset_t *os, const char *name, uint64_t *value)
2651 {
2652 	return (dsl_dataset_snap_lookup(os->os_dsl_dataset, name, value));
2653 }
2654 
2655 int
2656 dmu_dir_list_next(objset_t *os, int namelen, char *name,
2657     uint64_t *idp, uint64_t *offp)
2658 {
2659 	dsl_dir_t *dd = os->os_dsl_dataset->ds_dir;
2660 	zap_cursor_t cursor;
2661 	zap_attribute_t attr;
2662 
2663 	/* there is no next dir on a snapshot! */
2664 	if (os->os_dsl_dataset->ds_object !=
2665 	    dsl_dir_phys(dd)->dd_head_dataset_obj)
2666 		return (SET_ERROR(ENOENT));
2667 
2668 	zap_cursor_init_serialized(&cursor,
2669 	    dd->dd_pool->dp_meta_objset,
2670 	    dsl_dir_phys(dd)->dd_child_dir_zapobj, *offp);
2671 
2672 	if (zap_cursor_retrieve(&cursor, &attr) != 0) {
2673 		zap_cursor_fini(&cursor);
2674 		return (SET_ERROR(ENOENT));
2675 	}
2676 
2677 	if (strlen(attr.za_name) + 1 > namelen) {
2678 		zap_cursor_fini(&cursor);
2679 		return (SET_ERROR(ENAMETOOLONG));
2680 	}
2681 
2682 	(void) strlcpy(name, attr.za_name, namelen);
2683 	if (idp)
2684 		*idp = attr.za_first_integer;
2685 	zap_cursor_advance(&cursor);
2686 	*offp = zap_cursor_serialize(&cursor);
2687 	zap_cursor_fini(&cursor);
2688 
2689 	return (0);
2690 }
2691 
2692 typedef struct dmu_objset_find_ctx {
2693 	taskq_t		*dc_tq;
2694 	dsl_pool_t	*dc_dp;
2695 	uint64_t	dc_ddobj;
2696 	char		*dc_ddname; /* last component of ddobj's name */
2697 	int		(*dc_func)(dsl_pool_t *, dsl_dataset_t *, void *);
2698 	void		*dc_arg;
2699 	int		dc_flags;
2700 	kmutex_t	*dc_error_lock;
2701 	int		*dc_error;
2702 } dmu_objset_find_ctx_t;
2703 
2704 static void
2705 dmu_objset_find_dp_impl(dmu_objset_find_ctx_t *dcp)
2706 {
2707 	dsl_pool_t *dp = dcp->dc_dp;
2708 	dsl_dir_t *dd;
2709 	dsl_dataset_t *ds;
2710 	zap_cursor_t zc;
2711 	zap_attribute_t *attr;
2712 	uint64_t thisobj;
2713 	int err = 0;
2714 
2715 	/* don't process if there already was an error */
2716 	if (*dcp->dc_error != 0)
2717 		goto out;
2718 
2719 	/*
2720 	 * Note: passing the name (dc_ddname) here is optional, but it
2721 	 * improves performance because we don't need to call
2722 	 * zap_value_search() to determine the name.
2723 	 */
2724 	err = dsl_dir_hold_obj(dp, dcp->dc_ddobj, dcp->dc_ddname, FTAG, &dd);
2725 	if (err != 0)
2726 		goto out;
2727 
2728 	/* Don't visit hidden ($MOS & $ORIGIN) objsets. */
2729 	if (dd->dd_myname[0] == '$') {
2730 		dsl_dir_rele(dd, FTAG);
2731 		goto out;
2732 	}
2733 
2734 	thisobj = dsl_dir_phys(dd)->dd_head_dataset_obj;
2735 	attr = kmem_alloc(sizeof (zap_attribute_t), KM_SLEEP);
2736 
2737 	/*
2738 	 * Iterate over all children.
2739 	 */
2740 	if (dcp->dc_flags & DS_FIND_CHILDREN) {
2741 		for (zap_cursor_init(&zc, dp->dp_meta_objset,
2742 		    dsl_dir_phys(dd)->dd_child_dir_zapobj);
2743 		    zap_cursor_retrieve(&zc, attr) == 0;
2744 		    (void) zap_cursor_advance(&zc)) {
2745 			ASSERT3U(attr->za_integer_length, ==,
2746 			    sizeof (uint64_t));
2747 			ASSERT3U(attr->za_num_integers, ==, 1);
2748 
2749 			dmu_objset_find_ctx_t *child_dcp =
2750 			    kmem_alloc(sizeof (*child_dcp), KM_SLEEP);
2751 			*child_dcp = *dcp;
2752 			child_dcp->dc_ddobj = attr->za_first_integer;
2753 			child_dcp->dc_ddname = spa_strdup(attr->za_name);
2754 			if (dcp->dc_tq != NULL)
2755 				(void) taskq_dispatch(dcp->dc_tq,
2756 				    dmu_objset_find_dp_cb, child_dcp, TQ_SLEEP);
2757 			else
2758 				dmu_objset_find_dp_impl(child_dcp);
2759 		}
2760 		zap_cursor_fini(&zc);
2761 	}
2762 
2763 	/*
2764 	 * Iterate over all snapshots.
2765 	 */
2766 	if (dcp->dc_flags & DS_FIND_SNAPSHOTS) {
2767 		dsl_dataset_t *ds;
2768 		err = dsl_dataset_hold_obj(dp, thisobj, FTAG, &ds);
2769 
2770 		if (err == 0) {
2771 			uint64_t snapobj;
2772 
2773 			snapobj = dsl_dataset_phys(ds)->ds_snapnames_zapobj;
2774 			dsl_dataset_rele(ds, FTAG);
2775 
2776 			for (zap_cursor_init(&zc, dp->dp_meta_objset, snapobj);
2777 			    zap_cursor_retrieve(&zc, attr) == 0;
2778 			    (void) zap_cursor_advance(&zc)) {
2779 				ASSERT3U(attr->za_integer_length, ==,
2780 				    sizeof (uint64_t));
2781 				ASSERT3U(attr->za_num_integers, ==, 1);
2782 
2783 				err = dsl_dataset_hold_obj(dp,
2784 				    attr->za_first_integer, FTAG, &ds);
2785 				if (err != 0)
2786 					break;
2787 				err = dcp->dc_func(dp, ds, dcp->dc_arg);
2788 				dsl_dataset_rele(ds, FTAG);
2789 				if (err != 0)
2790 					break;
2791 			}
2792 			zap_cursor_fini(&zc);
2793 		}
2794 	}
2795 
2796 	kmem_free(attr, sizeof (zap_attribute_t));
2797 
2798 	if (err != 0) {
2799 		dsl_dir_rele(dd, FTAG);
2800 		goto out;
2801 	}
2802 
2803 	/*
2804 	 * Apply to self.
2805 	 */
2806 	err = dsl_dataset_hold_obj(dp, thisobj, FTAG, &ds);
2807 
2808 	/*
2809 	 * Note: we hold the dir while calling dsl_dataset_hold_obj() so
2810 	 * that the dir will remain cached, and we won't have to re-instantiate
2811 	 * it (which could be expensive due to finding its name via
2812 	 * zap_value_search()).
2813 	 */
2814 	dsl_dir_rele(dd, FTAG);
2815 	if (err != 0)
2816 		goto out;
2817 	err = dcp->dc_func(dp, ds, dcp->dc_arg);
2818 	dsl_dataset_rele(ds, FTAG);
2819 
2820 out:
2821 	if (err != 0) {
2822 		mutex_enter(dcp->dc_error_lock);
2823 		/* only keep first error */
2824 		if (*dcp->dc_error == 0)
2825 			*dcp->dc_error = err;
2826 		mutex_exit(dcp->dc_error_lock);
2827 	}
2828 
2829 	if (dcp->dc_ddname != NULL)
2830 		spa_strfree(dcp->dc_ddname);
2831 	kmem_free(dcp, sizeof (*dcp));
2832 }
2833 
2834 static void
2835 dmu_objset_find_dp_cb(void *arg)
2836 {
2837 	dmu_objset_find_ctx_t *dcp = arg;
2838 	dsl_pool_t *dp = dcp->dc_dp;
2839 
2840 	/*
2841 	 * We need to get a pool_config_lock here, as there are several
2842 	 * assert(pool_config_held) down the stack. Getting a lock via
2843 	 * dsl_pool_config_enter is risky, as it might be stalled by a
2844 	 * pending writer. This would deadlock, as the write lock can
2845 	 * only be granted when our parent thread gives up the lock.
2846 	 * The _prio interface gives us priority over a pending writer.
2847 	 */
2848 	dsl_pool_config_enter_prio(dp, FTAG);
2849 
2850 	dmu_objset_find_dp_impl(dcp);
2851 
2852 	dsl_pool_config_exit(dp, FTAG);
2853 }
2854 
2855 /*
2856  * Find objsets under and including ddobj, call func(ds) on each.
2857  * The order for the enumeration is completely undefined.
2858  * func is called with dsl_pool_config held.
2859  */
2860 int
2861 dmu_objset_find_dp(dsl_pool_t *dp, uint64_t ddobj,
2862     int func(dsl_pool_t *, dsl_dataset_t *, void *), void *arg, int flags)
2863 {
2864 	int error = 0;
2865 	taskq_t *tq = NULL;
2866 	int ntasks;
2867 	dmu_objset_find_ctx_t *dcp;
2868 	kmutex_t err_lock;
2869 
2870 	mutex_init(&err_lock, NULL, MUTEX_DEFAULT, NULL);
2871 	dcp = kmem_alloc(sizeof (*dcp), KM_SLEEP);
2872 	dcp->dc_tq = NULL;
2873 	dcp->dc_dp = dp;
2874 	dcp->dc_ddobj = ddobj;
2875 	dcp->dc_ddname = NULL;
2876 	dcp->dc_func = func;
2877 	dcp->dc_arg = arg;
2878 	dcp->dc_flags = flags;
2879 	dcp->dc_error_lock = &err_lock;
2880 	dcp->dc_error = &error;
2881 
2882 	if ((flags & DS_FIND_SERIALIZE) || dsl_pool_config_held_writer(dp)) {
2883 		/*
2884 		 * In case a write lock is held we can't make use of
2885 		 * parallelism, as down the stack of the worker threads
2886 		 * the lock is asserted via dsl_pool_config_held.
2887 		 * In case of a read lock this is solved by getting a read
2888 		 * lock in each worker thread, which isn't possible in case
2889 		 * of a writer lock. So we fall back to the synchronous path
2890 		 * here.
2891 		 * In the future it might be possible to get some magic into
2892 		 * dsl_pool_config_held in a way that it returns true for
2893 		 * the worker threads so that a single lock held from this
2894 		 * thread suffices. For now, stay single threaded.
2895 		 */
2896 		dmu_objset_find_dp_impl(dcp);
2897 		mutex_destroy(&err_lock);
2898 
2899 		return (error);
2900 	}
2901 
2902 	ntasks = dmu_find_threads;
2903 	if (ntasks == 0)
2904 		ntasks = vdev_count_leaves(dp->dp_spa) * 4;
2905 	tq = taskq_create("dmu_objset_find", ntasks, maxclsyspri, ntasks,
2906 	    INT_MAX, 0);
2907 	if (tq == NULL) {
2908 		kmem_free(dcp, sizeof (*dcp));
2909 		mutex_destroy(&err_lock);
2910 
2911 		return (SET_ERROR(ENOMEM));
2912 	}
2913 	dcp->dc_tq = tq;
2914 
2915 	/* dcp will be freed by task */
2916 	(void) taskq_dispatch(tq, dmu_objset_find_dp_cb, dcp, TQ_SLEEP);
2917 
2918 	/*
2919 	 * PORTING: this code relies on the property of taskq_wait to wait
2920 	 * until no more tasks are queued and no more tasks are active. As
2921 	 * we always queue new tasks from within other tasks, task_wait
2922 	 * reliably waits for the full recursion to finish, even though we
2923 	 * enqueue new tasks after taskq_wait has been called.
2924 	 * On platforms other than illumos, taskq_wait may not have this
2925 	 * property.
2926 	 */
2927 	taskq_wait(tq);
2928 	taskq_destroy(tq);
2929 	mutex_destroy(&err_lock);
2930 
2931 	return (error);
2932 }
2933 
2934 /*
2935  * Find all objsets under name, and for each, call 'func(child_name, arg)'.
2936  * The dp_config_rwlock must not be held when this is called, and it
2937  * will not be held when the callback is called.
2938  * Therefore this function should only be used when the pool is not changing
2939  * (e.g. in syncing context), or the callback can deal with the possible races.
2940  */
2941 static int
2942 dmu_objset_find_impl(spa_t *spa, const char *name,
2943     int func(const char *, void *), void *arg, int flags)
2944 {
2945 	dsl_dir_t *dd;
2946 	dsl_pool_t *dp = spa_get_dsl(spa);
2947 	dsl_dataset_t *ds;
2948 	zap_cursor_t zc;
2949 	zap_attribute_t *attr;
2950 	char *child;
2951 	uint64_t thisobj;
2952 	int err;
2953 
2954 	dsl_pool_config_enter(dp, FTAG);
2955 
2956 	err = dsl_dir_hold(dp, name, FTAG, &dd, NULL);
2957 	if (err != 0) {
2958 		dsl_pool_config_exit(dp, FTAG);
2959 		return (err);
2960 	}
2961 
2962 	/* Don't visit hidden ($MOS & $ORIGIN) objsets. */
2963 	if (dd->dd_myname[0] == '$') {
2964 		dsl_dir_rele(dd, FTAG);
2965 		dsl_pool_config_exit(dp, FTAG);
2966 		return (0);
2967 	}
2968 
2969 	thisobj = dsl_dir_phys(dd)->dd_head_dataset_obj;
2970 	attr = kmem_alloc(sizeof (zap_attribute_t), KM_SLEEP);
2971 
2972 	/*
2973 	 * Iterate over all children.
2974 	 */
2975 	if (flags & DS_FIND_CHILDREN) {
2976 		for (zap_cursor_init(&zc, dp->dp_meta_objset,
2977 		    dsl_dir_phys(dd)->dd_child_dir_zapobj);
2978 		    zap_cursor_retrieve(&zc, attr) == 0;
2979 		    (void) zap_cursor_advance(&zc)) {
2980 			ASSERT3U(attr->za_integer_length, ==,
2981 			    sizeof (uint64_t));
2982 			ASSERT3U(attr->za_num_integers, ==, 1);
2983 
2984 			child = kmem_asprintf("%s/%s", name, attr->za_name);
2985 			dsl_pool_config_exit(dp, FTAG);
2986 			err = dmu_objset_find_impl(spa, child,
2987 			    func, arg, flags);
2988 			dsl_pool_config_enter(dp, FTAG);
2989 			kmem_strfree(child);
2990 			if (err != 0)
2991 				break;
2992 		}
2993 		zap_cursor_fini(&zc);
2994 
2995 		if (err != 0) {
2996 			dsl_dir_rele(dd, FTAG);
2997 			dsl_pool_config_exit(dp, FTAG);
2998 			kmem_free(attr, sizeof (zap_attribute_t));
2999 			return (err);
3000 		}
3001 	}
3002 
3003 	/*
3004 	 * Iterate over all snapshots.
3005 	 */
3006 	if (flags & DS_FIND_SNAPSHOTS) {
3007 		err = dsl_dataset_hold_obj(dp, thisobj, FTAG, &ds);
3008 
3009 		if (err == 0) {
3010 			uint64_t snapobj;
3011 
3012 			snapobj = dsl_dataset_phys(ds)->ds_snapnames_zapobj;
3013 			dsl_dataset_rele(ds, FTAG);
3014 
3015 			for (zap_cursor_init(&zc, dp->dp_meta_objset, snapobj);
3016 			    zap_cursor_retrieve(&zc, attr) == 0;
3017 			    (void) zap_cursor_advance(&zc)) {
3018 				ASSERT3U(attr->za_integer_length, ==,
3019 				    sizeof (uint64_t));
3020 				ASSERT3U(attr->za_num_integers, ==, 1);
3021 
3022 				child = kmem_asprintf("%s@%s",
3023 				    name, attr->za_name);
3024 				dsl_pool_config_exit(dp, FTAG);
3025 				err = func(child, arg);
3026 				dsl_pool_config_enter(dp, FTAG);
3027 				kmem_strfree(child);
3028 				if (err != 0)
3029 					break;
3030 			}
3031 			zap_cursor_fini(&zc);
3032 		}
3033 	}
3034 
3035 	dsl_dir_rele(dd, FTAG);
3036 	kmem_free(attr, sizeof (zap_attribute_t));
3037 	dsl_pool_config_exit(dp, FTAG);
3038 
3039 	if (err != 0)
3040 		return (err);
3041 
3042 	/* Apply to self. */
3043 	return (func(name, arg));
3044 }
3045 
3046 /*
3047  * See comment above dmu_objset_find_impl().
3048  */
3049 int
3050 dmu_objset_find(const char *name, int func(const char *, void *), void *arg,
3051     int flags)
3052 {
3053 	spa_t *spa;
3054 	int error;
3055 
3056 	error = spa_open(name, &spa, FTAG);
3057 	if (error != 0)
3058 		return (error);
3059 	error = dmu_objset_find_impl(spa, name, func, arg, flags);
3060 	spa_close(spa, FTAG);
3061 	return (error);
3062 }
3063 
3064 boolean_t
3065 dmu_objset_incompatible_encryption_version(objset_t *os)
3066 {
3067 	return (dsl_dir_incompatible_encryption_version(
3068 	    os->os_dsl_dataset->ds_dir));
3069 }
3070 
3071 void
3072 dmu_objset_set_user(objset_t *os, void *user_ptr)
3073 {
3074 	ASSERT(MUTEX_HELD(&os->os_user_ptr_lock));
3075 	os->os_user_ptr = user_ptr;
3076 }
3077 
3078 void *
3079 dmu_objset_get_user(objset_t *os)
3080 {
3081 	ASSERT(MUTEX_HELD(&os->os_user_ptr_lock));
3082 	return (os->os_user_ptr);
3083 }
3084 
3085 /*
3086  * Determine name of filesystem, given name of snapshot.
3087  * buf must be at least ZFS_MAX_DATASET_NAME_LEN bytes
3088  */
3089 int
3090 dmu_fsname(const char *snapname, char *buf)
3091 {
3092 	char *atp = strchr(snapname, '@');
3093 	if (atp == NULL)
3094 		return (SET_ERROR(EINVAL));
3095 	if (atp - snapname >= ZFS_MAX_DATASET_NAME_LEN)
3096 		return (SET_ERROR(ENAMETOOLONG));
3097 	(void) strlcpy(buf, snapname, atp - snapname + 1);
3098 	return (0);
3099 }
3100 
3101 /*
3102  * Call when we think we're going to write/free space in open context
3103  * to track the amount of dirty data in the open txg, which is also the
3104  * amount of memory that can not be evicted until this txg syncs.
3105  *
3106  * Note that there are two conditions where this can be called from
3107  * syncing context:
3108  *
3109  * [1] When we just created the dataset, in which case we go on with
3110  *     updating any accounting of dirty data as usual.
3111  * [2] When we are dirtying MOS data, in which case we only update the
3112  *     pool's accounting of dirty data.
3113  */
3114 void
3115 dmu_objset_willuse_space(objset_t *os, int64_t space, dmu_tx_t *tx)
3116 {
3117 	dsl_dataset_t *ds = os->os_dsl_dataset;
3118 	int64_t aspace = spa_get_worst_case_asize(os->os_spa, space);
3119 
3120 	if (ds != NULL) {
3121 		dsl_dir_willuse_space(ds->ds_dir, aspace, tx);
3122 	}
3123 
3124 	dsl_pool_dirty_space(dmu_tx_pool(tx), space, tx);
3125 }
3126 
3127 #if defined(_KERNEL)
3128 EXPORT_SYMBOL(dmu_objset_zil);
3129 EXPORT_SYMBOL(dmu_objset_pool);
3130 EXPORT_SYMBOL(dmu_objset_ds);
3131 EXPORT_SYMBOL(dmu_objset_type);
3132 EXPORT_SYMBOL(dmu_objset_name);
3133 EXPORT_SYMBOL(dmu_objset_hold);
3134 EXPORT_SYMBOL(dmu_objset_hold_flags);
3135 EXPORT_SYMBOL(dmu_objset_own);
3136 EXPORT_SYMBOL(dmu_objset_rele);
3137 EXPORT_SYMBOL(dmu_objset_rele_flags);
3138 EXPORT_SYMBOL(dmu_objset_disown);
3139 EXPORT_SYMBOL(dmu_objset_from_ds);
3140 EXPORT_SYMBOL(dmu_objset_create);
3141 EXPORT_SYMBOL(dmu_objset_clone);
3142 EXPORT_SYMBOL(dmu_objset_stats);
3143 EXPORT_SYMBOL(dmu_objset_fast_stat);
3144 EXPORT_SYMBOL(dmu_objset_spa);
3145 EXPORT_SYMBOL(dmu_objset_space);
3146 EXPORT_SYMBOL(dmu_objset_fsid_guid);
3147 EXPORT_SYMBOL(dmu_objset_find);
3148 EXPORT_SYMBOL(dmu_objset_byteswap);
3149 EXPORT_SYMBOL(dmu_objset_evict_dbufs);
3150 EXPORT_SYMBOL(dmu_objset_snap_cmtime);
3151 EXPORT_SYMBOL(dmu_objset_dnodesize);
3152 
3153 EXPORT_SYMBOL(dmu_objset_sync);
3154 EXPORT_SYMBOL(dmu_objset_is_dirty);
3155 EXPORT_SYMBOL(dmu_objset_create_impl_dnstats);
3156 EXPORT_SYMBOL(dmu_objset_create_impl);
3157 EXPORT_SYMBOL(dmu_objset_open_impl);
3158 EXPORT_SYMBOL(dmu_objset_evict);
3159 EXPORT_SYMBOL(dmu_objset_register_type);
3160 EXPORT_SYMBOL(dmu_objset_sync_done);
3161 EXPORT_SYMBOL(dmu_objset_userquota_get_ids);
3162 EXPORT_SYMBOL(dmu_objset_userused_enabled);
3163 EXPORT_SYMBOL(dmu_objset_userspace_upgrade);
3164 EXPORT_SYMBOL(dmu_objset_userspace_present);
3165 EXPORT_SYMBOL(dmu_objset_userobjused_enabled);
3166 EXPORT_SYMBOL(dmu_objset_userobjspace_upgradable);
3167 EXPORT_SYMBOL(dmu_objset_userobjspace_present);
3168 EXPORT_SYMBOL(dmu_objset_projectquota_enabled);
3169 EXPORT_SYMBOL(dmu_objset_projectquota_present);
3170 EXPORT_SYMBOL(dmu_objset_projectquota_upgradable);
3171 EXPORT_SYMBOL(dmu_objset_id_quota_upgrade);
3172 #endif
3173