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