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