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