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