]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/cddl/contrib/opensolaris/uts/common/fs/zfs/dsl_pool.c
MFV r271515:
[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) 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  */
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 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  */
130 uint64_t zfs_delay_scale = 1000 * 1000 * 1000 / 2000;
131
132
133 #ifdef __FreeBSD__
134
135 extern int zfs_vdev_async_write_active_max_dirty_percent;
136
137 SYSCTL_DECL(_vfs_zfs);
138
139 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, dirty_data_max, CTLFLAG_RWTUN,
140     &zfs_dirty_data_max, 0,
141     "The maximum amount of dirty data in bytes after which new writes are "
142     "halted until space becomes available");
143
144 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, dirty_data_max_max, CTLFLAG_RDTUN,
145     &zfs_dirty_data_max_max, 0,
146     "The absolute cap on dirty_data_max when auto calculating");
147
148 SYSCTL_INT(_vfs_zfs, OID_AUTO, dirty_data_max_percent, CTLFLAG_RDTUN,
149     &zfs_dirty_data_max_percent, 0,
150     "The percent of physical memory used to auto calculate dirty_data_max");
151
152 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, dirty_data_sync, CTLFLAG_RWTUN,
153     &zfs_dirty_data_sync, 0,
154     "Force a txg if the number of dirty buffer bytes exceed this value");
155
156 static int sysctl_zfs_delay_min_dirty_percent(SYSCTL_HANDLER_ARGS);
157 /* No zfs_delay_min_dirty_percent tunable due to limit requirements */
158 SYSCTL_PROC(_vfs_zfs, OID_AUTO, delay_min_dirty_percent,
159     CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, sizeof(int),
160     sysctl_zfs_delay_min_dirty_percent, "I",
161     "The limit of outstanding dirty data before transations are delayed");
162
163 static int sysctl_zfs_delay_scale(SYSCTL_HANDLER_ARGS);
164 /* No zfs_delay_scale tunable due to limit requirements */
165 SYSCTL_PROC(_vfs_zfs, OID_AUTO, delay_scale,
166     CTLTYPE_U64 | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, sizeof(uint64_t),
167     sysctl_zfs_delay_scale, "QU",
168     "Controls how quickly the delay approaches infinity");
169
170 static int
171 sysctl_zfs_delay_min_dirty_percent(SYSCTL_HANDLER_ARGS)
172 {
173         int val, err;
174
175         val = zfs_delay_min_dirty_percent;
176         err = sysctl_handle_int(oidp, &val, 0, req);
177         if (err != 0 || req->newptr == NULL)
178                 return (err);
179
180         if (val < zfs_vdev_async_write_active_max_dirty_percent)
181                 return (EINVAL);
182
183         zfs_delay_min_dirty_percent = val;
184
185         return (0);
186 }
187
188 static int
189 sysctl_zfs_delay_scale(SYSCTL_HANDLER_ARGS)
190 {
191         uint64_t val;
192         int err;
193
194         val = zfs_delay_scale;
195         err = sysctl_handle_64(oidp, &val, 0, req);
196         if (err != 0 || req->newptr == NULL)
197                 return (err);
198
199         if (val > UINT64_MAX / zfs_dirty_data_max)
200                 return (EINVAL);
201
202         zfs_delay_scale = val;
203
204         return (0);
205 }
206 #endif
207
208 hrtime_t zfs_throttle_delay = MSEC2NSEC(10);
209 hrtime_t zfs_throttle_resolution = MSEC2NSEC(10);
210
211 int
212 dsl_pool_open_special_dir(dsl_pool_t *dp, const char *name, dsl_dir_t **ddp)
213 {
214         uint64_t obj;
215         int err;
216
217         err = zap_lookup(dp->dp_meta_objset,
218             dp->dp_root_dir->dd_phys->dd_child_dir_zapobj,
219             name, sizeof (obj), 1, &obj);
220         if (err)
221                 return (err);
222
223         return (dsl_dir_hold_obj(dp, obj, name, dp, ddp));
224 }
225
226 static dsl_pool_t *
227 dsl_pool_open_impl(spa_t *spa, uint64_t txg)
228 {
229         dsl_pool_t *dp;
230         blkptr_t *bp = spa_get_rootblkptr(spa);
231
232         dp = kmem_zalloc(sizeof (dsl_pool_t), KM_SLEEP);
233         dp->dp_spa = spa;
234         dp->dp_meta_rootbp = *bp;
235         rrw_init(&dp->dp_config_rwlock, B_TRUE);
236         txg_init(dp, txg);
237
238         txg_list_create(&dp->dp_dirty_datasets,
239             offsetof(dsl_dataset_t, ds_dirty_link));
240         txg_list_create(&dp->dp_dirty_zilogs,
241             offsetof(zilog_t, zl_dirty_link));
242         txg_list_create(&dp->dp_dirty_dirs,
243             offsetof(dsl_dir_t, dd_dirty_link));
244         txg_list_create(&dp->dp_sync_tasks,
245             offsetof(dsl_sync_task_t, dst_node));
246
247         mutex_init(&dp->dp_lock, NULL, MUTEX_DEFAULT, NULL);
248         cv_init(&dp->dp_spaceavail_cv, NULL, CV_DEFAULT, NULL);
249
250         dp->dp_vnrele_taskq = taskq_create("zfs_vn_rele_taskq", 1, minclsyspri,
251             1, 4, 0);
252
253         return (dp);
254 }
255
256 int
257 dsl_pool_init(spa_t *spa, uint64_t txg, dsl_pool_t **dpp)
258 {
259         int err;
260         dsl_pool_t *dp = dsl_pool_open_impl(spa, txg);
261
262         err = dmu_objset_open_impl(spa, NULL, &dp->dp_meta_rootbp,
263             &dp->dp_meta_objset);
264         if (err != 0)
265                 dsl_pool_close(dp);
266         else
267                 *dpp = dp;
268
269         return (err);
270 }
271
272 int
273 dsl_pool_open(dsl_pool_t *dp)
274 {
275         int err;
276         dsl_dir_t *dd;
277         dsl_dataset_t *ds;
278         uint64_t obj;
279
280         rrw_enter(&dp->dp_config_rwlock, RW_WRITER, FTAG);
281         err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
282             DMU_POOL_ROOT_DATASET, sizeof (uint64_t), 1,
283             &dp->dp_root_dir_obj);
284         if (err)
285                 goto out;
286
287         err = dsl_dir_hold_obj(dp, dp->dp_root_dir_obj,
288             NULL, dp, &dp->dp_root_dir);
289         if (err)
290                 goto out;
291
292         err = dsl_pool_open_special_dir(dp, MOS_DIR_NAME, &dp->dp_mos_dir);
293         if (err)
294                 goto out;
295
296         if (spa_version(dp->dp_spa) >= SPA_VERSION_ORIGIN) {
297                 err = dsl_pool_open_special_dir(dp, ORIGIN_DIR_NAME, &dd);
298                 if (err)
299                         goto out;
300                 err = dsl_dataset_hold_obj(dp, dd->dd_phys->dd_head_dataset_obj,
301                     FTAG, &ds);
302                 if (err == 0) {
303                         err = dsl_dataset_hold_obj(dp,
304                             ds->ds_phys->ds_prev_snap_obj, dp,
305                             &dp->dp_origin_snap);
306                         dsl_dataset_rele(ds, FTAG);
307                 }
308                 dsl_dir_rele(dd, dp);
309                 if (err)
310                         goto out;
311         }
312
313         if (spa_version(dp->dp_spa) >= SPA_VERSION_DEADLISTS) {
314                 err = dsl_pool_open_special_dir(dp, FREE_DIR_NAME,
315                     &dp->dp_free_dir);
316                 if (err)
317                         goto out;
318
319                 err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
320                     DMU_POOL_FREE_BPOBJ, sizeof (uint64_t), 1, &obj);
321                 if (err)
322                         goto out;
323                 VERIFY0(bpobj_open(&dp->dp_free_bpobj,
324                     dp->dp_meta_objset, obj));
325         }
326
327         /*
328          * Note: errors ignored, because the leak dir will not exist if we
329          * have not encountered a leak yet.
330          */
331         (void) dsl_pool_open_special_dir(dp, LEAK_DIR_NAME,
332             &dp->dp_leak_dir);
333
334         if (spa_feature_is_active(dp->dp_spa, SPA_FEATURE_ASYNC_DESTROY)) {
335                 err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
336                     DMU_POOL_BPTREE_OBJ, sizeof (uint64_t), 1,
337                     &dp->dp_bptree_obj);
338                 if (err != 0)
339                         goto out;
340         }
341
342         if (spa_feature_is_active(dp->dp_spa, SPA_FEATURE_EMPTY_BPOBJ)) {
343                 err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
344                     DMU_POOL_EMPTY_BPOBJ, sizeof (uint64_t), 1,
345                     &dp->dp_empty_bpobj);
346                 if (err != 0)
347                         goto out;
348         }
349
350         err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
351             DMU_POOL_TMP_USERREFS, sizeof (uint64_t), 1,
352             &dp->dp_tmp_userrefs_obj);
353         if (err == ENOENT)
354                 err = 0;
355         if (err)
356                 goto out;
357
358         err = dsl_scan_init(dp, dp->dp_tx.tx_open_txg);
359
360 out:
361         rrw_exit(&dp->dp_config_rwlock, FTAG);
362         return (err);
363 }
364
365 void
366 dsl_pool_close(dsl_pool_t *dp)
367 {
368         /*
369          * Drop our references from dsl_pool_open().
370          *
371          * Since we held the origin_snap from "syncing" context (which
372          * includes pool-opening context), it actually only got a "ref"
373          * and not a hold, so just drop that here.
374          */
375         if (dp->dp_origin_snap)
376                 dsl_dataset_rele(dp->dp_origin_snap, dp);
377         if (dp->dp_mos_dir)
378                 dsl_dir_rele(dp->dp_mos_dir, dp);
379         if (dp->dp_free_dir)
380                 dsl_dir_rele(dp->dp_free_dir, dp);
381         if (dp->dp_leak_dir)
382                 dsl_dir_rele(dp->dp_leak_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          * If we're trying to assess whether it's OK to do a free,
690          * cut the reservation in half to allow forward progress
691          * (e.g. make it possible to rm(1) files from a full pool).
692          */
693         space = spa_get_dspace(dp->dp_spa);
694         resv = spa_get_slop_space(dp->dp_spa);
695         if (netfree)
696                 resv >>= 1;
697
698         return (space - resv);
699 }
700
701 boolean_t
702 dsl_pool_need_dirty_delay(dsl_pool_t *dp)
703 {
704         uint64_t delay_min_bytes =
705             zfs_dirty_data_max * zfs_delay_min_dirty_percent / 100;
706         boolean_t rv;
707
708         mutex_enter(&dp->dp_lock);
709         if (dp->dp_dirty_total > zfs_dirty_data_sync)
710                 txg_kick(dp);
711         rv = (dp->dp_dirty_total > delay_min_bytes);
712         mutex_exit(&dp->dp_lock);
713         return (rv);
714 }
715
716 void
717 dsl_pool_dirty_space(dsl_pool_t *dp, int64_t space, dmu_tx_t *tx)
718 {
719         if (space > 0) {
720                 mutex_enter(&dp->dp_lock);
721                 dp->dp_dirty_pertxg[tx->tx_txg & TXG_MASK] += space;
722                 dsl_pool_dirty_delta(dp, space);
723                 mutex_exit(&dp->dp_lock);
724         }
725 }
726
727 void
728 dsl_pool_undirty_space(dsl_pool_t *dp, int64_t space, uint64_t txg)
729 {
730         ASSERT3S(space, >=, 0);
731         if (space == 0)
732                 return;
733         mutex_enter(&dp->dp_lock);
734         if (dp->dp_dirty_pertxg[txg & TXG_MASK] < space) {
735                 /* XXX writing something we didn't dirty? */
736                 space = dp->dp_dirty_pertxg[txg & TXG_MASK];
737         }
738         ASSERT3U(dp->dp_dirty_pertxg[txg & TXG_MASK], >=, space);
739         dp->dp_dirty_pertxg[txg & TXG_MASK] -= space;
740         ASSERT3U(dp->dp_dirty_total, >=, space);
741         dsl_pool_dirty_delta(dp, -space);
742         mutex_exit(&dp->dp_lock);
743 }
744
745 /* ARGSUSED */
746 static int
747 upgrade_clones_cb(dsl_pool_t *dp, dsl_dataset_t *hds, void *arg)
748 {
749         dmu_tx_t *tx = arg;
750         dsl_dataset_t *ds, *prev = NULL;
751         int err;
752
753         err = dsl_dataset_hold_obj(dp, hds->ds_object, FTAG, &ds);
754         if (err)
755                 return (err);
756
757         while (ds->ds_phys->ds_prev_snap_obj != 0) {
758                 err = dsl_dataset_hold_obj(dp, ds->ds_phys->ds_prev_snap_obj,
759                     FTAG, &prev);
760                 if (err) {
761                         dsl_dataset_rele(ds, FTAG);
762                         return (err);
763                 }
764
765                 if (prev->ds_phys->ds_next_snap_obj != ds->ds_object)
766                         break;
767                 dsl_dataset_rele(ds, FTAG);
768                 ds = prev;
769                 prev = NULL;
770         }
771
772         if (prev == NULL) {
773                 prev = dp->dp_origin_snap;
774
775                 /*
776                  * The $ORIGIN can't have any data, or the accounting
777                  * will be wrong.
778                  */
779                 ASSERT0(prev->ds_phys->ds_bp.blk_birth);
780
781                 /* The origin doesn't get attached to itself */
782                 if (ds->ds_object == prev->ds_object) {
783                         dsl_dataset_rele(ds, FTAG);
784                         return (0);
785                 }
786
787                 dmu_buf_will_dirty(ds->ds_dbuf, tx);
788                 ds->ds_phys->ds_prev_snap_obj = prev->ds_object;
789                 ds->ds_phys->ds_prev_snap_txg = prev->ds_phys->ds_creation_txg;
790
791                 dmu_buf_will_dirty(ds->ds_dir->dd_dbuf, tx);
792                 ds->ds_dir->dd_phys->dd_origin_obj = prev->ds_object;
793
794                 dmu_buf_will_dirty(prev->ds_dbuf, tx);
795                 prev->ds_phys->ds_num_children++;
796
797                 if (ds->ds_phys->ds_next_snap_obj == 0) {
798                         ASSERT(ds->ds_prev == NULL);
799                         VERIFY0(dsl_dataset_hold_obj(dp,
800                             ds->ds_phys->ds_prev_snap_obj, ds, &ds->ds_prev));
801                 }
802         }
803
804         ASSERT3U(ds->ds_dir->dd_phys->dd_origin_obj, ==, prev->ds_object);
805         ASSERT3U(ds->ds_phys->ds_prev_snap_obj, ==, prev->ds_object);
806
807         if (prev->ds_phys->ds_next_clones_obj == 0) {
808                 dmu_buf_will_dirty(prev->ds_dbuf, tx);
809                 prev->ds_phys->ds_next_clones_obj =
810                     zap_create(dp->dp_meta_objset,
811                     DMU_OT_NEXT_CLONES, DMU_OT_NONE, 0, tx);
812         }
813         VERIFY0(zap_add_int(dp->dp_meta_objset,
814             prev->ds_phys->ds_next_clones_obj, ds->ds_object, tx));
815
816         dsl_dataset_rele(ds, FTAG);
817         if (prev != dp->dp_origin_snap)
818                 dsl_dataset_rele(prev, FTAG);
819         return (0);
820 }
821
822 void
823 dsl_pool_upgrade_clones(dsl_pool_t *dp, dmu_tx_t *tx)
824 {
825         ASSERT(dmu_tx_is_syncing(tx));
826         ASSERT(dp->dp_origin_snap != NULL);
827
828         VERIFY0(dmu_objset_find_dp(dp, dp->dp_root_dir_obj, upgrade_clones_cb,
829             tx, DS_FIND_CHILDREN));
830 }
831
832 /* ARGSUSED */
833 static int
834 upgrade_dir_clones_cb(dsl_pool_t *dp, dsl_dataset_t *ds, void *arg)
835 {
836         dmu_tx_t *tx = arg;
837         objset_t *mos = dp->dp_meta_objset;
838
839         if (ds->ds_dir->dd_phys->dd_origin_obj != 0) {
840                 dsl_dataset_t *origin;
841
842                 VERIFY0(dsl_dataset_hold_obj(dp,
843                     ds->ds_dir->dd_phys->dd_origin_obj, FTAG, &origin));
844
845                 if (origin->ds_dir->dd_phys->dd_clones == 0) {
846                         dmu_buf_will_dirty(origin->ds_dir->dd_dbuf, tx);
847                         origin->ds_dir->dd_phys->dd_clones = zap_create(mos,
848                             DMU_OT_DSL_CLONES, DMU_OT_NONE, 0, tx);
849                 }
850
851                 VERIFY0(zap_add_int(dp->dp_meta_objset,
852                     origin->ds_dir->dd_phys->dd_clones, ds->ds_object, tx));
853
854                 dsl_dataset_rele(origin, FTAG);
855         }
856         return (0);
857 }
858
859 void
860 dsl_pool_upgrade_dir_clones(dsl_pool_t *dp, dmu_tx_t *tx)
861 {
862         ASSERT(dmu_tx_is_syncing(tx));
863         uint64_t obj;
864
865         (void) dsl_dir_create_sync(dp, dp->dp_root_dir, FREE_DIR_NAME, tx);
866         VERIFY0(dsl_pool_open_special_dir(dp,
867             FREE_DIR_NAME, &dp->dp_free_dir));
868
869         /*
870          * We can't use bpobj_alloc(), because spa_version() still
871          * returns the old version, and we need a new-version bpobj with
872          * subobj support.  So call dmu_object_alloc() directly.
873          */
874         obj = dmu_object_alloc(dp->dp_meta_objset, DMU_OT_BPOBJ,
875             SPA_MAXBLOCKSIZE, DMU_OT_BPOBJ_HDR, sizeof (bpobj_phys_t), tx);
876         VERIFY0(zap_add(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
877             DMU_POOL_FREE_BPOBJ, sizeof (uint64_t), 1, &obj, tx));
878         VERIFY0(bpobj_open(&dp->dp_free_bpobj, dp->dp_meta_objset, obj));
879
880         VERIFY0(dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
881             upgrade_dir_clones_cb, tx, DS_FIND_CHILDREN));
882 }
883
884 void
885 dsl_pool_create_origin(dsl_pool_t *dp, dmu_tx_t *tx)
886 {
887         uint64_t dsobj;
888         dsl_dataset_t *ds;
889
890         ASSERT(dmu_tx_is_syncing(tx));
891         ASSERT(dp->dp_origin_snap == NULL);
892         ASSERT(rrw_held(&dp->dp_config_rwlock, RW_WRITER));
893
894         /* create the origin dir, ds, & snap-ds */
895         dsobj = dsl_dataset_create_sync(dp->dp_root_dir, ORIGIN_DIR_NAME,
896             NULL, 0, kcred, tx);
897         VERIFY0(dsl_dataset_hold_obj(dp, dsobj, FTAG, &ds));
898         dsl_dataset_snapshot_sync_impl(ds, ORIGIN_DIR_NAME, tx);
899         VERIFY0(dsl_dataset_hold_obj(dp, ds->ds_phys->ds_prev_snap_obj,
900             dp, &dp->dp_origin_snap));
901         dsl_dataset_rele(ds, FTAG);
902 }
903
904 taskq_t *
905 dsl_pool_vnrele_taskq(dsl_pool_t *dp)
906 {
907         return (dp->dp_vnrele_taskq);
908 }
909
910 /*
911  * Walk through the pool-wide zap object of temporary snapshot user holds
912  * and release them.
913  */
914 void
915 dsl_pool_clean_tmp_userrefs(dsl_pool_t *dp)
916 {
917         zap_attribute_t za;
918         zap_cursor_t zc;
919         objset_t *mos = dp->dp_meta_objset;
920         uint64_t zapobj = dp->dp_tmp_userrefs_obj;
921         nvlist_t *holds;
922
923         if (zapobj == 0)
924                 return;
925         ASSERT(spa_version(dp->dp_spa) >= SPA_VERSION_USERREFS);
926
927         holds = fnvlist_alloc();
928
929         for (zap_cursor_init(&zc, mos, zapobj);
930             zap_cursor_retrieve(&zc, &za) == 0;
931             zap_cursor_advance(&zc)) {
932                 char *htag;
933                 nvlist_t *tags;
934
935                 htag = strchr(za.za_name, '-');
936                 *htag = '\0';
937                 ++htag;
938                 if (nvlist_lookup_nvlist(holds, za.za_name, &tags) != 0) {
939                         tags = fnvlist_alloc();
940                         fnvlist_add_boolean(tags, htag);
941                         fnvlist_add_nvlist(holds, za.za_name, tags);
942                         fnvlist_free(tags);
943                 } else {
944                         fnvlist_add_boolean(tags, htag);
945                 }
946         }
947         dsl_dataset_user_release_tmp(dp, holds);
948         fnvlist_free(holds);
949         zap_cursor_fini(&zc);
950 }
951
952 /*
953  * Create the pool-wide zap object for storing temporary snapshot holds.
954  */
955 void
956 dsl_pool_user_hold_create_obj(dsl_pool_t *dp, dmu_tx_t *tx)
957 {
958         objset_t *mos = dp->dp_meta_objset;
959
960         ASSERT(dp->dp_tmp_userrefs_obj == 0);
961         ASSERT(dmu_tx_is_syncing(tx));
962
963         dp->dp_tmp_userrefs_obj = zap_create_link(mos, DMU_OT_USERREFS,
964             DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_TMP_USERREFS, tx);
965 }
966
967 static int
968 dsl_pool_user_hold_rele_impl(dsl_pool_t *dp, uint64_t dsobj,
969     const char *tag, uint64_t now, dmu_tx_t *tx, boolean_t holding)
970 {
971         objset_t *mos = dp->dp_meta_objset;
972         uint64_t zapobj = dp->dp_tmp_userrefs_obj;
973         char *name;
974         int error;
975
976         ASSERT(spa_version(dp->dp_spa) >= SPA_VERSION_USERREFS);
977         ASSERT(dmu_tx_is_syncing(tx));
978
979         /*
980          * If the pool was created prior to SPA_VERSION_USERREFS, the
981          * zap object for temporary holds might not exist yet.
982          */
983         if (zapobj == 0) {
984                 if (holding) {
985                         dsl_pool_user_hold_create_obj(dp, tx);
986                         zapobj = dp->dp_tmp_userrefs_obj;
987                 } else {
988                         return (SET_ERROR(ENOENT));
989                 }
990         }
991
992         name = kmem_asprintf("%llx-%s", (u_longlong_t)dsobj, tag);
993         if (holding)
994                 error = zap_add(mos, zapobj, name, 8, 1, &now, tx);
995         else
996                 error = zap_remove(mos, zapobj, name, tx);
997         strfree(name);
998
999         return (error);
1000 }
1001
1002 /*
1003  * Add a temporary hold for the given dataset object and tag.
1004  */
1005 int
1006 dsl_pool_user_hold(dsl_pool_t *dp, uint64_t dsobj, const char *tag,
1007     uint64_t now, dmu_tx_t *tx)
1008 {
1009         return (dsl_pool_user_hold_rele_impl(dp, dsobj, tag, now, tx, B_TRUE));
1010 }
1011
1012 /*
1013  * Release a temporary hold for the given dataset object and tag.
1014  */
1015 int
1016 dsl_pool_user_release(dsl_pool_t *dp, uint64_t dsobj, const char *tag,
1017     dmu_tx_t *tx)
1018 {
1019         return (dsl_pool_user_hold_rele_impl(dp, dsobj, tag, 0,
1020             tx, B_FALSE));
1021 }
1022
1023 /*
1024  * DSL Pool Configuration Lock
1025  *
1026  * The dp_config_rwlock protects against changes to DSL state (e.g. dataset
1027  * creation / destruction / rename / property setting).  It must be held for
1028  * read to hold a dataset or dsl_dir.  I.e. you must call
1029  * dsl_pool_config_enter() or dsl_pool_hold() before calling
1030  * dsl_{dataset,dir}_hold{_obj}.  In most circumstances, the dp_config_rwlock
1031  * must be held continuously until all datasets and dsl_dirs are released.
1032  *
1033  * The only exception to this rule is that if a "long hold" is placed on
1034  * a dataset, then the dp_config_rwlock may be dropped while the dataset
1035  * is still held.  The long hold will prevent the dataset from being
1036  * destroyed -- the destroy will fail with EBUSY.  A long hold can be
1037  * obtained by calling dsl_dataset_long_hold(), or by "owning" a dataset
1038  * (by calling dsl_{dataset,objset}_{try}own{_obj}).
1039  *
1040  * Legitimate long-holders (including owners) should be long-running, cancelable
1041  * tasks that should cause "zfs destroy" to fail.  This includes DMU
1042  * consumers (i.e. a ZPL filesystem being mounted or ZVOL being open),
1043  * "zfs send", and "zfs diff".  There are several other long-holders whose
1044  * uses are suboptimal (e.g. "zfs promote", and zil_suspend()).
1045  *
1046  * The usual formula for long-holding would be:
1047  * dsl_pool_hold()
1048  * dsl_dataset_hold()
1049  * ... perform checks ...
1050  * dsl_dataset_long_hold()
1051  * dsl_pool_rele()
1052  * ... perform long-running task ...
1053  * dsl_dataset_long_rele()
1054  * dsl_dataset_rele()
1055  *
1056  * Note that when the long hold is released, the dataset is still held but
1057  * the pool is not held.  The dataset may change arbitrarily during this time
1058  * (e.g. it could be destroyed).  Therefore you shouldn't do anything to the
1059  * dataset except release it.
1060  *
1061  * User-initiated operations (e.g. ioctls, zfs_ioc_*()) are either read-only
1062  * or modifying operations.
1063  *
1064  * Modifying operations should generally use dsl_sync_task().  The synctask
1065  * infrastructure enforces proper locking strategy with respect to the
1066  * dp_config_rwlock.  See the comment above dsl_sync_task() for details.
1067  *
1068  * Read-only operations will manually hold the pool, then the dataset, obtain
1069  * information from the dataset, then release the pool and dataset.
1070  * dmu_objset_{hold,rele}() are convenience routines that also do the pool
1071  * hold/rele.
1072  */
1073
1074 int
1075 dsl_pool_hold(const char *name, void *tag, dsl_pool_t **dp)
1076 {
1077         spa_t *spa;
1078         int error;
1079
1080         error = spa_open(name, &spa, tag);
1081         if (error == 0) {
1082                 *dp = spa_get_dsl(spa);
1083                 dsl_pool_config_enter(*dp, tag);
1084         }
1085         return (error);
1086 }
1087
1088 void
1089 dsl_pool_rele(dsl_pool_t *dp, void *tag)
1090 {
1091         dsl_pool_config_exit(dp, tag);
1092         spa_close(dp->dp_spa, tag);
1093 }
1094
1095 void
1096 dsl_pool_config_enter(dsl_pool_t *dp, void *tag)
1097 {
1098         /*
1099          * We use a "reentrant" reader-writer lock, but not reentrantly.
1100          *
1101          * The rrwlock can (with the track_all flag) track all reading threads,
1102          * which is very useful for debugging which code path failed to release
1103          * the lock, and for verifying that the *current* thread does hold
1104          * the lock.
1105          *
1106          * (Unlike a rwlock, which knows that N threads hold it for
1107          * read, but not *which* threads, so rw_held(RW_READER) returns TRUE
1108          * if any thread holds it for read, even if this thread doesn't).
1109          */
1110         ASSERT(!rrw_held(&dp->dp_config_rwlock, RW_READER));
1111         rrw_enter(&dp->dp_config_rwlock, RW_READER, tag);
1112 }
1113
1114 void
1115 dsl_pool_config_exit(dsl_pool_t *dp, void *tag)
1116 {
1117         rrw_exit(&dp->dp_config_rwlock, tag);
1118 }
1119
1120 boolean_t
1121 dsl_pool_config_held(dsl_pool_t *dp)
1122 {
1123         return (RRW_LOCK_HELD(&dp->dp_config_rwlock));
1124 }