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