xref: /freebsd/sys/contrib/openzfs/module/zfs/dsl_pool.c (revision 9088779e3c8b810afb701adb80be154a7b2e0523)
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 https://opensource.org/licenses/CDDL-1.0.
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  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23  * Copyright (c) 2011, 2020 by Delphix. All rights reserved.
24  * Copyright (c) 2013 Steven Hartland. All rights reserved.
25  * Copyright (c) 2014 Spectra Logic Corporation, All rights reserved.
26  * Copyright 2016 Nexenta Systems, Inc.  All rights reserved.
27  */
28 
29 #include <sys/dsl_pool.h>
30 #include <sys/dsl_dataset.h>
31 #include <sys/dsl_prop.h>
32 #include <sys/dsl_dir.h>
33 #include <sys/dsl_synctask.h>
34 #include <sys/dsl_scan.h>
35 #include <sys/dnode.h>
36 #include <sys/dmu_tx.h>
37 #include <sys/dmu_objset.h>
38 #include <sys/arc.h>
39 #include <sys/zap.h>
40 #include <sys/zio.h>
41 #include <sys/zfs_context.h>
42 #include <sys/fs/zfs.h>
43 #include <sys/zfs_znode.h>
44 #include <sys/spa_impl.h>
45 #include <sys/vdev_impl.h>
46 #include <sys/metaslab_impl.h>
47 #include <sys/bptree.h>
48 #include <sys/zfeature.h>
49 #include <sys/zil_impl.h>
50 #include <sys/dsl_userhold.h>
51 #include <sys/trace_zfs.h>
52 #include <sys/mmp.h>
53 
54 /*
55  * ZFS Write Throttle
56  * ------------------
57  *
58  * ZFS must limit the rate of incoming writes to the rate at which it is able
59  * to sync data modifications to the backend storage. Throttling by too much
60  * creates an artificial limit; throttling by too little can only be sustained
61  * for short periods and would lead to highly lumpy performance. On a per-pool
62  * basis, ZFS tracks the amount of modified (dirty) data. As operations change
63  * data, the amount of dirty data increases; as ZFS syncs out data, the amount
64  * of dirty data decreases. When the amount of dirty data exceeds a
65  * predetermined threshold further modifications are blocked until the amount
66  * of dirty data decreases (as data is synced out).
67  *
68  * The limit on dirty data is tunable, and should be adjusted according to
69  * both the IO capacity and available memory of the system. The larger the
70  * window, the more ZFS is able to aggregate and amortize metadata (and data)
71  * changes. However, memory is a limited resource, and allowing for more dirty
72  * data comes at the cost of keeping other useful data in memory (for example
73  * ZFS data cached by the ARC).
74  *
75  * Implementation
76  *
77  * As buffers are modified dsl_pool_willuse_space() increments both the per-
78  * txg (dp_dirty_pertxg[]) and poolwide (dp_dirty_total) accounting of
79  * dirty space used; dsl_pool_dirty_space() decrements those values as data
80  * is synced out from dsl_pool_sync(). While only the poolwide value is
81  * relevant, the per-txg value is useful for debugging. The tunable
82  * zfs_dirty_data_max determines the dirty space limit. Once that value is
83  * exceeded, new writes are halted until space frees up.
84  *
85  * The zfs_dirty_data_sync_percent tunable dictates the threshold at which we
86  * ensure that there is a txg syncing (see the comment in txg.c for a full
87  * description of transaction group stages).
88  *
89  * The IO scheduler uses both the dirty space limit and current amount of
90  * dirty data as inputs. Those values affect the number of concurrent IOs ZFS
91  * issues. See the comment in vdev_queue.c for details of the IO scheduler.
92  *
93  * The delay is also calculated based on the amount of dirty data.  See the
94  * comment above dmu_tx_delay() for details.
95  */
96 
97 /*
98  * zfs_dirty_data_max will be set to zfs_dirty_data_max_percent% of all memory,
99  * capped at zfs_dirty_data_max_max.  It can also be overridden with a module
100  * parameter.
101  */
102 uint64_t zfs_dirty_data_max = 0;
103 uint64_t zfs_dirty_data_max_max = 0;
104 uint_t zfs_dirty_data_max_percent = 10;
105 uint_t zfs_dirty_data_max_max_percent = 25;
106 
107 /*
108  * The upper limit of TX_WRITE log data.  Write operations are throttled
109  * when approaching the limit until log data is cleared out after txg sync.
110  * It only counts TX_WRITE log with WR_COPIED or WR_NEED_COPY.
111  */
112 uint64_t zfs_wrlog_data_max = 0;
113 
114 /*
115  * If there's at least this much dirty data (as a percentage of
116  * zfs_dirty_data_max), push out a txg.  This should be less than
117  * zfs_vdev_async_write_active_min_dirty_percent.
118  */
119 static uint_t zfs_dirty_data_sync_percent = 20;
120 
121 /*
122  * Once there is this amount of dirty data, the dmu_tx_delay() will kick in
123  * and delay each transaction.
124  * This value should be >= zfs_vdev_async_write_active_max_dirty_percent.
125  */
126 uint_t zfs_delay_min_dirty_percent = 60;
127 
128 /*
129  * This controls how quickly the delay approaches infinity.
130  * Larger values cause it to delay more for a given amount of dirty data.
131  * Therefore larger values will cause there to be less dirty data for a
132  * given throughput.
133  *
134  * For the smoothest delay, this value should be about 1 billion divided
135  * by the maximum number of operations per second.  This will smoothly
136  * handle between 10x and 1/10th this number.
137  *
138  * Note: zfs_delay_scale * zfs_dirty_data_max must be < 2^64, due to the
139  * multiply in dmu_tx_delay().
140  */
141 uint64_t zfs_delay_scale = 1000 * 1000 * 1000 / 2000;
142 
143 /*
144  * This determines the number of threads used by the dp_sync_taskq.
145  */
146 static int zfs_sync_taskq_batch_pct = 75;
147 
148 /*
149  * These tunables determine the behavior of how zil_itxg_clean() is
150  * called via zil_clean() in the context of spa_sync(). When an itxg
151  * list needs to be cleaned, TQ_NOSLEEP will be used when dispatching.
152  * If the dispatch fails, the call to zil_itxg_clean() will occur
153  * synchronously in the context of spa_sync(), which can negatively
154  * impact the performance of spa_sync() (e.g. in the case of the itxg
155  * list having a large number of itxs that needs to be cleaned).
156  *
157  * Thus, these tunables can be used to manipulate the behavior of the
158  * taskq used by zil_clean(); they determine the number of taskq entries
159  * that are pre-populated when the taskq is first created (via the
160  * "zfs_zil_clean_taskq_minalloc" tunable) and the maximum number of
161  * taskq entries that are cached after an on-demand allocation (via the
162  * "zfs_zil_clean_taskq_maxalloc").
163  *
164  * The idea being, we want to try reasonably hard to ensure there will
165  * already be a taskq entry pre-allocated by the time that it is needed
166  * by zil_clean(). This way, we can avoid the possibility of an
167  * on-demand allocation of a new taskq entry from failing, which would
168  * result in zil_itxg_clean() being called synchronously from zil_clean()
169  * (which can adversely affect performance of spa_sync()).
170  *
171  * Additionally, the number of threads used by the taskq can be
172  * configured via the "zfs_zil_clean_taskq_nthr_pct" tunable.
173  */
174 static int zfs_zil_clean_taskq_nthr_pct = 100;
175 static int zfs_zil_clean_taskq_minalloc = 1024;
176 static int zfs_zil_clean_taskq_maxalloc = 1024 * 1024;
177 
178 int
179 dsl_pool_open_special_dir(dsl_pool_t *dp, const char *name, dsl_dir_t **ddp)
180 {
181 	uint64_t obj;
182 	int err;
183 
184 	err = zap_lookup(dp->dp_meta_objset,
185 	    dsl_dir_phys(dp->dp_root_dir)->dd_child_dir_zapobj,
186 	    name, sizeof (obj), 1, &obj);
187 	if (err)
188 		return (err);
189 
190 	return (dsl_dir_hold_obj(dp, obj, name, dp, ddp));
191 }
192 
193 static dsl_pool_t *
194 dsl_pool_open_impl(spa_t *spa, uint64_t txg)
195 {
196 	dsl_pool_t *dp;
197 	blkptr_t *bp = spa_get_rootblkptr(spa);
198 
199 	dp = kmem_zalloc(sizeof (dsl_pool_t), KM_SLEEP);
200 	dp->dp_spa = spa;
201 	dp->dp_meta_rootbp = *bp;
202 	rrw_init(&dp->dp_config_rwlock, B_TRUE);
203 	txg_init(dp, txg);
204 	mmp_init(spa);
205 
206 	txg_list_create(&dp->dp_dirty_datasets, spa,
207 	    offsetof(dsl_dataset_t, ds_dirty_link));
208 	txg_list_create(&dp->dp_dirty_zilogs, spa,
209 	    offsetof(zilog_t, zl_dirty_link));
210 	txg_list_create(&dp->dp_dirty_dirs, spa,
211 	    offsetof(dsl_dir_t, dd_dirty_link));
212 	txg_list_create(&dp->dp_sync_tasks, spa,
213 	    offsetof(dsl_sync_task_t, dst_node));
214 	txg_list_create(&dp->dp_early_sync_tasks, spa,
215 	    offsetof(dsl_sync_task_t, dst_node));
216 
217 	dp->dp_sync_taskq = taskq_create("dp_sync_taskq",
218 	    zfs_sync_taskq_batch_pct, minclsyspri, 1, INT_MAX,
219 	    TASKQ_THREADS_CPU_PCT);
220 
221 	dp->dp_zil_clean_taskq = taskq_create("dp_zil_clean_taskq",
222 	    zfs_zil_clean_taskq_nthr_pct, minclsyspri,
223 	    zfs_zil_clean_taskq_minalloc,
224 	    zfs_zil_clean_taskq_maxalloc,
225 	    TASKQ_PREPOPULATE | TASKQ_THREADS_CPU_PCT);
226 
227 	mutex_init(&dp->dp_lock, NULL, MUTEX_DEFAULT, NULL);
228 	cv_init(&dp->dp_spaceavail_cv, NULL, CV_DEFAULT, NULL);
229 
230 	aggsum_init(&dp->dp_wrlog_total, 0);
231 	for (int i = 0; i < TXG_SIZE; i++) {
232 		aggsum_init(&dp->dp_wrlog_pertxg[i], 0);
233 	}
234 
235 	dp->dp_zrele_taskq = taskq_create("z_zrele", 100, defclsyspri,
236 	    boot_ncpus * 8, INT_MAX, TASKQ_PREPOPULATE | TASKQ_DYNAMIC |
237 	    TASKQ_THREADS_CPU_PCT);
238 	dp->dp_unlinked_drain_taskq = taskq_create("z_unlinked_drain",
239 	    100, defclsyspri, boot_ncpus, INT_MAX,
240 	    TASKQ_PREPOPULATE | TASKQ_DYNAMIC | TASKQ_THREADS_CPU_PCT);
241 
242 	return (dp);
243 }
244 
245 int
246 dsl_pool_init(spa_t *spa, uint64_t txg, dsl_pool_t **dpp)
247 {
248 	int err;
249 	dsl_pool_t *dp = dsl_pool_open_impl(spa, txg);
250 
251 	/*
252 	 * Initialize the caller's dsl_pool_t structure before we actually open
253 	 * the meta objset.  This is done because a self-healing write zio may
254 	 * be issued as part of dmu_objset_open_impl() and the spa needs its
255 	 * dsl_pool_t initialized in order to handle the write.
256 	 */
257 	*dpp = dp;
258 
259 	err = dmu_objset_open_impl(spa, NULL, &dp->dp_meta_rootbp,
260 	    &dp->dp_meta_objset);
261 	if (err != 0) {
262 		dsl_pool_close(dp);
263 		*dpp = NULL;
264 	}
265 
266 	return (err);
267 }
268 
269 int
270 dsl_pool_open(dsl_pool_t *dp)
271 {
272 	int err;
273 	dsl_dir_t *dd;
274 	dsl_dataset_t *ds;
275 	uint64_t obj;
276 
277 	rrw_enter(&dp->dp_config_rwlock, RW_WRITER, FTAG);
278 	err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
279 	    DMU_POOL_ROOT_DATASET, sizeof (uint64_t), 1,
280 	    &dp->dp_root_dir_obj);
281 	if (err)
282 		goto out;
283 
284 	err = dsl_dir_hold_obj(dp, dp->dp_root_dir_obj,
285 	    NULL, dp, &dp->dp_root_dir);
286 	if (err)
287 		goto out;
288 
289 	err = dsl_pool_open_special_dir(dp, MOS_DIR_NAME, &dp->dp_mos_dir);
290 	if (err)
291 		goto out;
292 
293 	if (spa_version(dp->dp_spa) >= SPA_VERSION_ORIGIN) {
294 		err = dsl_pool_open_special_dir(dp, ORIGIN_DIR_NAME, &dd);
295 		if (err)
296 			goto out;
297 		err = dsl_dataset_hold_obj(dp,
298 		    dsl_dir_phys(dd)->dd_head_dataset_obj, FTAG, &ds);
299 		if (err == 0) {
300 			err = dsl_dataset_hold_obj(dp,
301 			    dsl_dataset_phys(ds)->ds_prev_snap_obj, dp,
302 			    &dp->dp_origin_snap);
303 			dsl_dataset_rele(ds, FTAG);
304 		}
305 		dsl_dir_rele(dd, dp);
306 		if (err)
307 			goto out;
308 	}
309 
310 	if (spa_version(dp->dp_spa) >= SPA_VERSION_DEADLISTS) {
311 		err = dsl_pool_open_special_dir(dp, FREE_DIR_NAME,
312 		    &dp->dp_free_dir);
313 		if (err)
314 			goto out;
315 
316 		err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
317 		    DMU_POOL_FREE_BPOBJ, sizeof (uint64_t), 1, &obj);
318 		if (err)
319 			goto out;
320 		VERIFY0(bpobj_open(&dp->dp_free_bpobj,
321 		    dp->dp_meta_objset, obj));
322 	}
323 
324 	if (spa_feature_is_active(dp->dp_spa, SPA_FEATURE_OBSOLETE_COUNTS)) {
325 		err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
326 		    DMU_POOL_OBSOLETE_BPOBJ, sizeof (uint64_t), 1, &obj);
327 		if (err == 0) {
328 			VERIFY0(bpobj_open(&dp->dp_obsolete_bpobj,
329 			    dp->dp_meta_objset, obj));
330 		} else if (err == ENOENT) {
331 			/*
332 			 * We might not have created the remap bpobj yet.
333 			 */
334 		} else {
335 			goto out;
336 		}
337 	}
338 
339 	/*
340 	 * Note: errors ignored, because the these special dirs, used for
341 	 * space accounting, are only created on demand.
342 	 */
343 	(void) dsl_pool_open_special_dir(dp, LEAK_DIR_NAME,
344 	    &dp->dp_leak_dir);
345 
346 	if (spa_feature_is_active(dp->dp_spa, SPA_FEATURE_ASYNC_DESTROY)) {
347 		err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
348 		    DMU_POOL_BPTREE_OBJ, sizeof (uint64_t), 1,
349 		    &dp->dp_bptree_obj);
350 		if (err != 0)
351 			goto out;
352 	}
353 
354 	if (spa_feature_is_active(dp->dp_spa, SPA_FEATURE_EMPTY_BPOBJ)) {
355 		err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
356 		    DMU_POOL_EMPTY_BPOBJ, sizeof (uint64_t), 1,
357 		    &dp->dp_empty_bpobj);
358 		if (err != 0)
359 			goto out;
360 	}
361 
362 	err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
363 	    DMU_POOL_TMP_USERREFS, sizeof (uint64_t), 1,
364 	    &dp->dp_tmp_userrefs_obj);
365 	if (err == ENOENT)
366 		err = 0;
367 	if (err)
368 		goto out;
369 
370 	err = dsl_scan_init(dp, dp->dp_tx.tx_open_txg);
371 
372 out:
373 	rrw_exit(&dp->dp_config_rwlock, FTAG);
374 	return (err);
375 }
376 
377 void
378 dsl_pool_close(dsl_pool_t *dp)
379 {
380 	/*
381 	 * Drop our references from dsl_pool_open().
382 	 *
383 	 * Since we held the origin_snap from "syncing" context (which
384 	 * includes pool-opening context), it actually only got a "ref"
385 	 * and not a hold, so just drop that here.
386 	 */
387 	if (dp->dp_origin_snap != NULL)
388 		dsl_dataset_rele(dp->dp_origin_snap, dp);
389 	if (dp->dp_mos_dir != NULL)
390 		dsl_dir_rele(dp->dp_mos_dir, dp);
391 	if (dp->dp_free_dir != NULL)
392 		dsl_dir_rele(dp->dp_free_dir, dp);
393 	if (dp->dp_leak_dir != NULL)
394 		dsl_dir_rele(dp->dp_leak_dir, dp);
395 	if (dp->dp_root_dir != NULL)
396 		dsl_dir_rele(dp->dp_root_dir, dp);
397 
398 	bpobj_close(&dp->dp_free_bpobj);
399 	bpobj_close(&dp->dp_obsolete_bpobj);
400 
401 	/* undo the dmu_objset_open_impl(mos) from dsl_pool_open() */
402 	if (dp->dp_meta_objset != NULL)
403 		dmu_objset_evict(dp->dp_meta_objset);
404 
405 	txg_list_destroy(&dp->dp_dirty_datasets);
406 	txg_list_destroy(&dp->dp_dirty_zilogs);
407 	txg_list_destroy(&dp->dp_sync_tasks);
408 	txg_list_destroy(&dp->dp_early_sync_tasks);
409 	txg_list_destroy(&dp->dp_dirty_dirs);
410 
411 	taskq_destroy(dp->dp_zil_clean_taskq);
412 	taskq_destroy(dp->dp_sync_taskq);
413 
414 	/*
415 	 * We can't set retry to TRUE since we're explicitly specifying
416 	 * a spa to flush. This is good enough; any missed buffers for
417 	 * this spa won't cause trouble, and they'll eventually fall
418 	 * out of the ARC just like any other unused buffer.
419 	 */
420 	arc_flush(dp->dp_spa, FALSE);
421 
422 	mmp_fini(dp->dp_spa);
423 	txg_fini(dp);
424 	dsl_scan_fini(dp);
425 	dmu_buf_user_evict_wait();
426 
427 	rrw_destroy(&dp->dp_config_rwlock);
428 	mutex_destroy(&dp->dp_lock);
429 	cv_destroy(&dp->dp_spaceavail_cv);
430 
431 	ASSERT0(aggsum_value(&dp->dp_wrlog_total));
432 	aggsum_fini(&dp->dp_wrlog_total);
433 	for (int i = 0; i < TXG_SIZE; i++) {
434 		ASSERT0(aggsum_value(&dp->dp_wrlog_pertxg[i]));
435 		aggsum_fini(&dp->dp_wrlog_pertxg[i]);
436 	}
437 
438 	taskq_destroy(dp->dp_unlinked_drain_taskq);
439 	taskq_destroy(dp->dp_zrele_taskq);
440 	if (dp->dp_blkstats != NULL)
441 		vmem_free(dp->dp_blkstats, sizeof (zfs_all_blkstats_t));
442 	kmem_free(dp, sizeof (dsl_pool_t));
443 }
444 
445 void
446 dsl_pool_create_obsolete_bpobj(dsl_pool_t *dp, dmu_tx_t *tx)
447 {
448 	uint64_t obj;
449 	/*
450 	 * Currently, we only create the obsolete_bpobj where there are
451 	 * indirect vdevs with referenced mappings.
452 	 */
453 	ASSERT(spa_feature_is_active(dp->dp_spa, SPA_FEATURE_DEVICE_REMOVAL));
454 	/* create and open the obsolete_bpobj */
455 	obj = bpobj_alloc(dp->dp_meta_objset, SPA_OLD_MAXBLOCKSIZE, tx);
456 	VERIFY0(bpobj_open(&dp->dp_obsolete_bpobj, dp->dp_meta_objset, obj));
457 	VERIFY0(zap_add(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
458 	    DMU_POOL_OBSOLETE_BPOBJ, sizeof (uint64_t), 1, &obj, tx));
459 	spa_feature_incr(dp->dp_spa, SPA_FEATURE_OBSOLETE_COUNTS, tx);
460 }
461 
462 void
463 dsl_pool_destroy_obsolete_bpobj(dsl_pool_t *dp, dmu_tx_t *tx)
464 {
465 	spa_feature_decr(dp->dp_spa, SPA_FEATURE_OBSOLETE_COUNTS, tx);
466 	VERIFY0(zap_remove(dp->dp_meta_objset,
467 	    DMU_POOL_DIRECTORY_OBJECT,
468 	    DMU_POOL_OBSOLETE_BPOBJ, tx));
469 	bpobj_free(dp->dp_meta_objset,
470 	    dp->dp_obsolete_bpobj.bpo_object, tx);
471 	bpobj_close(&dp->dp_obsolete_bpobj);
472 }
473 
474 dsl_pool_t *
475 dsl_pool_create(spa_t *spa, nvlist_t *zplprops __attribute__((unused)),
476     dsl_crypto_params_t *dcp, uint64_t txg)
477 {
478 	int err;
479 	dsl_pool_t *dp = dsl_pool_open_impl(spa, txg);
480 	dmu_tx_t *tx = dmu_tx_create_assigned(dp, txg);
481 #ifdef _KERNEL
482 	objset_t *os;
483 #else
484 	objset_t *os __attribute__((unused));
485 #endif
486 	dsl_dataset_t *ds;
487 	uint64_t obj;
488 
489 	rrw_enter(&dp->dp_config_rwlock, RW_WRITER, FTAG);
490 
491 	/* create and open the MOS (meta-objset) */
492 	dp->dp_meta_objset = dmu_objset_create_impl(spa,
493 	    NULL, &dp->dp_meta_rootbp, DMU_OST_META, tx);
494 	spa->spa_meta_objset = dp->dp_meta_objset;
495 
496 	/* create the pool directory */
497 	err = zap_create_claim(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
498 	    DMU_OT_OBJECT_DIRECTORY, DMU_OT_NONE, 0, tx);
499 	ASSERT0(err);
500 
501 	/* Initialize scan structures */
502 	VERIFY0(dsl_scan_init(dp, txg));
503 
504 	/* create and open the root dir */
505 	dp->dp_root_dir_obj = dsl_dir_create_sync(dp, NULL, NULL, tx);
506 	VERIFY0(dsl_dir_hold_obj(dp, dp->dp_root_dir_obj,
507 	    NULL, dp, &dp->dp_root_dir));
508 
509 	/* create and open the meta-objset dir */
510 	(void) dsl_dir_create_sync(dp, dp->dp_root_dir, MOS_DIR_NAME, tx);
511 	VERIFY0(dsl_pool_open_special_dir(dp,
512 	    MOS_DIR_NAME, &dp->dp_mos_dir));
513 
514 	if (spa_version(spa) >= SPA_VERSION_DEADLISTS) {
515 		/* create and open the free dir */
516 		(void) dsl_dir_create_sync(dp, dp->dp_root_dir,
517 		    FREE_DIR_NAME, tx);
518 		VERIFY0(dsl_pool_open_special_dir(dp,
519 		    FREE_DIR_NAME, &dp->dp_free_dir));
520 
521 		/* create and open the free_bplist */
522 		obj = bpobj_alloc(dp->dp_meta_objset, SPA_OLD_MAXBLOCKSIZE, tx);
523 		VERIFY(zap_add(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
524 		    DMU_POOL_FREE_BPOBJ, sizeof (uint64_t), 1, &obj, tx) == 0);
525 		VERIFY0(bpobj_open(&dp->dp_free_bpobj,
526 		    dp->dp_meta_objset, obj));
527 	}
528 
529 	if (spa_version(spa) >= SPA_VERSION_DSL_SCRUB)
530 		dsl_pool_create_origin(dp, tx);
531 
532 	/*
533 	 * Some features may be needed when creating the root dataset, so we
534 	 * create the feature objects here.
535 	 */
536 	if (spa_version(spa) >= SPA_VERSION_FEATURES)
537 		spa_feature_create_zap_objects(spa, tx);
538 
539 	if (dcp != NULL && dcp->cp_crypt != ZIO_CRYPT_OFF &&
540 	    dcp->cp_crypt != ZIO_CRYPT_INHERIT)
541 		spa_feature_enable(spa, SPA_FEATURE_ENCRYPTION, tx);
542 
543 	/* create the root dataset */
544 	obj = dsl_dataset_create_sync_dd(dp->dp_root_dir, NULL, dcp, 0, tx);
545 
546 	/* create the root objset */
547 	VERIFY0(dsl_dataset_hold_obj_flags(dp, obj,
548 	    DS_HOLD_FLAG_DECRYPT, FTAG, &ds));
549 	rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);
550 	os = dmu_objset_create_impl(dp->dp_spa, ds,
551 	    dsl_dataset_get_blkptr(ds), DMU_OST_ZFS, tx);
552 	rrw_exit(&ds->ds_bp_rwlock, FTAG);
553 #ifdef _KERNEL
554 	zfs_create_fs(os, kcred, zplprops, tx);
555 #endif
556 	dsl_dataset_rele_flags(ds, DS_HOLD_FLAG_DECRYPT, FTAG);
557 
558 	dmu_tx_commit(tx);
559 
560 	rrw_exit(&dp->dp_config_rwlock, FTAG);
561 
562 	return (dp);
563 }
564 
565 /*
566  * Account for the meta-objset space in its placeholder dsl_dir.
567  */
568 void
569 dsl_pool_mos_diduse_space(dsl_pool_t *dp,
570     int64_t used, int64_t comp, int64_t uncomp)
571 {
572 	ASSERT3U(comp, ==, uncomp); /* it's all metadata */
573 	mutex_enter(&dp->dp_lock);
574 	dp->dp_mos_used_delta += used;
575 	dp->dp_mos_compressed_delta += comp;
576 	dp->dp_mos_uncompressed_delta += uncomp;
577 	mutex_exit(&dp->dp_lock);
578 }
579 
580 static void
581 dsl_pool_sync_mos(dsl_pool_t *dp, dmu_tx_t *tx)
582 {
583 	zio_t *zio = zio_root(dp->dp_spa, NULL, NULL, ZIO_FLAG_MUSTSUCCEED);
584 	dmu_objset_sync(dp->dp_meta_objset, zio, tx);
585 	VERIFY0(zio_wait(zio));
586 	dmu_objset_sync_done(dp->dp_meta_objset, tx);
587 	taskq_wait(dp->dp_sync_taskq);
588 	multilist_destroy(&dp->dp_meta_objset->os_synced_dnodes);
589 
590 	dprintf_bp(&dp->dp_meta_rootbp, "meta objset rootbp is %s", "");
591 	spa_set_rootblkptr(dp->dp_spa, &dp->dp_meta_rootbp);
592 }
593 
594 static void
595 dsl_pool_dirty_delta(dsl_pool_t *dp, int64_t delta)
596 {
597 	ASSERT(MUTEX_HELD(&dp->dp_lock));
598 
599 	if (delta < 0)
600 		ASSERT3U(-delta, <=, dp->dp_dirty_total);
601 
602 	dp->dp_dirty_total += delta;
603 
604 	/*
605 	 * Note: we signal even when increasing dp_dirty_total.
606 	 * This ensures forward progress -- each thread wakes the next waiter.
607 	 */
608 	if (dp->dp_dirty_total < zfs_dirty_data_max)
609 		cv_signal(&dp->dp_spaceavail_cv);
610 }
611 
612 void
613 dsl_pool_wrlog_count(dsl_pool_t *dp, int64_t size, uint64_t txg)
614 {
615 	ASSERT3S(size, >=, 0);
616 
617 	aggsum_add(&dp->dp_wrlog_pertxg[txg & TXG_MASK], size);
618 	aggsum_add(&dp->dp_wrlog_total, size);
619 
620 	/* Choose a value slightly bigger than min dirty sync bytes */
621 	uint64_t sync_min =
622 	    zfs_wrlog_data_max * (zfs_dirty_data_sync_percent + 10) / 200;
623 	if (aggsum_compare(&dp->dp_wrlog_pertxg[txg & TXG_MASK], sync_min) > 0)
624 		txg_kick(dp, txg);
625 }
626 
627 boolean_t
628 dsl_pool_need_wrlog_delay(dsl_pool_t *dp)
629 {
630 	uint64_t delay_min_bytes =
631 	    zfs_wrlog_data_max * zfs_delay_min_dirty_percent / 100;
632 
633 	return (aggsum_compare(&dp->dp_wrlog_total, delay_min_bytes) > 0);
634 }
635 
636 static void
637 dsl_pool_wrlog_clear(dsl_pool_t *dp, uint64_t txg)
638 {
639 	int64_t delta;
640 	delta = -(int64_t)aggsum_value(&dp->dp_wrlog_pertxg[txg & TXG_MASK]);
641 	aggsum_add(&dp->dp_wrlog_pertxg[txg & TXG_MASK], delta);
642 	aggsum_add(&dp->dp_wrlog_total, delta);
643 	/* Compact per-CPU sums after the big change. */
644 	(void) aggsum_value(&dp->dp_wrlog_pertxg[txg & TXG_MASK]);
645 	(void) aggsum_value(&dp->dp_wrlog_total);
646 }
647 
648 #ifdef ZFS_DEBUG
649 static boolean_t
650 dsl_early_sync_task_verify(dsl_pool_t *dp, uint64_t txg)
651 {
652 	spa_t *spa = dp->dp_spa;
653 	vdev_t *rvd = spa->spa_root_vdev;
654 
655 	for (uint64_t c = 0; c < rvd->vdev_children; c++) {
656 		vdev_t *vd = rvd->vdev_child[c];
657 		txg_list_t *tl = &vd->vdev_ms_list;
658 		metaslab_t *ms;
659 
660 		for (ms = txg_list_head(tl, TXG_CLEAN(txg)); ms;
661 		    ms = txg_list_next(tl, ms, TXG_CLEAN(txg))) {
662 			VERIFY(range_tree_is_empty(ms->ms_freeing));
663 			VERIFY(range_tree_is_empty(ms->ms_checkpointing));
664 		}
665 	}
666 
667 	return (B_TRUE);
668 }
669 #else
670 #define	dsl_early_sync_task_verify(dp, txg) \
671 	((void) sizeof (dp), (void) sizeof (txg), B_TRUE)
672 #endif
673 
674 void
675 dsl_pool_sync(dsl_pool_t *dp, uint64_t txg)
676 {
677 	zio_t *zio;
678 	dmu_tx_t *tx;
679 	dsl_dir_t *dd;
680 	dsl_dataset_t *ds;
681 	objset_t *mos = dp->dp_meta_objset;
682 	list_t synced_datasets;
683 
684 	list_create(&synced_datasets, sizeof (dsl_dataset_t),
685 	    offsetof(dsl_dataset_t, ds_synced_link));
686 
687 	tx = dmu_tx_create_assigned(dp, txg);
688 
689 	/*
690 	 * Run all early sync tasks before writing out any dirty blocks.
691 	 * For more info on early sync tasks see block comment in
692 	 * dsl_early_sync_task().
693 	 */
694 	if (!txg_list_empty(&dp->dp_early_sync_tasks, txg)) {
695 		dsl_sync_task_t *dst;
696 
697 		ASSERT3U(spa_sync_pass(dp->dp_spa), ==, 1);
698 		while ((dst =
699 		    txg_list_remove(&dp->dp_early_sync_tasks, txg)) != NULL) {
700 			ASSERT(dsl_early_sync_task_verify(dp, txg));
701 			dsl_sync_task_sync(dst, tx);
702 		}
703 		ASSERT(dsl_early_sync_task_verify(dp, txg));
704 	}
705 
706 	/*
707 	 * Write out all dirty blocks of dirty datasets.
708 	 */
709 	zio = zio_root(dp->dp_spa, NULL, NULL, ZIO_FLAG_MUSTSUCCEED);
710 	while ((ds = txg_list_remove(&dp->dp_dirty_datasets, txg)) != NULL) {
711 		/*
712 		 * We must not sync any non-MOS datasets twice, because
713 		 * we may have taken a snapshot of them.  However, we
714 		 * may sync newly-created datasets on pass 2.
715 		 */
716 		ASSERT(!list_link_active(&ds->ds_synced_link));
717 		list_insert_tail(&synced_datasets, ds);
718 		dsl_dataset_sync(ds, zio, tx);
719 	}
720 	VERIFY0(zio_wait(zio));
721 
722 	/*
723 	 * Update the long range free counter after
724 	 * we're done syncing user data
725 	 */
726 	mutex_enter(&dp->dp_lock);
727 	ASSERT(spa_sync_pass(dp->dp_spa) == 1 ||
728 	    dp->dp_long_free_dirty_pertxg[txg & TXG_MASK] == 0);
729 	dp->dp_long_free_dirty_pertxg[txg & TXG_MASK] = 0;
730 	mutex_exit(&dp->dp_lock);
731 
732 	/*
733 	 * After the data blocks have been written (ensured by the zio_wait()
734 	 * above), update the user/group/project space accounting.  This happens
735 	 * in tasks dispatched to dp_sync_taskq, so wait for them before
736 	 * continuing.
737 	 */
738 	for (ds = list_head(&synced_datasets); ds != NULL;
739 	    ds = list_next(&synced_datasets, ds)) {
740 		dmu_objset_sync_done(ds->ds_objset, tx);
741 	}
742 	taskq_wait(dp->dp_sync_taskq);
743 
744 	/*
745 	 * Sync the datasets again to push out the changes due to
746 	 * userspace updates.  This must be done before we process the
747 	 * sync tasks, so that any snapshots will have the correct
748 	 * user accounting information (and we won't get confused
749 	 * about which blocks are part of the snapshot).
750 	 */
751 	zio = zio_root(dp->dp_spa, NULL, NULL, ZIO_FLAG_MUSTSUCCEED);
752 	while ((ds = txg_list_remove(&dp->dp_dirty_datasets, txg)) != NULL) {
753 		objset_t *os = ds->ds_objset;
754 
755 		ASSERT(list_link_active(&ds->ds_synced_link));
756 		dmu_buf_rele(ds->ds_dbuf, ds);
757 		dsl_dataset_sync(ds, zio, tx);
758 
759 		/*
760 		 * Release any key mappings created by calls to
761 		 * dsl_dataset_dirty() from the userquota accounting
762 		 * code paths.
763 		 */
764 		if (os->os_encrypted && !os->os_raw_receive &&
765 		    !os->os_next_write_raw[txg & TXG_MASK]) {
766 			ASSERT3P(ds->ds_key_mapping, !=, NULL);
767 			key_mapping_rele(dp->dp_spa, ds->ds_key_mapping, ds);
768 		}
769 	}
770 	VERIFY0(zio_wait(zio));
771 
772 	/*
773 	 * Now that the datasets have been completely synced, we can
774 	 * clean up our in-memory structures accumulated while syncing:
775 	 *
776 	 *  - move dead blocks from the pending deadlist and livelists
777 	 *    to the on-disk versions
778 	 *  - release hold from dsl_dataset_dirty()
779 	 *  - release key mapping hold from dsl_dataset_dirty()
780 	 */
781 	while ((ds = list_remove_head(&synced_datasets)) != NULL) {
782 		objset_t *os = ds->ds_objset;
783 
784 		if (os->os_encrypted && !os->os_raw_receive &&
785 		    !os->os_next_write_raw[txg & TXG_MASK]) {
786 			ASSERT3P(ds->ds_key_mapping, !=, NULL);
787 			key_mapping_rele(dp->dp_spa, ds->ds_key_mapping, ds);
788 		}
789 
790 		dsl_dataset_sync_done(ds, tx);
791 		dmu_buf_rele(ds->ds_dbuf, ds);
792 	}
793 
794 	while ((dd = txg_list_remove(&dp->dp_dirty_dirs, txg)) != NULL) {
795 		dsl_dir_sync(dd, tx);
796 	}
797 
798 	/*
799 	 * The MOS's space is accounted for in the pool/$MOS
800 	 * (dp_mos_dir).  We can't modify the mos while we're syncing
801 	 * it, so we remember the deltas and apply them here.
802 	 */
803 	if (dp->dp_mos_used_delta != 0 || dp->dp_mos_compressed_delta != 0 ||
804 	    dp->dp_mos_uncompressed_delta != 0) {
805 		dsl_dir_diduse_space(dp->dp_mos_dir, DD_USED_HEAD,
806 		    dp->dp_mos_used_delta,
807 		    dp->dp_mos_compressed_delta,
808 		    dp->dp_mos_uncompressed_delta, tx);
809 		dp->dp_mos_used_delta = 0;
810 		dp->dp_mos_compressed_delta = 0;
811 		dp->dp_mos_uncompressed_delta = 0;
812 	}
813 
814 	if (dmu_objset_is_dirty(mos, txg)) {
815 		dsl_pool_sync_mos(dp, tx);
816 	}
817 
818 	/*
819 	 * We have written all of the accounted dirty data, so our
820 	 * dp_space_towrite should now be zero. However, some seldom-used
821 	 * code paths do not adhere to this (e.g. dbuf_undirty()). Shore up
822 	 * the accounting of any dirtied space now.
823 	 *
824 	 * Note that, besides any dirty data from datasets, the amount of
825 	 * dirty data in the MOS is also accounted by the pool. Therefore,
826 	 * we want to do this cleanup after dsl_pool_sync_mos() so we don't
827 	 * attempt to update the accounting for the same dirty data twice.
828 	 * (i.e. at this point we only update the accounting for the space
829 	 * that we know that we "leaked").
830 	 */
831 	dsl_pool_undirty_space(dp, dp->dp_dirty_pertxg[txg & TXG_MASK], txg);
832 
833 	/*
834 	 * If we modify a dataset in the same txg that we want to destroy it,
835 	 * its dsl_dir's dd_dbuf will be dirty, and thus have a hold on it.
836 	 * dsl_dir_destroy_check() will fail if there are unexpected holds.
837 	 * Therefore, we want to sync the MOS (thus syncing the dd_dbuf
838 	 * and clearing the hold on it) before we process the sync_tasks.
839 	 * The MOS data dirtied by the sync_tasks will be synced on the next
840 	 * pass.
841 	 */
842 	if (!txg_list_empty(&dp->dp_sync_tasks, txg)) {
843 		dsl_sync_task_t *dst;
844 		/*
845 		 * No more sync tasks should have been added while we
846 		 * were syncing.
847 		 */
848 		ASSERT3U(spa_sync_pass(dp->dp_spa), ==, 1);
849 		while ((dst = txg_list_remove(&dp->dp_sync_tasks, txg)) != NULL)
850 			dsl_sync_task_sync(dst, tx);
851 	}
852 
853 	dmu_tx_commit(tx);
854 
855 	DTRACE_PROBE2(dsl_pool_sync__done, dsl_pool_t *dp, dp, uint64_t, txg);
856 }
857 
858 void
859 dsl_pool_sync_done(dsl_pool_t *dp, uint64_t txg)
860 {
861 	zilog_t *zilog;
862 
863 	while ((zilog = txg_list_head(&dp->dp_dirty_zilogs, txg))) {
864 		dsl_dataset_t *ds = dmu_objset_ds(zilog->zl_os);
865 		/*
866 		 * We don't remove the zilog from the dp_dirty_zilogs
867 		 * list until after we've cleaned it. This ensures that
868 		 * callers of zilog_is_dirty() receive an accurate
869 		 * answer when they are racing with the spa sync thread.
870 		 */
871 		zil_clean(zilog, txg);
872 		(void) txg_list_remove_this(&dp->dp_dirty_zilogs, zilog, txg);
873 		ASSERT(!dmu_objset_is_dirty(zilog->zl_os, txg));
874 		dmu_buf_rele(ds->ds_dbuf, zilog);
875 	}
876 
877 	dsl_pool_wrlog_clear(dp, txg);
878 
879 	ASSERT(!dmu_objset_is_dirty(dp->dp_meta_objset, txg));
880 }
881 
882 /*
883  * TRUE if the current thread is the tx_sync_thread or if we
884  * are being called from SPA context during pool initialization.
885  */
886 int
887 dsl_pool_sync_context(dsl_pool_t *dp)
888 {
889 	return (curthread == dp->dp_tx.tx_sync_thread ||
890 	    spa_is_initializing(dp->dp_spa) ||
891 	    taskq_member(dp->dp_sync_taskq, curthread));
892 }
893 
894 /*
895  * This function returns the amount of allocatable space in the pool
896  * minus whatever space is currently reserved by ZFS for specific
897  * purposes. Specifically:
898  *
899  * 1] Any reserved SLOP space
900  * 2] Any space used by the checkpoint
901  * 3] Any space used for deferred frees
902  *
903  * The latter 2 are especially important because they are needed to
904  * rectify the SPA's and DMU's different understanding of how much space
905  * is used. Now the DMU is aware of that extra space tracked by the SPA
906  * without having to maintain a separate special dir (e.g similar to
907  * $MOS, $FREEING, and $LEAKED).
908  *
909  * Note: By deferred frees here, we mean the frees that were deferred
910  * in spa_sync() after sync pass 1 (spa_deferred_bpobj), and not the
911  * segments placed in ms_defer trees during metaslab_sync_done().
912  */
913 uint64_t
914 dsl_pool_adjustedsize(dsl_pool_t *dp, zfs_space_check_t slop_policy)
915 {
916 	spa_t *spa = dp->dp_spa;
917 	uint64_t space, resv, adjustedsize;
918 	uint64_t spa_deferred_frees =
919 	    spa->spa_deferred_bpobj.bpo_phys->bpo_bytes;
920 
921 	space = spa_get_dspace(spa)
922 	    - spa_get_checkpoint_space(spa) - spa_deferred_frees;
923 	resv = spa_get_slop_space(spa);
924 
925 	switch (slop_policy) {
926 	case ZFS_SPACE_CHECK_NORMAL:
927 		break;
928 	case ZFS_SPACE_CHECK_RESERVED:
929 		resv >>= 1;
930 		break;
931 	case ZFS_SPACE_CHECK_EXTRA_RESERVED:
932 		resv >>= 2;
933 		break;
934 	case ZFS_SPACE_CHECK_NONE:
935 		resv = 0;
936 		break;
937 	default:
938 		panic("invalid slop policy value: %d", slop_policy);
939 		break;
940 	}
941 	adjustedsize = (space >= resv) ? (space - resv) : 0;
942 
943 	return (adjustedsize);
944 }
945 
946 uint64_t
947 dsl_pool_unreserved_space(dsl_pool_t *dp, zfs_space_check_t slop_policy)
948 {
949 	uint64_t poolsize = dsl_pool_adjustedsize(dp, slop_policy);
950 	uint64_t deferred =
951 	    metaslab_class_get_deferred(spa_normal_class(dp->dp_spa));
952 	uint64_t quota = (poolsize >= deferred) ? (poolsize - deferred) : 0;
953 	return (quota);
954 }
955 
956 uint64_t
957 dsl_pool_deferred_space(dsl_pool_t *dp)
958 {
959 	return (metaslab_class_get_deferred(spa_normal_class(dp->dp_spa)));
960 }
961 
962 boolean_t
963 dsl_pool_need_dirty_delay(dsl_pool_t *dp)
964 {
965 	uint64_t delay_min_bytes =
966 	    zfs_dirty_data_max * zfs_delay_min_dirty_percent / 100;
967 
968 	mutex_enter(&dp->dp_lock);
969 	uint64_t dirty = dp->dp_dirty_total;
970 	mutex_exit(&dp->dp_lock);
971 
972 	return (dirty > delay_min_bytes);
973 }
974 
975 static boolean_t
976 dsl_pool_need_dirty_sync(dsl_pool_t *dp, uint64_t txg)
977 {
978 	ASSERT(MUTEX_HELD(&dp->dp_lock));
979 
980 	uint64_t dirty_min_bytes =
981 	    zfs_dirty_data_max * zfs_dirty_data_sync_percent / 100;
982 	uint64_t dirty = dp->dp_dirty_pertxg[txg & TXG_MASK];
983 
984 	return (dirty > dirty_min_bytes);
985 }
986 
987 void
988 dsl_pool_dirty_space(dsl_pool_t *dp, int64_t space, dmu_tx_t *tx)
989 {
990 	if (space > 0) {
991 		mutex_enter(&dp->dp_lock);
992 		dp->dp_dirty_pertxg[tx->tx_txg & TXG_MASK] += space;
993 		dsl_pool_dirty_delta(dp, space);
994 		boolean_t needsync = !dmu_tx_is_syncing(tx) &&
995 		    dsl_pool_need_dirty_sync(dp, tx->tx_txg);
996 		mutex_exit(&dp->dp_lock);
997 
998 		if (needsync)
999 			txg_kick(dp, tx->tx_txg);
1000 	}
1001 }
1002 
1003 void
1004 dsl_pool_undirty_space(dsl_pool_t *dp, int64_t space, uint64_t txg)
1005 {
1006 	ASSERT3S(space, >=, 0);
1007 	if (space == 0)
1008 		return;
1009 
1010 	mutex_enter(&dp->dp_lock);
1011 	if (dp->dp_dirty_pertxg[txg & TXG_MASK] < space) {
1012 		/* XXX writing something we didn't dirty? */
1013 		space = dp->dp_dirty_pertxg[txg & TXG_MASK];
1014 	}
1015 	ASSERT3U(dp->dp_dirty_pertxg[txg & TXG_MASK], >=, space);
1016 	dp->dp_dirty_pertxg[txg & TXG_MASK] -= space;
1017 	ASSERT3U(dp->dp_dirty_total, >=, space);
1018 	dsl_pool_dirty_delta(dp, -space);
1019 	mutex_exit(&dp->dp_lock);
1020 }
1021 
1022 static int
1023 upgrade_clones_cb(dsl_pool_t *dp, dsl_dataset_t *hds, void *arg)
1024 {
1025 	dmu_tx_t *tx = arg;
1026 	dsl_dataset_t *ds, *prev = NULL;
1027 	int err;
1028 
1029 	err = dsl_dataset_hold_obj(dp, hds->ds_object, FTAG, &ds);
1030 	if (err)
1031 		return (err);
1032 
1033 	while (dsl_dataset_phys(ds)->ds_prev_snap_obj != 0) {
1034 		err = dsl_dataset_hold_obj(dp,
1035 		    dsl_dataset_phys(ds)->ds_prev_snap_obj, FTAG, &prev);
1036 		if (err) {
1037 			dsl_dataset_rele(ds, FTAG);
1038 			return (err);
1039 		}
1040 
1041 		if (dsl_dataset_phys(prev)->ds_next_snap_obj != ds->ds_object)
1042 			break;
1043 		dsl_dataset_rele(ds, FTAG);
1044 		ds = prev;
1045 		prev = NULL;
1046 	}
1047 
1048 	if (prev == NULL) {
1049 		prev = dp->dp_origin_snap;
1050 
1051 		/*
1052 		 * The $ORIGIN can't have any data, or the accounting
1053 		 * will be wrong.
1054 		 */
1055 		rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);
1056 		ASSERT0(dsl_dataset_phys(prev)->ds_bp.blk_birth);
1057 		rrw_exit(&ds->ds_bp_rwlock, FTAG);
1058 
1059 		/* The origin doesn't get attached to itself */
1060 		if (ds->ds_object == prev->ds_object) {
1061 			dsl_dataset_rele(ds, FTAG);
1062 			return (0);
1063 		}
1064 
1065 		dmu_buf_will_dirty(ds->ds_dbuf, tx);
1066 		dsl_dataset_phys(ds)->ds_prev_snap_obj = prev->ds_object;
1067 		dsl_dataset_phys(ds)->ds_prev_snap_txg =
1068 		    dsl_dataset_phys(prev)->ds_creation_txg;
1069 
1070 		dmu_buf_will_dirty(ds->ds_dir->dd_dbuf, tx);
1071 		dsl_dir_phys(ds->ds_dir)->dd_origin_obj = prev->ds_object;
1072 
1073 		dmu_buf_will_dirty(prev->ds_dbuf, tx);
1074 		dsl_dataset_phys(prev)->ds_num_children++;
1075 
1076 		if (dsl_dataset_phys(ds)->ds_next_snap_obj == 0) {
1077 			ASSERT(ds->ds_prev == NULL);
1078 			VERIFY0(dsl_dataset_hold_obj(dp,
1079 			    dsl_dataset_phys(ds)->ds_prev_snap_obj,
1080 			    ds, &ds->ds_prev));
1081 		}
1082 	}
1083 
1084 	ASSERT3U(dsl_dir_phys(ds->ds_dir)->dd_origin_obj, ==, prev->ds_object);
1085 	ASSERT3U(dsl_dataset_phys(ds)->ds_prev_snap_obj, ==, prev->ds_object);
1086 
1087 	if (dsl_dataset_phys(prev)->ds_next_clones_obj == 0) {
1088 		dmu_buf_will_dirty(prev->ds_dbuf, tx);
1089 		dsl_dataset_phys(prev)->ds_next_clones_obj =
1090 		    zap_create(dp->dp_meta_objset,
1091 		    DMU_OT_NEXT_CLONES, DMU_OT_NONE, 0, tx);
1092 	}
1093 	VERIFY0(zap_add_int(dp->dp_meta_objset,
1094 	    dsl_dataset_phys(prev)->ds_next_clones_obj, ds->ds_object, tx));
1095 
1096 	dsl_dataset_rele(ds, FTAG);
1097 	if (prev != dp->dp_origin_snap)
1098 		dsl_dataset_rele(prev, FTAG);
1099 	return (0);
1100 }
1101 
1102 void
1103 dsl_pool_upgrade_clones(dsl_pool_t *dp, dmu_tx_t *tx)
1104 {
1105 	ASSERT(dmu_tx_is_syncing(tx));
1106 	ASSERT(dp->dp_origin_snap != NULL);
1107 
1108 	VERIFY0(dmu_objset_find_dp(dp, dp->dp_root_dir_obj, upgrade_clones_cb,
1109 	    tx, DS_FIND_CHILDREN | DS_FIND_SERIALIZE));
1110 }
1111 
1112 static int
1113 upgrade_dir_clones_cb(dsl_pool_t *dp, dsl_dataset_t *ds, void *arg)
1114 {
1115 	dmu_tx_t *tx = arg;
1116 	objset_t *mos = dp->dp_meta_objset;
1117 
1118 	if (dsl_dir_phys(ds->ds_dir)->dd_origin_obj != 0) {
1119 		dsl_dataset_t *origin;
1120 
1121 		VERIFY0(dsl_dataset_hold_obj(dp,
1122 		    dsl_dir_phys(ds->ds_dir)->dd_origin_obj, FTAG, &origin));
1123 
1124 		if (dsl_dir_phys(origin->ds_dir)->dd_clones == 0) {
1125 			dmu_buf_will_dirty(origin->ds_dir->dd_dbuf, tx);
1126 			dsl_dir_phys(origin->ds_dir)->dd_clones =
1127 			    zap_create(mos, DMU_OT_DSL_CLONES, DMU_OT_NONE,
1128 			    0, tx);
1129 		}
1130 
1131 		VERIFY0(zap_add_int(dp->dp_meta_objset,
1132 		    dsl_dir_phys(origin->ds_dir)->dd_clones,
1133 		    ds->ds_object, tx));
1134 
1135 		dsl_dataset_rele(origin, FTAG);
1136 	}
1137 	return (0);
1138 }
1139 
1140 void
1141 dsl_pool_upgrade_dir_clones(dsl_pool_t *dp, dmu_tx_t *tx)
1142 {
1143 	uint64_t obj;
1144 
1145 	ASSERT(dmu_tx_is_syncing(tx));
1146 
1147 	(void) dsl_dir_create_sync(dp, dp->dp_root_dir, FREE_DIR_NAME, tx);
1148 	VERIFY0(dsl_pool_open_special_dir(dp,
1149 	    FREE_DIR_NAME, &dp->dp_free_dir));
1150 
1151 	/*
1152 	 * We can't use bpobj_alloc(), because spa_version() still
1153 	 * returns the old version, and we need a new-version bpobj with
1154 	 * subobj support.  So call dmu_object_alloc() directly.
1155 	 */
1156 	obj = dmu_object_alloc(dp->dp_meta_objset, DMU_OT_BPOBJ,
1157 	    SPA_OLD_MAXBLOCKSIZE, DMU_OT_BPOBJ_HDR, sizeof (bpobj_phys_t), tx);
1158 	VERIFY0(zap_add(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
1159 	    DMU_POOL_FREE_BPOBJ, sizeof (uint64_t), 1, &obj, tx));
1160 	VERIFY0(bpobj_open(&dp->dp_free_bpobj, dp->dp_meta_objset, obj));
1161 
1162 	VERIFY0(dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
1163 	    upgrade_dir_clones_cb, tx, DS_FIND_CHILDREN | DS_FIND_SERIALIZE));
1164 }
1165 
1166 void
1167 dsl_pool_create_origin(dsl_pool_t *dp, dmu_tx_t *tx)
1168 {
1169 	uint64_t dsobj;
1170 	dsl_dataset_t *ds;
1171 
1172 	ASSERT(dmu_tx_is_syncing(tx));
1173 	ASSERT(dp->dp_origin_snap == NULL);
1174 	ASSERT(rrw_held(&dp->dp_config_rwlock, RW_WRITER));
1175 
1176 	/* create the origin dir, ds, & snap-ds */
1177 	dsobj = dsl_dataset_create_sync(dp->dp_root_dir, ORIGIN_DIR_NAME,
1178 	    NULL, 0, kcred, NULL, tx);
1179 	VERIFY0(dsl_dataset_hold_obj(dp, dsobj, FTAG, &ds));
1180 	dsl_dataset_snapshot_sync_impl(ds, ORIGIN_DIR_NAME, tx);
1181 	VERIFY0(dsl_dataset_hold_obj(dp, dsl_dataset_phys(ds)->ds_prev_snap_obj,
1182 	    dp, &dp->dp_origin_snap));
1183 	dsl_dataset_rele(ds, FTAG);
1184 }
1185 
1186 taskq_t *
1187 dsl_pool_zrele_taskq(dsl_pool_t *dp)
1188 {
1189 	return (dp->dp_zrele_taskq);
1190 }
1191 
1192 taskq_t *
1193 dsl_pool_unlinked_drain_taskq(dsl_pool_t *dp)
1194 {
1195 	return (dp->dp_unlinked_drain_taskq);
1196 }
1197 
1198 /*
1199  * Walk through the pool-wide zap object of temporary snapshot user holds
1200  * and release them.
1201  */
1202 void
1203 dsl_pool_clean_tmp_userrefs(dsl_pool_t *dp)
1204 {
1205 	zap_attribute_t za;
1206 	zap_cursor_t zc;
1207 	objset_t *mos = dp->dp_meta_objset;
1208 	uint64_t zapobj = dp->dp_tmp_userrefs_obj;
1209 	nvlist_t *holds;
1210 
1211 	if (zapobj == 0)
1212 		return;
1213 	ASSERT(spa_version(dp->dp_spa) >= SPA_VERSION_USERREFS);
1214 
1215 	holds = fnvlist_alloc();
1216 
1217 	for (zap_cursor_init(&zc, mos, zapobj);
1218 	    zap_cursor_retrieve(&zc, &za) == 0;
1219 	    zap_cursor_advance(&zc)) {
1220 		char *htag;
1221 		nvlist_t *tags;
1222 
1223 		htag = strchr(za.za_name, '-');
1224 		*htag = '\0';
1225 		++htag;
1226 		if (nvlist_lookup_nvlist(holds, za.za_name, &tags) != 0) {
1227 			tags = fnvlist_alloc();
1228 			fnvlist_add_boolean(tags, htag);
1229 			fnvlist_add_nvlist(holds, za.za_name, tags);
1230 			fnvlist_free(tags);
1231 		} else {
1232 			fnvlist_add_boolean(tags, htag);
1233 		}
1234 	}
1235 	dsl_dataset_user_release_tmp(dp, holds);
1236 	fnvlist_free(holds);
1237 	zap_cursor_fini(&zc);
1238 }
1239 
1240 /*
1241  * Create the pool-wide zap object for storing temporary snapshot holds.
1242  */
1243 static void
1244 dsl_pool_user_hold_create_obj(dsl_pool_t *dp, dmu_tx_t *tx)
1245 {
1246 	objset_t *mos = dp->dp_meta_objset;
1247 
1248 	ASSERT(dp->dp_tmp_userrefs_obj == 0);
1249 	ASSERT(dmu_tx_is_syncing(tx));
1250 
1251 	dp->dp_tmp_userrefs_obj = zap_create_link(mos, DMU_OT_USERREFS,
1252 	    DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_TMP_USERREFS, tx);
1253 }
1254 
1255 static int
1256 dsl_pool_user_hold_rele_impl(dsl_pool_t *dp, uint64_t dsobj,
1257     const char *tag, uint64_t now, dmu_tx_t *tx, boolean_t holding)
1258 {
1259 	objset_t *mos = dp->dp_meta_objset;
1260 	uint64_t zapobj = dp->dp_tmp_userrefs_obj;
1261 	char *name;
1262 	int error;
1263 
1264 	ASSERT(spa_version(dp->dp_spa) >= SPA_VERSION_USERREFS);
1265 	ASSERT(dmu_tx_is_syncing(tx));
1266 
1267 	/*
1268 	 * If the pool was created prior to SPA_VERSION_USERREFS, the
1269 	 * zap object for temporary holds might not exist yet.
1270 	 */
1271 	if (zapobj == 0) {
1272 		if (holding) {
1273 			dsl_pool_user_hold_create_obj(dp, tx);
1274 			zapobj = dp->dp_tmp_userrefs_obj;
1275 		} else {
1276 			return (SET_ERROR(ENOENT));
1277 		}
1278 	}
1279 
1280 	name = kmem_asprintf("%llx-%s", (u_longlong_t)dsobj, tag);
1281 	if (holding)
1282 		error = zap_add(mos, zapobj, name, 8, 1, &now, tx);
1283 	else
1284 		error = zap_remove(mos, zapobj, name, tx);
1285 	kmem_strfree(name);
1286 
1287 	return (error);
1288 }
1289 
1290 /*
1291  * Add a temporary hold for the given dataset object and tag.
1292  */
1293 int
1294 dsl_pool_user_hold(dsl_pool_t *dp, uint64_t dsobj, const char *tag,
1295     uint64_t now, dmu_tx_t *tx)
1296 {
1297 	return (dsl_pool_user_hold_rele_impl(dp, dsobj, tag, now, tx, B_TRUE));
1298 }
1299 
1300 /*
1301  * Release a temporary hold for the given dataset object and tag.
1302  */
1303 int
1304 dsl_pool_user_release(dsl_pool_t *dp, uint64_t dsobj, const char *tag,
1305     dmu_tx_t *tx)
1306 {
1307 	return (dsl_pool_user_hold_rele_impl(dp, dsobj, tag, 0,
1308 	    tx, B_FALSE));
1309 }
1310 
1311 /*
1312  * DSL Pool Configuration Lock
1313  *
1314  * The dp_config_rwlock protects against changes to DSL state (e.g. dataset
1315  * creation / destruction / rename / property setting).  It must be held for
1316  * read to hold a dataset or dsl_dir.  I.e. you must call
1317  * dsl_pool_config_enter() or dsl_pool_hold() before calling
1318  * dsl_{dataset,dir}_hold{_obj}.  In most circumstances, the dp_config_rwlock
1319  * must be held continuously until all datasets and dsl_dirs are released.
1320  *
1321  * The only exception to this rule is that if a "long hold" is placed on
1322  * a dataset, then the dp_config_rwlock may be dropped while the dataset
1323  * is still held.  The long hold will prevent the dataset from being
1324  * destroyed -- the destroy will fail with EBUSY.  A long hold can be
1325  * obtained by calling dsl_dataset_long_hold(), or by "owning" a dataset
1326  * (by calling dsl_{dataset,objset}_{try}own{_obj}).
1327  *
1328  * Legitimate long-holders (including owners) should be long-running, cancelable
1329  * tasks that should cause "zfs destroy" to fail.  This includes DMU
1330  * consumers (i.e. a ZPL filesystem being mounted or ZVOL being open),
1331  * "zfs send", and "zfs diff".  There are several other long-holders whose
1332  * uses are suboptimal (e.g. "zfs promote", and zil_suspend()).
1333  *
1334  * The usual formula for long-holding would be:
1335  * dsl_pool_hold()
1336  * dsl_dataset_hold()
1337  * ... perform checks ...
1338  * dsl_dataset_long_hold()
1339  * dsl_pool_rele()
1340  * ... perform long-running task ...
1341  * dsl_dataset_long_rele()
1342  * dsl_dataset_rele()
1343  *
1344  * Note that when the long hold is released, the dataset is still held but
1345  * the pool is not held.  The dataset may change arbitrarily during this time
1346  * (e.g. it could be destroyed).  Therefore you shouldn't do anything to the
1347  * dataset except release it.
1348  *
1349  * Operations generally fall somewhere into the following taxonomy:
1350  *
1351  *                              Read-Only             Modifying
1352  *
1353  *    Dataset Layer / MOS        zfs get             zfs destroy
1354  *
1355  *     Individual Dataset         read()                write()
1356  *
1357  *
1358  * Dataset Layer Operations
1359  *
1360  * Modifying operations should generally use dsl_sync_task().  The synctask
1361  * infrastructure enforces proper locking strategy with respect to the
1362  * dp_config_rwlock.  See the comment above dsl_sync_task() for details.
1363  *
1364  * Read-only operations will manually hold the pool, then the dataset, obtain
1365  * information from the dataset, then release the pool and dataset.
1366  * dmu_objset_{hold,rele}() are convenience routines that also do the pool
1367  * hold/rele.
1368  *
1369  *
1370  * Operations On Individual Datasets
1371  *
1372  * Objects _within_ an objset should only be modified by the current 'owner'
1373  * of the objset to prevent incorrect concurrent modification. Thus, use
1374  * {dmu_objset,dsl_dataset}_own to mark some entity as the current owner,
1375  * and fail with EBUSY if there is already an owner. The owner can then
1376  * implement its own locking strategy, independent of the dataset layer's
1377  * locking infrastructure.
1378  * (E.g., the ZPL has its own set of locks to control concurrency. A regular
1379  *  vnop will not reach into the dataset layer).
1380  *
1381  * Ideally, objects would also only be read by the objset’s owner, so that we
1382  * don’t observe state mid-modification.
1383  * (E.g. the ZPL is creating a new object and linking it into a directory; if
1384  * you don’t coordinate with the ZPL to hold ZPL-level locks, you could see an
1385  * intermediate state.  The ioctl level violates this but in pretty benign
1386  * ways, e.g. reading the zpl props object.)
1387  */
1388 
1389 int
1390 dsl_pool_hold(const char *name, const void *tag, dsl_pool_t **dp)
1391 {
1392 	spa_t *spa;
1393 	int error;
1394 
1395 	error = spa_open(name, &spa, tag);
1396 	if (error == 0) {
1397 		*dp = spa_get_dsl(spa);
1398 		dsl_pool_config_enter(*dp, tag);
1399 	}
1400 	return (error);
1401 }
1402 
1403 void
1404 dsl_pool_rele(dsl_pool_t *dp, const void *tag)
1405 {
1406 	dsl_pool_config_exit(dp, tag);
1407 	spa_close(dp->dp_spa, tag);
1408 }
1409 
1410 void
1411 dsl_pool_config_enter(dsl_pool_t *dp, const void *tag)
1412 {
1413 	/*
1414 	 * We use a "reentrant" reader-writer lock, but not reentrantly.
1415 	 *
1416 	 * The rrwlock can (with the track_all flag) track all reading threads,
1417 	 * which is very useful for debugging which code path failed to release
1418 	 * the lock, and for verifying that the *current* thread does hold
1419 	 * the lock.
1420 	 *
1421 	 * (Unlike a rwlock, which knows that N threads hold it for
1422 	 * read, but not *which* threads, so rw_held(RW_READER) returns TRUE
1423 	 * if any thread holds it for read, even if this thread doesn't).
1424 	 */
1425 	ASSERT(!rrw_held(&dp->dp_config_rwlock, RW_READER));
1426 	rrw_enter(&dp->dp_config_rwlock, RW_READER, tag);
1427 }
1428 
1429 void
1430 dsl_pool_config_enter_prio(dsl_pool_t *dp, const void *tag)
1431 {
1432 	ASSERT(!rrw_held(&dp->dp_config_rwlock, RW_READER));
1433 	rrw_enter_read_prio(&dp->dp_config_rwlock, tag);
1434 }
1435 
1436 void
1437 dsl_pool_config_exit(dsl_pool_t *dp, const void *tag)
1438 {
1439 	rrw_exit(&dp->dp_config_rwlock, tag);
1440 }
1441 
1442 boolean_t
1443 dsl_pool_config_held(dsl_pool_t *dp)
1444 {
1445 	return (RRW_LOCK_HELD(&dp->dp_config_rwlock));
1446 }
1447 
1448 boolean_t
1449 dsl_pool_config_held_writer(dsl_pool_t *dp)
1450 {
1451 	return (RRW_WRITE_HELD(&dp->dp_config_rwlock));
1452 }
1453 
1454 EXPORT_SYMBOL(dsl_pool_config_enter);
1455 EXPORT_SYMBOL(dsl_pool_config_exit);
1456 
1457 /* zfs_dirty_data_max_percent only applied at module load in arc_init(). */
1458 ZFS_MODULE_PARAM(zfs, zfs_, dirty_data_max_percent, UINT, ZMOD_RD,
1459 	"Max percent of RAM allowed to be dirty");
1460 
1461 /* zfs_dirty_data_max_max_percent only applied at module load in arc_init(). */
1462 ZFS_MODULE_PARAM(zfs, zfs_, dirty_data_max_max_percent, UINT, ZMOD_RD,
1463 	"zfs_dirty_data_max upper bound as % of RAM");
1464 
1465 ZFS_MODULE_PARAM(zfs, zfs_, delay_min_dirty_percent, UINT, ZMOD_RW,
1466 	"Transaction delay threshold");
1467 
1468 ZFS_MODULE_PARAM(zfs, zfs_, dirty_data_max, U64, ZMOD_RW,
1469 	"Determines the dirty space limit");
1470 
1471 ZFS_MODULE_PARAM(zfs, zfs_, wrlog_data_max, U64, ZMOD_RW,
1472 	"The size limit of write-transaction zil log data");
1473 
1474 /* zfs_dirty_data_max_max only applied at module load in arc_init(). */
1475 ZFS_MODULE_PARAM(zfs, zfs_, dirty_data_max_max, U64, ZMOD_RD,
1476 	"zfs_dirty_data_max upper bound in bytes");
1477 
1478 ZFS_MODULE_PARAM(zfs, zfs_, dirty_data_sync_percent, UINT, ZMOD_RW,
1479 	"Dirty data txg sync threshold as a percentage of zfs_dirty_data_max");
1480 
1481 ZFS_MODULE_PARAM(zfs, zfs_, delay_scale, U64, ZMOD_RW,
1482 	"How quickly delay approaches infinity");
1483 
1484 ZFS_MODULE_PARAM(zfs, zfs_, sync_taskq_batch_pct, INT, ZMOD_RW,
1485 	"Max percent of CPUs that are used to sync dirty data");
1486 
1487 ZFS_MODULE_PARAM(zfs_zil, zfs_zil_, clean_taskq_nthr_pct, INT, ZMOD_RW,
1488 	"Max percent of CPUs that are used per dp_sync_taskq");
1489 
1490 ZFS_MODULE_PARAM(zfs_zil, zfs_zil_, clean_taskq_minalloc, INT, ZMOD_RW,
1491 	"Number of taskq entries that are pre-populated");
1492 
1493 ZFS_MODULE_PARAM(zfs_zil, zfs_zil_, clean_taskq_maxalloc, INT, ZMOD_RW,
1494 	"Max number of taskq entries that are cached");
1495