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