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