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