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