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 /*
23 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24 * Copyright (c) 2011, 2017 by Delphix. All rights reserved.
25 * Copyright (c) 2014 Spectra Logic Corporation, All rights reserved.
26 * Copyright 2018 Nexenta Systems, Inc. All rights reserved.
27 * Copyright 2013 Saso Kiselkov. All rights reserved.
28 * Copyright (c) 2014 Integros [integros.com]
29 * Copyright 2016 Toomas Soome <tsoome@me.com>
30 * Copyright 2018 Joyent, Inc.
31 * Copyright (c) 2017 Datto Inc.
32 */
33
34 /*
35 * SPA: Storage Pool Allocator
36 *
37 * This file contains all the routines used when modifying on-disk SPA state.
38 * This includes opening, importing, destroying, exporting a pool, and syncing a
39 * pool.
40 */
41
42 #include <sys/zfs_context.h>
43 #include <sys/fm/fs/zfs.h>
44 #include <sys/spa_impl.h>
45 #include <sys/zio.h>
46 #include <sys/zio_checksum.h>
47 #include <sys/dmu.h>
48 #include <sys/dmu_tx.h>
49 #include <sys/zap.h>
50 #include <sys/zil.h>
51 #include <sys/ddt.h>
52 #include <sys/vdev_impl.h>
53 #include <sys/metaslab.h>
54 #include <sys/metaslab_impl.h>
55 #include <sys/uberblock_impl.h>
56 #include <sys/txg.h>
57 #include <sys/avl.h>
58 #include <sys/dmu_traverse.h>
59 #include <sys/dmu_objset.h>
60 #include <sys/unique.h>
61 #include <sys/dsl_pool.h>
62 #include <sys/dsl_dataset.h>
63 #include <sys/dsl_dir.h>
64 #include <sys/dsl_prop.h>
65 #include <sys/dsl_synctask.h>
66 #include <sys/fs/zfs.h>
67 #include <sys/arc.h>
68 #include <sys/callb.h>
69 #include <sys/systeminfo.h>
70 #include <sys/spa_boot.h>
71 #include <sys/zfs_ioctl.h>
72 #include <sys/dsl_scan.h>
73 #include <sys/zfeature.h>
74 #include <sys/dsl_destroy.h>
75 #include <sys/cos.h>
76 #include <sys/special.h>
77 #include <sys/wbc.h>
78 #include <sys/abd.h>
79
80 #ifdef _KERNEL
81 #include <sys/bootprops.h>
82 #include <sys/callb.h>
83 #include <sys/cpupart.h>
84 #include <sys/pool.h>
85 #include <sys/sysdc.h>
86 #include <sys/zone.h>
87 #endif /* _KERNEL */
88
89 #include "zfs_prop.h"
90 #include "zfs_comutil.h"
91
92 /*
93 * The interval, in seconds, at which failed configuration cache file writes
94 * should be retried.
95 */
96 static int zfs_ccw_retry_interval = 300;
97
98 typedef enum zti_modes {
99 ZTI_MODE_FIXED, /* value is # of threads (min 1) */
100 ZTI_MODE_BATCH, /* cpu-intensive; value is ignored */
101 ZTI_MODE_NULL, /* don't create a taskq */
102 ZTI_NMODES
103 } zti_modes_t;
104
105 #define ZTI_P(n, q) { ZTI_MODE_FIXED, (n), (q) }
106 #define ZTI_BATCH { ZTI_MODE_BATCH, 0, 1 }
107 #define ZTI_NULL { ZTI_MODE_NULL, 0, 0 }
108
109 #define ZTI_N(n) ZTI_P(n, 1)
110 #define ZTI_ONE ZTI_N(1)
111
112 typedef struct zio_taskq_info {
113 zti_modes_t zti_mode;
114 uint_t zti_value;
115 uint_t zti_count;
116 } zio_taskq_info_t;
117
118 static const char *const zio_taskq_types[ZIO_TASKQ_TYPES] = {
119 "issue", "issue_high", "intr", "intr_high"
120 };
121
122 /*
123 * This table defines the taskq settings for each ZFS I/O type. When
124 * initializing a pool, we use this table to create an appropriately sized
125 * taskq. Some operations are low volume and therefore have a small, static
126 * number of threads assigned to their taskqs using the ZTI_N(#) or ZTI_ONE
127 * macros. Other operations process a large amount of data; the ZTI_BATCH
128 * macro causes us to create a taskq oriented for throughput. Some operations
129 * are so high frequency and short-lived that the taskq itself can become a a
130 * point of lock contention. The ZTI_P(#, #) macro indicates that we need an
131 * additional degree of parallelism specified by the number of threads per-
132 * taskq and the number of taskqs; when dispatching an event in this case, the
133 * particular taskq is chosen at random.
134 *
135 * The different taskq priorities are to handle the different contexts (issue
136 * and interrupt) and then to reserve threads for ZIO_PRIORITY_NOW I/Os that
137 * need to be handled with minimum delay.
138 */
139 const zio_taskq_info_t zio_taskqs[ZIO_TYPES][ZIO_TASKQ_TYPES] = {
140 /* ISSUE ISSUE_HIGH INTR INTR_HIGH */
141 { ZTI_ONE, ZTI_NULL, ZTI_ONE, ZTI_NULL }, /* NULL */
142 { ZTI_N(8), ZTI_NULL, ZTI_P(12, 8), ZTI_NULL }, /* READ */
143 { ZTI_BATCH, ZTI_N(5), ZTI_N(8), ZTI_N(5) }, /* WRITE */
144 { ZTI_P(12, 8), ZTI_NULL, ZTI_ONE, ZTI_NULL }, /* FREE */
145 { ZTI_ONE, ZTI_NULL, ZTI_ONE, ZTI_NULL }, /* CLAIM */
146 { ZTI_ONE, ZTI_NULL, ZTI_ONE, ZTI_NULL }, /* IOCTL */
147 };
148
149 static sysevent_t *spa_event_create(spa_t *spa, vdev_t *vd, nvlist_t *hist_nvl,
150 const char *name);
151 static void spa_event_notify_impl(sysevent_t *ev);
152 static void spa_sync_version(void *arg, dmu_tx_t *tx);
153 static void spa_sync_props(void *arg, dmu_tx_t *tx);
154 static void spa_vdev_sync_props(void *arg, dmu_tx_t *tx);
155 static int spa_vdev_prop_set_nosync(vdev_t *, nvlist_t *, boolean_t *);
156 static boolean_t spa_has_active_shared_spare(spa_t *spa);
157 static int spa_load_impl(spa_t *spa, uint64_t, nvlist_t *config,
158 spa_load_state_t state, spa_import_type_t type, boolean_t mosconfig,
159 char **ereport);
160 static void spa_vdev_resilver_done(spa_t *spa);
161 static void spa_auto_trim(spa_t *spa, uint64_t txg);
162 static void spa_vdev_man_trim_done(spa_t *spa);
163 static void spa_vdev_auto_trim_done(spa_t *spa);
164 static uint64_t spa_min_trim_rate(spa_t *spa);
165
166 uint_t zio_taskq_batch_pct = 75; /* 1 thread per cpu in pset */
167 id_t zio_taskq_psrset_bind = PS_NONE;
168 boolean_t zio_taskq_sysdc = B_TRUE; /* use SDC scheduling class */
169 uint_t zio_taskq_basedc = 80; /* base duty cycle */
170
171 boolean_t spa_create_process = B_TRUE; /* no process ==> no sysdc */
172 extern int zfs_sync_pass_deferred_free;
173
174 /*
175 * ==========================================================================
176 * SPA properties routines
177 * ==========================================================================
178 */
179
180 /*
181 * Add a (source=src, propname=propval) list to an nvlist.
182 */
183 static void
184 spa_prop_add_list(nvlist_t *nvl, zpool_prop_t prop, char *strval,
185 uint64_t intval, zprop_source_t src)
186 {
187 const char *propname = zpool_prop_to_name(prop);
188 nvlist_t *propval;
189
190 VERIFY(nvlist_alloc(&propval, NV_UNIQUE_NAME, KM_SLEEP) == 0);
191 VERIFY(nvlist_add_uint64(propval, ZPROP_SOURCE, src) == 0);
192
193 if (strval != NULL)
194 VERIFY(nvlist_add_string(propval, ZPROP_VALUE, strval) == 0);
195 else
196 VERIFY(nvlist_add_uint64(propval, ZPROP_VALUE, intval) == 0);
197
198 VERIFY(nvlist_add_nvlist(nvl, propname, propval) == 0);
199 nvlist_free(propval);
200 }
201
202 /*
203 * Get property values from the spa configuration.
204 */
205 static void
206 spa_prop_get_config(spa_t *spa, nvlist_t **nvp)
207 {
208 vdev_t *rvd = spa->spa_root_vdev;
209 dsl_pool_t *pool = spa->spa_dsl_pool;
210 spa_meta_placement_t *mp = &spa->spa_meta_policy;
211 uint64_t size, alloc, cap, version;
212 zprop_source_t src = ZPROP_SRC_NONE;
213 spa_config_dirent_t *dp;
214 metaslab_class_t *mc = spa_normal_class(spa);
215
216 ASSERT(MUTEX_HELD(&spa->spa_props_lock));
217
218 if (rvd != NULL) {
219 alloc = metaslab_class_get_alloc(spa_normal_class(spa));
220 size = metaslab_class_get_space(spa_normal_class(spa));
221 spa_prop_add_list(*nvp, ZPOOL_PROP_NAME, spa_name(spa), 0, src);
222 spa_prop_add_list(*nvp, ZPOOL_PROP_SIZE, NULL, size, src);
223 spa_prop_add_list(*nvp, ZPOOL_PROP_ALLOCATED, NULL, alloc, src);
224 spa_prop_add_list(*nvp, ZPOOL_PROP_FREE, NULL,
225 size - alloc, src);
226 spa_prop_add_list(*nvp, ZPOOL_PROP_ENABLESPECIAL, NULL,
227 (uint64_t)spa->spa_usesc, src);
228 spa_prop_add_list(*nvp, ZPOOL_PROP_MINWATERMARK, NULL,
229 spa->spa_minwat, src);
230 spa_prop_add_list(*nvp, ZPOOL_PROP_HIWATERMARK, NULL,
231 spa->spa_hiwat, src);
232 spa_prop_add_list(*nvp, ZPOOL_PROP_LOWATERMARK, NULL,
233 spa->spa_lowat, src);
234 spa_prop_add_list(*nvp, ZPOOL_PROP_DEDUPMETA_DITTO, NULL,
235 spa->spa_ddt_meta_copies, src);
236
237 spa_prop_add_list(*nvp, ZPOOL_PROP_META_PLACEMENT, NULL,
238 mp->spa_enable_meta_placement_selection, src);
239 spa_prop_add_list(*nvp, ZPOOL_PROP_SYNC_TO_SPECIAL, NULL,
240 mp->spa_sync_to_special, src);
241 spa_prop_add_list(*nvp, ZPOOL_PROP_DDT_META_TO_METADEV, NULL,
242 mp->spa_ddt_meta_to_special, src);
243 spa_prop_add_list(*nvp, ZPOOL_PROP_ZFS_META_TO_METADEV,
244 NULL, mp->spa_zfs_meta_to_special, src);
245 spa_prop_add_list(*nvp, ZPOOL_PROP_SMALL_DATA_TO_METADEV, NULL,
246 mp->spa_small_data_to_special, src);
247
248 spa_prop_add_list(*nvp, ZPOOL_PROP_FRAGMENTATION, NULL,
249 metaslab_class_fragmentation(mc), src);
250 spa_prop_add_list(*nvp, ZPOOL_PROP_EXPANDSZ, NULL,
251 metaslab_class_expandable_space(mc), src);
252 spa_prop_add_list(*nvp, ZPOOL_PROP_READONLY, NULL,
253 (spa_mode(spa) == FREAD), src);
254
255 spa_prop_add_list(*nvp, ZPOOL_PROP_DDT_DESEGREGATION, NULL,
256 (spa->spa_ddt_class_min == spa->spa_ddt_class_max), src);
257
258 cap = (size == 0) ? 0 : (alloc * 100 / size);
259 spa_prop_add_list(*nvp, ZPOOL_PROP_CAPACITY, NULL, cap, src);
260
261 spa_prop_add_list(*nvp, ZPOOL_PROP_DEDUP_BEST_EFFORT, NULL,
262 spa->spa_dedup_best_effort, src);
263
264 spa_prop_add_list(*nvp, ZPOOL_PROP_DEDUP_LO_BEST_EFFORT, NULL,
265 spa->spa_dedup_lo_best_effort, src);
266
267 spa_prop_add_list(*nvp, ZPOOL_PROP_DEDUP_HI_BEST_EFFORT, NULL,
268 spa->spa_dedup_hi_best_effort, src);
269
270 spa_prop_add_list(*nvp, ZPOOL_PROP_DEDUPRATIO, NULL,
271 ddt_get_pool_dedup_ratio(spa), src);
272
273 spa_prop_add_list(*nvp, ZPOOL_PROP_DDTCAPPED, NULL,
274 spa->spa_ddt_capped, src);
275
276 spa_prop_add_list(*nvp, ZPOOL_PROP_HEALTH, NULL,
277 rvd->vdev_state, src);
278
279 version = spa_version(spa);
280 if (version == zpool_prop_default_numeric(ZPOOL_PROP_VERSION))
281 src = ZPROP_SRC_DEFAULT;
282 else
283 src = ZPROP_SRC_LOCAL;
284 spa_prop_add_list(*nvp, ZPOOL_PROP_VERSION, NULL, version, src);
285 }
286
287 if (pool != NULL) {
288 /*
289 * The $FREE directory was introduced in SPA_VERSION_DEADLISTS,
290 * when opening pools before this version freedir will be NULL.
291 */
292 if (pool->dp_free_dir != NULL) {
293 spa_prop_add_list(*nvp, ZPOOL_PROP_FREEING, NULL,
294 dsl_dir_phys(pool->dp_free_dir)->dd_used_bytes +
295 pool->dp_long_freeing_total,
296 src);
297 } else {
298 spa_prop_add_list(*nvp, ZPOOL_PROP_FREEING,
299 NULL, pool->dp_long_freeing_total, src);
300 }
301
302 if (pool->dp_leak_dir != NULL) {
303 spa_prop_add_list(*nvp, ZPOOL_PROP_LEAKED, NULL,
304 dsl_dir_phys(pool->dp_leak_dir)->dd_used_bytes,
305 src);
306 } else {
307 spa_prop_add_list(*nvp, ZPOOL_PROP_LEAKED,
308 NULL, 0, src);
309 }
310 }
311
312 spa_prop_add_list(*nvp, ZPOOL_PROP_GUID, NULL, spa_guid(spa), src);
313
314 if (spa->spa_comment != NULL) {
315 spa_prop_add_list(*nvp, ZPOOL_PROP_COMMENT, spa->spa_comment,
316 0, ZPROP_SRC_LOCAL);
317 }
318
319 if (spa->spa_root != NULL)
320 spa_prop_add_list(*nvp, ZPOOL_PROP_ALTROOT, spa->spa_root,
321 0, ZPROP_SRC_LOCAL);
322
323 if (spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_BLOCKS)) {
324 spa_prop_add_list(*nvp, ZPOOL_PROP_MAXBLOCKSIZE, NULL,
325 MIN(zfs_max_recordsize, SPA_MAXBLOCKSIZE), ZPROP_SRC_NONE);
326 } else {
327 spa_prop_add_list(*nvp, ZPOOL_PROP_MAXBLOCKSIZE, NULL,
328 SPA_OLD_MAXBLOCKSIZE, ZPROP_SRC_NONE);
329 }
330
331 if ((dp = list_head(&spa->spa_config_list)) != NULL) {
332 if (dp->scd_path == NULL) {
333 spa_prop_add_list(*nvp, ZPOOL_PROP_CACHEFILE,
334 "none", 0, ZPROP_SRC_LOCAL);
335 } else if (strcmp(dp->scd_path, spa_config_path) != 0) {
336 spa_prop_add_list(*nvp, ZPOOL_PROP_CACHEFILE,
337 dp->scd_path, 0, ZPROP_SRC_LOCAL);
338 }
339 }
340 }
341
342 /*
343 * Get zpool property values.
344 */
345 int
346 spa_prop_get(spa_t *spa, nvlist_t **nvp)
347 {
348 objset_t *mos = spa->spa_meta_objset;
349 zap_cursor_t zc;
350 zap_attribute_t za;
351 int err;
352
353 VERIFY(nvlist_alloc(nvp, NV_UNIQUE_NAME, KM_SLEEP) == 0);
354
355 mutex_enter(&spa->spa_props_lock);
356
357 /*
358 * Get properties from the spa config.
359 */
360 spa_prop_get_config(spa, nvp);
361
362 /* If no pool property object, no more prop to get. */
363 if (mos == NULL || spa->spa_pool_props_object == 0) {
364 mutex_exit(&spa->spa_props_lock);
365 return (0);
366 }
367
368 /*
369 * Get properties from the MOS pool property object.
370 */
371 for (zap_cursor_init(&zc, mos, spa->spa_pool_props_object);
372 (err = zap_cursor_retrieve(&zc, &za)) == 0;
373 zap_cursor_advance(&zc)) {
374 uint64_t intval = 0;
375 char *strval = NULL;
376 zprop_source_t src = ZPROP_SRC_DEFAULT;
377 zpool_prop_t prop;
378
379 if ((prop = zpool_name_to_prop(za.za_name)) == ZPROP_INVAL)
380 continue;
381
382 switch (za.za_integer_length) {
383 case 8:
384 /* integer property */
385 if (za.za_first_integer !=
386 zpool_prop_default_numeric(prop))
387 src = ZPROP_SRC_LOCAL;
388
389 if (prop == ZPOOL_PROP_BOOTFS) {
390 dsl_pool_t *dp;
391 dsl_dataset_t *ds = NULL;
392
393 dp = spa_get_dsl(spa);
394 dsl_pool_config_enter(dp, FTAG);
395 if (err = dsl_dataset_hold_obj(dp,
396 za.za_first_integer, FTAG, &ds)) {
397 dsl_pool_config_exit(dp, FTAG);
398 break;
399 }
400
401 strval = kmem_alloc(ZFS_MAX_DATASET_NAME_LEN,
402 KM_SLEEP);
403 dsl_dataset_name(ds, strval);
404 dsl_dataset_rele(ds, FTAG);
405 dsl_pool_config_exit(dp, FTAG);
406 } else {
407 strval = NULL;
408 intval = za.za_first_integer;
409 }
410
411 spa_prop_add_list(*nvp, prop, strval, intval, src);
412
413 if (strval != NULL)
414 kmem_free(strval, ZFS_MAX_DATASET_NAME_LEN);
415
416 break;
417
418 case 1:
419 /* string property */
420 strval = kmem_alloc(za.za_num_integers, KM_SLEEP);
421 err = zap_lookup(mos, spa->spa_pool_props_object,
422 za.za_name, 1, za.za_num_integers, strval);
423 if (err) {
424 kmem_free(strval, za.za_num_integers);
425 break;
426 }
427 spa_prop_add_list(*nvp, prop, strval, 0, src);
428 kmem_free(strval, za.za_num_integers);
429 break;
430
431 default:
432 break;
433 }
434 }
435 zap_cursor_fini(&zc);
436 mutex_exit(&spa->spa_props_lock);
437 out:
438 if (err && err != ENOENT) {
439 nvlist_free(*nvp);
440 *nvp = NULL;
441 return (err);
442 }
443
444 return (0);
445 }
446
447 /*
448 * Validate the given pool properties nvlist and modify the list
449 * for the property values to be set.
450 */
451 static int
452 spa_prop_validate(spa_t *spa, nvlist_t *props)
453 {
454 nvpair_t *elem;
455 int error = 0, reset_bootfs = 0;
456 uint64_t objnum = 0;
457 boolean_t has_feature = B_FALSE;
458 uint64_t lowat = spa->spa_lowat, hiwat = spa->spa_hiwat,
459 minwat = spa->spa_minwat;
460
461 elem = NULL;
462 while ((elem = nvlist_next_nvpair(props, elem)) != NULL) {
463 uint64_t intval;
464 char *strval, *slash, *check, *fname;
465 const char *propname = nvpair_name(elem);
466 zpool_prop_t prop = zpool_name_to_prop(propname);
467 spa_feature_t feature;
468
469 switch (prop) {
470 case ZPROP_INVAL:
471 if (!zpool_prop_feature(propname)) {
472 error = SET_ERROR(EINVAL);
473 break;
474 }
475
476 /*
477 * Sanitize the input.
478 */
479 if (nvpair_type(elem) != DATA_TYPE_UINT64) {
480 error = SET_ERROR(EINVAL);
481 break;
482 }
483
484 if (nvpair_value_uint64(elem, &intval) != 0) {
485 error = SET_ERROR(EINVAL);
486 break;
487 }
488
489 if (intval != 0) {
490 error = SET_ERROR(EINVAL);
491 break;
492 }
493
494 fname = strchr(propname, '@') + 1;
495 if (zfeature_lookup_name(fname, &feature) != 0) {
496 error = SET_ERROR(EINVAL);
497 break;
498 }
499
500 if (feature == SPA_FEATURE_WBC &&
501 !spa_has_special(spa)) {
502 error = SET_ERROR(ENOTSUP);
503 break;
504 }
505
506 has_feature = B_TRUE;
507 break;
508
509 case ZPOOL_PROP_VERSION:
510 error = nvpair_value_uint64(elem, &intval);
511 if (!error &&
512 (intval < spa_version(spa) ||
513 intval > SPA_VERSION_BEFORE_FEATURES ||
514 has_feature))
515 error = SET_ERROR(EINVAL);
516 break;
517
518 case ZPOOL_PROP_DELEGATION:
519 case ZPOOL_PROP_AUTOREPLACE:
520 case ZPOOL_PROP_LISTSNAPS:
521 case ZPOOL_PROP_AUTOEXPAND:
522 case ZPOOL_PROP_DEDUP_BEST_EFFORT:
523 case ZPOOL_PROP_DDT_DESEGREGATION:
524 case ZPOOL_PROP_META_PLACEMENT:
525 case ZPOOL_PROP_FORCETRIM:
526 case ZPOOL_PROP_AUTOTRIM:
527 error = nvpair_value_uint64(elem, &intval);
528 if (!error && intval > 1)
529 error = SET_ERROR(EINVAL);
530 break;
531
532 case ZPOOL_PROP_DDT_META_TO_METADEV:
533 case ZPOOL_PROP_ZFS_META_TO_METADEV:
534 error = nvpair_value_uint64(elem, &intval);
535 if (!error && intval > META_PLACEMENT_DUAL)
536 error = SET_ERROR(EINVAL);
537 break;
538
539 case ZPOOL_PROP_SYNC_TO_SPECIAL:
540 error = nvpair_value_uint64(elem, &intval);
541 if (!error && intval > SYNC_TO_SPECIAL_ALWAYS)
542 error = SET_ERROR(EINVAL);
543 break;
544
545 case ZPOOL_PROP_SMALL_DATA_TO_METADEV:
546 error = nvpair_value_uint64(elem, &intval);
547 if (!error && intval > SPA_MAXBLOCKSIZE)
548 error = SET_ERROR(EINVAL);
549 break;
550
551 case ZPOOL_PROP_BOOTFS:
552 /*
553 * If the pool version is less than SPA_VERSION_BOOTFS,
554 * or the pool is still being created (version == 0),
555 * the bootfs property cannot be set.
556 */
557 if (spa_version(spa) < SPA_VERSION_BOOTFS) {
558 error = SET_ERROR(ENOTSUP);
559 break;
560 }
561
562 /*
563 * Make sure the vdev config is bootable
564 */
565 if (!vdev_is_bootable(spa->spa_root_vdev)) {
566 error = SET_ERROR(ENOTSUP);
567 break;
568 }
569
570 reset_bootfs = 1;
571
572 error = nvpair_value_string(elem, &strval);
573
574 if (!error) {
575 objset_t *os;
576 uint64_t propval;
577
578 if (strval == NULL || strval[0] == '\0') {
579 objnum = zpool_prop_default_numeric(
580 ZPOOL_PROP_BOOTFS);
581 break;
582 }
583
584 if (error = dmu_objset_hold(strval, FTAG, &os))
585 break;
586
587 /*
588 * Must be ZPL, and its property settings
589 * must be supported by GRUB (compression
590 * is not gzip, and large blocks are not used).
591 */
592
593 if (dmu_objset_type(os) != DMU_OST_ZFS) {
594 error = SET_ERROR(ENOTSUP);
595 } else if ((error =
596 dsl_prop_get_int_ds(dmu_objset_ds(os),
597 zfs_prop_to_name(ZFS_PROP_COMPRESSION),
598 &propval)) == 0 &&
599 !BOOTFS_COMPRESS_VALID(propval)) {
600 error = SET_ERROR(ENOTSUP);
601 } else {
602 objnum = dmu_objset_id(os);
603 }
604 dmu_objset_rele(os, FTAG);
605 }
606 break;
607
608 case ZPOOL_PROP_DEDUP_LO_BEST_EFFORT:
609 error = nvpair_value_uint64(elem, &intval);
610 if ((intval < 0) || (intval > 100) ||
611 (intval >= spa->spa_dedup_hi_best_effort))
612 error = SET_ERROR(EINVAL);
613 break;
614
615 case ZPOOL_PROP_DEDUP_HI_BEST_EFFORT:
616 error = nvpair_value_uint64(elem, &intval);
617 if ((intval < 0) || (intval > 100) ||
618 (intval <= spa->spa_dedup_lo_best_effort))
619 error = SET_ERROR(EINVAL);
620 break;
621
622 case ZPOOL_PROP_FAILUREMODE:
623 error = nvpair_value_uint64(elem, &intval);
624 if (!error && (intval < ZIO_FAILURE_MODE_WAIT ||
625 intval > ZIO_FAILURE_MODE_PANIC))
626 error = SET_ERROR(EINVAL);
627
628 /*
629 * This is a special case which only occurs when
630 * the pool has completely failed. This allows
631 * the user to change the in-core failmode property
632 * without syncing it out to disk (I/Os might
633 * currently be blocked). We do this by returning
634 * EIO to the caller (spa_prop_set) to trick it
635 * into thinking we encountered a property validation
636 * error.
637 */
638 if (!error && spa_suspended(spa)) {
639 spa->spa_failmode = intval;
640 error = SET_ERROR(EIO);
641 }
642 break;
643
644 case ZPOOL_PROP_CACHEFILE:
645 if ((error = nvpair_value_string(elem, &strval)) != 0)
646 break;
647
648 if (strval[0] == '\0')
649 break;
650
651 if (strcmp(strval, "none") == 0)
652 break;
653
654 if (strval[0] != '/') {
655 error = SET_ERROR(EINVAL);
656 break;
657 }
658
659 slash = strrchr(strval, '/');
660 ASSERT(slash != NULL);
661
662 if (slash[1] == '\0' || strcmp(slash, "/.") == 0 ||
663 strcmp(slash, "/..") == 0)
664 error = SET_ERROR(EINVAL);
665 break;
666
667 case ZPOOL_PROP_COMMENT:
668 if ((error = nvpair_value_string(elem, &strval)) != 0)
669 break;
670 for (check = strval; *check != '\0'; check++) {
671 /*
672 * The kernel doesn't have an easy isprint()
673 * check. For this kernel check, we merely
674 * check ASCII apart from DEL. Fix this if
675 * there is an easy-to-use kernel isprint().
676 */
677 if (*check >= 0x7f) {
678 error = SET_ERROR(EINVAL);
679 break;
680 }
681 }
682 if (strlen(strval) > ZPROP_MAX_COMMENT)
683 error = SET_ERROR(E2BIG);
684 break;
685
686 case ZPOOL_PROP_DEDUPDITTO:
687 if (spa_version(spa) < SPA_VERSION_DEDUP)
688 error = SET_ERROR(ENOTSUP);
689 else
690 error = nvpair_value_uint64(elem, &intval);
691 if (error == 0 &&
692 intval != 0 && intval < ZIO_DEDUPDITTO_MIN)
693 error = SET_ERROR(EINVAL);
694 break;
695
696 case ZPOOL_PROP_MINWATERMARK:
697 error = nvpair_value_uint64(elem, &intval);
698 if (!error && (intval > 100))
699 error = SET_ERROR(EINVAL);
700 minwat = intval;
701 break;
702 case ZPOOL_PROP_LOWATERMARK:
703 error = nvpair_value_uint64(elem, &intval);
704 if (!error && (intval > 100))
705 error = SET_ERROR(EINVAL);
706 lowat = intval;
707 break;
708 case ZPOOL_PROP_HIWATERMARK:
709 error = nvpair_value_uint64(elem, &intval);
710 if (!error && (intval > 100))
711 error = SET_ERROR(EINVAL);
712 hiwat = intval;
713 break;
714 case ZPOOL_PROP_DEDUPMETA_DITTO:
715 error = nvpair_value_uint64(elem, &intval);
716 if (!error && (intval > SPA_DVAS_PER_BP))
717 error = SET_ERROR(EINVAL);
718 break;
719 case ZPOOL_PROP_SCRUB_PRIO:
720 case ZPOOL_PROP_RESILVER_PRIO:
721 error = nvpair_value_uint64(elem, &intval);
722 if (error || intval > 100)
723 error = SET_ERROR(EINVAL);
724 break;
725 }
726
727 if (error)
728 break;
729 }
730
731 /* check if low watermark is less than high watermark */
732 if (lowat != 0 && lowat >= hiwat)
733 error = SET_ERROR(EINVAL);
734
735 /* check if min watermark is less than low watermark */
736 if (minwat != 0 && minwat >= lowat)
737 error = SET_ERROR(EINVAL);
738
739 if (!error && reset_bootfs) {
740 error = nvlist_remove(props,
741 zpool_prop_to_name(ZPOOL_PROP_BOOTFS), DATA_TYPE_STRING);
742
743 if (!error) {
744 error = nvlist_add_uint64(props,
745 zpool_prop_to_name(ZPOOL_PROP_BOOTFS), objnum);
746 }
747 }
748
749 return (error);
750 }
751
752 void
753 spa_configfile_set(spa_t *spa, nvlist_t *nvp, boolean_t need_sync)
754 {
755 char *cachefile;
756 spa_config_dirent_t *dp;
757
758 if (nvlist_lookup_string(nvp, zpool_prop_to_name(ZPOOL_PROP_CACHEFILE),
759 &cachefile) != 0)
760 return;
761
762 dp = kmem_alloc(sizeof (spa_config_dirent_t),
763 KM_SLEEP);
764
765 if (cachefile[0] == '\0')
766 dp->scd_path = spa_strdup(spa_config_path);
767 else if (strcmp(cachefile, "none") == 0)
768 dp->scd_path = NULL;
769 else
770 dp->scd_path = spa_strdup(cachefile);
771
772 list_insert_head(&spa->spa_config_list, dp);
773 if (need_sync)
774 spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
775 }
776
777 int
778 spa_prop_set(spa_t *spa, nvlist_t *nvp)
779 {
780 int error;
781 nvpair_t *elem = NULL;
782 boolean_t need_sync = B_FALSE;
783
784 if ((error = spa_prop_validate(spa, nvp)) != 0)
785 return (error);
786
787 while ((elem = nvlist_next_nvpair(nvp, elem)) != NULL) {
788 zpool_prop_t prop = zpool_name_to_prop(nvpair_name(elem));
789
790 if (prop == ZPOOL_PROP_CACHEFILE ||
791 prop == ZPOOL_PROP_ALTROOT ||
792 prop == ZPOOL_PROP_READONLY)
793 continue;
794
795 if (prop == ZPOOL_PROP_VERSION || prop == ZPROP_INVAL) {
796 uint64_t ver;
797
798 if (prop == ZPOOL_PROP_VERSION) {
799 VERIFY(nvpair_value_uint64(elem, &ver) == 0);
800 } else {
801 ASSERT(zpool_prop_feature(nvpair_name(elem)));
802 ver = SPA_VERSION_FEATURES;
803 need_sync = B_TRUE;
804 }
805
806 /* Save time if the version is already set. */
807 if (ver == spa_version(spa))
808 continue;
809
810 /*
811 * In addition to the pool directory object, we might
812 * create the pool properties object, the features for
813 * read object, the features for write object, or the
814 * feature descriptions object.
815 */
816 error = dsl_sync_task(spa->spa_name, NULL,
817 spa_sync_version, &ver,
818 6, ZFS_SPACE_CHECK_RESERVED);
819 if (error)
820 return (error);
821 continue;
822 }
823
824 need_sync = B_TRUE;
825 break;
826 }
827
828 if (need_sync) {
829 return (dsl_sync_task(spa->spa_name, NULL, spa_sync_props,
830 nvp, 6, ZFS_SPACE_CHECK_RESERVED));
831 }
832
833 return (0);
834 }
835
836 /*
837 * If the bootfs property value is dsobj, clear it.
838 */
839 void
840 spa_prop_clear_bootfs(spa_t *spa, uint64_t dsobj, dmu_tx_t *tx)
841 {
842 if (spa->spa_bootfs == dsobj && spa->spa_pool_props_object != 0) {
843 VERIFY(zap_remove(spa->spa_meta_objset,
844 spa->spa_pool_props_object,
845 zpool_prop_to_name(ZPOOL_PROP_BOOTFS), tx) == 0);
846 spa->spa_bootfs = 0;
847 }
848 }
849
850 /*ARGSUSED*/
851 static int
852 spa_change_guid_check(void *arg, dmu_tx_t *tx)
853 {
854 uint64_t *newguid = arg;
855 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
856 vdev_t *rvd = spa->spa_root_vdev;
857 uint64_t vdev_state;
858
859 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
860 vdev_state = rvd->vdev_state;
861 spa_config_exit(spa, SCL_STATE, FTAG);
862
863 if (vdev_state != VDEV_STATE_HEALTHY)
864 return (SET_ERROR(ENXIO));
865
866 ASSERT3U(spa_guid(spa), !=, *newguid);
867
868 return (0);
869 }
870
871 static void
872 spa_change_guid_sync(void *arg, dmu_tx_t *tx)
873 {
874 uint64_t *newguid = arg;
875 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
876 uint64_t oldguid;
877 vdev_t *rvd = spa->spa_root_vdev;
878
879 oldguid = spa_guid(spa);
880
881 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
882 rvd->vdev_guid = *newguid;
883 rvd->vdev_guid_sum += (*newguid - oldguid);
884 vdev_config_dirty(rvd);
885 spa_config_exit(spa, SCL_STATE, FTAG);
886
887 spa_history_log_internal(spa, "guid change", tx, "old=%llu new=%llu",
888 oldguid, *newguid);
889 }
890
891 /*
892 * Change the GUID for the pool. This is done so that we can later
893 * re-import a pool built from a clone of our own vdevs. We will modify
894 * the root vdev's guid, our own pool guid, and then mark all of our
895 * vdevs dirty. Note that we must make sure that all our vdevs are
896 * online when we do this, or else any vdevs that weren't present
897 * would be orphaned from our pool. We are also going to issue a
898 * sysevent to update any watchers.
899 */
900 int
901 spa_change_guid(spa_t *spa)
902 {
903 int error;
904 uint64_t guid;
905
906 mutex_enter(&spa->spa_vdev_top_lock);
907 mutex_enter(&spa_namespace_lock);
908 guid = spa_generate_guid(NULL);
909
910 error = dsl_sync_task(spa->spa_name, spa_change_guid_check,
911 spa_change_guid_sync, &guid, 5, ZFS_SPACE_CHECK_RESERVED);
912
913 if (error == 0) {
914 spa_config_sync(spa, B_FALSE, B_TRUE);
915 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_REGUID);
916 }
917
918 mutex_exit(&spa_namespace_lock);
919 mutex_exit(&spa->spa_vdev_top_lock);
920
921 return (error);
922 }
923
924 /*
925 * ==========================================================================
926 * SPA state manipulation (open/create/destroy/import/export)
927 * ==========================================================================
928 */
929
930 static int
931 spa_error_entry_compare(const void *a, const void *b)
932 {
933 spa_error_entry_t *sa = (spa_error_entry_t *)a;
934 spa_error_entry_t *sb = (spa_error_entry_t *)b;
935 int ret;
936
937 ret = bcmp(&sa->se_bookmark, &sb->se_bookmark,
938 sizeof (zbookmark_phys_t));
939
940 if (ret < 0)
941 return (-1);
942 else if (ret > 0)
943 return (1);
944 else
945 return (0);
946 }
947
948 /*
949 * Utility function which retrieves copies of the current logs and
950 * re-initializes them in the process.
951 */
952 void
953 spa_get_errlists(spa_t *spa, avl_tree_t *last, avl_tree_t *scrub)
954 {
955 ASSERT(MUTEX_HELD(&spa->spa_errlist_lock));
956
957 bcopy(&spa->spa_errlist_last, last, sizeof (avl_tree_t));
958 bcopy(&spa->spa_errlist_scrub, scrub, sizeof (avl_tree_t));
959
960 avl_create(&spa->spa_errlist_scrub,
961 spa_error_entry_compare, sizeof (spa_error_entry_t),
962 offsetof(spa_error_entry_t, se_avl));
963 avl_create(&spa->spa_errlist_last,
964 spa_error_entry_compare, sizeof (spa_error_entry_t),
965 offsetof(spa_error_entry_t, se_avl));
966 }
967
968 static void
969 spa_taskqs_init(spa_t *spa, zio_type_t t, zio_taskq_type_t q)
970 {
971 const zio_taskq_info_t *ztip = &zio_taskqs[t][q];
972 enum zti_modes mode = ztip->zti_mode;
973 uint_t value = ztip->zti_value;
974 uint_t count = ztip->zti_count;
975 spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
976 char name[32];
977 uint_t flags = 0;
978 boolean_t batch = B_FALSE;
979
980 if (mode == ZTI_MODE_NULL) {
981 tqs->stqs_count = 0;
982 tqs->stqs_taskq = NULL;
983 return;
984 }
985
986 ASSERT3U(count, >, 0);
987
988 tqs->stqs_count = count;
989 tqs->stqs_taskq = kmem_alloc(count * sizeof (taskq_t *), KM_SLEEP);
990
991 switch (mode) {
992 case ZTI_MODE_FIXED:
993 ASSERT3U(value, >=, 1);
994 value = MAX(value, 1);
995 break;
996
997 case ZTI_MODE_BATCH:
998 batch = B_TRUE;
999 flags |= TASKQ_THREADS_CPU_PCT;
1000 value = zio_taskq_batch_pct;
1001 break;
1002
1003 default:
1004 panic("unrecognized mode for %s_%s taskq (%u:%u) in "
1005 "spa_activate()",
1006 zio_type_name[t], zio_taskq_types[q], mode, value);
1007 break;
1008 }
1009
1010 for (uint_t i = 0; i < count; i++) {
1011 taskq_t *tq;
1012
1013 if (count > 1) {
1014 (void) snprintf(name, sizeof (name), "%s_%s_%u",
1015 zio_type_name[t], zio_taskq_types[q], i);
1016 } else {
1017 (void) snprintf(name, sizeof (name), "%s_%s",
1018 zio_type_name[t], zio_taskq_types[q]);
1019 }
1020
1021 if (zio_taskq_sysdc && spa->spa_proc != &p0) {
1022 if (batch)
1023 flags |= TASKQ_DC_BATCH;
1024
1025 tq = taskq_create_sysdc(name, value, 50, INT_MAX,
1026 spa->spa_proc, zio_taskq_basedc, flags);
1027 } else {
1028 pri_t pri = maxclsyspri;
1029 /*
1030 * The write issue taskq can be extremely CPU
1031 * intensive. Run it at slightly lower priority
1032 * than the other taskqs.
1033 */
1034 if (t == ZIO_TYPE_WRITE && q == ZIO_TASKQ_ISSUE)
1035 pri--;
1036
1037 tq = taskq_create_proc(name, value, pri, 50,
1038 INT_MAX, spa->spa_proc, flags);
1039 }
1040
1041 tqs->stqs_taskq[i] = tq;
1042 }
1043 }
1044
1045 static void
1046 spa_taskqs_fini(spa_t *spa, zio_type_t t, zio_taskq_type_t q)
1047 {
1048 spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
1049
1050 if (tqs->stqs_taskq == NULL) {
1051 ASSERT0(tqs->stqs_count);
1052 return;
1053 }
1054
1055 for (uint_t i = 0; i < tqs->stqs_count; i++) {
1056 ASSERT3P(tqs->stqs_taskq[i], !=, NULL);
1057 taskq_destroy(tqs->stqs_taskq[i]);
1058 }
1059
1060 kmem_free(tqs->stqs_taskq, tqs->stqs_count * sizeof (taskq_t *));
1061 tqs->stqs_taskq = NULL;
1062 }
1063
1064 /*
1065 * Dispatch a task to the appropriate taskq for the ZFS I/O type and priority.
1066 * Note that a type may have multiple discrete taskqs to avoid lock contention
1067 * on the taskq itself. In that case we choose which taskq at random by using
1068 * the low bits of gethrtime().
1069 */
1070 void
1071 spa_taskq_dispatch_ent(spa_t *spa, zio_type_t t, zio_taskq_type_t q,
1072 task_func_t *func, void *arg, uint_t flags, taskq_ent_t *ent)
1073 {
1074 spa_taskqs_t *tqs = &spa->spa_zio_taskq[t][q];
1075 taskq_t *tq;
1076
1077 ASSERT3P(tqs->stqs_taskq, !=, NULL);
1078 ASSERT3U(tqs->stqs_count, !=, 0);
1079
1080 if (tqs->stqs_count == 1) {
1081 tq = tqs->stqs_taskq[0];
1082 } else {
1083 tq = tqs->stqs_taskq[gethrtime() % tqs->stqs_count];
1084 }
1085
1086 taskq_dispatch_ent(tq, func, arg, flags, ent);
1087 }
1088
1089 static void
1090 spa_create_zio_taskqs(spa_t *spa)
1091 {
1092 for (int t = 0; t < ZIO_TYPES; t++) {
1093 for (int q = 0; q < ZIO_TASKQ_TYPES; q++) {
1094 spa_taskqs_init(spa, t, q);
1095 }
1096 }
1097 }
1098
1099 #ifdef _KERNEL
1100 static void
1101 spa_thread(void *arg)
1102 {
1103 callb_cpr_t cprinfo;
1104
1105 spa_t *spa = arg;
1106 user_t *pu = PTOU(curproc);
1107
1108 CALLB_CPR_INIT(&cprinfo, &spa->spa_proc_lock, callb_generic_cpr,
1109 spa->spa_name);
1110
1111 ASSERT(curproc != &p0);
1112 (void) snprintf(pu->u_psargs, sizeof (pu->u_psargs),
1113 "zpool-%s", spa->spa_name);
1114 (void) strlcpy(pu->u_comm, pu->u_psargs, sizeof (pu->u_comm));
1115
1116 /* bind this thread to the requested psrset */
1117 if (zio_taskq_psrset_bind != PS_NONE) {
1118 pool_lock();
1119 mutex_enter(&cpu_lock);
1120 mutex_enter(&pidlock);
1121 mutex_enter(&curproc->p_lock);
1122
1123 if (cpupart_bind_thread(curthread, zio_taskq_psrset_bind,
1124 0, NULL, NULL) == 0) {
1125 curthread->t_bind_pset = zio_taskq_psrset_bind;
1126 } else {
1127 cmn_err(CE_WARN,
1128 "Couldn't bind process for zfs pool \"%s\" to "
1129 "pset %d\n", spa->spa_name, zio_taskq_psrset_bind);
1130 }
1131
1132 mutex_exit(&curproc->p_lock);
1133 mutex_exit(&pidlock);
1134 mutex_exit(&cpu_lock);
1135 pool_unlock();
1136 }
1137
1138 if (zio_taskq_sysdc) {
1139 sysdc_thread_enter(curthread, 100, 0);
1140 }
1141
1142 spa->spa_proc = curproc;
1143 spa->spa_did = curthread->t_did;
1144
1145 spa_create_zio_taskqs(spa);
1146
1147 mutex_enter(&spa->spa_proc_lock);
1148 ASSERT(spa->spa_proc_state == SPA_PROC_CREATED);
1149
1150 spa->spa_proc_state = SPA_PROC_ACTIVE;
1151 cv_broadcast(&spa->spa_proc_cv);
1152
1153 CALLB_CPR_SAFE_BEGIN(&cprinfo);
1154 while (spa->spa_proc_state == SPA_PROC_ACTIVE)
1155 cv_wait(&spa->spa_proc_cv, &spa->spa_proc_lock);
1156 CALLB_CPR_SAFE_END(&cprinfo, &spa->spa_proc_lock);
1157
1158 ASSERT(spa->spa_proc_state == SPA_PROC_DEACTIVATE);
1159 spa->spa_proc_state = SPA_PROC_GONE;
1160 spa->spa_proc = &p0;
1161 cv_broadcast(&spa->spa_proc_cv);
1162 CALLB_CPR_EXIT(&cprinfo); /* drops spa_proc_lock */
1163
1164 mutex_enter(&curproc->p_lock);
1165 lwp_exit();
1166 }
1167 #endif
1168
1169 /*
1170 * Activate an uninitialized pool.
1171 */
1172 static void
1173 spa_activate(spa_t *spa, int mode)
1174 {
1175 ASSERT(spa->spa_state == POOL_STATE_UNINITIALIZED);
1176
1177 spa->spa_state = POOL_STATE_ACTIVE;
1178 spa->spa_mode = mode;
1179
1180 spa->spa_normal_class = metaslab_class_create(spa, zfs_metaslab_ops);
1181 spa->spa_log_class = metaslab_class_create(spa, zfs_metaslab_ops);
1182 spa->spa_special_class = metaslab_class_create(spa, zfs_metaslab_ops);
1183
1184 /* Try to create a covering process */
1185 mutex_enter(&spa->spa_proc_lock);
1186 ASSERT(spa->spa_proc_state == SPA_PROC_NONE);
1187 ASSERT(spa->spa_proc == &p0);
1188 spa->spa_did = 0;
1189
1190 /* Only create a process if we're going to be around a while. */
1191 if (spa_create_process && strcmp(spa->spa_name, TRYIMPORT_NAME) != 0) {
1192 if (newproc(spa_thread, (caddr_t)spa, syscid, maxclsyspri,
1193 NULL, 0) == 0) {
1194 spa->spa_proc_state = SPA_PROC_CREATED;
1195 while (spa->spa_proc_state == SPA_PROC_CREATED) {
1196 cv_wait(&spa->spa_proc_cv,
1197 &spa->spa_proc_lock);
1198 }
1199 ASSERT(spa->spa_proc_state == SPA_PROC_ACTIVE);
1200 ASSERT(spa->spa_proc != &p0);
1201 ASSERT(spa->spa_did != 0);
1202 } else {
1203 #ifdef _KERNEL
1204 cmn_err(CE_WARN,
1205 "Couldn't create process for zfs pool \"%s\"\n",
1206 spa->spa_name);
1207 #endif
1208 }
1209 }
1210 mutex_exit(&spa->spa_proc_lock);
1211
1212 /* If we didn't create a process, we need to create our taskqs. */
1213 if (spa->spa_proc == &p0) {
1214 spa_create_zio_taskqs(spa);
1215 }
1216
1217 list_create(&spa->spa_config_dirty_list, sizeof (vdev_t),
1218 offsetof(vdev_t, vdev_config_dirty_node));
1219 list_create(&spa->spa_evicting_os_list, sizeof (objset_t),
1220 offsetof(objset_t, os_evicting_node));
1221 list_create(&spa->spa_state_dirty_list, sizeof (vdev_t),
1222 offsetof(vdev_t, vdev_state_dirty_node));
1223
1224 txg_list_create(&spa->spa_vdev_txg_list, spa,
1225 offsetof(struct vdev, vdev_txg_node));
1226
1227 avl_create(&spa->spa_errlist_scrub,
1228 spa_error_entry_compare, sizeof (spa_error_entry_t),
1229 offsetof(spa_error_entry_t, se_avl));
1230 avl_create(&spa->spa_errlist_last,
1231 spa_error_entry_compare, sizeof (spa_error_entry_t),
1232 offsetof(spa_error_entry_t, se_avl));
1233 }
1234
1235 /*
1236 * Opposite of spa_activate().
1237 */
1238 static void
1239 spa_deactivate(spa_t *spa)
1240 {
1241 ASSERT(spa->spa_sync_on == B_FALSE);
1242 ASSERT(spa->spa_dsl_pool == NULL);
1243 ASSERT(spa->spa_root_vdev == NULL);
1244 ASSERT(spa->spa_async_zio_root == NULL);
1245 ASSERT(spa->spa_state != POOL_STATE_UNINITIALIZED);
1246
1247 spa_evicting_os_wait(spa);
1248
1249 txg_list_destroy(&spa->spa_vdev_txg_list);
1250
1251 list_destroy(&spa->spa_config_dirty_list);
1252 list_destroy(&spa->spa_evicting_os_list);
1253 list_destroy(&spa->spa_state_dirty_list);
1254
1255 for (int t = 0; t < ZIO_TYPES; t++) {
1256 for (int q = 0; q < ZIO_TASKQ_TYPES; q++) {
1257 spa_taskqs_fini(spa, t, q);
1258 }
1259 }
1260
1261 metaslab_class_destroy(spa->spa_normal_class);
1262 spa->spa_normal_class = NULL;
1263
1264 metaslab_class_destroy(spa->spa_log_class);
1265 spa->spa_log_class = NULL;
1266
1267 metaslab_class_destroy(spa->spa_special_class);
1268 spa->spa_special_class = NULL;
1269
1270 /*
1271 * If this was part of an import or the open otherwise failed, we may
1272 * still have errors left in the queues. Empty them just in case.
1273 */
1274 spa_errlog_drain(spa);
1275
1276 avl_destroy(&spa->spa_errlist_scrub);
1277 avl_destroy(&spa->spa_errlist_last);
1278
1279 spa->spa_state = POOL_STATE_UNINITIALIZED;
1280
1281 mutex_enter(&spa->spa_proc_lock);
1282 if (spa->spa_proc_state != SPA_PROC_NONE) {
1283 ASSERT(spa->spa_proc_state == SPA_PROC_ACTIVE);
1284 spa->spa_proc_state = SPA_PROC_DEACTIVATE;
1285 cv_broadcast(&spa->spa_proc_cv);
1286 while (spa->spa_proc_state == SPA_PROC_DEACTIVATE) {
1287 ASSERT(spa->spa_proc != &p0);
1288 cv_wait(&spa->spa_proc_cv, &spa->spa_proc_lock);
1289 }
1290 ASSERT(spa->spa_proc_state == SPA_PROC_GONE);
1291 spa->spa_proc_state = SPA_PROC_NONE;
1292 }
1293 ASSERT(spa->spa_proc == &p0);
1294 mutex_exit(&spa->spa_proc_lock);
1295
1296 /*
1297 * We want to make sure spa_thread() has actually exited the ZFS
1298 * module, so that the module can't be unloaded out from underneath
1299 * it.
1300 */
1301 if (spa->spa_did != 0) {
1302 thread_join(spa->spa_did);
1303 spa->spa_did = 0;
1304 }
1305 }
1306
1307 /*
1308 * Verify a pool configuration, and construct the vdev tree appropriately. This
1309 * will create all the necessary vdevs in the appropriate layout, with each vdev
1310 * in the CLOSED state. This will prep the pool before open/creation/import.
1311 * All vdev validation is done by the vdev_alloc() routine.
1312 */
1313 static int
1314 spa_config_parse(spa_t *spa, vdev_t **vdp, nvlist_t *nv, vdev_t *parent,
1315 uint_t id, int atype)
1316 {
1317 nvlist_t **child;
1318 uint_t children;
1319 int error;
1320
1321 if ((error = vdev_alloc(spa, vdp, nv, parent, id, atype)) != 0)
1322 return (error);
1323
1324 if ((*vdp)->vdev_ops->vdev_op_leaf)
1325 return (0);
1326
1327 error = nvlist_lookup_nvlist_array(nv, ZPOOL_CONFIG_CHILDREN,
1328 &child, &children);
1329
1330 if (error == ENOENT)
1331 return (0);
1332
1333 if (error) {
1334 vdev_free(*vdp);
1335 *vdp = NULL;
1336 return (SET_ERROR(EINVAL));
1337 }
1338
1339 for (int c = 0; c < children; c++) {
1340 vdev_t *vd;
1341 if ((error = spa_config_parse(spa, &vd, child[c], *vdp, c,
1342 atype)) != 0) {
1343 vdev_free(*vdp);
1344 *vdp = NULL;
1345 return (error);
1346 }
1347 }
1348
1349 ASSERT(*vdp != NULL);
1350
1351 return (0);
1352 }
1353
1354 /*
1355 * Opposite of spa_load().
1356 */
1357 static void
1358 spa_unload(spa_t *spa)
1359 {
1360 int i;
1361
1362 ASSERT(MUTEX_HELD(&spa_namespace_lock));
1363
1364 /*
1365 * Stop manual trim before stopping spa sync, because manual trim
1366 * needs to execute a synctask (trim timestamp sync) at the end.
1367 */
1368 mutex_enter(&spa->spa_auto_trim_lock);
1369 mutex_enter(&spa->spa_man_trim_lock);
1370 spa_trim_stop_wait(spa);
1371 mutex_exit(&spa->spa_man_trim_lock);
1372 mutex_exit(&spa->spa_auto_trim_lock);
1373
1374 /*
1375 * Stop async tasks.
1376 */
1377 spa_async_suspend(spa);
1378
1379 /*
1380 * Stop syncing.
1381 */
1382 if (spa->spa_sync_on) {
1383 txg_sync_stop(spa->spa_dsl_pool);
1384 spa->spa_sync_on = B_FALSE;
1385 }
1386
1387 /*
1388 * Even though vdev_free() also calls vdev_metaslab_fini, we need
1389 * to call it earlier, before we wait for async i/o to complete.
1390 * This ensures that there is no async metaslab prefetching, by
1391 * calling taskq_wait(mg_taskq).
1392 */
1393 if (spa->spa_root_vdev != NULL) {
1394 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1395 for (int c = 0; c < spa->spa_root_vdev->vdev_children; c++)
1396 vdev_metaslab_fini(spa->spa_root_vdev->vdev_child[c]);
1397 spa_config_exit(spa, SCL_ALL, FTAG);
1398 }
1399
1400 /*
1401 * Wait for any outstanding async I/O to complete.
1402 */
1403 if (spa->spa_async_zio_root != NULL) {
1404 for (int i = 0; i < max_ncpus; i++)
1405 (void) zio_wait(spa->spa_async_zio_root[i]);
1406 kmem_free(spa->spa_async_zio_root, max_ncpus * sizeof (void *));
1407 spa->spa_async_zio_root = NULL;
1408 }
1409
1410 bpobj_close(&spa->spa_deferred_bpobj);
1411
1412 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1413
1414 /*
1415 * Stop autotrim tasks.
1416 */
1417 mutex_enter(&spa->spa_auto_trim_lock);
1418 if (spa->spa_auto_trim_taskq)
1419 spa_auto_trim_taskq_destroy(spa);
1420 mutex_exit(&spa->spa_auto_trim_lock);
1421
1422 /*
1423 * Close all vdevs.
1424 */
1425 if (spa->spa_root_vdev)
1426 vdev_free(spa->spa_root_vdev);
1427 ASSERT(spa->spa_root_vdev == NULL);
1428
1429 /*
1430 * Close the dsl pool.
1431 */
1432 if (spa->spa_dsl_pool) {
1433 dsl_pool_close(spa->spa_dsl_pool);
1434 spa->spa_dsl_pool = NULL;
1435 spa->spa_meta_objset = NULL;
1436 }
1437
1438 ddt_unload(spa);
1439
1440 /*
1441 * Drop and purge level 2 cache
1442 */
1443 spa_l2cache_drop(spa);
1444
1445 for (i = 0; i < spa->spa_spares.sav_count; i++)
1446 vdev_free(spa->spa_spares.sav_vdevs[i]);
1447 if (spa->spa_spares.sav_vdevs) {
1448 kmem_free(spa->spa_spares.sav_vdevs,
1449 spa->spa_spares.sav_count * sizeof (void *));
1450 spa->spa_spares.sav_vdevs = NULL;
1451 }
1452 if (spa->spa_spares.sav_config) {
1453 nvlist_free(spa->spa_spares.sav_config);
1454 spa->spa_spares.sav_config = NULL;
1455 }
1456 spa->spa_spares.sav_count = 0;
1457
1458 for (i = 0; i < spa->spa_l2cache.sav_count; i++) {
1459 vdev_clear_stats(spa->spa_l2cache.sav_vdevs[i]);
1460 vdev_free(spa->spa_l2cache.sav_vdevs[i]);
1461 }
1462 if (spa->spa_l2cache.sav_vdevs) {
1463 kmem_free(spa->spa_l2cache.sav_vdevs,
1464 spa->spa_l2cache.sav_count * sizeof (void *));
1465 spa->spa_l2cache.sav_vdevs = NULL;
1466 }
1467 if (spa->spa_l2cache.sav_config) {
1468 nvlist_free(spa->spa_l2cache.sav_config);
1469 spa->spa_l2cache.sav_config = NULL;
1470 }
1471 spa->spa_l2cache.sav_count = 0;
1472
1473 spa->spa_async_suspended = 0;
1474
1475 if (spa->spa_comment != NULL) {
1476 spa_strfree(spa->spa_comment);
1477 spa->spa_comment = NULL;
1478 }
1479
1480 spa_config_exit(spa, SCL_ALL, FTAG);
1481 }
1482
1483 /*
1484 * Load (or re-load) the current list of vdevs describing the active spares for
1485 * this pool. When this is called, we have some form of basic information in
1486 * 'spa_spares.sav_config'. We parse this into vdevs, try to open them, and
1487 * then re-generate a more complete list including status information.
1488 */
1489 static void
1490 spa_load_spares(spa_t *spa)
1491 {
1492 nvlist_t **spares;
1493 uint_t nspares;
1494 int i;
1495 vdev_t *vd, *tvd;
1496
1497 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1498
1499 /*
1500 * First, close and free any existing spare vdevs.
1501 */
1502 for (i = 0; i < spa->spa_spares.sav_count; i++) {
1503 vd = spa->spa_spares.sav_vdevs[i];
1504
1505 /* Undo the call to spa_activate() below */
1506 if ((tvd = spa_lookup_by_guid(spa, vd->vdev_guid,
1507 B_FALSE)) != NULL && tvd->vdev_isspare)
1508 spa_spare_remove(tvd);
1509 vdev_close(vd);
1510 vdev_free(vd);
1511 }
1512
1513 if (spa->spa_spares.sav_vdevs)
1514 kmem_free(spa->spa_spares.sav_vdevs,
1515 spa->spa_spares.sav_count * sizeof (void *));
1516
1517 if (spa->spa_spares.sav_config == NULL)
1518 nspares = 0;
1519 else
1520 VERIFY(nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
1521 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
1522
1523 spa->spa_spares.sav_count = (int)nspares;
1524 spa->spa_spares.sav_vdevs = NULL;
1525
1526 if (nspares == 0)
1527 return;
1528
1529 /*
1530 * Construct the array of vdevs, opening them to get status in the
1531 * process. For each spare, there is potentially two different vdev_t
1532 * structures associated with it: one in the list of spares (used only
1533 * for basic validation purposes) and one in the active vdev
1534 * configuration (if it's spared in). During this phase we open and
1535 * validate each vdev on the spare list. If the vdev also exists in the
1536 * active configuration, then we also mark this vdev as an active spare.
1537 */
1538 spa->spa_spares.sav_vdevs = kmem_alloc(nspares * sizeof (void *),
1539 KM_SLEEP);
1540 for (i = 0; i < spa->spa_spares.sav_count; i++) {
1541 VERIFY(spa_config_parse(spa, &vd, spares[i], NULL, 0,
1542 VDEV_ALLOC_SPARE) == 0);
1543 ASSERT(vd != NULL);
1544
1545 spa->spa_spares.sav_vdevs[i] = vd;
1546
1547 if ((tvd = spa_lookup_by_guid(spa, vd->vdev_guid,
1548 B_FALSE)) != NULL) {
1549 if (!tvd->vdev_isspare)
1550 spa_spare_add(tvd);
1551
1552 /*
1553 * We only mark the spare active if we were successfully
1554 * able to load the vdev. Otherwise, importing a pool
1555 * with a bad active spare would result in strange
1556 * behavior, because multiple pool would think the spare
1557 * is actively in use.
1558 *
1559 * There is a vulnerability here to an equally bizarre
1560 * circumstance, where a dead active spare is later
1561 * brought back to life (onlined or otherwise). Given
1562 * the rarity of this scenario, and the extra complexity
1563 * it adds, we ignore the possibility.
1564 */
1565 if (!vdev_is_dead(tvd))
1566 spa_spare_activate(tvd);
1567 }
1568
1569 vd->vdev_top = vd;
1570 vd->vdev_aux = &spa->spa_spares;
1571
1572 if (vdev_open(vd) != 0)
1573 continue;
1574
1575 if (vdev_validate_aux(vd) == 0)
1576 spa_spare_add(vd);
1577 }
1578
1579 /*
1580 * Recompute the stashed list of spares, with status information
1581 * this time.
1582 */
1583 VERIFY(nvlist_remove(spa->spa_spares.sav_config, ZPOOL_CONFIG_SPARES,
1584 DATA_TYPE_NVLIST_ARRAY) == 0);
1585
1586 spares = kmem_alloc(spa->spa_spares.sav_count * sizeof (void *),
1587 KM_SLEEP);
1588 for (i = 0; i < spa->spa_spares.sav_count; i++)
1589 spares[i] = vdev_config_generate(spa,
1590 spa->spa_spares.sav_vdevs[i], B_TRUE, VDEV_CONFIG_SPARE);
1591 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
1592 ZPOOL_CONFIG_SPARES, spares, spa->spa_spares.sav_count) == 0);
1593 for (i = 0; i < spa->spa_spares.sav_count; i++)
1594 nvlist_free(spares[i]);
1595 kmem_free(spares, spa->spa_spares.sav_count * sizeof (void *));
1596 }
1597
1598 /*
1599 * Load (or re-load) the current list of vdevs describing the active l2cache for
1600 * this pool. When this is called, we have some form of basic information in
1601 * 'spa_l2cache.sav_config'. We parse this into vdevs, try to open them, and
1602 * then re-generate a more complete list including status information.
1603 * Devices which are already active have their details maintained, and are
1604 * not re-opened.
1605 */
1606 static void
1607 spa_load_l2cache(spa_t *spa)
1608 {
1609 nvlist_t **l2cache;
1610 uint_t nl2cache;
1611 int i, j, oldnvdevs;
1612 uint64_t guid;
1613 vdev_t *vd, **oldvdevs, **newvdevs;
1614 spa_aux_vdev_t *sav = &spa->spa_l2cache;
1615
1616 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
1617
1618 if (sav->sav_config != NULL) {
1619 VERIFY(nvlist_lookup_nvlist_array(sav->sav_config,
1620 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
1621 newvdevs = kmem_alloc(nl2cache * sizeof (void *), KM_SLEEP);
1622 } else {
1623 nl2cache = 0;
1624 newvdevs = NULL;
1625 }
1626
1627 oldvdevs = sav->sav_vdevs;
1628 oldnvdevs = sav->sav_count;
1629 sav->sav_vdevs = NULL;
1630 sav->sav_count = 0;
1631
1632 /*
1633 * Process new nvlist of vdevs.
1634 */
1635 for (i = 0; i < nl2cache; i++) {
1636 VERIFY(nvlist_lookup_uint64(l2cache[i], ZPOOL_CONFIG_GUID,
1637 &guid) == 0);
1638
1639 newvdevs[i] = NULL;
1640 for (j = 0; j < oldnvdevs; j++) {
1641 vd = oldvdevs[j];
1642 if (vd != NULL && guid == vd->vdev_guid) {
1643 /*
1644 * Retain previous vdev for add/remove ops.
1645 */
1646 newvdevs[i] = vd;
1647 oldvdevs[j] = NULL;
1648 break;
1649 }
1650 }
1651
1652 if (newvdevs[i] == NULL) {
1653 /*
1654 * Create new vdev
1655 */
1656 VERIFY(spa_config_parse(spa, &vd, l2cache[i], NULL, 0,
1657 VDEV_ALLOC_L2CACHE) == 0);
1658 ASSERT(vd != NULL);
1659 newvdevs[i] = vd;
1660
1661 /*
1662 * Commit this vdev as an l2cache device,
1663 * even if it fails to open.
1664 */
1665 spa_l2cache_add(vd);
1666
1667 vd->vdev_top = vd;
1668 vd->vdev_aux = sav;
1669
1670 spa_l2cache_activate(vd);
1671
1672 if (vdev_open(vd) != 0)
1673 continue;
1674
1675 (void) vdev_validate_aux(vd);
1676
1677 if (!vdev_is_dead(vd)) {
1678 boolean_t do_rebuild = B_FALSE;
1679
1680 (void) nvlist_lookup_boolean_value(l2cache[i],
1681 ZPOOL_CONFIG_L2CACHE_PERSISTENT,
1682 &do_rebuild);
1683 l2arc_add_vdev(spa, vd, do_rebuild);
1684 }
1685 }
1686 }
1687
1688 /*
1689 * Purge vdevs that were dropped
1690 */
1691 for (i = 0; i < oldnvdevs; i++) {
1692 uint64_t pool;
1693
1694 vd = oldvdevs[i];
1695 if (vd != NULL) {
1696 ASSERT(vd->vdev_isl2cache);
1697
1698 if (spa_l2cache_exists(vd->vdev_guid, &pool) &&
1699 pool != 0ULL && l2arc_vdev_present(vd))
1700 l2arc_remove_vdev(vd);
1701 vdev_clear_stats(vd);
1702 vdev_free(vd);
1703 }
1704 }
1705
1706 if (oldvdevs)
1707 kmem_free(oldvdevs, oldnvdevs * sizeof (void *));
1708
1709 if (sav->sav_config == NULL)
1710 goto out;
1711
1712 sav->sav_vdevs = newvdevs;
1713 sav->sav_count = (int)nl2cache;
1714
1715 /*
1716 * Recompute the stashed list of l2cache devices, with status
1717 * information this time.
1718 */
1719 VERIFY(nvlist_remove(sav->sav_config, ZPOOL_CONFIG_L2CACHE,
1720 DATA_TYPE_NVLIST_ARRAY) == 0);
1721
1722 l2cache = kmem_alloc(sav->sav_count * sizeof (void *), KM_SLEEP);
1723 for (i = 0; i < sav->sav_count; i++)
1724 l2cache[i] = vdev_config_generate(spa,
1725 sav->sav_vdevs[i], B_TRUE, VDEV_CONFIG_L2CACHE);
1726 VERIFY(nvlist_add_nvlist_array(sav->sav_config,
1727 ZPOOL_CONFIG_L2CACHE, l2cache, sav->sav_count) == 0);
1728 out:
1729 for (i = 0; i < sav->sav_count; i++)
1730 nvlist_free(l2cache[i]);
1731 if (sav->sav_count)
1732 kmem_free(l2cache, sav->sav_count * sizeof (void *));
1733 }
1734
1735 static int
1736 load_nvlist(spa_t *spa, uint64_t obj, nvlist_t **value)
1737 {
1738 dmu_buf_t *db;
1739 char *packed = NULL;
1740 size_t nvsize = 0;
1741 int error;
1742 *value = NULL;
1743
1744 error = dmu_bonus_hold(spa->spa_meta_objset, obj, FTAG, &db);
1745 if (error != 0)
1746 return (error);
1747
1748 nvsize = *(uint64_t *)db->db_data;
1749 dmu_buf_rele(db, FTAG);
1750
1751 packed = kmem_alloc(nvsize, KM_SLEEP);
1752 error = dmu_read(spa->spa_meta_objset, obj, 0, nvsize, packed,
1753 DMU_READ_PREFETCH);
1754 if (error == 0)
1755 error = nvlist_unpack(packed, nvsize, value, 0);
1756 kmem_free(packed, nvsize);
1757
1758 return (error);
1759 }
1760
1761 /*
1762 * Checks to see if the given vdev could not be opened, in which case we post a
1763 * sysevent to notify the autoreplace code that the device has been removed.
1764 */
1765 static void
1766 spa_check_removed(vdev_t *vd)
1767 {
1768 for (int c = 0; c < vd->vdev_children; c++)
1769 spa_check_removed(vd->vdev_child[c]);
1770
1771 if (vd->vdev_ops->vdev_op_leaf && vdev_is_dead(vd) &&
1772 !vd->vdev_ishole) {
1773 zfs_post_autoreplace(vd->vdev_spa, vd);
1774 spa_event_notify(vd->vdev_spa, vd, NULL, ESC_ZFS_VDEV_CHECK);
1775 }
1776 }
1777
1778 static void
1779 spa_config_valid_zaps(vdev_t *vd, vdev_t *mvd)
1780 {
1781 ASSERT3U(vd->vdev_children, ==, mvd->vdev_children);
1782
1783 vd->vdev_top_zap = mvd->vdev_top_zap;
1784 vd->vdev_leaf_zap = mvd->vdev_leaf_zap;
1785
1786 for (uint64_t i = 0; i < vd->vdev_children; i++) {
1787 spa_config_valid_zaps(vd->vdev_child[i], mvd->vdev_child[i]);
1788 }
1789 }
1790
1791 /*
1792 * Validate the current config against the MOS config
1793 */
1794 static boolean_t
1795 spa_config_valid(spa_t *spa, nvlist_t *config)
1796 {
1797 vdev_t *mrvd, *rvd = spa->spa_root_vdev;
1798 nvlist_t *nv;
1799
1800 VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nv) == 0);
1801
1802 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1803 VERIFY(spa_config_parse(spa, &mrvd, nv, NULL, 0, VDEV_ALLOC_LOAD) == 0);
1804
1805 /*
1806 * One of the earliest signs of a stale config is a mismatch
1807 * in the numbers of children vdev's
1808 */
1809 if (rvd->vdev_children != mrvd->vdev_children) {
1810 vdev_free(mrvd);
1811 spa_config_exit(spa, SCL_ALL, FTAG);
1812 return (B_FALSE);
1813 }
1814 /*
1815 * If we're doing a normal import, then build up any additional
1816 * diagnostic information about missing devices in this config.
1817 * We'll pass this up to the user for further processing.
1818 */
1819 if (!(spa->spa_import_flags & ZFS_IMPORT_MISSING_LOG)) {
1820 nvlist_t **child, *nv;
1821 uint64_t idx = 0;
1822
1823 child = kmem_alloc(rvd->vdev_children * sizeof (nvlist_t **),
1824 KM_SLEEP);
1825 VERIFY(nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) == 0);
1826
1827 for (int c = 0; c < rvd->vdev_children; c++) {
1828 vdev_t *tvd = rvd->vdev_child[c];
1829 vdev_t *mtvd = mrvd->vdev_child[c];
1830
1831 if (tvd->vdev_ops == &vdev_missing_ops &&
1832 mtvd->vdev_ops != &vdev_missing_ops &&
1833 mtvd->vdev_islog)
1834 child[idx++] = vdev_config_generate(spa, mtvd,
1835 B_FALSE, 0);
1836 }
1837
1838 if (idx) {
1839 VERIFY(nvlist_add_nvlist_array(nv,
1840 ZPOOL_CONFIG_CHILDREN, child, idx) == 0);
1841 VERIFY(nvlist_add_nvlist(spa->spa_load_info,
1842 ZPOOL_CONFIG_MISSING_DEVICES, nv) == 0);
1843
1844 for (int i = 0; i < idx; i++)
1845 nvlist_free(child[i]);
1846 }
1847 nvlist_free(nv);
1848 kmem_free(child, rvd->vdev_children * sizeof (char **));
1849 }
1850
1851 /*
1852 * Compare the root vdev tree with the information we have
1853 * from the MOS config (mrvd). Check each top-level vdev
1854 * with the corresponding MOS config top-level (mtvd).
1855 */
1856 for (int c = 0; c < rvd->vdev_children; c++) {
1857 vdev_t *tvd = rvd->vdev_child[c];
1858 vdev_t *mtvd = mrvd->vdev_child[c];
1859
1860 /*
1861 * Resolve any "missing" vdevs in the current configuration.
1862 * If we find that the MOS config has more accurate information
1863 * about the top-level vdev then use that vdev instead.
1864 */
1865 if (tvd->vdev_ops == &vdev_missing_ops &&
1866 mtvd->vdev_ops != &vdev_missing_ops) {
1867
1868 if (!(spa->spa_import_flags & ZFS_IMPORT_MISSING_LOG))
1869 continue;
1870
1871 /*
1872 * Device specific actions.
1873 */
1874 if (mtvd->vdev_islog) {
1875 spa_set_log_state(spa, SPA_LOG_CLEAR);
1876 } else {
1877 /*
1878 * XXX - once we have 'readonly' pool
1879 * support we should be able to handle
1880 * missing data devices by transitioning
1881 * the pool to readonly.
1882 */
1883 continue;
1884 }
1885
1886 /*
1887 * Swap the missing vdev with the data we were
1888 * able to obtain from the MOS config.
1889 */
1890 vdev_remove_child(rvd, tvd);
1891 vdev_remove_child(mrvd, mtvd);
1892
1893 vdev_add_child(rvd, mtvd);
1894 vdev_add_child(mrvd, tvd);
1895
1896 spa_config_exit(spa, SCL_ALL, FTAG);
1897 vdev_load(mtvd);
1898 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
1899
1900 vdev_reopen(rvd);
1901 } else {
1902 if (mtvd->vdev_islog) {
1903 /*
1904 * Load the slog device's state from the MOS
1905 * config since it's possible that the label
1906 * does not contain the most up-to-date
1907 * information.
1908 */
1909 vdev_load_log_state(tvd, mtvd);
1910 vdev_reopen(tvd);
1911 }
1912
1913 /*
1914 * Per-vdev ZAP info is stored exclusively in the MOS.
1915 */
1916 spa_config_valid_zaps(tvd, mtvd);
1917 }
1918 }
1919
1920 vdev_free(mrvd);
1921 spa_config_exit(spa, SCL_ALL, FTAG);
1922
1923 /*
1924 * Ensure we were able to validate the config.
1925 */
1926 return (rvd->vdev_guid_sum == spa->spa_uberblock.ub_guid_sum);
1927 }
1928
1929 /*
1930 * Check for missing log devices
1931 */
1932 static boolean_t
1933 spa_check_logs(spa_t *spa)
1934 {
1935 boolean_t rv = B_FALSE;
1936 dsl_pool_t *dp = spa_get_dsl(spa);
1937
1938 switch (spa->spa_log_state) {
1939 case SPA_LOG_MISSING:
1940 /* need to recheck in case slog has been restored */
1941 case SPA_LOG_UNKNOWN:
1942 rv = (dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
1943 zil_check_log_chain, NULL, DS_FIND_CHILDREN) != 0);
1944 if (rv)
1945 spa_set_log_state(spa, SPA_LOG_MISSING);
1946 break;
1947 }
1948 return (rv);
1949 }
1950
1951 static boolean_t
1952 spa_passivate_log(spa_t *spa)
1953 {
1954 vdev_t *rvd = spa->spa_root_vdev;
1955 boolean_t slog_found = B_FALSE;
1956
1957 ASSERT(spa_config_held(spa, SCL_ALLOC, RW_WRITER));
1958
1959 if (!spa_has_slogs(spa))
1960 return (B_FALSE);
1961
1962 for (int c = 0; c < rvd->vdev_children; c++) {
1963 vdev_t *tvd = rvd->vdev_child[c];
1964 metaslab_group_t *mg = tvd->vdev_mg;
1965
1966 if (tvd->vdev_islog) {
1967 metaslab_group_passivate(mg);
1968 slog_found = B_TRUE;
1969 }
1970 }
1971
1972 return (slog_found);
1973 }
1974
1975 static void
1976 spa_activate_log(spa_t *spa)
1977 {
1978 vdev_t *rvd = spa->spa_root_vdev;
1979
1980 ASSERT(spa_config_held(spa, SCL_ALLOC, RW_WRITER));
1981
1982 for (int c = 0; c < rvd->vdev_children; c++) {
1983 vdev_t *tvd = rvd->vdev_child[c];
1984 metaslab_group_t *mg = tvd->vdev_mg;
1985
1986 if (tvd->vdev_islog)
1987 metaslab_group_activate(mg);
1988 }
1989 }
1990
1991 int
1992 spa_offline_log(spa_t *spa)
1993 {
1994 int error;
1995
1996 error = dmu_objset_find(spa_name(spa), zil_vdev_offline,
1997 NULL, DS_FIND_CHILDREN);
1998 if (error == 0) {
1999 /*
2000 * We successfully offlined the log device, sync out the
2001 * current txg so that the "stubby" block can be removed
2002 * by zil_sync().
2003 */
2004 txg_wait_synced(spa->spa_dsl_pool, 0);
2005 }
2006 return (error);
2007 }
2008
2009 static void
2010 spa_aux_check_removed(spa_aux_vdev_t *sav)
2011 {
2012 for (int i = 0; i < sav->sav_count; i++)
2013 spa_check_removed(sav->sav_vdevs[i]);
2014 }
2015
2016 void
2017 spa_claim_notify(zio_t *zio)
2018 {
2019 spa_t *spa = zio->io_spa;
2020
2021 if (zio->io_error)
2022 return;
2023
2024 mutex_enter(&spa->spa_props_lock); /* any mutex will do */
2025 if (spa->spa_claim_max_txg < zio->io_bp->blk_birth)
2026 spa->spa_claim_max_txg = zio->io_bp->blk_birth;
2027 mutex_exit(&spa->spa_props_lock);
2028 }
2029
2030 typedef struct spa_load_error {
2031 uint64_t sle_meta_count;
2032 uint64_t sle_data_count;
2033 } spa_load_error_t;
2034
2035 static void
2036 spa_load_verify_done(zio_t *zio)
2037 {
2038 blkptr_t *bp = zio->io_bp;
2039 spa_load_error_t *sle = zio->io_private;
2040 dmu_object_type_t type = BP_GET_TYPE(bp);
2041 int error = zio->io_error;
2042 spa_t *spa = zio->io_spa;
2043
2044 abd_free(zio->io_abd);
2045 if (error) {
2046 if (BP_IS_METADATA(bp) && type != DMU_OT_INTENT_LOG)
2047 atomic_inc_64(&sle->sle_meta_count);
2048 else
2049 atomic_inc_64(&sle->sle_data_count);
2050 }
2051
2052 mutex_enter(&spa->spa_scrub_lock);
2053 spa->spa_scrub_inflight--;
2054 cv_broadcast(&spa->spa_scrub_io_cv);
2055 mutex_exit(&spa->spa_scrub_lock);
2056 }
2057
2058 /*
2059 * Maximum number of concurrent scrub i/os to create while verifying
2060 * a pool while importing it.
2061 */
2062 int spa_load_verify_maxinflight = 10000;
2063 boolean_t spa_load_verify_metadata = B_TRUE;
2064 boolean_t spa_load_verify_data = B_TRUE;
2065
2066 /*ARGSUSED*/
2067 static int
2068 spa_load_verify_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
2069 const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
2070 {
2071 if (bp == NULL || BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp))
2072 return (0);
2073 /*
2074 * Note: normally this routine will not be called if
2075 * spa_load_verify_metadata is not set. However, it may be useful
2076 * to manually set the flag after the traversal has begun.
2077 */
2078 if (!spa_load_verify_metadata)
2079 return (0);
2080 if (!BP_IS_METADATA(bp) && !spa_load_verify_data)
2081 return (0);
2082
2083 zio_t *rio = arg;
2084 size_t size = BP_GET_PSIZE(bp);
2085
2086 mutex_enter(&spa->spa_scrub_lock);
2087 while (spa->spa_scrub_inflight >= spa_load_verify_maxinflight)
2088 cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);
2089 spa->spa_scrub_inflight++;
2090 mutex_exit(&spa->spa_scrub_lock);
2091
2092 zio_nowait(zio_read(rio, spa, bp, abd_alloc_for_io(size, B_FALSE), size,
2093 spa_load_verify_done, rio->io_private, ZIO_PRIORITY_SCRUB,
2094 ZIO_FLAG_SPECULATIVE | ZIO_FLAG_CANFAIL |
2095 ZIO_FLAG_SCRUB | ZIO_FLAG_RAW, zb));
2096 return (0);
2097 }
2098
2099 /* ARGSUSED */
2100 int
2101 verify_dataset_name_len(dsl_pool_t *dp, dsl_dataset_t *ds, void *arg)
2102 {
2103 if (dsl_dataset_namelen(ds) >= ZFS_MAX_DATASET_NAME_LEN)
2104 return (SET_ERROR(ENAMETOOLONG));
2105
2106 return (0);
2107 }
2108
2109 static int
2110 spa_load_verify(spa_t *spa)
2111 {
2112 zio_t *rio;
2113 spa_load_error_t sle = { 0 };
2114 zpool_rewind_policy_t policy;
2115 boolean_t verify_ok = B_FALSE;
2116 int error = 0;
2117
2118 zpool_get_rewind_policy(spa->spa_config, &policy);
2119
2120 if (policy.zrp_request & ZPOOL_NEVER_REWIND)
2121 return (0);
2122
2123 dsl_pool_config_enter(spa->spa_dsl_pool, FTAG);
2124 error = dmu_objset_find_dp(spa->spa_dsl_pool,
2125 spa->spa_dsl_pool->dp_root_dir_obj, verify_dataset_name_len, NULL,
2126 DS_FIND_CHILDREN);
2127 dsl_pool_config_exit(spa->spa_dsl_pool, FTAG);
2128 if (error != 0)
2129 return (error);
2130
2131 rio = zio_root(spa, NULL, &sle,
2132 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE);
2133
2134 if (spa_load_verify_metadata) {
2135 zbookmark_phys_t zb = { 0 };
2136 error = traverse_pool(spa, spa->spa_verify_min_txg, UINT64_MAX,
2137 TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA,
2138 spa_load_verify_cb, rio, &zb);
2139 }
2140
2141 (void) zio_wait(rio);
2142
2143 spa->spa_load_meta_errors = sle.sle_meta_count;
2144 spa->spa_load_data_errors = sle.sle_data_count;
2145
2146 if (!error && sle.sle_meta_count <= policy.zrp_maxmeta &&
2147 sle.sle_data_count <= policy.zrp_maxdata) {
2148 int64_t loss = 0;
2149
2150 verify_ok = B_TRUE;
2151 spa->spa_load_txg = spa->spa_uberblock.ub_txg;
2152 spa->spa_load_txg_ts = spa->spa_uberblock.ub_timestamp;
2153
2154 loss = spa->spa_last_ubsync_txg_ts - spa->spa_load_txg_ts;
2155 VERIFY(nvlist_add_uint64(spa->spa_load_info,
2156 ZPOOL_CONFIG_LOAD_TIME, spa->spa_load_txg_ts) == 0);
2157 VERIFY(nvlist_add_int64(spa->spa_load_info,
2158 ZPOOL_CONFIG_REWIND_TIME, loss) == 0);
2159 VERIFY(nvlist_add_uint64(spa->spa_load_info,
2160 ZPOOL_CONFIG_LOAD_DATA_ERRORS, sle.sle_data_count) == 0);
2161 } else {
2162 spa->spa_load_max_txg = spa->spa_uberblock.ub_txg;
2163 }
2164
2165 if (error) {
2166 if (error != ENXIO && error != EIO)
2167 error = SET_ERROR(EIO);
2168 return (error);
2169 }
2170
2171 return (verify_ok ? 0 : EIO);
2172 }
2173
2174 /*
2175 * Find a value in the pool props object.
2176 */
2177 static void
2178 spa_prop_find(spa_t *spa, zpool_prop_t prop, uint64_t *val)
2179 {
2180 (void) zap_lookup(spa->spa_meta_objset, spa->spa_pool_props_object,
2181 zpool_prop_to_name(prop), sizeof (uint64_t), 1, val);
2182 }
2183
2184 /*
2185 * Find a value in the pool directory object.
2186 */
2187 static int
2188 spa_dir_prop(spa_t *spa, const char *name, uint64_t *val)
2189 {
2190 return (zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
2191 name, sizeof (uint64_t), 1, val));
2192 }
2193
2194 static void
2195 spa_set_ddt_classes(spa_t *spa, int desegregation)
2196 {
2197 /*
2198 * if desegregation is turned on then set up ddt_class restrictions
2199 */
2200 if (desegregation) {
2201 spa->spa_ddt_class_min = DDT_CLASS_DUPLICATE;
2202 spa->spa_ddt_class_max = DDT_CLASS_DUPLICATE;
2203 } else {
2204 spa->spa_ddt_class_min = DDT_CLASS_DITTO;
2205 spa->spa_ddt_class_max = DDT_CLASS_UNIQUE;
2206 }
2207 }
2208
2209 static int
2210 spa_vdev_err(vdev_t *vdev, vdev_aux_t aux, int err)
2211 {
2212 vdev_set_state(vdev, B_TRUE, VDEV_STATE_CANT_OPEN, aux);
2213 return (err);
2214 }
2215
2216 /*
2217 * Fix up config after a partly-completed split. This is done with the
2218 * ZPOOL_CONFIG_SPLIT nvlist. Both the splitting pool and the split-off
2219 * pool have that entry in their config, but only the splitting one contains
2220 * a list of all the guids of the vdevs that are being split off.
2221 *
2222 * This function determines what to do with that list: either rejoin
2223 * all the disks to the pool, or complete the splitting process. To attempt
2224 * the rejoin, each disk that is offlined is marked online again, and
2225 * we do a reopen() call. If the vdev label for every disk that was
2226 * marked online indicates it was successfully split off (VDEV_AUX_SPLIT_POOL)
2227 * then we call vdev_split() on each disk, and complete the split.
2228 *
2229 * Otherwise we leave the config alone, with all the vdevs in place in
2230 * the original pool.
2231 */
2232 static void
2233 spa_try_repair(spa_t *spa, nvlist_t *config)
2234 {
2235 uint_t extracted;
2236 uint64_t *glist;
2237 uint_t i, gcount;
2238 nvlist_t *nvl;
2239 vdev_t **vd;
2240 boolean_t attempt_reopen;
2241
2242 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_SPLIT, &nvl) != 0)
2243 return;
2244
2245 /* check that the config is complete */
2246 if (nvlist_lookup_uint64_array(nvl, ZPOOL_CONFIG_SPLIT_LIST,
2247 &glist, &gcount) != 0)
2248 return;
2249
2250 vd = kmem_zalloc(gcount * sizeof (vdev_t *), KM_SLEEP);
2251
2252 /* attempt to online all the vdevs & validate */
2253 attempt_reopen = B_TRUE;
2254 for (i = 0; i < gcount; i++) {
2255 if (glist[i] == 0) /* vdev is hole */
2256 continue;
2257
2258 vd[i] = spa_lookup_by_guid(spa, glist[i], B_FALSE);
2259 if (vd[i] == NULL) {
2260 /*
2261 * Don't bother attempting to reopen the disks;
2262 * just do the split.
2263 */
2264 attempt_reopen = B_FALSE;
2265 } else {
2266 /* attempt to re-online it */
2267 vd[i]->vdev_offline = B_FALSE;
2268 }
2269 }
2270
2271 if (attempt_reopen) {
2272 vdev_reopen(spa->spa_root_vdev);
2273
2274 /* check each device to see what state it's in */
2275 for (extracted = 0, i = 0; i < gcount; i++) {
2276 if (vd[i] != NULL &&
2277 vd[i]->vdev_stat.vs_aux != VDEV_AUX_SPLIT_POOL)
2278 break;
2279 ++extracted;
2280 }
2281 }
2282
2283 /*
2284 * If every disk has been moved to the new pool, or if we never
2285 * even attempted to look at them, then we split them off for
2286 * good.
2287 */
2288 if (!attempt_reopen || gcount == extracted) {
2289 for (i = 0; i < gcount; i++)
2290 if (vd[i] != NULL)
2291 vdev_split(vd[i]);
2292 vdev_reopen(spa->spa_root_vdev);
2293 }
2294
2295 kmem_free(vd, gcount * sizeof (vdev_t *));
2296 }
2297
2298 static int
2299 spa_load(spa_t *spa, spa_load_state_t state, spa_import_type_t type,
2300 boolean_t mosconfig)
2301 {
2302 nvlist_t *config = spa->spa_config;
2303 char *ereport = FM_EREPORT_ZFS_POOL;
2304 char *comment;
2305 int error;
2306 uint64_t pool_guid;
2307 nvlist_t *nvl;
2308
2309 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID, &pool_guid))
2310 return (SET_ERROR(EINVAL));
2311
2312 ASSERT(spa->spa_comment == NULL);
2313 if (nvlist_lookup_string(config, ZPOOL_CONFIG_COMMENT, &comment) == 0)
2314 spa->spa_comment = spa_strdup(comment);
2315
2316 /*
2317 * Versioning wasn't explicitly added to the label until later, so if
2318 * it's not present treat it as the initial version.
2319 */
2320 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_VERSION,
2321 &spa->spa_ubsync.ub_version) != 0)
2322 spa->spa_ubsync.ub_version = SPA_VERSION_INITIAL;
2323
2324 (void) nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG,
2325 &spa->spa_config_txg);
2326
2327 if ((state == SPA_LOAD_IMPORT || state == SPA_LOAD_TRYIMPORT) &&
2328 spa_guid_exists(pool_guid, 0)) {
2329 error = SET_ERROR(EEXIST);
2330 } else {
2331 spa->spa_config_guid = pool_guid;
2332
2333 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_SPLIT,
2334 &nvl) == 0) {
2335 VERIFY(nvlist_dup(nvl, &spa->spa_config_splitting,
2336 KM_SLEEP) == 0);
2337 }
2338
2339 nvlist_free(spa->spa_load_info);
2340 spa->spa_load_info = fnvlist_alloc();
2341
2342 gethrestime(&spa->spa_loaded_ts);
2343 error = spa_load_impl(spa, pool_guid, config, state, type,
2344 mosconfig, &ereport);
2345 }
2346
2347 /*
2348 * Don't count references from objsets that are already closed
2349 * and are making their way through the eviction process.
2350 */
2351 spa_evicting_os_wait(spa);
2352 spa->spa_minref = refcount_count(&spa->spa_refcount);
2353 if (error) {
2354 if (error != EEXIST) {
2355 spa->spa_loaded_ts.tv_sec = 0;
2356 spa->spa_loaded_ts.tv_nsec = 0;
2357 }
2358 if (error != EBADF) {
2359 zfs_ereport_post(ereport, spa, NULL, NULL, 0, 0);
2360 }
2361 }
2362 spa->spa_load_state = error ? SPA_LOAD_ERROR : SPA_LOAD_NONE;
2363 spa->spa_ena = 0;
2364 return (error);
2365 }
2366
2367 /*
2368 * Count the number of per-vdev ZAPs associated with all of the vdevs in the
2369 * vdev tree rooted in the given vd, and ensure that each ZAP is present in the
2370 * spa's per-vdev ZAP list.
2371 */
2372 static uint64_t
2373 vdev_count_verify_zaps(vdev_t *vd)
2374 {
2375 spa_t *spa = vd->vdev_spa;
2376 uint64_t total = 0;
2377 if (vd->vdev_top_zap != 0) {
2378 total++;
2379 ASSERT0(zap_lookup_int(spa->spa_meta_objset,
2380 spa->spa_all_vdev_zaps, vd->vdev_top_zap));
2381 }
2382 if (vd->vdev_leaf_zap != 0) {
2383 total++;
2384 ASSERT0(zap_lookup_int(spa->spa_meta_objset,
2385 spa->spa_all_vdev_zaps, vd->vdev_leaf_zap));
2386 }
2387
2388 for (uint64_t i = 0; i < vd->vdev_children; i++) {
2389 total += vdev_count_verify_zaps(vd->vdev_child[i]);
2390 }
2391
2392 return (total);
2393 }
2394
2395 /*
2396 * Load an existing storage pool, using the pool's builtin spa_config as a
2397 * source of configuration information.
2398 */
2399 static int
2400 spa_load_impl(spa_t *spa, uint64_t pool_guid, nvlist_t *config,
2401 spa_load_state_t state, spa_import_type_t type, boolean_t mosconfig,
2402 char **ereport)
2403 {
2404 int error = 0;
2405 nvlist_t *nvroot = NULL;
2406 nvlist_t *label;
2407 vdev_t *rvd;
2408 uberblock_t *ub = &spa->spa_uberblock;
2409 uint64_t children, config_cache_txg = spa->spa_config_txg;
2410 int orig_mode = spa->spa_mode;
2411 int parse;
2412 uint64_t obj;
2413 boolean_t missing_feat_write = B_FALSE;
2414 spa_meta_placement_t *mp;
2415
2416 /*
2417 * If this is an untrusted config, access the pool in read-only mode.
2418 * This prevents things like resilvering recently removed devices.
2419 */
2420 if (!mosconfig)
2421 spa->spa_mode = FREAD;
2422
2423 ASSERT(MUTEX_HELD(&spa_namespace_lock));
2424
2425 spa->spa_load_state = state;
2426
2427 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nvroot))
2428 return (SET_ERROR(EINVAL));
2429
2430 parse = (type == SPA_IMPORT_EXISTING ?
2431 VDEV_ALLOC_LOAD : VDEV_ALLOC_SPLIT);
2432
2433 /*
2434 * Create "The Godfather" zio to hold all async IOs
2435 */
2436 spa->spa_async_zio_root = kmem_alloc(max_ncpus * sizeof (void *),
2437 KM_SLEEP);
2438 for (int i = 0; i < max_ncpus; i++) {
2439 spa->spa_async_zio_root[i] = zio_root(spa, NULL, NULL,
2440 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
2441 ZIO_FLAG_GODFATHER);
2442 }
2443
2444 /*
2445 * Parse the configuration into a vdev tree. We explicitly set the
2446 * value that will be returned by spa_version() since parsing the
2447 * configuration requires knowing the version number.
2448 */
2449 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2450 error = spa_config_parse(spa, &rvd, nvroot, NULL, 0, parse);
2451 spa_config_exit(spa, SCL_ALL, FTAG);
2452
2453 if (error != 0)
2454 return (error);
2455
2456 ASSERT(spa->spa_root_vdev == rvd);
2457 ASSERT3U(spa->spa_min_ashift, >=, SPA_MINBLOCKSHIFT);
2458 ASSERT3U(spa->spa_max_ashift, <=, SPA_MAXBLOCKSHIFT);
2459
2460 if (type != SPA_IMPORT_ASSEMBLE) {
2461 ASSERT(spa_guid(spa) == pool_guid);
2462 }
2463
2464 /*
2465 * Try to open all vdevs, loading each label in the process.
2466 */
2467 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2468 error = vdev_open(rvd);
2469 spa_config_exit(spa, SCL_ALL, FTAG);
2470 if (error != 0)
2471 return (error);
2472
2473 /*
2474 * We need to validate the vdev labels against the configuration that
2475 * we have in hand, which is dependent on the setting of mosconfig. If
2476 * mosconfig is true then we're validating the vdev labels based on
2477 * that config. Otherwise, we're validating against the cached config
2478 * (zpool.cache) that was read when we loaded the zfs module, and then
2479 * later we will recursively call spa_load() and validate against
2480 * the vdev config.
2481 *
2482 * If we're assembling a new pool that's been split off from an
2483 * existing pool, the labels haven't yet been updated so we skip
2484 * validation for now.
2485 */
2486 if (type != SPA_IMPORT_ASSEMBLE) {
2487 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2488 error = vdev_validate(rvd, mosconfig);
2489 spa_config_exit(spa, SCL_ALL, FTAG);
2490
2491 if (error != 0)
2492 return (error);
2493
2494 if (rvd->vdev_state <= VDEV_STATE_CANT_OPEN)
2495 return (SET_ERROR(ENXIO));
2496 }
2497
2498 /*
2499 * Find the best uberblock.
2500 */
2501 vdev_uberblock_load(rvd, ub, &label);
2502
2503 /*
2504 * If we weren't able to find a single valid uberblock, return failure.
2505 */
2506 if (ub->ub_txg == 0) {
2507 nvlist_free(label);
2508 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, ENXIO));
2509 }
2510
2511 /*
2512 * If the pool has an unsupported version we can't open it.
2513 */
2514 if (!SPA_VERSION_IS_SUPPORTED(ub->ub_version)) {
2515 nvlist_free(label);
2516 return (spa_vdev_err(rvd, VDEV_AUX_VERSION_NEWER, ENOTSUP));
2517 }
2518
2519 if (ub->ub_version >= SPA_VERSION_FEATURES) {
2520 nvlist_t *features;
2521
2522 /*
2523 * If we weren't able to find what's necessary for reading the
2524 * MOS in the label, return failure.
2525 */
2526 if (label == NULL || nvlist_lookup_nvlist(label,
2527 ZPOOL_CONFIG_FEATURES_FOR_READ, &features) != 0) {
2528 nvlist_free(label);
2529 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
2530 ENXIO));
2531 }
2532
2533 /*
2534 * Update our in-core representation with the definitive values
2535 * from the label.
2536 */
2537 nvlist_free(spa->spa_label_features);
2538 VERIFY(nvlist_dup(features, &spa->spa_label_features, 0) == 0);
2539 }
2540
2541 nvlist_free(label);
2542
2543 /*
2544 * Look through entries in the label nvlist's features_for_read. If
2545 * there is a feature listed there which we don't understand then we
2546 * cannot open a pool.
2547 */
2548 if (ub->ub_version >= SPA_VERSION_FEATURES) {
2549 nvlist_t *unsup_feat;
2550
2551 VERIFY(nvlist_alloc(&unsup_feat, NV_UNIQUE_NAME, KM_SLEEP) ==
2552 0);
2553
2554 for (nvpair_t *nvp = nvlist_next_nvpair(spa->spa_label_features,
2555 NULL); nvp != NULL;
2556 nvp = nvlist_next_nvpair(spa->spa_label_features, nvp)) {
2557 if (!zfeature_is_supported(nvpair_name(nvp))) {
2558 VERIFY(nvlist_add_string(unsup_feat,
2559 nvpair_name(nvp), "") == 0);
2560 }
2561 }
2562
2563 if (!nvlist_empty(unsup_feat)) {
2564 VERIFY(nvlist_add_nvlist(spa->spa_load_info,
2565 ZPOOL_CONFIG_UNSUP_FEAT, unsup_feat) == 0);
2566 nvlist_free(unsup_feat);
2567 return (spa_vdev_err(rvd, VDEV_AUX_UNSUP_FEAT,
2568 ENOTSUP));
2569 }
2570
2571 nvlist_free(unsup_feat);
2572 }
2573
2574 /*
2575 * If the vdev guid sum doesn't match the uberblock, we have an
2576 * incomplete configuration. We first check to see if the pool
2577 * is aware of the complete config (i.e ZPOOL_CONFIG_VDEV_CHILDREN).
2578 * If it is, defer the vdev_guid_sum check till later so we
2579 * can handle missing vdevs.
2580 */
2581 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_VDEV_CHILDREN,
2582 &children) != 0 && mosconfig && type != SPA_IMPORT_ASSEMBLE &&
2583 rvd->vdev_guid_sum != ub->ub_guid_sum)
2584 return (spa_vdev_err(rvd, VDEV_AUX_BAD_GUID_SUM, ENXIO));
2585
2586 if (type != SPA_IMPORT_ASSEMBLE && spa->spa_config_splitting) {
2587 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2588 spa_try_repair(spa, config);
2589 spa_config_exit(spa, SCL_ALL, FTAG);
2590 nvlist_free(spa->spa_config_splitting);
2591 spa->spa_config_splitting = NULL;
2592 }
2593
2594 /*
2595 * Initialize internal SPA structures.
2596 */
2597 spa->spa_state = POOL_STATE_ACTIVE;
2598 spa->spa_ubsync = spa->spa_uberblock;
2599 spa->spa_verify_min_txg = spa->spa_extreme_rewind ?
2600 TXG_INITIAL - 1 : spa_last_synced_txg(spa) - TXG_DEFER_SIZE - 1;
2601 spa->spa_first_txg = spa->spa_last_ubsync_txg ?
2602 spa->spa_last_ubsync_txg : spa_last_synced_txg(spa) + 1;
2603 spa->spa_claim_max_txg = spa->spa_first_txg;
2604 spa->spa_prev_software_version = ub->ub_software_version;
2605
2606 error = dsl_pool_init(spa, spa->spa_first_txg, &spa->spa_dsl_pool);
2607 if (error)
2608 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2609 spa->spa_meta_objset = spa->spa_dsl_pool->dp_meta_objset;
2610
2611 if (spa_dir_prop(spa, DMU_POOL_CONFIG, &spa->spa_config_object) != 0)
2612 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2613
2614 if (spa_version(spa) >= SPA_VERSION_FEATURES) {
2615 boolean_t missing_feat_read = B_FALSE;
2616 nvlist_t *unsup_feat, *enabled_feat;
2617
2618 if (spa_dir_prop(spa, DMU_POOL_FEATURES_FOR_READ,
2619 &spa->spa_feat_for_read_obj) != 0) {
2620 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2621 }
2622
2623 if (spa_dir_prop(spa, DMU_POOL_FEATURES_FOR_WRITE,
2624 &spa->spa_feat_for_write_obj) != 0) {
2625 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2626 }
2627
2628 if (spa_dir_prop(spa, DMU_POOL_FEATURE_DESCRIPTIONS,
2629 &spa->spa_feat_desc_obj) != 0) {
2630 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2631 }
2632
2633 enabled_feat = fnvlist_alloc();
2634 unsup_feat = fnvlist_alloc();
2635
2636 if (!spa_features_check(spa, B_FALSE,
2637 unsup_feat, enabled_feat))
2638 missing_feat_read = B_TRUE;
2639
2640 if (spa_writeable(spa) || state == SPA_LOAD_TRYIMPORT) {
2641 if (!spa_features_check(spa, B_TRUE,
2642 unsup_feat, enabled_feat)) {
2643 missing_feat_write = B_TRUE;
2644 }
2645 }
2646
2647 fnvlist_add_nvlist(spa->spa_load_info,
2648 ZPOOL_CONFIG_ENABLED_FEAT, enabled_feat);
2649
2650 if (!nvlist_empty(unsup_feat)) {
2651 fnvlist_add_nvlist(spa->spa_load_info,
2652 ZPOOL_CONFIG_UNSUP_FEAT, unsup_feat);
2653 }
2654
2655 fnvlist_free(enabled_feat);
2656 fnvlist_free(unsup_feat);
2657
2658 if (!missing_feat_read) {
2659 fnvlist_add_boolean(spa->spa_load_info,
2660 ZPOOL_CONFIG_CAN_RDONLY);
2661 }
2662
2663 /*
2664 * If the state is SPA_LOAD_TRYIMPORT, our objective is
2665 * twofold: to determine whether the pool is available for
2666 * import in read-write mode and (if it is not) whether the
2667 * pool is available for import in read-only mode. If the pool
2668 * is available for import in read-write mode, it is displayed
2669 * as available in userland; if it is not available for import
2670 * in read-only mode, it is displayed as unavailable in
2671 * userland. If the pool is available for import in read-only
2672 * mode but not read-write mode, it is displayed as unavailable
2673 * in userland with a special note that the pool is actually
2674 * available for open in read-only mode.
2675 *
2676 * As a result, if the state is SPA_LOAD_TRYIMPORT and we are
2677 * missing a feature for write, we must first determine whether
2678 * the pool can be opened read-only before returning to
2679 * userland in order to know whether to display the
2680 * abovementioned note.
2681 */
2682 if (missing_feat_read || (missing_feat_write &&
2683 spa_writeable(spa))) {
2684 return (spa_vdev_err(rvd, VDEV_AUX_UNSUP_FEAT,
2685 ENOTSUP));
2686 }
2687
2688 /*
2689 * Load refcounts for ZFS features from disk into an in-memory
2690 * cache during SPA initialization.
2691 */
2692 for (spa_feature_t i = 0; i < SPA_FEATURES; i++) {
2693 uint64_t refcount;
2694
2695 error = feature_get_refcount_from_disk(spa,
2696 &spa_feature_table[i], &refcount);
2697 if (error == 0) {
2698 spa->spa_feat_refcount_cache[i] = refcount;
2699 } else if (error == ENOTSUP) {
2700 spa->spa_feat_refcount_cache[i] =
2701 SPA_FEATURE_DISABLED;
2702 } else {
2703 return (spa_vdev_err(rvd,
2704 VDEV_AUX_CORRUPT_DATA, EIO));
2705 }
2706 }
2707 }
2708
2709 if (spa_feature_is_active(spa, SPA_FEATURE_ENABLED_TXG)) {
2710 if (spa_dir_prop(spa, DMU_POOL_FEATURE_ENABLED_TXG,
2711 &spa->spa_feat_enabled_txg_obj) != 0)
2712 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2713 }
2714
2715 spa->spa_is_initializing = B_TRUE;
2716 error = dsl_pool_open(spa->spa_dsl_pool);
2717 spa->spa_is_initializing = B_FALSE;
2718 if (error != 0)
2719 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2720
2721 if (!mosconfig) {
2722 uint64_t hostid;
2723 nvlist_t *policy = NULL, *nvconfig;
2724
2725 if (load_nvlist(spa, spa->spa_config_object, &nvconfig) != 0)
2726 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2727
2728 if (!spa_is_root(spa) && nvlist_lookup_uint64(nvconfig,
2729 ZPOOL_CONFIG_HOSTID, &hostid) == 0) {
2730 char *hostname;
2731 unsigned long myhostid = 0;
2732
2733 VERIFY(nvlist_lookup_string(nvconfig,
2734 ZPOOL_CONFIG_HOSTNAME, &hostname) == 0);
2735
2736 #ifdef _KERNEL
2737 myhostid = zone_get_hostid(NULL);
2738 #else /* _KERNEL */
2739 /*
2740 * We're emulating the system's hostid in userland, so
2741 * we can't use zone_get_hostid().
2742 */
2743 (void) ddi_strtoul(hw_serial, NULL, 10, &myhostid);
2744 #endif /* _KERNEL */
2745 if (hostid != 0 && myhostid != 0 &&
2746 hostid != myhostid) {
2747 nvlist_free(nvconfig);
2748 cmn_err(CE_WARN, "pool '%s' could not be "
2749 "loaded as it was last accessed by "
2750 "another system (host: %s hostid: 0x%lx). "
2751 "See: http://illumos.org/msg/ZFS-8000-EY",
2752 spa_name(spa), hostname,
2753 (unsigned long)hostid);
2754 return (SET_ERROR(EBADF));
2755 }
2756 }
2757 if (nvlist_lookup_nvlist(spa->spa_config,
2758 ZPOOL_REWIND_POLICY, &policy) == 0)
2759 VERIFY(nvlist_add_nvlist(nvconfig,
2760 ZPOOL_REWIND_POLICY, policy) == 0);
2761
2762 spa_config_set(spa, nvconfig);
2763 spa_unload(spa);
2764 spa_deactivate(spa);
2765 spa_activate(spa, orig_mode);
2766
2767 return (spa_load(spa, state, SPA_IMPORT_EXISTING, B_TRUE));
2768 }
2769
2770 /* Grab the secret checksum salt from the MOS. */
2771 error = zap_lookup(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
2772 DMU_POOL_CHECKSUM_SALT, 1,
2773 sizeof (spa->spa_cksum_salt.zcs_bytes),
2774 spa->spa_cksum_salt.zcs_bytes);
2775 if (error == ENOENT) {
2776 /* Generate a new salt for subsequent use */
2777 (void) random_get_pseudo_bytes(spa->spa_cksum_salt.zcs_bytes,
2778 sizeof (spa->spa_cksum_salt.zcs_bytes));
2779 } else if (error != 0) {
2780 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2781 }
2782
2783 if (spa_dir_prop(spa, DMU_POOL_SYNC_BPOBJ, &obj) != 0)
2784 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2785 error = bpobj_open(&spa->spa_deferred_bpobj, spa->spa_meta_objset, obj);
2786 if (error != 0)
2787 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2788
2789 /*
2790 * Load the bit that tells us to use the new accounting function
2791 * (raid-z deflation). If we have an older pool, this will not
2792 * be present.
2793 */
2794 error = spa_dir_prop(spa, DMU_POOL_DEFLATE, &spa->spa_deflate);
2795 if (error != 0 && error != ENOENT)
2796 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2797
2798 error = spa_dir_prop(spa, DMU_POOL_CREATION_VERSION,
2799 &spa->spa_creation_version);
2800 if (error != 0 && error != ENOENT)
2801 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2802
2803 /*
2804 * Load the persistent error log. If we have an older pool, this will
2805 * not be present.
2806 */
2807 error = spa_dir_prop(spa, DMU_POOL_ERRLOG_LAST, &spa->spa_errlog_last);
2808 if (error != 0 && error != ENOENT)
2809 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2810
2811 error = spa_dir_prop(spa, DMU_POOL_ERRLOG_SCRUB,
2812 &spa->spa_errlog_scrub);
2813 if (error != 0 && error != ENOENT)
2814 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2815
2816 /*
2817 * Load the history object. If we have an older pool, this
2818 * will not be present.
2819 */
2820 error = spa_dir_prop(spa, DMU_POOL_HISTORY, &spa->spa_history);
2821 if (error != 0 && error != ENOENT)
2822 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2823
2824 /*
2825 * Load the per-vdev ZAP map. If we have an older pool, this will not
2826 * be present; in this case, defer its creation to a later time to
2827 * avoid dirtying the MOS this early / out of sync context. See
2828 * spa_sync_config_object.
2829 */
2830
2831 /* The sentinel is only available in the MOS config. */
2832 nvlist_t *mos_config;
2833 if (load_nvlist(spa, spa->spa_config_object, &mos_config) != 0)
2834 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2835
2836 error = spa_dir_prop(spa, DMU_POOL_VDEV_ZAP_MAP,
2837 &spa->spa_all_vdev_zaps);
2838
2839 if (error == ENOENT) {
2840 VERIFY(!nvlist_exists(mos_config,
2841 ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS));
2842 spa->spa_avz_action = AVZ_ACTION_INITIALIZE;
2843 ASSERT0(vdev_count_verify_zaps(spa->spa_root_vdev));
2844 } else if (error != 0) {
2845 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2846 } else if (!nvlist_exists(mos_config, ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS)) {
2847 /*
2848 * An older version of ZFS overwrote the sentinel value, so
2849 * we have orphaned per-vdev ZAPs in the MOS. Defer their
2850 * destruction to later; see spa_sync_config_object.
2851 */
2852 spa->spa_avz_action = AVZ_ACTION_DESTROY;
2853 /*
2854 * We're assuming that no vdevs have had their ZAPs created
2855 * before this. Better be sure of it.
2856 */
2857 ASSERT0(vdev_count_verify_zaps(spa->spa_root_vdev));
2858 }
2859 nvlist_free(mos_config);
2860
2861 /*
2862 * If we're assembling the pool from the split-off vdevs of
2863 * an existing pool, we don't want to attach the spares & cache
2864 * devices.
2865 */
2866
2867 /*
2868 * Load any hot spares for this pool.
2869 */
2870 error = spa_dir_prop(spa, DMU_POOL_SPARES, &spa->spa_spares.sav_object);
2871 if (error != 0 && error != ENOENT)
2872 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2873 if (error == 0 && type != SPA_IMPORT_ASSEMBLE) {
2874 ASSERT(spa_version(spa) >= SPA_VERSION_SPARES);
2875 if (load_nvlist(spa, spa->spa_spares.sav_object,
2876 &spa->spa_spares.sav_config) != 0)
2877 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2878
2879 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2880 spa_load_spares(spa);
2881 spa_config_exit(spa, SCL_ALL, FTAG);
2882 } else if (error == 0) {
2883 spa->spa_spares.sav_sync = B_TRUE;
2884 }
2885
2886 /*
2887 * Load any level 2 ARC devices for this pool.
2888 */
2889 error = spa_dir_prop(spa, DMU_POOL_L2CACHE,
2890 &spa->spa_l2cache.sav_object);
2891 if (error != 0 && error != ENOENT)
2892 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2893 if (error == 0 && type != SPA_IMPORT_ASSEMBLE) {
2894 ASSERT(spa_version(spa) >= SPA_VERSION_L2CACHE);
2895 if (load_nvlist(spa, spa->spa_l2cache.sav_object,
2896 &spa->spa_l2cache.sav_config) != 0)
2897 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2898
2899 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2900 spa_load_l2cache(spa);
2901 spa_config_exit(spa, SCL_ALL, FTAG);
2902 } else if (error == 0) {
2903 spa->spa_l2cache.sav_sync = B_TRUE;
2904 }
2905
2906 mp = &spa->spa_meta_policy;
2907
2908 spa->spa_delegation = zpool_prop_default_numeric(ZPOOL_PROP_DELEGATION);
2909 spa->spa_hiwat = zpool_prop_default_numeric(ZPOOL_PROP_HIWATERMARK);
2910 spa->spa_lowat = zpool_prop_default_numeric(ZPOOL_PROP_LOWATERMARK);
2911 spa->spa_minwat = zpool_prop_default_numeric(ZPOOL_PROP_MINWATERMARK);
2912 spa->spa_dedup_lo_best_effort =
2913 zpool_prop_default_numeric(ZPOOL_PROP_DEDUP_LO_BEST_EFFORT);
2914 spa->spa_dedup_hi_best_effort =
2915 zpool_prop_default_numeric(ZPOOL_PROP_DEDUP_HI_BEST_EFFORT);
2916
2917 mp->spa_enable_meta_placement_selection =
2918 zpool_prop_default_numeric(ZPOOL_PROP_META_PLACEMENT);
2919 mp->spa_sync_to_special =
2920 zpool_prop_default_numeric(ZPOOL_PROP_SYNC_TO_SPECIAL);
2921 mp->spa_ddt_meta_to_special =
2922 zpool_prop_default_numeric(ZPOOL_PROP_DDT_META_TO_METADEV);
2923 mp->spa_zfs_meta_to_special =
2924 zpool_prop_default_numeric(ZPOOL_PROP_ZFS_META_TO_METADEV);
2925 mp->spa_small_data_to_special =
2926 zpool_prop_default_numeric(ZPOOL_PROP_SMALL_DATA_TO_METADEV);
2927 spa_set_ddt_classes(spa,
2928 zpool_prop_default_numeric(ZPOOL_PROP_DDT_DESEGREGATION));
2929
2930 spa->spa_resilver_prio =
2931 zpool_prop_default_numeric(ZPOOL_PROP_RESILVER_PRIO);
2932 spa->spa_scrub_prio = zpool_prop_default_numeric(ZPOOL_PROP_SCRUB_PRIO);
2933
2934 error = spa_dir_prop(spa, DMU_POOL_PROPS, &spa->spa_pool_props_object);
2935 if (error && error != ENOENT)
2936 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
2937
2938 if (error == 0) {
2939 uint64_t autoreplace;
2940 uint64_t val = 0;
2941
2942 spa_prop_find(spa, ZPOOL_PROP_BOOTFS, &spa->spa_bootfs);
2943 spa_prop_find(spa, ZPOOL_PROP_AUTOREPLACE, &autoreplace);
2944 spa_prop_find(spa, ZPOOL_PROP_DELEGATION, &spa->spa_delegation);
2945 spa_prop_find(spa, ZPOOL_PROP_FAILUREMODE, &spa->spa_failmode);
2946 spa_prop_find(spa, ZPOOL_PROP_AUTOEXPAND, &spa->spa_autoexpand);
2947 spa_prop_find(spa, ZPOOL_PROP_BOOTSIZE, &spa->spa_bootsize);
2948 spa_prop_find(spa, ZPOOL_PROP_DEDUPDITTO,
2949 &spa->spa_dedup_ditto);
2950 spa_prop_find(spa, ZPOOL_PROP_FORCETRIM, &spa->spa_force_trim);
2951
2952 mutex_enter(&spa->spa_auto_trim_lock);
2953 spa_prop_find(spa, ZPOOL_PROP_AUTOTRIM, &spa->spa_auto_trim);
2954 if (spa->spa_auto_trim == SPA_AUTO_TRIM_ON)
2955 spa_auto_trim_taskq_create(spa);
2956 mutex_exit(&spa->spa_auto_trim_lock);
2957
2958 spa_prop_find(spa, ZPOOL_PROP_HIWATERMARK, &spa->spa_hiwat);
2959 spa_prop_find(spa, ZPOOL_PROP_LOWATERMARK, &spa->spa_lowat);
2960 spa_prop_find(spa, ZPOOL_PROP_MINWATERMARK, &spa->spa_minwat);
2961 spa_prop_find(spa, ZPOOL_PROP_DEDUPMETA_DITTO,
2962 &spa->spa_ddt_meta_copies);
2963 spa_prop_find(spa, ZPOOL_PROP_DDT_DESEGREGATION, &val);
2964 spa_set_ddt_classes(spa, val);
2965
2966 spa_prop_find(spa, ZPOOL_PROP_RESILVER_PRIO,
2967 &spa->spa_resilver_prio);
2968 spa_prop_find(spa, ZPOOL_PROP_SCRUB_PRIO,
2969 &spa->spa_scrub_prio);
2970
2971 spa_prop_find(spa, ZPOOL_PROP_DEDUP_BEST_EFFORT,
2972 &spa->spa_dedup_best_effort);
2973 spa_prop_find(spa, ZPOOL_PROP_DEDUP_LO_BEST_EFFORT,
2974 &spa->spa_dedup_lo_best_effort);
2975 spa_prop_find(spa, ZPOOL_PROP_DEDUP_HI_BEST_EFFORT,
2976 &spa->spa_dedup_hi_best_effort);
2977
2978 spa_prop_find(spa, ZPOOL_PROP_META_PLACEMENT,
2979 &mp->spa_enable_meta_placement_selection);
2980 spa_prop_find(spa, ZPOOL_PROP_SYNC_TO_SPECIAL,
2981 &mp->spa_sync_to_special);
2982 spa_prop_find(spa, ZPOOL_PROP_DDT_META_TO_METADEV,
2983 &mp->spa_ddt_meta_to_special);
2984 spa_prop_find(spa, ZPOOL_PROP_ZFS_META_TO_METADEV,
2985 &mp->spa_zfs_meta_to_special);
2986 spa_prop_find(spa, ZPOOL_PROP_SMALL_DATA_TO_METADEV,
2987 &mp->spa_small_data_to_special);
2988
2989 spa->spa_autoreplace = (autoreplace != 0);
2990 }
2991
2992 error = spa_dir_prop(spa, DMU_POOL_COS_PROPS,
2993 &spa->spa_cos_props_object);
2994 if (error == 0)
2995 (void) spa_load_cos_props(spa);
2996 error = spa_dir_prop(spa, DMU_POOL_VDEV_PROPS,
2997 &spa->spa_vdev_props_object);
2998 if (error == 0)
2999 (void) spa_load_vdev_props(spa);
3000
3001 (void) spa_dir_prop(spa, DMU_POOL_TRIM_START_TIME,
3002 &spa->spa_man_trim_start_time);
3003 (void) spa_dir_prop(spa, DMU_POOL_TRIM_STOP_TIME,
3004 &spa->spa_man_trim_stop_time);
3005
3006 /*
3007 * If the 'autoreplace' property is set, then post a resource notifying
3008 * the ZFS DE that it should not issue any faults for unopenable
3009 * devices. We also iterate over the vdevs, and post a sysevent for any
3010 * unopenable vdevs so that the normal autoreplace handler can take
3011 * over.
3012 */
3013 if (spa->spa_autoreplace && state != SPA_LOAD_TRYIMPORT) {
3014 spa_check_removed(spa->spa_root_vdev);
3015 /*
3016 * For the import case, this is done in spa_import(), because
3017 * at this point we're using the spare definitions from
3018 * the MOS config, not necessarily from the userland config.
3019 */
3020 if (state != SPA_LOAD_IMPORT) {
3021 spa_aux_check_removed(&spa->spa_spares);
3022 spa_aux_check_removed(&spa->spa_l2cache);
3023 }
3024 }
3025
3026 /*
3027 * Load the vdev state for all toplevel vdevs.
3028 */
3029 vdev_load(rvd);
3030
3031 /*
3032 * Propagate the leaf DTLs we just loaded all the way up the tree.
3033 */
3034 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3035 vdev_dtl_reassess(rvd, 0, 0, B_FALSE);
3036 spa_config_exit(spa, SCL_ALL, FTAG);
3037
3038 /*
3039 * Load the DDTs (dedup tables).
3040 */
3041 error = ddt_load(spa);
3042 if (error != 0)
3043 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3044
3045 spa_update_dspace(spa);
3046
3047 /*
3048 * Validate the config, using the MOS config to fill in any
3049 * information which might be missing. If we fail to validate
3050 * the config then declare the pool unfit for use. If we're
3051 * assembling a pool from a split, the log is not transferred
3052 * over.
3053 */
3054 if (type != SPA_IMPORT_ASSEMBLE) {
3055 nvlist_t *nvconfig;
3056
3057 if (load_nvlist(spa, spa->spa_config_object, &nvconfig) != 0)
3058 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA, EIO));
3059
3060 if (!spa_config_valid(spa, nvconfig)) {
3061 nvlist_free(nvconfig);
3062 return (spa_vdev_err(rvd, VDEV_AUX_BAD_GUID_SUM,
3063 ENXIO));
3064 }
3065 nvlist_free(nvconfig);
3066
3067 /*
3068 * Now that we've validated the config, check the state of the
3069 * root vdev. If it can't be opened, it indicates one or
3070 * more toplevel vdevs are faulted.
3071 */
3072 if (rvd->vdev_state <= VDEV_STATE_CANT_OPEN)
3073 return (SET_ERROR(ENXIO));
3074
3075 if (spa_writeable(spa) && spa_check_logs(spa)) {
3076 *ereport = FM_EREPORT_ZFS_LOG_REPLAY;
3077 return (spa_vdev_err(rvd, VDEV_AUX_BAD_LOG, ENXIO));
3078 }
3079 }
3080
3081 if (missing_feat_write) {
3082 ASSERT(state == SPA_LOAD_TRYIMPORT);
3083
3084 /*
3085 * At this point, we know that we can open the pool in
3086 * read-only mode but not read-write mode. We now have enough
3087 * information and can return to userland.
3088 */
3089 return (spa_vdev_err(rvd, VDEV_AUX_UNSUP_FEAT, ENOTSUP));
3090 }
3091
3092 /*
3093 * We've successfully opened the pool, verify that we're ready
3094 * to start pushing transactions.
3095 */
3096 if (state != SPA_LOAD_TRYIMPORT) {
3097 if (error = spa_load_verify(spa)) {
3098 return (spa_vdev_err(rvd, VDEV_AUX_CORRUPT_DATA,
3099 error));
3100 }
3101 }
3102
3103 if (spa_writeable(spa) && (state == SPA_LOAD_RECOVER ||
3104 spa->spa_load_max_txg == UINT64_MAX)) {
3105 dmu_tx_t *tx;
3106 int need_update = B_FALSE;
3107 dsl_pool_t *dp = spa_get_dsl(spa);
3108
3109 ASSERT(state != SPA_LOAD_TRYIMPORT);
3110
3111 /*
3112 * Claim log blocks that haven't been committed yet.
3113 * This must all happen in a single txg.
3114 * Note: spa_claim_max_txg is updated by spa_claim_notify(),
3115 * invoked from zil_claim_log_block()'s i/o done callback.
3116 * Price of rollback is that we abandon the log.
3117 */
3118 spa->spa_claiming = B_TRUE;
3119
3120 tx = dmu_tx_create_assigned(dp, spa_first_txg(spa));
3121 (void) dmu_objset_find_dp(dp, dp->dp_root_dir_obj,
3122 zil_claim, tx, DS_FIND_CHILDREN);
3123 dmu_tx_commit(tx);
3124
3125 spa->spa_claiming = B_FALSE;
3126
3127 spa_set_log_state(spa, SPA_LOG_GOOD);
3128 spa->spa_sync_on = B_TRUE;
3129 txg_sync_start(spa->spa_dsl_pool);
3130
3131 /*
3132 * Wait for all claims to sync. We sync up to the highest
3133 * claimed log block birth time so that claimed log blocks
3134 * don't appear to be from the future. spa_claim_max_txg
3135 * will have been set for us by either zil_check_log_chain()
3136 * (invoked from spa_check_logs()) or zil_claim() above.
3137 */
3138 txg_wait_synced(spa->spa_dsl_pool, spa->spa_claim_max_txg);
3139
3140 /*
3141 * If the config cache is stale, or we have uninitialized
3142 * metaslabs (see spa_vdev_add()), then update the config.
3143 *
3144 * If this is a verbatim import, trust the current
3145 * in-core spa_config and update the disk labels.
3146 */
3147 if (config_cache_txg != spa->spa_config_txg ||
3148 state == SPA_LOAD_IMPORT ||
3149 state == SPA_LOAD_RECOVER ||
3150 (spa->spa_import_flags & ZFS_IMPORT_VERBATIM))
3151 need_update = B_TRUE;
3152
3153 for (int c = 0; c < rvd->vdev_children; c++)
3154 if (rvd->vdev_child[c]->vdev_ms_array == 0)
3155 need_update = B_TRUE;
3156
3157 /*
3158 * Update the config cache asychronously in case we're the
3159 * root pool, in which case the config cache isn't writable yet.
3160 */
3161 if (need_update)
3162 spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
3163
3164 /*
3165 * Check all DTLs to see if anything needs resilvering.
3166 */
3167 if (!dsl_scan_resilvering(spa->spa_dsl_pool) &&
3168 vdev_resilver_needed(rvd, NULL, NULL))
3169 spa_async_request(spa, SPA_ASYNC_RESILVER);
3170
3171 /*
3172 * Log the fact that we booted up (so that we can detect if
3173 * we rebooted in the middle of an operation).
3174 */
3175 spa_history_log_version(spa, "open");
3176
3177 dsl_destroy_inconsistent(spa_get_dsl(spa));
3178
3179 /*
3180 * Clean up any stale temporary dataset userrefs.
3181 */
3182 dsl_pool_clean_tmp_userrefs(spa->spa_dsl_pool);
3183 }
3184
3185 spa_async_request(spa, SPA_ASYNC_L2CACHE_REBUILD);
3186
3187 return (0);
3188 }
3189
3190 static int
3191 spa_load_retry(spa_t *spa, spa_load_state_t state, int mosconfig)
3192 {
3193 int mode = spa->spa_mode;
3194
3195 spa_unload(spa);
3196 spa_deactivate(spa);
3197
3198 spa->spa_load_max_txg = spa->spa_uberblock.ub_txg - 1;
3199
3200 spa_activate(spa, mode);
3201 spa_async_suspend(spa);
3202
3203 return (spa_load(spa, state, SPA_IMPORT_EXISTING, mosconfig));
3204 }
3205
3206 /*
3207 * If spa_load() fails this function will try loading prior txg's. If
3208 * 'state' is SPA_LOAD_RECOVER and one of these loads succeeds the pool
3209 * will be rewound to that txg. If 'state' is not SPA_LOAD_RECOVER this
3210 * function will not rewind the pool and will return the same error as
3211 * spa_load().
3212 */
3213 static int
3214 spa_load_best(spa_t *spa, spa_load_state_t state, int mosconfig,
3215 uint64_t max_request, int rewind_flags)
3216 {
3217 nvlist_t *loadinfo = NULL;
3218 nvlist_t *config = NULL;
3219 int load_error, rewind_error;
3220 uint64_t safe_rewind_txg;
3221 uint64_t min_txg;
3222
3223 if (spa->spa_load_txg && state == SPA_LOAD_RECOVER) {
3224 spa->spa_load_max_txg = spa->spa_load_txg;
3225 spa_set_log_state(spa, SPA_LOG_CLEAR);
3226 } else {
3227 spa->spa_load_max_txg = max_request;
3228 if (max_request != UINT64_MAX)
3229 spa->spa_extreme_rewind = B_TRUE;
3230 }
3231
3232 load_error = rewind_error = spa_load(spa, state, SPA_IMPORT_EXISTING,
3233 mosconfig);
3234 if (load_error == 0)
3235 return (0);
3236
3237 if (spa->spa_root_vdev != NULL)
3238 config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
3239
3240 spa->spa_last_ubsync_txg = spa->spa_uberblock.ub_txg;
3241 spa->spa_last_ubsync_txg_ts = spa->spa_uberblock.ub_timestamp;
3242
3243 if (rewind_flags & ZPOOL_NEVER_REWIND) {
3244 nvlist_free(config);
3245 return (load_error);
3246 }
3247
3248 if (state == SPA_LOAD_RECOVER) {
3249 /* Price of rolling back is discarding txgs, including log */
3250 spa_set_log_state(spa, SPA_LOG_CLEAR);
3251 } else {
3252 /*
3253 * If we aren't rolling back save the load info from our first
3254 * import attempt so that we can restore it after attempting
3255 * to rewind.
3256 */
3257 loadinfo = spa->spa_load_info;
3258 spa->spa_load_info = fnvlist_alloc();
3259 }
3260
3261 spa->spa_load_max_txg = spa->spa_last_ubsync_txg;
3262 safe_rewind_txg = spa->spa_last_ubsync_txg - TXG_DEFER_SIZE;
3263 min_txg = (rewind_flags & ZPOOL_EXTREME_REWIND) ?
3264 TXG_INITIAL : safe_rewind_txg;
3265
3266 /*
3267 * Continue as long as we're finding errors, we're still within
3268 * the acceptable rewind range, and we're still finding uberblocks
3269 */
3270 while (rewind_error && spa->spa_uberblock.ub_txg >= min_txg &&
3271 spa->spa_uberblock.ub_txg <= spa->spa_load_max_txg) {
3272 if (spa->spa_load_max_txg < safe_rewind_txg)
3273 spa->spa_extreme_rewind = B_TRUE;
3274 rewind_error = spa_load_retry(spa, state, mosconfig);
3275 }
3276
3277 spa->spa_extreme_rewind = B_FALSE;
3278 spa->spa_load_max_txg = UINT64_MAX;
3279
3280 if (config && (rewind_error || state != SPA_LOAD_RECOVER))
3281 spa_config_set(spa, config);
3282 else
3283 nvlist_free(config);
3284
3285 if (state == SPA_LOAD_RECOVER) {
3286 ASSERT3P(loadinfo, ==, NULL);
3287 return (rewind_error);
3288 } else {
3289 /* Store the rewind info as part of the initial load info */
3290 fnvlist_add_nvlist(loadinfo, ZPOOL_CONFIG_REWIND_INFO,
3291 spa->spa_load_info);
3292
3293 /* Restore the initial load info */
3294 fnvlist_free(spa->spa_load_info);
3295 spa->spa_load_info = loadinfo;
3296
3297 return (load_error);
3298 }
3299 }
3300
3301 /*
3302 * Pool Open/Import
3303 *
3304 * The import case is identical to an open except that the configuration is sent
3305 * down from userland, instead of grabbed from the configuration cache. For the
3306 * case of an open, the pool configuration will exist in the
3307 * POOL_STATE_UNINITIALIZED state.
3308 *
3309 * The stats information (gen/count/ustats) is used to gather vdev statistics at
3310 * the same time open the pool, without having to keep around the spa_t in some
3311 * ambiguous state.
3312 */
3313 static int
3314 spa_open_common(const char *pool, spa_t **spapp, void *tag, nvlist_t *nvpolicy,
3315 nvlist_t **config)
3316 {
3317 spa_t *spa;
3318 spa_load_state_t state = SPA_LOAD_OPEN;
3319 int error;
3320 int locked = B_FALSE;
3321 boolean_t open_with_activation = B_FALSE;
3322
3323 *spapp = NULL;
3324
3325 /*
3326 * As disgusting as this is, we need to support recursive calls to this
3327 * function because dsl_dir_open() is called during spa_load(), and ends
3328 * up calling spa_open() again. The real fix is to figure out how to
3329 * avoid dsl_dir_open() calling this in the first place.
3330 */
3331 if (mutex_owner(&spa_namespace_lock) != curthread) {
3332 mutex_enter(&spa_namespace_lock);
3333 locked = B_TRUE;
3334 }
3335
3336 if ((spa = spa_lookup(pool)) == NULL) {
3337 if (locked)
3338 mutex_exit(&spa_namespace_lock);
3339 return (SET_ERROR(ENOENT));
3340 }
3341
3342 if (spa->spa_state == POOL_STATE_UNINITIALIZED) {
3343 zpool_rewind_policy_t policy;
3344
3345 zpool_get_rewind_policy(nvpolicy ? nvpolicy : spa->spa_config,
3346 &policy);
3347 if (policy.zrp_request & ZPOOL_DO_REWIND)
3348 state = SPA_LOAD_RECOVER;
3349
3350 spa_activate(spa, spa_mode_global);
3351
3352 if (state != SPA_LOAD_RECOVER)
3353 spa->spa_last_ubsync_txg = spa->spa_load_txg = 0;
3354
3355 error = spa_load_best(spa, state, B_FALSE, policy.zrp_txg,
3356 policy.zrp_request);
3357
3358 if (error == EBADF) {
3359 /*
3360 * If vdev_validate() returns failure (indicated by
3361 * EBADF), it indicates that one of the vdevs indicates
3362 * that the pool has been exported or destroyed. If
3363 * this is the case, the config cache is out of sync and
3364 * we should remove the pool from the namespace.
3365 */
3366 spa_unload(spa);
3367 spa_deactivate(spa);
3368 spa_config_sync(spa, B_TRUE, B_TRUE);
3369 spa_remove(spa);
3370 if (locked)
3371 mutex_exit(&spa_namespace_lock);
3372 return (SET_ERROR(ENOENT));
3373 }
3374
3375 if (error) {
3376 /*
3377 * We can't open the pool, but we still have useful
3378 * information: the state of each vdev after the
3379 * attempted vdev_open(). Return this to the user.
3380 */
3381 if (config != NULL && spa->spa_config) {
3382 VERIFY(nvlist_dup(spa->spa_config, config,
3383 KM_SLEEP) == 0);
3384 VERIFY(nvlist_add_nvlist(*config,
3385 ZPOOL_CONFIG_LOAD_INFO,
3386 spa->spa_load_info) == 0);
3387 }
3388 spa_unload(spa);
3389 spa_deactivate(spa);
3390 spa->spa_last_open_failed = error;
3391 if (locked)
3392 mutex_exit(&spa_namespace_lock);
3393 *spapp = NULL;
3394 return (error);
3395 }
3396
3397 open_with_activation = B_TRUE;
3398 }
3399
3400 spa_open_ref(spa, tag);
3401
3402 if (config != NULL)
3403 *config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
3404
3405 /*
3406 * If we've recovered the pool, pass back any information we
3407 * gathered while doing the load.
3408 */
3409 if (state == SPA_LOAD_RECOVER) {
3410 VERIFY(nvlist_add_nvlist(*config, ZPOOL_CONFIG_LOAD_INFO,
3411 spa->spa_load_info) == 0);
3412 }
3413
3414 if (locked) {
3415 spa->spa_last_open_failed = 0;
3416 spa->spa_last_ubsync_txg = 0;
3417 spa->spa_load_txg = 0;
3418 mutex_exit(&spa_namespace_lock);
3419 }
3420
3421 if (open_with_activation)
3422 wbc_activate(spa, B_FALSE);
3423
3424 *spapp = spa;
3425
3426 return (0);
3427 }
3428
3429 int
3430 spa_open_rewind(const char *name, spa_t **spapp, void *tag, nvlist_t *policy,
3431 nvlist_t **config)
3432 {
3433 return (spa_open_common(name, spapp, tag, policy, config));
3434 }
3435
3436 int
3437 spa_open(const char *name, spa_t **spapp, void *tag)
3438 {
3439 return (spa_open_common(name, spapp, tag, NULL, NULL));
3440 }
3441
3442 /*
3443 * Lookup the given spa_t, incrementing the inject count in the process,
3444 * preventing it from being exported or destroyed.
3445 */
3446 spa_t *
3447 spa_inject_addref(char *name)
3448 {
3449 spa_t *spa;
3450
3451 mutex_enter(&spa_namespace_lock);
3452 if ((spa = spa_lookup(name)) == NULL) {
3453 mutex_exit(&spa_namespace_lock);
3454 return (NULL);
3455 }
3456 spa->spa_inject_ref++;
3457 mutex_exit(&spa_namespace_lock);
3458
3459 return (spa);
3460 }
3461
3462 void
3463 spa_inject_delref(spa_t *spa)
3464 {
3465 mutex_enter(&spa_namespace_lock);
3466 spa->spa_inject_ref--;
3467 mutex_exit(&spa_namespace_lock);
3468 }
3469
3470 /*
3471 * Add spares device information to the nvlist.
3472 */
3473 static void
3474 spa_add_spares(spa_t *spa, nvlist_t *config)
3475 {
3476 nvlist_t **spares;
3477 uint_t i, nspares;
3478 nvlist_t *nvroot;
3479 uint64_t guid;
3480 vdev_stat_t *vs;
3481 uint_t vsc;
3482 uint64_t pool;
3483
3484 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
3485
3486 if (spa->spa_spares.sav_count == 0)
3487 return;
3488
3489 VERIFY(nvlist_lookup_nvlist(config,
3490 ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
3491 VERIFY(nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
3492 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
3493 if (nspares != 0) {
3494 VERIFY(nvlist_add_nvlist_array(nvroot,
3495 ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
3496 VERIFY(nvlist_lookup_nvlist_array(nvroot,
3497 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0);
3498
3499 /*
3500 * Go through and find any spares which have since been
3501 * repurposed as an active spare. If this is the case, update
3502 * their status appropriately.
3503 */
3504 for (i = 0; i < nspares; i++) {
3505 VERIFY(nvlist_lookup_uint64(spares[i],
3506 ZPOOL_CONFIG_GUID, &guid) == 0);
3507 if (spa_spare_exists(guid, &pool, NULL) &&
3508 pool != 0ULL) {
3509 VERIFY(nvlist_lookup_uint64_array(
3510 spares[i], ZPOOL_CONFIG_VDEV_STATS,
3511 (uint64_t **)&vs, &vsc) == 0);
3512 vs->vs_state = VDEV_STATE_CANT_OPEN;
3513 vs->vs_aux = VDEV_AUX_SPARED;
3514 }
3515 }
3516 }
3517 }
3518
3519 /*
3520 * Add l2cache device information to the nvlist, including vdev stats.
3521 */
3522 static void
3523 spa_add_l2cache(spa_t *spa, nvlist_t *config)
3524 {
3525 nvlist_t **l2cache;
3526 uint_t i, j, nl2cache;
3527 nvlist_t *nvroot;
3528 uint64_t guid;
3529 vdev_t *vd;
3530 vdev_stat_t *vs;
3531 uint_t vsc;
3532
3533 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
3534
3535 if (spa->spa_l2cache.sav_count == 0)
3536 return;
3537
3538 VERIFY(nvlist_lookup_nvlist(config,
3539 ZPOOL_CONFIG_VDEV_TREE, &nvroot) == 0);
3540 VERIFY(nvlist_lookup_nvlist_array(spa->spa_l2cache.sav_config,
3541 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
3542 if (nl2cache != 0) {
3543 VERIFY(nvlist_add_nvlist_array(nvroot,
3544 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
3545 VERIFY(nvlist_lookup_nvlist_array(nvroot,
3546 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0);
3547
3548 /*
3549 * Update level 2 cache device stats.
3550 */
3551
3552 for (i = 0; i < nl2cache; i++) {
3553 VERIFY(nvlist_lookup_uint64(l2cache[i],
3554 ZPOOL_CONFIG_GUID, &guid) == 0);
3555
3556 vd = NULL;
3557 for (j = 0; j < spa->spa_l2cache.sav_count; j++) {
3558 if (guid ==
3559 spa->spa_l2cache.sav_vdevs[j]->vdev_guid) {
3560 vd = spa->spa_l2cache.sav_vdevs[j];
3561 break;
3562 }
3563 }
3564 ASSERT(vd != NULL);
3565
3566 VERIFY(nvlist_lookup_uint64_array(l2cache[i],
3567 ZPOOL_CONFIG_VDEV_STATS, (uint64_t **)&vs, &vsc)
3568 == 0);
3569 vdev_get_stats(vd, vs);
3570 }
3571 }
3572 }
3573
3574 static void
3575 spa_add_feature_stats(spa_t *spa, nvlist_t *config)
3576 {
3577 nvlist_t *features;
3578 zap_cursor_t zc;
3579 zap_attribute_t za;
3580
3581 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
3582 VERIFY(nvlist_alloc(&features, NV_UNIQUE_NAME, KM_SLEEP) == 0);
3583
3584 if (spa->spa_feat_for_read_obj != 0) {
3585 for (zap_cursor_init(&zc, spa->spa_meta_objset,
3586 spa->spa_feat_for_read_obj);
3587 zap_cursor_retrieve(&zc, &za) == 0;
3588 zap_cursor_advance(&zc)) {
3589 ASSERT(za.za_integer_length == sizeof (uint64_t) &&
3590 za.za_num_integers == 1);
3591 VERIFY3U(0, ==, nvlist_add_uint64(features, za.za_name,
3592 za.za_first_integer));
3593 }
3594 zap_cursor_fini(&zc);
3595 }
3596
3597 if (spa->spa_feat_for_write_obj != 0) {
3598 for (zap_cursor_init(&zc, spa->spa_meta_objset,
3599 spa->spa_feat_for_write_obj);
3600 zap_cursor_retrieve(&zc, &za) == 0;
3601 zap_cursor_advance(&zc)) {
3602 ASSERT(za.za_integer_length == sizeof (uint64_t) &&
3603 za.za_num_integers == 1);
3604 VERIFY3U(0, ==, nvlist_add_uint64(features, za.za_name,
3605 za.za_first_integer));
3606 }
3607 zap_cursor_fini(&zc);
3608 }
3609
3610 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_FEATURE_STATS,
3611 features) == 0);
3612 nvlist_free(features);
3613 }
3614
3615 int
3616 spa_get_stats(const char *name, nvlist_t **config,
3617 char *altroot, size_t buflen)
3618 {
3619 int error;
3620 spa_t *spa;
3621
3622 *config = NULL;
3623 error = spa_open_common(name, &spa, FTAG, NULL, config);
3624
3625 if (spa != NULL) {
3626 /*
3627 * This still leaves a window of inconsistency where the spares
3628 * or l2cache devices could change and the config would be
3629 * self-inconsistent.
3630 */
3631 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
3632
3633 if (*config != NULL) {
3634 uint64_t loadtimes[2];
3635
3636 loadtimes[0] = spa->spa_loaded_ts.tv_sec;
3637 loadtimes[1] = spa->spa_loaded_ts.tv_nsec;
3638 VERIFY(nvlist_add_uint64_array(*config,
3639 ZPOOL_CONFIG_LOADED_TIME, loadtimes, 2) == 0);
3640
3641 VERIFY(nvlist_add_uint64(*config,
3642 ZPOOL_CONFIG_ERRCOUNT,
3643 spa_get_errlog_size(spa)) == 0);
3644
3645 if (spa_suspended(spa))
3646 VERIFY(nvlist_add_uint64(*config,
3647 ZPOOL_CONFIG_SUSPENDED,
3648 spa->spa_failmode) == 0);
3649
3650 spa_add_spares(spa, *config);
3651 spa_add_l2cache(spa, *config);
3652 spa_add_feature_stats(spa, *config);
3653 }
3654 }
3655
3656 /*
3657 * We want to get the alternate root even for faulted pools, so we cheat
3658 * and call spa_lookup() directly.
3659 */
3660 if (altroot) {
3661 if (spa == NULL) {
3662 mutex_enter(&spa_namespace_lock);
3663 spa = spa_lookup(name);
3664 if (spa)
3665 spa_altroot(spa, altroot, buflen);
3666 else
3667 altroot[0] = '\0';
3668 spa = NULL;
3669 mutex_exit(&spa_namespace_lock);
3670 } else {
3671 spa_altroot(spa, altroot, buflen);
3672 }
3673 }
3674
3675 if (spa != NULL) {
3676 spa_config_exit(spa, SCL_CONFIG, FTAG);
3677 spa_close(spa, FTAG);
3678 }
3679
3680 return (error);
3681 }
3682
3683 /*
3684 * Validate that the auxiliary device array is well formed. We must have an
3685 * array of nvlists, each which describes a valid leaf vdev. If this is an
3686 * import (mode is VDEV_ALLOC_SPARE), then we allow corrupted spares to be
3687 * specified, as long as they are well-formed.
3688 */
3689 static int
3690 spa_validate_aux_devs(spa_t *spa, nvlist_t *nvroot, uint64_t crtxg, int mode,
3691 spa_aux_vdev_t *sav, const char *config, uint64_t version,
3692 vdev_labeltype_t label)
3693 {
3694 nvlist_t **dev;
3695 uint_t i, ndev;
3696 vdev_t *vd;
3697 int error;
3698
3699 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
3700
3701 /*
3702 * It's acceptable to have no devs specified.
3703 */
3704 if (nvlist_lookup_nvlist_array(nvroot, config, &dev, &ndev) != 0)
3705 return (0);
3706
3707 if (ndev == 0)
3708 return (SET_ERROR(EINVAL));
3709
3710 /*
3711 * Make sure the pool is formatted with a version that supports this
3712 * device type.
3713 */
3714 if (spa_version(spa) < version)
3715 return (SET_ERROR(ENOTSUP));
3716
3717 /*
3718 * Set the pending device list so we correctly handle device in-use
3719 * checking.
3720 */
3721 sav->sav_pending = dev;
3722 sav->sav_npending = ndev;
3723
3724 for (i = 0; i < ndev; i++) {
3725 if ((error = spa_config_parse(spa, &vd, dev[i], NULL, 0,
3726 mode)) != 0)
3727 goto out;
3728
3729 if (!vd->vdev_ops->vdev_op_leaf) {
3730 vdev_free(vd);
3731 error = SET_ERROR(EINVAL);
3732 goto out;
3733 }
3734
3735 /*
3736 * The L2ARC currently only supports disk devices in
3737 * kernel context. For user-level testing, we allow it.
3738 */
3739 #ifdef _KERNEL
3740 if ((strcmp(config, ZPOOL_CONFIG_L2CACHE) == 0) &&
3741 strcmp(vd->vdev_ops->vdev_op_type, VDEV_TYPE_DISK) != 0) {
3742 error = SET_ERROR(ENOTBLK);
3743 vdev_free(vd);
3744 goto out;
3745 }
3746 #endif
3747 vd->vdev_top = vd;
3748
3749 if ((error = vdev_open(vd)) == 0 &&
3750 (error = vdev_label_init(vd, crtxg, label)) == 0) {
3751 VERIFY(nvlist_add_uint64(dev[i], ZPOOL_CONFIG_GUID,
3752 vd->vdev_guid) == 0);
3753 }
3754
3755 vdev_free(vd);
3756
3757 if (error &&
3758 (mode != VDEV_ALLOC_SPARE && mode != VDEV_ALLOC_L2CACHE))
3759 goto out;
3760 else
3761 error = 0;
3762 }
3763
3764 out:
3765 sav->sav_pending = NULL;
3766 sav->sav_npending = 0;
3767 return (error);
3768 }
3769
3770 static int
3771 spa_validate_aux(spa_t *spa, nvlist_t *nvroot, uint64_t crtxg, int mode)
3772 {
3773 int error;
3774
3775 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
3776
3777 if ((error = spa_validate_aux_devs(spa, nvroot, crtxg, mode,
3778 &spa->spa_spares, ZPOOL_CONFIG_SPARES, SPA_VERSION_SPARES,
3779 VDEV_LABEL_SPARE)) != 0) {
3780 return (error);
3781 }
3782
3783 return (spa_validate_aux_devs(spa, nvroot, crtxg, mode,
3784 &spa->spa_l2cache, ZPOOL_CONFIG_L2CACHE, SPA_VERSION_L2CACHE,
3785 VDEV_LABEL_L2CACHE));
3786 }
3787
3788 static void
3789 spa_set_aux_vdevs(spa_aux_vdev_t *sav, nvlist_t **devs, int ndevs,
3790 const char *config)
3791 {
3792 int i;
3793
3794 if (sav->sav_config != NULL) {
3795 nvlist_t **olddevs;
3796 uint_t oldndevs;
3797 nvlist_t **newdevs;
3798
3799 /*
3800 * Generate new dev list by concatentating with the
3801 * current dev list.
3802 */
3803 VERIFY(nvlist_lookup_nvlist_array(sav->sav_config, config,
3804 &olddevs, &oldndevs) == 0);
3805
3806 newdevs = kmem_alloc(sizeof (void *) *
3807 (ndevs + oldndevs), KM_SLEEP);
3808 for (i = 0; i < oldndevs; i++)
3809 VERIFY(nvlist_dup(olddevs[i], &newdevs[i],
3810 KM_SLEEP) == 0);
3811 for (i = 0; i < ndevs; i++)
3812 VERIFY(nvlist_dup(devs[i], &newdevs[i + oldndevs],
3813 KM_SLEEP) == 0);
3814
3815 VERIFY(nvlist_remove(sav->sav_config, config,
3816 DATA_TYPE_NVLIST_ARRAY) == 0);
3817
3818 VERIFY(nvlist_add_nvlist_array(sav->sav_config,
3819 config, newdevs, ndevs + oldndevs) == 0);
3820 for (i = 0; i < oldndevs + ndevs; i++)
3821 nvlist_free(newdevs[i]);
3822 kmem_free(newdevs, (oldndevs + ndevs) * sizeof (void *));
3823 } else {
3824 /*
3825 * Generate a new dev list.
3826 */
3827 VERIFY(nvlist_alloc(&sav->sav_config, NV_UNIQUE_NAME,
3828 KM_SLEEP) == 0);
3829 VERIFY(nvlist_add_nvlist_array(sav->sav_config, config,
3830 devs, ndevs) == 0);
3831 }
3832 }
3833
3834 /*
3835 * Stop and drop level 2 ARC devices
3836 */
3837 void
3838 spa_l2cache_drop(spa_t *spa)
3839 {
3840 vdev_t *vd;
3841 int i;
3842 spa_aux_vdev_t *sav = &spa->spa_l2cache;
3843
3844 for (i = 0; i < sav->sav_count; i++) {
3845 uint64_t pool;
3846
3847 vd = sav->sav_vdevs[i];
3848 ASSERT(vd != NULL);
3849
3850 if (spa_l2cache_exists(vd->vdev_guid, &pool) &&
3851 pool != 0ULL && l2arc_vdev_present(vd))
3852 l2arc_remove_vdev(vd);
3853 }
3854 }
3855
3856 /*
3857 * Pool Creation
3858 */
3859 int
3860 spa_create(const char *pool, nvlist_t *nvroot, nvlist_t *props,
3861 nvlist_t *zplprops)
3862 {
3863 spa_t *spa;
3864 char *altroot = NULL;
3865 vdev_t *rvd;
3866 dsl_pool_t *dp;
3867 dmu_tx_t *tx;
3868 int error = 0;
3869 uint64_t txg = TXG_INITIAL;
3870 nvlist_t **spares, **l2cache;
3871 uint_t nspares, nl2cache;
3872 uint64_t version, obj;
3873 boolean_t has_features = B_FALSE, wbc_feature_exists = B_FALSE;
3874 spa_meta_placement_t *mp;
3875
3876 /*
3877 * If this pool already exists, return failure.
3878 */
3879 mutex_enter(&spa_namespace_lock);
3880 if (spa_lookup(pool) != NULL) {
3881 mutex_exit(&spa_namespace_lock);
3882 return (SET_ERROR(EEXIST));
3883 }
3884
3885 /*
3886 * Allocate a new spa_t structure.
3887 */
3888 (void) nvlist_lookup_string(props,
3889 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
3890 spa = spa_add(pool, NULL, altroot);
3891 spa_activate(spa, spa_mode_global);
3892
3893 if (props != NULL) {
3894 nvpair_t *wbc_feature_nvp = NULL;
3895
3896 for (nvpair_t *elem = nvlist_next_nvpair(props, NULL);
3897 elem != NULL; elem = nvlist_next_nvpair(props, elem)) {
3898 const char *propname = nvpair_name(elem);
3899 if (zpool_prop_feature(propname)) {
3900 spa_feature_t feature;
3901 int err;
3902 const char *fname = strchr(propname, '@') + 1;
3903
3904 err = zfeature_lookup_name(fname, &feature);
3905 if (err == 0 && feature == SPA_FEATURE_WBC) {
3906 wbc_feature_nvp = elem;
3907 wbc_feature_exists = B_TRUE;
3908 }
3909
3910 has_features = B_TRUE;
3911 }
3912 }
3913
3914 /*
3915 * We do not want to enabled feature@wbc if
3916 * this pool does not have special vdev.
3917 * At this stage we remove this feature from common list,
3918 * but later after check that special vdev available this
3919 * feature will be enabled
3920 */
3921 if (wbc_feature_nvp != NULL)
3922 fnvlist_remove_nvpair(props, wbc_feature_nvp);
3923
3924 if ((error = spa_prop_validate(spa, props)) != 0) {
3925 spa_deactivate(spa);
3926 spa_remove(spa);
3927 mutex_exit(&spa_namespace_lock);
3928 return (error);
3929 }
3930 }
3931
3932
3933 if (has_features || nvlist_lookup_uint64(props,
3934 zpool_prop_to_name(ZPOOL_PROP_VERSION), &version) != 0) {
3935 version = SPA_VERSION;
3936 }
3937 ASSERT(SPA_VERSION_IS_SUPPORTED(version));
3938
3939 spa->spa_first_txg = txg;
3940 spa->spa_uberblock.ub_txg = txg - 1;
3941 spa->spa_uberblock.ub_version = version;
3942 spa->spa_ubsync = spa->spa_uberblock;
3943 spa->spa_load_state = SPA_LOAD_CREATE;
3944
3945 /*
3946 * Create "The Godfather" zio to hold all async IOs
3947 */
3948 spa->spa_async_zio_root = kmem_alloc(max_ncpus * sizeof (void *),
3949 KM_SLEEP);
3950 for (int i = 0; i < max_ncpus; i++) {
3951 spa->spa_async_zio_root[i] = zio_root(spa, NULL, NULL,
3952 ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
3953 ZIO_FLAG_GODFATHER);
3954 }
3955
3956 /*
3957 * Create the root vdev.
3958 */
3959 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3960
3961 error = spa_config_parse(spa, &rvd, nvroot, NULL, 0, VDEV_ALLOC_ADD);
3962
3963 ASSERT(error != 0 || rvd != NULL);
3964 ASSERT(error != 0 || spa->spa_root_vdev == rvd);
3965
3966 if (error == 0 && !zfs_allocatable_devs(nvroot))
3967 error = SET_ERROR(EINVAL);
3968
3969 if (error == 0 &&
3970 (error = vdev_create(rvd, txg, B_FALSE)) == 0 &&
3971 (error = spa_validate_aux(spa, nvroot, txg,
3972 VDEV_ALLOC_ADD)) == 0) {
3973 for (int c = 0; c < rvd->vdev_children; c++) {
3974 vdev_metaslab_set_size(rvd->vdev_child[c]);
3975 vdev_expand(rvd->vdev_child[c], txg);
3976 }
3977 }
3978
3979 spa_config_exit(spa, SCL_ALL, FTAG);
3980
3981 if (error != 0) {
3982 spa_unload(spa);
3983 spa_deactivate(spa);
3984 spa_remove(spa);
3985 mutex_exit(&spa_namespace_lock);
3986 return (error);
3987 }
3988
3989 /*
3990 * Get the list of spares, if specified.
3991 */
3992 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
3993 &spares, &nspares) == 0) {
3994 VERIFY(nvlist_alloc(&spa->spa_spares.sav_config, NV_UNIQUE_NAME,
3995 KM_SLEEP) == 0);
3996 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
3997 ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
3998 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3999 spa_load_spares(spa);
4000 spa_config_exit(spa, SCL_ALL, FTAG);
4001 spa->spa_spares.sav_sync = B_TRUE;
4002 }
4003
4004 /*
4005 * Get the list of level 2 cache devices, if specified.
4006 */
4007 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
4008 &l2cache, &nl2cache) == 0) {
4009 VERIFY(nvlist_alloc(&spa->spa_l2cache.sav_config,
4010 NV_UNIQUE_NAME, KM_SLEEP) == 0);
4011 VERIFY(nvlist_add_nvlist_array(spa->spa_l2cache.sav_config,
4012 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
4013 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4014 spa_load_l2cache(spa);
4015 spa_config_exit(spa, SCL_ALL, FTAG);
4016 spa->spa_l2cache.sav_sync = B_TRUE;
4017 }
4018
4019 spa->spa_is_initializing = B_TRUE;
4020 spa->spa_dsl_pool = dp = dsl_pool_create(spa, zplprops, txg);
4021 spa->spa_meta_objset = dp->dp_meta_objset;
4022 spa->spa_is_initializing = B_FALSE;
4023
4024 /*
4025 * Create DDTs (dedup tables).
4026 */
4027 ddt_create(spa);
4028
4029 spa_update_dspace(spa);
4030
4031 tx = dmu_tx_create_assigned(dp, txg);
4032
4033 /*
4034 * Create the pool config object.
4035 */
4036 spa->spa_config_object = dmu_object_alloc(spa->spa_meta_objset,
4037 DMU_OT_PACKED_NVLIST, SPA_CONFIG_BLOCKSIZE,
4038 DMU_OT_PACKED_NVLIST_SIZE, sizeof (uint64_t), tx);
4039
4040 if (zap_add(spa->spa_meta_objset,
4041 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CONFIG,
4042 sizeof (uint64_t), 1, &spa->spa_config_object, tx) != 0) {
4043 cmn_err(CE_PANIC, "failed to add pool config");
4044 }
4045
4046 if (spa_version(spa) >= SPA_VERSION_FEATURES)
4047 spa_feature_create_zap_objects(spa, tx);
4048
4049 if (zap_add(spa->spa_meta_objset,
4050 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CREATION_VERSION,
4051 sizeof (uint64_t), 1, &version, tx) != 0) {
4052 cmn_err(CE_PANIC, "failed to add pool version");
4053 }
4054
4055 /* Newly created pools with the right version are always deflated. */
4056 if (version >= SPA_VERSION_RAIDZ_DEFLATE) {
4057 spa->spa_deflate = TRUE;
4058 if (zap_add(spa->spa_meta_objset,
4059 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_DEFLATE,
4060 sizeof (uint64_t), 1, &spa->spa_deflate, tx) != 0) {
4061 cmn_err(CE_PANIC, "failed to add deflate");
4062 }
4063 }
4064
4065 /*
4066 * Create the deferred-free bpobj. Turn off compression
4067 * because sync-to-convergence takes longer if the blocksize
4068 * keeps changing.
4069 */
4070 obj = bpobj_alloc(spa->spa_meta_objset, 1 << 14, tx);
4071 dmu_object_set_compress(spa->spa_meta_objset, obj,
4072 ZIO_COMPRESS_OFF, tx);
4073 if (zap_add(spa->spa_meta_objset,
4074 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_SYNC_BPOBJ,
4075 sizeof (uint64_t), 1, &obj, tx) != 0) {
4076 cmn_err(CE_PANIC, "failed to add bpobj");
4077 }
4078 VERIFY3U(0, ==, bpobj_open(&spa->spa_deferred_bpobj,
4079 spa->spa_meta_objset, obj));
4080
4081 /*
4082 * Create the pool's history object.
4083 */
4084 if (version >= SPA_VERSION_ZPOOL_HISTORY)
4085 spa_history_create_obj(spa, tx);
4086
4087 mp = &spa->spa_meta_policy;
4088
4089 /*
4090 * Generate some random noise for salted checksums to operate on.
4091 */
4092 (void) random_get_pseudo_bytes(spa->spa_cksum_salt.zcs_bytes,
4093 sizeof (spa->spa_cksum_salt.zcs_bytes));
4094
4095 /*
4096 * Set pool properties.
4097 */
4098 spa->spa_bootfs = zpool_prop_default_numeric(ZPOOL_PROP_BOOTFS);
4099 spa->spa_delegation = zpool_prop_default_numeric(ZPOOL_PROP_DELEGATION);
4100 spa->spa_failmode = zpool_prop_default_numeric(ZPOOL_PROP_FAILUREMODE);
4101 spa->spa_autoexpand = zpool_prop_default_numeric(ZPOOL_PROP_AUTOEXPAND);
4102 spa->spa_minwat = zpool_prop_default_numeric(ZPOOL_PROP_MINWATERMARK);
4103 spa->spa_hiwat = zpool_prop_default_numeric(ZPOOL_PROP_HIWATERMARK);
4104 spa->spa_lowat = zpool_prop_default_numeric(ZPOOL_PROP_LOWATERMARK);
4105 spa->spa_ddt_meta_copies =
4106 zpool_prop_default_numeric(ZPOOL_PROP_DEDUPMETA_DITTO);
4107 spa->spa_dedup_best_effort =
4108 zpool_prop_default_numeric(ZPOOL_PROP_DEDUP_BEST_EFFORT);
4109 spa->spa_dedup_lo_best_effort =
4110 zpool_prop_default_numeric(ZPOOL_PROP_DEDUP_LO_BEST_EFFORT);
4111 spa->spa_dedup_hi_best_effort =
4112 zpool_prop_default_numeric(ZPOOL_PROP_DEDUP_HI_BEST_EFFORT);
4113 spa->spa_force_trim = zpool_prop_default_numeric(ZPOOL_PROP_FORCETRIM);
4114
4115 spa->spa_resilver_prio =
4116 zpool_prop_default_numeric(ZPOOL_PROP_RESILVER_PRIO);
4117 spa->spa_scrub_prio = zpool_prop_default_numeric(ZPOOL_PROP_SCRUB_PRIO);
4118
4119 mutex_enter(&spa->spa_auto_trim_lock);
4120 spa->spa_auto_trim = zpool_prop_default_numeric(ZPOOL_PROP_AUTOTRIM);
4121 if (spa->spa_auto_trim == SPA_AUTO_TRIM_ON)
4122 spa_auto_trim_taskq_create(spa);
4123 mutex_exit(&spa->spa_auto_trim_lock);
4124
4125 mp->spa_enable_meta_placement_selection =
4126 zpool_prop_default_numeric(ZPOOL_PROP_META_PLACEMENT);
4127 mp->spa_sync_to_special =
4128 zpool_prop_default_numeric(ZPOOL_PROP_SYNC_TO_SPECIAL);
4129 mp->spa_ddt_meta_to_special =
4130 zpool_prop_default_numeric(ZPOOL_PROP_DDT_META_TO_METADEV);
4131 mp->spa_zfs_meta_to_special =
4132 zpool_prop_default_numeric(ZPOOL_PROP_ZFS_META_TO_METADEV);
4133 mp->spa_small_data_to_special =
4134 zpool_prop_default_numeric(ZPOOL_PROP_SMALL_DATA_TO_METADEV);
4135
4136 spa_set_ddt_classes(spa, 0);
4137
4138 if (props != NULL) {
4139 spa_configfile_set(spa, props, B_FALSE);
4140 spa_sync_props(props, tx);
4141 }
4142
4143 if (spa_has_special(spa)) {
4144 spa_feature_enable(spa, SPA_FEATURE_META_DEVICES, tx);
4145 spa_feature_incr(spa, SPA_FEATURE_META_DEVICES, tx);
4146
4147 if (wbc_feature_exists)
4148 spa_feature_enable(spa, SPA_FEATURE_WBC, tx);
4149 }
4150
4151 dmu_tx_commit(tx);
4152
4153 spa->spa_sync_on = B_TRUE;
4154 txg_sync_start(spa->spa_dsl_pool);
4155
4156 /*
4157 * We explicitly wait for the first transaction to complete so that our
4158 * bean counters are appropriately updated.
4159 */
4160 txg_wait_synced(spa->spa_dsl_pool, txg);
4161
4162 spa_config_sync(spa, B_FALSE, B_TRUE);
4163 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_CREATE);
4164
4165 spa_history_log_version(spa, "create");
4166
4167 /*
4168 * Don't count references from objsets that are already closed
4169 * and are making their way through the eviction process.
4170 */
4171 spa_evicting_os_wait(spa);
4172 spa->spa_minref = refcount_count(&spa->spa_refcount);
4173 spa->spa_load_state = SPA_LOAD_NONE;
4174
4175 mutex_exit(&spa_namespace_lock);
4176
4177 wbc_activate(spa, B_TRUE);
4178
4179 return (0);
4180 }
4181
4182
4183 /*
4184 * See if the pool has special tier, and if so, enable/activate
4185 * the feature as needed. Activation is not reference counted.
4186 */
4187 static void
4188 spa_check_special_feature(spa_t *spa)
4189 {
4190 if (spa_has_special(spa)) {
4191 nvlist_t *props = NULL;
4192
4193 if (!spa_feature_is_enabled(spa, SPA_FEATURE_META_DEVICES)) {
4194 VERIFY(nvlist_alloc(&props, NV_UNIQUE_NAME, 0) == 0);
4195 VERIFY(nvlist_add_uint64(props,
4196 FEATURE_META_DEVICES, 0) == 0);
4197 VERIFY(spa_prop_set(spa, props) == 0);
4198 nvlist_free(props);
4199 }
4200
4201 if (!spa_feature_is_active(spa, SPA_FEATURE_META_DEVICES)) {
4202 dmu_tx_t *tx =
4203 dmu_tx_create_dd(spa->spa_dsl_pool->dp_mos_dir);
4204
4205 VERIFY(dmu_tx_assign(tx, TXG_WAIT) == 0);
4206 spa_feature_incr(spa, SPA_FEATURE_META_DEVICES, tx);
4207 dmu_tx_commit(tx);
4208 }
4209 }
4210 }
4211
4212 static void
4213 spa_special_feature_activate(void *arg, dmu_tx_t *tx)
4214 {
4215 spa_t *spa = (spa_t *)arg;
4216
4217 if (spa_has_special(spa)) {
4218 /* enable and activate as needed */
4219 spa_feature_enable(spa, SPA_FEATURE_META_DEVICES, tx);
4220 if (!spa_feature_is_active(spa, SPA_FEATURE_META_DEVICES)) {
4221 spa_feature_incr(spa, SPA_FEATURE_META_DEVICES, tx);
4222 }
4223
4224 spa_feature_enable(spa, SPA_FEATURE_WBC, tx);
4225 }
4226 }
4227
4228 #ifdef _KERNEL
4229 /*
4230 * Get the root pool information from the root disk, then import the root pool
4231 * during the system boot up time.
4232 */
4233 extern int vdev_disk_read_rootlabel(char *, char *, nvlist_t **);
4234
4235 static nvlist_t *
4236 spa_generate_rootconf(char *devpath, char *devid, uint64_t *guid)
4237 {
4238 nvlist_t *config;
4239 nvlist_t *nvtop, *nvroot;
4240 uint64_t pgid;
4241
4242 if (vdev_disk_read_rootlabel(devpath, devid, &config) != 0)
4243 return (NULL);
4244
4245 /*
4246 * Add this top-level vdev to the child array.
4247 */
4248 VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
4249 &nvtop) == 0);
4250 VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
4251 &pgid) == 0);
4252 VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_GUID, guid) == 0);
4253
4254 /*
4255 * Put this pool's top-level vdevs into a root vdev.
4256 */
4257 VERIFY(nvlist_alloc(&nvroot, NV_UNIQUE_NAME, KM_SLEEP) == 0);
4258 VERIFY(nvlist_add_string(nvroot, ZPOOL_CONFIG_TYPE,
4259 VDEV_TYPE_ROOT) == 0);
4260 VERIFY(nvlist_add_uint64(nvroot, ZPOOL_CONFIG_ID, 0ULL) == 0);
4261 VERIFY(nvlist_add_uint64(nvroot, ZPOOL_CONFIG_GUID, pgid) == 0);
4262 VERIFY(nvlist_add_nvlist_array(nvroot, ZPOOL_CONFIG_CHILDREN,
4263 &nvtop, 1) == 0);
4264
4265 /*
4266 * Replace the existing vdev_tree with the new root vdev in
4267 * this pool's configuration (remove the old, add the new).
4268 */
4269 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, nvroot) == 0);
4270 nvlist_free(nvroot);
4271 return (config);
4272 }
4273
4274 /*
4275 * Walk the vdev tree and see if we can find a device with "better"
4276 * configuration. A configuration is "better" if the label on that
4277 * device has a more recent txg.
4278 */
4279 static void
4280 spa_alt_rootvdev(vdev_t *vd, vdev_t **avd, uint64_t *txg)
4281 {
4282 for (int c = 0; c < vd->vdev_children; c++)
4283 spa_alt_rootvdev(vd->vdev_child[c], avd, txg);
4284
4285 if (vd->vdev_ops->vdev_op_leaf) {
4286 nvlist_t *label;
4287 uint64_t label_txg;
4288
4289 if (vdev_disk_read_rootlabel(vd->vdev_physpath, vd->vdev_devid,
4290 &label) != 0)
4291 return;
4292
4293 VERIFY(nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_TXG,
4294 &label_txg) == 0);
4295
4296 /*
4297 * Do we have a better boot device?
4298 */
4299 if (label_txg > *txg) {
4300 *txg = label_txg;
4301 *avd = vd;
4302 }
4303 nvlist_free(label);
4304 }
4305 }
4306
4307 /*
4308 * Import a root pool.
4309 *
4310 * For x86. devpath_list will consist of devid and/or physpath name of
4311 * the vdev (e.g. "id1,sd@SSEAGATE..." or "/pci@1f,0/ide@d/disk@0,0:a").
4312 * The GRUB "findroot" command will return the vdev we should boot.
4313 *
4314 * For Sparc, devpath_list consists the physpath name of the booting device
4315 * no matter the rootpool is a single device pool or a mirrored pool.
4316 * e.g.
4317 * "/pci@1f,0/ide@d/disk@0,0:a"
4318 */
4319 int
4320 spa_import_rootpool(char *devpath, char *devid)
4321 {
4322 spa_t *spa;
4323 vdev_t *rvd, *bvd, *avd = NULL;
4324 nvlist_t *config, *nvtop;
4325 uint64_t guid, txg;
4326 char *pname;
4327 int error;
4328
4329 /*
4330 * Read the label from the boot device and generate a configuration.
4331 */
4332 config = spa_generate_rootconf(devpath, devid, &guid);
4333 #if defined(_OBP) && defined(_KERNEL)
4334 if (config == NULL) {
4335 if (strstr(devpath, "/iscsi/ssd") != NULL) {
4336 /* iscsi boot */
4337 get_iscsi_bootpath_phy(devpath);
4338 config = spa_generate_rootconf(devpath, devid, &guid);
4339 }
4340 }
4341 #endif
4342 if (config == NULL) {
4343 cmn_err(CE_NOTE, "Cannot read the pool label from '%s'",
4344 devpath);
4345 return (SET_ERROR(EIO));
4346 }
4347
4348 VERIFY(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
4349 &pname) == 0);
4350 VERIFY(nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_TXG, &txg) == 0);
4351
4352 mutex_enter(&spa_namespace_lock);
4353 if ((spa = spa_lookup(pname)) != NULL || spa_config_guid_exists(guid)) {
4354 /*
4355 * Remove the existing root pool from the namespace so that we
4356 * can replace it with the correct config we just read in.
4357 */
4358 spa_remove(spa);
4359 }
4360
4361 spa = spa_add(pname, config, NULL);
4362 spa->spa_is_root = B_TRUE;
4363 spa->spa_import_flags = ZFS_IMPORT_VERBATIM;
4364
4365 /*
4366 * Build up a vdev tree based on the boot device's label config.
4367 */
4368 VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
4369 &nvtop) == 0);
4370 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4371 error = spa_config_parse(spa, &rvd, nvtop, NULL, 0,
4372 VDEV_ALLOC_ROOTPOOL);
4373 spa_config_exit(spa, SCL_ALL, FTAG);
4374 if (error) {
4375 mutex_exit(&spa_namespace_lock);
4376 nvlist_free(config);
4377 cmn_err(CE_NOTE, "Can not parse the config for pool '%s'",
4378 pname);
4379 return (error);
4380 }
4381
4382 /*
4383 * Get the boot vdev.
4384 */
4385 if ((bvd = vdev_lookup_by_guid(rvd, guid)) == NULL) {
4386 cmn_err(CE_NOTE, "Can not find the boot vdev for guid %llu",
4387 (u_longlong_t)guid);
4388 error = SET_ERROR(ENOENT);
4389 goto out;
4390 }
4391
4392 /*
4393 * Determine if there is a better boot device.
4394 */
4395 avd = bvd;
4396 spa_alt_rootvdev(rvd, &avd, &txg);
4397 if (avd != bvd) {
4398 cmn_err(CE_NOTE, "The boot device is 'degraded'. Please "
4399 "try booting from '%s'", avd->vdev_path);
4400 error = SET_ERROR(EINVAL);
4401 goto out;
4402 }
4403
4404 /*
4405 * If the boot device is part of a spare vdev then ensure that
4406 * we're booting off the active spare.
4407 */
4408 if (bvd->vdev_parent->vdev_ops == &vdev_spare_ops &&
4409 !bvd->vdev_isspare) {
4410 cmn_err(CE_NOTE, "The boot device is currently spared. Please "
4411 "try booting from '%s'",
4412 bvd->vdev_parent->
4413 vdev_child[bvd->vdev_parent->vdev_children - 1]->vdev_path);
4414 error = SET_ERROR(EINVAL);
4415 goto out;
4416 }
4417
4418 error = 0;
4419 out:
4420 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4421 vdev_free(rvd);
4422 spa_config_exit(spa, SCL_ALL, FTAG);
4423 mutex_exit(&spa_namespace_lock);
4424
4425 nvlist_free(config);
4426 return (error);
4427 }
4428
4429 #endif
4430
4431 /*
4432 * Import a non-root pool into the system.
4433 */
4434 int
4435 spa_import(const char *pool, nvlist_t *config, nvlist_t *props, uint64_t flags)
4436 {
4437 spa_t *spa;
4438 char *altroot = NULL;
4439 spa_load_state_t state = SPA_LOAD_IMPORT;
4440 zpool_rewind_policy_t policy;
4441 uint64_t mode = spa_mode_global;
4442 uint64_t readonly = B_FALSE;
4443 int error;
4444 nvlist_t *nvroot;
4445 nvlist_t **spares, **l2cache;
4446 uint_t nspares, nl2cache;
4447 uint64_t guid;
4448
4449 if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID, &guid) != 0)
4450 return (SET_ERROR(EINVAL));
4451
4452 /*
4453 * If a pool with this name exists, return failure.
4454 */
4455 mutex_enter(&spa_namespace_lock);
4456 if (spa_lookup(pool) != NULL || spa_config_guid_exists(guid)) {
4457 mutex_exit(&spa_namespace_lock);
4458 return (SET_ERROR(EEXIST));
4459 }
4460
4461 /*
4462 * Create and initialize the spa structure.
4463 */
4464 (void) nvlist_lookup_string(props,
4465 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
4466 (void) nvlist_lookup_uint64(props,
4467 zpool_prop_to_name(ZPOOL_PROP_READONLY), &readonly);
4468 if (readonly)
4469 mode = FREAD;
4470 spa = spa_add(pool, config, altroot);
4471 spa->spa_import_flags = flags;
4472
4473 /*
4474 * Verbatim import - Take a pool and insert it into the namespace
4475 * as if it had been loaded at boot.
4476 */
4477 if (spa->spa_import_flags & ZFS_IMPORT_VERBATIM) {
4478 if (props != NULL)
4479 spa_configfile_set(spa, props, B_FALSE);
4480
4481 spa_config_sync(spa, B_FALSE, B_TRUE);
4482 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_IMPORT);
4483
4484 mutex_exit(&spa_namespace_lock);
4485 return (0);
4486 }
4487
4488 spa_activate(spa, mode);
4489
4490 /*
4491 * Don't start async tasks until we know everything is healthy.
4492 */
4493 spa_async_suspend(spa);
4494
4495 zpool_get_rewind_policy(config, &policy);
4496 if (policy.zrp_request & ZPOOL_DO_REWIND)
4497 state = SPA_LOAD_RECOVER;
4498
4499 /*
4500 * Pass off the heavy lifting to spa_load(). Pass TRUE for mosconfig
4501 * because the user-supplied config is actually the one to trust when
4502 * doing an import.
4503 */
4504 if (state != SPA_LOAD_RECOVER)
4505 spa->spa_last_ubsync_txg = spa->spa_load_txg = 0;
4506
4507 error = spa_load_best(spa, state, B_TRUE, policy.zrp_txg,
4508 policy.zrp_request);
4509
4510 /*
4511 * Propagate anything learned while loading the pool and pass it
4512 * back to caller (i.e. rewind info, missing devices, etc).
4513 */
4514 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_LOAD_INFO,
4515 spa->spa_load_info) == 0);
4516
4517 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4518 /*
4519 * Toss any existing sparelist, as it doesn't have any validity
4520 * anymore, and conflicts with spa_has_spare().
4521 */
4522 if (spa->spa_spares.sav_config) {
4523 nvlist_free(spa->spa_spares.sav_config);
4524 spa->spa_spares.sav_config = NULL;
4525 spa_load_spares(spa);
4526 }
4527 if (spa->spa_l2cache.sav_config) {
4528 nvlist_free(spa->spa_l2cache.sav_config);
4529 spa->spa_l2cache.sav_config = NULL;
4530 spa_load_l2cache(spa);
4531 }
4532
4533 VERIFY(nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
4534 &nvroot) == 0);
4535 if (error == 0)
4536 error = spa_validate_aux(spa, nvroot, -1ULL,
4537 VDEV_ALLOC_SPARE);
4538 if (error == 0)
4539 error = spa_validate_aux(spa, nvroot, -1ULL,
4540 VDEV_ALLOC_L2CACHE);
4541 spa_config_exit(spa, SCL_ALL, FTAG);
4542
4543 if (props != NULL)
4544 spa_configfile_set(spa, props, B_FALSE);
4545
4546 if (error != 0 || (props && spa_writeable(spa) &&
4547 (error = spa_prop_set(spa, props)))) {
4548 spa_unload(spa);
4549 spa_deactivate(spa);
4550 spa_remove(spa);
4551 mutex_exit(&spa_namespace_lock);
4552 return (error);
4553 }
4554
4555 /*
4556 * Override any spares and level 2 cache devices as specified by
4557 * the user, as these may have correct device names/devids, etc.
4558 */
4559 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES,
4560 &spares, &nspares) == 0) {
4561 if (spa->spa_spares.sav_config)
4562 VERIFY(nvlist_remove(spa->spa_spares.sav_config,
4563 ZPOOL_CONFIG_SPARES, DATA_TYPE_NVLIST_ARRAY) == 0);
4564 else
4565 VERIFY(nvlist_alloc(&spa->spa_spares.sav_config,
4566 NV_UNIQUE_NAME, KM_SLEEP) == 0);
4567 VERIFY(nvlist_add_nvlist_array(spa->spa_spares.sav_config,
4568 ZPOOL_CONFIG_SPARES, spares, nspares) == 0);
4569 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4570 spa_load_spares(spa);
4571 spa_config_exit(spa, SCL_ALL, FTAG);
4572 spa->spa_spares.sav_sync = B_TRUE;
4573 }
4574 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE,
4575 &l2cache, &nl2cache) == 0) {
4576 if (spa->spa_l2cache.sav_config)
4577 VERIFY(nvlist_remove(spa->spa_l2cache.sav_config,
4578 ZPOOL_CONFIG_L2CACHE, DATA_TYPE_NVLIST_ARRAY) == 0);
4579 else
4580 VERIFY(nvlist_alloc(&spa->spa_l2cache.sav_config,
4581 NV_UNIQUE_NAME, KM_SLEEP) == 0);
4582 VERIFY(nvlist_add_nvlist_array(spa->spa_l2cache.sav_config,
4583 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache) == 0);
4584 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4585 spa_load_l2cache(spa);
4586 spa_config_exit(spa, SCL_ALL, FTAG);
4587 spa->spa_l2cache.sav_sync = B_TRUE;
4588 }
4589
4590 /* At this point, we can load spare props */
4591 (void) spa_load_vdev_props(spa);
4592
4593 /*
4594 * Check for any removed devices.
4595 */
4596 if (spa->spa_autoreplace) {
4597 spa_aux_check_removed(&spa->spa_spares);
4598 spa_aux_check_removed(&spa->spa_l2cache);
4599 }
4600
4601 if (spa_writeable(spa)) {
4602 /*
4603 * Update the config cache to include the newly-imported pool.
4604 */
4605 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
4606 }
4607
4608 /*
4609 * Start async resume as late as possible to reduce I/O activity when
4610 * importing a pool. This will let any pending txgs (e.g. from scrub
4611 * or resilver) to complete quickly thereby reducing import times in
4612 * such cases.
4613 */
4614 spa_async_resume(spa);
4615
4616 /*
4617 * It's possible that the pool was expanded while it was exported.
4618 * We kick off an async task to handle this for us.
4619 */
4620 spa_async_request(spa, SPA_ASYNC_AUTOEXPAND);
4621
4622 /* Set/activate meta feature as needed */
4623 if (!spa_writeable(spa))
4624 spa_check_special_feature(spa);
4625 spa_history_log_version(spa, "import");
4626
4627 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_IMPORT);
4628
4629 mutex_exit(&spa_namespace_lock);
4630
4631 if (!spa_writeable(spa))
4632 return (0);
4633
4634 wbc_activate(spa, B_FALSE);
4635
4636 return (dsl_sync_task(spa->spa_name, NULL, spa_special_feature_activate,
4637 spa, 3, ZFS_SPACE_CHECK_RESERVED));
4638 }
4639
4640 nvlist_t *
4641 spa_tryimport(nvlist_t *tryconfig)
4642 {
4643 nvlist_t *config = NULL;
4644 char *poolname;
4645 spa_t *spa;
4646 uint64_t state;
4647 int error;
4648
4649 if (nvlist_lookup_string(tryconfig, ZPOOL_CONFIG_POOL_NAME, &poolname))
4650 return (NULL);
4651
4652 if (nvlist_lookup_uint64(tryconfig, ZPOOL_CONFIG_POOL_STATE, &state))
4653 return (NULL);
4654
4655 /*
4656 * Create and initialize the spa structure.
4657 */
4658 mutex_enter(&spa_namespace_lock);
4659 spa = spa_add(TRYIMPORT_NAME, tryconfig, NULL);
4660 spa_activate(spa, FREAD);
4661
4662 /*
4663 * Pass off the heavy lifting to spa_load().
4664 * Pass TRUE for mosconfig because the user-supplied config
4665 * is actually the one to trust when doing an import.
4666 */
4667 error = spa_load(spa, SPA_LOAD_TRYIMPORT, SPA_IMPORT_EXISTING, B_TRUE);
4668
4669 /*
4670 * If 'tryconfig' was at least parsable, return the current config.
4671 */
4672 if (spa->spa_root_vdev != NULL) {
4673 config = spa_config_generate(spa, NULL, -1ULL, B_TRUE);
4674 VERIFY(nvlist_add_string(config, ZPOOL_CONFIG_POOL_NAME,
4675 poolname) == 0);
4676 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_STATE,
4677 state) == 0);
4678 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_TIMESTAMP,
4679 spa->spa_uberblock.ub_timestamp) == 0);
4680 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_LOAD_INFO,
4681 spa->spa_load_info) == 0);
4682
4683 /*
4684 * If the bootfs property exists on this pool then we
4685 * copy it out so that external consumers can tell which
4686 * pools are bootable.
4687 */
4688 if ((!error || error == EEXIST) && spa->spa_bootfs) {
4689 char *tmpname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
4690
4691 /*
4692 * We have to play games with the name since the
4693 * pool was opened as TRYIMPORT_NAME.
4694 */
4695 if (dsl_dsobj_to_dsname(spa_name(spa),
4696 spa->spa_bootfs, tmpname) == 0) {
4697 char *cp;
4698 char *dsname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
4699
4700 cp = strchr(tmpname, '/');
4701 if (cp == NULL) {
4702 (void) strlcpy(dsname, tmpname,
4703 MAXPATHLEN);
4704 } else {
4705 (void) snprintf(dsname, MAXPATHLEN,
4706 "%s/%s", poolname, ++cp);
4707 }
4708 VERIFY(nvlist_add_string(config,
4709 ZPOOL_CONFIG_BOOTFS, dsname) == 0);
4710 kmem_free(dsname, MAXPATHLEN);
4711 }
4712 kmem_free(tmpname, MAXPATHLEN);
4713 }
4714
4715 /*
4716 * Add the list of hot spares and level 2 cache devices.
4717 */
4718 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
4719 spa_add_spares(spa, config);
4720 spa_add_l2cache(spa, config);
4721 spa_config_exit(spa, SCL_CONFIG, FTAG);
4722 }
4723
4724 spa_unload(spa);
4725 spa_deactivate(spa);
4726 spa_remove(spa);
4727 mutex_exit(&spa_namespace_lock);
4728
4729 return (config);
4730 }
4731
4732 /*
4733 * Pool export/destroy
4734 *
4735 * The act of destroying or exporting a pool is very simple. We make sure there
4736 * is no more pending I/O and any references to the pool are gone. Then, we
4737 * update the pool state and sync all the labels to disk, removing the
4738 * configuration from the cache afterwards. If the 'hardforce' flag is set, then
4739 * we don't sync the labels or remove the configuration cache.
4740 */
4741 static int
4742 spa_export_common(char *pool, int new_state, nvlist_t **oldconfig,
4743 boolean_t force, boolean_t hardforce, boolean_t saveconfig)
4744 {
4745 spa_t *spa;
4746 zfs_autosnap_t *autosnap;
4747 boolean_t wbcthr_stopped = B_FALSE;
4748
4749 if (oldconfig)
4750 *oldconfig = NULL;
4751
4752 if (!(spa_mode_global & FWRITE))
4753 return (SET_ERROR(EROFS));
4754
4755 mutex_enter(&spa_namespace_lock);
4756 if ((spa = spa_lookup(pool)) == NULL) {
4757 mutex_exit(&spa_namespace_lock);
4758 return (SET_ERROR(ENOENT));
4759 }
4760
4761 /*
4762 * Put a hold on the pool, drop the namespace lock, stop async tasks
4763 * and write cache thread, reacquire the namespace lock, and see
4764 * if we can export.
4765 */
4766 spa_open_ref(spa, FTAG);
4767 mutex_exit(&spa_namespace_lock);
4768
4769 autosnap = spa_get_autosnap(spa);
4770 mutex_enter(&autosnap->autosnap_lock);
4771
4772 if (autosnap_has_children_zone(autosnap,
4773 spa_name(spa), B_TRUE)) {
4774 mutex_exit(&autosnap->autosnap_lock);
4775 spa_close(spa, FTAG);
4776 return (EBUSY);
4777 }
4778
4779 mutex_exit(&autosnap->autosnap_lock);
4780
4781 wbcthr_stopped = wbc_stop_thread(spa); /* stop write cache thread */
4782 autosnap_destroyer_thread_stop(spa);
4783 spa_async_suspend(spa);
4784 mutex_enter(&spa_namespace_lock);
4785 spa_close(spa, FTAG);
4786
4787 /*
4788 * The pool will be in core if it's openable,
4789 * in which case we can modify its state.
4790 */
4791 if (spa->spa_state != POOL_STATE_UNINITIALIZED && spa->spa_sync_on) {
4792 /*
4793 * Objsets may be open only because they're dirty, so we
4794 * have to force it to sync before checking spa_refcnt.
4795 */
4796 txg_wait_synced(spa->spa_dsl_pool, 0);
4797 spa_evicting_os_wait(spa);
4798
4799 /*
4800 * A pool cannot be exported or destroyed if there are active
4801 * references. If we are resetting a pool, allow references by
4802 * fault injection handlers.
4803 */
4804 if (!spa_refcount_zero(spa) ||
4805 (spa->spa_inject_ref != 0 &&
4806 new_state != POOL_STATE_UNINITIALIZED)) {
4807 spa_async_resume(spa);
4808 mutex_exit(&spa_namespace_lock);
4809 if (wbcthr_stopped)
4810 (void) wbc_start_thread(spa);
4811 autosnap_destroyer_thread_start(spa);
4812 return (SET_ERROR(EBUSY));
4813 }
4814
4815 /*
4816 * A pool cannot be exported if it has an active shared spare.
4817 * This is to prevent other pools stealing the active spare
4818 * from an exported pool. At user's own will, such pool can
4819 * be forcedly exported.
4820 */
4821 if (!force && new_state == POOL_STATE_EXPORTED &&
4822 spa_has_active_shared_spare(spa)) {
4823 spa_async_resume(spa);
4824 mutex_exit(&spa_namespace_lock);
4825 if (wbcthr_stopped)
4826 (void) wbc_start_thread(spa);
4827 autosnap_destroyer_thread_start(spa);
4828 return (SET_ERROR(EXDEV));
4829 }
4830
4831 /*
4832 * We want this to be reflected on every label,
4833 * so mark them all dirty. spa_unload() will do the
4834 * final sync that pushes these changes out.
4835 */
4836 if (new_state != POOL_STATE_UNINITIALIZED && !hardforce) {
4837 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
4838 spa->spa_state = new_state;
4839 spa->spa_final_txg = spa_last_synced_txg(spa) +
4840 TXG_DEFER_SIZE + 1;
4841 vdev_config_dirty(spa->spa_root_vdev);
4842 spa_config_exit(spa, SCL_ALL, FTAG);
4843 }
4844 }
4845
4846 spa_event_notify(spa, NULL, NULL, ESC_ZFS_POOL_DESTROY);
4847
4848 if (spa->spa_state != POOL_STATE_UNINITIALIZED) {
4849 wbc_deactivate(spa);
4850
4851 spa_unload(spa);
4852 spa_deactivate(spa);
4853 }
4854
4855 if (oldconfig && spa->spa_config)
4856 VERIFY(nvlist_dup(spa->spa_config, oldconfig, 0) == 0);
4857
4858 if (new_state != POOL_STATE_UNINITIALIZED) {
4859 if (!hardforce)
4860 spa_config_sync(spa, !saveconfig, B_TRUE);
4861
4862 spa_remove(spa);
4863 }
4864 mutex_exit(&spa_namespace_lock);
4865
4866 return (0);
4867 }
4868
4869 /*
4870 * Destroy a storage pool.
4871 */
4872 int
4873 spa_destroy(char *pool)
4874 {
4875 return (spa_export_common(pool, POOL_STATE_DESTROYED, NULL,
4876 B_FALSE, B_FALSE, B_FALSE));
4877 }
4878
4879 /*
4880 * Export a storage pool.
4881 */
4882 int
4883 spa_export(char *pool, nvlist_t **oldconfig, boolean_t force,
4884 boolean_t hardforce, boolean_t saveconfig)
4885 {
4886 return (spa_export_common(pool, POOL_STATE_EXPORTED, oldconfig,
4887 force, hardforce, saveconfig));
4888 }
4889
4890 /*
4891 * Similar to spa_export(), this unloads the spa_t without actually removing it
4892 * from the namespace in any way.
4893 */
4894 int
4895 spa_reset(char *pool)
4896 {
4897 return (spa_export_common(pool, POOL_STATE_UNINITIALIZED, NULL,
4898 B_FALSE, B_FALSE, B_FALSE));
4899 }
4900
4901 /*
4902 * ==========================================================================
4903 * Device manipulation
4904 * ==========================================================================
4905 */
4906
4907 /*
4908 * Add a device to a storage pool.
4909 */
4910 int
4911 spa_vdev_add(spa_t *spa, nvlist_t *nvroot)
4912 {
4913 uint64_t txg, id;
4914 int error;
4915 vdev_t *rvd = spa->spa_root_vdev;
4916 vdev_t *vd, *tvd;
4917 nvlist_t **spares, **l2cache;
4918 uint_t nspares, nl2cache;
4919 dmu_tx_t *tx = NULL;
4920
4921 ASSERT(spa_writeable(spa));
4922
4923 txg = spa_vdev_enter(spa);
4924
4925 if ((error = spa_config_parse(spa, &vd, nvroot, NULL, 0,
4926 VDEV_ALLOC_ADD)) != 0)
4927 return (spa_vdev_exit(spa, NULL, txg, error));
4928
4929 spa->spa_pending_vdev = vd; /* spa_vdev_exit() will clear this */
4930
4931 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_SPARES, &spares,
4932 &nspares) != 0)
4933 nspares = 0;
4934
4935 if (nvlist_lookup_nvlist_array(nvroot, ZPOOL_CONFIG_L2CACHE, &l2cache,
4936 &nl2cache) != 0)
4937 nl2cache = 0;
4938
4939 if (vd->vdev_children == 0 && nspares == 0 && nl2cache == 0)
4940 return (spa_vdev_exit(spa, vd, txg, EINVAL));
4941
4942 if (vd->vdev_children != 0 &&
4943 (error = vdev_create(vd, txg, B_FALSE)) != 0)
4944 return (spa_vdev_exit(spa, vd, txg, error));
4945
4946 /*
4947 * We must validate the spares and l2cache devices after checking the
4948 * children. Otherwise, vdev_inuse() will blindly overwrite the spare.
4949 */
4950 if ((error = spa_validate_aux(spa, nvroot, txg, VDEV_ALLOC_ADD)) != 0)
4951 return (spa_vdev_exit(spa, vd, txg, error));
4952
4953 /*
4954 * Transfer each new top-level vdev from vd to rvd.
4955 */
4956 for (int c = 0; c < vd->vdev_children; c++) {
4957
4958 /*
4959 * Set the vdev id to the first hole, if one exists.
4960 */
4961 for (id = 0; id < rvd->vdev_children; id++) {
4962 if (rvd->vdev_child[id]->vdev_ishole) {
4963 vdev_free(rvd->vdev_child[id]);
4964 break;
4965 }
4966 }
4967 tvd = vd->vdev_child[c];
4968 vdev_remove_child(vd, tvd);
4969 tvd->vdev_id = id;
4970 vdev_add_child(rvd, tvd);
4971 vdev_config_dirty(tvd);
4972 }
4973
4974 if (nspares != 0) {
4975 spa_set_aux_vdevs(&spa->spa_spares, spares, nspares,
4976 ZPOOL_CONFIG_SPARES);
4977 spa_load_spares(spa);
4978 spa->spa_spares.sav_sync = B_TRUE;
4979 }
4980
4981 if (nl2cache != 0) {
4982 spa_set_aux_vdevs(&spa->spa_l2cache, l2cache, nl2cache,
4983 ZPOOL_CONFIG_L2CACHE);
4984 spa_load_l2cache(spa);
4985 spa->spa_l2cache.sav_sync = B_TRUE;
4986 }
4987
4988 /*
4989 * We have to be careful when adding new vdevs to an existing pool.
4990 * If other threads start allocating from these vdevs before we
4991 * sync the config cache, and we lose power, then upon reboot we may
4992 * fail to open the pool because there are DVAs that the config cache
4993 * can't translate. Therefore, we first add the vdevs without
4994 * initializing metaslabs; sync the config cache (via spa_vdev_exit());
4995 * and then let spa_config_update() initialize the new metaslabs.
4996 *
4997 * spa_load() checks for added-but-not-initialized vdevs, so that
4998 * if we lose power at any point in this sequence, the remaining
4999 * steps will be completed the next time we load the pool.
5000 */
5001 (void) spa_vdev_exit(spa, vd, txg, 0);
5002
5003 mutex_enter(&spa_namespace_lock);
5004 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
5005 spa_event_notify(spa, NULL, NULL, ESC_ZFS_VDEV_ADD);
5006 mutex_exit(&spa_namespace_lock);
5007
5008 /*
5009 * "spa_last_synced_txg(spa) + 1" is used because:
5010 * - spa_vdev_exit() calls txg_wait_synced() for "txg"
5011 * - spa_config_update() calls txg_wait_synced() for
5012 * "spa_last_synced_txg(spa) + 1"
5013 */
5014 tx = dmu_tx_create_assigned(spa_get_dsl(spa),
5015 spa_last_synced_txg(spa) + 1);
5016 spa_special_feature_activate(spa, tx);
5017 dmu_tx_commit(tx);
5018
5019 wbc_activate(spa, B_FALSE);
5020
5021 return (0);
5022 }
5023
5024 /*
5025 * Attach a device to a mirror. The arguments are the path to any device
5026 * in the mirror, and the nvroot for the new device. If the path specifies
5027 * a device that is not mirrored, we automatically insert the mirror vdev.
5028 *
5029 * If 'replacing' is specified, the new device is intended to replace the
5030 * existing device; in this case the two devices are made into their own
5031 * mirror using the 'replacing' vdev, which is functionally identical to
5032 * the mirror vdev (it actually reuses all the same ops) but has a few
5033 * extra rules: you can't attach to it after it's been created, and upon
5034 * completion of resilvering, the first disk (the one being replaced)
5035 * is automatically detached.
5036 */
5037 int
5038 spa_vdev_attach(spa_t *spa, uint64_t guid, nvlist_t *nvroot, int replacing)
5039 {
5040 uint64_t txg, dtl_max_txg;
5041 vdev_t *rvd = spa->spa_root_vdev;
5042 vdev_t *oldvd, *newvd, *newrootvd, *pvd, *tvd;
5043 vdev_ops_t *pvops;
5044 char *oldvdpath, *newvdpath;
5045 int newvd_isspare;
5046 int error;
5047
5048 ASSERT(spa_writeable(spa));
5049
5050 txg = spa_vdev_enter(spa);
5051
5052 oldvd = spa_lookup_by_guid(spa, guid, B_FALSE);
5053
5054 if (oldvd == NULL)
5055 return (spa_vdev_exit(spa, NULL, txg, ENODEV));
5056
5057 if (!oldvd->vdev_ops->vdev_op_leaf)
5058 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
5059
5060 pvd = oldvd->vdev_parent;
5061
5062 if ((error = spa_config_parse(spa, &newrootvd, nvroot, NULL, 0,
5063 VDEV_ALLOC_ATTACH)) != 0)
5064 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
5065
5066 if (newrootvd->vdev_children != 1)
5067 return (spa_vdev_exit(spa, newrootvd, txg, EINVAL));
5068
5069 newvd = newrootvd->vdev_child[0];
5070
5071 if (!newvd->vdev_ops->vdev_op_leaf)
5072 return (spa_vdev_exit(spa, newrootvd, txg, EINVAL));
5073
5074 if ((error = vdev_create(newrootvd, txg, replacing)) != 0)
5075 return (spa_vdev_exit(spa, newrootvd, txg, error));
5076
5077 /*
5078 * Spares can't replace logs
5079 */
5080 if (oldvd->vdev_top->vdev_islog && newvd->vdev_isspare)
5081 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
5082
5083 if (!replacing) {
5084 /*
5085 * For attach, the only allowable parent is a mirror or the root
5086 * vdev.
5087 */
5088 if (pvd->vdev_ops != &vdev_mirror_ops &&
5089 pvd->vdev_ops != &vdev_root_ops)
5090 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
5091
5092 pvops = &vdev_mirror_ops;
5093 } else {
5094 /*
5095 * Active hot spares can only be replaced by inactive hot
5096 * spares.
5097 */
5098 if (pvd->vdev_ops == &vdev_spare_ops &&
5099 oldvd->vdev_isspare &&
5100 !spa_has_spare(spa, newvd->vdev_guid))
5101 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
5102
5103 /*
5104 * If the source is a hot spare, and the parent isn't already a
5105 * spare, then we want to create a new hot spare. Otherwise, we
5106 * want to create a replacing vdev. The user is not allowed to
5107 * attach to a spared vdev child unless the 'isspare' state is
5108 * the same (spare replaces spare, non-spare replaces
5109 * non-spare).
5110 */
5111 if (pvd->vdev_ops == &vdev_replacing_ops &&
5112 spa_version(spa) < SPA_VERSION_MULTI_REPLACE) {
5113 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
5114 } else if (pvd->vdev_ops == &vdev_spare_ops &&
5115 newvd->vdev_isspare != oldvd->vdev_isspare) {
5116 return (spa_vdev_exit(spa, newrootvd, txg, ENOTSUP));
5117 }
5118
5119 if (newvd->vdev_isspare)
5120 pvops = &vdev_spare_ops;
5121 else
5122 pvops = &vdev_replacing_ops;
5123 }
5124
5125 /*
5126 * Make sure the new device is big enough.
5127 */
5128 if (newvd->vdev_asize < vdev_get_min_asize(oldvd))
5129 return (spa_vdev_exit(spa, newrootvd, txg, EOVERFLOW));
5130
5131 /*
5132 * The new device cannot have a higher alignment requirement
5133 * than the top-level vdev.
5134 */
5135 if (newvd->vdev_ashift > oldvd->vdev_top->vdev_ashift)
5136 return (spa_vdev_exit(spa, newrootvd, txg, EDOM));
5137
5138 /*
5139 * If this is an in-place replacement, update oldvd's path and devid
5140 * to make it distinguishable from newvd, and unopenable from now on.
5141 */
5142 if (strcmp(oldvd->vdev_path, newvd->vdev_path) == 0) {
5143 spa_strfree(oldvd->vdev_path);
5144 oldvd->vdev_path = kmem_alloc(strlen(newvd->vdev_path) + 5,
5145 KM_SLEEP);
5146 (void) sprintf(oldvd->vdev_path, "%s/%s",
5147 newvd->vdev_path, "old");
5148 if (oldvd->vdev_devid != NULL) {
5149 spa_strfree(oldvd->vdev_devid);
5150 oldvd->vdev_devid = NULL;
5151 }
5152 }
5153
5154 /* mark the device being resilvered */
5155 newvd->vdev_resilver_txg = txg;
5156
5157 /*
5158 * If the parent is not a mirror, or if we're replacing, insert the new
5159 * mirror/replacing/spare vdev above oldvd.
5160 */
5161 if (pvd->vdev_ops != pvops)
5162 pvd = vdev_add_parent(oldvd, pvops);
5163
5164 ASSERT(pvd->vdev_top->vdev_parent == rvd);
5165 ASSERT(pvd->vdev_ops == pvops);
5166 ASSERT(oldvd->vdev_parent == pvd);
5167
5168 /*
5169 * Extract the new device from its root and add it to pvd.
5170 */
5171 vdev_remove_child(newrootvd, newvd);
5172 newvd->vdev_id = pvd->vdev_children;
5173 newvd->vdev_crtxg = oldvd->vdev_crtxg;
5174 vdev_add_child(pvd, newvd);
5175
5176 tvd = newvd->vdev_top;
5177 ASSERT(pvd->vdev_top == tvd);
5178 ASSERT(tvd->vdev_parent == rvd);
5179
5180 vdev_config_dirty(tvd);
5181
5182 /*
5183 * Set newvd's DTL to [TXG_INITIAL, dtl_max_txg) so that we account
5184 * for any dmu_sync-ed blocks. It will propagate upward when
5185 * spa_vdev_exit() calls vdev_dtl_reassess().
5186 */
5187 dtl_max_txg = txg + TXG_CONCURRENT_STATES;
5188
5189 vdev_dtl_dirty(newvd, DTL_MISSING, TXG_INITIAL,
5190 dtl_max_txg - TXG_INITIAL);
5191
5192 if (newvd->vdev_isspare) {
5193 spa_spare_activate(newvd);
5194 spa_event_notify(spa, newvd, NULL, ESC_ZFS_VDEV_SPARE);
5195 }
5196
5197 oldvdpath = spa_strdup(oldvd->vdev_path);
5198 newvdpath = spa_strdup(newvd->vdev_path);
5199 newvd_isspare = newvd->vdev_isspare;
5200
5201 /*
5202 * Mark newvd's DTL dirty in this txg.
5203 */
5204 vdev_dirty(tvd, VDD_DTL, newvd, txg);
5205
5206 /*
5207 * Schedule the resilver to restart in the future. We do this to
5208 * ensure that dmu_sync-ed blocks have been stitched into the
5209 * respective datasets.
5210 */
5211 dsl_resilver_restart(spa->spa_dsl_pool, dtl_max_txg);
5212
5213 if (spa->spa_bootfs)
5214 spa_event_notify(spa, newvd, NULL, ESC_ZFS_BOOTFS_VDEV_ATTACH);
5215
5216 spa_event_notify(spa, newvd, NULL, ESC_ZFS_VDEV_ATTACH);
5217
5218 /*
5219 * Check CoS property of the old vdev, add reference by new vdev
5220 */
5221 if (oldvd->vdev_queue.vq_cos) {
5222 cos_hold(oldvd->vdev_queue.vq_cos);
5223 newvd->vdev_queue.vq_cos = oldvd->vdev_queue.vq_cos;
5224 }
5225
5226 /*
5227 * Commit the config
5228 */
5229 (void) spa_vdev_exit(spa, newrootvd, dtl_max_txg, 0);
5230
5231 spa_history_log_internal(spa, "vdev attach", NULL,
5232 "%s vdev=%s %s vdev=%s",
5233 replacing && newvd_isspare ? "spare in" :
5234 replacing ? "replace" : "attach", newvdpath,
5235 replacing ? "for" : "to", oldvdpath);
5236
5237 spa_strfree(oldvdpath);
5238 spa_strfree(newvdpath);
5239
5240 return (0);
5241 }
5242
5243 /*
5244 * Detach a device from a mirror or replacing vdev.
5245 *
5246 * If 'replace_done' is specified, only detach if the parent
5247 * is a replacing vdev.
5248 */
5249 int
5250 spa_vdev_detach(spa_t *spa, uint64_t guid, uint64_t pguid, int replace_done)
5251 {
5252 uint64_t txg;
5253 int error;
5254 vdev_t *rvd = spa->spa_root_vdev;
5255 vdev_t *vd, *pvd, *cvd, *tvd;
5256 boolean_t unspare = B_FALSE;
5257 uint64_t unspare_guid = 0;
5258 char *vdpath;
5259
5260 ASSERT(spa_writeable(spa));
5261
5262 txg = spa_vdev_enter(spa);
5263
5264 vd = spa_lookup_by_guid(spa, guid, B_FALSE);
5265
5266 if (vd == NULL)
5267 return (spa_vdev_exit(spa, NULL, txg, ENODEV));
5268
5269 if (!vd->vdev_ops->vdev_op_leaf)
5270 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
5271
5272 pvd = vd->vdev_parent;
5273
5274 /*
5275 * If the parent/child relationship is not as expected, don't do it.
5276 * Consider M(A,R(B,C)) -- that is, a mirror of A with a replacing
5277 * vdev that's replacing B with C. The user's intent in replacing
5278 * is to go from M(A,B) to M(A,C). If the user decides to cancel
5279 * the replace by detaching C, the expected behavior is to end up
5280 * M(A,B). But suppose that right after deciding to detach C,
5281 * the replacement of B completes. We would have M(A,C), and then
5282 * ask to detach C, which would leave us with just A -- not what
5283 * the user wanted. To prevent this, we make sure that the
5284 * parent/child relationship hasn't changed -- in this example,
5285 * that C's parent is still the replacing vdev R.
5286 */
5287 if (pvd->vdev_guid != pguid && pguid != 0)
5288 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
5289
5290 /*
5291 * Only 'replacing' or 'spare' vdevs can be replaced.
5292 */
5293 if (replace_done && pvd->vdev_ops != &vdev_replacing_ops &&
5294 pvd->vdev_ops != &vdev_spare_ops)
5295 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
5296
5297 ASSERT(pvd->vdev_ops != &vdev_spare_ops ||
5298 spa_version(spa) >= SPA_VERSION_SPARES);
5299
5300 /*
5301 * Only mirror, replacing, and spare vdevs support detach.
5302 */
5303 if (pvd->vdev_ops != &vdev_replacing_ops &&
5304 pvd->vdev_ops != &vdev_mirror_ops &&
5305 pvd->vdev_ops != &vdev_spare_ops)
5306 return (spa_vdev_exit(spa, NULL, txg, ENOTSUP));
5307
5308 /*
5309 * If this device has the only valid copy of some data,
5310 * we cannot safely detach it.
5311 */
5312 if (vdev_dtl_required(vd))
5313 return (spa_vdev_exit(spa, NULL, txg, EBUSY));
5314
5315 ASSERT(pvd->vdev_children >= 2);
5316
5317 /*
5318 * If we are detaching the second disk from a replacing vdev, then
5319 * check to see if we changed the original vdev's path to have "/old"
5320 * at the end in spa_vdev_attach(). If so, undo that change now.
5321 */
5322 if (pvd->vdev_ops == &vdev_replacing_ops && vd->vdev_id > 0 &&
5323 vd->vdev_path != NULL) {
5324 size_t len = strlen(vd->vdev_path);
5325
5326 for (int c = 0; c < pvd->vdev_children; c++) {
5327 cvd = pvd->vdev_child[c];
5328
5329 if (cvd == vd || cvd->vdev_path == NULL)
5330 continue;
5331
5332 if (strncmp(cvd->vdev_path, vd->vdev_path, len) == 0 &&
5333 strcmp(cvd->vdev_path + len, "/old") == 0) {
5334 spa_strfree(cvd->vdev_path);
5335 cvd->vdev_path = spa_strdup(vd->vdev_path);
5336 break;
5337 }
5338 }
5339 }
5340
5341 /*
5342 * If we are detaching the original disk from a spare, then it implies
5343 * that the spare should become a real disk, and be removed from the
5344 * active spare list for the pool.
5345 */
5346 if (pvd->vdev_ops == &vdev_spare_ops &&
5347 vd->vdev_id == 0 &&
5348 pvd->vdev_child[pvd->vdev_children - 1]->vdev_isspare)
5349 unspare = B_TRUE;
5350
5351 /*
5352 * Erase the disk labels so the disk can be used for other things.
5353 * This must be done after all other error cases are handled,
5354 * but before we disembowel vd (so we can still do I/O to it).
5355 * But if we can't do it, don't treat the error as fatal --
5356 * it may be that the unwritability of the disk is the reason
5357 * it's being detached!
5358 */
5359 error = vdev_label_init(vd, 0, VDEV_LABEL_REMOVE);
5360
5361 /*
5362 * Remove vd from its parent and compact the parent's children.
5363 */
5364 vdev_remove_child(pvd, vd);
5365 vdev_compact_children(pvd);
5366
5367 /*
5368 * Remember one of the remaining children so we can get tvd below.
5369 */
5370 cvd = pvd->vdev_child[pvd->vdev_children - 1];
5371
5372 /*
5373 * If we need to remove the remaining child from the list of hot spares,
5374 * do it now, marking the vdev as no longer a spare in the process.
5375 * We must do this before vdev_remove_parent(), because that can
5376 * change the GUID if it creates a new toplevel GUID. For a similar
5377 * reason, we must remove the spare now, in the same txg as the detach;
5378 * otherwise someone could attach a new sibling, change the GUID, and
5379 * the subsequent attempt to spa_vdev_remove(unspare_guid) would fail.
5380 */
5381 if (unspare) {
5382 ASSERT(cvd->vdev_isspare);
5383 spa_spare_remove(cvd);
5384 unspare_guid = cvd->vdev_guid;
5385 (void) spa_vdev_remove(spa, unspare_guid, B_TRUE);
5386 cvd->vdev_unspare = B_TRUE;
5387 }
5388
5389 /*
5390 * If the parent mirror/replacing vdev only has one child,
5391 * the parent is no longer needed. Remove it from the tree.
5392 */
5393 if (pvd->vdev_children == 1) {
5394 if (pvd->vdev_ops == &vdev_spare_ops)
5395 cvd->vdev_unspare = B_FALSE;
5396 vdev_remove_parent(cvd);
5397 }
5398
5399
5400 /*
5401 * We don't set tvd until now because the parent we just removed
5402 * may have been the previous top-level vdev.
5403 */
5404 tvd = cvd->vdev_top;
5405 ASSERT(tvd->vdev_parent == rvd);
5406
5407 /*
5408 * Reevaluate the parent vdev state.
5409 */
5410 vdev_propagate_state(cvd);
5411
5412 /*
5413 * If the 'autoexpand' property is set on the pool then automatically
5414 * try to expand the size of the pool. For example if the device we
5415 * just detached was smaller than the others, it may be possible to
5416 * add metaslabs (i.e. grow the pool). We need to reopen the vdev
5417 * first so that we can obtain the updated sizes of the leaf vdevs.
5418 */
5419 if (spa->spa_autoexpand) {
5420 vdev_reopen(tvd);
5421 vdev_expand(tvd, txg);
5422 }
5423
5424 vdev_config_dirty(tvd);
5425
5426 /*
5427 * Mark vd's DTL as dirty in this txg. vdev_dtl_sync() will see that
5428 * vd->vdev_detached is set and free vd's DTL object in syncing context.
5429 * But first make sure we're not on any *other* txg's DTL list, to
5430 * prevent vd from being accessed after it's freed.
5431 */
5432 vdpath = spa_strdup(vd->vdev_path);
5433 for (int t = 0; t < TXG_SIZE; t++)
5434 (void) txg_list_remove_this(&tvd->vdev_dtl_list, vd, t);
5435 vd->vdev_detached = B_TRUE;
5436 vdev_dirty(tvd, VDD_DTL, vd, txg);
5437
5438 spa_event_notify(spa, vd, NULL, ESC_ZFS_VDEV_REMOVE);
5439
5440 /*
5441 * Release the references to CoS descriptors if any
5442 */
5443 if (vd->vdev_queue.vq_cos) {
5444 cos_rele(vd->vdev_queue.vq_cos);
5445 vd->vdev_queue.vq_cos = NULL;
5446 }
5447
5448 /* hang on to the spa before we release the lock */
5449 spa_open_ref(spa, FTAG);
5450
5451 error = spa_vdev_exit(spa, vd, txg, 0);
5452
5453 spa_history_log_internal(spa, "detach", NULL,
5454 "vdev=%s", vdpath);
5455 spa_strfree(vdpath);
5456
5457 /*
5458 * If this was the removal of the original device in a hot spare vdev,
5459 * then we want to go through and remove the device from the hot spare
5460 * list of every other pool.
5461 */
5462 if (unspare) {
5463 spa_t *altspa = NULL;
5464
5465 mutex_enter(&spa_namespace_lock);
5466 while ((altspa = spa_next(altspa)) != NULL) {
5467 if (altspa->spa_state != POOL_STATE_ACTIVE ||
5468 altspa == spa)
5469 continue;
5470
5471 spa_open_ref(altspa, FTAG);
5472 mutex_exit(&spa_namespace_lock);
5473 (void) spa_vdev_remove(altspa, unspare_guid, B_TRUE);
5474 mutex_enter(&spa_namespace_lock);
5475 spa_close(altspa, FTAG);
5476 }
5477 mutex_exit(&spa_namespace_lock);
5478
5479 /* search the rest of the vdevs for spares to remove */
5480 spa_vdev_resilver_done(spa);
5481 }
5482
5483 /* all done with the spa; OK to release */
5484 mutex_enter(&spa_namespace_lock);
5485 spa_close(spa, FTAG);
5486 mutex_exit(&spa_namespace_lock);
5487
5488 return (error);
5489 }
5490
5491 /*
5492 * Split a set of devices from their mirrors, and create a new pool from them.
5493 */
5494 int
5495 spa_vdev_split_mirror(spa_t *spa, char *newname, nvlist_t *config,
5496 nvlist_t *props, boolean_t exp)
5497 {
5498 int error = 0;
5499 uint64_t txg, *glist;
5500 spa_t *newspa;
5501 uint_t c, children, lastlog;
5502 nvlist_t **child, *nvl, *tmp;
5503 dmu_tx_t *tx;
5504 char *altroot = NULL;
5505 vdev_t *rvd, **vml = NULL; /* vdev modify list */
5506 boolean_t activate_slog;
5507
5508 ASSERT(spa_writeable(spa));
5509
5510 /*
5511 * split for pools with activated WBC
5512 * will be implemented in the next release
5513 */
5514 if (spa_feature_is_active(spa, SPA_FEATURE_WBC))
5515 return (SET_ERROR(ENOTSUP));
5516
5517 txg = spa_vdev_enter(spa);
5518
5519 /* clear the log and flush everything up to now */
5520 activate_slog = spa_passivate_log(spa);
5521 (void) spa_vdev_config_exit(spa, NULL, txg, 0, FTAG);
5522 error = spa_offline_log(spa);
5523 txg = spa_vdev_config_enter(spa);
5524
5525 if (activate_slog)
5526 spa_activate_log(spa);
5527
5528 if (error != 0)
5529 return (spa_vdev_exit(spa, NULL, txg, error));
5530
5531 /* check new spa name before going any further */
5532 if (spa_lookup(newname) != NULL)
5533 return (spa_vdev_exit(spa, NULL, txg, EEXIST));
5534
5535 /*
5536 * scan through all the children to ensure they're all mirrors
5537 */
5538 if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &nvl) != 0 ||
5539 nvlist_lookup_nvlist_array(nvl, ZPOOL_CONFIG_CHILDREN, &child,
5540 &children) != 0)
5541 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
5542
5543 /* first, check to ensure we've got the right child count */
5544 rvd = spa->spa_root_vdev;
5545 lastlog = 0;
5546 for (c = 0; c < rvd->vdev_children; c++) {
5547 vdev_t *vd = rvd->vdev_child[c];
5548
5549 /* don't count the holes & logs as children */
5550 if (vd->vdev_islog || vd->vdev_ishole) {
5551 if (lastlog == 0)
5552 lastlog = c;
5553 continue;
5554 }
5555
5556 lastlog = 0;
5557 }
5558 if (children != (lastlog != 0 ? lastlog : rvd->vdev_children))
5559 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
5560
5561 /* next, ensure no spare or cache devices are part of the split */
5562 if (nvlist_lookup_nvlist(nvl, ZPOOL_CONFIG_SPARES, &tmp) == 0 ||
5563 nvlist_lookup_nvlist(nvl, ZPOOL_CONFIG_L2CACHE, &tmp) == 0)
5564 return (spa_vdev_exit(spa, NULL, txg, EINVAL));
5565
5566 vml = kmem_zalloc(children * sizeof (vdev_t *), KM_SLEEP);
5567 glist = kmem_zalloc(children * sizeof (uint64_t), KM_SLEEP);
5568
5569 /* then, loop over each vdev and validate it */
5570 for (c = 0; c < children; c++) {
5571 uint64_t is_hole = 0;
5572
5573 (void) nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_IS_HOLE,
5574 &is_hole);
5575
5576 if (is_hole != 0) {
5577 if (spa->spa_root_vdev->vdev_child[c]->vdev_ishole ||
5578 spa->spa_root_vdev->vdev_child[c]->vdev_islog) {
5579 continue;
5580 } else {
5581 error = SET_ERROR(EINVAL);
5582 break;
5583 }
5584 }
5585
5586 /* which disk is going to be split? */
5587 if (nvlist_lookup_uint64(child[c], ZPOOL_CONFIG_GUID,
5588 &glist[c]) != 0) {
5589 error = SET_ERROR(EINVAL);
5590 break;
5591 }
5592
5593 /* look it up in the spa */
5594 vml[c] = spa_lookup_by_guid(spa, glist[c], B_FALSE);
5595 if (vml[c] == NULL) {
5596 error = SET_ERROR(ENODEV);
5597 break;
5598 }
5599
5600 /* make sure there's nothing stopping the split */
5601 if (vml[c]->vdev_parent->vdev_ops != &vdev_mirror_ops ||
5602 vml[c]->vdev_islog ||
5603 vml[c]->vdev_ishole ||
5604 vml[c]->vdev_isspare ||
5605 vml[c]->vdev_isl2cache ||
5606 !vdev_writeable(vml[c]) ||
5607 vml[c]->vdev_children != 0 ||
5608 vml[c]->vdev_state != VDEV_STATE_HEALTHY ||
5609 c != spa->spa_root_vdev->vdev_child[c]->vdev_id) {
5610 error = SET_ERROR(EINVAL);
5611 break;
5612 }
5613
5614 if (vdev_dtl_required(vml[c])) {
5615 error = SET_ERROR(EBUSY);
5616 break;
5617 }
5618
5619 /* we need certain info from the top level */
5620 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_METASLAB_ARRAY,
5621 vml[c]->vdev_top->vdev_ms_array) == 0);
5622 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_METASLAB_SHIFT,
5623 vml[c]->vdev_top->vdev_ms_shift) == 0);
5624 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_ASIZE,
5625 vml[c]->vdev_top->vdev_asize) == 0);
5626 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_ASHIFT,
5627 vml[c]->vdev_top->vdev_ashift) == 0);
5628
5629 /* transfer per-vdev ZAPs */
5630 ASSERT3U(vml[c]->vdev_leaf_zap, !=, 0);
5631 VERIFY0(nvlist_add_uint64(child[c],
5632 ZPOOL_CONFIG_VDEV_LEAF_ZAP, vml[c]->vdev_leaf_zap));
5633
5634 ASSERT3U(vml[c]->vdev_top->vdev_top_zap, !=, 0);
5635 VERIFY0(nvlist_add_uint64(child[c],
5636 ZPOOL_CONFIG_VDEV_TOP_ZAP,
5637 vml[c]->vdev_parent->vdev_top_zap));
5638 }
5639
5640 if (error != 0) {
5641 kmem_free(vml, children * sizeof (vdev_t *));
5642 kmem_free(glist, children * sizeof (uint64_t));
5643 return (spa_vdev_exit(spa, NULL, txg, error));
5644 }
5645
5646 /* stop writers from using the disks */
5647 for (c = 0; c < children; c++) {
5648 if (vml[c] != NULL)
5649 vml[c]->vdev_offline = B_TRUE;
5650 }
5651 vdev_reopen(spa->spa_root_vdev);
5652
5653 /*
5654 * Temporarily record the splitting vdevs in the spa config. This
5655 * will disappear once the config is regenerated.
5656 */
5657 VERIFY(nvlist_alloc(&nvl, NV_UNIQUE_NAME, KM_SLEEP) == 0);
5658 VERIFY(nvlist_add_uint64_array(nvl, ZPOOL_CONFIG_SPLIT_LIST,
5659 glist, children) == 0);
5660 kmem_free(glist, children * sizeof (uint64_t));
5661
5662 mutex_enter(&spa->spa_props_lock);
5663 VERIFY(nvlist_add_nvlist(spa->spa_config, ZPOOL_CONFIG_SPLIT,
5664 nvl) == 0);
5665 mutex_exit(&spa->spa_props_lock);
5666 spa->spa_config_splitting = nvl;
5667 vdev_config_dirty(spa->spa_root_vdev);
5668
5669 /* configure and create the new pool */
5670 VERIFY(nvlist_add_string(config, ZPOOL_CONFIG_POOL_NAME, newname) == 0);
5671 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_STATE,
5672 exp ? POOL_STATE_EXPORTED : POOL_STATE_ACTIVE) == 0);
5673 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_VERSION,
5674 spa_version(spa)) == 0);
5675 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_TXG,
5676 spa->spa_config_txg) == 0);
5677 VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_GUID,
5678 spa_generate_guid(NULL)) == 0);
5679 VERIFY0(nvlist_add_boolean(config, ZPOOL_CONFIG_HAS_PER_VDEV_ZAPS));
5680 (void) nvlist_lookup_string(props,
5681 zpool_prop_to_name(ZPOOL_PROP_ALTROOT), &altroot);
5682
5683 /* add the new pool to the namespace */
5684 newspa = spa_add(newname, config, altroot);
5685 newspa->spa_avz_action = AVZ_ACTION_REBUILD;
5686 newspa->spa_config_txg = spa->spa_config_txg;
5687 spa_set_log_state(newspa, SPA_LOG_CLEAR);
5688
5689 /* release the spa config lock, retaining the namespace lock */
5690 spa_vdev_config_exit(spa, NULL, txg, 0, FTAG);
5691
5692 if (zio_injection_enabled)
5693 zio_handle_panic_injection(spa, FTAG, 1);
5694
5695 spa_activate(newspa, spa_mode_global);
5696 spa_async_suspend(newspa);
5697
5698 /* create the new pool from the disks of the original pool */
5699 error = spa_load(newspa, SPA_LOAD_IMPORT, SPA_IMPORT_ASSEMBLE, B_TRUE);
5700 if (error)
5701 goto out;
5702
5703 /* if that worked, generate a real config for the new pool */
5704 if (newspa->spa_root_vdev != NULL) {
5705 VERIFY(nvlist_alloc(&newspa->spa_config_splitting,
5706 NV_UNIQUE_NAME, KM_SLEEP) == 0);
5707 VERIFY(nvlist_add_uint64(newspa->spa_config_splitting,
5708 ZPOOL_CONFIG_SPLIT_GUID, spa_guid(spa)) == 0);
5709 spa_config_set(newspa, spa_config_generate(newspa, NULL, -1ULL,
5710 B_TRUE));
5711 }
5712
5713 /* set the props */
5714 if (props != NULL) {
5715 spa_configfile_set(newspa, props, B_FALSE);
5716 error = spa_prop_set(newspa, props);
5717 if (error)
5718 goto out;
5719 }
5720
5721 /* flush everything */
5722 txg = spa_vdev_config_enter(newspa);
5723 vdev_config_dirty(newspa->spa_root_vdev);
5724 (void) spa_vdev_config_exit(newspa, NULL, txg, 0, FTAG);
5725
5726 if (zio_injection_enabled)
5727 zio_handle_panic_injection(spa, FTAG, 2);
5728
5729 spa_async_resume(newspa);
5730
5731 /* finally, update the original pool's config */
5732 txg = spa_vdev_config_enter(spa);
5733 tx = dmu_tx_create_dd(spa_get_dsl(spa)->dp_mos_dir);
5734 error = dmu_tx_assign(tx, TXG_WAIT);
5735 if (error != 0)
5736 dmu_tx_abort(tx);
5737 for (c = 0; c < children; c++) {
5738 if (vml[c] != NULL) {
5739 vdev_t *tvd = vml[c]->vdev_top;
5740
5741 /*
5742 * Need to be sure the detachable VDEV is not
5743 * on any *other* txg's DTL list to prevent it
5744 * from being accessed after it's freed.
5745 */
5746 for (int t = 0; t < TXG_SIZE; t++) {
5747 (void) txg_list_remove_this(
5748 &tvd->vdev_dtl_list, vml[c], t);
5749 }
5750
5751 vdev_split(vml[c]);
5752 if (error == 0)
5753 spa_history_log_internal(spa, "detach", tx,
5754 "vdev=%s", vml[c]->vdev_path);
5755
5756 vdev_free(vml[c]);
5757 }
5758 }
5759 spa->spa_avz_action = AVZ_ACTION_REBUILD;
5760 vdev_config_dirty(spa->spa_root_vdev);
5761 spa->spa_config_splitting = NULL;
5762 nvlist_free(nvl);
5763 if (error == 0)
5764 dmu_tx_commit(tx);
5765 (void) spa_vdev_exit(spa, NULL, txg, 0);
5766
5767 if (zio_injection_enabled)
5768 zio_handle_panic_injection(spa, FTAG, 3);
5769
5770 /* split is complete; log a history record */
5771 spa_history_log_internal(newspa, "split", NULL,
5772 "from pool %s", spa_name(spa));
5773
5774 kmem_free(vml, children * sizeof (vdev_t *));
5775
5776 /* if we're not going to mount the filesystems in userland, export */
5777 if (exp)
5778 error = spa_export_common(newname, POOL_STATE_EXPORTED, NULL,
5779 B_FALSE, B_FALSE, B_FALSE);
5780
5781 return (error);
5782
5783 out:
5784 spa_unload(newspa);
5785 spa_deactivate(newspa);
5786 spa_remove(newspa);
5787
5788 txg = spa_vdev_config_enter(spa);
5789
5790 /* re-online all offlined disks */
5791 for (c = 0; c < children; c++) {
5792 if (vml[c] != NULL)
5793 vml[c]->vdev_offline = B_FALSE;
5794 }
5795 vdev_reopen(spa->spa_root_vdev);
5796
5797 nvlist_free(spa->spa_config_splitting);
5798 spa->spa_config_splitting = NULL;
5799 (void) spa_vdev_exit(spa, NULL, txg, error);
5800
5801 kmem_free(vml, children * sizeof (vdev_t *));
5802 return (error);
5803 }
5804
5805 static nvlist_t *
5806 spa_nvlist_lookup_by_guid(nvlist_t **nvpp, int count, uint64_t target_guid)
5807 {
5808 for (int i = 0; i < count; i++) {
5809 uint64_t guid;
5810
5811 VERIFY(nvlist_lookup_uint64(nvpp[i], ZPOOL_CONFIG_GUID,
5812 &guid) == 0);
5813
5814 if (guid == target_guid)
5815 return (nvpp[i]);
5816 }
5817
5818 return (NULL);
5819 }
5820
5821 static void
5822 spa_vdev_remove_aux(nvlist_t *config, char *name, nvlist_t **dev, int count,
5823 nvlist_t *dev_to_remove)
5824 {
5825 nvlist_t **newdev = NULL;
5826
5827 if (count > 1)
5828 newdev = kmem_alloc((count - 1) * sizeof (void *), KM_SLEEP);
5829
5830 for (int i = 0, j = 0; i < count; i++) {
5831 if (dev[i] == dev_to_remove)
5832 continue;
5833 VERIFY(nvlist_dup(dev[i], &newdev[j++], KM_SLEEP) == 0);
5834 }
5835
5836 VERIFY(nvlist_remove(config, name, DATA_TYPE_NVLIST_ARRAY) == 0);
5837 VERIFY(nvlist_add_nvlist_array(config, name, newdev, count - 1) == 0);
5838
5839 for (int i = 0; i < count - 1; i++)
5840 nvlist_free(newdev[i]);
5841
5842 if (count > 1)
5843 kmem_free(newdev, (count - 1) * sizeof (void *));
5844 }
5845
5846 /*
5847 * Evacuate the device.
5848 */
5849 static int
5850 spa_vdev_remove_evacuate(spa_t *spa, vdev_t *vd)
5851 {
5852 uint64_t txg;
5853 int error = 0;
5854
5855 ASSERT(MUTEX_HELD(&spa_namespace_lock));
5856 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
5857 ASSERT(vd == vd->vdev_top);
5858
5859 /*
5860 * Evacuate the device. We don't hold the config lock as writer
5861 * since we need to do I/O but we do keep the
5862 * spa_namespace_lock held. Once this completes the device
5863 * should no longer have any blocks allocated on it.
5864 */
5865 if (vd->vdev_islog) {
5866 if (vd->vdev_stat.vs_alloc != 0)
5867 error = spa_offline_log(spa);
5868 } else {
5869 error = SET_ERROR(ENOTSUP);
5870 }
5871
5872 if (error)
5873 return (error);
5874
5875 /*
5876 * The evacuation succeeded. Remove any remaining MOS metadata
5877 * associated with this vdev, and wait for these changes to sync.
5878 */
5879 ASSERT0(vd->vdev_stat.vs_alloc);
5880 txg = spa_vdev_config_enter(spa);
5881 vd->vdev_removing = B_TRUE;
5882 vdev_dirty_leaves(vd, VDD_DTL, txg);
5883 vdev_config_dirty(vd);
5884 spa_vdev_config_exit(spa, NULL, txg, 0, FTAG);
5885
5886 return (0);
5887 }
5888
5889 /*
5890 * Complete the removal by cleaning up the namespace.
5891 */
5892 static void
5893 spa_vdev_remove_from_namespace(spa_t *spa, vdev_t *vd)
5894 {
5895 vdev_t *rvd = spa->spa_root_vdev;
5896 uint64_t id = vd->vdev_id;
5897 boolean_t last_vdev = (id == (rvd->vdev_children - 1));
5898
5899 ASSERT(MUTEX_HELD(&spa_namespace_lock));
5900 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
5901 ASSERT(vd == vd->vdev_top);
5902
5903 /*
5904 * Only remove any devices which are empty.
5905 */
5906 if (vd->vdev_stat.vs_alloc != 0)
5907 return;
5908
5909 (void) vdev_label_init(vd, 0, VDEV_LABEL_REMOVE);
5910
5911 if (list_link_active(&vd->vdev_state_dirty_node))
5912 vdev_state_clean(vd);
5913 if (list_link_active(&vd->vdev_config_dirty_node))
5914 vdev_config_clean(vd);
5915
5916 vdev_free(vd);
5917
5918 if (last_vdev) {
5919 vdev_compact_children(rvd);
5920 } else {
5921 vd = vdev_alloc_common(spa, id, 0, &vdev_hole_ops);
5922 vdev_add_child(rvd, vd);
5923 }
5924 vdev_config_dirty(rvd);
5925
5926 /*
5927 * Reassess the health of our root vdev.
5928 */
5929 vdev_reopen(rvd);
5930 }
5931
5932 /*
5933 * Remove a device from the pool -
5934 *
5935 * Removing a device from the vdev namespace requires several steps
5936 * and can take a significant amount of time. As a result we use
5937 * the spa_vdev_config_[enter/exit] functions which allow us to
5938 * grab and release the spa_config_lock while still holding the namespace
5939 * lock. During each step the configuration is synced out.
5940 *
5941 * Currently, this supports removing only hot spares, slogs, level 2 ARC
5942 * and special devices.
5943 */
5944 int
5945 spa_vdev_remove(spa_t *spa, uint64_t guid, boolean_t unspare)
5946 {
5947 vdev_t *vd;
5948 sysevent_t *ev = NULL;
5949 metaslab_group_t *mg;
5950 nvlist_t **spares, **l2cache, *nv;
5951 uint64_t txg = 0;
5952 uint_t nspares, nl2cache;
5953 int error = 0;
5954 boolean_t locked = MUTEX_HELD(&spa_namespace_lock);
5955
5956 ASSERT(spa_writeable(spa));
5957
5958 if (!locked)
5959 txg = spa_vdev_enter(spa);
5960
5961 vd = spa_lookup_by_guid(spa, guid, B_FALSE);
5962
5963 if (spa->spa_spares.sav_vdevs != NULL &&
5964 nvlist_lookup_nvlist_array(spa->spa_spares.sav_config,
5965 ZPOOL_CONFIG_SPARES, &spares, &nspares) == 0 &&
5966 (nv = spa_nvlist_lookup_by_guid(spares, nspares, guid)) != NULL) {
5967 /*
5968 * Only remove the hot spare if it's not currently in use
5969 * in this pool.
5970 */
5971 if (vd == NULL || unspare) {
5972 if (vd == NULL)
5973 vd = spa_lookup_by_guid(spa, guid, B_TRUE);
5974
5975 /*
5976 * Release the references to CoS descriptors if any
5977 */
5978 if (vd != NULL && vd->vdev_queue.vq_cos) {
5979 cos_rele(vd->vdev_queue.vq_cos);
5980 vd->vdev_queue.vq_cos = NULL;
5981 }
5982
5983 ev = spa_event_create(spa, vd, NULL, ESC_ZFS_VDEV_REMOVE_AUX);
5984 spa_vdev_remove_aux(spa->spa_spares.sav_config,
5985 ZPOOL_CONFIG_SPARES, spares, nspares, nv);
5986 spa_load_spares(spa);
5987 spa->spa_spares.sav_sync = B_TRUE;
5988 } else {
5989 error = SET_ERROR(EBUSY);
5990 }
5991 } else if (spa->spa_l2cache.sav_vdevs != NULL &&
5992 nvlist_lookup_nvlist_array(spa->spa_l2cache.sav_config,
5993 ZPOOL_CONFIG_L2CACHE, &l2cache, &nl2cache) == 0 &&
5994 (nv = spa_nvlist_lookup_by_guid(l2cache, nl2cache, guid)) != NULL) {
5995 /*
5996 * Cache devices can always be removed.
5997 */
5998 if (vd == NULL)
5999 vd = spa_lookup_by_guid(spa, guid, B_TRUE);
6000 /*
6001 * Release the references to CoS descriptors if any
6002 */
6003 if (vd != NULL && vd->vdev_queue.vq_cos) {
6004 cos_rele(vd->vdev_queue.vq_cos);
6005 vd->vdev_queue.vq_cos = NULL;
6006 }
6007
6008 ev = spa_event_create(spa, vd, NULL, ESC_ZFS_VDEV_REMOVE_AUX);
6009 spa_vdev_remove_aux(spa->spa_l2cache.sav_config,
6010 ZPOOL_CONFIG_L2CACHE, l2cache, nl2cache, nv);
6011 spa_load_l2cache(spa);
6012 spa->spa_l2cache.sav_sync = B_TRUE;
6013 } else if (vd != NULL && vd->vdev_islog) {
6014 ASSERT(!locked);
6015
6016 if (vd != vd->vdev_top)
6017 return (spa_vdev_exit(spa, NULL, txg, SET_ERROR(ENOTSUP)));
6018
6019 mg = vd->vdev_mg;
6020
6021 /*
6022 * Stop allocating from this vdev.
6023 */
6024 metaslab_group_passivate(mg);
6025
6026 /*
6027 * Wait for the youngest allocations and frees to sync,
6028 * and then wait for the deferral of those frees to finish.
6029 */
6030 spa_vdev_config_exit(spa, NULL,
6031 txg + TXG_CONCURRENT_STATES + TXG_DEFER_SIZE, 0, FTAG);
6032
6033 /*
6034 * Attempt to evacuate the vdev.
6035 */
6036 error = spa_vdev_remove_evacuate(spa, vd);
6037
6038 txg = spa_vdev_config_enter(spa);
6039
6040 /*
6041 * If we couldn't evacuate the vdev, unwind.
6042 */
6043 if (error) {
6044 metaslab_group_activate(mg);
6045 return (spa_vdev_exit(spa, NULL, txg, error));
6046 }
6047
6048 /*
6049 * Release the references to CoS descriptors if any
6050 */
6051 if (vd->vdev_queue.vq_cos) {
6052 cos_rele(vd->vdev_queue.vq_cos);
6053 vd->vdev_queue.vq_cos = NULL;
6054 }
6055
6056 ev = spa_event_create(spa, vd, NULL, ESC_ZFS_VDEV_REMOVE_DEV);
6057
6058 /*
6059 * Clean up the vdev namespace.
6060 */
6061 ev = spa_event_create(spa, vd, NULL, ESC_ZFS_VDEV_REMOVE_DEV);
6062 spa_vdev_remove_from_namespace(spa, vd);
6063
6064 } else if (vd != NULL && vdev_is_special(vd)) {
6065 ASSERT(!locked);
6066
6067 if (vd != vd->vdev_top)
6068 return (spa_vdev_exit(spa, NULL, txg, SET_ERROR(ENOTSUP)));
6069
6070 error = spa_special_vdev_remove(spa, vd, &txg);
6071 if (error == 0) {
6072 ev = spa_event_create(spa, vd, NULL, ESC_ZFS_VDEV_REMOVE_DEV);
6073 spa_vdev_remove_from_namespace(spa, vd);
6074
6075 /*
6076 * User sees this field as 'enablespecial'
6077 * pool-level property
6078 */
6079 spa->spa_usesc = B_FALSE;
6080 }
6081 } else if (vd != NULL) {
6082 /*
6083 * Normal vdevs cannot be removed (yet).
6084 */
6085 error = SET_ERROR(ENOTSUP);
6086 } else {
6087 /*
6088 * There is no vdev of any kind with the specified guid.
6089 */
6090 error = SET_ERROR(ENOENT);
6091 }
6092
6093 if (!locked)
6094 error = spa_vdev_exit(spa, NULL, txg, error);
6095
6096 if (ev)
6097 spa_event_notify_impl(ev);
6098
6099 return (error);
6100 }
6101
6102 /*
6103 * Find any device that's done replacing, or a vdev marked 'unspare' that's
6104 * currently spared, so we can detach it.
6105 */
6106 static vdev_t *
6107 spa_vdev_resilver_done_hunt(vdev_t *vd)
6108 {
6109 vdev_t *newvd, *oldvd;
6110
6111 for (int c = 0; c < vd->vdev_children; c++) {
6112 oldvd = spa_vdev_resilver_done_hunt(vd->vdev_child[c]);
6113 if (oldvd != NULL)
6114 return (oldvd);
6115 }
6116
6117 /*
6118 * Check for a completed replacement. We always consider the first
6119 * vdev in the list to be the oldest vdev, and the last one to be
6120 * the newest (see spa_vdev_attach() for how that works). In
6121 * the case where the newest vdev is faulted, we will not automatically
6122 * remove it after a resilver completes. This is OK as it will require
6123 * user intervention to determine which disk the admin wishes to keep.
6124 */
6125 if (vd->vdev_ops == &vdev_replacing_ops) {
6126 ASSERT(vd->vdev_children > 1);
6127
6128 newvd = vd->vdev_child[vd->vdev_children - 1];
6129 oldvd = vd->vdev_child[0];
6130
6131 if (vdev_dtl_empty(newvd, DTL_MISSING) &&
6132 vdev_dtl_empty(newvd, DTL_OUTAGE) &&
6133 !vdev_dtl_required(oldvd))
6134 return (oldvd);
6135 }
6136
6137 /*
6138 * Check for a completed resilver with the 'unspare' flag set.
6139 * Also potentially update faulted state.
6140 */
6141 if (vd->vdev_ops == &vdev_spare_ops) {
6142 vdev_t *first = vd->vdev_child[0];
6143 vdev_t *last = vd->vdev_child[vd->vdev_children - 1];
6144
6145 if (last->vdev_unspare) {
6146 oldvd = first;
6147 newvd = last;
6148 } else if (first->vdev_unspare) {
6149 oldvd = last;
6150 newvd = first;
6151 } else {
6152 oldvd = NULL;
6153 }
6154
6155 if (oldvd != NULL &&
6156 vdev_dtl_empty(newvd, DTL_MISSING) &&
6157 vdev_dtl_empty(newvd, DTL_OUTAGE) &&
6158 !vdev_dtl_required(oldvd))
6159 return (oldvd);
6160
6161 vdev_propagate_state(vd);
6162
6163 /*
6164 * If there are more than two spares attached to a disk,
6165 * and those spares are not required, then we want to
6166 * attempt to free them up now so that they can be used
6167 * by other pools. Once we're back down to a single
6168 * disk+spare, we stop removing them.
6169 */
6170 if (vd->vdev_children > 2) {
6171 newvd = vd->vdev_child[1];
6172
6173 if (newvd->vdev_isspare && last->vdev_isspare &&
6174 vdev_dtl_empty(last, DTL_MISSING) &&
6175 vdev_dtl_empty(last, DTL_OUTAGE) &&
6176 !vdev_dtl_required(newvd))
6177 return (newvd);
6178 }
6179 }
6180
6181 return (NULL);
6182 }
6183
6184 static void
6185 spa_vdev_resilver_done(spa_t *spa)
6186 {
6187 vdev_t *vd, *pvd, *ppvd;
6188 uint64_t guid, sguid, pguid, ppguid;
6189
6190 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
6191
6192 while ((vd = spa_vdev_resilver_done_hunt(spa->spa_root_vdev)) != NULL) {
6193 pvd = vd->vdev_parent;
6194 ppvd = pvd->vdev_parent;
6195 guid = vd->vdev_guid;
6196 pguid = pvd->vdev_guid;
6197 ppguid = ppvd->vdev_guid;
6198 sguid = 0;
6199 /*
6200 * If we have just finished replacing a hot spared device, then
6201 * we need to detach the parent's first child (the original hot
6202 * spare) as well.
6203 */
6204 if (ppvd->vdev_ops == &vdev_spare_ops && pvd->vdev_id == 0 &&
6205 ppvd->vdev_children == 2) {
6206 ASSERT(pvd->vdev_ops == &vdev_replacing_ops);
6207 sguid = ppvd->vdev_child[1]->vdev_guid;
6208 }
6209 ASSERT(vd->vdev_resilver_txg == 0 || !vdev_dtl_required(vd));
6210
6211 spa_config_exit(spa, SCL_ALL, FTAG);
6212 if (spa_vdev_detach(spa, guid, pguid, B_TRUE) != 0)
6213 return;
6214 if (sguid && spa_vdev_detach(spa, sguid, ppguid, B_TRUE) != 0)
6215 return;
6216 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
6217 }
6218
6219 spa_config_exit(spa, SCL_ALL, FTAG);
6220 }
6221
6222 /*
6223 * ==========================================================================
6224 * SPA Scanning
6225 * ==========================================================================
6226 */
6227 int
6228 spa_scrub_pause_resume(spa_t *spa, pool_scrub_cmd_t cmd)
6229 {
6230 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
6231
6232 if (dsl_scan_resilvering(spa->spa_dsl_pool))
6233 return (SET_ERROR(EBUSY));
6234
6235 return (dsl_scrub_set_pause_resume(spa->spa_dsl_pool, cmd));
6236 }
6237
6238 int
6239 spa_scan_stop(spa_t *spa)
6240 {
6241 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
6242 if (dsl_scan_resilvering(spa->spa_dsl_pool))
6243 return (SET_ERROR(EBUSY));
6244 return (dsl_scan_cancel(spa->spa_dsl_pool));
6245 }
6246
6247 int
6248 spa_scan(spa_t *spa, pool_scan_func_t func)
6249 {
6250 ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == 0);
6251
6252 if (func >= POOL_SCAN_FUNCS || func == POOL_SCAN_NONE)
6253 return (SET_ERROR(ENOTSUP));
6254
6255 /*
6256 * If a resilver was requested, but there is no DTL on a
6257 * writeable leaf device, we have nothing to do.
6258 */
6259 if (func == POOL_SCAN_RESILVER &&
6260 !vdev_resilver_needed(spa->spa_root_vdev, NULL, NULL)) {
6261 spa_async_request(spa, SPA_ASYNC_RESILVER_DONE);
6262 return (0);
6263 }
6264
6265 return (dsl_scan(spa->spa_dsl_pool, func));
6266 }
6267
6268 /*
6269 * ==========================================================================
6270 * SPA async task processing
6271 * ==========================================================================
6272 */
6273
6274 static void
6275 spa_async_remove(spa_t *spa, vdev_t *vd)
6276 {
6277 if (vd->vdev_remove_wanted) {
6278 vd->vdev_remove_wanted = B_FALSE;
6279 vd->vdev_delayed_close = B_FALSE;
6280 vdev_set_state(vd, B_FALSE, VDEV_STATE_REMOVED, VDEV_AUX_NONE);
6281
6282 /*
6283 * We want to clear the stats, but we don't want to do a full
6284 * vdev_clear() as that will cause us to throw away
6285 * degraded/faulted state as well as attempt to reopen the
6286 * device, all of which is a waste.
6287 */
6288 vd->vdev_stat.vs_read_errors = 0;
6289 vd->vdev_stat.vs_write_errors = 0;
6290 vd->vdev_stat.vs_checksum_errors = 0;
6291
6292 vdev_state_dirty(vd->vdev_top);
6293 }
6294
6295 for (int c = 0; c < vd->vdev_children; c++)
6296 spa_async_remove(spa, vd->vdev_child[c]);
6297 }
6298
6299 static void
6300 spa_async_probe(spa_t *spa, vdev_t *vd)
6301 {
6302 if (vd->vdev_probe_wanted) {
6303 vd->vdev_probe_wanted = B_FALSE;
6304 vdev_reopen(vd); /* vdev_open() does the actual probe */
6305 }
6306
6307 for (int c = 0; c < vd->vdev_children; c++)
6308 spa_async_probe(spa, vd->vdev_child[c]);
6309 }
6310
6311 static void
6312 spa_async_autoexpand(spa_t *spa, vdev_t *vd)
6313 {
6314 sysevent_id_t eid;
6315 nvlist_t *attr;
6316 char *physpath;
6317
6318 if (!spa->spa_autoexpand)
6319 return;
6320
6321 for (int c = 0; c < vd->vdev_children; c++) {
6322 vdev_t *cvd = vd->vdev_child[c];
6323 spa_async_autoexpand(spa, cvd);
6324 }
6325
6326 if (!vd->vdev_ops->vdev_op_leaf || vd->vdev_physpath == NULL)
6327 return;
6328
6329 physpath = kmem_zalloc(MAXPATHLEN, KM_SLEEP);
6330 (void) snprintf(physpath, MAXPATHLEN, "/devices%s", vd->vdev_physpath);
6331
6332 VERIFY(nvlist_alloc(&attr, NV_UNIQUE_NAME, KM_SLEEP) == 0);
6333 VERIFY(nvlist_add_string(attr, DEV_PHYS_PATH, physpath) == 0);
6334
6335 (void) ddi_log_sysevent(zfs_dip, SUNW_VENDOR, EC_DEV_STATUS,
6336 ESC_DEV_DLE, attr, &eid, DDI_SLEEP);
6337
6338 nvlist_free(attr);
6339 kmem_free(physpath, MAXPATHLEN);
6340 }
6341
6342 static void
6343 spa_async_thread(void *arg)
6344 {
6345 spa_t *spa = (spa_t *)arg;
6346 int tasks;
6347
6348 ASSERT(spa->spa_sync_on);
6349
6350 mutex_enter(&spa->spa_async_lock);
6351 tasks = spa->spa_async_tasks;
6352 spa->spa_async_tasks = 0;
6353 mutex_exit(&spa->spa_async_lock);
6354
6355 /*
6356 * See if the config needs to be updated.
6357 */
6358 if (tasks & SPA_ASYNC_CONFIG_UPDATE) {
6359 uint64_t old_space, new_space;
6360
6361 mutex_enter(&spa_namespace_lock);
6362 old_space = metaslab_class_get_space(spa_normal_class(spa));
6363 spa_config_update(spa, SPA_CONFIG_UPDATE_POOL);
6364 new_space = metaslab_class_get_space(spa_normal_class(spa));
6365 mutex_exit(&spa_namespace_lock);
6366
6367 /*
6368 * If the pool grew as a result of the config update,
6369 * then log an internal history event.
6370 */
6371 if (new_space != old_space) {
6372 spa_history_log_internal(spa, "vdev online", NULL,
6373 "pool '%s' size: %llu(+%llu)",
6374 spa_name(spa), new_space, new_space - old_space);
6375 }
6376 }
6377
6378 /*
6379 * See if any devices need to be marked REMOVED.
6380 */
6381 if (tasks & SPA_ASYNC_REMOVE) {
6382 spa_vdev_state_enter(spa, SCL_NONE);
6383 spa_async_remove(spa, spa->spa_root_vdev);
6384 for (int i = 0; i < spa->spa_l2cache.sav_count; i++)
6385 spa_async_remove(spa, spa->spa_l2cache.sav_vdevs[i]);
6386 for (int i = 0; i < spa->spa_spares.sav_count; i++)
6387 spa_async_remove(spa, spa->spa_spares.sav_vdevs[i]);
6388 (void) spa_vdev_state_exit(spa, NULL, 0);
6389 }
6390
6391 if ((tasks & SPA_ASYNC_AUTOEXPAND) && !spa_suspended(spa)) {
6392 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
6393 spa_async_autoexpand(spa, spa->spa_root_vdev);
6394 spa_config_exit(spa, SCL_CONFIG, FTAG);
6395 }
6396
6397 /*
6398 * See if any devices need to be probed.
6399 */
6400 if (tasks & SPA_ASYNC_PROBE) {
6401 spa_vdev_state_enter(spa, SCL_NONE);
6402 spa_async_probe(spa, spa->spa_root_vdev);
6403 (void) spa_vdev_state_exit(spa, NULL, 0);
6404 }
6405
6406 /*
6407 * If any devices are done replacing, detach them.
6408 */
6409 if (tasks & SPA_ASYNC_RESILVER_DONE)
6410 spa_vdev_resilver_done(spa);
6411
6412 /*
6413 * Kick off a resilver.
6414 */
6415 if (tasks & SPA_ASYNC_RESILVER)
6416 dsl_resilver_restart(spa->spa_dsl_pool, 0);
6417
6418 /*
6419 * Kick off L2 cache rebuilding.
6420 */
6421 if (tasks & SPA_ASYNC_L2CACHE_REBUILD)
6422 l2arc_spa_rebuild_start(spa);
6423
6424 if (tasks & SPA_ASYNC_MAN_TRIM_TASKQ_DESTROY) {
6425 mutex_enter(&spa->spa_man_trim_lock);
6426 spa_man_trim_taskq_destroy(spa);
6427 mutex_exit(&spa->spa_man_trim_lock);
6428 }
6429
6430 /*
6431 * Let the world know that we're done.
6432 */
6433 mutex_enter(&spa->spa_async_lock);
6434 spa->spa_async_thread = NULL;
6435 cv_broadcast(&spa->spa_async_cv);
6436 mutex_exit(&spa->spa_async_lock);
6437 thread_exit();
6438 }
6439
6440 void
6441 spa_async_suspend(spa_t *spa)
6442 {
6443 mutex_enter(&spa->spa_async_lock);
6444 spa->spa_async_suspended++;
6445 while (spa->spa_async_thread != NULL)
6446 cv_wait(&spa->spa_async_cv, &spa->spa_async_lock);
6447 mutex_exit(&spa->spa_async_lock);
6448 }
6449
6450 void
6451 spa_async_resume(spa_t *spa)
6452 {
6453 mutex_enter(&spa->spa_async_lock);
6454 ASSERT(spa->spa_async_suspended != 0);
6455 spa->spa_async_suspended--;
6456 mutex_exit(&spa->spa_async_lock);
6457 }
6458
6459 static boolean_t
6460 spa_async_tasks_pending(spa_t *spa)
6461 {
6462 uint_t non_config_tasks;
6463 uint_t config_task;
6464 boolean_t config_task_suspended;
6465
6466 non_config_tasks = spa->spa_async_tasks & ~SPA_ASYNC_CONFIG_UPDATE;
6467 config_task = spa->spa_async_tasks & SPA_ASYNC_CONFIG_UPDATE;
6468 if (spa->spa_ccw_fail_time == 0) {
6469 config_task_suspended = B_FALSE;
6470 } else {
6471 config_task_suspended =
6472 (gethrtime() - spa->spa_ccw_fail_time) <
6473 (zfs_ccw_retry_interval * NANOSEC);
6474 }
6475
6476 return (non_config_tasks || (config_task && !config_task_suspended));
6477 }
6478
6479 static void
6480 spa_async_dispatch(spa_t *spa)
6481 {
6482 mutex_enter(&spa->spa_async_lock);
6483 if (spa_async_tasks_pending(spa) &&
6484 !spa->spa_async_suspended &&
6485 spa->spa_async_thread == NULL &&
6486 rootdir != NULL)
6487 spa->spa_async_thread = thread_create(NULL, 0,
6488 spa_async_thread, spa, 0, &p0, TS_RUN, maxclsyspri);
6489 mutex_exit(&spa->spa_async_lock);
6490 }
6491
6492 void
6493 spa_async_request(spa_t *spa, int task)
6494 {
6495 zfs_dbgmsg("spa=%s async request task=%u", spa->spa_name, task);
6496 mutex_enter(&spa->spa_async_lock);
6497 spa->spa_async_tasks |= task;
6498 mutex_exit(&spa->spa_async_lock);
6499 }
6500
6501 void
6502 spa_async_unrequest(spa_t *spa, int task)
6503 {
6504 zfs_dbgmsg("spa=%s async unrequest task=%u", spa->spa_name, task);
6505 mutex_enter(&spa->spa_async_lock);
6506 spa->spa_async_tasks &= ~task;
6507 mutex_exit(&spa->spa_async_lock);
6508 }
6509
6510 /*
6511 * ==========================================================================
6512 * SPA syncing routines
6513 * ==========================================================================
6514 */
6515
6516 static int
6517 bpobj_enqueue_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
6518 {
6519 bpobj_t *bpo = arg;
6520 bpobj_enqueue(bpo, bp, tx);
6521 return (0);
6522 }
6523
6524 static int
6525 spa_free_sync_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
6526 {
6527 zio_t *zio = arg;
6528
6529 zio_nowait(zio_free_sync(zio, zio->io_spa, dmu_tx_get_txg(tx), bp,
6530 zio->io_flags));
6531 return (0);
6532 }
6533
6534 /*
6535 * Note: this simple function is not inlined to make it easier to dtrace the
6536 * amount of time spent syncing frees.
6537 */
6538 static void
6539 spa_sync_frees(spa_t *spa, bplist_t *bpl, dmu_tx_t *tx)
6540 {
6541 zio_t *zio = zio_root(spa, NULL, NULL, 0);
6542 bplist_iterate(bpl, spa_free_sync_cb, zio, tx);
6543 VERIFY(zio_wait(zio) == 0);
6544 }
6545
6546 /*
6547 * Note: this simple function is not inlined to make it easier to dtrace the
6548 * amount of time spent syncing deferred frees.
6549 */
6550 static void
6551 spa_sync_deferred_frees(spa_t *spa, dmu_tx_t *tx)
6552 {
6553 zio_t *zio = zio_root(spa, NULL, NULL, 0);
6554 VERIFY3U(bpobj_iterate(&spa->spa_deferred_bpobj,
6555 spa_free_sync_cb, zio, tx), ==, 0);
6556 VERIFY0(zio_wait(zio));
6557 }
6558
6559
6560 static void
6561 spa_sync_nvlist(spa_t *spa, uint64_t obj, nvlist_t *nv, dmu_tx_t *tx)
6562 {
6563 char *packed = NULL;
6564 size_t bufsize;
6565 size_t nvsize = 0;
6566 dmu_buf_t *db;
6567
6568 VERIFY(nvlist_size(nv, &nvsize, NV_ENCODE_XDR) == 0);
6569
6570 /*
6571 * Write full (SPA_CONFIG_BLOCKSIZE) blocks of configuration
6572 * information. This avoids the dmu_buf_will_dirty() path and
6573 * saves us a pre-read to get data we don't actually care about.
6574 */
6575 bufsize = P2ROUNDUP((uint64_t)nvsize, SPA_CONFIG_BLOCKSIZE);
6576 packed = kmem_alloc(bufsize, KM_SLEEP);
6577
6578 VERIFY(nvlist_pack(nv, &packed, &nvsize, NV_ENCODE_XDR,
6579 KM_SLEEP) == 0);
6580 bzero(packed + nvsize, bufsize - nvsize);
6581
6582 dmu_write(spa->spa_meta_objset, obj, 0, bufsize, packed, tx);
6583
6584 kmem_free(packed, bufsize);
6585
6586 VERIFY(0 == dmu_bonus_hold(spa->spa_meta_objset, obj, FTAG, &db));
6587 dmu_buf_will_dirty(db, tx);
6588 *(uint64_t *)db->db_data = nvsize;
6589 dmu_buf_rele(db, FTAG);
6590 }
6591
6592 static void
6593 spa_sync_aux_dev(spa_t *spa, spa_aux_vdev_t *sav, dmu_tx_t *tx,
6594 const char *config, const char *entry)
6595 {
6596 nvlist_t *nvroot;
6597 nvlist_t **list;
6598 int i;
6599
6600 if (!sav->sav_sync)
6601 return;
6602
6603 /*
6604 * Update the MOS nvlist describing the list of available devices.
6605 * spa_validate_aux() will have already made sure this nvlist is
6606 * valid and the vdevs are labeled appropriately.
6607 */
6608 if (sav->sav_object == 0) {
6609 sav->sav_object = dmu_object_alloc(spa->spa_meta_objset,
6610 DMU_OT_PACKED_NVLIST, 1 << 14, DMU_OT_PACKED_NVLIST_SIZE,
6611 sizeof (uint64_t), tx);
6612 VERIFY(zap_update(spa->spa_meta_objset,
6613 DMU_POOL_DIRECTORY_OBJECT, entry, sizeof (uint64_t), 1,
6614 &sav->sav_object, tx) == 0);
6615 }
6616
6617 VERIFY(nvlist_alloc(&nvroot, NV_UNIQUE_NAME, KM_SLEEP) == 0);
6618 if (sav->sav_count == 0) {
6619 VERIFY(nvlist_add_nvlist_array(nvroot, config, NULL, 0) == 0);
6620 } else {
6621 list = kmem_alloc(sav->sav_count * sizeof (void *), KM_SLEEP);
6622 for (i = 0; i < sav->sav_count; i++)
6623 list[i] = vdev_config_generate(spa, sav->sav_vdevs[i],
6624 B_FALSE, VDEV_CONFIG_L2CACHE);
6625 VERIFY(nvlist_add_nvlist_array(nvroot, config, list,
6626 sav->sav_count) == 0);
6627 for (i = 0; i < sav->sav_count; i++)
6628 nvlist_free(list[i]);
6629 kmem_free(list, sav->sav_count * sizeof (void *));
6630 }
6631
6632 spa_sync_nvlist(spa, sav->sav_object, nvroot, tx);
6633 nvlist_free(nvroot);
6634
6635 sav->sav_sync = B_FALSE;
6636 }
6637
6638 /*
6639 * Rebuild spa's all-vdev ZAP from the vdev ZAPs indicated in each vdev_t.
6640 * The all-vdev ZAP must be empty.
6641 */
6642 static void
6643 spa_avz_build(vdev_t *vd, uint64_t avz, dmu_tx_t *tx)
6644 {
6645 spa_t *spa = vd->vdev_spa;
6646 if (vd->vdev_top_zap != 0) {
6647 VERIFY0(zap_add_int(spa->spa_meta_objset, avz,
6648 vd->vdev_top_zap, tx));
6649 }
6650 if (vd->vdev_leaf_zap != 0) {
6651 VERIFY0(zap_add_int(spa->spa_meta_objset, avz,
6652 vd->vdev_leaf_zap, tx));
6653 }
6654 for (uint64_t i = 0; i < vd->vdev_children; i++) {
6655 spa_avz_build(vd->vdev_child[i], avz, tx);
6656 }
6657 }
6658
6659 static void
6660 spa_sync_config_object(spa_t *spa, dmu_tx_t *tx)
6661 {
6662 nvlist_t *config;
6663
6664 /*
6665 * If the pool is being imported from a pre-per-vdev-ZAP version of ZFS,
6666 * its config may not be dirty but we still need to build per-vdev ZAPs.
6667 * Similarly, if the pool is being assembled (e.g. after a split), we
6668 * need to rebuild the AVZ although the config may not be dirty.
6669 */
6670 if (list_is_empty(&spa->spa_config_dirty_list) &&
6671 spa->spa_avz_action == AVZ_ACTION_NONE)
6672 return;
6673
6674 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
6675
6676 ASSERT(spa->spa_avz_action == AVZ_ACTION_NONE ||
6677 spa->spa_avz_action == AVZ_ACTION_INITIALIZE ||
6678 spa->spa_all_vdev_zaps != 0);
6679
6680 if (spa->spa_avz_action == AVZ_ACTION_REBUILD) {
6681 /* Make and build the new AVZ */
6682 uint64_t new_avz = zap_create(spa->spa_meta_objset,
6683 DMU_OTN_ZAP_METADATA, DMU_OT_NONE, 0, tx);
6684 spa_avz_build(spa->spa_root_vdev, new_avz, tx);
6685
6686 /* Diff old AVZ with new one */
6687 zap_cursor_t zc;
6688 zap_attribute_t za;
6689
6690 for (zap_cursor_init(&zc, spa->spa_meta_objset,
6691 spa->spa_all_vdev_zaps);
6692 zap_cursor_retrieve(&zc, &za) == 0;
6693 zap_cursor_advance(&zc)) {
6694 uint64_t vdzap = za.za_first_integer;
6695 if (zap_lookup_int(spa->spa_meta_objset, new_avz,
6696 vdzap) == ENOENT) {
6697 /*
6698 * ZAP is listed in old AVZ but not in new one;
6699 * destroy it
6700 */
6701 VERIFY0(zap_destroy(spa->spa_meta_objset, vdzap,
6702 tx));
6703 }
6704 }
6705
6706 zap_cursor_fini(&zc);
6707
6708 /* Destroy the old AVZ */
6709 VERIFY0(zap_destroy(spa->spa_meta_objset,
6710 spa->spa_all_vdev_zaps, tx));
6711
6712 /* Replace the old AVZ in the dir obj with the new one */
6713 VERIFY0(zap_update(spa->spa_meta_objset,
6714 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_VDEV_ZAP_MAP,
6715 sizeof (new_avz), 1, &new_avz, tx));
6716
6717 spa->spa_all_vdev_zaps = new_avz;
6718 } else if (spa->spa_avz_action == AVZ_ACTION_DESTROY) {
6719 zap_cursor_t zc;
6720 zap_attribute_t za;
6721
6722 /* Walk through the AVZ and destroy all listed ZAPs */
6723 for (zap_cursor_init(&zc, spa->spa_meta_objset,
6724 spa->spa_all_vdev_zaps);
6725 zap_cursor_retrieve(&zc, &za) == 0;
6726 zap_cursor_advance(&zc)) {
6727 uint64_t zap = za.za_first_integer;
6728 VERIFY0(zap_destroy(spa->spa_meta_objset, zap, tx));
6729 }
6730
6731 zap_cursor_fini(&zc);
6732
6733 /* Destroy and unlink the AVZ itself */
6734 VERIFY0(zap_destroy(spa->spa_meta_objset,
6735 spa->spa_all_vdev_zaps, tx));
6736 VERIFY0(zap_remove(spa->spa_meta_objset,
6737 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_VDEV_ZAP_MAP, tx));
6738 spa->spa_all_vdev_zaps = 0;
6739 }
6740
6741 if (spa->spa_all_vdev_zaps == 0) {
6742 spa->spa_all_vdev_zaps = zap_create_link(spa->spa_meta_objset,
6743 DMU_OTN_ZAP_METADATA, DMU_POOL_DIRECTORY_OBJECT,
6744 DMU_POOL_VDEV_ZAP_MAP, tx);
6745 }
6746 spa->spa_avz_action = AVZ_ACTION_NONE;
6747
6748 /* Create ZAPs for vdevs that don't have them. */
6749 vdev_construct_zaps(spa->spa_root_vdev, tx);
6750
6751 config = spa_config_generate(spa, spa->spa_root_vdev,
6752 dmu_tx_get_txg(tx), B_FALSE);
6753
6754 /*
6755 * If we're upgrading the spa version then make sure that
6756 * the config object gets updated with the correct version.
6757 */
6758 if (spa->spa_ubsync.ub_version < spa->spa_uberblock.ub_version)
6759 fnvlist_add_uint64(config, ZPOOL_CONFIG_VERSION,
6760 spa->spa_uberblock.ub_version);
6761
6762 spa_config_exit(spa, SCL_STATE, FTAG);
6763
6764 nvlist_free(spa->spa_config_syncing);
6765 spa->spa_config_syncing = config;
6766
6767 spa_sync_nvlist(spa, spa->spa_config_object, config, tx);
6768 }
6769
6770 static void
6771 spa_sync_version(void *arg, dmu_tx_t *tx)
6772 {
6773 uint64_t *versionp = arg;
6774 uint64_t version = *versionp;
6775 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
6776
6777 /*
6778 * Setting the version is special cased when first creating the pool.
6779 */
6780 ASSERT(tx->tx_txg != TXG_INITIAL);
6781
6782 ASSERT(SPA_VERSION_IS_SUPPORTED(version));
6783 ASSERT(version >= spa_version(spa));
6784
6785 spa->spa_uberblock.ub_version = version;
6786 vdev_config_dirty(spa->spa_root_vdev);
6787 spa_history_log_internal(spa, "set", tx, "version=%lld", version);
6788 }
6789
6790 /*
6791 * Set zpool properties.
6792 */
6793 static void
6794 spa_sync_props(void *arg, dmu_tx_t *tx)
6795 {
6796 nvlist_t *nvp = arg;
6797 spa_t *spa = dmu_tx_pool(tx)->dp_spa;
6798 spa_meta_placement_t *mp = &spa->spa_meta_policy;
6799 objset_t *mos = spa->spa_meta_objset;
6800 nvpair_t *elem = NULL;
6801
6802 mutex_enter(&spa->spa_props_lock);
6803
6804 while ((elem = nvlist_next_nvpair(nvp, elem))) {
6805 uint64_t intval;
6806 char *strval, *fname;
6807 zpool_prop_t prop;
6808 const char *propname;
6809 zprop_type_t proptype;
6810 spa_feature_t fid;
6811
6812 switch (prop = zpool_name_to_prop(nvpair_name(elem))) {
6813 case ZPROP_INVAL:
6814 /*
6815 * We checked this earlier in spa_prop_validate().
6816 */
6817 ASSERT(zpool_prop_feature(nvpair_name(elem)));
6818
6819 fname = strchr(nvpair_name(elem), '@') + 1;
6820 VERIFY0(zfeature_lookup_name(fname, &fid));
6821
6822 spa_feature_enable(spa, fid, tx);
6823 spa_history_log_internal(spa, "set", tx,
6824 "%s=enabled", nvpair_name(elem));
6825 break;
6826
6827 case ZPOOL_PROP_VERSION:
6828 intval = fnvpair_value_uint64(elem);
6829 /*
6830 * The version is synced seperatly before other
6831 * properties and should be correct by now.
6832 */
6833 ASSERT3U(spa_version(spa), >=, intval);
6834 break;
6835
6836 case ZPOOL_PROP_ALTROOT:
6837 /*
6838 * 'altroot' is a non-persistent property. It should
6839 * have been set temporarily at creation or import time.
6840 */
6841 ASSERT(spa->spa_root != NULL);
6842 break;
6843
6844 case ZPOOL_PROP_READONLY:
6845 case ZPOOL_PROP_CACHEFILE:
6846 /*
6847 * 'readonly' and 'cachefile' are also non-persisitent
6848 * properties.
6849 */
6850 break;
6851 case ZPOOL_PROP_COMMENT:
6852 strval = fnvpair_value_string(elem);
6853 if (spa->spa_comment != NULL)
6854 spa_strfree(spa->spa_comment);
6855 spa->spa_comment = spa_strdup(strval);
6856 /*
6857 * We need to dirty the configuration on all the vdevs
6858 * so that their labels get updated. It's unnecessary
6859 * to do this for pool creation since the vdev's
6860 * configuratoin has already been dirtied.
6861 */
6862 if (tx->tx_txg != TXG_INITIAL)
6863 vdev_config_dirty(spa->spa_root_vdev);
6864 spa_history_log_internal(spa, "set", tx,
6865 "%s=%s", nvpair_name(elem), strval);
6866 break;
6867 default:
6868 /*
6869 * Set pool property values in the poolprops mos object.
6870 */
6871 if (spa->spa_pool_props_object == 0) {
6872 spa->spa_pool_props_object =
6873 zap_create_link(mos, DMU_OT_POOL_PROPS,
6874 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_PROPS,
6875 tx);
6876 }
6877
6878 /* normalize the property name */
6879 propname = zpool_prop_to_name(prop);
6880 proptype = zpool_prop_get_type(prop);
6881
6882 if (nvpair_type(elem) == DATA_TYPE_STRING) {
6883 ASSERT(proptype == PROP_TYPE_STRING);
6884 strval = fnvpair_value_string(elem);
6885 VERIFY0(zap_update(mos,
6886 spa->spa_pool_props_object, propname,
6887 1, strlen(strval) + 1, strval, tx));
6888 spa_history_log_internal(spa, "set", tx,
6889 "%s=%s", nvpair_name(elem), strval);
6890 } else if (nvpair_type(elem) == DATA_TYPE_UINT64) {
6891 intval = fnvpair_value_uint64(elem);
6892
6893 if (proptype == PROP_TYPE_INDEX) {
6894 const char *unused;
6895 VERIFY0(zpool_prop_index_to_string(
6896 prop, intval, &unused));
6897 }
6898 VERIFY0(zap_update(mos,
6899 spa->spa_pool_props_object, propname,
6900 8, 1, &intval, tx));
6901 spa_history_log_internal(spa, "set", tx,
6902 "%s=%lld", nvpair_name(elem), intval);
6903 } else {
6904 ASSERT(0); /* not allowed */
6905 }
6906
6907 switch (prop) {
6908 case ZPOOL_PROP_DELEGATION:
6909 spa->spa_delegation = intval;
6910 break;
6911 case ZPOOL_PROP_DDT_DESEGREGATION:
6912 spa_set_ddt_classes(spa, intval);
6913 break;
6914 case ZPOOL_PROP_DEDUP_BEST_EFFORT:
6915 spa->spa_dedup_best_effort = intval;
6916 break;
6917 case ZPOOL_PROP_DEDUP_LO_BEST_EFFORT:
6918 spa->spa_dedup_lo_best_effort = intval;
6919 break;
6920 case ZPOOL_PROP_DEDUP_HI_BEST_EFFORT:
6921 spa->spa_dedup_hi_best_effort = intval;
6922 break;
6923 case ZPOOL_PROP_BOOTFS:
6924 spa->spa_bootfs = intval;
6925 break;
6926 case ZPOOL_PROP_FAILUREMODE:
6927 spa->spa_failmode = intval;
6928 break;
6929 case ZPOOL_PROP_FORCETRIM:
6930 spa->spa_force_trim = intval;
6931 break;
6932 case ZPOOL_PROP_AUTOTRIM:
6933 mutex_enter(&spa->spa_auto_trim_lock);
6934 if (intval != spa->spa_auto_trim) {
6935 spa->spa_auto_trim = intval;
6936 if (intval != 0)
6937 spa_auto_trim_taskq_create(spa);
6938 else
6939 spa_auto_trim_taskq_destroy(
6940 spa);
6941 }
6942 mutex_exit(&spa->spa_auto_trim_lock);
6943 break;
6944 case ZPOOL_PROP_AUTOEXPAND:
6945 spa->spa_autoexpand = intval;
6946 if (tx->tx_txg != TXG_INITIAL)
6947 spa_async_request(spa,
6948 SPA_ASYNC_AUTOEXPAND);
6949 break;
6950 case ZPOOL_PROP_DEDUPDITTO:
6951 spa->spa_dedup_ditto = intval;
6952 break;
6953 case ZPOOL_PROP_MINWATERMARK:
6954 spa->spa_minwat = intval;
6955 break;
6956 case ZPOOL_PROP_LOWATERMARK:
6957 spa->spa_lowat = intval;
6958 break;
6959 case ZPOOL_PROP_HIWATERMARK:
6960 spa->spa_hiwat = intval;
6961 break;
6962 case ZPOOL_PROP_DEDUPMETA_DITTO:
6963 spa->spa_ddt_meta_copies = intval;
6964 break;
6965 case ZPOOL_PROP_META_PLACEMENT:
6966 mp->spa_enable_meta_placement_selection =
6967 intval;
6968 break;
6969 case ZPOOL_PROP_SYNC_TO_SPECIAL:
6970 mp->spa_sync_to_special = intval;
6971 break;
6972 case ZPOOL_PROP_DDT_META_TO_METADEV:
6973 mp->spa_ddt_meta_to_special = intval;
6974 break;
6975 case ZPOOL_PROP_ZFS_META_TO_METADEV:
6976 mp->spa_zfs_meta_to_special = intval;
6977 break;
6978 case ZPOOL_PROP_SMALL_DATA_TO_METADEV:
6979 mp->spa_small_data_to_special = intval;
6980 break;
6981 case ZPOOL_PROP_RESILVER_PRIO:
6982 spa->spa_resilver_prio = intval;
6983 break;
6984 case ZPOOL_PROP_SCRUB_PRIO:
6985 spa->spa_scrub_prio = intval;
6986 break;
6987 default:
6988 break;
6989 }
6990 }
6991
6992 }
6993
6994 mutex_exit(&spa->spa_props_lock);
6995 }
6996
6997 /*
6998 * Perform one-time upgrade on-disk changes. spa_version() does not
6999 * reflect the new version this txg, so there must be no changes this
7000 * txg to anything that the upgrade code depends on after it executes.
7001 * Therefore this must be called after dsl_pool_sync() does the sync
7002 * tasks.
7003 */
7004 static void
7005 spa_sync_upgrades(spa_t *spa, dmu_tx_t *tx)
7006 {
7007 dsl_pool_t *dp = spa->spa_dsl_pool;
7008
7009 ASSERT(spa->spa_sync_pass == 1);
7010
7011 rrw_enter(&dp->dp_config_rwlock, RW_WRITER, FTAG);
7012
7013 if (spa->spa_ubsync.ub_version < SPA_VERSION_ORIGIN &&
7014 spa->spa_uberblock.ub_version >= SPA_VERSION_ORIGIN) {
7015 dsl_pool_create_origin(dp, tx);
7016
7017 /* Keeping the origin open increases spa_minref */
7018 spa->spa_minref += 3;
7019 }
7020
7021 if (spa->spa_ubsync.ub_version < SPA_VERSION_NEXT_CLONES &&
7022 spa->spa_uberblock.ub_version >= SPA_VERSION_NEXT_CLONES) {
7023 dsl_pool_upgrade_clones(dp, tx);
7024 }
7025
7026 if (spa->spa_ubsync.ub_version < SPA_VERSION_DIR_CLONES &&
7027 spa->spa_uberblock.ub_version >= SPA_VERSION_DIR_CLONES) {
7028 dsl_pool_upgrade_dir_clones(dp, tx);
7029
7030 /* Keeping the freedir open increases spa_minref */
7031 spa->spa_minref += 3;
7032 }
7033
7034 if (spa->spa_ubsync.ub_version < SPA_VERSION_FEATURES &&
7035 spa->spa_uberblock.ub_version >= SPA_VERSION_FEATURES) {
7036 spa_feature_create_zap_objects(spa, tx);
7037 }
7038
7039 /*
7040 * LZ4_COMPRESS feature's behaviour was changed to activate_on_enable
7041 * when possibility to use lz4 compression for metadata was added
7042 * Old pools that have this feature enabled must be upgraded to have
7043 * this feature active
7044 */
7045 if (spa->spa_uberblock.ub_version >= SPA_VERSION_FEATURES) {
7046 boolean_t lz4_en = spa_feature_is_enabled(spa,
7047 SPA_FEATURE_LZ4_COMPRESS);
7048 boolean_t lz4_ac = spa_feature_is_active(spa,
7049 SPA_FEATURE_LZ4_COMPRESS);
7050
7051 if (lz4_en && !lz4_ac)
7052 spa_feature_incr(spa, SPA_FEATURE_LZ4_COMPRESS, tx);
7053 }
7054
7055 /*
7056 * If we haven't written the salt, do so now. Note that the
7057 * feature may not be activated yet, but that's fine since
7058 * the presence of this ZAP entry is backwards compatible.
7059 */
7060 if (zap_contains(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
7061 DMU_POOL_CHECKSUM_SALT) == ENOENT) {
7062 VERIFY0(zap_add(spa->spa_meta_objset,
7063 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_CHECKSUM_SALT, 1,
7064 sizeof (spa->spa_cksum_salt.zcs_bytes),
7065 spa->spa_cksum_salt.zcs_bytes, tx));
7066 }
7067
7068 rrw_exit(&dp->dp_config_rwlock, FTAG);
7069 }
7070
7071 static void
7072 spa_initialize_alloc_trees(spa_t *spa, uint32_t max_queue_depth,
7073 uint64_t queue_depth_total)
7074 {
7075 vdev_t *rvd = spa->spa_root_vdev;
7076 boolean_t dva_throttle_enabled = zio_dva_throttle_enabled;
7077 metaslab_class_t *mcs[2] = {
7078 spa_normal_class(spa),
7079 spa_special_class(spa)
7080 };
7081 size_t mcs_len = sizeof (mcs) / sizeof (metaslab_class_t *);
7082
7083 for (size_t i = 0; i < mcs_len; i++) {
7084 metaslab_class_t *mc = mcs[i];
7085
7086 ASSERT0(refcount_count(&mc->mc_alloc_slots));
7087 mc->mc_alloc_max_slots = queue_depth_total;
7088 mc->mc_alloc_throttle_enabled = dva_throttle_enabled;
7089
7090 ASSERT3U(mc->mc_alloc_max_slots, <=,
7091 max_queue_depth * rvd->vdev_children);
7092 }
7093 }
7094
7095 static void
7096 spa_check_alloc_trees(spa_t *spa)
7097 {
7098 metaslab_class_t *mcs[2] = {
7099 spa_normal_class(spa),
7100 spa_special_class(spa)
7101 };
7102 size_t mcs_len = sizeof (mcs) / sizeof (metaslab_class_t *);
7103
7104 for (size_t i = 0; i < mcs_len; i++) {
7105 metaslab_class_t *mc = mcs[i];
7106
7107 mutex_enter(&mc->mc_alloc_lock);
7108 VERIFY0(avl_numnodes(&mc->mc_alloc_tree));
7109 mutex_exit(&mc->mc_alloc_lock);
7110 }
7111 }
7112
7113 /*
7114 * Sync the specified transaction group. New blocks may be dirtied as
7115 * part of the process, so we iterate until it converges.
7116 */
7117 void
7118 spa_sync(spa_t *spa, uint64_t txg)
7119 {
7120 dsl_pool_t *dp = spa->spa_dsl_pool;
7121 objset_t *mos = spa->spa_meta_objset;
7122 bplist_t *free_bpl = &spa->spa_free_bplist[txg & TXG_MASK];
7123 vdev_t *rvd = spa->spa_root_vdev;
7124 vdev_t *vd;
7125 dmu_tx_t *tx;
7126 int error;
7127 uint32_t max_queue_depth = zfs_vdev_async_write_max_active *
7128 zfs_vdev_queue_depth_pct / 100;
7129
7130 VERIFY(spa_writeable(spa));
7131
7132 /*
7133 * Lock out configuration changes.
7134 */
7135 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
7136
7137 spa->spa_syncing_txg = txg;
7138 spa->spa_sync_pass = 0;
7139
7140 spa_check_alloc_trees(spa);
7141
7142 /*
7143 * Another pool management task might be currently preventing
7144 * from starting and the current txg sync was invoked on its behalf,
7145 * so be prepared to postpone autotrim processing.
7146 */
7147 if (mutex_tryenter(&spa->spa_auto_trim_lock)) {
7148 if (spa->spa_auto_trim == SPA_AUTO_TRIM_ON)
7149 spa_auto_trim(spa, txg);
7150 mutex_exit(&spa->spa_auto_trim_lock);
7151 }
7152
7153 /*
7154 * If there are any pending vdev state changes, convert them
7155 * into config changes that go out with this transaction group.
7156 */
7157 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
7158 while (list_head(&spa->spa_state_dirty_list) != NULL) {
7159 /*
7160 * We need the write lock here because, for aux vdevs,
7161 * calling vdev_config_dirty() modifies sav_config.
7162 * This is ugly and will become unnecessary when we
7163 * eliminate the aux vdev wart by integrating all vdevs
7164 * into the root vdev tree.
7165 */
7166 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
7167 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_WRITER);
7168 while ((vd = list_head(&spa->spa_state_dirty_list)) != NULL) {
7169 vdev_state_clean(vd);
7170 vdev_config_dirty(vd);
7171 }
7172 spa_config_exit(spa, SCL_CONFIG | SCL_STATE, FTAG);
7173 spa_config_enter(spa, SCL_CONFIG | SCL_STATE, FTAG, RW_READER);
7174 }
7175 spa_config_exit(spa, SCL_STATE, FTAG);
7176
7177 tx = dmu_tx_create_assigned(dp, txg);
7178
7179 spa->spa_sync_starttime = gethrtime();
7180 VERIFY(cyclic_reprogram(spa->spa_deadman_cycid,
7181 spa->spa_sync_starttime + spa->spa_deadman_synctime));
7182
7183 /*
7184 * If we are upgrading to SPA_VERSION_RAIDZ_DEFLATE this txg,
7185 * set spa_deflate if we have no raid-z vdevs.
7186 */
7187 if (spa->spa_ubsync.ub_version < SPA_VERSION_RAIDZ_DEFLATE &&
7188 spa->spa_uberblock.ub_version >= SPA_VERSION_RAIDZ_DEFLATE) {
7189 int i;
7190
7191 for (i = 0; i < rvd->vdev_children; i++) {
7192 vd = rvd->vdev_child[i];
7193 if (vd->vdev_deflate_ratio != SPA_MINBLOCKSIZE)
7194 break;
7195 }
7196 if (i == rvd->vdev_children) {
7197 spa->spa_deflate = TRUE;
7198 VERIFY(0 == zap_add(spa->spa_meta_objset,
7199 DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_DEFLATE,
7200 sizeof (uint64_t), 1, &spa->spa_deflate, tx));
7201 }
7202 }
7203
7204 /*
7205 * Set the top-level vdev's max queue depth. Evaluate each
7206 * top-level's async write queue depth in case it changed.
7207 * The max queue depth will not change in the middle of syncing
7208 * out this txg.
7209 */
7210 uint64_t queue_depth_total = 0;
7211 for (int c = 0; c < rvd->vdev_children; c++) {
7212 vdev_t *tvd = rvd->vdev_child[c];
7213 metaslab_group_t *mg = tvd->vdev_mg;
7214
7215 if (mg == NULL || mg->mg_class != spa_normal_class(spa) ||
7216 !metaslab_group_initialized(mg))
7217 continue;
7218
7219 /*
7220 * It is safe to do a lock-free check here because only async
7221 * allocations look at mg_max_alloc_queue_depth, and async
7222 * allocations all happen from spa_sync().
7223 */
7224 ASSERT0(refcount_count(&mg->mg_alloc_queue_depth));
7225 mg->mg_max_alloc_queue_depth = max_queue_depth;
7226 queue_depth_total += mg->mg_max_alloc_queue_depth;
7227 }
7228
7229 spa_initialize_alloc_trees(spa, max_queue_depth,
7230 queue_depth_total);
7231
7232 /*
7233 * Iterate to convergence.
7234 */
7235
7236 zfs_autosnap_t *autosnap = spa_get_autosnap(dp->dp_spa);
7237 mutex_enter(&autosnap->autosnap_lock);
7238
7239 autosnap_zone_t *zone = list_head(&autosnap->autosnap_zones);
7240 while (zone != NULL) {
7241 zone->created = B_FALSE;
7242 zone->dirty = B_FALSE;
7243 zone = list_next(&autosnap->autosnap_zones, zone);
7244 }
7245
7246 mutex_exit(&autosnap->autosnap_lock);
7247
7248 do {
7249 int pass = ++spa->spa_sync_pass;
7250
7251 spa_sync_config_object(spa, tx);
7252 spa_sync_aux_dev(spa, &spa->spa_spares, tx,
7253 ZPOOL_CONFIG_SPARES, DMU_POOL_SPARES);
7254 spa_sync_aux_dev(spa, &spa->spa_l2cache, tx,
7255 ZPOOL_CONFIG_L2CACHE, DMU_POOL_L2CACHE);
7256 spa_errlog_sync(spa, txg);
7257 dsl_pool_sync(dp, txg);
7258
7259 if (pass < zfs_sync_pass_deferred_free) {
7260 spa_sync_frees(spa, free_bpl, tx);
7261 } else {
7262 /*
7263 * We can not defer frees in pass 1, because
7264 * we sync the deferred frees later in pass 1.
7265 */
7266 ASSERT3U(pass, >, 1);
7267 bplist_iterate(free_bpl, bpobj_enqueue_cb,
7268 &spa->spa_deferred_bpobj, tx);
7269 }
7270
7271 ddt_sync(spa, txg);
7272 dsl_scan_sync(dp, tx);
7273
7274 while (vd = txg_list_remove(&spa->spa_vdev_txg_list, txg))
7275 vdev_sync(vd, txg);
7276
7277 if (pass == 1) {
7278 spa_sync_upgrades(spa, tx);
7279 ASSERT3U(txg, >=,
7280 spa->spa_uberblock.ub_rootbp.blk_birth);
7281 /*
7282 * Note: We need to check if the MOS is dirty
7283 * because we could have marked the MOS dirty
7284 * without updating the uberblock (e.g. if we
7285 * have sync tasks but no dirty user data). We
7286 * need to check the uberblock's rootbp because
7287 * it is updated if we have synced out dirty
7288 * data (though in this case the MOS will most
7289 * likely also be dirty due to second order
7290 * effects, we don't want to rely on that here).
7291 */
7292 if (spa->spa_uberblock.ub_rootbp.blk_birth < txg &&
7293 !dmu_objset_is_dirty(mos, txg)) {
7294 /*
7295 * Nothing changed on the first pass,
7296 * therefore this TXG is a no-op. Avoid
7297 * syncing deferred frees, so that we
7298 * can keep this TXG as a no-op.
7299 */
7300 ASSERT(txg_list_empty(&dp->dp_dirty_datasets,
7301 txg));
7302 ASSERT(txg_list_empty(&dp->dp_dirty_dirs, txg));
7303 ASSERT(txg_list_empty(&dp->dp_sync_tasks, txg));
7304 break;
7305 }
7306 spa_sync_deferred_frees(spa, tx);
7307 }
7308
7309 } while (dmu_objset_is_dirty(mos, txg));
7310
7311 if (!list_is_empty(&spa->spa_config_dirty_list)) {
7312 /*
7313 * Make sure that the number of ZAPs for all the vdevs matches
7314 * the number of ZAPs in the per-vdev ZAP list. This only gets
7315 * called if the config is dirty; otherwise there may be
7316 * outstanding AVZ operations that weren't completed in
7317 * spa_sync_config_object.
7318 */
7319 uint64_t all_vdev_zap_entry_count;
7320 ASSERT0(zap_count(spa->spa_meta_objset,
7321 spa->spa_all_vdev_zaps, &all_vdev_zap_entry_count));
7322 ASSERT3U(vdev_count_verify_zaps(spa->spa_root_vdev), ==,
7323 all_vdev_zap_entry_count);
7324 }
7325
7326 /*
7327 * Rewrite the vdev configuration (which includes the uberblock)
7328 * to commit the transaction group.
7329 *
7330 * If there are no dirty vdevs, we sync the uberblock to a few
7331 * random top-level vdevs that are known to be visible in the
7332 * config cache (see spa_vdev_add() for a complete description).
7333 * If there *are* dirty vdevs, sync the uberblock to all vdevs.
7334 */
7335 for (;;) {
7336 /*
7337 * We hold SCL_STATE to prevent vdev open/close/etc.
7338 * while we're attempting to write the vdev labels.
7339 */
7340 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
7341
7342 if (list_is_empty(&spa->spa_config_dirty_list)) {
7343 vdev_t *svd[SPA_DVAS_PER_BP];
7344 int svdcount = 0;
7345 int children = rvd->vdev_children;
7346 int c0 = spa_get_random(children);
7347
7348 for (int c = 0; c < children; c++) {
7349 vd = rvd->vdev_child[(c0 + c) % children];
7350 if (vd->vdev_ms_array == 0 || vd->vdev_islog)
7351 continue;
7352 svd[svdcount++] = vd;
7353 if (svdcount == SPA_DVAS_PER_BP)
7354 break;
7355 }
7356 error = vdev_config_sync(svd, svdcount, txg);
7357 } else {
7358 error = vdev_config_sync(rvd->vdev_child,
7359 rvd->vdev_children, txg);
7360 }
7361
7362 if (error == 0)
7363 spa->spa_last_synced_guid = rvd->vdev_guid;
7364
7365 spa_config_exit(spa, SCL_STATE, FTAG);
7366
7367 if (error == 0)
7368 break;
7369 zio_suspend(spa, NULL);
7370 zio_resume_wait(spa);
7371 }
7372 dmu_tx_commit(tx);
7373
7374 VERIFY(cyclic_reprogram(spa->spa_deadman_cycid, CY_INFINITY));
7375
7376 /*
7377 * Clear the dirty config list.
7378 */
7379 while ((vd = list_head(&spa->spa_config_dirty_list)) != NULL)
7380 vdev_config_clean(vd);
7381
7382 /*
7383 * Now that the new config has synced transactionally,
7384 * let it become visible to the config cache.
7385 */
7386 if (spa->spa_config_syncing != NULL) {
7387 spa_config_set(spa, spa->spa_config_syncing);
7388 spa->spa_config_txg = txg;
7389 spa->spa_config_syncing = NULL;
7390 }
7391
7392 dsl_pool_sync_done(dp, txg);
7393
7394 spa_check_alloc_trees(spa);
7395
7396 /*
7397 * Update usable space statistics.
7398 */
7399 while (vd = txg_list_remove(&spa->spa_vdev_txg_list, TXG_CLEAN(txg)))
7400 vdev_sync_done(vd, txg);
7401
7402 spa_update_dspace(spa);
7403 spa_update_latency(spa);
7404 /*
7405 * It had better be the case that we didn't dirty anything
7406 * since vdev_config_sync().
7407 */
7408 ASSERT(txg_list_empty(&dp->dp_dirty_datasets, txg));
7409 ASSERT(txg_list_empty(&dp->dp_dirty_dirs, txg));
7410 ASSERT(txg_list_empty(&spa->spa_vdev_txg_list, txg));
7411
7412 spa->spa_sync_pass = 0;
7413
7414 spa_check_special(spa);
7415
7416 /*
7417 * Update the last synced uberblock here. We want to do this at
7418 * the end of spa_sync() so that consumers of spa_last_synced_txg()
7419 * will be guaranteed that all the processing associated with
7420 * that txg has been completed.
7421 */
7422 spa->spa_ubsync = spa->spa_uberblock;
7423 spa_config_exit(spa, SCL_CONFIG, FTAG);
7424
7425 spa_handle_ignored_writes(spa);
7426
7427 /*
7428 * If any async tasks have been requested, kick them off.
7429 */
7430 spa_async_dispatch(spa);
7431 }
7432
7433 /*
7434 * Sync all pools. We don't want to hold the namespace lock across these
7435 * operations, so we take a reference on the spa_t and drop the lock during the
7436 * sync.
7437 */
7438 void
7439 spa_sync_allpools(void)
7440 {
7441 spa_t *spa = NULL;
7442 mutex_enter(&spa_namespace_lock);
7443 while ((spa = spa_next(spa)) != NULL) {
7444 if (spa_state(spa) != POOL_STATE_ACTIVE ||
7445 !spa_writeable(spa) || spa_suspended(spa))
7446 continue;
7447 spa_open_ref(spa, FTAG);
7448 mutex_exit(&spa_namespace_lock);
7449 txg_wait_synced(spa_get_dsl(spa), 0);
7450 mutex_enter(&spa_namespace_lock);
7451 spa_close(spa, FTAG);
7452 }
7453 mutex_exit(&spa_namespace_lock);
7454 }
7455
7456 /*
7457 * ==========================================================================
7458 * Miscellaneous routines
7459 * ==========================================================================
7460 */
7461
7462 /*
7463 * Remove all pools in the system.
7464 */
7465 void
7466 spa_evict_all(void)
7467 {
7468 spa_t *spa;
7469
7470 /*
7471 * Remove all cached state. All pools should be closed now,
7472 * so every spa in the AVL tree should be unreferenced.
7473 */
7474 mutex_enter(&spa_namespace_lock);
7475 while ((spa = spa_next(NULL)) != NULL) {
7476 /*
7477 * Stop async tasks. The async thread may need to detach
7478 * a device that's been replaced, which requires grabbing
7479 * spa_namespace_lock, so we must drop it here.
7480 */
7481 spa_open_ref(spa, FTAG);
7482 mutex_exit(&spa_namespace_lock);
7483 spa_async_suspend(spa);
7484 mutex_enter(&spa_namespace_lock);
7485 spa_close(spa, FTAG);
7486
7487 if (spa->spa_state != POOL_STATE_UNINITIALIZED) {
7488 wbc_deactivate(spa);
7489
7490 spa_unload(spa);
7491 spa_deactivate(spa);
7492 }
7493
7494 spa_remove(spa);
7495 }
7496 mutex_exit(&spa_namespace_lock);
7497 }
7498
7499 vdev_t *
7500 spa_lookup_by_guid(spa_t *spa, uint64_t guid, boolean_t aux)
7501 {
7502 vdev_t *vd;
7503 int i;
7504
7505 if ((vd = vdev_lookup_by_guid(spa->spa_root_vdev, guid)) != NULL)
7506 return (vd);
7507
7508 if (aux) {
7509 for (i = 0; i < spa->spa_l2cache.sav_count; i++) {
7510 vd = spa->spa_l2cache.sav_vdevs[i];
7511 if (vd->vdev_guid == guid)
7512 return (vd);
7513 }
7514
7515 for (i = 0; i < spa->spa_spares.sav_count; i++) {
7516 vd = spa->spa_spares.sav_vdevs[i];
7517 if (vd->vdev_guid == guid)
7518 return (vd);
7519 }
7520 }
7521
7522 return (NULL);
7523 }
7524
7525 void
7526 spa_upgrade(spa_t *spa, uint64_t version)
7527 {
7528 ASSERT(spa_writeable(spa));
7529
7530 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
7531
7532 /*
7533 * This should only be called for a non-faulted pool, and since a
7534 * future version would result in an unopenable pool, this shouldn't be
7535 * possible.
7536 */
7537 ASSERT(SPA_VERSION_IS_SUPPORTED(spa->spa_uberblock.ub_version));
7538 ASSERT3U(version, >=, spa->spa_uberblock.ub_version);
7539
7540 spa->spa_uberblock.ub_version = version;
7541 vdev_config_dirty(spa->spa_root_vdev);
7542
7543 spa_config_exit(spa, SCL_ALL, FTAG);
7544
7545 txg_wait_synced(spa_get_dsl(spa), 0);
7546 }
7547
7548 boolean_t
7549 spa_has_spare(spa_t *spa, uint64_t guid)
7550 {
7551 int i;
7552 uint64_t spareguid;
7553 spa_aux_vdev_t *sav = &spa->spa_spares;
7554
7555 for (i = 0; i < sav->sav_count; i++)
7556 if (sav->sav_vdevs[i]->vdev_guid == guid)
7557 return (B_TRUE);
7558
7559 for (i = 0; i < sav->sav_npending; i++) {
7560 if (nvlist_lookup_uint64(sav->sav_pending[i], ZPOOL_CONFIG_GUID,
7561 &spareguid) == 0 && spareguid == guid)
7562 return (B_TRUE);
7563 }
7564
7565 return (B_FALSE);
7566 }
7567
7568 /*
7569 * Check if a pool has an active shared spare device.
7570 * Note: reference count of an active spare is 2, as a spare and as a replace
7571 */
7572 static boolean_t
7573 spa_has_active_shared_spare(spa_t *spa)
7574 {
7575 int i, refcnt;
7576 uint64_t pool;
7577 spa_aux_vdev_t *sav = &spa->spa_spares;
7578
7579 for (i = 0; i < sav->sav_count; i++) {
7580 if (spa_spare_exists(sav->sav_vdevs[i]->vdev_guid, &pool,
7581 &refcnt) && pool != 0ULL && pool == spa_guid(spa) &&
7582 refcnt > 2)
7583 return (B_TRUE);
7584 }
7585
7586 return (B_FALSE);
7587 }
7588
7589 /*
7590 * Post a sysevent corresponding to the given event. The 'name' must be one of
7591 * the event definitions in sys/sysevent/eventdefs.h. The payload will be
7592 * filled in from the spa and (optionally) the vdev. This doesn't do anything
7593 * in the userland libzpool, as we don't want consumers to misinterpret ztest
7594 * or zdb as real changes.
7595 */
7596 static sysevent_t *
7597 spa_event_create(spa_t *spa, vdev_t *vd, nvlist_t *hist_nvl, const char *name)
7598 {
7599 sysevent_t *ev = NULL;
7600 #ifdef _KERNEL
7601 sysevent_attr_list_t *attr = NULL;
7602 sysevent_value_t value;
7603
7604 ev = sysevent_alloc(EC_ZFS, (char *)name, SUNW_KERN_PUB "zfs",
7605 SE_SLEEP);
7606 ASSERT(ev != NULL);
7607
7608 value.value_type = SE_DATA_TYPE_STRING;
7609 value.value.sv_string = spa_name(spa);
7610 if (sysevent_add_attr(&attr, ZFS_EV_POOL_NAME, &value, SE_SLEEP) != 0)
7611 goto done;
7612
7613 value.value_type = SE_DATA_TYPE_UINT64;
7614 value.value.sv_uint64 = spa_guid(spa);
7615 if (sysevent_add_attr(&attr, ZFS_EV_POOL_GUID, &value, SE_SLEEP) != 0)
7616 goto done;
7617
7618 if (vd != NULL) {
7619 value.value_type = SE_DATA_TYPE_UINT64;
7620 value.value.sv_uint64 = vd->vdev_guid;
7621 if (sysevent_add_attr(&attr, ZFS_EV_VDEV_GUID, &value,
7622 SE_SLEEP) != 0)
7623 goto done;
7624
7625 if (vd->vdev_path) {
7626 value.value_type = SE_DATA_TYPE_STRING;
7627 value.value.sv_string = vd->vdev_path;
7628 if (sysevent_add_attr(&attr, ZFS_EV_VDEV_PATH,
7629 &value, SE_SLEEP) != 0)
7630 goto done;
7631 }
7632 }
7633
7634 if (hist_nvl != NULL) {
7635 fnvlist_merge((nvlist_t *)attr, hist_nvl);
7636 }
7637
7638 if (sysevent_attach_attributes(ev, attr) != 0)
7639 goto done;
7640 attr = NULL;
7641
7642 done:
7643 if (attr)
7644 sysevent_free_attr(attr);
7645
7646 #endif
7647 return (ev);
7648 }
7649
7650 static void
7651 spa_event_post(void *arg)
7652 {
7653 #ifdef _KERNEL
7654 sysevent_t *ev = (sysevent_t *)arg;
7655
7656 sysevent_id_t eid;
7657
7658 (void) log_sysevent(ev, SE_SLEEP, &eid);
7659 sysevent_free(ev);
7660 #endif
7661 }
7662
7663 /*
7664 * Dispatch event notifications to the taskq such that the corresponding
7665 * sysevents are queued with no spa locks held
7666 */
7667 taskq_t *spa_sysevent_taskq;
7668
7669 static void
7670 spa_event_notify_impl(sysevent_t *ev)
7671 {
7672 if (taskq_dispatch(spa_sysevent_taskq, spa_event_post,
7673 ev, TQ_NOSLEEP) == NULL) {
7674 /*
7675 * These are management sysevents; as much as it is
7676 * unpleasant to drop these due to syseventd not being able
7677 * to keep up, perhaps due to resource shortages, we are not
7678 * going to sleep here and risk locking up the pool sync
7679 * process; notify admin of problems
7680 */
7681 cmn_err(CE_NOTE, "Could not dispatch sysevent nofitication "
7682 "for %s, please check state of syseventd\n",
7683 sysevent_get_subclass_name(ev));
7684
7685 sysevent_free(ev);
7686
7687 return;
7688 }
7689 }
7690
7691 void
7692 spa_event_notify(spa_t *spa, vdev_t *vd, nvlist_t *hist_nvl, const char *name)
7693 {
7694 spa_event_notify_impl(spa_event_create(spa, vd, hist_nvl, name));
7695 }
7696
7697 /*
7698 * Dispatches all auto-trim processing to all top-level vdevs. This is
7699 * called from spa_sync once every txg.
7700 */
7701 static void
7702 spa_auto_trim(spa_t *spa, uint64_t txg)
7703 {
7704 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER) == SCL_CONFIG);
7705 ASSERT(MUTEX_HELD(&spa->spa_auto_trim_lock));
7706 ASSERT(spa->spa_auto_trim_taskq != NULL);
7707
7708 for (uint64_t i = 0; i < spa->spa_root_vdev->vdev_children; i++) {
7709 vdev_trim_info_t *vti = kmem_zalloc(sizeof (*vti), KM_SLEEP);
7710 vti->vti_vdev = spa->spa_root_vdev->vdev_child[i];
7711 vti->vti_txg = txg;
7712 vti->vti_done_cb = (void (*)(void *))spa_vdev_auto_trim_done;
7713 vti->vti_done_arg = spa;
7714 (void) taskq_dispatch(spa->spa_auto_trim_taskq,
7715 (void (*)(void *))vdev_auto_trim, vti, TQ_SLEEP);
7716 spa->spa_num_auto_trimming++;
7717 }
7718 }
7719
7720 /*
7721 * Performs the sync update of the MOS pool directory's trim start/stop values.
7722 */
7723 static void
7724 spa_trim_update_time_sync(void *arg, dmu_tx_t *tx)
7725 {
7726 spa_t *spa = arg;
7727 VERIFY0(zap_update(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
7728 DMU_POOL_TRIM_START_TIME, sizeof (uint64_t), 1,
7729 &spa->spa_man_trim_start_time, tx));
7730 VERIFY0(zap_update(spa->spa_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
7731 DMU_POOL_TRIM_STOP_TIME, sizeof (uint64_t), 1,
7732 &spa->spa_man_trim_stop_time, tx));
7733 }
7734
7735 /*
7736 * Updates the in-core and on-disk manual TRIM operation start/stop time.
7737 * Passing UINT64_MAX for either start_time or stop_time means that no
7738 * update to that value should be recorded.
7739 */
7740 static dmu_tx_t *
7741 spa_trim_update_time(spa_t *spa, uint64_t start_time, uint64_t stop_time)
7742 {
7743 int err;
7744 dmu_tx_t *tx;
7745
7746 ASSERT(MUTEX_HELD(&spa->spa_man_trim_lock));
7747 if (start_time != UINT64_MAX)
7748 spa->spa_man_trim_start_time = start_time;
7749 if (stop_time != UINT64_MAX)
7750 spa->spa_man_trim_stop_time = stop_time;
7751 tx = dmu_tx_create_dd(spa_get_dsl(spa)->dp_mos_dir);
7752 err = dmu_tx_assign(tx, TXG_WAIT);
7753 if (err) {
7754 dmu_tx_abort(tx);
7755 return (NULL);
7756 }
7757 dsl_sync_task_nowait(spa_get_dsl(spa), spa_trim_update_time_sync,
7758 spa, 1, ZFS_SPACE_CHECK_RESERVED, tx);
7759
7760 return (tx);
7761 }
7762
7763 /*
7764 * Initiates an manual TRIM of the whole pool. This kicks off individual
7765 * TRIM tasks for each top-level vdev, which then pass over all of the free
7766 * space in all of the vdev's metaslabs and issues TRIM commands for that
7767 * space to the underlying vdevs.
7768 */
7769 extern void
7770 spa_man_trim(spa_t *spa, uint64_t rate)
7771 {
7772 dmu_tx_t *time_update_tx;
7773
7774 mutex_enter(&spa->spa_man_trim_lock);
7775
7776 if (rate != 0)
7777 spa->spa_man_trim_rate = MAX(rate, spa_min_trim_rate(spa));
7778 else
7779 spa->spa_man_trim_rate = 0;
7780
7781 if (spa->spa_num_man_trimming) {
7782 /*
7783 * TRIM is already ongoing. Wake up all sleeping vdev trim
7784 * threads because the trim rate might have changed above.
7785 */
7786 cv_broadcast(&spa->spa_man_trim_update_cv);
7787 mutex_exit(&spa->spa_man_trim_lock);
7788 return;
7789 }
7790 spa_man_trim_taskq_create(spa);
7791 spa->spa_man_trim_stop = B_FALSE;
7792
7793 spa_event_notify(spa, NULL, NULL, ESC_ZFS_TRIM_START);
7794 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
7795 for (uint64_t i = 0; i < spa->spa_root_vdev->vdev_children; i++) {
7796 vdev_t *vd = spa->spa_root_vdev->vdev_child[i];
7797 vdev_trim_info_t *vti = kmem_zalloc(sizeof (*vti), KM_SLEEP);
7798 vti->vti_vdev = vd;
7799 vti->vti_done_cb = (void (*)(void *))spa_vdev_man_trim_done;
7800 vti->vti_done_arg = spa;
7801 spa->spa_num_man_trimming++;
7802
7803 vd->vdev_trim_prog = 0;
7804 (void) taskq_dispatch(spa->spa_man_trim_taskq,
7805 (void (*)(void *))vdev_man_trim, vti, TQ_SLEEP);
7806 }
7807 spa_config_exit(spa, SCL_CONFIG, FTAG);
7808 time_update_tx = spa_trim_update_time(spa, gethrestime_sec(), 0);
7809 mutex_exit(&spa->spa_man_trim_lock);
7810 /* mustn't hold spa_man_trim_lock to prevent deadlock /w syncing ctx */
7811 if (time_update_tx != NULL)
7812 dmu_tx_commit(time_update_tx);
7813 }
7814
7815 /*
7816 * Orders a manual TRIM operation to stop and returns immediately.
7817 */
7818 extern void
7819 spa_man_trim_stop(spa_t *spa)
7820 {
7821 boolean_t held = MUTEX_HELD(&spa->spa_man_trim_lock);
7822 if (!held)
7823 mutex_enter(&spa->spa_man_trim_lock);
7824 spa->spa_man_trim_stop = B_TRUE;
7825 cv_broadcast(&spa->spa_man_trim_update_cv);
7826 if (!held)
7827 mutex_exit(&spa->spa_man_trim_lock);
7828 }
7829
7830 /*
7831 * Orders a manual TRIM operation to stop and waits for both manual and
7832 * automatic TRIM to complete. By holding both the spa_man_trim_lock and
7833 * the spa_auto_trim_lock, the caller can guarantee that after this
7834 * function returns, no new TRIM operations can be initiated in parallel.
7835 */
7836 void
7837 spa_trim_stop_wait(spa_t *spa)
7838 {
7839 ASSERT(MUTEX_HELD(&spa->spa_man_trim_lock));
7840 ASSERT(MUTEX_HELD(&spa->spa_auto_trim_lock));
7841 spa->spa_man_trim_stop = B_TRUE;
7842 cv_broadcast(&spa->spa_man_trim_update_cv);
7843 while (spa->spa_num_man_trimming > 0)
7844 cv_wait(&spa->spa_man_trim_done_cv, &spa->spa_man_trim_lock);
7845 while (spa->spa_num_auto_trimming > 0)
7846 cv_wait(&spa->spa_auto_trim_done_cv, &spa->spa_auto_trim_lock);
7847 }
7848
7849 /*
7850 * Returns manual TRIM progress. Progress is indicated by four return values:
7851 * 1) prog: the number of bytes of space on the pool in total that manual
7852 * TRIM has already passed (regardless if the space is allocated or not).
7853 * Completion of the operation is indicated when either the returned value
7854 * is zero, or when the returned value is equal to the sum of the sizes of
7855 * all top-level vdevs.
7856 * 2) rate: the trim rate in bytes per second. A value of zero indicates that
7857 * trim progresses as fast as possible.
7858 * 3) start_time: the UNIXTIME of when the last manual TRIM operation was
7859 * started. If no manual trim was ever initiated on the pool, this is
7860 * zero.
7861 * 4) stop_time: the UNIXTIME of when the last manual TRIM operation has
7862 * stopped on the pool. If a trim was started (start_time != 0), but has
7863 * not yet completed, stop_time will be zero. If a trim is NOT currently
7864 * ongoing and start_time is non-zero, this indicates that the previously
7865 * initiated TRIM operation was interrupted.
7866 */
7867 extern void
7868 spa_get_trim_prog(spa_t *spa, uint64_t *prog, uint64_t *rate,
7869 uint64_t *start_time, uint64_t *stop_time)
7870 {
7871 uint64_t total = 0;
7872 vdev_t *root_vd = spa->spa_root_vdev;
7873
7874 ASSERT(spa_config_held(spa, SCL_CONFIG, RW_READER));
7875 mutex_enter(&spa->spa_man_trim_lock);
7876 if (spa->spa_num_man_trimming > 0) {
7877 for (uint64_t i = 0; i < root_vd->vdev_children; i++) {
7878 total += root_vd->vdev_child[i]->vdev_trim_prog;
7879 }
7880 }
7881 *prog = total;
7882 *rate = spa->spa_man_trim_rate;
7883 *start_time = spa->spa_man_trim_start_time;
7884 *stop_time = spa->spa_man_trim_stop_time;
7885 mutex_exit(&spa->spa_man_trim_lock);
7886 }
7887
7888 /*
7889 * Callback when a vdev_man_trim has finished on a single top-level vdev.
7890 */
7891 static void
7892 spa_vdev_man_trim_done(spa_t *spa)
7893 {
7894 dmu_tx_t *time_update_tx = NULL;
7895
7896 mutex_enter(&spa->spa_man_trim_lock);
7897 ASSERT(spa->spa_num_man_trimming > 0);
7898 spa->spa_num_man_trimming--;
7899 if (spa->spa_num_man_trimming == 0) {
7900 /* if we were interrupted, leave stop_time at zero */
7901 if (!spa->spa_man_trim_stop)
7902 time_update_tx = spa_trim_update_time(spa, UINT64_MAX,
7903 gethrestime_sec());
7904 spa_event_notify(spa, NULL, NULL, ESC_ZFS_TRIM_FINISH);
7905 spa_async_request(spa, SPA_ASYNC_MAN_TRIM_TASKQ_DESTROY);
7906 cv_broadcast(&spa->spa_man_trim_done_cv);
7907 }
7908 mutex_exit(&spa->spa_man_trim_lock);
7909
7910 if (time_update_tx != NULL)
7911 dmu_tx_commit(time_update_tx);
7912 }
7913
7914 /*
7915 * Called from vdev_auto_trim when a vdev has completed its auto-trim
7916 * processing.
7917 */
7918 static void
7919 spa_vdev_auto_trim_done(spa_t *spa)
7920 {
7921 mutex_enter(&spa->spa_auto_trim_lock);
7922 ASSERT(spa->spa_num_auto_trimming > 0);
7923 spa->spa_num_auto_trimming--;
7924 if (spa->spa_num_auto_trimming == 0)
7925 cv_broadcast(&spa->spa_auto_trim_done_cv);
7926 mutex_exit(&spa->spa_auto_trim_lock);
7927 }
7928
7929 /*
7930 * Determines the minimum sensible rate at which a manual TRIM can be
7931 * performed on a given spa and returns it. Since we perform TRIM in
7932 * metaslab-sized increments, we'll just let the longest step between
7933 * metaslab TRIMs be 100s (random number, really). Thus, on a typical
7934 * 200-metaslab vdev, the longest TRIM should take is about 5.5 hours.
7935 * It *can* take longer if the device is really slow respond to
7936 * zio_trim() commands or it contains more than 200 metaslabs, or
7937 * metaslab sizes vary widely between top-level vdevs.
7938 */
7939 static uint64_t
7940 spa_min_trim_rate(spa_t *spa)
7941 {
7942 uint64_t smallest_ms_sz = UINT64_MAX;
7943
7944 /* find the smallest metaslab */
7945 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
7946 for (uint64_t i = 0; i < spa->spa_root_vdev->vdev_children; i++) {
7947 smallest_ms_sz = MIN(smallest_ms_sz,
7948 spa->spa_root_vdev->vdev_child[i]->vdev_ms[0]->ms_size);
7949 }
7950 spa_config_exit(spa, SCL_CONFIG, FTAG);
7951 VERIFY(smallest_ms_sz != 0);
7952
7953 /* minimum TRIM rate is 1/100th of the smallest metaslab size */
7954 return (smallest_ms_sz / 100);
7955 }