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