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