]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/cddl/contrib/opensolaris/uts/common/fs/zfs/dsl_pool.c
MFV r267569:
[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 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          * Reserve about 1.6% (1/64), or at least 32MB, for allocation
695          * efficiency.
696          * XXX The intent log is not accounted for, so it must fit
697          * within this slop.
698          *
699          * If we're trying to assess whether it's OK to do a free,
700          * cut the reservation in half to allow forward progress
701          * (e.g. make it possible to rm(1) files from a full pool).
702          */
703         space = spa_get_dspace(dp->dp_spa);
704         resv = MAX(space >> 6, SPA_MINDEVSIZE >> 1);
705         if (netfree)
706                 resv >>= 1;
707
708         return (space - resv);
709 }
710
711 boolean_t
712 dsl_pool_need_dirty_delay(dsl_pool_t *dp)
713 {
714         uint64_t delay_min_bytes =
715             zfs_dirty_data_max * zfs_delay_min_dirty_percent / 100;
716         boolean_t rv;
717
718         mutex_enter(&dp->dp_lock);
719         if (dp->dp_dirty_total > zfs_dirty_data_sync)
720                 txg_kick(dp);
721         rv = (dp->dp_dirty_total > delay_min_bytes);
722         mutex_exit(&dp->dp_lock);
723         return (rv);
724 }
725
726 void
727 dsl_pool_dirty_space(dsl_pool_t *dp, int64_t space, dmu_tx_t *tx)
728 {
729         if (space > 0) {
730                 mutex_enter(&dp->dp_lock);
731                 dp->dp_dirty_pertxg[tx->tx_txg & TXG_MASK] += space;
732                 dsl_pool_dirty_delta(dp, space);
733                 mutex_exit(&dp->dp_lock);
734         }
735 }
736
737 void
738 dsl_pool_undirty_space(dsl_pool_t *dp, int64_t space, uint64_t txg)
739 {
740         ASSERT3S(space, >=, 0);
741         if (space == 0)
742                 return;
743         mutex_enter(&dp->dp_lock);
744         if (dp->dp_dirty_pertxg[txg & TXG_MASK] < space) {
745                 /* XXX writing something we didn't dirty? */
746                 space = dp->dp_dirty_pertxg[txg & TXG_MASK];
747         }
748         ASSERT3U(dp->dp_dirty_pertxg[txg & TXG_MASK], >=, space);
749         dp->dp_dirty_pertxg[txg & TXG_MASK] -= space;
750         ASSERT3U(dp->dp_dirty_total, >=, space);
751         dsl_pool_dirty_delta(dp, -space);
752         mutex_exit(&dp->dp_lock);
753 }
754
755 /* ARGSUSED */
756 static int
757 upgrade_clones_cb(dsl_pool_t *dp, dsl_dataset_t *hds, void *arg)
758 {
759         dmu_tx_t *tx = arg;
760         dsl_dataset_t *ds, *prev = NULL;
761         int err;
762
763         err = dsl_dataset_hold_obj(dp, hds->ds_object, FTAG, &ds);
764         if (err)
765                 return (err);
766
767         while (ds->ds_phys->ds_prev_snap_obj != 0) {
768                 err = dsl_dataset_hold_obj(dp, ds->ds_phys->ds_prev_snap_obj,
769                     FTAG, &prev);
770                 if (err) {
771                         dsl_dataset_rele(ds, FTAG);
772                         return (err);
773                 }
774
775                 if (prev->ds_phys->ds_next_snap_obj != ds->ds_object)
776                         break;
777                 dsl_dataset_rele(ds, FTAG);
778                 ds = prev;
779                 prev = NULL;
780         }
781
782         if (prev == NULL) {
783                 prev = dp->dp_origin_snap;
784
785                 /*
786                  * The $ORIGIN can't have any data, or the accounting
787                  * will be wrong.
788                  */
789                 ASSERT0(prev->ds_phys->ds_bp.blk_birth);
790
791                 /* The origin doesn't get attached to itself */
792                 if (ds->ds_object == prev->ds_object) {
793                         dsl_dataset_rele(ds, FTAG);
794                         return (0);
795                 }
796
797                 dmu_buf_will_dirty(ds->ds_dbuf, tx);
798                 ds->ds_phys->ds_prev_snap_obj = prev->ds_object;
799                 ds->ds_phys->ds_prev_snap_txg = prev->ds_phys->ds_creation_txg;
800
801                 dmu_buf_will_dirty(ds->ds_dir->dd_dbuf, tx);
802                 ds->ds_dir->dd_phys->dd_origin_obj = prev->ds_object;
803
804                 dmu_buf_will_dirty(prev->ds_dbuf, tx);
805                 prev->ds_phys->ds_num_children++;
806
807                 if (ds->ds_phys->ds_next_snap_obj == 0) {
808                         ASSERT(ds->ds_prev == NULL);
809                         VERIFY0(dsl_dataset_hold_obj(dp,
810                             ds->ds_phys->ds_prev_snap_obj, ds, &ds->ds_prev));
811                 }
812         }
813
814         ASSERT3U(ds->ds_dir->dd_phys->dd_origin_obj, ==, prev->ds_object);
815         ASSERT3U(ds->ds_phys->ds_prev_snap_obj, ==, prev->ds_object);
816
817         if (prev->ds_phys->ds_next_clones_obj == 0) {
818                 dmu_buf_will_dirty(prev->ds_dbuf, tx);
819                 prev->ds_phys->ds_next_clones_obj =
820                     zap_create(dp->dp_meta_objset,
821                     DMU_OT_NEXT_CLONES, DMU_OT_NONE, 0, tx);
822         }
823         VERIFY0(zap_add_int(dp->dp_meta_objset,
824             prev->ds_phys->ds_next_clones_obj, ds->ds_object, tx));
825
826         dsl_dataset_rele(ds, FTAG);
827         if (prev != dp->dp_origin_snap)
828                 dsl_dataset_rele(prev, FTAG);
829         return (0);
830 }
831
832 void
833 dsl_pool_upgrade_clones(dsl_pool_t *dp, dmu_tx_t *tx)
834 {
835         ASSERT(dmu_tx_is_syncing(tx));
836         ASSERT(dp->dp_origin_snap != NULL);
837
838         VERIFY0(dmu_objset_find_dp(dp, dp->dp_root_dir_obj, upgrade_clones_cb,
839             tx, DS_FIND_CHILDREN));
840 }
841
842 /* ARGSUSED */
843 static int
844 upgrade_dir_clones_cb(dsl_pool_t *dp, dsl_dataset_t *ds, void *arg)
845 {
846         dmu_tx_t *tx = arg;
847         objset_t *mos = dp->dp_meta_objset;
848
849         if (ds->ds_dir->dd_phys->dd_origin_obj != 0) {
850                 dsl_dataset_t *origin;
851
852                 VERIFY0(dsl_dataset_hold_obj(dp,
853                     ds->ds_dir->dd_phys->dd_origin_obj, FTAG, &origin));
854
855                 if (origin->ds_dir->dd_phys->dd_clones == 0) {
856                         dmu_buf_will_dirty(origin->ds_dir->dd_dbuf, tx);
857                         origin->ds_dir->dd_phys->dd_clones = zap_create(mos,
858                             DMU_OT_DSL_CLONES, DMU_OT_NONE, 0, tx);
859                 }
860
861                 VERIFY0(zap_add_int(dp->dp_meta_objset,
862                     origin->ds_dir->dd_phys->dd_clones, ds->ds_object, tx));
863
864                 dsl_dataset_rele(origin, FTAG);
865         }
866         return (0);
867 }
868
869 void
870 dsl_pool_upgrade_dir_clones(dsl_pool_t *dp, dmu_tx_t *tx)
871 {
872         ASSERT(dmu_tx_is_syncing(tx));
873         uint64_t obj;
874
875         (void) dsl_dir_create_sync(dp, dp->dp_root_dir, FREE_DIR_NAME, tx);
876         VERIFY0(dsl_pool_open_special_dir(dp,
877             FREE_DIR_NAME, &dp->dp_free_dir));
878
879         /*
880          * We can't use bpobj_alloc(), because spa_version() still
881          * returns the old version, and we need a new-version bpobj with
882          * subobj support.  So call dmu_object_alloc() directly.
883          */
884         obj = dmu_object_alloc(dp->dp_meta_objset, DMU_OT_BPOBJ,
885             SPA_MAXBLOCKSIZE, DMU_OT_BPOBJ_HDR, sizeof (bpobj_phys_t), tx);
886         VERIFY0(zap_add(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
887             DMU_POOL_FREE_BPOBJ, sizeof (uint64_t), 1, &obj, tx));
888         VERIFY0(bpobj_open(&dp->dp_free_bpobj, dp->dp_meta_objset, obj));
889
890         VERIFY0(dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
891             upgrade_dir_clones_cb, tx, DS_FIND_CHILDREN));
892 }
893
894 void
895 dsl_pool_create_origin(dsl_pool_t *dp, dmu_tx_t *tx)
896 {
897         uint64_t dsobj;
898         dsl_dataset_t *ds;
899
900         ASSERT(dmu_tx_is_syncing(tx));
901         ASSERT(dp->dp_origin_snap == NULL);
902         ASSERT(rrw_held(&dp->dp_config_rwlock, RW_WRITER));
903
904         /* create the origin dir, ds, & snap-ds */
905         dsobj = dsl_dataset_create_sync(dp->dp_root_dir, ORIGIN_DIR_NAME,
906             NULL, 0, kcred, tx);
907         VERIFY0(dsl_dataset_hold_obj(dp, dsobj, FTAG, &ds));
908         dsl_dataset_snapshot_sync_impl(ds, ORIGIN_DIR_NAME, tx);
909         VERIFY0(dsl_dataset_hold_obj(dp, ds->ds_phys->ds_prev_snap_obj,
910             dp, &dp->dp_origin_snap));
911         dsl_dataset_rele(ds, FTAG);
912 }
913
914 taskq_t *
915 dsl_pool_vnrele_taskq(dsl_pool_t *dp)
916 {
917         return (dp->dp_vnrele_taskq);
918 }
919
920 /*
921  * Walk through the pool-wide zap object of temporary snapshot user holds
922  * and release them.
923  */
924 void
925 dsl_pool_clean_tmp_userrefs(dsl_pool_t *dp)
926 {
927         zap_attribute_t za;
928         zap_cursor_t zc;
929         objset_t *mos = dp->dp_meta_objset;
930         uint64_t zapobj = dp->dp_tmp_userrefs_obj;
931         nvlist_t *holds;
932
933         if (zapobj == 0)
934                 return;
935         ASSERT(spa_version(dp->dp_spa) >= SPA_VERSION_USERREFS);
936
937         holds = fnvlist_alloc();
938
939         for (zap_cursor_init(&zc, mos, zapobj);
940             zap_cursor_retrieve(&zc, &za) == 0;
941             zap_cursor_advance(&zc)) {
942                 char *htag;
943                 nvlist_t *tags;
944
945                 htag = strchr(za.za_name, '-');
946                 *htag = '\0';
947                 ++htag;
948                 if (nvlist_lookup_nvlist(holds, za.za_name, &tags) != 0) {
949                         tags = fnvlist_alloc();
950                         fnvlist_add_boolean(tags, htag);
951                         fnvlist_add_nvlist(holds, za.za_name, tags);
952                         fnvlist_free(tags);
953                 } else {
954                         fnvlist_add_boolean(tags, htag);
955                 }
956         }
957         dsl_dataset_user_release_tmp(dp, holds);
958         fnvlist_free(holds);
959         zap_cursor_fini(&zc);
960 }
961
962 /*
963  * Create the pool-wide zap object for storing temporary snapshot holds.
964  */
965 void
966 dsl_pool_user_hold_create_obj(dsl_pool_t *dp, dmu_tx_t *tx)
967 {
968         objset_t *mos = dp->dp_meta_objset;
969
970         ASSERT(dp->dp_tmp_userrefs_obj == 0);
971         ASSERT(dmu_tx_is_syncing(tx));
972
973         dp->dp_tmp_userrefs_obj = zap_create_link(mos, DMU_OT_USERREFS,
974             DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_TMP_USERREFS, tx);
975 }
976
977 static int
978 dsl_pool_user_hold_rele_impl(dsl_pool_t *dp, uint64_t dsobj,
979     const char *tag, uint64_t now, dmu_tx_t *tx, boolean_t holding)
980 {
981         objset_t *mos = dp->dp_meta_objset;
982         uint64_t zapobj = dp->dp_tmp_userrefs_obj;
983         char *name;
984         int error;
985
986         ASSERT(spa_version(dp->dp_spa) >= SPA_VERSION_USERREFS);
987         ASSERT(dmu_tx_is_syncing(tx));
988
989         /*
990          * If the pool was created prior to SPA_VERSION_USERREFS, the
991          * zap object for temporary holds might not exist yet.
992          */
993         if (zapobj == 0) {
994                 if (holding) {
995                         dsl_pool_user_hold_create_obj(dp, tx);
996                         zapobj = dp->dp_tmp_userrefs_obj;
997                 } else {
998                         return (SET_ERROR(ENOENT));
999                 }
1000         }
1001
1002         name = kmem_asprintf("%llx-%s", (u_longlong_t)dsobj, tag);
1003         if (holding)
1004                 error = zap_add(mos, zapobj, name, 8, 1, &now, tx);
1005         else
1006                 error = zap_remove(mos, zapobj, name, tx);
1007         strfree(name);
1008
1009         return (error);
1010 }
1011
1012 /*
1013  * Add a temporary hold for the given dataset object and tag.
1014  */
1015 int
1016 dsl_pool_user_hold(dsl_pool_t *dp, uint64_t dsobj, const char *tag,
1017     uint64_t now, dmu_tx_t *tx)
1018 {
1019         return (dsl_pool_user_hold_rele_impl(dp, dsobj, tag, now, tx, B_TRUE));
1020 }
1021
1022 /*
1023  * Release a temporary hold for the given dataset object and tag.
1024  */
1025 int
1026 dsl_pool_user_release(dsl_pool_t *dp, uint64_t dsobj, const char *tag,
1027     dmu_tx_t *tx)
1028 {
1029         return (dsl_pool_user_hold_rele_impl(dp, dsobj, tag, 0,
1030             tx, B_FALSE));
1031 }
1032
1033 /*
1034  * DSL Pool Configuration Lock
1035  *
1036  * The dp_config_rwlock protects against changes to DSL state (e.g. dataset
1037  * creation / destruction / rename / property setting).  It must be held for
1038  * read to hold a dataset or dsl_dir.  I.e. you must call
1039  * dsl_pool_config_enter() or dsl_pool_hold() before calling
1040  * dsl_{dataset,dir}_hold{_obj}.  In most circumstances, the dp_config_rwlock
1041  * must be held continuously until all datasets and dsl_dirs are released.
1042  *
1043  * The only exception to this rule is that if a "long hold" is placed on
1044  * a dataset, then the dp_config_rwlock may be dropped while the dataset
1045  * is still held.  The long hold will prevent the dataset from being
1046  * destroyed -- the destroy will fail with EBUSY.  A long hold can be
1047  * obtained by calling dsl_dataset_long_hold(), or by "owning" a dataset
1048  * (by calling dsl_{dataset,objset}_{try}own{_obj}).
1049  *
1050  * Legitimate long-holders (including owners) should be long-running, cancelable
1051  * tasks that should cause "zfs destroy" to fail.  This includes DMU
1052  * consumers (i.e. a ZPL filesystem being mounted or ZVOL being open),
1053  * "zfs send", and "zfs diff".  There are several other long-holders whose
1054  * uses are suboptimal (e.g. "zfs promote", and zil_suspend()).
1055  *
1056  * The usual formula for long-holding would be:
1057  * dsl_pool_hold()
1058  * dsl_dataset_hold()
1059  * ... perform checks ...
1060  * dsl_dataset_long_hold()
1061  * dsl_pool_rele()
1062  * ... perform long-running task ...
1063  * dsl_dataset_long_rele()
1064  * dsl_dataset_rele()
1065  *
1066  * Note that when the long hold is released, the dataset is still held but
1067  * the pool is not held.  The dataset may change arbitrarily during this time
1068  * (e.g. it could be destroyed).  Therefore you shouldn't do anything to the
1069  * dataset except release it.
1070  *
1071  * User-initiated operations (e.g. ioctls, zfs_ioc_*()) are either read-only
1072  * or modifying operations.
1073  *
1074  * Modifying operations should generally use dsl_sync_task().  The synctask
1075  * infrastructure enforces proper locking strategy with respect to the
1076  * dp_config_rwlock.  See the comment above dsl_sync_task() for details.
1077  *
1078  * Read-only operations will manually hold the pool, then the dataset, obtain
1079  * information from the dataset, then release the pool and dataset.
1080  * dmu_objset_{hold,rele}() are convenience routines that also do the pool
1081  * hold/rele.
1082  */
1083
1084 int
1085 dsl_pool_hold(const char *name, void *tag, dsl_pool_t **dp)
1086 {
1087         spa_t *spa;
1088         int error;
1089
1090         error = spa_open(name, &spa, tag);
1091         if (error == 0) {
1092                 *dp = spa_get_dsl(spa);
1093                 dsl_pool_config_enter(*dp, tag);
1094         }
1095         return (error);
1096 }
1097
1098 void
1099 dsl_pool_rele(dsl_pool_t *dp, void *tag)
1100 {
1101         dsl_pool_config_exit(dp, tag);
1102         spa_close(dp->dp_spa, tag);
1103 }
1104
1105 void
1106 dsl_pool_config_enter(dsl_pool_t *dp, void *tag)
1107 {
1108         /*
1109          * We use a "reentrant" reader-writer lock, but not reentrantly.
1110          *
1111          * The rrwlock can (with the track_all flag) track all reading threads,
1112          * which is very useful for debugging which code path failed to release
1113          * the lock, and for verifying that the *current* thread does hold
1114          * the lock.
1115          *
1116          * (Unlike a rwlock, which knows that N threads hold it for
1117          * read, but not *which* threads, so rw_held(RW_READER) returns TRUE
1118          * if any thread holds it for read, even if this thread doesn't).
1119          */
1120         ASSERT(!rrw_held(&dp->dp_config_rwlock, RW_READER));
1121         rrw_enter(&dp->dp_config_rwlock, RW_READER, tag);
1122 }
1123
1124 void
1125 dsl_pool_config_exit(dsl_pool_t *dp, void *tag)
1126 {
1127         rrw_exit(&dp->dp_config_rwlock, tag);
1128 }
1129
1130 boolean_t
1131 dsl_pool_config_held(dsl_pool_t *dp)
1132 {
1133         return (RRW_LOCK_HELD(&dp->dp_config_rwlock));
1134 }