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