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