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