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