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