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