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, 2014 by Delphix. All rights reserved.
24 * Copyright (c) 2013 Steven Hartland. All rights reserved.
25 */
26
27#include <sys/dsl_pool.h>
28#include <sys/dsl_dataset.h>
29#include <sys/dsl_prop.h>
30#include <sys/dsl_dir.h>
31#include <sys/dsl_synctask.h>
32#include <sys/dsl_scan.h>
33#include <sys/dnode.h>
34#include <sys/dmu_tx.h>
35#include <sys/dmu_objset.h>
36#include <sys/arc.h>
37#include <sys/zap.h>
38#include <sys/zio.h>
39#include <sys/zfs_context.h>
40#include <sys/fs/zfs.h>
41#include <sys/zfs_znode.h>
42#include <sys/spa_impl.h>
43#include <sys/dsl_deadlist.h>
44#include <sys/bptree.h>
45#include <sys/zfeature.h>
46#include <sys/zil_impl.h>
47#include <sys/dsl_userhold.h>
48
49#ifdef __FreeBSD__
50#include <sys/sysctl.h>
51#include <sys/types.h>
52#endif
53
54/*
55 * ZFS Write Throttle
56 * ------------------
57 *
58 * ZFS must limit the rate of incoming writes to the rate at which it is able
59 * to sync data modifications to the backend storage. Throttling by too much
60 * creates an artificial limit; throttling by too little can only be sustained
61 * for short periods and would lead to highly lumpy performance. On a per-pool
62 * basis, ZFS tracks the amount of modified (dirty) data. As operations change
63 * data, the amount of dirty data increases; as ZFS syncs out data, the amount
64 * of dirty data decreases. When the amount of dirty data exceeds a
65 * predetermined threshold further modifications are blocked until the amount
66 * of dirty data decreases (as data is synced out).
67 *
68 * The limit on dirty data is tunable, and should be adjusted according to
69 * both the IO capacity and available memory of the system. The larger the
70 * window, the more ZFS is able to aggregate and amortize metadata (and data)
71 * changes. However, memory is a limited resource, and allowing for more dirty
72 * data comes at the cost of keeping other useful data in memory (for example
73 * ZFS data cached by the ARC).
74 *
75 * Implementation
76 *
77 * As buffers are modified dsl_pool_willuse_space() increments both the per-
78 * txg (dp_dirty_pertxg[]) and poolwide (dp_dirty_total) accounting of
79 * dirty space used; dsl_pool_dirty_space() decrements those values as data
80 * is synced out from dsl_pool_sync(). While only the poolwide value is
81 * relevant, the per-txg value is useful for debugging. The tunable
82 * zfs_dirty_data_max determines the dirty space limit. Once that value is
83 * exceeded, new writes are halted until space frees up.
84 *
85 * The zfs_dirty_data_sync tunable dictates the threshold at which we
86 * ensure that there is a txg syncing (see the comment in txg.c for a full
87 * description of transaction group stages).
88 *
89 * The IO scheduler uses both the dirty space limit and current amount of
90 * dirty data as inputs. Those values affect the number of concurrent IOs ZFS
91 * issues. See the comment in vdev_queue.c for details of the IO scheduler.
92 *
93 * The delay is also calculated based on the amount of dirty data.  See the
94 * comment above dmu_tx_delay() for details.
95 */
96
97/*
98 * zfs_dirty_data_max will be set to zfs_dirty_data_max_percent% of all memory,
99 * capped at zfs_dirty_data_max_max.  It can also be overridden in /etc/system.
100 */
101uint64_t zfs_dirty_data_max;
102uint64_t zfs_dirty_data_max_max = 4ULL * 1024 * 1024 * 1024;
103int zfs_dirty_data_max_percent = 10;
104
105/*
106 * If there is at least this much dirty data, push out a txg.
107 */
108uint64_t zfs_dirty_data_sync = 64 * 1024 * 1024;
109
110/*
111 * Once there is this amount of dirty data, the dmu_tx_delay() will kick in
112 * and delay each transaction.
113 * This value should be >= zfs_vdev_async_write_active_max_dirty_percent.
114 */
115int zfs_delay_min_dirty_percent = 60;
116
117/*
118 * This controls how quickly the delay approaches infinity.
119 * Larger values cause it to delay more for a given amount of dirty data.
120 * Therefore larger values will cause there to be less dirty data for a
121 * given throughput.
122 *
123 * For the smoothest delay, this value should be about 1 billion divided
124 * by the maximum number of operations per second.  This will smoothly
125 * handle between 10x and 1/10th this number.
126 *
127 * Note: zfs_delay_scale * zfs_dirty_data_max must be < 2^64, due to the
128 * multiply in dmu_tx_delay().
129 */
130uint64_t zfs_delay_scale = 1000 * 1000 * 1000 / 2000;
131
132
133#ifdef __FreeBSD__
134
135extern int zfs_vdev_async_write_active_max_dirty_percent;
136
137SYSCTL_DECL(_vfs_zfs);
138
139TUNABLE_QUAD("vfs.zfs.dirty_data_max", &zfs_dirty_data_max);
140SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, dirty_data_max, CTLFLAG_RWTUN,
141    &zfs_dirty_data_max, 0,
142    "The maximum amount of dirty data in bytes after which new writes are "
143    "halted until space becomes available");
144
145TUNABLE_QUAD("vfs.zfs.dirty_data_max_max", &zfs_dirty_data_max_max);
146SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, dirty_data_max_max, CTLFLAG_RDTUN,
147    &zfs_dirty_data_max_max, 0,
148    "The absolute cap on dirty_data_max when auto calculating");
149
150TUNABLE_INT("vfs.zfs.dirty_data_max_percent", &zfs_dirty_data_max_percent);
151SYSCTL_INT(_vfs_zfs, OID_AUTO, dirty_data_max_percent, CTLFLAG_RDTUN,
152    &zfs_dirty_data_max_percent, 0,
153    "The percent of physical memory used to auto calculate dirty_data_max");
154
155TUNABLE_QUAD("vfs.zfs.dirty_data_sync", &zfs_dirty_data_sync);
156SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, dirty_data_sync, CTLFLAG_RWTUN,
157    &zfs_dirty_data_sync, 0,
158    "Force a txg if the number of dirty buffer bytes exceed this value");
159
160static int sysctl_zfs_delay_min_dirty_percent(SYSCTL_HANDLER_ARGS);
161/* No zfs_delay_min_dirty_percent tunable due to limit requirements */
162SYSCTL_PROC(_vfs_zfs, OID_AUTO, delay_min_dirty_percent,
163    CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, sizeof(int),
164    sysctl_zfs_delay_min_dirty_percent, "I",
165    "The limit of outstanding dirty data before transations are delayed");
166
167static int sysctl_zfs_delay_scale(SYSCTL_HANDLER_ARGS);
168/* No zfs_delay_scale tunable due to limit requirements */
169SYSCTL_PROC(_vfs_zfs, OID_AUTO, delay_scale,
170    CTLTYPE_U64 | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, sizeof(uint64_t),
171    sysctl_zfs_delay_scale, "QU",
172    "Controls how quickly the delay approaches infinity");
173
174static int
175sysctl_zfs_delay_min_dirty_percent(SYSCTL_HANDLER_ARGS)
176{
177	int val, err;
178
179	val = zfs_delay_min_dirty_percent;
180	err = sysctl_handle_int(oidp, &val, 0, req);
181	if (err != 0 || req->newptr == NULL)
182		return (err);
183
184	if (val < zfs_vdev_async_write_active_max_dirty_percent)
185		return (EINVAL);
186
187	zfs_delay_min_dirty_percent = val;
188
189	return (0);
190}
191
192static int
193sysctl_zfs_delay_scale(SYSCTL_HANDLER_ARGS)
194{
195	uint64_t val;
196	int err;
197
198	val = zfs_delay_scale;
199	err = sysctl_handle_64(oidp, &val, 0, req);
200	if (err != 0 || req->newptr == NULL)
201		return (err);
202
203	if (val > UINT64_MAX / zfs_dirty_data_max)
204		return (EINVAL);
205
206	zfs_delay_scale = val;
207
208	return (0);
209}
210#endif
211
212hrtime_t zfs_throttle_delay = MSEC2NSEC(10);
213hrtime_t zfs_throttle_resolution = MSEC2NSEC(10);
214
215int
216dsl_pool_open_special_dir(dsl_pool_t *dp, const char *name, dsl_dir_t **ddp)
217{
218	uint64_t obj;
219	int err;
220
221	err = zap_lookup(dp->dp_meta_objset,
222	    dp->dp_root_dir->dd_phys->dd_child_dir_zapobj,
223	    name, sizeof (obj), 1, &obj);
224	if (err)
225		return (err);
226
227	return (dsl_dir_hold_obj(dp, obj, name, dp, ddp));
228}
229
230static dsl_pool_t *
231dsl_pool_open_impl(spa_t *spa, uint64_t txg)
232{
233	dsl_pool_t *dp;
234	blkptr_t *bp = spa_get_rootblkptr(spa);
235
236	dp = kmem_zalloc(sizeof (dsl_pool_t), KM_SLEEP);
237	dp->dp_spa = spa;
238	dp->dp_meta_rootbp = *bp;
239	rrw_init(&dp->dp_config_rwlock, B_TRUE);
240	txg_init(dp, txg);
241
242	txg_list_create(&dp->dp_dirty_datasets,
243	    offsetof(dsl_dataset_t, ds_dirty_link));
244	txg_list_create(&dp->dp_dirty_zilogs,
245	    offsetof(zilog_t, zl_dirty_link));
246	txg_list_create(&dp->dp_dirty_dirs,
247	    offsetof(dsl_dir_t, dd_dirty_link));
248	txg_list_create(&dp->dp_sync_tasks,
249	    offsetof(dsl_sync_task_t, dst_node));
250
251	mutex_init(&dp->dp_lock, NULL, MUTEX_DEFAULT, NULL);
252	cv_init(&dp->dp_spaceavail_cv, NULL, CV_DEFAULT, NULL);
253
254	dp->dp_vnrele_taskq = taskq_create("zfs_vn_rele_taskq", 1, minclsyspri,
255	    1, 4, 0);
256
257	return (dp);
258}
259
260int
261dsl_pool_init(spa_t *spa, uint64_t txg, dsl_pool_t **dpp)
262{
263	int err;
264	dsl_pool_t *dp = dsl_pool_open_impl(spa, txg);
265
266	err = dmu_objset_open_impl(spa, NULL, &dp->dp_meta_rootbp,
267	    &dp->dp_meta_objset);
268	if (err != 0)
269		dsl_pool_close(dp);
270	else
271		*dpp = dp;
272
273	return (err);
274}
275
276int
277dsl_pool_open(dsl_pool_t *dp)
278{
279	int err;
280	dsl_dir_t *dd;
281	dsl_dataset_t *ds;
282	uint64_t obj;
283
284	rrw_enter(&dp->dp_config_rwlock, RW_WRITER, FTAG);
285	err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
286	    DMU_POOL_ROOT_DATASET, sizeof (uint64_t), 1,
287	    &dp->dp_root_dir_obj);
288	if (err)
289		goto out;
290
291	err = dsl_dir_hold_obj(dp, dp->dp_root_dir_obj,
292	    NULL, dp, &dp->dp_root_dir);
293	if (err)
294		goto out;
295
296	err = dsl_pool_open_special_dir(dp, MOS_DIR_NAME, &dp->dp_mos_dir);
297	if (err)
298		goto out;
299
300	if (spa_version(dp->dp_spa) >= SPA_VERSION_ORIGIN) {
301		err = dsl_pool_open_special_dir(dp, ORIGIN_DIR_NAME, &dd);
302		if (err)
303			goto out;
304		err = dsl_dataset_hold_obj(dp, dd->dd_phys->dd_head_dataset_obj,
305		    FTAG, &ds);
306		if (err == 0) {
307			err = dsl_dataset_hold_obj(dp,
308			    ds->ds_phys->ds_prev_snap_obj, dp,
309			    &dp->dp_origin_snap);
310			dsl_dataset_rele(ds, FTAG);
311		}
312		dsl_dir_rele(dd, dp);
313		if (err)
314			goto out;
315	}
316
317	if (spa_version(dp->dp_spa) >= SPA_VERSION_DEADLISTS) {
318		err = dsl_pool_open_special_dir(dp, FREE_DIR_NAME,
319		    &dp->dp_free_dir);
320		if (err)
321			goto out;
322
323		err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
324		    DMU_POOL_FREE_BPOBJ, sizeof (uint64_t), 1, &obj);
325		if (err)
326			goto out;
327		VERIFY0(bpobj_open(&dp->dp_free_bpobj,
328		    dp->dp_meta_objset, obj));
329	}
330
331	/*
332	 * Note: errors ignored, because the leak dir will not exist if we
333	 * have not encountered a leak yet.
334	 */
335	(void) dsl_pool_open_special_dir(dp, LEAK_DIR_NAME,
336	    &dp->dp_leak_dir);
337
338	if (spa_feature_is_active(dp->dp_spa, SPA_FEATURE_ASYNC_DESTROY)) {
339		err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
340		    DMU_POOL_BPTREE_OBJ, sizeof (uint64_t), 1,
341		    &dp->dp_bptree_obj);
342		if (err != 0)
343			goto out;
344	}
345
346	if (spa_feature_is_active(dp->dp_spa, SPA_FEATURE_EMPTY_BPOBJ)) {
347		err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
348		    DMU_POOL_EMPTY_BPOBJ, sizeof (uint64_t), 1,
349		    &dp->dp_empty_bpobj);
350		if (err != 0)
351			goto out;
352	}
353
354	err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
355	    DMU_POOL_TMP_USERREFS, sizeof (uint64_t), 1,
356	    &dp->dp_tmp_userrefs_obj);
357	if (err == ENOENT)
358		err = 0;
359	if (err)
360		goto out;
361
362	err = dsl_scan_init(dp, dp->dp_tx.tx_open_txg);
363
364out:
365	rrw_exit(&dp->dp_config_rwlock, FTAG);
366	return (err);
367}
368
369void
370dsl_pool_close(dsl_pool_t *dp)
371{
372	/*
373	 * Drop our references from dsl_pool_open().
374	 *
375	 * Since we held the origin_snap from "syncing" context (which
376	 * includes pool-opening context), it actually only got a "ref"
377	 * and not a hold, so just drop that here.
378	 */
379	if (dp->dp_origin_snap)
380		dsl_dataset_rele(dp->dp_origin_snap, dp);
381	if (dp->dp_mos_dir)
382		dsl_dir_rele(dp->dp_mos_dir, dp);
383	if (dp->dp_free_dir)
384		dsl_dir_rele(dp->dp_free_dir, dp);
385	if (dp->dp_leak_dir)
386		dsl_dir_rele(dp->dp_leak_dir, dp);
387	if (dp->dp_root_dir)
388		dsl_dir_rele(dp->dp_root_dir, dp);
389
390	bpobj_close(&dp->dp_free_bpobj);
391
392	/* undo the dmu_objset_open_impl(mos) from dsl_pool_open() */
393	if (dp->dp_meta_objset)
394		dmu_objset_evict(dp->dp_meta_objset);
395
396	txg_list_destroy(&dp->dp_dirty_datasets);
397	txg_list_destroy(&dp->dp_dirty_zilogs);
398	txg_list_destroy(&dp->dp_sync_tasks);
399	txg_list_destroy(&dp->dp_dirty_dirs);
400
401	arc_flush(dp->dp_spa);
402	txg_fini(dp);
403	dsl_scan_fini(dp);
404	rrw_destroy(&dp->dp_config_rwlock);
405	mutex_destroy(&dp->dp_lock);
406	taskq_destroy(dp->dp_vnrele_taskq);
407	if (dp->dp_blkstats)
408		kmem_free(dp->dp_blkstats, sizeof (zfs_all_blkstats_t));
409	kmem_free(dp, sizeof (dsl_pool_t));
410}
411
412dsl_pool_t *
413dsl_pool_create(spa_t *spa, nvlist_t *zplprops, uint64_t txg)
414{
415	int err;
416	dsl_pool_t *dp = dsl_pool_open_impl(spa, txg);
417	dmu_tx_t *tx = dmu_tx_create_assigned(dp, txg);
418	objset_t *os;
419	dsl_dataset_t *ds;
420	uint64_t obj;
421
422	rrw_enter(&dp->dp_config_rwlock, RW_WRITER, FTAG);
423
424	/* create and open the MOS (meta-objset) */
425	dp->dp_meta_objset = dmu_objset_create_impl(spa,
426	    NULL, &dp->dp_meta_rootbp, DMU_OST_META, tx);
427
428	/* create the pool directory */
429	err = zap_create_claim(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
430	    DMU_OT_OBJECT_DIRECTORY, DMU_OT_NONE, 0, tx);
431	ASSERT0(err);
432
433	/* Initialize scan structures */
434	VERIFY0(dsl_scan_init(dp, txg));
435
436	/* create and open the root dir */
437	dp->dp_root_dir_obj = dsl_dir_create_sync(dp, NULL, NULL, tx);
438	VERIFY0(dsl_dir_hold_obj(dp, dp->dp_root_dir_obj,
439	    NULL, dp, &dp->dp_root_dir));
440
441	/* create and open the meta-objset dir */
442	(void) dsl_dir_create_sync(dp, dp->dp_root_dir, MOS_DIR_NAME, tx);
443	VERIFY0(dsl_pool_open_special_dir(dp,
444	    MOS_DIR_NAME, &dp->dp_mos_dir));
445
446	if (spa_version(spa) >= SPA_VERSION_DEADLISTS) {
447		/* create and open the free dir */
448		(void) dsl_dir_create_sync(dp, dp->dp_root_dir,
449		    FREE_DIR_NAME, tx);
450		VERIFY0(dsl_pool_open_special_dir(dp,
451		    FREE_DIR_NAME, &dp->dp_free_dir));
452
453		/* create and open the free_bplist */
454		obj = bpobj_alloc(dp->dp_meta_objset, SPA_MAXBLOCKSIZE, tx);
455		VERIFY(zap_add(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
456		    DMU_POOL_FREE_BPOBJ, sizeof (uint64_t), 1, &obj, tx) == 0);
457		VERIFY0(bpobj_open(&dp->dp_free_bpobj,
458		    dp->dp_meta_objset, obj));
459	}
460
461	if (spa_version(spa) >= SPA_VERSION_DSL_SCRUB)
462		dsl_pool_create_origin(dp, tx);
463
464	/* create the root dataset */
465	obj = dsl_dataset_create_sync_dd(dp->dp_root_dir, NULL, 0, tx);
466
467	/* create the root objset */
468	VERIFY0(dsl_dataset_hold_obj(dp, obj, FTAG, &ds));
469	os = dmu_objset_create_impl(dp->dp_spa, ds,
470	    dsl_dataset_get_blkptr(ds), DMU_OST_ZFS, tx);
471#ifdef _KERNEL
472	zfs_create_fs(os, kcred, zplprops, tx);
473#endif
474	dsl_dataset_rele(ds, FTAG);
475
476	dmu_tx_commit(tx);
477
478	rrw_exit(&dp->dp_config_rwlock, FTAG);
479
480	return (dp);
481}
482
483/*
484 * Account for the meta-objset space in its placeholder dsl_dir.
485 */
486void
487dsl_pool_mos_diduse_space(dsl_pool_t *dp,
488    int64_t used, int64_t comp, int64_t uncomp)
489{
490	ASSERT3U(comp, ==, uncomp); /* it's all metadata */
491	mutex_enter(&dp->dp_lock);
492	dp->dp_mos_used_delta += used;
493	dp->dp_mos_compressed_delta += comp;
494	dp->dp_mos_uncompressed_delta += uncomp;
495	mutex_exit(&dp->dp_lock);
496}
497
498static int
499deadlist_enqueue_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
500{
501	dsl_deadlist_t *dl = arg;
502	dsl_deadlist_insert(dl, bp, tx);
503	return (0);
504}
505
506static void
507dsl_pool_sync_mos(dsl_pool_t *dp, dmu_tx_t *tx)
508{
509	zio_t *zio = zio_root(dp->dp_spa, NULL, NULL, ZIO_FLAG_MUSTSUCCEED);
510	dmu_objset_sync(dp->dp_meta_objset, zio, tx);
511	VERIFY0(zio_wait(zio));
512	dprintf_bp(&dp->dp_meta_rootbp, "meta objset rootbp is %s", "");
513	spa_set_rootblkptr(dp->dp_spa, &dp->dp_meta_rootbp);
514}
515
516static void
517dsl_pool_dirty_delta(dsl_pool_t *dp, int64_t delta)
518{
519	ASSERT(MUTEX_HELD(&dp->dp_lock));
520
521	if (delta < 0)
522		ASSERT3U(-delta, <=, dp->dp_dirty_total);
523
524	dp->dp_dirty_total += delta;
525
526	/*
527	 * Note: we signal even when increasing dp_dirty_total.
528	 * This ensures forward progress -- each thread wakes the next waiter.
529	 */
530	if (dp->dp_dirty_total <= zfs_dirty_data_max)
531		cv_signal(&dp->dp_spaceavail_cv);
532}
533
534void
535dsl_pool_sync(dsl_pool_t *dp, uint64_t txg)
536{
537	zio_t *zio;
538	dmu_tx_t *tx;
539	dsl_dir_t *dd;
540	dsl_dataset_t *ds;
541	objset_t *mos = dp->dp_meta_objset;
542	list_t synced_datasets;
543
544	list_create(&synced_datasets, sizeof (dsl_dataset_t),
545	    offsetof(dsl_dataset_t, ds_synced_link));
546
547	tx = dmu_tx_create_assigned(dp, txg);
548
549	/*
550	 * Write out all dirty blocks of dirty datasets.
551	 */
552	zio = zio_root(dp->dp_spa, NULL, NULL, ZIO_FLAG_MUSTSUCCEED);
553	while ((ds = txg_list_remove(&dp->dp_dirty_datasets, txg)) != NULL) {
554		/*
555		 * We must not sync any non-MOS datasets twice, because
556		 * we may have taken a snapshot of them.  However, we
557		 * may sync newly-created datasets on pass 2.
558		 */
559		ASSERT(!list_link_active(&ds->ds_synced_link));
560		list_insert_tail(&synced_datasets, ds);
561		dsl_dataset_sync(ds, zio, tx);
562	}
563	VERIFY0(zio_wait(zio));
564
565	/*
566	 * We have written all of the accounted dirty data, so our
567	 * dp_space_towrite should now be zero.  However, some seldom-used
568	 * code paths do not adhere to this (e.g. dbuf_undirty(), also
569	 * rounding error in dbuf_write_physdone).
570	 * Shore up the accounting of any dirtied space now.
571	 */
572	dsl_pool_undirty_space(dp, dp->dp_dirty_pertxg[txg & TXG_MASK], txg);
573
574	/*
575	 * After the data blocks have been written (ensured by the zio_wait()
576	 * above), update the user/group space accounting.
577	 */
578	for (ds = list_head(&synced_datasets); ds != NULL;
579	    ds = list_next(&synced_datasets, ds)) {
580		dmu_objset_do_userquota_updates(ds->ds_objset, tx);
581	}
582
583	/*
584	 * Sync the datasets again to push out the changes due to
585	 * userspace updates.  This must be done before we process the
586	 * sync tasks, so that any snapshots will have the correct
587	 * user accounting information (and we won't get confused
588	 * about which blocks are part of the snapshot).
589	 */
590	zio = zio_root(dp->dp_spa, NULL, NULL, ZIO_FLAG_MUSTSUCCEED);
591	while ((ds = txg_list_remove(&dp->dp_dirty_datasets, txg)) != NULL) {
592		ASSERT(list_link_active(&ds->ds_synced_link));
593		dmu_buf_rele(ds->ds_dbuf, ds);
594		dsl_dataset_sync(ds, zio, tx);
595	}
596	VERIFY0(zio_wait(zio));
597
598	/*
599	 * Now that the datasets have been completely synced, we can
600	 * clean up our in-memory structures accumulated while syncing:
601	 *
602	 *  - move dead blocks from the pending deadlist to the on-disk deadlist
603	 *  - release hold from dsl_dataset_dirty()
604	 */
605	while ((ds = list_remove_head(&synced_datasets)) != NULL) {
606		objset_t *os = ds->ds_objset;
607		bplist_iterate(&ds->ds_pending_deadlist,
608		    deadlist_enqueue_cb, &ds->ds_deadlist, tx);
609		ASSERT(!dmu_objset_is_dirty(os, txg));
610		dmu_buf_rele(ds->ds_dbuf, ds);
611	}
612	while ((dd = txg_list_remove(&dp->dp_dirty_dirs, txg)) != NULL) {
613		dsl_dir_sync(dd, tx);
614	}
615
616	/*
617	 * The MOS's space is accounted for in the pool/$MOS
618	 * (dp_mos_dir).  We can't modify the mos while we're syncing
619	 * it, so we remember the deltas and apply them here.
620	 */
621	if (dp->dp_mos_used_delta != 0 || dp->dp_mos_compressed_delta != 0 ||
622	    dp->dp_mos_uncompressed_delta != 0) {
623		dsl_dir_diduse_space(dp->dp_mos_dir, DD_USED_HEAD,
624		    dp->dp_mos_used_delta,
625		    dp->dp_mos_compressed_delta,
626		    dp->dp_mos_uncompressed_delta, tx);
627		dp->dp_mos_used_delta = 0;
628		dp->dp_mos_compressed_delta = 0;
629		dp->dp_mos_uncompressed_delta = 0;
630	}
631
632	if (list_head(&mos->os_dirty_dnodes[txg & TXG_MASK]) != NULL ||
633	    list_head(&mos->os_free_dnodes[txg & TXG_MASK]) != NULL) {
634		dsl_pool_sync_mos(dp, tx);
635	}
636
637	/*
638	 * If we modify a dataset in the same txg that we want to destroy it,
639	 * its dsl_dir's dd_dbuf will be dirty, and thus have a hold on it.
640	 * dsl_dir_destroy_check() will fail if there are unexpected holds.
641	 * Therefore, we want to sync the MOS (thus syncing the dd_dbuf
642	 * and clearing the hold on it) before we process the sync_tasks.
643	 * The MOS data dirtied by the sync_tasks will be synced on the next
644	 * pass.
645	 */
646	if (!txg_list_empty(&dp->dp_sync_tasks, txg)) {
647		dsl_sync_task_t *dst;
648		/*
649		 * No more sync tasks should have been added while we
650		 * were syncing.
651		 */
652		ASSERT3U(spa_sync_pass(dp->dp_spa), ==, 1);
653		while ((dst = txg_list_remove(&dp->dp_sync_tasks, txg)) != NULL)
654			dsl_sync_task_sync(dst, tx);
655	}
656
657	dmu_tx_commit(tx);
658
659	DTRACE_PROBE2(dsl_pool_sync__done, dsl_pool_t *dp, dp, uint64_t, txg);
660}
661
662void
663dsl_pool_sync_done(dsl_pool_t *dp, uint64_t txg)
664{
665	zilog_t *zilog;
666
667	while (zilog = txg_list_remove(&dp->dp_dirty_zilogs, txg)) {
668		dsl_dataset_t *ds = dmu_objset_ds(zilog->zl_os);
669		zil_clean(zilog, txg);
670		ASSERT(!dmu_objset_is_dirty(zilog->zl_os, txg));
671		dmu_buf_rele(ds->ds_dbuf, zilog);
672	}
673	ASSERT(!dmu_objset_is_dirty(dp->dp_meta_objset, txg));
674}
675
676/*
677 * TRUE if the current thread is the tx_sync_thread or if we
678 * are being called from SPA context during pool initialization.
679 */
680int
681dsl_pool_sync_context(dsl_pool_t *dp)
682{
683	return (curthread == dp->dp_tx.tx_sync_thread ||
684	    spa_is_initializing(dp->dp_spa));
685}
686
687uint64_t
688dsl_pool_adjustedsize(dsl_pool_t *dp, boolean_t netfree)
689{
690	uint64_t space, resv;
691
692	/*
693	 * If we're trying to assess whether it's OK to do a free,
694	 * cut the reservation in half to allow forward progress
695	 * (e.g. make it possible to rm(1) files from a full pool).
696	 */
697	space = spa_get_dspace(dp->dp_spa);
698	resv = spa_get_slop_space(dp->dp_spa);
699	if (netfree)
700		resv >>= 1;
701
702	return (space - resv);
703}
704
705boolean_t
706dsl_pool_need_dirty_delay(dsl_pool_t *dp)
707{
708	uint64_t delay_min_bytes =
709	    zfs_dirty_data_max * zfs_delay_min_dirty_percent / 100;
710	boolean_t rv;
711
712	mutex_enter(&dp->dp_lock);
713	if (dp->dp_dirty_total > zfs_dirty_data_sync)
714		txg_kick(dp);
715	rv = (dp->dp_dirty_total > delay_min_bytes);
716	mutex_exit(&dp->dp_lock);
717	return (rv);
718}
719
720void
721dsl_pool_dirty_space(dsl_pool_t *dp, int64_t space, dmu_tx_t *tx)
722{
723	if (space > 0) {
724		mutex_enter(&dp->dp_lock);
725		dp->dp_dirty_pertxg[tx->tx_txg & TXG_MASK] += space;
726		dsl_pool_dirty_delta(dp, space);
727		mutex_exit(&dp->dp_lock);
728	}
729}
730
731void
732dsl_pool_undirty_space(dsl_pool_t *dp, int64_t space, uint64_t txg)
733{
734	ASSERT3S(space, >=, 0);
735	if (space == 0)
736		return;
737	mutex_enter(&dp->dp_lock);
738	if (dp->dp_dirty_pertxg[txg & TXG_MASK] < space) {
739		/* XXX writing something we didn't dirty? */
740		space = dp->dp_dirty_pertxg[txg & TXG_MASK];
741	}
742	ASSERT3U(dp->dp_dirty_pertxg[txg & TXG_MASK], >=, space);
743	dp->dp_dirty_pertxg[txg & TXG_MASK] -= space;
744	ASSERT3U(dp->dp_dirty_total, >=, space);
745	dsl_pool_dirty_delta(dp, -space);
746	mutex_exit(&dp->dp_lock);
747}
748
749/* ARGSUSED */
750static int
751upgrade_clones_cb(dsl_pool_t *dp, dsl_dataset_t *hds, void *arg)
752{
753	dmu_tx_t *tx = arg;
754	dsl_dataset_t *ds, *prev = NULL;
755	int err;
756
757	err = dsl_dataset_hold_obj(dp, hds->ds_object, FTAG, &ds);
758	if (err)
759		return (err);
760
761	while (ds->ds_phys->ds_prev_snap_obj != 0) {
762		err = dsl_dataset_hold_obj(dp, ds->ds_phys->ds_prev_snap_obj,
763		    FTAG, &prev);
764		if (err) {
765			dsl_dataset_rele(ds, FTAG);
766			return (err);
767		}
768
769		if (prev->ds_phys->ds_next_snap_obj != ds->ds_object)
770			break;
771		dsl_dataset_rele(ds, FTAG);
772		ds = prev;
773		prev = NULL;
774	}
775
776	if (prev == NULL) {
777		prev = dp->dp_origin_snap;
778
779		/*
780		 * The $ORIGIN can't have any data, or the accounting
781		 * will be wrong.
782		 */
783		ASSERT0(prev->ds_phys->ds_bp.blk_birth);
784
785		/* The origin doesn't get attached to itself */
786		if (ds->ds_object == prev->ds_object) {
787			dsl_dataset_rele(ds, FTAG);
788			return (0);
789		}
790
791		dmu_buf_will_dirty(ds->ds_dbuf, tx);
792		ds->ds_phys->ds_prev_snap_obj = prev->ds_object;
793		ds->ds_phys->ds_prev_snap_txg = prev->ds_phys->ds_creation_txg;
794
795		dmu_buf_will_dirty(ds->ds_dir->dd_dbuf, tx);
796		ds->ds_dir->dd_phys->dd_origin_obj = prev->ds_object;
797
798		dmu_buf_will_dirty(prev->ds_dbuf, tx);
799		prev->ds_phys->ds_num_children++;
800
801		if (ds->ds_phys->ds_next_snap_obj == 0) {
802			ASSERT(ds->ds_prev == NULL);
803			VERIFY0(dsl_dataset_hold_obj(dp,
804			    ds->ds_phys->ds_prev_snap_obj, ds, &ds->ds_prev));
805		}
806	}
807
808	ASSERT3U(ds->ds_dir->dd_phys->dd_origin_obj, ==, prev->ds_object);
809	ASSERT3U(ds->ds_phys->ds_prev_snap_obj, ==, prev->ds_object);
810
811	if (prev->ds_phys->ds_next_clones_obj == 0) {
812		dmu_buf_will_dirty(prev->ds_dbuf, tx);
813		prev->ds_phys->ds_next_clones_obj =
814		    zap_create(dp->dp_meta_objset,
815		    DMU_OT_NEXT_CLONES, DMU_OT_NONE, 0, tx);
816	}
817	VERIFY0(zap_add_int(dp->dp_meta_objset,
818	    prev->ds_phys->ds_next_clones_obj, ds->ds_object, tx));
819
820	dsl_dataset_rele(ds, FTAG);
821	if (prev != dp->dp_origin_snap)
822		dsl_dataset_rele(prev, FTAG);
823	return (0);
824}
825
826void
827dsl_pool_upgrade_clones(dsl_pool_t *dp, dmu_tx_t *tx)
828{
829	ASSERT(dmu_tx_is_syncing(tx));
830	ASSERT(dp->dp_origin_snap != NULL);
831
832	VERIFY0(dmu_objset_find_dp(dp, dp->dp_root_dir_obj, upgrade_clones_cb,
833	    tx, DS_FIND_CHILDREN));
834}
835
836/* ARGSUSED */
837static int
838upgrade_dir_clones_cb(dsl_pool_t *dp, dsl_dataset_t *ds, void *arg)
839{
840	dmu_tx_t *tx = arg;
841	objset_t *mos = dp->dp_meta_objset;
842
843	if (ds->ds_dir->dd_phys->dd_origin_obj != 0) {
844		dsl_dataset_t *origin;
845
846		VERIFY0(dsl_dataset_hold_obj(dp,
847		    ds->ds_dir->dd_phys->dd_origin_obj, FTAG, &origin));
848
849		if (origin->ds_dir->dd_phys->dd_clones == 0) {
850			dmu_buf_will_dirty(origin->ds_dir->dd_dbuf, tx);
851			origin->ds_dir->dd_phys->dd_clones = zap_create(mos,
852			    DMU_OT_DSL_CLONES, DMU_OT_NONE, 0, tx);
853		}
854
855		VERIFY0(zap_add_int(dp->dp_meta_objset,
856		    origin->ds_dir->dd_phys->dd_clones, ds->ds_object, tx));
857
858		dsl_dataset_rele(origin, FTAG);
859	}
860	return (0);
861}
862
863void
864dsl_pool_upgrade_dir_clones(dsl_pool_t *dp, dmu_tx_t *tx)
865{
866	ASSERT(dmu_tx_is_syncing(tx));
867	uint64_t obj;
868
869	(void) dsl_dir_create_sync(dp, dp->dp_root_dir, FREE_DIR_NAME, tx);
870	VERIFY0(dsl_pool_open_special_dir(dp,
871	    FREE_DIR_NAME, &dp->dp_free_dir));
872
873	/*
874	 * We can't use bpobj_alloc(), because spa_version() still
875	 * returns the old version, and we need a new-version bpobj with
876	 * subobj support.  So call dmu_object_alloc() directly.
877	 */
878	obj = dmu_object_alloc(dp->dp_meta_objset, DMU_OT_BPOBJ,
879	    SPA_MAXBLOCKSIZE, DMU_OT_BPOBJ_HDR, sizeof (bpobj_phys_t), tx);
880	VERIFY0(zap_add(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
881	    DMU_POOL_FREE_BPOBJ, sizeof (uint64_t), 1, &obj, tx));
882	VERIFY0(bpobj_open(&dp->dp_free_bpobj, dp->dp_meta_objset, obj));
883
884	VERIFY0(dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
885	    upgrade_dir_clones_cb, tx, DS_FIND_CHILDREN));
886}
887
888void
889dsl_pool_create_origin(dsl_pool_t *dp, dmu_tx_t *tx)
890{
891	uint64_t dsobj;
892	dsl_dataset_t *ds;
893
894	ASSERT(dmu_tx_is_syncing(tx));
895	ASSERT(dp->dp_origin_snap == NULL);
896	ASSERT(rrw_held(&dp->dp_config_rwlock, RW_WRITER));
897
898	/* create the origin dir, ds, & snap-ds */
899	dsobj = dsl_dataset_create_sync(dp->dp_root_dir, ORIGIN_DIR_NAME,
900	    NULL, 0, kcred, tx);
901	VERIFY0(dsl_dataset_hold_obj(dp, dsobj, FTAG, &ds));
902	dsl_dataset_snapshot_sync_impl(ds, ORIGIN_DIR_NAME, tx);
903	VERIFY0(dsl_dataset_hold_obj(dp, ds->ds_phys->ds_prev_snap_obj,
904	    dp, &dp->dp_origin_snap));
905	dsl_dataset_rele(ds, FTAG);
906}
907
908taskq_t *
909dsl_pool_vnrele_taskq(dsl_pool_t *dp)
910{
911	return (dp->dp_vnrele_taskq);
912}
913
914/*
915 * Walk through the pool-wide zap object of temporary snapshot user holds
916 * and release them.
917 */
918void
919dsl_pool_clean_tmp_userrefs(dsl_pool_t *dp)
920{
921	zap_attribute_t za;
922	zap_cursor_t zc;
923	objset_t *mos = dp->dp_meta_objset;
924	uint64_t zapobj = dp->dp_tmp_userrefs_obj;
925	nvlist_t *holds;
926
927	if (zapobj == 0)
928		return;
929	ASSERT(spa_version(dp->dp_spa) >= SPA_VERSION_USERREFS);
930
931	holds = fnvlist_alloc();
932
933	for (zap_cursor_init(&zc, mos, zapobj);
934	    zap_cursor_retrieve(&zc, &za) == 0;
935	    zap_cursor_advance(&zc)) {
936		char *htag;
937		nvlist_t *tags;
938
939		htag = strchr(za.za_name, '-');
940		*htag = '\0';
941		++htag;
942		if (nvlist_lookup_nvlist(holds, za.za_name, &tags) != 0) {
943			tags = fnvlist_alloc();
944			fnvlist_add_boolean(tags, htag);
945			fnvlist_add_nvlist(holds, za.za_name, tags);
946			fnvlist_free(tags);
947		} else {
948			fnvlist_add_boolean(tags, htag);
949		}
950	}
951	dsl_dataset_user_release_tmp(dp, holds);
952	fnvlist_free(holds);
953	zap_cursor_fini(&zc);
954}
955
956/*
957 * Create the pool-wide zap object for storing temporary snapshot holds.
958 */
959void
960dsl_pool_user_hold_create_obj(dsl_pool_t *dp, dmu_tx_t *tx)
961{
962	objset_t *mos = dp->dp_meta_objset;
963
964	ASSERT(dp->dp_tmp_userrefs_obj == 0);
965	ASSERT(dmu_tx_is_syncing(tx));
966
967	dp->dp_tmp_userrefs_obj = zap_create_link(mos, DMU_OT_USERREFS,
968	    DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_TMP_USERREFS, tx);
969}
970
971static int
972dsl_pool_user_hold_rele_impl(dsl_pool_t *dp, uint64_t dsobj,
973    const char *tag, uint64_t now, dmu_tx_t *tx, boolean_t holding)
974{
975	objset_t *mos = dp->dp_meta_objset;
976	uint64_t zapobj = dp->dp_tmp_userrefs_obj;
977	char *name;
978	int error;
979
980	ASSERT(spa_version(dp->dp_spa) >= SPA_VERSION_USERREFS);
981	ASSERT(dmu_tx_is_syncing(tx));
982
983	/*
984	 * If the pool was created prior to SPA_VERSION_USERREFS, the
985	 * zap object for temporary holds might not exist yet.
986	 */
987	if (zapobj == 0) {
988		if (holding) {
989			dsl_pool_user_hold_create_obj(dp, tx);
990			zapobj = dp->dp_tmp_userrefs_obj;
991		} else {
992			return (SET_ERROR(ENOENT));
993		}
994	}
995
996	name = kmem_asprintf("%llx-%s", (u_longlong_t)dsobj, tag);
997	if (holding)
998		error = zap_add(mos, zapobj, name, 8, 1, &now, tx);
999	else
1000		error = zap_remove(mos, zapobj, name, tx);
1001	strfree(name);
1002
1003	return (error);
1004}
1005
1006/*
1007 * Add a temporary hold for the given dataset object and tag.
1008 */
1009int
1010dsl_pool_user_hold(dsl_pool_t *dp, uint64_t dsobj, const char *tag,
1011    uint64_t now, dmu_tx_t *tx)
1012{
1013	return (dsl_pool_user_hold_rele_impl(dp, dsobj, tag, now, tx, B_TRUE));
1014}
1015
1016/*
1017 * Release a temporary hold for the given dataset object and tag.
1018 */
1019int
1020dsl_pool_user_release(dsl_pool_t *dp, uint64_t dsobj, const char *tag,
1021    dmu_tx_t *tx)
1022{
1023	return (dsl_pool_user_hold_rele_impl(dp, dsobj, tag, 0,
1024	    tx, B_FALSE));
1025}
1026
1027/*
1028 * DSL Pool Configuration Lock
1029 *
1030 * The dp_config_rwlock protects against changes to DSL state (e.g. dataset
1031 * creation / destruction / rename / property setting).  It must be held for
1032 * read to hold a dataset or dsl_dir.  I.e. you must call
1033 * dsl_pool_config_enter() or dsl_pool_hold() before calling
1034 * dsl_{dataset,dir}_hold{_obj}.  In most circumstances, the dp_config_rwlock
1035 * must be held continuously until all datasets and dsl_dirs are released.
1036 *
1037 * The only exception to this rule is that if a "long hold" is placed on
1038 * a dataset, then the dp_config_rwlock may be dropped while the dataset
1039 * is still held.  The long hold will prevent the dataset from being
1040 * destroyed -- the destroy will fail with EBUSY.  A long hold can be
1041 * obtained by calling dsl_dataset_long_hold(), or by "owning" a dataset
1042 * (by calling dsl_{dataset,objset}_{try}own{_obj}).
1043 *
1044 * Legitimate long-holders (including owners) should be long-running, cancelable
1045 * tasks that should cause "zfs destroy" to fail.  This includes DMU
1046 * consumers (i.e. a ZPL filesystem being mounted or ZVOL being open),
1047 * "zfs send", and "zfs diff".  There are several other long-holders whose
1048 * uses are suboptimal (e.g. "zfs promote", and zil_suspend()).
1049 *
1050 * The usual formula for long-holding would be:
1051 * dsl_pool_hold()
1052 * dsl_dataset_hold()
1053 * ... perform checks ...
1054 * dsl_dataset_long_hold()
1055 * dsl_pool_rele()
1056 * ... perform long-running task ...
1057 * dsl_dataset_long_rele()
1058 * dsl_dataset_rele()
1059 *
1060 * Note that when the long hold is released, the dataset is still held but
1061 * the pool is not held.  The dataset may change arbitrarily during this time
1062 * (e.g. it could be destroyed).  Therefore you shouldn't do anything to the
1063 * dataset except release it.
1064 *
1065 * User-initiated operations (e.g. ioctls, zfs_ioc_*()) are either read-only
1066 * or modifying operations.
1067 *
1068 * Modifying operations should generally use dsl_sync_task().  The synctask
1069 * infrastructure enforces proper locking strategy with respect to the
1070 * dp_config_rwlock.  See the comment above dsl_sync_task() for details.
1071 *
1072 * Read-only operations will manually hold the pool, then the dataset, obtain
1073 * information from the dataset, then release the pool and dataset.
1074 * dmu_objset_{hold,rele}() are convenience routines that also do the pool
1075 * hold/rele.
1076 */
1077
1078int
1079dsl_pool_hold(const char *name, void *tag, dsl_pool_t **dp)
1080{
1081	spa_t *spa;
1082	int error;
1083
1084	error = spa_open(name, &spa, tag);
1085	if (error == 0) {
1086		*dp = spa_get_dsl(spa);
1087		dsl_pool_config_enter(*dp, tag);
1088	}
1089	return (error);
1090}
1091
1092void
1093dsl_pool_rele(dsl_pool_t *dp, void *tag)
1094{
1095	dsl_pool_config_exit(dp, tag);
1096	spa_close(dp->dp_spa, tag);
1097}
1098
1099void
1100dsl_pool_config_enter(dsl_pool_t *dp, void *tag)
1101{
1102	/*
1103	 * We use a "reentrant" reader-writer lock, but not reentrantly.
1104	 *
1105	 * The rrwlock can (with the track_all flag) track all reading threads,
1106	 * which is very useful for debugging which code path failed to release
1107	 * the lock, and for verifying that the *current* thread does hold
1108	 * the lock.
1109	 *
1110	 * (Unlike a rwlock, which knows that N threads hold it for
1111	 * read, but not *which* threads, so rw_held(RW_READER) returns TRUE
1112	 * if any thread holds it for read, even if this thread doesn't).
1113	 */
1114	ASSERT(!rrw_held(&dp->dp_config_rwlock, RW_READER));
1115	rrw_enter(&dp->dp_config_rwlock, RW_READER, tag);
1116}
1117
1118void
1119dsl_pool_config_exit(dsl_pool_t *dp, void *tag)
1120{
1121	rrw_exit(&dp->dp_config_rwlock, tag);
1122}
1123
1124boolean_t
1125dsl_pool_config_held(dsl_pool_t *dp)
1126{
1127	return (RRW_LOCK_HELD(&dp->dp_config_rwlock));
1128}
1129