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