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