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