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