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