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, 2017 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) 2014 Integros [integros.com]
30  * Copyright 2017 Nexenta Systems, Inc.
31  * Copyright (c) 2018, loli10K <ezomori.nozomu@gmail.com>. All rights reserved.
32  */
33 
34 /* Portions Copyright 2010 Robert Milkowski */
35 
36 #include <sys/cred.h>
37 #include <sys/zfs_context.h>
38 #include <sys/dmu_objset.h>
39 #include <sys/dsl_dir.h>
40 #include <sys/dsl_dataset.h>
41 #include <sys/dsl_prop.h>
42 #include <sys/dsl_pool.h>
43 #include <sys/dsl_synctask.h>
44 #include <sys/dsl_deleg.h>
45 #include <sys/dnode.h>
46 #include <sys/dbuf.h>
47 #include <sys/zvol.h>
48 #include <sys/dmu_tx.h>
49 #include <sys/zap.h>
50 #include <sys/zil.h>
51 #include <sys/dmu_impl.h>
52 #include <sys/zfs_ioctl.h>
53 #include <sys/sa.h>
54 #include <sys/zfs_onexit.h>
55 #include <sys/dsl_destroy.h>
56 #include <sys/vdev.h>
57 #include <sys/zfeature.h>
58 #include "zfs_namecheck.h"
59 
60 /*
61  * Needed to close a window in dnode_move() that allows the objset to be freed
62  * before it can be safely accessed.
63  */
64 krwlock_t os_lock;
65 
66 /*
67  * Tunable to overwrite the maximum number of threads for the parallization
68  * of dmu_objset_find_dp, needed to speed up the import of pools with many
69  * datasets.
70  * Default is 4 times the number of leaf vdevs.
71  */
72 int dmu_find_threads = 0;
73 
74 /*
75  * Backfill lower metadnode objects after this many have been freed.
76  * Backfilling negatively impacts object creation rates, so only do it
77  * if there are enough holes to fill.
78  */
79 int dmu_rescan_dnode_threshold = 131072;
80 
81 static void dmu_objset_find_dp_cb(void *arg);
82 
83 void
dmu_objset_init(void)84 dmu_objset_init(void)
85 {
86 	rw_init(&os_lock, NULL, RW_DEFAULT, NULL);
87 }
88 
89 void
dmu_objset_fini(void)90 dmu_objset_fini(void)
91 {
92 	rw_destroy(&os_lock);
93 }
94 
95 spa_t *
dmu_objset_spa(objset_t * os)96 dmu_objset_spa(objset_t *os)
97 {
98 	return (os->os_spa);
99 }
100 
101 zilog_t *
dmu_objset_zil(objset_t * os)102 dmu_objset_zil(objset_t *os)
103 {
104 	return (os->os_zil);
105 }
106 
107 dsl_pool_t *
dmu_objset_pool(objset_t * os)108 dmu_objset_pool(objset_t *os)
109 {
110 	dsl_dataset_t *ds;
111 
112 	if ((ds = os->os_dsl_dataset) != NULL && ds->ds_dir)
113 		return (ds->ds_dir->dd_pool);
114 	else
115 		return (spa_get_dsl(os->os_spa));
116 }
117 
118 dsl_dataset_t *
dmu_objset_ds(objset_t * os)119 dmu_objset_ds(objset_t *os)
120 {
121 	return (os->os_dsl_dataset);
122 }
123 
124 dmu_objset_type_t
dmu_objset_type(objset_t * os)125 dmu_objset_type(objset_t *os)
126 {
127 	return (os->os_phys->os_type);
128 }
129 
130 void
dmu_objset_name(objset_t * os,char * buf)131 dmu_objset_name(objset_t *os, char *buf)
132 {
133 	dsl_dataset_name(os->os_dsl_dataset, buf);
134 }
135 
136 uint64_t
dmu_objset_id(objset_t * os)137 dmu_objset_id(objset_t *os)
138 {
139 	dsl_dataset_t *ds = os->os_dsl_dataset;
140 
141 	return (ds ? ds->ds_object : 0);
142 }
143 
144 uint64_t
dmu_objset_dnodesize(objset_t * os)145 dmu_objset_dnodesize(objset_t *os)
146 {
147 	return (os->os_dnodesize);
148 }
149 
150 zfs_sync_type_t
dmu_objset_syncprop(objset_t * os)151 dmu_objset_syncprop(objset_t *os)
152 {
153 	return (os->os_sync);
154 }
155 
156 zfs_logbias_op_t
dmu_objset_logbias(objset_t * os)157 dmu_objset_logbias(objset_t *os)
158 {
159 	return (os->os_logbias);
160 }
161 
162 static void
checksum_changed_cb(void * arg,uint64_t newval)163 checksum_changed_cb(void *arg, uint64_t newval)
164 {
165 	objset_t *os = arg;
166 
167 	/*
168 	 * Inheritance should have been done by now.
169 	 */
170 	ASSERT(newval != ZIO_CHECKSUM_INHERIT);
171 
172 	os->os_checksum = zio_checksum_select(newval, ZIO_CHECKSUM_ON_VALUE);
173 }
174 
175 static void
compression_changed_cb(void * arg,uint64_t newval)176 compression_changed_cb(void *arg, uint64_t newval)
177 {
178 	objset_t *os = arg;
179 
180 	/*
181 	 * Inheritance and range checking should have been done by now.
182 	 */
183 	ASSERT(newval != ZIO_COMPRESS_INHERIT);
184 
185 	os->os_compress = zio_compress_select(os->os_spa, newval,
186 	    ZIO_COMPRESS_ON);
187 }
188 
189 static void
copies_changed_cb(void * arg,uint64_t newval)190 copies_changed_cb(void *arg, uint64_t newval)
191 {
192 	objset_t *os = arg;
193 
194 	/*
195 	 * Inheritance and range checking should have been done by now.
196 	 */
197 	ASSERT(newval > 0);
198 	ASSERT(newval <= spa_max_replication(os->os_spa));
199 
200 	os->os_copies = newval;
201 }
202 
203 static void
dedup_changed_cb(void * arg,uint64_t newval)204 dedup_changed_cb(void *arg, uint64_t newval)
205 {
206 	objset_t *os = arg;
207 	spa_t *spa = os->os_spa;
208 	enum zio_checksum checksum;
209 
210 	/*
211 	 * Inheritance should have been done by now.
212 	 */
213 	ASSERT(newval != ZIO_CHECKSUM_INHERIT);
214 
215 	checksum = zio_checksum_dedup_select(spa, newval, ZIO_CHECKSUM_OFF);
216 
217 	os->os_dedup_checksum = checksum & ZIO_CHECKSUM_MASK;
218 	os->os_dedup_verify = !!(checksum & ZIO_CHECKSUM_VERIFY);
219 }
220 
221 static void
primary_cache_changed_cb(void * arg,uint64_t newval)222 primary_cache_changed_cb(void *arg, uint64_t newval)
223 {
224 	objset_t *os = arg;
225 
226 	/*
227 	 * Inheritance and range checking should have been done by now.
228 	 */
229 	ASSERT(newval == ZFS_CACHE_ALL || newval == ZFS_CACHE_NONE ||
230 	    newval == ZFS_CACHE_METADATA);
231 
232 	os->os_primary_cache = newval;
233 }
234 
235 static void
secondary_cache_changed_cb(void * arg,uint64_t newval)236 secondary_cache_changed_cb(void *arg, uint64_t newval)
237 {
238 	objset_t *os = arg;
239 
240 	/*
241 	 * Inheritance and range checking should have been done by now.
242 	 */
243 	ASSERT(newval == ZFS_CACHE_ALL || newval == ZFS_CACHE_NONE ||
244 	    newval == ZFS_CACHE_METADATA);
245 
246 	os->os_secondary_cache = newval;
247 }
248 
249 static void
sync_changed_cb(void * arg,uint64_t newval)250 sync_changed_cb(void *arg, uint64_t newval)
251 {
252 	objset_t *os = arg;
253 
254 	/*
255 	 * Inheritance and range checking should have been done by now.
256 	 */
257 	ASSERT(newval == ZFS_SYNC_STANDARD || newval == ZFS_SYNC_ALWAYS ||
258 	    newval == ZFS_SYNC_DISABLED);
259 
260 	os->os_sync = newval;
261 	if (os->os_zil)
262 		zil_set_sync(os->os_zil, newval);
263 }
264 
265 static void
redundant_metadata_changed_cb(void * arg,uint64_t newval)266 redundant_metadata_changed_cb(void *arg, uint64_t newval)
267 {
268 	objset_t *os = arg;
269 
270 	/*
271 	 * Inheritance and range checking should have been done by now.
272 	 */
273 	ASSERT(newval == ZFS_REDUNDANT_METADATA_ALL ||
274 	    newval == ZFS_REDUNDANT_METADATA_MOST);
275 
276 	os->os_redundant_metadata = newval;
277 }
278 
279 static void
dnodesize_changed_cb(void * arg,uint64_t newval)280 dnodesize_changed_cb(void *arg, uint64_t newval)
281 {
282 	objset_t *os = arg;
283 
284 	switch (newval) {
285 	case ZFS_DNSIZE_LEGACY:
286 		os->os_dnodesize = DNODE_MIN_SIZE;
287 		break;
288 	case ZFS_DNSIZE_AUTO:
289 		/*
290 		 * Choose a dnode size that will work well for most
291 		 * workloads if the user specified "auto". Future code
292 		 * improvements could dynamically select a dnode size
293 		 * based on observed workload patterns.
294 		 */
295 		os->os_dnodesize = DNODE_MIN_SIZE * 2;
296 		break;
297 	case ZFS_DNSIZE_1K:
298 	case ZFS_DNSIZE_2K:
299 	case ZFS_DNSIZE_4K:
300 	case ZFS_DNSIZE_8K:
301 	case ZFS_DNSIZE_16K:
302 		os->os_dnodesize = newval;
303 		break;
304 	}
305 }
306 
307 static void
smallblk_changed_cb(void * arg,uint64_t newval)308 smallblk_changed_cb(void *arg, uint64_t newval)
309 {
310 	objset_t *os = arg;
311 
312 	/*
313 	 * Inheritance and range checking should have been done by now.
314 	 */
315 	ASSERT(newval <= SPA_OLD_MAXBLOCKSIZE);
316 	ASSERT(ISP2(newval));
317 
318 	os->os_zpl_special_smallblock = newval;
319 }
320 
321 static void
logbias_changed_cb(void * arg,uint64_t newval)322 logbias_changed_cb(void *arg, uint64_t newval)
323 {
324 	objset_t *os = arg;
325 
326 	ASSERT(newval == ZFS_LOGBIAS_LATENCY ||
327 	    newval == ZFS_LOGBIAS_THROUGHPUT);
328 	os->os_logbias = newval;
329 	if (os->os_zil)
330 		zil_set_logbias(os->os_zil, newval);
331 }
332 
333 static void
recordsize_changed_cb(void * arg,uint64_t newval)334 recordsize_changed_cb(void *arg, uint64_t newval)
335 {
336 	objset_t *os = arg;
337 
338 	os->os_recordsize = newval;
339 }
340 
341 void
dmu_objset_byteswap(void * buf,size_t size)342 dmu_objset_byteswap(void *buf, size_t size)
343 {
344 	objset_phys_t *osp = buf;
345 
346 	ASSERT(size == OBJSET_OLD_PHYS_SIZE || size == sizeof (objset_phys_t));
347 	dnode_byteswap(&osp->os_meta_dnode);
348 	byteswap_uint64_array(&osp->os_zil_header, sizeof (zil_header_t));
349 	osp->os_type = BSWAP_64(osp->os_type);
350 	osp->os_flags = BSWAP_64(osp->os_flags);
351 	if (size == sizeof (objset_phys_t)) {
352 		dnode_byteswap(&osp->os_userused_dnode);
353 		dnode_byteswap(&osp->os_groupused_dnode);
354 	}
355 }
356 
357 /*
358  * The hash is a CRC-based hash of the objset_t pointer and the object number.
359  */
360 static uint64_t
dnode_hash(const objset_t * os,uint64_t obj)361 dnode_hash(const objset_t *os, uint64_t obj)
362 {
363 	uintptr_t osv = (uintptr_t)os;
364 	uint64_t crc = -1ULL;
365 
366 	ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
367 	/*
368 	 * The low 6 bits of the pointer don't have much entropy, because
369 	 * the objset_t is larger than 2^6 bytes long.
370 	 */
371 	crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (osv >> 6)) & 0xFF];
372 	crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (obj >> 0)) & 0xFF];
373 	crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (obj >> 8)) & 0xFF];
374 	crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (obj >> 16)) & 0xFF];
375 
376 	crc ^= (osv>>14) ^ (obj>>24);
377 
378 	return (crc);
379 }
380 
381 unsigned int
dnode_multilist_index_func(multilist_t * ml,void * obj)382 dnode_multilist_index_func(multilist_t *ml, void *obj)
383 {
384 	dnode_t *dn = obj;
385 	return (dnode_hash(dn->dn_objset, dn->dn_object) %
386 	    multilist_get_num_sublists(ml));
387 }
388 
389 /*
390  * Instantiates the objset_t in-memory structure corresponding to the
391  * objset_phys_t that's pointed to by the specified blkptr_t.
392  */
393 int
dmu_objset_open_impl(spa_t * spa,dsl_dataset_t * ds,blkptr_t * bp,objset_t ** osp)394 dmu_objset_open_impl(spa_t *spa, dsl_dataset_t *ds, blkptr_t *bp,
395     objset_t **osp)
396 {
397 	objset_t *os;
398 	int i, err;
399 
400 	ASSERT(ds == NULL || MUTEX_HELD(&ds->ds_opening_lock));
401 
402 #if 0
403 	/*
404 	 * The $ORIGIN dataset (if it exists) doesn't have an associated
405 	 * objset, so there's no reason to open it. The $ORIGIN dataset
406 	 * will not exist on pools older than SPA_VERSION_ORIGIN.
407 	 */
408 	if (ds != NULL && spa_get_dsl(spa) != NULL &&
409 	    spa_get_dsl(spa)->dp_origin_snap != NULL) {
410 		ASSERT3P(ds->ds_dir, !=,
411 		    spa_get_dsl(spa)->dp_origin_snap->ds_dir);
412 	}
413 #endif
414 
415 	os = kmem_zalloc(sizeof (objset_t), KM_SLEEP);
416 	os->os_dsl_dataset = ds;
417 	os->os_spa = spa;
418 	os->os_rootbp = bp;
419 	if (!BP_IS_HOLE(os->os_rootbp)) {
420 		arc_flags_t aflags = ARC_FLAG_WAIT;
421 		zbookmark_phys_t zb;
422 		SET_BOOKMARK(&zb, ds ? ds->ds_object : DMU_META_OBJSET,
423 		    ZB_ROOT_OBJECT, ZB_ROOT_LEVEL, ZB_ROOT_BLKID);
424 
425 		if (DMU_OS_IS_L2CACHEABLE(os))
426 			aflags |= ARC_FLAG_L2CACHE;
427 
428 		dprintf_bp(os->os_rootbp, "reading %s", "");
429 		err = arc_read(NULL, spa, os->os_rootbp,
430 		    arc_getbuf_func, &os->os_phys_buf,
431 		    ZIO_PRIORITY_SYNC_READ, ZIO_FLAG_CANFAIL, &aflags, &zb);
432 		if (err != 0) {
433 			kmem_free(os, sizeof (objset_t));
434 			/* convert checksum errors into IO errors */
435 			if (err == ECKSUM)
436 				err = SET_ERROR(EIO);
437 			return (err);
438 		}
439 
440 		/* Increase the blocksize if we are permitted. */
441 		if (spa_version(spa) >= SPA_VERSION_USERSPACE &&
442 		    arc_buf_size(os->os_phys_buf) < sizeof (objset_phys_t)) {
443 			arc_buf_t *buf = arc_alloc_buf(spa, &os->os_phys_buf,
444 			    ARC_BUFC_METADATA, sizeof (objset_phys_t));
445 			bzero(buf->b_data, sizeof (objset_phys_t));
446 			bcopy(os->os_phys_buf->b_data, buf->b_data,
447 			    arc_buf_size(os->os_phys_buf));
448 			arc_buf_destroy(os->os_phys_buf, &os->os_phys_buf);
449 			os->os_phys_buf = buf;
450 		}
451 
452 		os->os_phys = os->os_phys_buf->b_data;
453 		os->os_flags = os->os_phys->os_flags;
454 	} else {
455 		int size = spa_version(spa) >= SPA_VERSION_USERSPACE ?
456 		    sizeof (objset_phys_t) : OBJSET_OLD_PHYS_SIZE;
457 		os->os_phys_buf = arc_alloc_buf(spa, &os->os_phys_buf,
458 		    ARC_BUFC_METADATA, size);
459 		os->os_phys = os->os_phys_buf->b_data;
460 		bzero(os->os_phys, size);
461 	}
462 
463 	/*
464 	 * Note: the changed_cb will be called once before the register
465 	 * func returns, thus changing the checksum/compression from the
466 	 * default (fletcher2/off).  Snapshots don't need to know about
467 	 * checksum/compression/copies.
468 	 */
469 	if (ds != NULL) {
470 		boolean_t needlock = B_FALSE;
471 
472 		/*
473 		 * Note: it's valid to open the objset if the dataset is
474 		 * long-held, in which case the pool_config lock will not
475 		 * be held.
476 		 */
477 		if (!dsl_pool_config_held(dmu_objset_pool(os))) {
478 			needlock = B_TRUE;
479 			dsl_pool_config_enter(dmu_objset_pool(os), FTAG);
480 		}
481 		err = dsl_prop_register(ds,
482 		    zfs_prop_to_name(ZFS_PROP_PRIMARYCACHE),
483 		    primary_cache_changed_cb, os);
484 		if (err == 0) {
485 			err = dsl_prop_register(ds,
486 			    zfs_prop_to_name(ZFS_PROP_SECONDARYCACHE),
487 			    secondary_cache_changed_cb, os);
488 		}
489 		if (!ds->ds_is_snapshot) {
490 			if (err == 0) {
491 				err = dsl_prop_register(ds,
492 				    zfs_prop_to_name(ZFS_PROP_CHECKSUM),
493 				    checksum_changed_cb, os);
494 			}
495 			if (err == 0) {
496 				err = dsl_prop_register(ds,
497 				    zfs_prop_to_name(ZFS_PROP_COMPRESSION),
498 				    compression_changed_cb, os);
499 			}
500 			if (err == 0) {
501 				err = dsl_prop_register(ds,
502 				    zfs_prop_to_name(ZFS_PROP_COPIES),
503 				    copies_changed_cb, os);
504 			}
505 			if (err == 0) {
506 				err = dsl_prop_register(ds,
507 				    zfs_prop_to_name(ZFS_PROP_DEDUP),
508 				    dedup_changed_cb, os);
509 			}
510 			if (err == 0) {
511 				err = dsl_prop_register(ds,
512 				    zfs_prop_to_name(ZFS_PROP_LOGBIAS),
513 				    logbias_changed_cb, os);
514 			}
515 			if (err == 0) {
516 				err = dsl_prop_register(ds,
517 				    zfs_prop_to_name(ZFS_PROP_SYNC),
518 				    sync_changed_cb, os);
519 			}
520 			if (err == 0) {
521 				err = dsl_prop_register(ds,
522 				    zfs_prop_to_name(
523 				    ZFS_PROP_REDUNDANT_METADATA),
524 				    redundant_metadata_changed_cb, os);
525 			}
526 			if (err == 0) {
527 				err = dsl_prop_register(ds,
528 				    zfs_prop_to_name(ZFS_PROP_RECORDSIZE),
529 				    recordsize_changed_cb, os);
530 			}
531 			if (err == 0) {
532 				err = dsl_prop_register(ds,
533 				    zfs_prop_to_name(ZFS_PROP_DNODESIZE),
534 				    dnodesize_changed_cb, os);
535 			}
536 			if (err == 0) {
537 				err = dsl_prop_register(ds,
538 				    zfs_prop_to_name(
539 				    ZFS_PROP_SPECIAL_SMALL_BLOCKS),
540 				    smallblk_changed_cb, os);
541 			}
542 		}
543 		if (needlock)
544 			dsl_pool_config_exit(dmu_objset_pool(os), FTAG);
545 		if (err != 0) {
546 			arc_buf_destroy(os->os_phys_buf, &os->os_phys_buf);
547 			kmem_free(os, sizeof (objset_t));
548 			return (err);
549 		}
550 	} else {
551 		/* It's the meta-objset. */
552 		os->os_checksum = ZIO_CHECKSUM_FLETCHER_4;
553 		os->os_compress = ZIO_COMPRESS_ON;
554 		os->os_copies = spa_max_replication(spa);
555 		os->os_dedup_checksum = ZIO_CHECKSUM_OFF;
556 		os->os_dedup_verify = B_FALSE;
557 		os->os_logbias = ZFS_LOGBIAS_LATENCY;
558 		os->os_sync = ZFS_SYNC_STANDARD;
559 		os->os_primary_cache = ZFS_CACHE_ALL;
560 		os->os_secondary_cache = ZFS_CACHE_ALL;
561 		os->os_dnodesize = DNODE_MIN_SIZE;
562 	}
563 	/*
564 	 * These properties will be filled in by the logic in zfs_get_zplprop()
565 	 * when they are queried for the first time.
566 	 */
567 	os->os_version = OBJSET_PROP_UNINITIALIZED;
568 	os->os_normalization = OBJSET_PROP_UNINITIALIZED;
569 	os->os_utf8only = OBJSET_PROP_UNINITIALIZED;
570 	os->os_casesensitivity = OBJSET_PROP_UNINITIALIZED;
571 
572 	if (ds == NULL || !ds->ds_is_snapshot)
573 		os->os_zil_header = os->os_phys->os_zil_header;
574 	os->os_zil = zil_alloc(os, &os->os_zil_header);
575 
576 	for (i = 0; i < TXG_SIZE; i++) {
577 		os->os_dirty_dnodes[i] = multilist_create(sizeof (dnode_t),
578 		    offsetof(dnode_t, dn_dirty_link[i]),
579 		    dnode_multilist_index_func);
580 	}
581 	list_create(&os->os_dnodes, sizeof (dnode_t),
582 	    offsetof(dnode_t, dn_link));
583 	list_create(&os->os_downgraded_dbufs, sizeof (dmu_buf_impl_t),
584 	    offsetof(dmu_buf_impl_t, db_link));
585 
586 	mutex_init(&os->os_lock, NULL, MUTEX_DEFAULT, NULL);
587 	mutex_init(&os->os_userused_lock, NULL, MUTEX_DEFAULT, NULL);
588 	mutex_init(&os->os_obj_lock, NULL, MUTEX_DEFAULT, NULL);
589 	mutex_init(&os->os_user_ptr_lock, NULL, MUTEX_DEFAULT, NULL);
590 	os->os_obj_next_percpu_len = boot_ncpus;
591 	os->os_obj_next_percpu = kmem_zalloc(os->os_obj_next_percpu_len *
592 	    sizeof (os->os_obj_next_percpu[0]), KM_SLEEP);
593 
594 	dnode_special_open(os, &os->os_phys->os_meta_dnode,
595 	    DMU_META_DNODE_OBJECT, &os->os_meta_dnode);
596 	if (arc_buf_size(os->os_phys_buf) >= sizeof (objset_phys_t)) {
597 		dnode_special_open(os, &os->os_phys->os_userused_dnode,
598 		    DMU_USERUSED_OBJECT, &os->os_userused_dnode);
599 		dnode_special_open(os, &os->os_phys->os_groupused_dnode,
600 		    DMU_GROUPUSED_OBJECT, &os->os_groupused_dnode);
601 	}
602 
603 	*osp = os;
604 	return (0);
605 }
606 
607 int
dmu_objset_from_ds(dsl_dataset_t * ds,objset_t ** osp)608 dmu_objset_from_ds(dsl_dataset_t *ds, objset_t **osp)
609 {
610 	int err = 0;
611 
612 	/*
613 	 * We shouldn't be doing anything with dsl_dataset_t's unless the
614 	 * pool_config lock is held, or the dataset is long-held.
615 	 */
616 	ASSERT(dsl_pool_config_held(ds->ds_dir->dd_pool) ||
617 	    dsl_dataset_long_held(ds));
618 
619 	mutex_enter(&ds->ds_opening_lock);
620 	if (ds->ds_objset == NULL) {
621 		objset_t *os;
622 		rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);
623 		err = dmu_objset_open_impl(dsl_dataset_get_spa(ds),
624 		    ds, dsl_dataset_get_blkptr(ds), &os);
625 		rrw_exit(&ds->ds_bp_rwlock, FTAG);
626 
627 		if (err == 0) {
628 			mutex_enter(&ds->ds_lock);
629 			ASSERT(ds->ds_objset == NULL);
630 			ds->ds_objset = os;
631 			mutex_exit(&ds->ds_lock);
632 		}
633 	}
634 	*osp = ds->ds_objset;
635 	mutex_exit(&ds->ds_opening_lock);
636 	return (err);
637 }
638 
639 /*
640  * Holds the pool while the objset is held.  Therefore only one objset
641  * can be held at a time.
642  */
643 int
dmu_objset_hold(const char * name,void * tag,objset_t ** osp)644 dmu_objset_hold(const char *name, void *tag, objset_t **osp)
645 {
646 	dsl_pool_t *dp;
647 	dsl_dataset_t *ds;
648 	int err;
649 
650 	err = dsl_pool_hold(name, tag, &dp);
651 	if (err != 0)
652 		return (err);
653 	err = dsl_dataset_hold(dp, name, tag, &ds);
654 	if (err != 0) {
655 		dsl_pool_rele(dp, tag);
656 		return (err);
657 	}
658 
659 	err = dmu_objset_from_ds(ds, osp);
660 	if (err != 0) {
661 		dsl_dataset_rele(ds, tag);
662 		dsl_pool_rele(dp, tag);
663 	}
664 
665 	return (err);
666 }
667 
668 static int
dmu_objset_own_impl(dsl_dataset_t * ds,dmu_objset_type_t type,boolean_t readonly,void * tag,objset_t ** osp)669 dmu_objset_own_impl(dsl_dataset_t *ds, dmu_objset_type_t type,
670     boolean_t readonly, void *tag, objset_t **osp)
671 {
672 	int err;
673 
674 	err = dmu_objset_from_ds(ds, osp);
675 	if (err != 0) {
676 		dsl_dataset_disown(ds, tag);
677 	} else if (type != DMU_OST_ANY && type != (*osp)->os_phys->os_type) {
678 		dsl_dataset_disown(ds, tag);
679 		return (SET_ERROR(EINVAL));
680 	} else if (!readonly && dsl_dataset_is_snapshot(ds)) {
681 		dsl_dataset_disown(ds, tag);
682 		return (SET_ERROR(EROFS));
683 	}
684 	return (err);
685 }
686 
687 /*
688  * dsl_pool must not be held when this is called.
689  * Upon successful return, there will be a longhold on the dataset,
690  * and the dsl_pool will not be held.
691  */
692 int
dmu_objset_own(const char * name,dmu_objset_type_t type,boolean_t readonly,void * tag,objset_t ** osp)693 dmu_objset_own(const char *name, dmu_objset_type_t type,
694     boolean_t readonly, void *tag, objset_t **osp)
695 {
696 	dsl_pool_t *dp;
697 	dsl_dataset_t *ds;
698 	int err;
699 
700 	err = dsl_pool_hold(name, FTAG, &dp);
701 	if (err != 0)
702 		return (err);
703 	err = dsl_dataset_own(dp, name, tag, &ds);
704 	if (err != 0) {
705 		dsl_pool_rele(dp, FTAG);
706 		return (err);
707 	}
708 	err = dmu_objset_own_impl(ds, type, readonly, tag, osp);
709 	dsl_pool_rele(dp, FTAG);
710 
711 	return (err);
712 }
713 
714 int
dmu_objset_own_obj(dsl_pool_t * dp,uint64_t obj,dmu_objset_type_t type,boolean_t readonly,void * tag,objset_t ** osp)715 dmu_objset_own_obj(dsl_pool_t *dp, uint64_t obj, dmu_objset_type_t type,
716     boolean_t readonly, void *tag, objset_t **osp)
717 {
718 	dsl_dataset_t *ds;
719 	int err;
720 
721 	err = dsl_dataset_own_obj(dp, obj, tag, &ds);
722 	if (err != 0)
723 		return (err);
724 
725 	return (dmu_objset_own_impl(ds, type, readonly, tag, osp));
726 }
727 
728 void
dmu_objset_rele(objset_t * os,void * tag)729 dmu_objset_rele(objset_t *os, void *tag)
730 {
731 	dsl_pool_t *dp = dmu_objset_pool(os);
732 	dsl_dataset_rele(os->os_dsl_dataset, tag);
733 	dsl_pool_rele(dp, tag);
734 }
735 
736 /*
737  * When we are called, os MUST refer to an objset associated with a dataset
738  * that is owned by 'tag'; that is, is held and long held by 'tag' and ds_owner
739  * == tag.  We will then release and reacquire ownership of the dataset while
740  * holding the pool config_rwlock to avoid intervening namespace or ownership
741  * changes may occur.
742  *
743  * This exists solely to accommodate zfs_ioc_userspace_upgrade()'s desire to
744  * release the hold on its dataset and acquire a new one on the dataset of the
745  * same name so that it can be partially torn down and reconstructed.
746  */
747 void
dmu_objset_refresh_ownership(dsl_dataset_t * ds,dsl_dataset_t ** newds,void * tag)748 dmu_objset_refresh_ownership(dsl_dataset_t *ds, dsl_dataset_t **newds,
749     void *tag)
750 {
751 	dsl_pool_t *dp;
752 	char name[ZFS_MAX_DATASET_NAME_LEN];
753 
754 	VERIFY3P(ds, !=, NULL);
755 	VERIFY3P(ds->ds_owner, ==, tag);
756 	VERIFY(dsl_dataset_long_held(ds));
757 
758 	dsl_dataset_name(ds, name);
759 	dp = ds->ds_dir->dd_pool;
760 	dsl_pool_config_enter(dp, FTAG);
761 	dsl_dataset_disown(ds, tag);
762 	VERIFY0(dsl_dataset_own(dp, name, tag, newds));
763 	dsl_pool_config_exit(dp, FTAG);
764 }
765 
766 void
dmu_objset_disown(objset_t * os,void * tag)767 dmu_objset_disown(objset_t *os, void *tag)
768 {
769 	dsl_dataset_disown(os->os_dsl_dataset, tag);
770 }
771 
772 void
dmu_objset_evict_dbufs(objset_t * os)773 dmu_objset_evict_dbufs(objset_t *os)
774 {
775 	dnode_t dn_marker;
776 	dnode_t *dn;
777 
778 	mutex_enter(&os->os_lock);
779 	dn = list_head(&os->os_dnodes);
780 	while (dn != NULL) {
781 		/*
782 		 * Skip dnodes without holds.  We have to do this dance
783 		 * because dnode_add_ref() only works if there is already a
784 		 * hold.  If the dnode has no holds, then it has no dbufs.
785 		 */
786 		if (dnode_add_ref(dn, FTAG)) {
787 			list_insert_after(&os->os_dnodes, dn, &dn_marker);
788 			mutex_exit(&os->os_lock);
789 
790 			dnode_evict_dbufs(dn);
791 			dnode_rele(dn, FTAG);
792 
793 			mutex_enter(&os->os_lock);
794 			dn = list_next(&os->os_dnodes, &dn_marker);
795 			list_remove(&os->os_dnodes, &dn_marker);
796 		} else {
797 			dn = list_next(&os->os_dnodes, dn);
798 		}
799 	}
800 	mutex_exit(&os->os_lock);
801 
802 	if (DMU_USERUSED_DNODE(os) != NULL) {
803 		dnode_evict_dbufs(DMU_GROUPUSED_DNODE(os));
804 		dnode_evict_dbufs(DMU_USERUSED_DNODE(os));
805 	}
806 	dnode_evict_dbufs(DMU_META_DNODE(os));
807 }
808 
809 /*
810  * Objset eviction processing is split into into two pieces.
811  * The first marks the objset as evicting, evicts any dbufs that
812  * have a refcount of zero, and then queues up the objset for the
813  * second phase of eviction.  Once os->os_dnodes has been cleared by
814  * dnode_buf_pageout()->dnode_destroy(), the second phase is executed.
815  * The second phase closes the special dnodes, dequeues the objset from
816  * the list of those undergoing eviction, and finally frees the objset.
817  *
818  * NOTE: Due to asynchronous eviction processing (invocation of
819  *       dnode_buf_pageout()), it is possible for the meta dnode for the
820  *       objset to have no holds even though os->os_dnodes is not empty.
821  */
822 void
dmu_objset_evict(objset_t * os)823 dmu_objset_evict(objset_t *os)
824 {
825 	dsl_dataset_t *ds = os->os_dsl_dataset;
826 
827 	for (int t = 0; t < TXG_SIZE; t++)
828 		ASSERT(!dmu_objset_is_dirty(os, t));
829 
830 	if (ds)
831 		dsl_prop_unregister_all(ds, os);
832 
833 	if (os->os_sa)
834 		sa_tear_down(os);
835 
836 	dmu_objset_evict_dbufs(os);
837 
838 	mutex_enter(&os->os_lock);
839 	spa_evicting_os_register(os->os_spa, os);
840 	if (list_is_empty(&os->os_dnodes)) {
841 		mutex_exit(&os->os_lock);
842 		dmu_objset_evict_done(os);
843 	} else {
844 		mutex_exit(&os->os_lock);
845 	}
846 }
847 
848 void
dmu_objset_evict_done(objset_t * os)849 dmu_objset_evict_done(objset_t *os)
850 {
851 	ASSERT3P(list_head(&os->os_dnodes), ==, NULL);
852 
853 	dnode_special_close(&os->os_meta_dnode);
854 	if (DMU_USERUSED_DNODE(os)) {
855 		dnode_special_close(&os->os_userused_dnode);
856 		dnode_special_close(&os->os_groupused_dnode);
857 	}
858 	zil_free(os->os_zil);
859 
860 	arc_buf_destroy(os->os_phys_buf, &os->os_phys_buf);
861 
862 	/*
863 	 * This is a barrier to prevent the objset from going away in
864 	 * dnode_move() until we can safely ensure that the objset is still in
865 	 * use. We consider the objset valid before the barrier and invalid
866 	 * after the barrier.
867 	 */
868 	rw_enter(&os_lock, RW_READER);
869 	rw_exit(&os_lock);
870 
871 	kmem_free(os->os_obj_next_percpu,
872 	    os->os_obj_next_percpu_len * sizeof (os->os_obj_next_percpu[0]));
873 
874 	mutex_destroy(&os->os_lock);
875 	mutex_destroy(&os->os_userused_lock);
876 	mutex_destroy(&os->os_obj_lock);
877 	mutex_destroy(&os->os_user_ptr_lock);
878 	for (int i = 0; i < TXG_SIZE; i++) {
879 		multilist_destroy(os->os_dirty_dnodes[i]);
880 	}
881 	spa_evicting_os_deregister(os->os_spa, os);
882 	kmem_free(os, sizeof (objset_t));
883 }
884 
885 timestruc_t
dmu_objset_snap_cmtime(objset_t * os)886 dmu_objset_snap_cmtime(objset_t *os)
887 {
888 	return (dsl_dir_snap_cmtime(os->os_dsl_dataset->ds_dir));
889 }
890 
891 /* called from dsl for meta-objset */
892 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)893 dmu_objset_create_impl(spa_t *spa, dsl_dataset_t *ds, blkptr_t *bp,
894     dmu_objset_type_t type, dmu_tx_t *tx)
895 {
896 	objset_t *os;
897 	dnode_t *mdn;
898 
899 	ASSERT(dmu_tx_is_syncing(tx));
900 
901 	if (ds != NULL)
902 		VERIFY0(dmu_objset_from_ds(ds, &os));
903 	else
904 		VERIFY0(dmu_objset_open_impl(spa, NULL, bp, &os));
905 
906 	mdn = DMU_META_DNODE(os);
907 
908 	dnode_allocate(mdn, DMU_OT_DNODE, DNODE_BLOCK_SIZE, DN_MAX_INDBLKSHIFT,
909 	    DMU_OT_NONE, 0, DNODE_MIN_SLOTS, tx);
910 
911 	/*
912 	 * We don't want to have to increase the meta-dnode's nlevels
913 	 * later, because then we could do it in quescing context while
914 	 * we are also accessing it in open context.
915 	 *
916 	 * This precaution is not necessary for the MOS (ds == NULL),
917 	 * because the MOS is only updated in syncing context.
918 	 * This is most fortunate: the MOS is the only objset that
919 	 * needs to be synced multiple times as spa_sync() iterates
920 	 * to convergence, so minimizing its dn_nlevels matters.
921 	 */
922 	if (ds != NULL) {
923 		int levels = 1;
924 
925 		/*
926 		 * Determine the number of levels necessary for the meta-dnode
927 		 * to contain DN_MAX_OBJECT dnodes.  Note that in order to
928 		 * ensure that we do not overflow 64 bits, there has to be
929 		 * a nlevels that gives us a number of blocks > DN_MAX_OBJECT
930 		 * but < 2^64.  Therefore,
931 		 * (mdn->dn_indblkshift - SPA_BLKPTRSHIFT) (10) must be
932 		 * less than (64 - log2(DN_MAX_OBJECT)) (16).
933 		 */
934 		while ((uint64_t)mdn->dn_nblkptr <<
935 		    (mdn->dn_datablkshift - DNODE_SHIFT +
936 		    (levels - 1) * (mdn->dn_indblkshift - SPA_BLKPTRSHIFT)) <
937 		    DN_MAX_OBJECT)
938 			levels++;
939 
940 		mdn->dn_next_nlevels[tx->tx_txg & TXG_MASK] =
941 		    mdn->dn_nlevels = levels;
942 	}
943 
944 	ASSERT(type != DMU_OST_NONE);
945 	ASSERT(type != DMU_OST_ANY);
946 	ASSERT(type < DMU_OST_NUMTYPES);
947 	os->os_phys->os_type = type;
948 	if (dmu_objset_userused_enabled(os)) {
949 		os->os_phys->os_flags |= OBJSET_FLAG_USERACCOUNTING_COMPLETE;
950 		os->os_flags = os->os_phys->os_flags;
951 	}
952 
953 	dsl_dataset_dirty(ds, tx);
954 
955 	return (os);
956 }
957 
958 typedef struct dmu_objset_create_arg {
959 	const char *doca_name;
960 	cred_t *doca_cred;
961 	void (*doca_userfunc)(objset_t *os, void *arg,
962 	    cred_t *cr, dmu_tx_t *tx);
963 	void *doca_userarg;
964 	dmu_objset_type_t doca_type;
965 	uint64_t doca_flags;
966 } dmu_objset_create_arg_t;
967 
968 /*ARGSUSED*/
969 static int
dmu_objset_create_check(void * arg,dmu_tx_t * tx)970 dmu_objset_create_check(void *arg, dmu_tx_t *tx)
971 {
972 	dmu_objset_create_arg_t *doca = arg;
973 	dsl_pool_t *dp = dmu_tx_pool(tx);
974 	dsl_dir_t *pdd;
975 	dsl_dataset_t *parentds;
976 	objset_t *parentos;
977 	const char *tail;
978 	int error;
979 
980 	if (strchr(doca->doca_name, '@') != NULL)
981 		return (SET_ERROR(EINVAL));
982 
983 	if (strlen(doca->doca_name) >= ZFS_MAX_DATASET_NAME_LEN)
984 		return (SET_ERROR(ENAMETOOLONG));
985 
986 	if (dataset_nestcheck(doca->doca_name) != 0)
987 		return (SET_ERROR(ENAMETOOLONG));
988 
989 	error = dsl_dir_hold(dp, doca->doca_name, FTAG, &pdd, &tail);
990 	if (error != 0)
991 		return (error);
992 	if (tail == NULL) {
993 		dsl_dir_rele(pdd, FTAG);
994 		return (SET_ERROR(EEXIST));
995 	}
996 	error = dsl_fs_ss_limit_check(pdd, 1, ZFS_PROP_FILESYSTEM_LIMIT, NULL,
997 	    doca->doca_cred);
998 	if (error != 0) {
999 		dsl_dir_rele(pdd, FTAG);
1000 		return (error);
1001 	}
1002 
1003 	/* can't create below anything but filesystems (eg. no ZVOLs) */
1004 	error = dsl_dataset_hold_obj(pdd->dd_pool,
1005 	    dsl_dir_phys(pdd)->dd_head_dataset_obj, FTAG, &parentds);
1006 	if (error != 0) {
1007 		dsl_dir_rele(pdd, FTAG);
1008 		return (error);
1009 	}
1010 	error = dmu_objset_from_ds(parentds, &parentos);
1011 	if (error != 0) {
1012 		dsl_dataset_rele(parentds, FTAG);
1013 		dsl_dir_rele(pdd, FTAG);
1014 		return (error);
1015 	}
1016 	if (dmu_objset_type(parentos) != DMU_OST_ZFS) {
1017 		dsl_dataset_rele(parentds, FTAG);
1018 		dsl_dir_rele(pdd, FTAG);
1019 		return (SET_ERROR(ZFS_ERR_WRONG_PARENT));
1020 	}
1021 	dsl_dataset_rele(parentds, FTAG);
1022 	dsl_dir_rele(pdd, FTAG);
1023 
1024 	return (error);
1025 }
1026 
1027 static void
dmu_objset_create_sync(void * arg,dmu_tx_t * tx)1028 dmu_objset_create_sync(void *arg, dmu_tx_t *tx)
1029 {
1030 	dmu_objset_create_arg_t *doca = arg;
1031 	dsl_pool_t *dp = dmu_tx_pool(tx);
1032 	dsl_dir_t *pdd;
1033 	const char *tail;
1034 	dsl_dataset_t *ds;
1035 	uint64_t obj;
1036 	blkptr_t *bp;
1037 	objset_t *os;
1038 
1039 	VERIFY0(dsl_dir_hold(dp, doca->doca_name, FTAG, &pdd, &tail));
1040 
1041 	obj = dsl_dataset_create_sync(pdd, tail, NULL, doca->doca_flags,
1042 	    doca->doca_cred, tx);
1043 
1044 	VERIFY0(dsl_dataset_hold_obj(pdd->dd_pool, obj, FTAG, &ds));
1045 	rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);
1046 	bp = dsl_dataset_get_blkptr(ds);
1047 	os = dmu_objset_create_impl(pdd->dd_pool->dp_spa,
1048 	    ds, bp, doca->doca_type, tx);
1049 	rrw_exit(&ds->ds_bp_rwlock, FTAG);
1050 
1051 	if (doca->doca_userfunc != NULL) {
1052 		doca->doca_userfunc(os, doca->doca_userarg,
1053 		    doca->doca_cred, tx);
1054 	}
1055 
1056 #if defined(__FreeBSD__) && defined(_KERNEL)
1057 	zvol_create_minors(dp->dp_spa, doca->doca_name);
1058 #endif
1059 	spa_history_log_internal_ds(ds, "create", tx, "");
1060 	dsl_dataset_rele(ds, FTAG);
1061 	dsl_dir_rele(pdd, FTAG);
1062 }
1063 
1064 int
dmu_objset_create(const char * name,dmu_objset_type_t type,uint64_t flags,void (* func)(objset_t * os,void * arg,cred_t * cr,dmu_tx_t * tx),void * arg)1065 dmu_objset_create(const char *name, dmu_objset_type_t type, uint64_t flags,
1066     void (*func)(objset_t *os, void *arg, cred_t *cr, dmu_tx_t *tx), void *arg)
1067 {
1068 	dmu_objset_create_arg_t doca;
1069 
1070 	doca.doca_name = name;
1071 	doca.doca_cred = CRED();
1072 	doca.doca_flags = flags;
1073 	doca.doca_userfunc = func;
1074 	doca.doca_userarg = arg;
1075 	doca.doca_type = type;
1076 
1077 	return (dsl_sync_task(name,
1078 	    dmu_objset_create_check, dmu_objset_create_sync, &doca,
1079 	    5, ZFS_SPACE_CHECK_NORMAL));
1080 }
1081 
1082 typedef struct dmu_objset_clone_arg {
1083 	const char *doca_clone;
1084 	const char *doca_origin;
1085 	cred_t *doca_cred;
1086 } dmu_objset_clone_arg_t;
1087 
1088 /*ARGSUSED*/
1089 static int
dmu_objset_clone_check(void * arg,dmu_tx_t * tx)1090 dmu_objset_clone_check(void *arg, dmu_tx_t *tx)
1091 {
1092 	dmu_objset_clone_arg_t *doca = arg;
1093 	dsl_dir_t *pdd;
1094 	const char *tail;
1095 	int error;
1096 	dsl_dataset_t *origin;
1097 	dsl_pool_t *dp = dmu_tx_pool(tx);
1098 
1099 	if (strchr(doca->doca_clone, '@') != NULL)
1100 		return (SET_ERROR(EINVAL));
1101 
1102 	if (strlen(doca->doca_clone) >= ZFS_MAX_DATASET_NAME_LEN)
1103 		return (SET_ERROR(ENAMETOOLONG));
1104 
1105 	error = dsl_dir_hold(dp, doca->doca_clone, FTAG, &pdd, &tail);
1106 	if (error != 0)
1107 		return (error);
1108 	if (tail == NULL) {
1109 		dsl_dir_rele(pdd, FTAG);
1110 		return (SET_ERROR(EEXIST));
1111 	}
1112 
1113 	error = dsl_fs_ss_limit_check(pdd, 1, ZFS_PROP_FILESYSTEM_LIMIT, NULL,
1114 	    doca->doca_cred);
1115 	if (error != 0) {
1116 		dsl_dir_rele(pdd, FTAG);
1117 		return (SET_ERROR(EDQUOT));
1118 	}
1119 	dsl_dir_rele(pdd, FTAG);
1120 
1121 	error = dsl_dataset_hold(dp, doca->doca_origin, FTAG, &origin);
1122 	if (error != 0)
1123 		return (error);
1124 
1125 	/* You can only clone snapshots, not the head datasets. */
1126 	if (!origin->ds_is_snapshot) {
1127 		dsl_dataset_rele(origin, FTAG);
1128 		return (SET_ERROR(EINVAL));
1129 	}
1130 	dsl_dataset_rele(origin, FTAG);
1131 
1132 	return (0);
1133 }
1134 
1135 static void
dmu_objset_clone_sync(void * arg,dmu_tx_t * tx)1136 dmu_objset_clone_sync(void *arg, dmu_tx_t *tx)
1137 {
1138 	dmu_objset_clone_arg_t *doca = arg;
1139 	dsl_pool_t *dp = dmu_tx_pool(tx);
1140 	dsl_dir_t *pdd;
1141 	const char *tail;
1142 	dsl_dataset_t *origin, *ds;
1143 	uint64_t obj;
1144 	char namebuf[ZFS_MAX_DATASET_NAME_LEN];
1145 
1146 	VERIFY0(dsl_dir_hold(dp, doca->doca_clone, FTAG, &pdd, &tail));
1147 	VERIFY0(dsl_dataset_hold(dp, doca->doca_origin, FTAG, &origin));
1148 
1149 	obj = dsl_dataset_create_sync(pdd, tail, origin, 0,
1150 	    doca->doca_cred, tx);
1151 
1152 	VERIFY0(dsl_dataset_hold_obj(pdd->dd_pool, obj, FTAG, &ds));
1153 	dsl_dataset_name(origin, namebuf);
1154 #if defined(__FreeBSD__) && defined(_KERNEL)
1155 	zvol_create_minors(dp->dp_spa, doca->doca_clone);
1156 #endif
1157 	spa_history_log_internal_ds(ds, "clone", tx,
1158 	    "origin=%s (%llu)", namebuf, origin->ds_object);
1159 	dsl_dataset_rele(ds, FTAG);
1160 	dsl_dataset_rele(origin, FTAG);
1161 	dsl_dir_rele(pdd, FTAG);
1162 }
1163 
1164 int
dmu_objset_clone(const char * clone,const char * origin)1165 dmu_objset_clone(const char *clone, const char *origin)
1166 {
1167 	dmu_objset_clone_arg_t doca;
1168 
1169 	doca.doca_clone = clone;
1170 	doca.doca_origin = origin;
1171 	doca.doca_cred = CRED();
1172 
1173 	return (dsl_sync_task(clone,
1174 	    dmu_objset_clone_check, dmu_objset_clone_sync, &doca,
1175 	    5, ZFS_SPACE_CHECK_NORMAL));
1176 }
1177 
1178 static int
dmu_objset_remap_indirects_impl(objset_t * os,uint64_t last_removed_txg)1179 dmu_objset_remap_indirects_impl(objset_t *os, uint64_t last_removed_txg)
1180 {
1181 	int error = 0;
1182 	uint64_t object = 0;
1183 	while ((error = dmu_object_next(os, &object, B_FALSE, 0)) == 0) {
1184 		error = dmu_object_remap_indirects(os, object,
1185 		    last_removed_txg);
1186 		/*
1187 		 * If the ZPL removed the object before we managed to dnode_hold
1188 		 * it, we would get an ENOENT. If the ZPL declares its intent
1189 		 * to remove the object (dnode_free) before we manage to
1190 		 * dnode_hold it, we would get an EEXIST. In either case, we
1191 		 * want to continue remapping the other objects in the objset;
1192 		 * in all other cases, we want to break early.
1193 		 */
1194 		if (error != 0 && error != ENOENT && error != EEXIST) {
1195 			break;
1196 		}
1197 	}
1198 	if (error == ESRCH) {
1199 		error = 0;
1200 	}
1201 	return (error);
1202 }
1203 
1204 int
dmu_objset_remap_indirects(const char * fsname)1205 dmu_objset_remap_indirects(const char *fsname)
1206 {
1207 	int error = 0;
1208 	objset_t *os = NULL;
1209 	uint64_t last_removed_txg;
1210 	uint64_t remap_start_txg;
1211 	dsl_dir_t *dd;
1212 
1213 	error = dmu_objset_hold(fsname, FTAG, &os);
1214 	if (error != 0) {
1215 		return (error);
1216 	}
1217 	dd = dmu_objset_ds(os)->ds_dir;
1218 
1219 	if (!spa_feature_is_enabled(dmu_objset_spa(os),
1220 	    SPA_FEATURE_OBSOLETE_COUNTS)) {
1221 		dmu_objset_rele(os, FTAG);
1222 		return (SET_ERROR(ENOTSUP));
1223 	}
1224 
1225 	if (dsl_dataset_is_snapshot(dmu_objset_ds(os))) {
1226 		dmu_objset_rele(os, FTAG);
1227 		return (SET_ERROR(EINVAL));
1228 	}
1229 
1230 	/*
1231 	 * If there has not been a removal, we're done.
1232 	 */
1233 	last_removed_txg = spa_get_last_removal_txg(dmu_objset_spa(os));
1234 	if (last_removed_txg == -1ULL) {
1235 		dmu_objset_rele(os, FTAG);
1236 		return (0);
1237 	}
1238 
1239 	/*
1240 	 * If we have remapped since the last removal, we're done.
1241 	 */
1242 	if (dsl_dir_is_zapified(dd)) {
1243 		uint64_t last_remap_txg;
1244 		if (zap_lookup(spa_meta_objset(dmu_objset_spa(os)),
1245 		    dd->dd_object, DD_FIELD_LAST_REMAP_TXG,
1246 		    sizeof (last_remap_txg), 1, &last_remap_txg) == 0 &&
1247 		    last_remap_txg > last_removed_txg) {
1248 			dmu_objset_rele(os, FTAG);
1249 			return (0);
1250 		}
1251 	}
1252 
1253 	dsl_dataset_long_hold(dmu_objset_ds(os), FTAG);
1254 	dsl_pool_rele(dmu_objset_pool(os), FTAG);
1255 
1256 	remap_start_txg = spa_last_synced_txg(dmu_objset_spa(os));
1257 	error = dmu_objset_remap_indirects_impl(os, last_removed_txg);
1258 	if (error == 0) {
1259 		/*
1260 		 * We update the last_remap_txg to be the start txg so that
1261 		 * we can guarantee that every block older than last_remap_txg
1262 		 * that can be remapped has been remapped.
1263 		 */
1264 		error = dsl_dir_update_last_remap_txg(dd, remap_start_txg);
1265 	}
1266 
1267 	dsl_dataset_long_rele(dmu_objset_ds(os), FTAG);
1268 	dsl_dataset_rele(dmu_objset_ds(os), FTAG);
1269 
1270 	return (error);
1271 }
1272 
1273 int
dmu_objset_snapshot_one(const char * fsname,const char * snapname)1274 dmu_objset_snapshot_one(const char *fsname, const char *snapname)
1275 {
1276 	int err;
1277 	char *longsnap = kmem_asprintf("%s@%s", fsname, snapname);
1278 	nvlist_t *snaps = fnvlist_alloc();
1279 
1280 	fnvlist_add_boolean(snaps, longsnap);
1281 	strfree(longsnap);
1282 	err = dsl_dataset_snapshot(snaps, NULL, NULL);
1283 	fnvlist_free(snaps);
1284 	return (err);
1285 }
1286 
1287 static void
dmu_objset_sync_dnodes(multilist_sublist_t * list,dmu_tx_t * tx)1288 dmu_objset_sync_dnodes(multilist_sublist_t *list, dmu_tx_t *tx)
1289 {
1290 	dnode_t *dn;
1291 
1292 	while ((dn = multilist_sublist_head(list)) != NULL) {
1293 		ASSERT(dn->dn_object != DMU_META_DNODE_OBJECT);
1294 		ASSERT(dn->dn_dbuf->db_data_pending);
1295 		/*
1296 		 * Initialize dn_zio outside dnode_sync() because the
1297 		 * meta-dnode needs to set it ouside dnode_sync().
1298 		 */
1299 		dn->dn_zio = dn->dn_dbuf->db_data_pending->dr_zio;
1300 		ASSERT(dn->dn_zio);
1301 
1302 		ASSERT3U(dn->dn_nlevels, <=, DN_MAX_LEVELS);
1303 		multilist_sublist_remove(list, dn);
1304 
1305 		/*
1306 		 * If we are not doing useraccounting (os_synced_dnodes == NULL)
1307 		 * we are done with this dnode for this txg. Unset dn_dirty_txg
1308 		 * if later txgs aren't dirtying it so that future holders do
1309 		 * not get a stale value. Otherwise, we will do this in
1310 		 * userquota_updates_task() when processing has completely
1311 		 * finished for this txg.
1312 		 */
1313 		multilist_t *newlist = dn->dn_objset->os_synced_dnodes;
1314 		if (newlist != NULL) {
1315 			(void) dnode_add_ref(dn, newlist);
1316 			multilist_insert(newlist, dn);
1317 		} else {
1318 			mutex_enter(&dn->dn_mtx);
1319 			if (dn->dn_dirty_txg == tx->tx_txg)
1320 				dn->dn_dirty_txg = 0;
1321 			mutex_exit(&dn->dn_mtx);
1322 		}
1323 
1324 		dnode_sync(dn, tx);
1325 	}
1326 }
1327 
1328 /* ARGSUSED */
1329 static void
dmu_objset_write_ready(zio_t * zio,arc_buf_t * abuf,void * arg)1330 dmu_objset_write_ready(zio_t *zio, arc_buf_t *abuf, void *arg)
1331 {
1332 	blkptr_t *bp = zio->io_bp;
1333 	objset_t *os = arg;
1334 	dnode_phys_t *dnp = &os->os_phys->os_meta_dnode;
1335 
1336 	ASSERT(!BP_IS_EMBEDDED(bp));
1337 	ASSERT3U(BP_GET_TYPE(bp), ==, DMU_OT_OBJSET);
1338 	ASSERT0(BP_GET_LEVEL(bp));
1339 
1340 	/*
1341 	 * Update rootbp fill count: it should be the number of objects
1342 	 * allocated in the object set (not counting the "special"
1343 	 * objects that are stored in the objset_phys_t -- the meta
1344 	 * dnode and user/group accounting objects).
1345 	 */
1346 	bp->blk_fill = 0;
1347 	for (int i = 0; i < dnp->dn_nblkptr; i++)
1348 		bp->blk_fill += BP_GET_FILL(&dnp->dn_blkptr[i]);
1349 	if (os->os_dsl_dataset != NULL)
1350 		rrw_enter(&os->os_dsl_dataset->ds_bp_rwlock, RW_WRITER, FTAG);
1351 	*os->os_rootbp = *bp;
1352 	if (os->os_dsl_dataset != NULL)
1353 		rrw_exit(&os->os_dsl_dataset->ds_bp_rwlock, FTAG);
1354 }
1355 
1356 /* ARGSUSED */
1357 static void
dmu_objset_write_done(zio_t * zio,arc_buf_t * abuf,void * arg)1358 dmu_objset_write_done(zio_t *zio, arc_buf_t *abuf, void *arg)
1359 {
1360 	blkptr_t *bp = zio->io_bp;
1361 	blkptr_t *bp_orig = &zio->io_bp_orig;
1362 	objset_t *os = arg;
1363 
1364 	if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
1365 		ASSERT(BP_EQUAL(bp, bp_orig));
1366 	} else {
1367 		dsl_dataset_t *ds = os->os_dsl_dataset;
1368 		dmu_tx_t *tx = os->os_synctx;
1369 
1370 		(void) dsl_dataset_block_kill(ds, bp_orig, tx, B_TRUE);
1371 		dsl_dataset_block_born(ds, bp, tx);
1372 	}
1373 	kmem_free(bp, sizeof (*bp));
1374 }
1375 
1376 typedef struct sync_dnodes_arg {
1377 	multilist_t *sda_list;
1378 	int sda_sublist_idx;
1379 	multilist_t *sda_newlist;
1380 	dmu_tx_t *sda_tx;
1381 } sync_dnodes_arg_t;
1382 
1383 static void
sync_dnodes_task(void * arg)1384 sync_dnodes_task(void *arg)
1385 {
1386 	sync_dnodes_arg_t *sda = arg;
1387 
1388 	multilist_sublist_t *ms =
1389 	    multilist_sublist_lock(sda->sda_list, sda->sda_sublist_idx);
1390 
1391 	dmu_objset_sync_dnodes(ms, sda->sda_tx);
1392 
1393 	multilist_sublist_unlock(ms);
1394 
1395 	kmem_free(sda, sizeof (*sda));
1396 }
1397 
1398 
1399 /* called from dsl */
1400 void
dmu_objset_sync(objset_t * os,zio_t * pio,dmu_tx_t * tx)1401 dmu_objset_sync(objset_t *os, zio_t *pio, dmu_tx_t *tx)
1402 {
1403 	int txgoff;
1404 	zbookmark_phys_t zb;
1405 	zio_prop_t zp;
1406 	zio_t *zio;
1407 	list_t *list;
1408 	dbuf_dirty_record_t *dr;
1409 	int num_sublists;
1410 	multilist_t *ml;
1411 	blkptr_t *blkptr_copy = kmem_alloc(sizeof (*os->os_rootbp), KM_SLEEP);
1412 	*blkptr_copy = *os->os_rootbp;
1413 
1414 	dprintf_ds(os->os_dsl_dataset, "txg=%llu\n", tx->tx_txg);
1415 
1416 	ASSERT(dmu_tx_is_syncing(tx));
1417 	/* XXX the write_done callback should really give us the tx... */
1418 	os->os_synctx = tx;
1419 
1420 	if (os->os_dsl_dataset == NULL) {
1421 		/*
1422 		 * This is the MOS.  If we have upgraded,
1423 		 * spa_max_replication() could change, so reset
1424 		 * os_copies here.
1425 		 */
1426 		os->os_copies = spa_max_replication(os->os_spa);
1427 	}
1428 
1429 	/*
1430 	 * Create the root block IO
1431 	 */
1432 	SET_BOOKMARK(&zb, os->os_dsl_dataset ?
1433 	    os->os_dsl_dataset->ds_object : DMU_META_OBJSET,
1434 	    ZB_ROOT_OBJECT, ZB_ROOT_LEVEL, ZB_ROOT_BLKID);
1435 	arc_release(os->os_phys_buf, &os->os_phys_buf);
1436 
1437 	dmu_write_policy(os, NULL, 0, 0, &zp);
1438 
1439 	zio = arc_write(pio, os->os_spa, tx->tx_txg,
1440 	    blkptr_copy, os->os_phys_buf, DMU_OS_IS_L2CACHEABLE(os),
1441 	    &zp, dmu_objset_write_ready, NULL, NULL, dmu_objset_write_done,
1442 	    os, ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_MUSTSUCCEED, &zb);
1443 
1444 	/*
1445 	 * Sync special dnodes - the parent IO for the sync is the root block
1446 	 */
1447 	DMU_META_DNODE(os)->dn_zio = zio;
1448 	dnode_sync(DMU_META_DNODE(os), tx);
1449 
1450 	os->os_phys->os_flags = os->os_flags;
1451 
1452 	if (DMU_USERUSED_DNODE(os) &&
1453 	    DMU_USERUSED_DNODE(os)->dn_type != DMU_OT_NONE) {
1454 		DMU_USERUSED_DNODE(os)->dn_zio = zio;
1455 		dnode_sync(DMU_USERUSED_DNODE(os), tx);
1456 		DMU_GROUPUSED_DNODE(os)->dn_zio = zio;
1457 		dnode_sync(DMU_GROUPUSED_DNODE(os), tx);
1458 	}
1459 
1460 	txgoff = tx->tx_txg & TXG_MASK;
1461 
1462 	if (dmu_objset_userused_enabled(os)) {
1463 		/*
1464 		 * We must create the list here because it uses the
1465 		 * dn_dirty_link[] of this txg.  But it may already
1466 		 * exist because we call dsl_dataset_sync() twice per txg.
1467 		 */
1468 		if (os->os_synced_dnodes == NULL) {
1469 			os->os_synced_dnodes =
1470 			    multilist_create(sizeof (dnode_t),
1471 			    offsetof(dnode_t, dn_dirty_link[txgoff]),
1472 			    dnode_multilist_index_func);
1473 		} else {
1474 			ASSERT3U(os->os_synced_dnodes->ml_offset, ==,
1475 			    offsetof(dnode_t, dn_dirty_link[txgoff]));
1476 		}
1477 	}
1478 
1479 	ml = os->os_dirty_dnodes[txgoff];
1480 	num_sublists = multilist_get_num_sublists(ml);
1481 	for (int i = 0; i < num_sublists; i++) {
1482 		if (multilist_sublist_is_empty_idx(ml, i))
1483 			continue;
1484 		sync_dnodes_arg_t *sda = kmem_alloc(sizeof (*sda), KM_SLEEP);
1485 		sda->sda_list = ml;
1486 		sda->sda_sublist_idx = i;
1487 		sda->sda_tx = tx;
1488 		(void) taskq_dispatch(dmu_objset_pool(os)->dp_sync_taskq,
1489 		    sync_dnodes_task, sda, 0);
1490 		/* callback frees sda */
1491 	}
1492 	taskq_wait(dmu_objset_pool(os)->dp_sync_taskq);
1493 
1494 	list = &DMU_META_DNODE(os)->dn_dirty_records[txgoff];
1495 	while ((dr = list_head(list)) != NULL) {
1496 		ASSERT0(dr->dr_dbuf->db_level);
1497 		list_remove(list, dr);
1498 		if (dr->dr_zio)
1499 			zio_nowait(dr->dr_zio);
1500 	}
1501 
1502 	/* Enable dnode backfill if enough objects have been freed. */
1503 	if (os->os_freed_dnodes >= dmu_rescan_dnode_threshold) {
1504 		os->os_rescan_dnodes = B_TRUE;
1505 		os->os_freed_dnodes = 0;
1506 	}
1507 
1508 	/*
1509 	 * Free intent log blocks up to this tx.
1510 	 */
1511 	zil_sync(os->os_zil, tx);
1512 	os->os_phys->os_zil_header = os->os_zil_header;
1513 	zio_nowait(zio);
1514 }
1515 
1516 boolean_t
dmu_objset_is_dirty(objset_t * os,uint64_t txg)1517 dmu_objset_is_dirty(objset_t *os, uint64_t txg)
1518 {
1519 	return (!multilist_is_empty(os->os_dirty_dnodes[txg & TXG_MASK]));
1520 }
1521 
1522 static objset_used_cb_t *used_cbs[DMU_OST_NUMTYPES];
1523 
1524 void
dmu_objset_register_type(dmu_objset_type_t ost,objset_used_cb_t * cb)1525 dmu_objset_register_type(dmu_objset_type_t ost, objset_used_cb_t *cb)
1526 {
1527 	used_cbs[ost] = cb;
1528 }
1529 
1530 boolean_t
dmu_objset_userused_enabled(objset_t * os)1531 dmu_objset_userused_enabled(objset_t *os)
1532 {
1533 	return (spa_version(os->os_spa) >= SPA_VERSION_USERSPACE &&
1534 	    used_cbs[os->os_phys->os_type] != NULL &&
1535 	    DMU_USERUSED_DNODE(os) != NULL);
1536 }
1537 
1538 typedef struct userquota_node {
1539 	uint64_t uqn_id;
1540 	int64_t uqn_delta;
1541 	avl_node_t uqn_node;
1542 } userquota_node_t;
1543 
1544 typedef struct userquota_cache {
1545 	avl_tree_t uqc_user_deltas;
1546 	avl_tree_t uqc_group_deltas;
1547 } userquota_cache_t;
1548 
1549 static int
userquota_compare(const void * l,const void * r)1550 userquota_compare(const void *l, const void *r)
1551 {
1552 	const userquota_node_t *luqn = l;
1553 	const userquota_node_t *ruqn = r;
1554 
1555 	if (luqn->uqn_id < ruqn->uqn_id)
1556 		return (-1);
1557 	if (luqn->uqn_id > ruqn->uqn_id)
1558 		return (1);
1559 	return (0);
1560 }
1561 
1562 static void
do_userquota_cacheflush(objset_t * os,userquota_cache_t * cache,dmu_tx_t * tx)1563 do_userquota_cacheflush(objset_t *os, userquota_cache_t *cache, dmu_tx_t *tx)
1564 {
1565 	void *cookie;
1566 	userquota_node_t *uqn;
1567 
1568 	ASSERT(dmu_tx_is_syncing(tx));
1569 
1570 	cookie = NULL;
1571 	while ((uqn = avl_destroy_nodes(&cache->uqc_user_deltas,
1572 	    &cookie)) != NULL) {
1573 		/*
1574 		 * os_userused_lock protects against concurrent calls to
1575 		 * zap_increment_int().  It's needed because zap_increment_int()
1576 		 * is not thread-safe (i.e. not atomic).
1577 		 */
1578 		mutex_enter(&os->os_userused_lock);
1579 		VERIFY0(zap_increment_int(os, DMU_USERUSED_OBJECT,
1580 		    uqn->uqn_id, uqn->uqn_delta, tx));
1581 		mutex_exit(&os->os_userused_lock);
1582 		kmem_free(uqn, sizeof (*uqn));
1583 	}
1584 	avl_destroy(&cache->uqc_user_deltas);
1585 
1586 	cookie = NULL;
1587 	while ((uqn = avl_destroy_nodes(&cache->uqc_group_deltas,
1588 	    &cookie)) != NULL) {
1589 		mutex_enter(&os->os_userused_lock);
1590 		VERIFY0(zap_increment_int(os, DMU_GROUPUSED_OBJECT,
1591 		    uqn->uqn_id, uqn->uqn_delta, tx));
1592 		mutex_exit(&os->os_userused_lock);
1593 		kmem_free(uqn, sizeof (*uqn));
1594 	}
1595 	avl_destroy(&cache->uqc_group_deltas);
1596 }
1597 
1598 static void
userquota_update_cache(avl_tree_t * avl,uint64_t id,int64_t delta)1599 userquota_update_cache(avl_tree_t *avl, uint64_t id, int64_t delta)
1600 {
1601 	userquota_node_t search = { .uqn_id = id };
1602 	avl_index_t idx;
1603 
1604 	userquota_node_t *uqn = avl_find(avl, &search, &idx);
1605 	if (uqn == NULL) {
1606 		uqn = kmem_zalloc(sizeof (*uqn), KM_SLEEP);
1607 		uqn->uqn_id = id;
1608 		avl_insert(avl, uqn, idx);
1609 	}
1610 	uqn->uqn_delta += delta;
1611 }
1612 
1613 static void
do_userquota_update(userquota_cache_t * cache,uint64_t used,uint64_t flags,uint64_t user,uint64_t group,boolean_t subtract)1614 do_userquota_update(userquota_cache_t *cache, uint64_t used, uint64_t flags,
1615     uint64_t user, uint64_t group, boolean_t subtract)
1616 {
1617 	if ((flags & DNODE_FLAG_USERUSED_ACCOUNTED)) {
1618 		int64_t delta = DNODE_MIN_SIZE + used;
1619 		if (subtract)
1620 			delta = -delta;
1621 
1622 		userquota_update_cache(&cache->uqc_user_deltas, user, delta);
1623 		userquota_update_cache(&cache->uqc_group_deltas, group, delta);
1624 	}
1625 }
1626 
1627 typedef struct userquota_updates_arg {
1628 	objset_t *uua_os;
1629 	int uua_sublist_idx;
1630 	dmu_tx_t *uua_tx;
1631 } userquota_updates_arg_t;
1632 
1633 static void
userquota_updates_task(void * arg)1634 userquota_updates_task(void *arg)
1635 {
1636 	userquota_updates_arg_t *uua = arg;
1637 	objset_t *os = uua->uua_os;
1638 	dmu_tx_t *tx = uua->uua_tx;
1639 	dnode_t *dn;
1640 	userquota_cache_t cache = { 0 };
1641 
1642 	multilist_sublist_t *list =
1643 	    multilist_sublist_lock(os->os_synced_dnodes, uua->uua_sublist_idx);
1644 
1645 	ASSERT(multilist_sublist_head(list) == NULL ||
1646 	    dmu_objset_userused_enabled(os));
1647 	avl_create(&cache.uqc_user_deltas, userquota_compare,
1648 	    sizeof (userquota_node_t), offsetof(userquota_node_t, uqn_node));
1649 	avl_create(&cache.uqc_group_deltas, userquota_compare,
1650 	    sizeof (userquota_node_t), offsetof(userquota_node_t, uqn_node));
1651 
1652 	while ((dn = multilist_sublist_head(list)) != NULL) {
1653 		int flags;
1654 		ASSERT(!DMU_OBJECT_IS_SPECIAL(dn->dn_object));
1655 		ASSERT(dn->dn_phys->dn_type == DMU_OT_NONE ||
1656 		    dn->dn_phys->dn_flags &
1657 		    DNODE_FLAG_USERUSED_ACCOUNTED);
1658 
1659 		flags = dn->dn_id_flags;
1660 		ASSERT(flags);
1661 		if (flags & DN_ID_OLD_EXIST)  {
1662 			do_userquota_update(&cache,
1663 			    dn->dn_oldused, dn->dn_oldflags,
1664 			    dn->dn_olduid, dn->dn_oldgid, B_TRUE);
1665 		}
1666 		if (flags & DN_ID_NEW_EXIST) {
1667 			do_userquota_update(&cache,
1668 			    DN_USED_BYTES(dn->dn_phys),
1669 			    dn->dn_phys->dn_flags,  dn->dn_newuid,
1670 			    dn->dn_newgid, B_FALSE);
1671 		}
1672 
1673 		mutex_enter(&dn->dn_mtx);
1674 		dn->dn_oldused = 0;
1675 		dn->dn_oldflags = 0;
1676 		if (dn->dn_id_flags & DN_ID_NEW_EXIST) {
1677 			dn->dn_olduid = dn->dn_newuid;
1678 			dn->dn_oldgid = dn->dn_newgid;
1679 			dn->dn_id_flags |= DN_ID_OLD_EXIST;
1680 			if (dn->dn_bonuslen == 0)
1681 				dn->dn_id_flags |= DN_ID_CHKED_SPILL;
1682 			else
1683 				dn->dn_id_flags |= DN_ID_CHKED_BONUS;
1684 		}
1685 		dn->dn_id_flags &= ~(DN_ID_NEW_EXIST);
1686 		if (dn->dn_dirty_txg == spa_syncing_txg(os->os_spa))
1687 			dn->dn_dirty_txg = 0;
1688 		mutex_exit(&dn->dn_mtx);
1689 
1690 		multilist_sublist_remove(list, dn);
1691 		dnode_rele(dn, os->os_synced_dnodes);
1692 	}
1693 	do_userquota_cacheflush(os, &cache, tx);
1694 	multilist_sublist_unlock(list);
1695 	kmem_free(uua, sizeof (*uua));
1696 }
1697 
1698 void
dmu_objset_do_userquota_updates(objset_t * os,dmu_tx_t * tx)1699 dmu_objset_do_userquota_updates(objset_t *os, dmu_tx_t *tx)
1700 {
1701 	int num_sublists;
1702 
1703 	if (!dmu_objset_userused_enabled(os))
1704 		return;
1705 
1706 	/* Allocate the user/groupused objects if necessary. */
1707 	if (DMU_USERUSED_DNODE(os)->dn_type == DMU_OT_NONE) {
1708 		VERIFY0(zap_create_claim(os,
1709 		    DMU_USERUSED_OBJECT,
1710 		    DMU_OT_USERGROUP_USED, DMU_OT_NONE, 0, tx));
1711 		VERIFY0(zap_create_claim(os,
1712 		    DMU_GROUPUSED_OBJECT,
1713 		    DMU_OT_USERGROUP_USED, DMU_OT_NONE, 0, tx));
1714 	}
1715 
1716 	num_sublists = multilist_get_num_sublists(os->os_synced_dnodes);
1717 	for (int i = 0; i < num_sublists; i++) {
1718 		if (multilist_sublist_is_empty_idx(os->os_synced_dnodes, i))
1719 			continue;
1720 		userquota_updates_arg_t *uua =
1721 		    kmem_alloc(sizeof (*uua), KM_SLEEP);
1722 		uua->uua_os = os;
1723 		uua->uua_sublist_idx = i;
1724 		uua->uua_tx = tx;
1725 		/* note: caller does taskq_wait() */
1726 		(void) taskq_dispatch(dmu_objset_pool(os)->dp_sync_taskq,
1727 		    userquota_updates_task, uua, 0);
1728 		/* callback frees uua */
1729 	}
1730 }
1731 
1732 /*
1733  * Returns a pointer to data to find uid/gid from
1734  *
1735  * If a dirty record for transaction group that is syncing can't
1736  * be found then NULL is returned.  In the NULL case it is assumed
1737  * the uid/gid aren't changing.
1738  */
1739 static void *
dmu_objset_userquota_find_data(dmu_buf_impl_t * db,dmu_tx_t * tx)1740 dmu_objset_userquota_find_data(dmu_buf_impl_t *db, dmu_tx_t *tx)
1741 {
1742 	dbuf_dirty_record_t *dr, **drp;
1743 	void *data;
1744 
1745 	if (db->db_dirtycnt == 0)
1746 		return (db->db.db_data);  /* Nothing is changing */
1747 
1748 	for (drp = &db->db_last_dirty; (dr = *drp) != NULL; drp = &dr->dr_next)
1749 		if (dr->dr_txg == tx->tx_txg)
1750 			break;
1751 
1752 	if (dr == NULL) {
1753 		data = NULL;
1754 	} else {
1755 		dnode_t *dn;
1756 
1757 		DB_DNODE_ENTER(dr->dr_dbuf);
1758 		dn = DB_DNODE(dr->dr_dbuf);
1759 
1760 		if (dn->dn_bonuslen == 0 &&
1761 		    dr->dr_dbuf->db_blkid == DMU_SPILL_BLKID)
1762 			data = dr->dt.dl.dr_data->b_data;
1763 		else
1764 			data = dr->dt.dl.dr_data;
1765 
1766 		DB_DNODE_EXIT(dr->dr_dbuf);
1767 	}
1768 
1769 	return (data);
1770 }
1771 
1772 void
dmu_objset_userquota_get_ids(dnode_t * dn,boolean_t before,dmu_tx_t * tx)1773 dmu_objset_userquota_get_ids(dnode_t *dn, boolean_t before, dmu_tx_t *tx)
1774 {
1775 	objset_t *os = dn->dn_objset;
1776 	void *data = NULL;
1777 	dmu_buf_impl_t *db = NULL;
1778 	uint64_t *user = NULL;
1779 	uint64_t *group = NULL;
1780 	int flags = dn->dn_id_flags;
1781 	int error;
1782 	boolean_t have_spill = B_FALSE;
1783 
1784 	if (!dmu_objset_userused_enabled(dn->dn_objset))
1785 		return;
1786 
1787 	if (before && (flags & (DN_ID_CHKED_BONUS|DN_ID_OLD_EXIST|
1788 	    DN_ID_CHKED_SPILL)))
1789 		return;
1790 
1791 	if (before && dn->dn_bonuslen != 0)
1792 		data = DN_BONUS(dn->dn_phys);
1793 	else if (!before && dn->dn_bonuslen != 0) {
1794 		if (dn->dn_bonus) {
1795 			db = dn->dn_bonus;
1796 			mutex_enter(&db->db_mtx);
1797 			data = dmu_objset_userquota_find_data(db, tx);
1798 		} else {
1799 			data = DN_BONUS(dn->dn_phys);
1800 		}
1801 	} else if (dn->dn_bonuslen == 0 && dn->dn_bonustype == DMU_OT_SA) {
1802 			int rf = 0;
1803 
1804 			if (RW_WRITE_HELD(&dn->dn_struct_rwlock))
1805 				rf |= DB_RF_HAVESTRUCT;
1806 			error = dmu_spill_hold_by_dnode(dn,
1807 			    rf | DB_RF_MUST_SUCCEED,
1808 			    FTAG, (dmu_buf_t **)&db);
1809 			ASSERT(error == 0);
1810 			mutex_enter(&db->db_mtx);
1811 			data = (before) ? db->db.db_data :
1812 			    dmu_objset_userquota_find_data(db, tx);
1813 			have_spill = B_TRUE;
1814 	} else {
1815 		mutex_enter(&dn->dn_mtx);
1816 		dn->dn_id_flags |= DN_ID_CHKED_BONUS;
1817 		mutex_exit(&dn->dn_mtx);
1818 		return;
1819 	}
1820 
1821 	if (before) {
1822 		ASSERT(data);
1823 		user = &dn->dn_olduid;
1824 		group = &dn->dn_oldgid;
1825 	} else if (data) {
1826 		user = &dn->dn_newuid;
1827 		group = &dn->dn_newgid;
1828 	}
1829 
1830 	/*
1831 	 * Must always call the callback in case the object
1832 	 * type has changed and that type isn't an object type to track
1833 	 */
1834 	error = used_cbs[os->os_phys->os_type](dn->dn_bonustype, data,
1835 	    user, group);
1836 
1837 	/*
1838 	 * Preserve existing uid/gid when the callback can't determine
1839 	 * what the new uid/gid are and the callback returned EEXIST.
1840 	 * The EEXIST error tells us to just use the existing uid/gid.
1841 	 * If we don't know what the old values are then just assign
1842 	 * them to 0, since that is a new file  being created.
1843 	 */
1844 	if (!before && data == NULL && error == EEXIST) {
1845 		if (flags & DN_ID_OLD_EXIST) {
1846 			dn->dn_newuid = dn->dn_olduid;
1847 			dn->dn_newgid = dn->dn_oldgid;
1848 		} else {
1849 			dn->dn_newuid = 0;
1850 			dn->dn_newgid = 0;
1851 		}
1852 		error = 0;
1853 	}
1854 
1855 	if (db)
1856 		mutex_exit(&db->db_mtx);
1857 
1858 	mutex_enter(&dn->dn_mtx);
1859 	if (error == 0 && before)
1860 		dn->dn_id_flags |= DN_ID_OLD_EXIST;
1861 	if (error == 0 && !before)
1862 		dn->dn_id_flags |= DN_ID_NEW_EXIST;
1863 
1864 	if (have_spill) {
1865 		dn->dn_id_flags |= DN_ID_CHKED_SPILL;
1866 	} else {
1867 		dn->dn_id_flags |= DN_ID_CHKED_BONUS;
1868 	}
1869 	mutex_exit(&dn->dn_mtx);
1870 	if (have_spill)
1871 		dmu_buf_rele((dmu_buf_t *)db, FTAG);
1872 }
1873 
1874 boolean_t
dmu_objset_userspace_present(objset_t * os)1875 dmu_objset_userspace_present(objset_t *os)
1876 {
1877 	return (os->os_phys->os_flags &
1878 	    OBJSET_FLAG_USERACCOUNTING_COMPLETE);
1879 }
1880 
1881 int
dmu_objset_userspace_upgrade(objset_t * os)1882 dmu_objset_userspace_upgrade(objset_t *os)
1883 {
1884 	uint64_t obj;
1885 	int err = 0;
1886 
1887 	if (dmu_objset_userspace_present(os))
1888 		return (0);
1889 	if (!dmu_objset_userused_enabled(os))
1890 		return (SET_ERROR(ENOTSUP));
1891 	if (dmu_objset_is_snapshot(os))
1892 		return (SET_ERROR(EINVAL));
1893 
1894 	/*
1895 	 * We simply need to mark every object dirty, so that it will be
1896 	 * synced out and now accounted.  If this is called
1897 	 * concurrently, or if we already did some work before crashing,
1898 	 * that's fine, since we track each object's accounted state
1899 	 * independently.
1900 	 */
1901 
1902 	for (obj = 0; err == 0; err = dmu_object_next(os, &obj, FALSE, 0)) {
1903 		dmu_tx_t *tx;
1904 		dmu_buf_t *db;
1905 		int objerr;
1906 
1907 		if (issig(JUSTLOOKING) && issig(FORREAL))
1908 			return (SET_ERROR(EINTR));
1909 
1910 		objerr = dmu_bonus_hold(os, obj, FTAG, &db);
1911 		if (objerr != 0)
1912 			continue;
1913 		tx = dmu_tx_create(os);
1914 		dmu_tx_hold_bonus(tx, obj);
1915 		objerr = dmu_tx_assign(tx, TXG_WAIT);
1916 		if (objerr != 0) {
1917 			dmu_tx_abort(tx);
1918 			continue;
1919 		}
1920 		dmu_buf_will_dirty(db, tx);
1921 		dmu_buf_rele(db, FTAG);
1922 		dmu_tx_commit(tx);
1923 	}
1924 
1925 	os->os_flags |= OBJSET_FLAG_USERACCOUNTING_COMPLETE;
1926 	txg_wait_synced(dmu_objset_pool(os), 0);
1927 	return (0);
1928 }
1929 
1930 void
dmu_objset_space(objset_t * os,uint64_t * refdbytesp,uint64_t * availbytesp,uint64_t * usedobjsp,uint64_t * availobjsp)1931 dmu_objset_space(objset_t *os, uint64_t *refdbytesp, uint64_t *availbytesp,
1932     uint64_t *usedobjsp, uint64_t *availobjsp)
1933 {
1934 	dsl_dataset_space(os->os_dsl_dataset, refdbytesp, availbytesp,
1935 	    usedobjsp, availobjsp);
1936 }
1937 
1938 uint64_t
dmu_objset_fsid_guid(objset_t * os)1939 dmu_objset_fsid_guid(objset_t *os)
1940 {
1941 	return (dsl_dataset_fsid_guid(os->os_dsl_dataset));
1942 }
1943 
1944 void
dmu_objset_fast_stat(objset_t * os,dmu_objset_stats_t * stat)1945 dmu_objset_fast_stat(objset_t *os, dmu_objset_stats_t *stat)
1946 {
1947 	stat->dds_type = os->os_phys->os_type;
1948 	if (os->os_dsl_dataset)
1949 		dsl_dataset_fast_stat(os->os_dsl_dataset, stat);
1950 }
1951 
1952 void
dmu_objset_stats(objset_t * os,nvlist_t * nv)1953 dmu_objset_stats(objset_t *os, nvlist_t *nv)
1954 {
1955 	ASSERT(os->os_dsl_dataset ||
1956 	    os->os_phys->os_type == DMU_OST_META);
1957 
1958 	if (os->os_dsl_dataset != NULL)
1959 		dsl_dataset_stats(os->os_dsl_dataset, nv);
1960 
1961 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_TYPE,
1962 	    os->os_phys->os_type);
1963 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USERACCOUNTING,
1964 	    dmu_objset_userspace_present(os));
1965 }
1966 
1967 int
dmu_objset_is_snapshot(objset_t * os)1968 dmu_objset_is_snapshot(objset_t *os)
1969 {
1970 	if (os->os_dsl_dataset != NULL)
1971 		return (os->os_dsl_dataset->ds_is_snapshot);
1972 	else
1973 		return (B_FALSE);
1974 }
1975 
1976 int
dmu_snapshot_realname(objset_t * os,char * name,char * real,int maxlen,boolean_t * conflict)1977 dmu_snapshot_realname(objset_t *os, char *name, char *real, int maxlen,
1978     boolean_t *conflict)
1979 {
1980 	dsl_dataset_t *ds = os->os_dsl_dataset;
1981 	uint64_t ignored;
1982 
1983 	if (dsl_dataset_phys(ds)->ds_snapnames_zapobj == 0)
1984 		return (SET_ERROR(ENOENT));
1985 
1986 	return (zap_lookup_norm(ds->ds_dir->dd_pool->dp_meta_objset,
1987 	    dsl_dataset_phys(ds)->ds_snapnames_zapobj, name, 8, 1, &ignored,
1988 	    MT_NORMALIZE, real, maxlen, conflict));
1989 }
1990 
1991 int
dmu_snapshot_list_next(objset_t * os,int namelen,char * name,uint64_t * idp,uint64_t * offp,boolean_t * case_conflict)1992 dmu_snapshot_list_next(objset_t *os, int namelen, char *name,
1993     uint64_t *idp, uint64_t *offp, boolean_t *case_conflict)
1994 {
1995 	dsl_dataset_t *ds = os->os_dsl_dataset;
1996 	zap_cursor_t cursor;
1997 	zap_attribute_t attr;
1998 
1999 	ASSERT(dsl_pool_config_held(dmu_objset_pool(os)));
2000 
2001 	if (dsl_dataset_phys(ds)->ds_snapnames_zapobj == 0)
2002 		return (SET_ERROR(ENOENT));
2003 
2004 	zap_cursor_init_serialized(&cursor,
2005 	    ds->ds_dir->dd_pool->dp_meta_objset,
2006 	    dsl_dataset_phys(ds)->ds_snapnames_zapobj, *offp);
2007 
2008 	if (zap_cursor_retrieve(&cursor, &attr) != 0) {
2009 		zap_cursor_fini(&cursor);
2010 		return (SET_ERROR(ENOENT));
2011 	}
2012 
2013 	if (strlen(attr.za_name) + 1 > namelen) {
2014 		zap_cursor_fini(&cursor);
2015 		return (SET_ERROR(ENAMETOOLONG));
2016 	}
2017 
2018 	(void) strcpy(name, attr.za_name);
2019 	if (idp)
2020 		*idp = attr.za_first_integer;
2021 	if (case_conflict)
2022 		*case_conflict = attr.za_normalization_conflict;
2023 	zap_cursor_advance(&cursor);
2024 	*offp = zap_cursor_serialize(&cursor);
2025 	zap_cursor_fini(&cursor);
2026 
2027 	return (0);
2028 }
2029 
2030 int
dmu_dir_list_next(objset_t * os,int namelen,char * name,uint64_t * idp,uint64_t * offp)2031 dmu_dir_list_next(objset_t *os, int namelen, char *name,
2032     uint64_t *idp, uint64_t *offp)
2033 {
2034 	dsl_dir_t *dd = os->os_dsl_dataset->ds_dir;
2035 	zap_cursor_t cursor;
2036 	zap_attribute_t attr;
2037 
2038 	/* there is no next dir on a snapshot! */
2039 	if (os->os_dsl_dataset->ds_object !=
2040 	    dsl_dir_phys(dd)->dd_head_dataset_obj)
2041 		return (SET_ERROR(ENOENT));
2042 
2043 	zap_cursor_init_serialized(&cursor,
2044 	    dd->dd_pool->dp_meta_objset,
2045 	    dsl_dir_phys(dd)->dd_child_dir_zapobj, *offp);
2046 
2047 	if (zap_cursor_retrieve(&cursor, &attr) != 0) {
2048 		zap_cursor_fini(&cursor);
2049 		return (SET_ERROR(ENOENT));
2050 	}
2051 
2052 	if (strlen(attr.za_name) + 1 > namelen) {
2053 		zap_cursor_fini(&cursor);
2054 		return (SET_ERROR(ENAMETOOLONG));
2055 	}
2056 
2057 	(void) strcpy(name, attr.za_name);
2058 	if (idp)
2059 		*idp = attr.za_first_integer;
2060 	zap_cursor_advance(&cursor);
2061 	*offp = zap_cursor_serialize(&cursor);
2062 	zap_cursor_fini(&cursor);
2063 
2064 	return (0);
2065 }
2066 
2067 typedef struct dmu_objset_find_ctx {
2068 	taskq_t		*dc_tq;
2069 	dsl_pool_t	*dc_dp;
2070 	uint64_t	dc_ddobj;
2071 	char		*dc_ddname; /* last component of ddobj's name */
2072 	int		(*dc_func)(dsl_pool_t *, dsl_dataset_t *, void *);
2073 	void		*dc_arg;
2074 	int		dc_flags;
2075 	kmutex_t	*dc_error_lock;
2076 	int		*dc_error;
2077 } dmu_objset_find_ctx_t;
2078 
2079 static void
dmu_objset_find_dp_impl(dmu_objset_find_ctx_t * dcp)2080 dmu_objset_find_dp_impl(dmu_objset_find_ctx_t *dcp)
2081 {
2082 	dsl_pool_t *dp = dcp->dc_dp;
2083 	dsl_dir_t *dd;
2084 	dsl_dataset_t *ds;
2085 	zap_cursor_t zc;
2086 	zap_attribute_t *attr;
2087 	uint64_t thisobj;
2088 	int err = 0;
2089 
2090 	/* don't process if there already was an error */
2091 	if (*dcp->dc_error != 0)
2092 		goto out;
2093 
2094 	/*
2095 	 * Note: passing the name (dc_ddname) here is optional, but it
2096 	 * improves performance because we don't need to call
2097 	 * zap_value_search() to determine the name.
2098 	 */
2099 	err = dsl_dir_hold_obj(dp, dcp->dc_ddobj, dcp->dc_ddname, FTAG, &dd);
2100 	if (err != 0)
2101 		goto out;
2102 
2103 	/* Don't visit hidden ($MOS & $ORIGIN) objsets. */
2104 	if (dd->dd_myname[0] == '$') {
2105 		dsl_dir_rele(dd, FTAG);
2106 		goto out;
2107 	}
2108 
2109 	thisobj = dsl_dir_phys(dd)->dd_head_dataset_obj;
2110 	attr = kmem_alloc(sizeof (zap_attribute_t), KM_SLEEP);
2111 
2112 	/*
2113 	 * Iterate over all children.
2114 	 */
2115 	if (dcp->dc_flags & DS_FIND_CHILDREN) {
2116 		for (zap_cursor_init(&zc, dp->dp_meta_objset,
2117 		    dsl_dir_phys(dd)->dd_child_dir_zapobj);
2118 		    zap_cursor_retrieve(&zc, attr) == 0;
2119 		    (void) zap_cursor_advance(&zc)) {
2120 			ASSERT3U(attr->za_integer_length, ==,
2121 			    sizeof (uint64_t));
2122 			ASSERT3U(attr->za_num_integers, ==, 1);
2123 
2124 			dmu_objset_find_ctx_t *child_dcp =
2125 			    kmem_alloc(sizeof (*child_dcp), KM_SLEEP);
2126 			*child_dcp = *dcp;
2127 			child_dcp->dc_ddobj = attr->za_first_integer;
2128 			child_dcp->dc_ddname = spa_strdup(attr->za_name);
2129 			if (dcp->dc_tq != NULL)
2130 				(void) taskq_dispatch(dcp->dc_tq,
2131 				    dmu_objset_find_dp_cb, child_dcp, TQ_SLEEP);
2132 			else
2133 				dmu_objset_find_dp_impl(child_dcp);
2134 		}
2135 		zap_cursor_fini(&zc);
2136 	}
2137 
2138 	/*
2139 	 * Iterate over all snapshots.
2140 	 */
2141 	if (dcp->dc_flags & DS_FIND_SNAPSHOTS) {
2142 		dsl_dataset_t *ds;
2143 		err = dsl_dataset_hold_obj(dp, thisobj, FTAG, &ds);
2144 
2145 		if (err == 0) {
2146 			uint64_t snapobj;
2147 
2148 			snapobj = dsl_dataset_phys(ds)->ds_snapnames_zapobj;
2149 			dsl_dataset_rele(ds, FTAG);
2150 
2151 			for (zap_cursor_init(&zc, dp->dp_meta_objset, snapobj);
2152 			    zap_cursor_retrieve(&zc, attr) == 0;
2153 			    (void) zap_cursor_advance(&zc)) {
2154 				ASSERT3U(attr->za_integer_length, ==,
2155 				    sizeof (uint64_t));
2156 				ASSERT3U(attr->za_num_integers, ==, 1);
2157 
2158 				err = dsl_dataset_hold_obj(dp,
2159 				    attr->za_first_integer, FTAG, &ds);
2160 				if (err != 0)
2161 					break;
2162 				err = dcp->dc_func(dp, ds, dcp->dc_arg);
2163 				dsl_dataset_rele(ds, FTAG);
2164 				if (err != 0)
2165 					break;
2166 			}
2167 			zap_cursor_fini(&zc);
2168 		}
2169 	}
2170 
2171 	kmem_free(attr, sizeof (zap_attribute_t));
2172 
2173 	if (err != 0) {
2174 		dsl_dir_rele(dd, FTAG);
2175 		goto out;
2176 	}
2177 
2178 	/*
2179 	 * Apply to self.
2180 	 */
2181 	err = dsl_dataset_hold_obj(dp, thisobj, FTAG, &ds);
2182 
2183 	/*
2184 	 * Note: we hold the dir while calling dsl_dataset_hold_obj() so
2185 	 * that the dir will remain cached, and we won't have to re-instantiate
2186 	 * it (which could be expensive due to finding its name via
2187 	 * zap_value_search()).
2188 	 */
2189 	dsl_dir_rele(dd, FTAG);
2190 	if (err != 0)
2191 		goto out;
2192 	err = dcp->dc_func(dp, ds, dcp->dc_arg);
2193 	dsl_dataset_rele(ds, FTAG);
2194 
2195 out:
2196 	if (err != 0) {
2197 		mutex_enter(dcp->dc_error_lock);
2198 		/* only keep first error */
2199 		if (*dcp->dc_error == 0)
2200 			*dcp->dc_error = err;
2201 		mutex_exit(dcp->dc_error_lock);
2202 	}
2203 
2204 	if (dcp->dc_ddname != NULL)
2205 		spa_strfree(dcp->dc_ddname);
2206 	kmem_free(dcp, sizeof (*dcp));
2207 }
2208 
2209 static void
dmu_objset_find_dp_cb(void * arg)2210 dmu_objset_find_dp_cb(void *arg)
2211 {
2212 	dmu_objset_find_ctx_t *dcp = arg;
2213 	dsl_pool_t *dp = dcp->dc_dp;
2214 
2215 	/*
2216 	 * We need to get a pool_config_lock here, as there are several
2217 	 * asssert(pool_config_held) down the stack. Getting a lock via
2218 	 * dsl_pool_config_enter is risky, as it might be stalled by a
2219 	 * pending writer. This would deadlock, as the write lock can
2220 	 * only be granted when our parent thread gives up the lock.
2221 	 * The _prio interface gives us priority over a pending writer.
2222 	 */
2223 	dsl_pool_config_enter_prio(dp, FTAG);
2224 
2225 	dmu_objset_find_dp_impl(dcp);
2226 
2227 	dsl_pool_config_exit(dp, FTAG);
2228 }
2229 
2230 /*
2231  * Find objsets under and including ddobj, call func(ds) on each.
2232  * The order for the enumeration is completely undefined.
2233  * func is called with dsl_pool_config held.
2234  */
2235 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)2236 dmu_objset_find_dp(dsl_pool_t *dp, uint64_t ddobj,
2237     int func(dsl_pool_t *, dsl_dataset_t *, void *), void *arg, int flags)
2238 {
2239 	int error = 0;
2240 	taskq_t *tq = NULL;
2241 	int ntasks;
2242 	dmu_objset_find_ctx_t *dcp;
2243 	kmutex_t err_lock;
2244 
2245 	mutex_init(&err_lock, NULL, MUTEX_DEFAULT, NULL);
2246 	dcp = kmem_alloc(sizeof (*dcp), KM_SLEEP);
2247 	dcp->dc_tq = NULL;
2248 	dcp->dc_dp = dp;
2249 	dcp->dc_ddobj = ddobj;
2250 	dcp->dc_ddname = NULL;
2251 	dcp->dc_func = func;
2252 	dcp->dc_arg = arg;
2253 	dcp->dc_flags = flags;
2254 	dcp->dc_error_lock = &err_lock;
2255 	dcp->dc_error = &error;
2256 
2257 	if ((flags & DS_FIND_SERIALIZE) || dsl_pool_config_held_writer(dp)) {
2258 		/*
2259 		 * In case a write lock is held we can't make use of
2260 		 * parallelism, as down the stack of the worker threads
2261 		 * the lock is asserted via dsl_pool_config_held.
2262 		 * In case of a read lock this is solved by getting a read
2263 		 * lock in each worker thread, which isn't possible in case
2264 		 * of a writer lock. So we fall back to the synchronous path
2265 		 * here.
2266 		 * In the future it might be possible to get some magic into
2267 		 * dsl_pool_config_held in a way that it returns true for
2268 		 * the worker threads so that a single lock held from this
2269 		 * thread suffices. For now, stay single threaded.
2270 		 */
2271 		dmu_objset_find_dp_impl(dcp);
2272 		mutex_destroy(&err_lock);
2273 
2274 		return (error);
2275 	}
2276 
2277 	ntasks = dmu_find_threads;
2278 	if (ntasks == 0)
2279 		ntasks = vdev_count_leaves(dp->dp_spa) * 4;
2280 	tq = taskq_create("dmu_objset_find", ntasks, minclsyspri, ntasks,
2281 	    INT_MAX, 0);
2282 	if (tq == NULL) {
2283 		kmem_free(dcp, sizeof (*dcp));
2284 		mutex_destroy(&err_lock);
2285 
2286 		return (SET_ERROR(ENOMEM));
2287 	}
2288 	dcp->dc_tq = tq;
2289 
2290 	/* dcp will be freed by task */
2291 	(void) taskq_dispatch(tq, dmu_objset_find_dp_cb, dcp, TQ_SLEEP);
2292 
2293 	/*
2294 	 * PORTING: this code relies on the property of taskq_wait to wait
2295 	 * until no more tasks are queued and no more tasks are active. As
2296 	 * we always queue new tasks from within other tasks, task_wait
2297 	 * reliably waits for the full recursion to finish, even though we
2298 	 * enqueue new tasks after taskq_wait has been called.
2299 	 * On platforms other than illumos, taskq_wait may not have this
2300 	 * property.
2301 	 */
2302 	taskq_wait(tq);
2303 	taskq_destroy(tq);
2304 	mutex_destroy(&err_lock);
2305 
2306 	return (error);
2307 }
2308 
2309 /*
2310  * Find all objsets under name, and for each, call 'func(child_name, arg)'.
2311  * The dp_config_rwlock must not be held when this is called, and it
2312  * will not be held when the callback is called.
2313  * Therefore this function should only be used when the pool is not changing
2314  * (e.g. in syncing context), or the callback can deal with the possible races.
2315  */
2316 static int
dmu_objset_find_impl(spa_t * spa,const char * name,int func (const char *,void *),void * arg,int flags)2317 dmu_objset_find_impl(spa_t *spa, const char *name,
2318     int func(const char *, void *), void *arg, int flags)
2319 {
2320 	dsl_dir_t *dd;
2321 	dsl_pool_t *dp = spa_get_dsl(spa);
2322 	dsl_dataset_t *ds;
2323 	zap_cursor_t zc;
2324 	zap_attribute_t *attr;
2325 	char *child;
2326 	uint64_t thisobj;
2327 	int err;
2328 
2329 	dsl_pool_config_enter(dp, FTAG);
2330 
2331 	err = dsl_dir_hold(dp, name, FTAG, &dd, NULL);
2332 	if (err != 0) {
2333 		dsl_pool_config_exit(dp, FTAG);
2334 		return (err);
2335 	}
2336 
2337 	/* Don't visit hidden ($MOS & $ORIGIN) objsets. */
2338 	if (dd->dd_myname[0] == '$') {
2339 		dsl_dir_rele(dd, FTAG);
2340 		dsl_pool_config_exit(dp, FTAG);
2341 		return (0);
2342 	}
2343 
2344 	thisobj = dsl_dir_phys(dd)->dd_head_dataset_obj;
2345 	attr = kmem_alloc(sizeof (zap_attribute_t), KM_SLEEP);
2346 
2347 	/*
2348 	 * Iterate over all children.
2349 	 */
2350 	if (flags & DS_FIND_CHILDREN) {
2351 		for (zap_cursor_init(&zc, dp->dp_meta_objset,
2352 		    dsl_dir_phys(dd)->dd_child_dir_zapobj);
2353 		    zap_cursor_retrieve(&zc, attr) == 0;
2354 		    (void) zap_cursor_advance(&zc)) {
2355 			ASSERT3U(attr->za_integer_length, ==,
2356 			    sizeof (uint64_t));
2357 			ASSERT3U(attr->za_num_integers, ==, 1);
2358 
2359 			child = kmem_asprintf("%s/%s", name, attr->za_name);
2360 			dsl_pool_config_exit(dp, FTAG);
2361 			err = dmu_objset_find_impl(spa, child,
2362 			    func, arg, flags);
2363 			dsl_pool_config_enter(dp, FTAG);
2364 			strfree(child);
2365 			if (err != 0)
2366 				break;
2367 		}
2368 		zap_cursor_fini(&zc);
2369 
2370 		if (err != 0) {
2371 			dsl_dir_rele(dd, FTAG);
2372 			dsl_pool_config_exit(dp, FTAG);
2373 			kmem_free(attr, sizeof (zap_attribute_t));
2374 			return (err);
2375 		}
2376 	}
2377 
2378 	/*
2379 	 * Iterate over all snapshots.
2380 	 */
2381 	if (flags & DS_FIND_SNAPSHOTS) {
2382 		err = dsl_dataset_hold_obj(dp, thisobj, FTAG, &ds);
2383 
2384 		if (err == 0) {
2385 			uint64_t snapobj;
2386 
2387 			snapobj = dsl_dataset_phys(ds)->ds_snapnames_zapobj;
2388 			dsl_dataset_rele(ds, FTAG);
2389 
2390 			for (zap_cursor_init(&zc, dp->dp_meta_objset, snapobj);
2391 			    zap_cursor_retrieve(&zc, attr) == 0;
2392 			    (void) zap_cursor_advance(&zc)) {
2393 				ASSERT3U(attr->za_integer_length, ==,
2394 				    sizeof (uint64_t));
2395 				ASSERT3U(attr->za_num_integers, ==, 1);
2396 
2397 				child = kmem_asprintf("%s@%s",
2398 				    name, attr->za_name);
2399 				dsl_pool_config_exit(dp, FTAG);
2400 				err = func(child, arg);
2401 				dsl_pool_config_enter(dp, FTAG);
2402 				strfree(child);
2403 				if (err != 0)
2404 					break;
2405 			}
2406 			zap_cursor_fini(&zc);
2407 		}
2408 	}
2409 
2410 	dsl_dir_rele(dd, FTAG);
2411 	kmem_free(attr, sizeof (zap_attribute_t));
2412 	dsl_pool_config_exit(dp, FTAG);
2413 
2414 	if (err != 0)
2415 		return (err);
2416 
2417 	/* Apply to self. */
2418 	return (func(name, arg));
2419 }
2420 
2421 /*
2422  * See comment above dmu_objset_find_impl().
2423  */
2424 int
dmu_objset_find(char * name,int func (const char *,void *),void * arg,int flags)2425 dmu_objset_find(char *name, int func(const char *, void *), void *arg,
2426     int flags)
2427 {
2428 	spa_t *spa;
2429 	int error;
2430 
2431 	error = spa_open(name, &spa, FTAG);
2432 	if (error != 0)
2433 		return (error);
2434 	error = dmu_objset_find_impl(spa, name, func, arg, flags);
2435 	spa_close(spa, FTAG);
2436 	return (error);
2437 }
2438 
2439 void
dmu_objset_set_user(objset_t * os,void * user_ptr)2440 dmu_objset_set_user(objset_t *os, void *user_ptr)
2441 {
2442 	ASSERT(MUTEX_HELD(&os->os_user_ptr_lock));
2443 	os->os_user_ptr = user_ptr;
2444 }
2445 
2446 void *
dmu_objset_get_user(objset_t * os)2447 dmu_objset_get_user(objset_t *os)
2448 {
2449 	ASSERT(MUTEX_HELD(&os->os_user_ptr_lock));
2450 	return (os->os_user_ptr);
2451 }
2452 
2453 /*
2454  * Determine name of filesystem, given name of snapshot.
2455  * buf must be at least ZFS_MAX_DATASET_NAME_LEN bytes
2456  */
2457 int
dmu_fsname(const char * snapname,char * buf)2458 dmu_fsname(const char *snapname, char *buf)
2459 {
2460 	char *atp = strchr(snapname, '@');
2461 	if (atp == NULL)
2462 		return (SET_ERROR(EINVAL));
2463 	if (atp - snapname >= ZFS_MAX_DATASET_NAME_LEN)
2464 		return (SET_ERROR(ENAMETOOLONG));
2465 	(void) strlcpy(buf, snapname, atp - snapname + 1);
2466 	return (0);
2467 }
2468 
2469 /*
2470  * Call when we think we're going to write/free space in open context to track
2471  * the amount of dirty data in the open txg, which is also the amount
2472  * of memory that can not be evicted until this txg syncs.
2473  */
2474 void
dmu_objset_willuse_space(objset_t * os,int64_t space,dmu_tx_t * tx)2475 dmu_objset_willuse_space(objset_t *os, int64_t space, dmu_tx_t *tx)
2476 {
2477 	dsl_dataset_t *ds = os->os_dsl_dataset;
2478 	int64_t aspace = spa_get_worst_case_asize(os->os_spa, space);
2479 
2480 	if (ds != NULL) {
2481 		dsl_dir_willuse_space(ds->ds_dir, aspace, tx);
2482 		dsl_pool_dirty_space(dmu_tx_pool(tx), space, tx);
2483 	}
2484 }
2485