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