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