]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/cddl/contrib/opensolaris/uts/common/fs/zfs/dsl_pool.c
Merge bmake-20180512
[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, 2017 by Delphix. All rights reserved.
24  * Copyright (c) 2013 Steven Hartland. All rights reserved.
25  * Copyright (c) 2014 Spectra Logic Corporation, All rights reserved.
26  * Copyright (c) 2014 Integros [integros.com]
27  * Copyright 2016 Nexenta Systems, Inc.  All rights reserved.
28  */
29
30 #include <sys/dsl_pool.h>
31 #include <sys/dsl_dataset.h>
32 #include <sys/dsl_prop.h>
33 #include <sys/dsl_dir.h>
34 #include <sys/dsl_synctask.h>
35 #include <sys/dsl_scan.h>
36 #include <sys/dnode.h>
37 #include <sys/dmu_tx.h>
38 #include <sys/dmu_objset.h>
39 #include <sys/arc.h>
40 #include <sys/zap.h>
41 #include <sys/zio.h>
42 #include <sys/zfs_context.h>
43 #include <sys/fs/zfs.h>
44 #include <sys/zfs_znode.h>
45 #include <sys/spa_impl.h>
46 #include <sys/dsl_deadlist.h>
47 #include <sys/vdev_impl.h>
48 #include <sys/metaslab_impl.h>
49 #include <sys/bptree.h>
50 #include <sys/zfeature.h>
51 #include <sys/zil_impl.h>
52 #include <sys/dsl_userhold.h>
53
54 #if defined(__FreeBSD__) && defined(_KERNEL)
55 #include <sys/types.h>
56 #include <sys/sysctl.h>
57 #endif
58
59 /*
60  * ZFS Write Throttle
61  * ------------------
62  *
63  * ZFS must limit the rate of incoming writes to the rate at which it is able
64  * to sync data modifications to the backend storage. Throttling by too much
65  * creates an artificial limit; throttling by too little can only be sustained
66  * for short periods and would lead to highly lumpy performance. On a per-pool
67  * basis, ZFS tracks the amount of modified (dirty) data. As operations change
68  * data, the amount of dirty data increases; as ZFS syncs out data, the amount
69  * of dirty data decreases. When the amount of dirty data exceeds a
70  * predetermined threshold further modifications are blocked until the amount
71  * of dirty data decreases (as data is synced out).
72  *
73  * The limit on dirty data is tunable, and should be adjusted according to
74  * both the IO capacity and available memory of the system. The larger the
75  * window, the more ZFS is able to aggregate and amortize metadata (and data)
76  * changes. However, memory is a limited resource, and allowing for more dirty
77  * data comes at the cost of keeping other useful data in memory (for example
78  * ZFS data cached by the ARC).
79  *
80  * Implementation
81  *
82  * As buffers are modified dsl_pool_willuse_space() increments both the per-
83  * txg (dp_dirty_pertxg[]) and poolwide (dp_dirty_total) accounting of
84  * dirty space used; dsl_pool_dirty_space() decrements those values as data
85  * is synced out from dsl_pool_sync(). While only the poolwide value is
86  * relevant, the per-txg value is useful for debugging. The tunable
87  * zfs_dirty_data_max determines the dirty space limit. Once that value is
88  * exceeded, new writes are halted until space frees up.
89  *
90  * The zfs_dirty_data_sync tunable dictates the threshold at which we
91  * ensure that there is a txg syncing (see the comment in txg.c for a full
92  * description of transaction group stages).
93  *
94  * The IO scheduler uses both the dirty space limit and current amount of
95  * dirty data as inputs. Those values affect the number of concurrent IOs ZFS
96  * issues. See the comment in vdev_queue.c for details of the IO scheduler.
97  *
98  * The delay is also calculated based on the amount of dirty data.  See the
99  * comment above dmu_tx_delay() for details.
100  */
101
102 /*
103  * zfs_dirty_data_max will be set to zfs_dirty_data_max_percent% of all memory,
104  * capped at zfs_dirty_data_max_max.  It can also be overridden in /etc/system.
105  */
106 uint64_t zfs_dirty_data_max;
107 uint64_t zfs_dirty_data_max_max = 4ULL * 1024 * 1024 * 1024;
108 int zfs_dirty_data_max_percent = 10;
109
110 /*
111  * If there is at least this much dirty data, push out a txg.
112  */
113 uint64_t zfs_dirty_data_sync = 64 * 1024 * 1024;
114
115 /*
116  * Once there is this amount of dirty data, the dmu_tx_delay() will kick in
117  * and delay each transaction.
118  * This value should be >= zfs_vdev_async_write_active_max_dirty_percent.
119  */
120 int zfs_delay_min_dirty_percent = 60;
121
122 /*
123  * This controls how quickly the delay approaches infinity.
124  * Larger values cause it to delay more for a given amount of dirty data.
125  * Therefore larger values will cause there to be less dirty data for a
126  * given throughput.
127  *
128  * For the smoothest delay, this value should be about 1 billion divided
129  * by the maximum number of operations per second.  This will smoothly
130  * handle between 10x and 1/10th this number.
131  *
132  * Note: zfs_delay_scale * zfs_dirty_data_max must be < 2^64, due to the
133  * multiply in dmu_tx_delay().
134  */
135 uint64_t zfs_delay_scale = 1000 * 1000 * 1000 / 2000;
136
137 /*
138  * This determines the number of threads used by the dp_sync_taskq.
139  */
140 int zfs_sync_taskq_batch_pct = 75;
141
142 /*
143  * These tunables determine the behavior of how zil_itxg_clean() is
144  * called via zil_clean() in the context of spa_sync(). When an itxg
145  * list needs to be cleaned, TQ_NOSLEEP will be used when dispatching.
146  * If the dispatch fails, the call to zil_itxg_clean() will occur
147  * synchronously in the context of spa_sync(), which can negatively
148  * impact the performance of spa_sync() (e.g. in the case of the itxg
149  * list having a large number of itxs that needs to be cleaned).
150  *
151  * Thus, these tunables can be used to manipulate the behavior of the
152  * taskq used by zil_clean(); they determine the number of taskq entries
153  * that are pre-populated when the taskq is first created (via the
154  * "zfs_zil_clean_taskq_minalloc" tunable) and the maximum number of
155  * taskq entries that are cached after an on-demand allocation (via the
156  * "zfs_zil_clean_taskq_maxalloc").
157  *
158  * The idea being, we want to try reasonably hard to ensure there will
159  * already be a taskq entry pre-allocated by the time that it is needed
160  * by zil_clean(). This way, we can avoid the possibility of an
161  * on-demand allocation of a new taskq entry from failing, which would
162  * result in zil_itxg_clean() being called synchronously from zil_clean()
163  * (which can adversely affect performance of spa_sync()).
164  *
165  * Additionally, the number of threads used by the taskq can be
166  * configured via the "zfs_zil_clean_taskq_nthr_pct" tunable.
167  */
168 int zfs_zil_clean_taskq_nthr_pct = 100;
169 int zfs_zil_clean_taskq_minalloc = 1024;
170 int zfs_zil_clean_taskq_maxalloc = 1024 * 1024;
171
172 #if defined(__FreeBSD__) && defined(_KERNEL)
173
174 extern int zfs_vdev_async_write_active_max_dirty_percent;
175
176 SYSCTL_DECL(_vfs_zfs);
177
178 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, dirty_data_max, CTLFLAG_RWTUN,
179     &zfs_dirty_data_max, 0,
180     "The maximum amount of dirty data in bytes after which new writes are "
181     "halted until space becomes available");
182
183 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, dirty_data_max_max, CTLFLAG_RDTUN,
184     &zfs_dirty_data_max_max, 0,
185     "The absolute cap on dirty_data_max when auto calculating");
186
187 static int sysctl_zfs_dirty_data_max_percent(SYSCTL_HANDLER_ARGS);
188 SYSCTL_PROC(_vfs_zfs, OID_AUTO, dirty_data_max_percent,
189     CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_RWTUN, 0, sizeof(int),
190     sysctl_zfs_dirty_data_max_percent, "I",
191     "The percent of physical memory used to auto calculate dirty_data_max");
192
193 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, dirty_data_sync, CTLFLAG_RWTUN,
194     &zfs_dirty_data_sync, 0,
195     "Force a txg if the number of dirty buffer bytes exceed this value");
196
197 static int sysctl_zfs_delay_min_dirty_percent(SYSCTL_HANDLER_ARGS);
198 /* No zfs_delay_min_dirty_percent tunable due to limit requirements */
199 SYSCTL_PROC(_vfs_zfs, OID_AUTO, delay_min_dirty_percent,
200     CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, sizeof(int),
201     sysctl_zfs_delay_min_dirty_percent, "I",
202     "The limit of outstanding dirty data before transactions are delayed");
203
204 static int sysctl_zfs_delay_scale(SYSCTL_HANDLER_ARGS);
205 /* No zfs_delay_scale tunable due to limit requirements */
206 SYSCTL_PROC(_vfs_zfs, OID_AUTO, delay_scale,
207     CTLTYPE_U64 | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, sizeof(uint64_t),
208     sysctl_zfs_delay_scale, "QU",
209     "Controls how quickly the delay approaches infinity");
210
211 static int
212 sysctl_zfs_dirty_data_max_percent(SYSCTL_HANDLER_ARGS)
213 {
214         int val, err;
215
216         val = zfs_dirty_data_max_percent;
217         err = sysctl_handle_int(oidp, &val, 0, req);
218         if (err != 0 || req->newptr == NULL)
219                 return (err);
220
221         if (val < 0 || val > 100)
222                 return (EINVAL);
223
224         zfs_dirty_data_max_percent = val;
225
226         return (0);
227 }
228
229 static int
230 sysctl_zfs_delay_min_dirty_percent(SYSCTL_HANDLER_ARGS)
231 {
232         int val, err;
233
234         val = zfs_delay_min_dirty_percent;
235         err = sysctl_handle_int(oidp, &val, 0, req);
236         if (err != 0 || req->newptr == NULL)
237                 return (err);
238
239         if (val < zfs_vdev_async_write_active_max_dirty_percent)
240                 return (EINVAL);
241
242         zfs_delay_min_dirty_percent = val;
243
244         return (0);
245 }
246
247 static int
248 sysctl_zfs_delay_scale(SYSCTL_HANDLER_ARGS)
249 {
250         uint64_t val;
251         int err;
252
253         val = zfs_delay_scale;
254         err = sysctl_handle_64(oidp, &val, 0, req);
255         if (err != 0 || req->newptr == NULL)
256                 return (err);
257
258         if (val > UINT64_MAX / zfs_dirty_data_max)
259                 return (EINVAL);
260
261         zfs_delay_scale = val;
262
263         return (0);
264 }
265 #endif
266
267 int
268 dsl_pool_open_special_dir(dsl_pool_t *dp, const char *name, dsl_dir_t **ddp)
269 {
270         uint64_t obj;
271         int err;
272
273         err = zap_lookup(dp->dp_meta_objset,
274             dsl_dir_phys(dp->dp_root_dir)->dd_child_dir_zapobj,
275             name, sizeof (obj), 1, &obj);
276         if (err)
277                 return (err);
278
279         return (dsl_dir_hold_obj(dp, obj, name, dp, ddp));
280 }
281
282 static dsl_pool_t *
283 dsl_pool_open_impl(spa_t *spa, uint64_t txg)
284 {
285         dsl_pool_t *dp;
286         blkptr_t *bp = spa_get_rootblkptr(spa);
287
288         dp = kmem_zalloc(sizeof (dsl_pool_t), KM_SLEEP);
289         dp->dp_spa = spa;
290         dp->dp_meta_rootbp = *bp;
291         rrw_init(&dp->dp_config_rwlock, B_TRUE);
292         txg_init(dp, txg);
293
294         txg_list_create(&dp->dp_dirty_datasets, spa,
295             offsetof(dsl_dataset_t, ds_dirty_link));
296         txg_list_create(&dp->dp_dirty_zilogs, spa,
297             offsetof(zilog_t, zl_dirty_link));
298         txg_list_create(&dp->dp_dirty_dirs, spa,
299             offsetof(dsl_dir_t, dd_dirty_link));
300         txg_list_create(&dp->dp_sync_tasks, spa,
301             offsetof(dsl_sync_task_t, dst_node));
302         txg_list_create(&dp->dp_early_sync_tasks, spa,
303             offsetof(dsl_sync_task_t, dst_node));
304
305         dp->dp_sync_taskq = taskq_create("dp_sync_taskq",
306             zfs_sync_taskq_batch_pct, minclsyspri, 1, INT_MAX,
307             TASKQ_THREADS_CPU_PCT);
308
309         dp->dp_zil_clean_taskq = taskq_create("dp_zil_clean_taskq",
310             zfs_zil_clean_taskq_nthr_pct, minclsyspri,
311             zfs_zil_clean_taskq_minalloc,
312             zfs_zil_clean_taskq_maxalloc,
313             TASKQ_PREPOPULATE | TASKQ_THREADS_CPU_PCT);
314
315         mutex_init(&dp->dp_lock, NULL, MUTEX_DEFAULT, NULL);
316         cv_init(&dp->dp_spaceavail_cv, NULL, CV_DEFAULT, NULL);
317
318         dp->dp_vnrele_taskq = taskq_create("zfs_vn_rele_taskq", 1, minclsyspri,
319             1, 4, 0);
320
321         return (dp);
322 }
323
324 int
325 dsl_pool_init(spa_t *spa, uint64_t txg, dsl_pool_t **dpp)
326 {
327         int err;
328         dsl_pool_t *dp = dsl_pool_open_impl(spa, txg);
329
330         err = dmu_objset_open_impl(spa, NULL, &dp->dp_meta_rootbp,
331             &dp->dp_meta_objset);
332         if (err != 0)
333                 dsl_pool_close(dp);
334         else
335                 *dpp = dp;
336
337         return (err);
338 }
339
340 int
341 dsl_pool_open(dsl_pool_t *dp)
342 {
343         int err;
344         dsl_dir_t *dd;
345         dsl_dataset_t *ds;
346         uint64_t obj;
347
348         rrw_enter(&dp->dp_config_rwlock, RW_WRITER, FTAG);
349         err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
350             DMU_POOL_ROOT_DATASET, sizeof (uint64_t), 1,
351             &dp->dp_root_dir_obj);
352         if (err)
353                 goto out;
354
355         err = dsl_dir_hold_obj(dp, dp->dp_root_dir_obj,
356             NULL, dp, &dp->dp_root_dir);
357         if (err)
358                 goto out;
359
360         err = dsl_pool_open_special_dir(dp, MOS_DIR_NAME, &dp->dp_mos_dir);
361         if (err)
362                 goto out;
363
364         if (spa_version(dp->dp_spa) >= SPA_VERSION_ORIGIN) {
365                 err = dsl_pool_open_special_dir(dp, ORIGIN_DIR_NAME, &dd);
366                 if (err)
367                         goto out;
368                 err = dsl_dataset_hold_obj(dp,
369                     dsl_dir_phys(dd)->dd_head_dataset_obj, FTAG, &ds);
370                 if (err == 0) {
371                         err = dsl_dataset_hold_obj(dp,
372                             dsl_dataset_phys(ds)->ds_prev_snap_obj, dp,
373                             &dp->dp_origin_snap);
374                         dsl_dataset_rele(ds, FTAG);
375                 }
376                 dsl_dir_rele(dd, dp);
377                 if (err)
378                         goto out;
379         }
380
381         if (spa_version(dp->dp_spa) >= SPA_VERSION_DEADLISTS) {
382                 err = dsl_pool_open_special_dir(dp, FREE_DIR_NAME,
383                     &dp->dp_free_dir);
384                 if (err)
385                         goto out;
386
387                 err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
388                     DMU_POOL_FREE_BPOBJ, sizeof (uint64_t), 1, &obj);
389                 if (err)
390                         goto out;
391                 VERIFY0(bpobj_open(&dp->dp_free_bpobj,
392                     dp->dp_meta_objset, obj));
393         }
394
395         if (spa_feature_is_active(dp->dp_spa, SPA_FEATURE_OBSOLETE_COUNTS)) {
396                 err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
397                     DMU_POOL_OBSOLETE_BPOBJ, sizeof (uint64_t), 1, &obj);
398                 if (err == 0) {
399                         VERIFY0(bpobj_open(&dp->dp_obsolete_bpobj,
400                             dp->dp_meta_objset, obj));
401                 } else if (err == ENOENT) {
402                         /*
403                          * We might not have created the remap bpobj yet.
404                          */
405                         err = 0;
406                 } else {
407                         goto out;
408                 }
409         }
410
411         /*
412          * Note: errors ignored, because the these special dirs, used for
413          * space accounting, are only created on demand.
414          */
415         (void) dsl_pool_open_special_dir(dp, LEAK_DIR_NAME,
416             &dp->dp_leak_dir);
417
418         if (spa_feature_is_active(dp->dp_spa, SPA_FEATURE_ASYNC_DESTROY)) {
419                 err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
420                     DMU_POOL_BPTREE_OBJ, sizeof (uint64_t), 1,
421                     &dp->dp_bptree_obj);
422                 if (err != 0)
423                         goto out;
424         }
425
426         if (spa_feature_is_active(dp->dp_spa, SPA_FEATURE_EMPTY_BPOBJ)) {
427                 err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
428                     DMU_POOL_EMPTY_BPOBJ, sizeof (uint64_t), 1,
429                     &dp->dp_empty_bpobj);
430                 if (err != 0)
431                         goto out;
432         }
433
434         err = zap_lookup(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
435             DMU_POOL_TMP_USERREFS, sizeof (uint64_t), 1,
436             &dp->dp_tmp_userrefs_obj);
437         if (err == ENOENT)
438                 err = 0;
439         if (err)
440                 goto out;
441
442         err = dsl_scan_init(dp, dp->dp_tx.tx_open_txg);
443
444 out:
445         rrw_exit(&dp->dp_config_rwlock, FTAG);
446         return (err);
447 }
448
449 void
450 dsl_pool_close(dsl_pool_t *dp)
451 {
452         /*
453          * Drop our references from dsl_pool_open().
454          *
455          * Since we held the origin_snap from "syncing" context (which
456          * includes pool-opening context), it actually only got a "ref"
457          * and not a hold, so just drop that here.
458          */
459         if (dp->dp_origin_snap != NULL)
460                 dsl_dataset_rele(dp->dp_origin_snap, dp);
461         if (dp->dp_mos_dir != NULL)
462                 dsl_dir_rele(dp->dp_mos_dir, dp);
463         if (dp->dp_free_dir != NULL)
464                 dsl_dir_rele(dp->dp_free_dir, dp);
465         if (dp->dp_leak_dir != NULL)
466                 dsl_dir_rele(dp->dp_leak_dir, dp);
467         if (dp->dp_root_dir != NULL)
468                 dsl_dir_rele(dp->dp_root_dir, dp);
469
470         bpobj_close(&dp->dp_free_bpobj);
471         bpobj_close(&dp->dp_obsolete_bpobj);
472
473         /* undo the dmu_objset_open_impl(mos) from dsl_pool_open() */
474         if (dp->dp_meta_objset != NULL)
475                 dmu_objset_evict(dp->dp_meta_objset);
476
477         txg_list_destroy(&dp->dp_dirty_datasets);
478         txg_list_destroy(&dp->dp_dirty_zilogs);
479         txg_list_destroy(&dp->dp_sync_tasks);
480         txg_list_destroy(&dp->dp_early_sync_tasks);
481         txg_list_destroy(&dp->dp_dirty_dirs);
482
483         taskq_destroy(dp->dp_zil_clean_taskq);
484         taskq_destroy(dp->dp_sync_taskq);
485
486         /*
487          * We can't set retry to TRUE since we're explicitly specifying
488          * a spa to flush. This is good enough; any missed buffers for
489          * this spa won't cause trouble, and they'll eventually fall
490          * out of the ARC just like any other unused buffer.
491          */
492         arc_flush(dp->dp_spa, FALSE);
493
494         txg_fini(dp);
495         dsl_scan_fini(dp);
496         dmu_buf_user_evict_wait();
497
498         rrw_destroy(&dp->dp_config_rwlock);
499         mutex_destroy(&dp->dp_lock);
500         taskq_destroy(dp->dp_vnrele_taskq);
501         if (dp->dp_blkstats != NULL)
502                 kmem_free(dp->dp_blkstats, sizeof (zfs_all_blkstats_t));
503         kmem_free(dp, sizeof (dsl_pool_t));
504 }
505
506 void
507 dsl_pool_create_obsolete_bpobj(dsl_pool_t *dp, dmu_tx_t *tx)
508 {
509         uint64_t obj;
510         /*
511          * Currently, we only create the obsolete_bpobj where there are
512          * indirect vdevs with referenced mappings.
513          */
514         ASSERT(spa_feature_is_active(dp->dp_spa, SPA_FEATURE_DEVICE_REMOVAL));
515         /* create and open the obsolete_bpobj */
516         obj = bpobj_alloc(dp->dp_meta_objset, SPA_OLD_MAXBLOCKSIZE, tx);
517         VERIFY0(bpobj_open(&dp->dp_obsolete_bpobj, dp->dp_meta_objset, obj));
518         VERIFY0(zap_add(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
519             DMU_POOL_OBSOLETE_BPOBJ, sizeof (uint64_t), 1, &obj, tx));
520         spa_feature_incr(dp->dp_spa, SPA_FEATURE_OBSOLETE_COUNTS, tx);
521 }
522
523 void
524 dsl_pool_destroy_obsolete_bpobj(dsl_pool_t *dp, dmu_tx_t *tx)
525 {
526         spa_feature_decr(dp->dp_spa, SPA_FEATURE_OBSOLETE_COUNTS, tx);
527         VERIFY0(zap_remove(dp->dp_meta_objset,
528             DMU_POOL_DIRECTORY_OBJECT,
529             DMU_POOL_OBSOLETE_BPOBJ, tx));
530         bpobj_free(dp->dp_meta_objset,
531             dp->dp_obsolete_bpobj.bpo_object, tx);
532         bpobj_close(&dp->dp_obsolete_bpobj);
533 }
534
535 dsl_pool_t *
536 dsl_pool_create(spa_t *spa, nvlist_t *zplprops, uint64_t txg)
537 {
538         int err;
539         dsl_pool_t *dp = dsl_pool_open_impl(spa, txg);
540         dmu_tx_t *tx = dmu_tx_create_assigned(dp, txg);
541         dsl_dataset_t *ds;
542         uint64_t obj;
543
544         rrw_enter(&dp->dp_config_rwlock, RW_WRITER, FTAG);
545
546         /* create and open the MOS (meta-objset) */
547         dp->dp_meta_objset = dmu_objset_create_impl(spa,
548             NULL, &dp->dp_meta_rootbp, DMU_OST_META, tx);
549
550         /* create the pool directory */
551         err = zap_create_claim(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
552             DMU_OT_OBJECT_DIRECTORY, DMU_OT_NONE, 0, tx);
553         ASSERT0(err);
554
555         /* Initialize scan structures */
556         VERIFY0(dsl_scan_init(dp, txg));
557
558         /* create and open the root dir */
559         dp->dp_root_dir_obj = dsl_dir_create_sync(dp, NULL, NULL, tx);
560         VERIFY0(dsl_dir_hold_obj(dp, dp->dp_root_dir_obj,
561             NULL, dp, &dp->dp_root_dir));
562
563         /* create and open the meta-objset dir */
564         (void) dsl_dir_create_sync(dp, dp->dp_root_dir, MOS_DIR_NAME, tx);
565         VERIFY0(dsl_pool_open_special_dir(dp,
566             MOS_DIR_NAME, &dp->dp_mos_dir));
567
568         if (spa_version(spa) >= SPA_VERSION_DEADLISTS) {
569                 /* create and open the free dir */
570                 (void) dsl_dir_create_sync(dp, dp->dp_root_dir,
571                     FREE_DIR_NAME, tx);
572                 VERIFY0(dsl_pool_open_special_dir(dp,
573                     FREE_DIR_NAME, &dp->dp_free_dir));
574
575                 /* create and open the free_bplist */
576                 obj = bpobj_alloc(dp->dp_meta_objset, SPA_OLD_MAXBLOCKSIZE, tx);
577                 VERIFY(zap_add(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
578                     DMU_POOL_FREE_BPOBJ, sizeof (uint64_t), 1, &obj, tx) == 0);
579                 VERIFY0(bpobj_open(&dp->dp_free_bpobj,
580                     dp->dp_meta_objset, obj));
581         }
582
583         if (spa_version(spa) >= SPA_VERSION_DSL_SCRUB)
584                 dsl_pool_create_origin(dp, tx);
585
586         /* create the root dataset */
587         obj = dsl_dataset_create_sync_dd(dp->dp_root_dir, NULL, 0, tx);
588
589         /* create the root objset */
590         VERIFY0(dsl_dataset_hold_obj(dp, obj, FTAG, &ds));
591 #ifdef _KERNEL
592         {
593                 objset_t *os;
594                 rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);
595                 os = dmu_objset_create_impl(dp->dp_spa, ds,
596                     dsl_dataset_get_blkptr(ds), DMU_OST_ZFS, tx);
597                 rrw_exit(&ds->ds_bp_rwlock, FTAG);
598                 zfs_create_fs(os, kcred, zplprops, tx);
599         }
600 #endif
601         dsl_dataset_rele(ds, FTAG);
602
603         dmu_tx_commit(tx);
604
605         rrw_exit(&dp->dp_config_rwlock, FTAG);
606
607         return (dp);
608 }
609
610 /*
611  * Account for the meta-objset space in its placeholder dsl_dir.
612  */
613 void
614 dsl_pool_mos_diduse_space(dsl_pool_t *dp,
615     int64_t used, int64_t comp, int64_t uncomp)
616 {
617         ASSERT3U(comp, ==, uncomp); /* it's all metadata */
618         mutex_enter(&dp->dp_lock);
619         dp->dp_mos_used_delta += used;
620         dp->dp_mos_compressed_delta += comp;
621         dp->dp_mos_uncompressed_delta += uncomp;
622         mutex_exit(&dp->dp_lock);
623 }
624
625 static void
626 dsl_pool_sync_mos(dsl_pool_t *dp, dmu_tx_t *tx)
627 {
628         zio_t *zio = zio_root(dp->dp_spa, NULL, NULL, ZIO_FLAG_MUSTSUCCEED);
629         dmu_objset_sync(dp->dp_meta_objset, zio, tx);
630         VERIFY0(zio_wait(zio));
631         dprintf_bp(&dp->dp_meta_rootbp, "meta objset rootbp is %s", "");
632         spa_set_rootblkptr(dp->dp_spa, &dp->dp_meta_rootbp);
633 }
634
635 static void
636 dsl_pool_dirty_delta(dsl_pool_t *dp, int64_t delta)
637 {
638         ASSERT(MUTEX_HELD(&dp->dp_lock));
639
640         if (delta < 0)
641                 ASSERT3U(-delta, <=, dp->dp_dirty_total);
642
643         dp->dp_dirty_total += delta;
644
645         /*
646          * Note: we signal even when increasing dp_dirty_total.
647          * This ensures forward progress -- each thread wakes the next waiter.
648          */
649         if (dp->dp_dirty_total < zfs_dirty_data_max)
650                 cv_signal(&dp->dp_spaceavail_cv);
651 }
652
653 static boolean_t
654 dsl_early_sync_task_verify(dsl_pool_t *dp, uint64_t txg)
655 {
656         spa_t *spa = dp->dp_spa;
657         vdev_t *rvd = spa->spa_root_vdev;
658
659         for (uint64_t c = 0; c < rvd->vdev_children; c++) {
660                 vdev_t *vd = rvd->vdev_child[c];
661                 txg_list_t *tl = &vd->vdev_ms_list;
662                 metaslab_t *ms;
663
664                 for (ms = txg_list_head(tl, TXG_CLEAN(txg)); ms;
665                     ms = txg_list_next(tl, ms, TXG_CLEAN(txg))) {
666                         VERIFY(range_tree_is_empty(ms->ms_freeing));
667                         VERIFY(range_tree_is_empty(ms->ms_checkpointing));
668                 }
669         }
670
671         return (B_TRUE);
672 }
673
674 void
675 dsl_pool_sync(dsl_pool_t *dp, uint64_t txg)
676 {
677         zio_t *zio;
678         dmu_tx_t *tx;
679         dsl_dir_t *dd;
680         dsl_dataset_t *ds;
681         objset_t *mos = dp->dp_meta_objset;
682         list_t synced_datasets;
683
684         list_create(&synced_datasets, sizeof (dsl_dataset_t),
685             offsetof(dsl_dataset_t, ds_synced_link));
686
687         tx = dmu_tx_create_assigned(dp, txg);
688
689         /*
690          * Run all early sync tasks before writing out any dirty blocks.
691          * For more info on early sync tasks see block comment in
692          * dsl_early_sync_task().
693          */
694         if (!txg_list_empty(&dp->dp_early_sync_tasks, txg)) {
695                 dsl_sync_task_t *dst;
696
697                 ASSERT3U(spa_sync_pass(dp->dp_spa), ==, 1);
698                 while ((dst =
699                     txg_list_remove(&dp->dp_early_sync_tasks, txg)) != NULL) {
700                         ASSERT(dsl_early_sync_task_verify(dp, txg));
701                         dsl_sync_task_sync(dst, tx);
702                 }
703                 ASSERT(dsl_early_sync_task_verify(dp, txg));
704         }
705
706         /*
707          * Write out all dirty blocks of dirty datasets.
708          */
709         zio = zio_root(dp->dp_spa, NULL, NULL, ZIO_FLAG_MUSTSUCCEED);
710         while ((ds = txg_list_remove(&dp->dp_dirty_datasets, txg)) != NULL) {
711                 /*
712                  * We must not sync any non-MOS datasets twice, because
713                  * we may have taken a snapshot of them.  However, we
714                  * may sync newly-created datasets on pass 2.
715                  */
716                 ASSERT(!list_link_active(&ds->ds_synced_link));
717                 list_insert_tail(&synced_datasets, ds);
718                 dsl_dataset_sync(ds, zio, tx);
719         }
720         VERIFY0(zio_wait(zio));
721
722         /*
723          * We have written all of the accounted dirty data, so our
724          * dp_space_towrite should now be zero.  However, some seldom-used
725          * code paths do not adhere to this (e.g. dbuf_undirty(), also
726          * rounding error in dbuf_write_physdone).
727          * Shore up the accounting of any dirtied space now.
728          */
729         dsl_pool_undirty_space(dp, dp->dp_dirty_pertxg[txg & TXG_MASK], txg);
730
731         /*
732          * Update the long range free counter after
733          * we're done syncing user data
734          */
735         mutex_enter(&dp->dp_lock);
736         ASSERT(spa_sync_pass(dp->dp_spa) == 1 ||
737             dp->dp_long_free_dirty_pertxg[txg & TXG_MASK] == 0);
738         dp->dp_long_free_dirty_pertxg[txg & TXG_MASK] = 0;
739         mutex_exit(&dp->dp_lock);
740
741         /*
742          * After the data blocks have been written (ensured by the zio_wait()
743          * above), update the user/group space accounting.  This happens
744          * in tasks dispatched to dp_sync_taskq, so wait for them before
745          * continuing.
746          */
747         for (ds = list_head(&synced_datasets); ds != NULL;
748             ds = list_next(&synced_datasets, ds)) {
749                 dmu_objset_do_userquota_updates(ds->ds_objset, tx);
750         }
751         taskq_wait(dp->dp_sync_taskq);
752
753         /*
754          * Sync the datasets again to push out the changes due to
755          * userspace updates.  This must be done before we process the
756          * sync tasks, so that any snapshots will have the correct
757          * user accounting information (and we won't get confused
758          * about which blocks are part of the snapshot).
759          */
760         zio = zio_root(dp->dp_spa, NULL, NULL, ZIO_FLAG_MUSTSUCCEED);
761         while ((ds = txg_list_remove(&dp->dp_dirty_datasets, txg)) != NULL) {
762                 ASSERT(list_link_active(&ds->ds_synced_link));
763                 dmu_buf_rele(ds->ds_dbuf, ds);
764                 dsl_dataset_sync(ds, zio, tx);
765         }
766         VERIFY0(zio_wait(zio));
767
768         /*
769          * Now that the datasets have been completely synced, we can
770          * clean up our in-memory structures accumulated while syncing:
771          *
772          *  - move dead blocks from the pending deadlist to the on-disk deadlist
773          *  - release hold from dsl_dataset_dirty()
774          */
775         while ((ds = list_remove_head(&synced_datasets)) != NULL) {
776                 dsl_dataset_sync_done(ds, tx);
777         }
778         while ((dd = txg_list_remove(&dp->dp_dirty_dirs, txg)) != NULL) {
779                 dsl_dir_sync(dd, tx);
780         }
781
782         /*
783          * The MOS's space is accounted for in the pool/$MOS
784          * (dp_mos_dir).  We can't modify the mos while we're syncing
785          * it, so we remember the deltas and apply them here.
786          */
787         if (dp->dp_mos_used_delta != 0 || dp->dp_mos_compressed_delta != 0 ||
788             dp->dp_mos_uncompressed_delta != 0) {
789                 dsl_dir_diduse_space(dp->dp_mos_dir, DD_USED_HEAD,
790                     dp->dp_mos_used_delta,
791                     dp->dp_mos_compressed_delta,
792                     dp->dp_mos_uncompressed_delta, tx);
793                 dp->dp_mos_used_delta = 0;
794                 dp->dp_mos_compressed_delta = 0;
795                 dp->dp_mos_uncompressed_delta = 0;
796         }
797
798         if (!multilist_is_empty(mos->os_dirty_dnodes[txg & TXG_MASK])) {
799                 dsl_pool_sync_mos(dp, tx);
800         }
801
802         /*
803          * If we modify a dataset in the same txg that we want to destroy it,
804          * its dsl_dir's dd_dbuf will be dirty, and thus have a hold on it.
805          * dsl_dir_destroy_check() will fail if there are unexpected holds.
806          * Therefore, we want to sync the MOS (thus syncing the dd_dbuf
807          * and clearing the hold on it) before we process the sync_tasks.
808          * The MOS data dirtied by the sync_tasks will be synced on the next
809          * pass.
810          */
811         if (!txg_list_empty(&dp->dp_sync_tasks, txg)) {
812                 dsl_sync_task_t *dst;
813                 /*
814                  * No more sync tasks should have been added while we
815                  * were syncing.
816                  */
817                 ASSERT3U(spa_sync_pass(dp->dp_spa), ==, 1);
818                 while ((dst = txg_list_remove(&dp->dp_sync_tasks, txg)) != NULL)
819                         dsl_sync_task_sync(dst, tx);
820         }
821
822         dmu_tx_commit(tx);
823
824         DTRACE_PROBE2(dsl_pool_sync__done, dsl_pool_t *dp, dp, uint64_t, txg);
825 }
826
827 void
828 dsl_pool_sync_done(dsl_pool_t *dp, uint64_t txg)
829 {
830         zilog_t *zilog;
831
832         while (zilog = txg_list_head(&dp->dp_dirty_zilogs, txg)) {
833                 dsl_dataset_t *ds = dmu_objset_ds(zilog->zl_os);
834                 /*
835                  * We don't remove the zilog from the dp_dirty_zilogs
836                  * list until after we've cleaned it. This ensures that
837                  * callers of zilog_is_dirty() receive an accurate
838                  * answer when they are racing with the spa sync thread.
839                  */
840                 zil_clean(zilog, txg);
841                 (void) txg_list_remove_this(&dp->dp_dirty_zilogs, zilog, txg);
842                 ASSERT(!dmu_objset_is_dirty(zilog->zl_os, txg));
843                 dmu_buf_rele(ds->ds_dbuf, zilog);
844         }
845         ASSERT(!dmu_objset_is_dirty(dp->dp_meta_objset, txg));
846 }
847
848 /*
849  * TRUE if the current thread is the tx_sync_thread or if we
850  * are being called from SPA context during pool initialization.
851  */
852 int
853 dsl_pool_sync_context(dsl_pool_t *dp)
854 {
855         return (curthread == dp->dp_tx.tx_sync_thread ||
856             spa_is_initializing(dp->dp_spa) ||
857             taskq_member(dp->dp_sync_taskq, curthread));
858 }
859
860 /*
861  * This function returns the amount of allocatable space in the pool
862  * minus whatever space is currently reserved by ZFS for specific
863  * purposes. Specifically:
864  *
865  * 1] Any reserved SLOP space
866  * 2] Any space used by the checkpoint
867  * 3] Any space used for deferred frees
868  *
869  * The latter 2 are especially important because they are needed to
870  * rectify the SPA's and DMU's different understanding of how much space
871  * is used. Now the DMU is aware of that extra space tracked by the SPA
872  * without having to maintain a separate special dir (e.g similar to
873  * $MOS, $FREEING, and $LEAKED).
874  *
875  * Note: By deferred frees here, we mean the frees that were deferred
876  * in spa_sync() after sync pass 1 (spa_deferred_bpobj), and not the
877  * segments placed in ms_defer trees during metaslab_sync_done().
878  */
879 uint64_t
880 dsl_pool_adjustedsize(dsl_pool_t *dp, zfs_space_check_t slop_policy)
881 {
882         spa_t *spa = dp->dp_spa;
883         uint64_t space, resv, adjustedsize;
884         uint64_t spa_deferred_frees =
885             spa->spa_deferred_bpobj.bpo_phys->bpo_bytes;
886
887         space = spa_get_dspace(spa)
888             - spa_get_checkpoint_space(spa) - spa_deferred_frees;
889         resv = spa_get_slop_space(spa);
890
891         switch (slop_policy) {
892         case ZFS_SPACE_CHECK_NORMAL:
893                 break;
894         case ZFS_SPACE_CHECK_RESERVED:
895                 resv >>= 1;
896                 break;
897         case ZFS_SPACE_CHECK_EXTRA_RESERVED:
898                 resv >>= 2;
899                 break;
900         case ZFS_SPACE_CHECK_NONE:
901                 resv = 0;
902                 break;
903         default:
904                 panic("invalid slop policy value: %d", slop_policy);
905                 break;
906         }
907         adjustedsize = (space >= resv) ? (space - resv) : 0;
908
909         return (adjustedsize);
910 }
911
912 uint64_t
913 dsl_pool_unreserved_space(dsl_pool_t *dp, zfs_space_check_t slop_policy)
914 {
915         uint64_t poolsize = dsl_pool_adjustedsize(dp, slop_policy);
916         uint64_t deferred =
917             metaslab_class_get_deferred(spa_normal_class(dp->dp_spa));
918         uint64_t quota = (poolsize >= deferred) ? (poolsize - deferred) : 0;
919         return (quota);
920 }
921
922 boolean_t
923 dsl_pool_need_dirty_delay(dsl_pool_t *dp)
924 {
925         uint64_t delay_min_bytes =
926             zfs_dirty_data_max * zfs_delay_min_dirty_percent / 100;
927         boolean_t rv;
928
929         mutex_enter(&dp->dp_lock);
930         if (dp->dp_dirty_total > zfs_dirty_data_sync)
931                 txg_kick(dp);
932         rv = (dp->dp_dirty_total > delay_min_bytes);
933         mutex_exit(&dp->dp_lock);
934         return (rv);
935 }
936
937 void
938 dsl_pool_dirty_space(dsl_pool_t *dp, int64_t space, dmu_tx_t *tx)
939 {
940         if (space > 0) {
941                 mutex_enter(&dp->dp_lock);
942                 dp->dp_dirty_pertxg[tx->tx_txg & TXG_MASK] += space;
943                 dsl_pool_dirty_delta(dp, space);
944                 mutex_exit(&dp->dp_lock);
945         }
946 }
947
948 void
949 dsl_pool_undirty_space(dsl_pool_t *dp, int64_t space, uint64_t txg)
950 {
951         ASSERT3S(space, >=, 0);
952         if (space == 0)
953                 return;
954         mutex_enter(&dp->dp_lock);
955         if (dp->dp_dirty_pertxg[txg & TXG_MASK] < space) {
956                 /* XXX writing something we didn't dirty? */
957                 space = dp->dp_dirty_pertxg[txg & TXG_MASK];
958         }
959         ASSERT3U(dp->dp_dirty_pertxg[txg & TXG_MASK], >=, space);
960         dp->dp_dirty_pertxg[txg & TXG_MASK] -= space;
961         ASSERT3U(dp->dp_dirty_total, >=, space);
962         dsl_pool_dirty_delta(dp, -space);
963         mutex_exit(&dp->dp_lock);
964 }
965
966 /* ARGSUSED */
967 static int
968 upgrade_clones_cb(dsl_pool_t *dp, dsl_dataset_t *hds, void *arg)
969 {
970         dmu_tx_t *tx = arg;
971         dsl_dataset_t *ds, *prev = NULL;
972         int err;
973
974         err = dsl_dataset_hold_obj(dp, hds->ds_object, FTAG, &ds);
975         if (err)
976                 return (err);
977
978         while (dsl_dataset_phys(ds)->ds_prev_snap_obj != 0) {
979                 err = dsl_dataset_hold_obj(dp,
980                     dsl_dataset_phys(ds)->ds_prev_snap_obj, FTAG, &prev);
981                 if (err) {
982                         dsl_dataset_rele(ds, FTAG);
983                         return (err);
984                 }
985
986                 if (dsl_dataset_phys(prev)->ds_next_snap_obj != ds->ds_object)
987                         break;
988                 dsl_dataset_rele(ds, FTAG);
989                 ds = prev;
990                 prev = NULL;
991         }
992
993         if (prev == NULL) {
994                 prev = dp->dp_origin_snap;
995
996                 /*
997                  * The $ORIGIN can't have any data, or the accounting
998                  * will be wrong.
999                  */
1000                 rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);
1001                 ASSERT0(dsl_dataset_phys(prev)->ds_bp.blk_birth);
1002                 rrw_exit(&ds->ds_bp_rwlock, FTAG);
1003
1004                 /* The origin doesn't get attached to itself */
1005                 if (ds->ds_object == prev->ds_object) {
1006                         dsl_dataset_rele(ds, FTAG);
1007                         return (0);
1008                 }
1009
1010                 dmu_buf_will_dirty(ds->ds_dbuf, tx);
1011                 dsl_dataset_phys(ds)->ds_prev_snap_obj = prev->ds_object;
1012                 dsl_dataset_phys(ds)->ds_prev_snap_txg =
1013                     dsl_dataset_phys(prev)->ds_creation_txg;
1014
1015                 dmu_buf_will_dirty(ds->ds_dir->dd_dbuf, tx);
1016                 dsl_dir_phys(ds->ds_dir)->dd_origin_obj = prev->ds_object;
1017
1018                 dmu_buf_will_dirty(prev->ds_dbuf, tx);
1019                 dsl_dataset_phys(prev)->ds_num_children++;
1020
1021                 if (dsl_dataset_phys(ds)->ds_next_snap_obj == 0) {
1022                         ASSERT(ds->ds_prev == NULL);
1023                         VERIFY0(dsl_dataset_hold_obj(dp,
1024                             dsl_dataset_phys(ds)->ds_prev_snap_obj,
1025                             ds, &ds->ds_prev));
1026                 }
1027         }
1028
1029         ASSERT3U(dsl_dir_phys(ds->ds_dir)->dd_origin_obj, ==, prev->ds_object);
1030         ASSERT3U(dsl_dataset_phys(ds)->ds_prev_snap_obj, ==, prev->ds_object);
1031
1032         if (dsl_dataset_phys(prev)->ds_next_clones_obj == 0) {
1033                 dmu_buf_will_dirty(prev->ds_dbuf, tx);
1034                 dsl_dataset_phys(prev)->ds_next_clones_obj =
1035                     zap_create(dp->dp_meta_objset,
1036                     DMU_OT_NEXT_CLONES, DMU_OT_NONE, 0, tx);
1037         }
1038         VERIFY0(zap_add_int(dp->dp_meta_objset,
1039             dsl_dataset_phys(prev)->ds_next_clones_obj, ds->ds_object, tx));
1040
1041         dsl_dataset_rele(ds, FTAG);
1042         if (prev != dp->dp_origin_snap)
1043                 dsl_dataset_rele(prev, FTAG);
1044         return (0);
1045 }
1046
1047 void
1048 dsl_pool_upgrade_clones(dsl_pool_t *dp, dmu_tx_t *tx)
1049 {
1050         ASSERT(dmu_tx_is_syncing(tx));
1051         ASSERT(dp->dp_origin_snap != NULL);
1052
1053         VERIFY0(dmu_objset_find_dp(dp, dp->dp_root_dir_obj, upgrade_clones_cb,
1054             tx, DS_FIND_CHILDREN | DS_FIND_SERIALIZE));
1055 }
1056
1057 /* ARGSUSED */
1058 static int
1059 upgrade_dir_clones_cb(dsl_pool_t *dp, dsl_dataset_t *ds, void *arg)
1060 {
1061         dmu_tx_t *tx = arg;
1062         objset_t *mos = dp->dp_meta_objset;
1063
1064         if (dsl_dir_phys(ds->ds_dir)->dd_origin_obj != 0) {
1065                 dsl_dataset_t *origin;
1066
1067                 VERIFY0(dsl_dataset_hold_obj(dp,
1068                     dsl_dir_phys(ds->ds_dir)->dd_origin_obj, FTAG, &origin));
1069
1070                 if (dsl_dir_phys(origin->ds_dir)->dd_clones == 0) {
1071                         dmu_buf_will_dirty(origin->ds_dir->dd_dbuf, tx);
1072                         dsl_dir_phys(origin->ds_dir)->dd_clones =
1073                             zap_create(mos, DMU_OT_DSL_CLONES, DMU_OT_NONE,
1074                             0, tx);
1075                 }
1076
1077                 VERIFY0(zap_add_int(dp->dp_meta_objset,
1078                     dsl_dir_phys(origin->ds_dir)->dd_clones,
1079                     ds->ds_object, tx));
1080
1081                 dsl_dataset_rele(origin, FTAG);
1082         }
1083         return (0);
1084 }
1085
1086 void
1087 dsl_pool_upgrade_dir_clones(dsl_pool_t *dp, dmu_tx_t *tx)
1088 {
1089         ASSERT(dmu_tx_is_syncing(tx));
1090         uint64_t obj;
1091
1092         (void) dsl_dir_create_sync(dp, dp->dp_root_dir, FREE_DIR_NAME, tx);
1093         VERIFY0(dsl_pool_open_special_dir(dp,
1094             FREE_DIR_NAME, &dp->dp_free_dir));
1095
1096         /*
1097          * We can't use bpobj_alloc(), because spa_version() still
1098          * returns the old version, and we need a new-version bpobj with
1099          * subobj support.  So call dmu_object_alloc() directly.
1100          */
1101         obj = dmu_object_alloc(dp->dp_meta_objset, DMU_OT_BPOBJ,
1102             SPA_OLD_MAXBLOCKSIZE, DMU_OT_BPOBJ_HDR, sizeof (bpobj_phys_t), tx);
1103         VERIFY0(zap_add(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
1104             DMU_POOL_FREE_BPOBJ, sizeof (uint64_t), 1, &obj, tx));
1105         VERIFY0(bpobj_open(&dp->dp_free_bpobj, dp->dp_meta_objset, obj));
1106
1107         VERIFY0(dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
1108             upgrade_dir_clones_cb, tx, DS_FIND_CHILDREN | DS_FIND_SERIALIZE));
1109 }
1110
1111 void
1112 dsl_pool_create_origin(dsl_pool_t *dp, dmu_tx_t *tx)
1113 {
1114         uint64_t dsobj;
1115         dsl_dataset_t *ds;
1116
1117         ASSERT(dmu_tx_is_syncing(tx));
1118         ASSERT(dp->dp_origin_snap == NULL);
1119         ASSERT(rrw_held(&dp->dp_config_rwlock, RW_WRITER));
1120
1121         /* create the origin dir, ds, & snap-ds */
1122         dsobj = dsl_dataset_create_sync(dp->dp_root_dir, ORIGIN_DIR_NAME,
1123             NULL, 0, kcred, tx);
1124         VERIFY0(dsl_dataset_hold_obj(dp, dsobj, FTAG, &ds));
1125         dsl_dataset_snapshot_sync_impl(ds, ORIGIN_DIR_NAME, tx);
1126         VERIFY0(dsl_dataset_hold_obj(dp, dsl_dataset_phys(ds)->ds_prev_snap_obj,
1127             dp, &dp->dp_origin_snap));
1128         dsl_dataset_rele(ds, FTAG);
1129 }
1130
1131 taskq_t *
1132 dsl_pool_vnrele_taskq(dsl_pool_t *dp)
1133 {
1134         return (dp->dp_vnrele_taskq);
1135 }
1136
1137 /*
1138  * Walk through the pool-wide zap object of temporary snapshot user holds
1139  * and release them.
1140  */
1141 void
1142 dsl_pool_clean_tmp_userrefs(dsl_pool_t *dp)
1143 {
1144         zap_attribute_t za;
1145         zap_cursor_t zc;
1146         objset_t *mos = dp->dp_meta_objset;
1147         uint64_t zapobj = dp->dp_tmp_userrefs_obj;
1148         nvlist_t *holds;
1149
1150         if (zapobj == 0)
1151                 return;
1152         ASSERT(spa_version(dp->dp_spa) >= SPA_VERSION_USERREFS);
1153
1154         holds = fnvlist_alloc();
1155
1156         for (zap_cursor_init(&zc, mos, zapobj);
1157             zap_cursor_retrieve(&zc, &za) == 0;
1158             zap_cursor_advance(&zc)) {
1159                 char *htag;
1160                 nvlist_t *tags;
1161
1162                 htag = strchr(za.za_name, '-');
1163                 *htag = '\0';
1164                 ++htag;
1165                 if (nvlist_lookup_nvlist(holds, za.za_name, &tags) != 0) {
1166                         tags = fnvlist_alloc();
1167                         fnvlist_add_boolean(tags, htag);
1168                         fnvlist_add_nvlist(holds, za.za_name, tags);
1169                         fnvlist_free(tags);
1170                 } else {
1171                         fnvlist_add_boolean(tags, htag);
1172                 }
1173         }
1174         dsl_dataset_user_release_tmp(dp, holds);
1175         fnvlist_free(holds);
1176         zap_cursor_fini(&zc);
1177 }
1178
1179 /*
1180  * Create the pool-wide zap object for storing temporary snapshot holds.
1181  */
1182 void
1183 dsl_pool_user_hold_create_obj(dsl_pool_t *dp, dmu_tx_t *tx)
1184 {
1185         objset_t *mos = dp->dp_meta_objset;
1186
1187         ASSERT(dp->dp_tmp_userrefs_obj == 0);
1188         ASSERT(dmu_tx_is_syncing(tx));
1189
1190         dp->dp_tmp_userrefs_obj = zap_create_link(mos, DMU_OT_USERREFS,
1191             DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_TMP_USERREFS, tx);
1192 }
1193
1194 static int
1195 dsl_pool_user_hold_rele_impl(dsl_pool_t *dp, uint64_t dsobj,
1196     const char *tag, uint64_t now, dmu_tx_t *tx, boolean_t holding)
1197 {
1198         objset_t *mos = dp->dp_meta_objset;
1199         uint64_t zapobj = dp->dp_tmp_userrefs_obj;
1200         char *name;
1201         int error;
1202
1203         ASSERT(spa_version(dp->dp_spa) >= SPA_VERSION_USERREFS);
1204         ASSERT(dmu_tx_is_syncing(tx));
1205
1206         /*
1207          * If the pool was created prior to SPA_VERSION_USERREFS, the
1208          * zap object for temporary holds might not exist yet.
1209          */
1210         if (zapobj == 0) {
1211                 if (holding) {
1212                         dsl_pool_user_hold_create_obj(dp, tx);
1213                         zapobj = dp->dp_tmp_userrefs_obj;
1214                 } else {
1215                         return (SET_ERROR(ENOENT));
1216                 }
1217         }
1218
1219         name = kmem_asprintf("%llx-%s", (u_longlong_t)dsobj, tag);
1220         if (holding)
1221                 error = zap_add(mos, zapobj, name, 8, 1, &now, tx);
1222         else
1223                 error = zap_remove(mos, zapobj, name, tx);
1224         strfree(name);
1225
1226         return (error);
1227 }
1228
1229 /*
1230  * Add a temporary hold for the given dataset object and tag.
1231  */
1232 int
1233 dsl_pool_user_hold(dsl_pool_t *dp, uint64_t dsobj, const char *tag,
1234     uint64_t now, dmu_tx_t *tx)
1235 {
1236         return (dsl_pool_user_hold_rele_impl(dp, dsobj, tag, now, tx, B_TRUE));
1237 }
1238
1239 /*
1240  * Release a temporary hold for the given dataset object and tag.
1241  */
1242 int
1243 dsl_pool_user_release(dsl_pool_t *dp, uint64_t dsobj, const char *tag,
1244     dmu_tx_t *tx)
1245 {
1246         return (dsl_pool_user_hold_rele_impl(dp, dsobj, tag, 0,
1247             tx, B_FALSE));
1248 }
1249
1250 /*
1251  * DSL Pool Configuration Lock
1252  *
1253  * The dp_config_rwlock protects against changes to DSL state (e.g. dataset
1254  * creation / destruction / rename / property setting).  It must be held for
1255  * read to hold a dataset or dsl_dir.  I.e. you must call
1256  * dsl_pool_config_enter() or dsl_pool_hold() before calling
1257  * dsl_{dataset,dir}_hold{_obj}.  In most circumstances, the dp_config_rwlock
1258  * must be held continuously until all datasets and dsl_dirs are released.
1259  *
1260  * The only exception to this rule is that if a "long hold" is placed on
1261  * a dataset, then the dp_config_rwlock may be dropped while the dataset
1262  * is still held.  The long hold will prevent the dataset from being
1263  * destroyed -- the destroy will fail with EBUSY.  A long hold can be
1264  * obtained by calling dsl_dataset_long_hold(), or by "owning" a dataset
1265  * (by calling dsl_{dataset,objset}_{try}own{_obj}).
1266  *
1267  * Legitimate long-holders (including owners) should be long-running, cancelable
1268  * tasks that should cause "zfs destroy" to fail.  This includes DMU
1269  * consumers (i.e. a ZPL filesystem being mounted or ZVOL being open),
1270  * "zfs send", and "zfs diff".  There are several other long-holders whose
1271  * uses are suboptimal (e.g. "zfs promote", and zil_suspend()).
1272  *
1273  * The usual formula for long-holding would be:
1274  * dsl_pool_hold()
1275  * dsl_dataset_hold()
1276  * ... perform checks ...
1277  * dsl_dataset_long_hold()
1278  * dsl_pool_rele()
1279  * ... perform long-running task ...
1280  * dsl_dataset_long_rele()
1281  * dsl_dataset_rele()
1282  *
1283  * Note that when the long hold is released, the dataset is still held but
1284  * the pool is not held.  The dataset may change arbitrarily during this time
1285  * (e.g. it could be destroyed).  Therefore you shouldn't do anything to the
1286  * dataset except release it.
1287  *
1288  * User-initiated operations (e.g. ioctls, zfs_ioc_*()) are either read-only
1289  * or modifying operations.
1290  *
1291  * Modifying operations should generally use dsl_sync_task().  The synctask
1292  * infrastructure enforces proper locking strategy with respect to the
1293  * dp_config_rwlock.  See the comment above dsl_sync_task() for details.
1294  *
1295  * Read-only operations will manually hold the pool, then the dataset, obtain
1296  * information from the dataset, then release the pool and dataset.
1297  * dmu_objset_{hold,rele}() are convenience routines that also do the pool
1298  * hold/rele.
1299  */
1300
1301 int
1302 dsl_pool_hold(const char *name, void *tag, dsl_pool_t **dp)
1303 {
1304         spa_t *spa;
1305         int error;
1306
1307         error = spa_open(name, &spa, tag);
1308         if (error == 0) {
1309                 *dp = spa_get_dsl(spa);
1310                 dsl_pool_config_enter(*dp, tag);
1311         }
1312         return (error);
1313 }
1314
1315 void
1316 dsl_pool_rele(dsl_pool_t *dp, void *tag)
1317 {
1318         dsl_pool_config_exit(dp, tag);
1319         spa_close(dp->dp_spa, tag);
1320 }
1321
1322 void
1323 dsl_pool_config_enter(dsl_pool_t *dp, void *tag)
1324 {
1325         /*
1326          * We use a "reentrant" reader-writer lock, but not reentrantly.
1327          *
1328          * The rrwlock can (with the track_all flag) track all reading threads,
1329          * which is very useful for debugging which code path failed to release
1330          * the lock, and for verifying that the *current* thread does hold
1331          * the lock.
1332          *
1333          * (Unlike a rwlock, which knows that N threads hold it for
1334          * read, but not *which* threads, so rw_held(RW_READER) returns TRUE
1335          * if any thread holds it for read, even if this thread doesn't).
1336          */
1337         ASSERT(!rrw_held(&dp->dp_config_rwlock, RW_READER));
1338         rrw_enter(&dp->dp_config_rwlock, RW_READER, tag);
1339 }
1340
1341 void
1342 dsl_pool_config_enter_prio(dsl_pool_t *dp, void *tag)
1343 {
1344         ASSERT(!rrw_held(&dp->dp_config_rwlock, RW_READER));
1345         rrw_enter_read_prio(&dp->dp_config_rwlock, tag);
1346 }
1347
1348 void
1349 dsl_pool_config_exit(dsl_pool_t *dp, void *tag)
1350 {
1351         rrw_exit(&dp->dp_config_rwlock, tag);
1352 }
1353
1354 boolean_t
1355 dsl_pool_config_held(dsl_pool_t *dp)
1356 {
1357         return (RRW_LOCK_HELD(&dp->dp_config_rwlock));
1358 }
1359
1360 boolean_t
1361 dsl_pool_config_held_writer(dsl_pool_t *dp)
1362 {
1363         return (RRW_WRITE_HELD(&dp->dp_config_rwlock));
1364 }