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