xref: /freebsd/sys/contrib/openzfs/module/zfs/dmu_objset.c (revision 66e85755595a451db490d2fe24267d85db4b09c2)
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 			ASSERT0P(ds->ds_objset);
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,
1456 		    B_TRUE)) == 0) {
1457 			dsl_dataset_long_rele(dmu_objset_ds(os), upgrade_tag);
1458 		}
1459 		txg_wait_synced(os->os_spa->spa_dsl_pool, 0);
1460 	} else {
1461 		mutex_exit(&os->os_upgrade_lock);
1462 	}
1463 }
1464 
1465 static void
dmu_objset_sync_dnodes(multilist_sublist_t * list,dmu_tx_t * tx)1466 dmu_objset_sync_dnodes(multilist_sublist_t *list, dmu_tx_t *tx)
1467 {
1468 	dnode_t *dn;
1469 
1470 	while ((dn = multilist_sublist_head(list)) != NULL) {
1471 		ASSERT(dn->dn_object != DMU_META_DNODE_OBJECT);
1472 		ASSERT(dn->dn_dbuf->db_data_pending);
1473 		/*
1474 		 * Initialize dn_zio outside dnode_sync() because the
1475 		 * meta-dnode needs to set it outside dnode_sync().
1476 		 */
1477 		dn->dn_zio = dn->dn_dbuf->db_data_pending->dr_zio;
1478 		ASSERT(dn->dn_zio);
1479 
1480 		ASSERT3U(dn->dn_nlevels, <=, DN_MAX_LEVELS);
1481 		multilist_sublist_remove(list, dn);
1482 
1483 		/*
1484 		 * See the comment above dnode_rele_task() for an explanation
1485 		 * of why this dnode hold is always needed (even when not
1486 		 * doing user accounting).
1487 		 */
1488 		multilist_t *newlist = &dn->dn_objset->os_synced_dnodes;
1489 		(void) dnode_add_ref(dn, newlist);
1490 		multilist_insert(newlist, dn);
1491 
1492 		dnode_sync(dn, tx);
1493 	}
1494 }
1495 
1496 static void
dmu_objset_write_ready(zio_t * zio,arc_buf_t * abuf,void * arg)1497 dmu_objset_write_ready(zio_t *zio, arc_buf_t *abuf, void *arg)
1498 {
1499 	(void) abuf;
1500 	blkptr_t *bp = zio->io_bp;
1501 	objset_t *os = arg;
1502 	dnode_phys_t *dnp = &os->os_phys->os_meta_dnode;
1503 	uint64_t fill = 0;
1504 
1505 	ASSERT(!BP_IS_EMBEDDED(bp));
1506 	ASSERT3U(BP_GET_TYPE(bp), ==, DMU_OT_OBJSET);
1507 	ASSERT0(BP_GET_LEVEL(bp));
1508 
1509 	/*
1510 	 * Update rootbp fill count: it should be the number of objects
1511 	 * allocated in the object set (not counting the "special"
1512 	 * objects that are stored in the objset_phys_t -- the meta
1513 	 * dnode and user/group/project accounting objects).
1514 	 */
1515 	for (int i = 0; i < dnp->dn_nblkptr; i++)
1516 		fill += BP_GET_FILL(&dnp->dn_blkptr[i]);
1517 
1518 	BP_SET_FILL(bp, fill);
1519 
1520 	if (os->os_dsl_dataset != NULL)
1521 		rrw_enter(&os->os_dsl_dataset->ds_bp_rwlock, RW_WRITER, FTAG);
1522 	*os->os_rootbp = *bp;
1523 	if (os->os_dsl_dataset != NULL)
1524 		rrw_exit(&os->os_dsl_dataset->ds_bp_rwlock, FTAG);
1525 }
1526 
1527 static void
dmu_objset_write_done(zio_t * zio,arc_buf_t * abuf,void * arg)1528 dmu_objset_write_done(zio_t *zio, arc_buf_t *abuf, void *arg)
1529 {
1530 	(void) abuf;
1531 	blkptr_t *bp = zio->io_bp;
1532 	blkptr_t *bp_orig = &zio->io_bp_orig;
1533 	objset_t *os = arg;
1534 
1535 	if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
1536 		ASSERT(BP_EQUAL(bp, bp_orig));
1537 	} else {
1538 		dsl_dataset_t *ds = os->os_dsl_dataset;
1539 		dmu_tx_t *tx = os->os_synctx;
1540 
1541 		(void) dsl_dataset_block_kill(ds, bp_orig, tx, B_TRUE);
1542 		dsl_dataset_block_born(ds, bp, tx);
1543 	}
1544 	kmem_free(bp, sizeof (*bp));
1545 }
1546 
1547 typedef struct sync_objset_arg {
1548 	zio_t		*soa_zio;
1549 	objset_t	*soa_os;
1550 	dmu_tx_t	*soa_tx;
1551 	kmutex_t	soa_mutex;
1552 	int		soa_count;
1553 	taskq_ent_t	soa_tq_ent;
1554 } sync_objset_arg_t;
1555 
1556 typedef struct sync_dnodes_arg {
1557 	multilist_t	*sda_list;
1558 	int		sda_sublist_idx;
1559 	multilist_t	*sda_newlist;
1560 	sync_objset_arg_t *sda_soa;
1561 } sync_dnodes_arg_t;
1562 
1563 static void sync_meta_dnode_task(void *arg);
1564 
1565 static void
sync_dnodes_task(void * arg)1566 sync_dnodes_task(void *arg)
1567 {
1568 	sync_dnodes_arg_t *sda = arg;
1569 	sync_objset_arg_t *soa = sda->sda_soa;
1570 	objset_t *os = soa->soa_os;
1571 
1572 	uint_t allocator = spa_acq_allocator(os->os_spa);
1573 	multilist_sublist_t *ms =
1574 	    multilist_sublist_lock_idx(sda->sda_list, sda->sda_sublist_idx);
1575 
1576 	dmu_objset_sync_dnodes(ms, soa->soa_tx);
1577 
1578 	multilist_sublist_unlock(ms);
1579 	spa_rel_allocator(os->os_spa, allocator);
1580 
1581 	kmem_free(sda, sizeof (*sda));
1582 
1583 	mutex_enter(&soa->soa_mutex);
1584 	ASSERT(soa->soa_count != 0);
1585 	if (--soa->soa_count != 0) {
1586 		mutex_exit(&soa->soa_mutex);
1587 		return;
1588 	}
1589 	mutex_exit(&soa->soa_mutex);
1590 
1591 	taskq_dispatch_ent(dmu_objset_pool(os)->dp_sync_taskq,
1592 	    sync_meta_dnode_task, soa, TQ_FRONT, &soa->soa_tq_ent);
1593 }
1594 
1595 /*
1596  * Issue the zio_nowait() for all dirty record zios on the meta dnode,
1597  * then trigger the callback for the zil_sync. This runs once for each
1598  * objset, only after any/all sublists in the objset have been synced.
1599  */
1600 static void
sync_meta_dnode_task(void * arg)1601 sync_meta_dnode_task(void *arg)
1602 {
1603 	sync_objset_arg_t *soa = arg;
1604 	objset_t *os = soa->soa_os;
1605 	dmu_tx_t *tx = soa->soa_tx;
1606 	int txgoff = tx->tx_txg & TXG_MASK;
1607 	dbuf_dirty_record_t *dr;
1608 
1609 	ASSERT0(soa->soa_count);
1610 
1611 	list_t *list = &DMU_META_DNODE(os)->dn_dirty_records[txgoff];
1612 	while ((dr = list_remove_head(list)) != NULL) {
1613 		ASSERT0(dr->dr_dbuf->db_level);
1614 		zio_nowait(dr->dr_zio);
1615 	}
1616 
1617 	/* Enable dnode backfill if enough objects have been freed. */
1618 	if (os->os_freed_dnodes >= dmu_rescan_dnode_threshold) {
1619 		os->os_rescan_dnodes = B_TRUE;
1620 		os->os_freed_dnodes = 0;
1621 	}
1622 
1623 	/*
1624 	 * Free intent log blocks up to this tx.
1625 	 */
1626 	zil_sync(os->os_zil, tx);
1627 	os->os_phys->os_zil_header = os->os_zil_header;
1628 	zio_nowait(soa->soa_zio);
1629 
1630 	mutex_destroy(&soa->soa_mutex);
1631 	kmem_free(soa, sizeof (*soa));
1632 }
1633 
1634 /* called from dsl */
1635 void
dmu_objset_sync(objset_t * os,zio_t * pio,dmu_tx_t * tx)1636 dmu_objset_sync(objset_t *os, zio_t *pio, dmu_tx_t *tx)
1637 {
1638 	int txgoff;
1639 	zbookmark_phys_t zb;
1640 	zio_prop_t zp;
1641 	zio_t *zio;
1642 	int num_sublists;
1643 	multilist_t *ml;
1644 	blkptr_t *blkptr_copy = kmem_alloc(sizeof (*os->os_rootbp), KM_SLEEP);
1645 	*blkptr_copy = *os->os_rootbp;
1646 
1647 	dprintf_ds(os->os_dsl_dataset, "txg=%llu\n", (u_longlong_t)tx->tx_txg);
1648 
1649 	ASSERT(dmu_tx_is_syncing(tx));
1650 	/* XXX the write_done callback should really give us the tx... */
1651 	os->os_synctx = tx;
1652 
1653 	if (os->os_dsl_dataset == NULL) {
1654 		/*
1655 		 * This is the MOS.  If we have upgraded,
1656 		 * spa_max_replication() could change, so reset
1657 		 * os_copies here.
1658 		 */
1659 		os->os_copies = spa_max_replication(os->os_spa);
1660 	}
1661 
1662 	/*
1663 	 * Create the root block IO
1664 	 */
1665 	SET_BOOKMARK(&zb, os->os_dsl_dataset ?
1666 	    os->os_dsl_dataset->ds_object : DMU_META_OBJSET,
1667 	    ZB_ROOT_OBJECT, ZB_ROOT_LEVEL, ZB_ROOT_BLKID);
1668 	arc_release(os->os_phys_buf, &os->os_phys_buf);
1669 
1670 	dmu_write_policy(os, NULL, 0, 0, &zp);
1671 
1672 	/*
1673 	 * If we are either claiming the ZIL or doing a raw receive, write
1674 	 * out the os_phys_buf raw. Neither of these actions will effect the
1675 	 * MAC at this point.
1676 	 */
1677 	if (os->os_raw_receive ||
1678 	    os->os_next_write_raw[tx->tx_txg & TXG_MASK]) {
1679 		ASSERT(os->os_encrypted);
1680 		arc_convert_to_raw(os->os_phys_buf,
1681 		    os->os_dsl_dataset->ds_object, ZFS_HOST_BYTEORDER,
1682 		    DMU_OT_OBJSET, NULL, NULL, NULL);
1683 	}
1684 
1685 	zio = arc_write(pio, os->os_spa, tx->tx_txg,
1686 	    blkptr_copy, os->os_phys_buf, B_FALSE, dmu_os_is_l2cacheable(os),
1687 	    &zp, dmu_objset_write_ready, NULL, dmu_objset_write_done,
1688 	    os, ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_MUSTSUCCEED, &zb);
1689 
1690 	/*
1691 	 * Sync special dnodes - the parent IO for the sync is the root block
1692 	 */
1693 	DMU_META_DNODE(os)->dn_zio = zio;
1694 	dnode_sync(DMU_META_DNODE(os), tx);
1695 
1696 	os->os_phys->os_flags = os->os_flags;
1697 
1698 	if (DMU_USERUSED_DNODE(os) &&
1699 	    DMU_USERUSED_DNODE(os)->dn_type != DMU_OT_NONE) {
1700 		DMU_USERUSED_DNODE(os)->dn_zio = zio;
1701 		dnode_sync(DMU_USERUSED_DNODE(os), tx);
1702 		DMU_GROUPUSED_DNODE(os)->dn_zio = zio;
1703 		dnode_sync(DMU_GROUPUSED_DNODE(os), tx);
1704 	}
1705 
1706 	if (DMU_PROJECTUSED_DNODE(os) &&
1707 	    DMU_PROJECTUSED_DNODE(os)->dn_type != DMU_OT_NONE) {
1708 		DMU_PROJECTUSED_DNODE(os)->dn_zio = zio;
1709 		dnode_sync(DMU_PROJECTUSED_DNODE(os), tx);
1710 	}
1711 
1712 	txgoff = tx->tx_txg & TXG_MASK;
1713 
1714 	/*
1715 	 * We must create the list here because it uses the
1716 	 * dn_dirty_link[] of this txg.  But it may already
1717 	 * exist because we call dsl_dataset_sync() twice per txg.
1718 	 */
1719 	if (os->os_synced_dnodes.ml_sublists == NULL) {
1720 		multilist_create(&os->os_synced_dnodes, sizeof (dnode_t),
1721 		    offsetof(dnode_t, dn_dirty_link[txgoff]),
1722 		    dnode_multilist_index_func);
1723 	} else {
1724 		ASSERT3U(os->os_synced_dnodes.ml_offset, ==,
1725 		    offsetof(dnode_t, dn_dirty_link[txgoff]));
1726 	}
1727 
1728 	/*
1729 	 * zio_nowait(zio) is done after any/all sublist and meta dnode
1730 	 * zios have been nowaited, and the zil_sync() has been performed.
1731 	 * The soa is freed at the end of sync_meta_dnode_task.
1732 	 */
1733 	sync_objset_arg_t *soa = kmem_alloc(sizeof (*soa), KM_SLEEP);
1734 	soa->soa_zio = zio;
1735 	soa->soa_os = os;
1736 	soa->soa_tx = tx;
1737 	taskq_init_ent(&soa->soa_tq_ent);
1738 	mutex_init(&soa->soa_mutex, NULL, MUTEX_DEFAULT, NULL);
1739 
1740 	ml = &os->os_dirty_dnodes[txgoff];
1741 	soa->soa_count = num_sublists = multilist_get_num_sublists(ml);
1742 
1743 	for (int i = 0; i < num_sublists; i++) {
1744 		if (multilist_sublist_is_empty_idx(ml, i))
1745 			soa->soa_count--;
1746 	}
1747 
1748 	if (soa->soa_count == 0) {
1749 		taskq_dispatch_ent(dmu_objset_pool(os)->dp_sync_taskq,
1750 		    sync_meta_dnode_task, soa, TQ_FRONT, &soa->soa_tq_ent);
1751 	} else {
1752 		/*
1753 		 * Sync sublists in parallel. The last to finish
1754 		 * (i.e., when soa->soa_count reaches zero) must
1755 		 *  dispatch sync_meta_dnode_task.
1756 		 */
1757 		for (int i = 0; i < num_sublists; i++) {
1758 			if (multilist_sublist_is_empty_idx(ml, i))
1759 				continue;
1760 			sync_dnodes_arg_t *sda =
1761 			    kmem_alloc(sizeof (*sda), KM_SLEEP);
1762 			sda->sda_list = ml;
1763 			sda->sda_sublist_idx = i;
1764 			sda->sda_soa = soa;
1765 			(void) taskq_dispatch(
1766 			    dmu_objset_pool(os)->dp_sync_taskq,
1767 			    sync_dnodes_task, sda, 0);
1768 			/* sync_dnodes_task frees sda */
1769 		}
1770 	}
1771 }
1772 
1773 boolean_t
dmu_objset_is_dirty(objset_t * os,uint64_t txg)1774 dmu_objset_is_dirty(objset_t *os, uint64_t txg)
1775 {
1776 	return (!multilist_is_empty(&os->os_dirty_dnodes[txg & TXG_MASK]));
1777 }
1778 
1779 static file_info_cb_t *file_cbs[DMU_OST_NUMTYPES];
1780 
1781 void
dmu_objset_register_type(dmu_objset_type_t ost,file_info_cb_t * cb)1782 dmu_objset_register_type(dmu_objset_type_t ost, file_info_cb_t *cb)
1783 {
1784 	file_cbs[ost] = cb;
1785 }
1786 
1787 int
dmu_get_file_info(objset_t * os,dmu_object_type_t bonustype,const void * data,zfs_file_info_t * zfi)1788 dmu_get_file_info(objset_t *os, dmu_object_type_t bonustype, const void *data,
1789     zfs_file_info_t *zfi)
1790 {
1791 	file_info_cb_t *cb = file_cbs[os->os_phys->os_type];
1792 	if (cb == NULL)
1793 		return (EINVAL);
1794 	return (cb(bonustype, data, zfi));
1795 }
1796 
1797 boolean_t
dmu_objset_userused_enabled(objset_t * os)1798 dmu_objset_userused_enabled(objset_t *os)
1799 {
1800 	return (spa_version(os->os_spa) >= SPA_VERSION_USERSPACE &&
1801 	    file_cbs[os->os_phys->os_type] != NULL &&
1802 	    DMU_USERUSED_DNODE(os) != NULL);
1803 }
1804 
1805 boolean_t
dmu_objset_userobjused_enabled(objset_t * os)1806 dmu_objset_userobjused_enabled(objset_t *os)
1807 {
1808 	return (dmu_objset_userused_enabled(os) &&
1809 	    spa_feature_is_enabled(os->os_spa, SPA_FEATURE_USEROBJ_ACCOUNTING));
1810 }
1811 
1812 boolean_t
dmu_objset_projectquota_enabled(objset_t * os)1813 dmu_objset_projectquota_enabled(objset_t *os)
1814 {
1815 	return (file_cbs[os->os_phys->os_type] != NULL &&
1816 	    DMU_PROJECTUSED_DNODE(os) != NULL &&
1817 	    spa_feature_is_enabled(os->os_spa, SPA_FEATURE_PROJECT_QUOTA));
1818 }
1819 
1820 typedef struct userquota_node {
1821 	/* must be in the first filed, see userquota_update_cache() */
1822 	char		uqn_id[20 + DMU_OBJACCT_PREFIX_LEN];
1823 	int64_t		uqn_delta;
1824 	avl_node_t	uqn_node;
1825 } userquota_node_t;
1826 
1827 typedef struct userquota_cache {
1828 	avl_tree_t uqc_user_deltas;
1829 	avl_tree_t uqc_group_deltas;
1830 	avl_tree_t uqc_project_deltas;
1831 } userquota_cache_t;
1832 
1833 static int
userquota_compare(const void * l,const void * r)1834 userquota_compare(const void *l, const void *r)
1835 {
1836 	const userquota_node_t *luqn = l;
1837 	const userquota_node_t *ruqn = r;
1838 	int rv;
1839 
1840 	/*
1841 	 * NB: can only access uqn_id because userquota_update_cache() doesn't
1842 	 * pass in an entire userquota_node_t.
1843 	 */
1844 	rv = strcmp(luqn->uqn_id, ruqn->uqn_id);
1845 
1846 	return (TREE_ISIGN(rv));
1847 }
1848 
1849 static void
do_userquota_cacheflush(objset_t * os,userquota_cache_t * cache,dmu_tx_t * tx)1850 do_userquota_cacheflush(objset_t *os, userquota_cache_t *cache, dmu_tx_t *tx)
1851 {
1852 	void *cookie;
1853 	userquota_node_t *uqn;
1854 
1855 	ASSERT(dmu_tx_is_syncing(tx));
1856 
1857 	cookie = NULL;
1858 	while ((uqn = avl_destroy_nodes(&cache->uqc_user_deltas,
1859 	    &cookie)) != NULL) {
1860 		/*
1861 		 * os_userused_lock protects against concurrent calls to
1862 		 * zap_increment_int().  It's needed because zap_increment_int()
1863 		 * is not thread-safe (i.e. not atomic).
1864 		 */
1865 		mutex_enter(&os->os_userused_lock);
1866 		VERIFY0(zap_increment(os, DMU_USERUSED_OBJECT,
1867 		    uqn->uqn_id, uqn->uqn_delta, tx));
1868 		mutex_exit(&os->os_userused_lock);
1869 		kmem_free(uqn, sizeof (*uqn));
1870 	}
1871 	avl_destroy(&cache->uqc_user_deltas);
1872 
1873 	cookie = NULL;
1874 	while ((uqn = avl_destroy_nodes(&cache->uqc_group_deltas,
1875 	    &cookie)) != NULL) {
1876 		mutex_enter(&os->os_userused_lock);
1877 		VERIFY0(zap_increment(os, DMU_GROUPUSED_OBJECT,
1878 		    uqn->uqn_id, uqn->uqn_delta, tx));
1879 		mutex_exit(&os->os_userused_lock);
1880 		kmem_free(uqn, sizeof (*uqn));
1881 	}
1882 	avl_destroy(&cache->uqc_group_deltas);
1883 
1884 	if (dmu_objset_projectquota_enabled(os)) {
1885 		cookie = NULL;
1886 		while ((uqn = avl_destroy_nodes(&cache->uqc_project_deltas,
1887 		    &cookie)) != NULL) {
1888 			mutex_enter(&os->os_userused_lock);
1889 			VERIFY0(zap_increment(os, DMU_PROJECTUSED_OBJECT,
1890 			    uqn->uqn_id, uqn->uqn_delta, tx));
1891 			mutex_exit(&os->os_userused_lock);
1892 			kmem_free(uqn, sizeof (*uqn));
1893 		}
1894 		avl_destroy(&cache->uqc_project_deltas);
1895 	}
1896 }
1897 
1898 static void
userquota_update_cache(avl_tree_t * avl,const char * id,int64_t delta)1899 userquota_update_cache(avl_tree_t *avl, const char *id, int64_t delta)
1900 {
1901 	userquota_node_t *uqn;
1902 	avl_index_t idx;
1903 
1904 	ASSERT(strlen(id) < sizeof (uqn->uqn_id));
1905 	/*
1906 	 * Use id directly for searching because uqn_id is the first field of
1907 	 * userquota_node_t and fields after uqn_id won't be accessed in
1908 	 * avl_find().
1909 	 */
1910 	uqn = avl_find(avl, (const void *)id, &idx);
1911 	if (uqn == NULL) {
1912 		uqn = kmem_zalloc(sizeof (*uqn), KM_SLEEP);
1913 		strlcpy(uqn->uqn_id, id, sizeof (uqn->uqn_id));
1914 		avl_insert(avl, uqn, idx);
1915 	}
1916 	uqn->uqn_delta += delta;
1917 }
1918 
1919 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)1920 do_userquota_update(objset_t *os, userquota_cache_t *cache, uint64_t used,
1921     uint64_t flags, uint64_t user, uint64_t group, uint64_t project,
1922     boolean_t subtract)
1923 {
1924 	if (flags & DNODE_FLAG_USERUSED_ACCOUNTED) {
1925 		int64_t delta = DNODE_MIN_SIZE + used;
1926 		char name[20];
1927 
1928 		if (subtract)
1929 			delta = -delta;
1930 
1931 		(void) snprintf(name, sizeof (name), "%llx", (longlong_t)user);
1932 		userquota_update_cache(&cache->uqc_user_deltas, name, delta);
1933 
1934 		(void) snprintf(name, sizeof (name), "%llx", (longlong_t)group);
1935 		userquota_update_cache(&cache->uqc_group_deltas, name, delta);
1936 
1937 		if (dmu_objset_projectquota_enabled(os)) {
1938 			(void) snprintf(name, sizeof (name), "%llx",
1939 			    (longlong_t)project);
1940 			userquota_update_cache(&cache->uqc_project_deltas,
1941 			    name, delta);
1942 		}
1943 	}
1944 }
1945 
1946 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)1947 do_userobjquota_update(objset_t *os, userquota_cache_t *cache, uint64_t flags,
1948     uint64_t user, uint64_t group, uint64_t project, boolean_t subtract)
1949 {
1950 	if (flags & DNODE_FLAG_USEROBJUSED_ACCOUNTED) {
1951 		char name[20 + DMU_OBJACCT_PREFIX_LEN];
1952 		int delta = subtract ? -1 : 1;
1953 
1954 		(void) snprintf(name, sizeof (name), DMU_OBJACCT_PREFIX "%llx",
1955 		    (longlong_t)user);
1956 		userquota_update_cache(&cache->uqc_user_deltas, name, delta);
1957 
1958 		(void) snprintf(name, sizeof (name), DMU_OBJACCT_PREFIX "%llx",
1959 		    (longlong_t)group);
1960 		userquota_update_cache(&cache->uqc_group_deltas, name, delta);
1961 
1962 		if (dmu_objset_projectquota_enabled(os)) {
1963 			(void) snprintf(name, sizeof (name),
1964 			    DMU_OBJACCT_PREFIX "%llx", (longlong_t)project);
1965 			userquota_update_cache(&cache->uqc_project_deltas,
1966 			    name, delta);
1967 		}
1968 	}
1969 }
1970 
1971 typedef struct userquota_updates_arg {
1972 	objset_t *uua_os;
1973 	int uua_sublist_idx;
1974 	dmu_tx_t *uua_tx;
1975 } userquota_updates_arg_t;
1976 
1977 static void
userquota_updates_task(void * arg)1978 userquota_updates_task(void *arg)
1979 {
1980 	userquota_updates_arg_t *uua = arg;
1981 	objset_t *os = uua->uua_os;
1982 	dmu_tx_t *tx = uua->uua_tx;
1983 	dnode_t *dn;
1984 	userquota_cache_t cache = { { 0 } };
1985 
1986 	multilist_sublist_t *list = multilist_sublist_lock_idx(
1987 	    &os->os_synced_dnodes, uua->uua_sublist_idx);
1988 
1989 	ASSERT(multilist_sublist_head(list) == NULL ||
1990 	    dmu_objset_userused_enabled(os));
1991 	avl_create(&cache.uqc_user_deltas, userquota_compare,
1992 	    sizeof (userquota_node_t), offsetof(userquota_node_t, uqn_node));
1993 	avl_create(&cache.uqc_group_deltas, userquota_compare,
1994 	    sizeof (userquota_node_t), offsetof(userquota_node_t, uqn_node));
1995 	if (dmu_objset_projectquota_enabled(os))
1996 		avl_create(&cache.uqc_project_deltas, userquota_compare,
1997 		    sizeof (userquota_node_t), offsetof(userquota_node_t,
1998 		    uqn_node));
1999 
2000 	while ((dn = multilist_sublist_head(list)) != NULL) {
2001 		int flags;
2002 		ASSERT(!DMU_OBJECT_IS_SPECIAL(dn->dn_object));
2003 		ASSERT(dn->dn_phys->dn_type == DMU_OT_NONE ||
2004 		    dn->dn_phys->dn_flags &
2005 		    DNODE_FLAG_USERUSED_ACCOUNTED);
2006 
2007 		flags = dn->dn_id_flags;
2008 		ASSERT(flags);
2009 		if (flags & DN_ID_OLD_EXIST)  {
2010 			do_userquota_update(os, &cache, dn->dn_oldused,
2011 			    dn->dn_oldflags, dn->dn_olduid, dn->dn_oldgid,
2012 			    dn->dn_oldprojid, B_TRUE);
2013 			do_userobjquota_update(os, &cache, dn->dn_oldflags,
2014 			    dn->dn_olduid, dn->dn_oldgid,
2015 			    dn->dn_oldprojid, B_TRUE);
2016 		}
2017 		if (flags & DN_ID_NEW_EXIST) {
2018 			do_userquota_update(os, &cache,
2019 			    DN_USED_BYTES(dn->dn_phys), dn->dn_phys->dn_flags,
2020 			    dn->dn_newuid, dn->dn_newgid,
2021 			    dn->dn_newprojid, B_FALSE);
2022 			do_userobjquota_update(os, &cache,
2023 			    dn->dn_phys->dn_flags, dn->dn_newuid, dn->dn_newgid,
2024 			    dn->dn_newprojid, B_FALSE);
2025 		}
2026 
2027 		mutex_enter(&dn->dn_mtx);
2028 		dn->dn_oldused = 0;
2029 		dn->dn_oldflags = 0;
2030 		if (dn->dn_id_flags & DN_ID_NEW_EXIST) {
2031 			dn->dn_olduid = dn->dn_newuid;
2032 			dn->dn_oldgid = dn->dn_newgid;
2033 			dn->dn_oldprojid = dn->dn_newprojid;
2034 			dn->dn_id_flags |= DN_ID_OLD_EXIST;
2035 			if (dn->dn_bonuslen == 0)
2036 				dn->dn_id_flags |= DN_ID_CHKED_SPILL;
2037 			else
2038 				dn->dn_id_flags |= DN_ID_CHKED_BONUS;
2039 		}
2040 		dn->dn_id_flags &= ~(DN_ID_NEW_EXIST);
2041 		ASSERT3U(dn->dn_dirtycnt, >, 0);
2042 		dn->dn_dirtycnt--;
2043 		mutex_exit(&dn->dn_mtx);
2044 
2045 		multilist_sublist_remove(list, dn);
2046 		dnode_rele(dn, &os->os_synced_dnodes);
2047 	}
2048 	do_userquota_cacheflush(os, &cache, tx);
2049 	multilist_sublist_unlock(list);
2050 	kmem_free(uua, sizeof (*uua));
2051 }
2052 
2053 /*
2054  * Release dnode holds from dmu_objset_sync_dnodes().  When the dnode is being
2055  * synced (i.e. we have issued the zio's for blocks in the dnode), it can't be
2056  * evicted because the block containing the dnode can't be evicted until it is
2057  * written out.  However, this hold is necessary to prevent the dnode_t from
2058  * being moved (via dnode_move()) while it's still referenced by
2059  * dbuf_dirty_record_t:dr_dnode.  And dr_dnode is needed for
2060  * dirty_lightweight_leaf-type dirty records.
2061  *
2062  * If we are doing user-object accounting, the dnode_rele() happens from
2063  * userquota_updates_task() instead.
2064  */
2065 static void
dnode_rele_task(void * arg)2066 dnode_rele_task(void *arg)
2067 {
2068 	userquota_updates_arg_t *uua = arg;
2069 	objset_t *os = uua->uua_os;
2070 
2071 	multilist_sublist_t *list = multilist_sublist_lock_idx(
2072 	    &os->os_synced_dnodes, uua->uua_sublist_idx);
2073 
2074 	dnode_t *dn;
2075 	while ((dn = multilist_sublist_head(list)) != NULL) {
2076 		mutex_enter(&dn->dn_mtx);
2077 		ASSERT3U(dn->dn_dirtycnt, >, 0);
2078 		dn->dn_dirtycnt--;
2079 		mutex_exit(&dn->dn_mtx);
2080 		multilist_sublist_remove(list, dn);
2081 		dnode_rele(dn, &os->os_synced_dnodes);
2082 	}
2083 	multilist_sublist_unlock(list);
2084 	kmem_free(uua, sizeof (*uua));
2085 }
2086 
2087 /*
2088  * Return TRUE if userquota updates are needed.
2089  */
2090 static boolean_t
dmu_objset_do_userquota_updates_prep(objset_t * os,dmu_tx_t * tx)2091 dmu_objset_do_userquota_updates_prep(objset_t *os, dmu_tx_t *tx)
2092 {
2093 	if (!dmu_objset_userused_enabled(os))
2094 		return (B_FALSE);
2095 
2096 	/*
2097 	 * If this is a raw receive just return and handle accounting
2098 	 * later when we have the keys loaded. We also don't do user
2099 	 * accounting during claiming since the datasets are not owned
2100 	 * for the duration of claiming and this txg should only be
2101 	 * used for recovery.
2102 	 */
2103 	if (os->os_encrypted && dmu_objset_is_receiving(os))
2104 		return (B_FALSE);
2105 
2106 	if (tx->tx_txg <= os->os_spa->spa_claim_max_txg)
2107 		return (B_FALSE);
2108 
2109 	/* Allocate the user/group/project used objects if necessary. */
2110 	if (DMU_USERUSED_DNODE(os)->dn_type == DMU_OT_NONE) {
2111 		VERIFY0(zap_create_claim(os,
2112 		    DMU_USERUSED_OBJECT,
2113 		    DMU_OT_USERGROUP_USED, DMU_OT_NONE, 0, tx));
2114 		VERIFY0(zap_create_claim(os,
2115 		    DMU_GROUPUSED_OBJECT,
2116 		    DMU_OT_USERGROUP_USED, DMU_OT_NONE, 0, tx));
2117 	}
2118 
2119 	if (dmu_objset_projectquota_enabled(os) &&
2120 	    DMU_PROJECTUSED_DNODE(os)->dn_type == DMU_OT_NONE) {
2121 		VERIFY0(zap_create_claim(os, DMU_PROJECTUSED_OBJECT,
2122 		    DMU_OT_USERGROUP_USED, DMU_OT_NONE, 0, tx));
2123 	}
2124 	return (B_TRUE);
2125 }
2126 
2127 /*
2128  * Dispatch taskq tasks to dp_sync_taskq to update the user accounting, and
2129  * also release the holds on the dnodes from dmu_objset_sync_dnodes().
2130  * The caller must taskq_wait(dp_sync_taskq).
2131  */
2132 void
dmu_objset_sync_done(objset_t * os,dmu_tx_t * tx)2133 dmu_objset_sync_done(objset_t *os, dmu_tx_t *tx)
2134 {
2135 	boolean_t need_userquota = dmu_objset_do_userquota_updates_prep(os, tx);
2136 
2137 	int num_sublists = multilist_get_num_sublists(&os->os_synced_dnodes);
2138 	for (int i = 0; i < num_sublists; i++) {
2139 		userquota_updates_arg_t *uua =
2140 		    kmem_alloc(sizeof (*uua), KM_SLEEP);
2141 		uua->uua_os = os;
2142 		uua->uua_sublist_idx = i;
2143 		uua->uua_tx = tx;
2144 
2145 		/*
2146 		 * If we don't need to update userquotas, use
2147 		 * dnode_rele_task() to call dnode_rele()
2148 		 */
2149 		(void) taskq_dispatch(dmu_objset_pool(os)->dp_sync_taskq,
2150 		    need_userquota ? userquota_updates_task : dnode_rele_task,
2151 		    uua, 0);
2152 		/* callback frees uua */
2153 	}
2154 }
2155 
2156 
2157 /*
2158  * Returns a pointer to data to find uid/gid from
2159  *
2160  * If a dirty record for transaction group that is syncing can't
2161  * be found then NULL is returned.  In the NULL case it is assumed
2162  * the uid/gid aren't changing.
2163  */
2164 static void *
dmu_objset_userquota_find_data(dmu_buf_impl_t * db,dmu_tx_t * tx)2165 dmu_objset_userquota_find_data(dmu_buf_impl_t *db, dmu_tx_t *tx)
2166 {
2167 	dbuf_dirty_record_t *dr;
2168 	void *data;
2169 
2170 	if (db->db_dirtycnt == 0) {
2171 		ASSERT(MUTEX_HELD(&db->db_mtx));
2172 		return (db->db.db_data);  /* Nothing is changing */
2173 	}
2174 
2175 	dr = dbuf_find_dirty_eq(db, tx->tx_txg);
2176 
2177 	if (dr == NULL) {
2178 		data = NULL;
2179 	} else {
2180 		if (dr->dr_dnode->dn_bonuslen == 0 &&
2181 		    dr->dr_dbuf->db_blkid == DMU_SPILL_BLKID)
2182 			data = dr->dt.dl.dr_data->b_data;
2183 		else
2184 			data = dr->dt.dl.dr_data;
2185 	}
2186 
2187 	return (data);
2188 }
2189 
2190 void
dmu_objset_userquota_get_ids(dnode_t * dn,boolean_t before,dmu_tx_t * tx)2191 dmu_objset_userquota_get_ids(dnode_t *dn, boolean_t before, dmu_tx_t *tx)
2192 {
2193 	objset_t *os = dn->dn_objset;
2194 	void *data = NULL;
2195 	dmu_buf_impl_t *db = NULL;
2196 	int flags = dn->dn_id_flags;
2197 	int error;
2198 	boolean_t have_spill = B_FALSE;
2199 
2200 	if (!dmu_objset_userused_enabled(dn->dn_objset))
2201 		return;
2202 
2203 	/*
2204 	 * Raw receives introduce a problem with user accounting. Raw
2205 	 * receives cannot update the user accounting info because the
2206 	 * user ids and the sizes are encrypted. To guarantee that we
2207 	 * never end up with bad user accounting, we simply disable it
2208 	 * during raw receives. We also disable this for normal receives
2209 	 * so that an incremental raw receive may be done on top of an
2210 	 * existing non-raw receive.
2211 	 */
2212 	if (os->os_encrypted && dmu_objset_is_receiving(os))
2213 		return;
2214 
2215 	if (before && (flags & (DN_ID_CHKED_BONUS|DN_ID_OLD_EXIST|
2216 	    DN_ID_CHKED_SPILL)))
2217 		return;
2218 
2219 	if (before && dn->dn_bonuslen != 0)
2220 		data = DN_BONUS(dn->dn_phys);
2221 	else if (!before && dn->dn_bonuslen != 0) {
2222 		if (dn->dn_bonus) {
2223 			db = dn->dn_bonus;
2224 			mutex_enter(&db->db_mtx);
2225 			data = dmu_objset_userquota_find_data(db, tx);
2226 		} else {
2227 			data = DN_BONUS(dn->dn_phys);
2228 		}
2229 	} else if (dn->dn_bonuslen == 0 && dn->dn_bonustype == DMU_OT_SA) {
2230 			dmu_flags_t rf = DB_RF_MUST_SUCCEED;
2231 
2232 			if (RW_WRITE_HELD(&dn->dn_struct_rwlock))
2233 				rf |= DB_RF_HAVESTRUCT;
2234 			error = dmu_spill_hold_by_dnode(dn, rf,
2235 			    FTAG, (dmu_buf_t **)&db);
2236 			ASSERT0(error);
2237 			mutex_enter(&db->db_mtx);
2238 			data = (before) ? db->db.db_data :
2239 			    dmu_objset_userquota_find_data(db, tx);
2240 			have_spill = B_TRUE;
2241 	} else {
2242 		mutex_enter(&dn->dn_mtx);
2243 		dn->dn_id_flags |= DN_ID_CHKED_BONUS;
2244 		mutex_exit(&dn->dn_mtx);
2245 		return;
2246 	}
2247 
2248 	/*
2249 	 * Must always call the callback in case the object
2250 	 * type has changed and that type isn't an object type to track
2251 	 */
2252 	zfs_file_info_t zfi;
2253 	error = file_cbs[os->os_phys->os_type](dn->dn_bonustype, data, &zfi);
2254 
2255 	if (before) {
2256 		ASSERT(data);
2257 		dn->dn_olduid = zfi.zfi_user;
2258 		dn->dn_oldgid = zfi.zfi_group;
2259 		dn->dn_oldprojid = zfi.zfi_project;
2260 	} else if (data) {
2261 		dn->dn_newuid = zfi.zfi_user;
2262 		dn->dn_newgid = zfi.zfi_group;
2263 		dn->dn_newprojid = zfi.zfi_project;
2264 	}
2265 
2266 	/*
2267 	 * Preserve existing uid/gid when the callback can't determine
2268 	 * what the new uid/gid are and the callback returned EEXIST.
2269 	 * The EEXIST error tells us to just use the existing uid/gid.
2270 	 * If we don't know what the old values are then just assign
2271 	 * them to 0, since that is a new file  being created.
2272 	 */
2273 	if (!before && data == NULL && error == EEXIST) {
2274 		if (flags & DN_ID_OLD_EXIST) {
2275 			dn->dn_newuid = dn->dn_olduid;
2276 			dn->dn_newgid = dn->dn_oldgid;
2277 			dn->dn_newprojid = dn->dn_oldprojid;
2278 		} else {
2279 			dn->dn_newuid = 0;
2280 			dn->dn_newgid = 0;
2281 			dn->dn_newprojid = ZFS_DEFAULT_PROJID;
2282 		}
2283 		error = 0;
2284 	}
2285 
2286 	if (db)
2287 		mutex_exit(&db->db_mtx);
2288 
2289 	mutex_enter(&dn->dn_mtx);
2290 	if (error == 0 && before)
2291 		dn->dn_id_flags |= DN_ID_OLD_EXIST;
2292 	if (error == 0 && !before)
2293 		dn->dn_id_flags |= DN_ID_NEW_EXIST;
2294 
2295 	if (have_spill) {
2296 		dn->dn_id_flags |= DN_ID_CHKED_SPILL;
2297 	} else {
2298 		dn->dn_id_flags |= DN_ID_CHKED_BONUS;
2299 	}
2300 	mutex_exit(&dn->dn_mtx);
2301 	if (have_spill)
2302 		dmu_buf_rele((dmu_buf_t *)db, FTAG);
2303 }
2304 
2305 boolean_t
dmu_objset_userspace_present(objset_t * os)2306 dmu_objset_userspace_present(objset_t *os)
2307 {
2308 	return (os->os_phys->os_flags &
2309 	    OBJSET_FLAG_USERACCOUNTING_COMPLETE);
2310 }
2311 
2312 boolean_t
dmu_objset_userobjspace_present(objset_t * os)2313 dmu_objset_userobjspace_present(objset_t *os)
2314 {
2315 	return (os->os_phys->os_flags &
2316 	    OBJSET_FLAG_USEROBJACCOUNTING_COMPLETE);
2317 }
2318 
2319 boolean_t
dmu_objset_projectquota_present(objset_t * os)2320 dmu_objset_projectquota_present(objset_t *os)
2321 {
2322 	return (os->os_phys->os_flags &
2323 	    OBJSET_FLAG_PROJECTQUOTA_COMPLETE);
2324 }
2325 
2326 static int
dmu_objset_space_upgrade(objset_t * os)2327 dmu_objset_space_upgrade(objset_t *os)
2328 {
2329 	uint64_t obj;
2330 	int err = 0;
2331 
2332 	/*
2333 	 * We simply need to mark every object dirty, so that it will be
2334 	 * synced out and now accounted.  If this is called
2335 	 * concurrently, or if we already did some work before crashing,
2336 	 * that's fine, since we track each object's accounted state
2337 	 * independently.
2338 	 */
2339 
2340 	for (obj = 0; err == 0; err = dmu_object_next(os, &obj, FALSE, 0)) {
2341 		dmu_tx_t *tx;
2342 		dmu_buf_t *db;
2343 		int objerr;
2344 
2345 		mutex_enter(&os->os_upgrade_lock);
2346 		if (os->os_upgrade_exit)
2347 			err = SET_ERROR(EINTR);
2348 		mutex_exit(&os->os_upgrade_lock);
2349 		if (err != 0)
2350 			return (err);
2351 
2352 		if (issig())
2353 			return (SET_ERROR(EINTR));
2354 
2355 		objerr = dmu_bonus_hold(os, obj, FTAG, &db);
2356 		if (objerr != 0)
2357 			continue;
2358 		tx = dmu_tx_create(os);
2359 		dmu_tx_hold_bonus(tx, obj);
2360 		objerr = dmu_tx_assign(tx, DMU_TX_WAIT);
2361 		if (objerr != 0) {
2362 			dmu_buf_rele(db, FTAG);
2363 			dmu_tx_abort(tx);
2364 			continue;
2365 		}
2366 		dmu_buf_will_dirty(db, tx);
2367 		dmu_buf_rele(db, FTAG);
2368 		dmu_tx_commit(tx);
2369 	}
2370 	return (0);
2371 }
2372 
2373 static int
dmu_objset_userspace_upgrade_cb(objset_t * os)2374 dmu_objset_userspace_upgrade_cb(objset_t *os)
2375 {
2376 	int err = 0;
2377 
2378 	if (dmu_objset_userspace_present(os))
2379 		return (0);
2380 	if (dmu_objset_is_snapshot(os))
2381 		return (SET_ERROR(EINVAL));
2382 	if (!dmu_objset_userused_enabled(os))
2383 		return (SET_ERROR(ENOTSUP));
2384 
2385 	err = dmu_objset_space_upgrade(os);
2386 	if (err)
2387 		return (err);
2388 
2389 	os->os_flags |= OBJSET_FLAG_USERACCOUNTING_COMPLETE;
2390 	txg_wait_synced(dmu_objset_pool(os), 0);
2391 	return (0);
2392 }
2393 
2394 void
dmu_objset_userspace_upgrade(objset_t * os)2395 dmu_objset_userspace_upgrade(objset_t *os)
2396 {
2397 	dmu_objset_upgrade(os, dmu_objset_userspace_upgrade_cb);
2398 }
2399 
2400 static int
dmu_objset_id_quota_upgrade_cb(objset_t * os)2401 dmu_objset_id_quota_upgrade_cb(objset_t *os)
2402 {
2403 	int err = 0;
2404 
2405 	if (dmu_objset_userobjspace_present(os) &&
2406 	    dmu_objset_projectquota_present(os))
2407 		return (0);
2408 	if (dmu_objset_is_snapshot(os))
2409 		return (SET_ERROR(EINVAL));
2410 	if (!dmu_objset_userused_enabled(os))
2411 		return (SET_ERROR(ENOTSUP));
2412 	if (!dmu_objset_projectquota_enabled(os) &&
2413 	    dmu_objset_userobjspace_present(os))
2414 		return (SET_ERROR(ENOTSUP));
2415 
2416 	if (dmu_objset_userobjused_enabled(os))
2417 		dmu_objset_ds(os)->ds_feature_activation[
2418 		    SPA_FEATURE_USEROBJ_ACCOUNTING] = (void *)B_TRUE;
2419 	if (dmu_objset_projectquota_enabled(os))
2420 		dmu_objset_ds(os)->ds_feature_activation[
2421 		    SPA_FEATURE_PROJECT_QUOTA] = (void *)B_TRUE;
2422 
2423 	err = dmu_objset_space_upgrade(os);
2424 	if (err)
2425 		return (err);
2426 
2427 	os->os_flags |= OBJSET_FLAG_USERACCOUNTING_COMPLETE;
2428 	if (dmu_objset_userobjused_enabled(os))
2429 		os->os_flags |= OBJSET_FLAG_USEROBJACCOUNTING_COMPLETE;
2430 	if (dmu_objset_projectquota_enabled(os))
2431 		os->os_flags |= OBJSET_FLAG_PROJECTQUOTA_COMPLETE;
2432 
2433 	txg_wait_synced(dmu_objset_pool(os), 0);
2434 	return (0);
2435 }
2436 
2437 void
dmu_objset_id_quota_upgrade(objset_t * os)2438 dmu_objset_id_quota_upgrade(objset_t *os)
2439 {
2440 	dmu_objset_upgrade(os, dmu_objset_id_quota_upgrade_cb);
2441 }
2442 
2443 boolean_t
dmu_objset_userobjspace_upgradable(objset_t * os)2444 dmu_objset_userobjspace_upgradable(objset_t *os)
2445 {
2446 	return (dmu_objset_type(os) == DMU_OST_ZFS &&
2447 	    !dmu_objset_is_snapshot(os) &&
2448 	    dmu_objset_userobjused_enabled(os) &&
2449 	    !dmu_objset_userobjspace_present(os) &&
2450 	    spa_writeable(dmu_objset_spa(os)));
2451 }
2452 
2453 boolean_t
dmu_objset_projectquota_upgradable(objset_t * os)2454 dmu_objset_projectquota_upgradable(objset_t *os)
2455 {
2456 	return (dmu_objset_type(os) == DMU_OST_ZFS &&
2457 	    !dmu_objset_is_snapshot(os) &&
2458 	    dmu_objset_projectquota_enabled(os) &&
2459 	    !dmu_objset_projectquota_present(os) &&
2460 	    spa_writeable(dmu_objset_spa(os)));
2461 }
2462 
2463 void
dmu_objset_space(objset_t * os,uint64_t * refdbytesp,uint64_t * availbytesp,uint64_t * usedobjsp,uint64_t * availobjsp)2464 dmu_objset_space(objset_t *os, uint64_t *refdbytesp, uint64_t *availbytesp,
2465     uint64_t *usedobjsp, uint64_t *availobjsp)
2466 {
2467 	dsl_dataset_space(os->os_dsl_dataset, refdbytesp, availbytesp,
2468 	    usedobjsp, availobjsp);
2469 }
2470 
2471 uint64_t
dmu_objset_fsid_guid(objset_t * os)2472 dmu_objset_fsid_guid(objset_t *os)
2473 {
2474 	return (dsl_dataset_fsid_guid(os->os_dsl_dataset));
2475 }
2476 
2477 void
dmu_objset_fast_stat(objset_t * os,dmu_objset_stats_t * stat)2478 dmu_objset_fast_stat(objset_t *os, dmu_objset_stats_t *stat)
2479 {
2480 	stat->dds_type = os->os_phys->os_type;
2481 	if (os->os_dsl_dataset)
2482 		dsl_dataset_fast_stat(os->os_dsl_dataset, stat);
2483 }
2484 
2485 void
dmu_objset_stats(objset_t * os,nvlist_t * nv)2486 dmu_objset_stats(objset_t *os, nvlist_t *nv)
2487 {
2488 	ASSERT(os->os_dsl_dataset ||
2489 	    os->os_phys->os_type == DMU_OST_META);
2490 
2491 	if (os->os_dsl_dataset != NULL)
2492 		dsl_dataset_stats(os->os_dsl_dataset, nv);
2493 
2494 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_TYPE,
2495 	    os->os_phys->os_type);
2496 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USERACCOUNTING,
2497 	    dmu_objset_userspace_present(os));
2498 }
2499 
2500 int
dmu_objset_is_snapshot(objset_t * os)2501 dmu_objset_is_snapshot(objset_t *os)
2502 {
2503 	if (os->os_dsl_dataset != NULL)
2504 		return (os->os_dsl_dataset->ds_is_snapshot);
2505 	else
2506 		return (B_FALSE);
2507 }
2508 
2509 int
dmu_snapshot_realname(objset_t * os,const char * name,char * real,int maxlen,boolean_t * conflict)2510 dmu_snapshot_realname(objset_t *os, const char *name, char *real, int maxlen,
2511     boolean_t *conflict)
2512 {
2513 	dsl_dataset_t *ds = os->os_dsl_dataset;
2514 	uint64_t ignored;
2515 
2516 	if (dsl_dataset_phys(ds)->ds_snapnames_zapobj == 0)
2517 		return (SET_ERROR(ENOENT));
2518 
2519 	return (zap_lookup_norm(ds->ds_dir->dd_pool->dp_meta_objset,
2520 	    dsl_dataset_phys(ds)->ds_snapnames_zapobj, name, 8, 1, &ignored,
2521 	    MT_NORMALIZE, real, maxlen, conflict));
2522 }
2523 
2524 int
dmu_snapshot_list_next(objset_t * os,int namelen,char * name,uint64_t * idp,uint64_t * offp,boolean_t * case_conflict)2525 dmu_snapshot_list_next(objset_t *os, int namelen, char *name,
2526     uint64_t *idp, uint64_t *offp, boolean_t *case_conflict)
2527 {
2528 	dsl_dataset_t *ds = os->os_dsl_dataset;
2529 	zap_cursor_t cursor;
2530 	zap_attribute_t *attr;
2531 
2532 	ASSERT(dsl_pool_config_held(dmu_objset_pool(os)));
2533 
2534 	if (dsl_dataset_phys(ds)->ds_snapnames_zapobj == 0)
2535 		return (SET_ERROR(ENOENT));
2536 
2537 	attr = zap_attribute_alloc();
2538 	zap_cursor_init_serialized(&cursor,
2539 	    ds->ds_dir->dd_pool->dp_meta_objset,
2540 	    dsl_dataset_phys(ds)->ds_snapnames_zapobj, *offp);
2541 
2542 	if (zap_cursor_retrieve(&cursor, attr) != 0) {
2543 		zap_cursor_fini(&cursor);
2544 		zap_attribute_free(attr);
2545 		return (SET_ERROR(ENOENT));
2546 	}
2547 
2548 	if (strlen(attr->za_name) + 1 > namelen) {
2549 		zap_cursor_fini(&cursor);
2550 		zap_attribute_free(attr);
2551 		return (SET_ERROR(ENAMETOOLONG));
2552 	}
2553 
2554 	(void) strlcpy(name, attr->za_name, namelen);
2555 	if (idp)
2556 		*idp = attr->za_first_integer;
2557 	if (case_conflict)
2558 		*case_conflict = attr->za_normalization_conflict;
2559 	zap_cursor_advance(&cursor);
2560 	*offp = zap_cursor_serialize(&cursor);
2561 	zap_cursor_fini(&cursor);
2562 	zap_attribute_free(attr);
2563 
2564 	return (0);
2565 }
2566 
2567 int
dmu_snapshot_lookup(objset_t * os,const char * name,uint64_t * value)2568 dmu_snapshot_lookup(objset_t *os, const char *name, uint64_t *value)
2569 {
2570 	return (dsl_dataset_snap_lookup(os->os_dsl_dataset, name, value));
2571 }
2572 
2573 int
dmu_dir_list_next(objset_t * os,int namelen,char * name,uint64_t * idp,uint64_t * offp)2574 dmu_dir_list_next(objset_t *os, int namelen, char *name,
2575     uint64_t *idp, uint64_t *offp)
2576 {
2577 	dsl_dir_t *dd = os->os_dsl_dataset->ds_dir;
2578 	zap_cursor_t cursor;
2579 	zap_attribute_t *attr;
2580 
2581 	/* there is no next dir on a snapshot! */
2582 	if (os->os_dsl_dataset->ds_object !=
2583 	    dsl_dir_phys(dd)->dd_head_dataset_obj)
2584 		return (SET_ERROR(ENOENT));
2585 
2586 	attr = zap_attribute_alloc();
2587 	zap_cursor_init_serialized(&cursor,
2588 	    dd->dd_pool->dp_meta_objset,
2589 	    dsl_dir_phys(dd)->dd_child_dir_zapobj, *offp);
2590 
2591 	if (zap_cursor_retrieve(&cursor, attr) != 0) {
2592 		zap_cursor_fini(&cursor);
2593 		zap_attribute_free(attr);
2594 		return (SET_ERROR(ENOENT));
2595 	}
2596 
2597 	if (strlen(attr->za_name) + 1 > namelen) {
2598 		zap_cursor_fini(&cursor);
2599 		zap_attribute_free(attr);
2600 		return (SET_ERROR(ENAMETOOLONG));
2601 	}
2602 
2603 	(void) strlcpy(name, attr->za_name, namelen);
2604 	if (idp)
2605 		*idp = attr->za_first_integer;
2606 	zap_cursor_advance(&cursor);
2607 	*offp = zap_cursor_serialize(&cursor);
2608 	zap_cursor_fini(&cursor);
2609 	zap_attribute_free(attr);
2610 
2611 	return (0);
2612 }
2613 
2614 typedef struct dmu_objset_find_ctx {
2615 	taskq_t		*dc_tq;
2616 	dsl_pool_t	*dc_dp;
2617 	uint64_t	dc_ddobj;
2618 	char		*dc_ddname; /* last component of ddobj's name */
2619 	int		(*dc_func)(dsl_pool_t *, dsl_dataset_t *, void *);
2620 	void		*dc_arg;
2621 	int		dc_flags;
2622 	kmutex_t	*dc_error_lock;
2623 	int		*dc_error;
2624 } dmu_objset_find_ctx_t;
2625 
2626 static void
dmu_objset_find_dp_impl(dmu_objset_find_ctx_t * dcp)2627 dmu_objset_find_dp_impl(dmu_objset_find_ctx_t *dcp)
2628 {
2629 	dsl_pool_t *dp = dcp->dc_dp;
2630 	dsl_dir_t *dd;
2631 	dsl_dataset_t *ds;
2632 	zap_cursor_t zc;
2633 	zap_attribute_t *attr;
2634 	uint64_t thisobj;
2635 	int err = 0;
2636 
2637 	/* don't process if there already was an error */
2638 	if (*dcp->dc_error != 0)
2639 		goto out;
2640 
2641 	/*
2642 	 * Note: passing the name (dc_ddname) here is optional, but it
2643 	 * improves performance because we don't need to call
2644 	 * zap_value_search() to determine the name.
2645 	 */
2646 	err = dsl_dir_hold_obj(dp, dcp->dc_ddobj, dcp->dc_ddname, FTAG, &dd);
2647 	if (err != 0)
2648 		goto out;
2649 
2650 	/* Don't visit hidden ($MOS & $ORIGIN) objsets. */
2651 	if (dd->dd_myname[0] == '$') {
2652 		dsl_dir_rele(dd, FTAG);
2653 		goto out;
2654 	}
2655 
2656 	thisobj = dsl_dir_phys(dd)->dd_head_dataset_obj;
2657 	attr = zap_attribute_alloc();
2658 
2659 	/*
2660 	 * Iterate over all children.
2661 	 */
2662 	if (dcp->dc_flags & DS_FIND_CHILDREN) {
2663 		for (zap_cursor_init(&zc, dp->dp_meta_objset,
2664 		    dsl_dir_phys(dd)->dd_child_dir_zapobj);
2665 		    zap_cursor_retrieve(&zc, attr) == 0;
2666 		    (void) zap_cursor_advance(&zc)) {
2667 			ASSERT3U(attr->za_integer_length, ==,
2668 			    sizeof (uint64_t));
2669 			ASSERT3U(attr->za_num_integers, ==, 1);
2670 
2671 			dmu_objset_find_ctx_t *child_dcp =
2672 			    kmem_alloc(sizeof (*child_dcp), KM_SLEEP);
2673 			*child_dcp = *dcp;
2674 			child_dcp->dc_ddobj = attr->za_first_integer;
2675 			child_dcp->dc_ddname = spa_strdup(attr->za_name);
2676 			if (dcp->dc_tq != NULL)
2677 				(void) taskq_dispatch(dcp->dc_tq,
2678 				    dmu_objset_find_dp_cb, child_dcp, TQ_SLEEP);
2679 			else
2680 				dmu_objset_find_dp_impl(child_dcp);
2681 		}
2682 		zap_cursor_fini(&zc);
2683 	}
2684 
2685 	/*
2686 	 * Iterate over all snapshots.
2687 	 */
2688 	if (dcp->dc_flags & DS_FIND_SNAPSHOTS) {
2689 		dsl_dataset_t *ds;
2690 		err = dsl_dataset_hold_obj(dp, thisobj, FTAG, &ds);
2691 
2692 		if (err == 0) {
2693 			uint64_t snapobj;
2694 
2695 			snapobj = dsl_dataset_phys(ds)->ds_snapnames_zapobj;
2696 			dsl_dataset_rele(ds, FTAG);
2697 
2698 			for (zap_cursor_init(&zc, dp->dp_meta_objset, snapobj);
2699 			    zap_cursor_retrieve(&zc, attr) == 0;
2700 			    (void) zap_cursor_advance(&zc)) {
2701 				ASSERT3U(attr->za_integer_length, ==,
2702 				    sizeof (uint64_t));
2703 				ASSERT3U(attr->za_num_integers, ==, 1);
2704 
2705 				err = dsl_dataset_hold_obj(dp,
2706 				    attr->za_first_integer, FTAG, &ds);
2707 				if (err != 0)
2708 					break;
2709 				err = dcp->dc_func(dp, ds, dcp->dc_arg);
2710 				dsl_dataset_rele(ds, FTAG);
2711 				if (err != 0)
2712 					break;
2713 			}
2714 			zap_cursor_fini(&zc);
2715 		}
2716 	}
2717 
2718 	zap_attribute_free(attr);
2719 
2720 	if (err != 0) {
2721 		dsl_dir_rele(dd, FTAG);
2722 		goto out;
2723 	}
2724 
2725 	/*
2726 	 * Apply to self.
2727 	 */
2728 	err = dsl_dataset_hold_obj(dp, thisobj, FTAG, &ds);
2729 
2730 	/*
2731 	 * Note: we hold the dir while calling dsl_dataset_hold_obj() so
2732 	 * that the dir will remain cached, and we won't have to re-instantiate
2733 	 * it (which could be expensive due to finding its name via
2734 	 * zap_value_search()).
2735 	 */
2736 	dsl_dir_rele(dd, FTAG);
2737 	if (err != 0)
2738 		goto out;
2739 	err = dcp->dc_func(dp, ds, dcp->dc_arg);
2740 	dsl_dataset_rele(ds, FTAG);
2741 
2742 out:
2743 	if (err != 0) {
2744 		mutex_enter(dcp->dc_error_lock);
2745 		/* only keep first error */
2746 		if (*dcp->dc_error == 0)
2747 			*dcp->dc_error = err;
2748 		mutex_exit(dcp->dc_error_lock);
2749 	}
2750 
2751 	if (dcp->dc_ddname != NULL)
2752 		spa_strfree(dcp->dc_ddname);
2753 	kmem_free(dcp, sizeof (*dcp));
2754 }
2755 
2756 static void
dmu_objset_find_dp_cb(void * arg)2757 dmu_objset_find_dp_cb(void *arg)
2758 {
2759 	dmu_objset_find_ctx_t *dcp = arg;
2760 	dsl_pool_t *dp = dcp->dc_dp;
2761 
2762 	/*
2763 	 * We need to get a pool_config_lock here, as there are several
2764 	 * assert(pool_config_held) down the stack. Getting a lock via
2765 	 * dsl_pool_config_enter is risky, as it might be stalled by a
2766 	 * pending writer. This would deadlock, as the write lock can
2767 	 * only be granted when our parent thread gives up the lock.
2768 	 * The _prio interface gives us priority over a pending writer.
2769 	 */
2770 	dsl_pool_config_enter_prio(dp, FTAG);
2771 
2772 	dmu_objset_find_dp_impl(dcp);
2773 
2774 	dsl_pool_config_exit(dp, FTAG);
2775 }
2776 
2777 /*
2778  * Find objsets under and including ddobj, call func(ds) on each.
2779  * The order for the enumeration is completely undefined.
2780  * func is called with dsl_pool_config held.
2781  */
2782 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)2783 dmu_objset_find_dp(dsl_pool_t *dp, uint64_t ddobj,
2784     int func(dsl_pool_t *, dsl_dataset_t *, void *), void *arg, int flags)
2785 {
2786 	int error = 0;
2787 	taskq_t *tq = NULL;
2788 	int ntasks;
2789 	dmu_objset_find_ctx_t *dcp;
2790 	kmutex_t err_lock;
2791 
2792 	mutex_init(&err_lock, NULL, MUTEX_DEFAULT, NULL);
2793 	dcp = kmem_alloc(sizeof (*dcp), KM_SLEEP);
2794 	dcp->dc_tq = NULL;
2795 	dcp->dc_dp = dp;
2796 	dcp->dc_ddobj = ddobj;
2797 	dcp->dc_ddname = NULL;
2798 	dcp->dc_func = func;
2799 	dcp->dc_arg = arg;
2800 	dcp->dc_flags = flags;
2801 	dcp->dc_error_lock = &err_lock;
2802 	dcp->dc_error = &error;
2803 
2804 	if ((flags & DS_FIND_SERIALIZE) || dsl_pool_config_held_writer(dp)) {
2805 		/*
2806 		 * In case a write lock is held we can't make use of
2807 		 * parallelism, as down the stack of the worker threads
2808 		 * the lock is asserted via dsl_pool_config_held.
2809 		 * In case of a read lock this is solved by getting a read
2810 		 * lock in each worker thread, which isn't possible in case
2811 		 * of a writer lock. So we fall back to the synchronous path
2812 		 * here.
2813 		 * In the future it might be possible to get some magic into
2814 		 * dsl_pool_config_held in a way that it returns true for
2815 		 * the worker threads so that a single lock held from this
2816 		 * thread suffices. For now, stay single threaded.
2817 		 */
2818 		dmu_objset_find_dp_impl(dcp);
2819 		mutex_destroy(&err_lock);
2820 
2821 		return (error);
2822 	}
2823 
2824 	ntasks = dmu_find_threads;
2825 	if (ntasks == 0)
2826 		ntasks = vdev_count_leaves(dp->dp_spa) * 4;
2827 	tq = taskq_create("dmu_objset_find", ntasks, maxclsyspri, ntasks,
2828 	    INT_MAX, 0);
2829 	if (tq == NULL) {
2830 		kmem_free(dcp, sizeof (*dcp));
2831 		mutex_destroy(&err_lock);
2832 
2833 		return (SET_ERROR(ENOMEM));
2834 	}
2835 	dcp->dc_tq = tq;
2836 
2837 	/* dcp will be freed by task */
2838 	(void) taskq_dispatch(tq, dmu_objset_find_dp_cb, dcp, TQ_SLEEP);
2839 
2840 	/*
2841 	 * PORTING: this code relies on the property of taskq_wait to wait
2842 	 * until no more tasks are queued and no more tasks are active. As
2843 	 * we always queue new tasks from within other tasks, task_wait
2844 	 * reliably waits for the full recursion to finish, even though we
2845 	 * enqueue new tasks after taskq_wait has been called.
2846 	 * On platforms other than illumos, taskq_wait may not have this
2847 	 * property.
2848 	 */
2849 	taskq_wait(tq);
2850 	taskq_destroy(tq);
2851 	mutex_destroy(&err_lock);
2852 
2853 	return (error);
2854 }
2855 
2856 /*
2857  * Find all objsets under name, and for each, call 'func(child_name, arg)'.
2858  * The dp_config_rwlock must not be held when this is called, and it
2859  * will not be held when the callback is called.
2860  * Therefore this function should only be used when the pool is not changing
2861  * (e.g. in syncing context), or the callback can deal with the possible races.
2862  */
2863 static int
dmu_objset_find_impl(spa_t * spa,const char * name,int func (const char *,void *),void * arg,int flags)2864 dmu_objset_find_impl(spa_t *spa, const char *name,
2865     int func(const char *, void *), void *arg, int flags)
2866 {
2867 	dsl_dir_t *dd;
2868 	dsl_pool_t *dp = spa_get_dsl(spa);
2869 	dsl_dataset_t *ds;
2870 	zap_cursor_t zc;
2871 	zap_attribute_t *attr;
2872 	char *child;
2873 	uint64_t thisobj;
2874 	int err;
2875 
2876 	dsl_pool_config_enter(dp, FTAG);
2877 
2878 	err = dsl_dir_hold(dp, name, FTAG, &dd, NULL);
2879 	if (err != 0) {
2880 		dsl_pool_config_exit(dp, FTAG);
2881 		return (err);
2882 	}
2883 
2884 	/* Don't visit hidden ($MOS & $ORIGIN) objsets. */
2885 	if (dd->dd_myname[0] == '$') {
2886 		dsl_dir_rele(dd, FTAG);
2887 		dsl_pool_config_exit(dp, FTAG);
2888 		return (0);
2889 	}
2890 
2891 	thisobj = dsl_dir_phys(dd)->dd_head_dataset_obj;
2892 	attr = zap_attribute_alloc();
2893 
2894 	/*
2895 	 * Iterate over all children.
2896 	 */
2897 	if (flags & DS_FIND_CHILDREN) {
2898 		for (zap_cursor_init(&zc, dp->dp_meta_objset,
2899 		    dsl_dir_phys(dd)->dd_child_dir_zapobj);
2900 		    zap_cursor_retrieve(&zc, attr) == 0;
2901 		    (void) zap_cursor_advance(&zc)) {
2902 			ASSERT3U(attr->za_integer_length, ==,
2903 			    sizeof (uint64_t));
2904 			ASSERT3U(attr->za_num_integers, ==, 1);
2905 
2906 			child = kmem_asprintf("%s/%s", name, attr->za_name);
2907 			dsl_pool_config_exit(dp, FTAG);
2908 			err = dmu_objset_find_impl(spa, child,
2909 			    func, arg, flags);
2910 			dsl_pool_config_enter(dp, FTAG);
2911 			kmem_strfree(child);
2912 			if (err != 0)
2913 				break;
2914 		}
2915 		zap_cursor_fini(&zc);
2916 
2917 		if (err != 0) {
2918 			dsl_dir_rele(dd, FTAG);
2919 			dsl_pool_config_exit(dp, FTAG);
2920 			zap_attribute_free(attr);
2921 			return (err);
2922 		}
2923 	}
2924 
2925 	/*
2926 	 * Iterate over all snapshots.
2927 	 */
2928 	if (flags & DS_FIND_SNAPSHOTS) {
2929 		err = dsl_dataset_hold_obj(dp, thisobj, FTAG, &ds);
2930 
2931 		if (err == 0) {
2932 			uint64_t snapobj;
2933 
2934 			snapobj = dsl_dataset_phys(ds)->ds_snapnames_zapobj;
2935 			dsl_dataset_rele(ds, FTAG);
2936 
2937 			for (zap_cursor_init(&zc, dp->dp_meta_objset, snapobj);
2938 			    zap_cursor_retrieve(&zc, attr) == 0;
2939 			    (void) zap_cursor_advance(&zc)) {
2940 				ASSERT3U(attr->za_integer_length, ==,
2941 				    sizeof (uint64_t));
2942 				ASSERT3U(attr->za_num_integers, ==, 1);
2943 
2944 				child = kmem_asprintf("%s@%s",
2945 				    name, attr->za_name);
2946 				dsl_pool_config_exit(dp, FTAG);
2947 				err = func(child, arg);
2948 				dsl_pool_config_enter(dp, FTAG);
2949 				kmem_strfree(child);
2950 				if (err != 0)
2951 					break;
2952 			}
2953 			zap_cursor_fini(&zc);
2954 		}
2955 	}
2956 
2957 	dsl_dir_rele(dd, FTAG);
2958 	zap_attribute_free(attr);
2959 	dsl_pool_config_exit(dp, FTAG);
2960 
2961 	if (err != 0)
2962 		return (err);
2963 
2964 	/* Apply to self. */
2965 	return (func(name, arg));
2966 }
2967 
2968 /*
2969  * See comment above dmu_objset_find_impl().
2970  */
2971 int
dmu_objset_find(const char * name,int func (const char *,void *),void * arg,int flags)2972 dmu_objset_find(const char *name, int func(const char *, void *), void *arg,
2973     int flags)
2974 {
2975 	spa_t *spa;
2976 	int error;
2977 
2978 	error = spa_open(name, &spa, FTAG);
2979 	if (error != 0)
2980 		return (error);
2981 	error = dmu_objset_find_impl(spa, name, func, arg, flags);
2982 	spa_close(spa, FTAG);
2983 	return (error);
2984 }
2985 
2986 boolean_t
dmu_objset_incompatible_encryption_version(objset_t * os)2987 dmu_objset_incompatible_encryption_version(objset_t *os)
2988 {
2989 	return (dsl_dir_incompatible_encryption_version(
2990 	    os->os_dsl_dataset->ds_dir));
2991 }
2992 
2993 void
dmu_objset_set_user(objset_t * os,void * user_ptr)2994 dmu_objset_set_user(objset_t *os, void *user_ptr)
2995 {
2996 	ASSERT(MUTEX_HELD(&os->os_user_ptr_lock));
2997 	os->os_user_ptr = user_ptr;
2998 }
2999 
3000 void *
dmu_objset_get_user(objset_t * os)3001 dmu_objset_get_user(objset_t *os)
3002 {
3003 	ASSERT(MUTEX_HELD(&os->os_user_ptr_lock));
3004 	return (os->os_user_ptr);
3005 }
3006 
3007 /*
3008  * Determine name of filesystem, given name of snapshot.
3009  * buf must be at least ZFS_MAX_DATASET_NAME_LEN bytes
3010  */
3011 int
dmu_fsname(const char * snapname,char * buf)3012 dmu_fsname(const char *snapname, char *buf)
3013 {
3014 	char *atp = strchr(snapname, '@');
3015 	if (atp == NULL)
3016 		return (SET_ERROR(EINVAL));
3017 	if (atp - snapname >= ZFS_MAX_DATASET_NAME_LEN)
3018 		return (SET_ERROR(ENAMETOOLONG));
3019 	(void) strlcpy(buf, snapname, atp - snapname + 1);
3020 	return (0);
3021 }
3022 
3023 /*
3024  * Call when we think we're going to write/free space in open context
3025  * to track the amount of dirty data in the open txg, which is also the
3026  * amount of memory that can not be evicted until this txg syncs.
3027  *
3028  * Note that there are two conditions where this can be called from
3029  * syncing context:
3030  *
3031  * [1] When we just created the dataset, in which case we go on with
3032  *     updating any accounting of dirty data as usual.
3033  * [2] When we are dirtying MOS data, in which case we only update the
3034  *     pool's accounting of dirty data.
3035  */
3036 void
dmu_objset_willuse_space(objset_t * os,int64_t space,dmu_tx_t * tx)3037 dmu_objset_willuse_space(objset_t *os, int64_t space, dmu_tx_t *tx)
3038 {
3039 	dsl_dataset_t *ds = os->os_dsl_dataset;
3040 	int64_t aspace = spa_get_worst_case_asize(os->os_spa, space);
3041 
3042 	if (ds != NULL) {
3043 		dsl_dir_willuse_space(ds->ds_dir, aspace, tx);
3044 	}
3045 
3046 	dsl_pool_dirty_space(dmu_tx_pool(tx), space, tx);
3047 }
3048 
3049 #if defined(_KERNEL)
3050 EXPORT_SYMBOL(dmu_objset_zil);
3051 EXPORT_SYMBOL(dmu_objset_pool);
3052 EXPORT_SYMBOL(dmu_objset_ds);
3053 EXPORT_SYMBOL(dmu_objset_type);
3054 EXPORT_SYMBOL(dmu_objset_name);
3055 EXPORT_SYMBOL(dmu_objset_hold);
3056 EXPORT_SYMBOL(dmu_objset_hold_flags);
3057 EXPORT_SYMBOL(dmu_objset_own);
3058 EXPORT_SYMBOL(dmu_objset_rele);
3059 EXPORT_SYMBOL(dmu_objset_rele_flags);
3060 EXPORT_SYMBOL(dmu_objset_disown);
3061 EXPORT_SYMBOL(dmu_objset_from_ds);
3062 EXPORT_SYMBOL(dmu_objset_create);
3063 EXPORT_SYMBOL(dmu_objset_stats);
3064 EXPORT_SYMBOL(dmu_objset_fast_stat);
3065 EXPORT_SYMBOL(dmu_objset_spa);
3066 EXPORT_SYMBOL(dmu_objset_space);
3067 EXPORT_SYMBOL(dmu_objset_fsid_guid);
3068 EXPORT_SYMBOL(dmu_objset_find);
3069 EXPORT_SYMBOL(dmu_objset_byteswap);
3070 EXPORT_SYMBOL(dmu_objset_evict_dbufs);
3071 EXPORT_SYMBOL(dmu_objset_snap_cmtime);
3072 EXPORT_SYMBOL(dmu_objset_dnodesize);
3073 
3074 EXPORT_SYMBOL(dmu_objset_sync);
3075 EXPORT_SYMBOL(dmu_objset_is_dirty);
3076 EXPORT_SYMBOL(dmu_objset_create_impl_dnstats);
3077 EXPORT_SYMBOL(dmu_objset_create_impl);
3078 EXPORT_SYMBOL(dmu_objset_open_impl);
3079 EXPORT_SYMBOL(dmu_objset_evict);
3080 EXPORT_SYMBOL(dmu_objset_register_type);
3081 EXPORT_SYMBOL(dmu_objset_sync_done);
3082 EXPORT_SYMBOL(dmu_objset_userquota_get_ids);
3083 EXPORT_SYMBOL(dmu_objset_userused_enabled);
3084 EXPORT_SYMBOL(dmu_objset_userspace_upgrade);
3085 EXPORT_SYMBOL(dmu_objset_userspace_present);
3086 EXPORT_SYMBOL(dmu_objset_userobjused_enabled);
3087 EXPORT_SYMBOL(dmu_objset_userobjspace_upgradable);
3088 EXPORT_SYMBOL(dmu_objset_userobjspace_present);
3089 EXPORT_SYMBOL(dmu_objset_projectquota_enabled);
3090 EXPORT_SYMBOL(dmu_objset_projectquota_present);
3091 EXPORT_SYMBOL(dmu_objset_projectquota_upgradable);
3092 EXPORT_SYMBOL(dmu_objset_id_quota_upgrade);
3093 #endif
3094