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