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