]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/cddl/contrib/opensolaris/uts/common/fs/zfs/dsl_pool.c
MFV r268850:
[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 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 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, dirty_data_max, CTLFLAG_RWTUN,
145     &zfs_dirty_data_max, 0,
146     "The maximum amount of dirty data in bytes after which new writes are "
147     "halted until space becomes available");
148
149 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, dirty_data_max_max, CTLFLAG_RDTUN,
150     &zfs_dirty_data_max_max, 0,
151     "The absolute cap on dirty_data_max when auto calculating");
152
153 SYSCTL_INT(_vfs_zfs, OID_AUTO, dirty_data_max_percent, CTLFLAG_RDTUN,
154     &zfs_dirty_data_max_percent, 0,
155     "The percent of physical memory used to auto calculate dirty_data_max");
156
157 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, dirty_data_sync, CTLFLAG_RWTUN,
158     &zfs_dirty_data_sync, 0,
159     "Force a txg if the number of dirty buffer bytes exceed this value");
160
161 static int sysctl_zfs_delay_min_dirty_percent(SYSCTL_HANDLER_ARGS);
162 /* No zfs_delay_min_dirty_percent tunable due to limit requirements */
163 SYSCTL_PROC(_vfs_zfs, OID_AUTO, delay_min_dirty_percent,
164     CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, sizeof(int),
165     sysctl_zfs_delay_min_dirty_percent, "I",
166     "The limit of outstanding dirty data before transations are delayed");
167
168 static int sysctl_zfs_delay_scale(SYSCTL_HANDLER_ARGS);
169 /* No zfs_delay_scale tunable due to limit requirements */
170 SYSCTL_PROC(_vfs_zfs, OID_AUTO, delay_scale,
171     CTLTYPE_U64 | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, sizeof(uint64_t),
172     sysctl_zfs_delay_scale, "QU",
173     "Controls how quickly the delay approaches infinity");
174
175 static int
176 sysctl_zfs_delay_min_dirty_percent(SYSCTL_HANDLER_ARGS)
177 {
178         int val, err;
179
180         val = zfs_delay_min_dirty_percent;
181         err = sysctl_handle_int(oidp, &val, 0, req);
182         if (err != 0 || req->newptr == NULL)
183                 return (err);
184
185         if (val < zfs_vdev_async_write_active_max_dirty_percent)
186                 return (EINVAL);
187
188         zfs_delay_min_dirty_percent = val;
189
190         return (0);
191 }
192
193 static int
194 sysctl_zfs_delay_scale(SYSCTL_HANDLER_ARGS)
195 {
196         uint64_t val;
197         int err;
198
199         val = zfs_delay_scale;
200         err = sysctl_handle_64(oidp, &val, 0, req);
201         if (err != 0 || req->newptr == NULL)
202                 return (err);
203
204         if (val > UINT64_MAX / zfs_dirty_data_max)
205                 return (EINVAL);
206
207         zfs_delay_scale = val;
208
209         return (0);
210 }
211 #endif
212
213 hrtime_t zfs_throttle_delay = MSEC2NSEC(10);
214 hrtime_t zfs_throttle_resolution = MSEC2NSEC(10);
215
216 int
217 dsl_pool_open_special_dir(dsl_pool_t *dp, const char *name, dsl_dir_t **ddp)
218 {
219         uint64_t obj;
220         int err;
221
222         err = zap_lookup(dp->dp_meta_objset,
223             dp->dp_root_dir->dd_phys->dd_child_dir_zapobj,
224             name, sizeof (obj), 1, &obj);
225         if (err)
226                 return (err);
227
228         return (dsl_dir_hold_obj(dp, obj, name, dp, ddp));
229 }
230
231 static dsl_pool_t *
232 dsl_pool_open_impl(spa_t *spa, uint64_t txg)
233 {
234         dsl_pool_t *dp;
235         blkptr_t *bp = spa_get_rootblkptr(spa);
236
237         dp = kmem_zalloc(sizeof (dsl_pool_t), KM_SLEEP);
238         dp->dp_spa = spa;
239         dp->dp_meta_rootbp = *bp;
240         rrw_init(&dp->dp_config_rwlock, B_TRUE);
241         txg_init(dp, txg);
242
243         txg_list_create(&dp->dp_dirty_datasets,
244             offsetof(dsl_dataset_t, ds_dirty_link));
245         txg_list_create(&dp->dp_dirty_zilogs,
246             offsetof(zilog_t, zl_dirty_link));
247         txg_list_create(&dp->dp_dirty_dirs,
248             offsetof(dsl_dir_t, dd_dirty_link));
249         txg_list_create(&dp->dp_sync_tasks,
250             offsetof(dsl_sync_task_t, dst_node));
251
252         mutex_init(&dp->dp_lock, NULL, MUTEX_DEFAULT, NULL);
253         cv_init(&dp->dp_spaceavail_cv, NULL, CV_DEFAULT, NULL);
254
255         dp->dp_vnrele_taskq = taskq_create("zfs_vn_rele_taskq", 1, minclsyspri,
256             1, 4, 0);
257
258         return (dp);
259 }
260
261 int
262 dsl_pool_init(spa_t *spa, uint64_t txg, dsl_pool_t **dpp)
263 {
264         int err;
265         dsl_pool_t *dp = dsl_pool_open_impl(spa, txg);
266
267         err = dmu_objset_open_impl(spa, NULL, &dp->dp_meta_rootbp,
268             &dp->dp_meta_objset);
269         if (err != 0)
270                 dsl_pool_close(dp);
271         else
272                 *dpp = dp;
273
274         return (err);
275 }
276
277 int
278 dsl_pool_open(dsl_pool_t *dp)
279 {
280         int err;
281         dsl_dir_t *dd;
282         dsl_dataset_t *ds;
283         uint64_t obj;
284
285         rrw_enter(&dp->dp_config_rwlock, RW_WRITER, FTAG);
286         err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
287             DMU_POOL_ROOT_DATASET, sizeof (uint64_t), 1,
288             &dp->dp_root_dir_obj);
289         if (err)
290                 goto out;
291
292         err = dsl_dir_hold_obj(dp, dp->dp_root_dir_obj,
293             NULL, dp, &dp->dp_root_dir);
294         if (err)
295                 goto out;
296
297         err = dsl_pool_open_special_dir(dp, MOS_DIR_NAME, &dp->dp_mos_dir);
298         if (err)
299                 goto out;
300
301         if (spa_version(dp->dp_spa) >= SPA_VERSION_ORIGIN) {
302                 err = dsl_pool_open_special_dir(dp, ORIGIN_DIR_NAME, &dd);
303                 if (err)
304                         goto out;
305                 err = dsl_dataset_hold_obj(dp, dd->dd_phys->dd_head_dataset_obj,
306                     FTAG, &ds);
307                 if (err == 0) {
308                         err = dsl_dataset_hold_obj(dp,
309                             ds->ds_phys->ds_prev_snap_obj, dp,
310                             &dp->dp_origin_snap);
311                         dsl_dataset_rele(ds, FTAG);
312                 }
313                 dsl_dir_rele(dd, dp);
314                 if (err)
315                         goto out;
316         }
317
318         if (spa_version(dp->dp_spa) >= SPA_VERSION_DEADLISTS) {
319                 err = dsl_pool_open_special_dir(dp, FREE_DIR_NAME,
320                     &dp->dp_free_dir);
321                 if (err)
322                         goto out;
323
324                 err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
325                     DMU_POOL_FREE_BPOBJ, sizeof (uint64_t), 1, &obj);
326                 if (err)
327                         goto out;
328                 VERIFY0(bpobj_open(&dp->dp_free_bpobj,
329                     dp->dp_meta_objset, obj));
330         }
331
332         /*
333          * Note: errors ignored, because the leak dir will not exist if we
334          * have not encountered a leak yet.
335          */
336         (void) dsl_pool_open_special_dir(dp, LEAK_DIR_NAME,
337             &dp->dp_leak_dir);
338
339         if (spa_feature_is_active(dp->dp_spa, SPA_FEATURE_ASYNC_DESTROY)) {
340                 err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
341                     DMU_POOL_BPTREE_OBJ, sizeof (uint64_t), 1,
342                     &dp->dp_bptree_obj);
343                 if (err != 0)
344                         goto out;
345         }
346
347         if (spa_feature_is_active(dp->dp_spa, SPA_FEATURE_EMPTY_BPOBJ)) {
348                 err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
349                     DMU_POOL_EMPTY_BPOBJ, sizeof (uint64_t), 1,
350                     &dp->dp_empty_bpobj);
351                 if (err != 0)
352                         goto out;
353         }
354
355         err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
356             DMU_POOL_TMP_USERREFS, sizeof (uint64_t), 1,
357             &dp->dp_tmp_userrefs_obj);
358         if (err == ENOENT)
359                 err = 0;
360         if (err)
361                 goto out;
362
363         err = dsl_scan_init(dp, dp->dp_tx.tx_open_txg);
364
365 out:
366         rrw_exit(&dp->dp_config_rwlock, FTAG);
367         return (err);
368 }
369
370 void
371 dsl_pool_close(dsl_pool_t *dp)
372 {
373         /*
374          * Drop our references from dsl_pool_open().
375          *
376          * Since we held the origin_snap from "syncing" context (which
377          * includes pool-opening context), it actually only got a "ref"
378          * and not a hold, so just drop that here.
379          */
380         if (dp->dp_origin_snap)
381                 dsl_dataset_rele(dp->dp_origin_snap, dp);
382         if (dp->dp_mos_dir)
383                 dsl_dir_rele(dp->dp_mos_dir, dp);
384         if (dp->dp_free_dir)
385                 dsl_dir_rele(dp->dp_free_dir, dp);
386         if (dp->dp_leak_dir)
387                 dsl_dir_rele(dp->dp_leak_dir, dp);
388         if (dp->dp_root_dir)
389                 dsl_dir_rele(dp->dp_root_dir, dp);
390
391         bpobj_close(&dp->dp_free_bpobj);
392
393         /* undo the dmu_objset_open_impl(mos) from dsl_pool_open() */
394         if (dp->dp_meta_objset)
395                 dmu_objset_evict(dp->dp_meta_objset);
396
397         txg_list_destroy(&dp->dp_dirty_datasets);
398         txg_list_destroy(&dp->dp_dirty_zilogs);
399         txg_list_destroy(&dp->dp_sync_tasks);
400         txg_list_destroy(&dp->dp_dirty_dirs);
401
402         arc_flush(dp->dp_spa);
403         txg_fini(dp);
404         dsl_scan_fini(dp);
405         rrw_destroy(&dp->dp_config_rwlock);
406         mutex_destroy(&dp->dp_lock);
407         taskq_destroy(dp->dp_vnrele_taskq);
408         if (dp->dp_blkstats)
409                 kmem_free(dp->dp_blkstats, sizeof (zfs_all_blkstats_t));
410         kmem_free(dp, sizeof (dsl_pool_t));
411 }
412
413 dsl_pool_t *
414 dsl_pool_create(spa_t *spa, nvlist_t *zplprops, uint64_t txg)
415 {
416         int err;
417         dsl_pool_t *dp = dsl_pool_open_impl(spa, txg);
418         dmu_tx_t *tx = dmu_tx_create_assigned(dp, txg);
419         objset_t *os;
420         dsl_dataset_t *ds;
421         uint64_t obj;
422
423         rrw_enter(&dp->dp_config_rwlock, RW_WRITER, FTAG);
424
425         /* create and open the MOS (meta-objset) */
426         dp->dp_meta_objset = dmu_objset_create_impl(spa,
427             NULL, &dp->dp_meta_rootbp, DMU_OST_META, tx);
428
429         /* create the pool directory */
430         err = zap_create_claim(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
431             DMU_OT_OBJECT_DIRECTORY, DMU_OT_NONE, 0, tx);
432         ASSERT0(err);
433
434         /* Initialize scan structures */
435         VERIFY0(dsl_scan_init(dp, txg));
436
437         /* create and open the root dir */
438         dp->dp_root_dir_obj = dsl_dir_create_sync(dp, NULL, NULL, tx);
439         VERIFY0(dsl_dir_hold_obj(dp, dp->dp_root_dir_obj,
440             NULL, dp, &dp->dp_root_dir));
441
442         /* create and open the meta-objset dir */
443         (void) dsl_dir_create_sync(dp, dp->dp_root_dir, MOS_DIR_NAME, tx);
444         VERIFY0(dsl_pool_open_special_dir(dp,
445             MOS_DIR_NAME, &dp->dp_mos_dir));
446
447         if (spa_version(spa) >= SPA_VERSION_DEADLISTS) {
448                 /* create and open the free dir */
449                 (void) dsl_dir_create_sync(dp, dp->dp_root_dir,
450                     FREE_DIR_NAME, tx);
451                 VERIFY0(dsl_pool_open_special_dir(dp,
452                     FREE_DIR_NAME, &dp->dp_free_dir));
453
454                 /* create and open the free_bplist */
455                 obj = bpobj_alloc(dp->dp_meta_objset, SPA_MAXBLOCKSIZE, tx);
456                 VERIFY(zap_add(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
457                     DMU_POOL_FREE_BPOBJ, sizeof (uint64_t), 1, &obj, tx) == 0);
458                 VERIFY0(bpobj_open(&dp->dp_free_bpobj,
459                     dp->dp_meta_objset, obj));
460         }
461
462         if (spa_version(spa) >= SPA_VERSION_DSL_SCRUB)
463                 dsl_pool_create_origin(dp, tx);
464
465         /* create the root dataset */
466         obj = dsl_dataset_create_sync_dd(dp->dp_root_dir, NULL, 0, tx);
467
468         /* create the root objset */
469         VERIFY0(dsl_dataset_hold_obj(dp, obj, FTAG, &ds));
470         os = dmu_objset_create_impl(dp->dp_spa, ds,
471             dsl_dataset_get_blkptr(ds), DMU_OST_ZFS, tx);
472 #ifdef _KERNEL
473         zfs_create_fs(os, kcred, zplprops, tx);
474 #endif
475         dsl_dataset_rele(ds, FTAG);
476
477         dmu_tx_commit(tx);
478
479         rrw_exit(&dp->dp_config_rwlock, FTAG);
480
481         return (dp);
482 }
483
484 /*
485  * Account for the meta-objset space in its placeholder dsl_dir.
486  */
487 void
488 dsl_pool_mos_diduse_space(dsl_pool_t *dp,
489     int64_t used, int64_t comp, int64_t uncomp)
490 {
491         ASSERT3U(comp, ==, uncomp); /* it's all metadata */
492         mutex_enter(&dp->dp_lock);
493         dp->dp_mos_used_delta += used;
494         dp->dp_mos_compressed_delta += comp;
495         dp->dp_mos_uncompressed_delta += uncomp;
496         mutex_exit(&dp->dp_lock);
497 }
498
499 static int
500 deadlist_enqueue_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
501 {
502         dsl_deadlist_t *dl = arg;
503         dsl_deadlist_insert(dl, bp, tx);
504         return (0);
505 }
506
507 static void
508 dsl_pool_sync_mos(dsl_pool_t *dp, dmu_tx_t *tx)
509 {
510         zio_t *zio = zio_root(dp->dp_spa, NULL, NULL, ZIO_FLAG_MUSTSUCCEED);
511         dmu_objset_sync(dp->dp_meta_objset, zio, tx);
512         VERIFY0(zio_wait(zio));
513         dprintf_bp(&dp->dp_meta_rootbp, "meta objset rootbp is %s", "");
514         spa_set_rootblkptr(dp->dp_spa, &dp->dp_meta_rootbp);
515 }
516
517 static void
518 dsl_pool_dirty_delta(dsl_pool_t *dp, int64_t delta)
519 {
520         ASSERT(MUTEX_HELD(&dp->dp_lock));
521
522         if (delta < 0)
523                 ASSERT3U(-delta, <=, dp->dp_dirty_total);
524
525         dp->dp_dirty_total += delta;
526
527         /*
528          * Note: we signal even when increasing dp_dirty_total.
529          * This ensures forward progress -- each thread wakes the next waiter.
530          */
531         if (dp->dp_dirty_total <= zfs_dirty_data_max)
532                 cv_signal(&dp->dp_spaceavail_cv);
533 }
534
535 void
536 dsl_pool_sync(dsl_pool_t *dp, uint64_t txg)
537 {
538         zio_t *zio;
539         dmu_tx_t *tx;
540         dsl_dir_t *dd;
541         dsl_dataset_t *ds;
542         objset_t *mos = dp->dp_meta_objset;
543         list_t synced_datasets;
544
545         list_create(&synced_datasets, sizeof (dsl_dataset_t),
546             offsetof(dsl_dataset_t, ds_synced_link));
547
548         tx = dmu_tx_create_assigned(dp, txg);
549
550         /*
551          * Write out all dirty blocks of dirty datasets.
552          */
553         zio = zio_root(dp->dp_spa, NULL, NULL, ZIO_FLAG_MUSTSUCCEED);
554         while ((ds = txg_list_remove(&dp->dp_dirty_datasets, txg)) != NULL) {
555                 /*
556                  * We must not sync any non-MOS datasets twice, because
557                  * we may have taken a snapshot of them.  However, we
558                  * may sync newly-created datasets on pass 2.
559                  */
560                 ASSERT(!list_link_active(&ds->ds_synced_link));
561                 list_insert_tail(&synced_datasets, ds);
562                 dsl_dataset_sync(ds, zio, tx);
563         }
564         VERIFY0(zio_wait(zio));
565
566         /*
567          * We have written all of the accounted dirty data, so our
568          * dp_space_towrite should now be zero.  However, some seldom-used
569          * code paths do not adhere to this (e.g. dbuf_undirty(), also
570          * rounding error in dbuf_write_physdone).
571          * Shore up the accounting of any dirtied space now.
572          */
573         dsl_pool_undirty_space(dp, dp->dp_dirty_pertxg[txg & TXG_MASK], txg);
574
575         /*
576          * After the data blocks have been written (ensured by the zio_wait()
577          * above), update the user/group space accounting.
578          */
579         for (ds = list_head(&synced_datasets); ds != NULL;
580             ds = list_next(&synced_datasets, ds)) {
581                 dmu_objset_do_userquota_updates(ds->ds_objset, tx);
582         }
583
584         /*
585          * Sync the datasets again to push out the changes due to
586          * userspace updates.  This must be done before we process the
587          * sync tasks, so that any snapshots will have the correct
588          * user accounting information (and we won't get confused
589          * about which blocks are part of the snapshot).
590          */
591         zio = zio_root(dp->dp_spa, NULL, NULL, ZIO_FLAG_MUSTSUCCEED);
592         while ((ds = txg_list_remove(&dp->dp_dirty_datasets, txg)) != NULL) {
593                 ASSERT(list_link_active(&ds->ds_synced_link));
594                 dmu_buf_rele(ds->ds_dbuf, ds);
595                 dsl_dataset_sync(ds, zio, tx);
596         }
597         VERIFY0(zio_wait(zio));
598
599         /*
600          * Now that the datasets have been completely synced, we can
601          * clean up our in-memory structures accumulated while syncing:
602          *
603          *  - move dead blocks from the pending deadlist to the on-disk deadlist
604          *  - release hold from dsl_dataset_dirty()
605          */
606         while ((ds = list_remove_head(&synced_datasets)) != NULL) {
607                 objset_t *os = ds->ds_objset;
608                 bplist_iterate(&ds->ds_pending_deadlist,
609                     deadlist_enqueue_cb, &ds->ds_deadlist, tx);
610                 ASSERT(!dmu_objset_is_dirty(os, txg));
611                 dmu_buf_rele(ds->ds_dbuf, ds);
612         }
613         while ((dd = txg_list_remove(&dp->dp_dirty_dirs, txg)) != NULL) {
614                 dsl_dir_sync(dd, tx);
615         }
616
617         /*
618          * The MOS's space is accounted for in the pool/$MOS
619          * (dp_mos_dir).  We can't modify the mos while we're syncing
620          * it, so we remember the deltas and apply them here.
621          */
622         if (dp->dp_mos_used_delta != 0 || dp->dp_mos_compressed_delta != 0 ||
623             dp->dp_mos_uncompressed_delta != 0) {
624                 dsl_dir_diduse_space(dp->dp_mos_dir, DD_USED_HEAD,
625                     dp->dp_mos_used_delta,
626                     dp->dp_mos_compressed_delta,
627                     dp->dp_mos_uncompressed_delta, tx);
628                 dp->dp_mos_used_delta = 0;
629                 dp->dp_mos_compressed_delta = 0;
630                 dp->dp_mos_uncompressed_delta = 0;
631         }
632
633         if (list_head(&mos->os_dirty_dnodes[txg & TXG_MASK]) != NULL ||
634             list_head(&mos->os_free_dnodes[txg & TXG_MASK]) != NULL) {
635                 dsl_pool_sync_mos(dp, tx);
636         }
637
638         /*
639          * If we modify a dataset in the same txg that we want to destroy it,
640          * its dsl_dir's dd_dbuf will be dirty, and thus have a hold on it.
641          * dsl_dir_destroy_check() will fail if there are unexpected holds.
642          * Therefore, we want to sync the MOS (thus syncing the dd_dbuf
643          * and clearing the hold on it) before we process the sync_tasks.
644          * The MOS data dirtied by the sync_tasks will be synced on the next
645          * pass.
646          */
647         if (!txg_list_empty(&dp->dp_sync_tasks, txg)) {
648                 dsl_sync_task_t *dst;
649                 /*
650                  * No more sync tasks should have been added while we
651                  * were syncing.
652                  */
653                 ASSERT3U(spa_sync_pass(dp->dp_spa), ==, 1);
654                 while ((dst = txg_list_remove(&dp->dp_sync_tasks, txg)) != NULL)
655                         dsl_sync_task_sync(dst, tx);
656         }
657
658         dmu_tx_commit(tx);
659
660         DTRACE_PROBE2(dsl_pool_sync__done, dsl_pool_t *dp, dp, uint64_t, txg);
661 }
662
663 void
664 dsl_pool_sync_done(dsl_pool_t *dp, uint64_t txg)
665 {
666         zilog_t *zilog;
667
668         while (zilog = txg_list_remove(&dp->dp_dirty_zilogs, txg)) {
669                 dsl_dataset_t *ds = dmu_objset_ds(zilog->zl_os);
670                 zil_clean(zilog, txg);
671                 ASSERT(!dmu_objset_is_dirty(zilog->zl_os, txg));
672                 dmu_buf_rele(ds->ds_dbuf, zilog);
673         }
674         ASSERT(!dmu_objset_is_dirty(dp->dp_meta_objset, txg));
675 }
676
677 /*
678  * TRUE if the current thread is the tx_sync_thread or if we
679  * are being called from SPA context during pool initialization.
680  */
681 int
682 dsl_pool_sync_context(dsl_pool_t *dp)
683 {
684         return (curthread == dp->dp_tx.tx_sync_thread ||
685             spa_is_initializing(dp->dp_spa));
686 }
687
688 uint64_t
689 dsl_pool_adjustedsize(dsl_pool_t *dp, boolean_t netfree)
690 {
691         uint64_t space, resv;
692
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 = spa_get_slop_space(dp->dp_spa);
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 }