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